dnsname_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build !js
  5. package net
  6. import (
  7. "strings"
  8. "testing"
  9. )
  10. type dnsNameTest struct {
  11. name string
  12. result bool
  13. }
  14. var dnsNameTests = []dnsNameTest{
  15. // RFC 2181, section 11.
  16. {"_xmpp-server._tcp.google.com", true},
  17. {"foo.com", true},
  18. {"1foo.com", true},
  19. {"26.0.0.73.com", true},
  20. {"10-0-0-1", true},
  21. {"fo-o.com", true},
  22. {"fo1o.com", true},
  23. {"foo1.com", true},
  24. {"a.b..com", false},
  25. {"a.b-.com", false},
  26. {"a.b.com-", false},
  27. {"a.b..", false},
  28. {"b.com.", true},
  29. }
  30. func emitDNSNameTest(ch chan<- dnsNameTest) {
  31. defer close(ch)
  32. var char63 = ""
  33. for i := 0; i < 63; i++ {
  34. char63 += "a"
  35. }
  36. char64 := char63 + "a"
  37. longDomain := strings.Repeat(char63+".", 5) + "example"
  38. for _, tc := range dnsNameTests {
  39. ch <- tc
  40. }
  41. ch <- dnsNameTest{char63 + ".com", true}
  42. ch <- dnsNameTest{char64 + ".com", false}
  43. // Remember: wire format is two octets longer than presentation
  44. // (length octets for the first and [root] last labels).
  45. // 253 is fine:
  46. ch <- dnsNameTest{longDomain[len(longDomain)-253:], true}
  47. // A terminal dot doesn't contribute to length:
  48. ch <- dnsNameTest{longDomain[len(longDomain)-253:] + ".", true}
  49. // 254 is bad:
  50. ch <- dnsNameTest{longDomain[len(longDomain)-254:], false}
  51. }
  52. func TestDNSName(t *testing.T) {
  53. ch := make(chan dnsNameTest)
  54. go emitDNSNameTest(ch)
  55. for tc := range ch {
  56. if isDomainName(tc.name) != tc.result {
  57. t.Errorf("isDomainName(%q) = %v; want %v", tc.name, !tc.result, tc.result)
  58. }
  59. }
  60. }
  61. func BenchmarkDNSName(b *testing.B) {
  62. testHookUninstaller.Do(uninstallTestHooks)
  63. benchmarks := append(dnsNameTests, []dnsNameTest{
  64. {strings.Repeat("a", 63), true},
  65. {strings.Repeat("a", 64), false},
  66. }...)
  67. for n := 0; n < b.N; n++ {
  68. for _, tc := range benchmarks {
  69. if isDomainName(tc.name) != tc.result {
  70. b.Errorf("isDomainName(%q) = %v; want %v", tc.name, !tc.result, tc.result)
  71. }
  72. }
  73. }
  74. }