error_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package netutil
  17. import (
  18. "net"
  19. "testing"
  20. "time"
  21. )
  22. // This test checks that isPacketTooBig correctly identifies
  23. // errors that result from receiving a UDP packet larger
  24. // than the supplied receive buffer.
  25. func TestIsPacketTooBig(t *testing.T) {
  26. listener, err := net.ListenPacket("udp", "127.0.0.1:0")
  27. if err != nil {
  28. t.Fatal(err)
  29. }
  30. defer listener.Close()
  31. sender, err := net.Dial("udp", listener.LocalAddr().String())
  32. if err != nil {
  33. t.Fatal(err)
  34. }
  35. defer sender.Close()
  36. sendN := 1800
  37. recvN := 300
  38. for i := 0; i < 20; i++ {
  39. go func() {
  40. buf := make([]byte, sendN)
  41. for i := range buf {
  42. buf[i] = byte(i)
  43. }
  44. sender.Write(buf)
  45. }()
  46. buf := make([]byte, recvN)
  47. listener.SetDeadline(time.Now().Add(1 * time.Second))
  48. n, _, err := listener.ReadFrom(buf)
  49. if err != nil {
  50. if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
  51. continue
  52. }
  53. if !isPacketTooBig(err) {
  54. t.Fatalf("unexpected read error: %v", err)
  55. }
  56. continue
  57. }
  58. if n != recvN {
  59. t.Fatalf("short read: %d, want %d", n, recvN)
  60. }
  61. for i := range buf {
  62. if buf[i] != byte(i) {
  63. t.Fatalf("error in pattern")
  64. break
  65. }
  66. }
  67. }
  68. }