mac_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2011 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. package net
  5. import (
  6. "reflect"
  7. "strings"
  8. "testing"
  9. )
  10. var mactests = []struct {
  11. in string
  12. out HardwareAddr
  13. err string
  14. }{
  15. {"01:23:45:67:89:AB", HardwareAddr{1, 0x23, 0x45, 0x67, 0x89, 0xab}, ""},
  16. {"01-23-45-67-89-AB", HardwareAddr{1, 0x23, 0x45, 0x67, 0x89, 0xab}, ""},
  17. {"0123.4567.89AB", HardwareAddr{1, 0x23, 0x45, 0x67, 0x89, 0xab}, ""},
  18. {"ab:cd:ef:AB:CD:EF", HardwareAddr{0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef}, ""},
  19. {"01.02.03.04.05.06", nil, "invalid MAC address"},
  20. {"01:02:03:04:05:06:", nil, "invalid MAC address"},
  21. {"x1:02:03:04:05:06", nil, "invalid MAC address"},
  22. {"01002:03:04:05:06", nil, "invalid MAC address"},
  23. {"01:02003:04:05:06", nil, "invalid MAC address"},
  24. {"01:02:03004:05:06", nil, "invalid MAC address"},
  25. {"01:02:03:04005:06", nil, "invalid MAC address"},
  26. {"01:02:03:04:05006", nil, "invalid MAC address"},
  27. {"01-02:03:04:05:06", nil, "invalid MAC address"},
  28. {"01:02-03-04-05-06", nil, "invalid MAC address"},
  29. {"0123:4567:89AF", nil, "invalid MAC address"},
  30. {"0123-4567-89AF", nil, "invalid MAC address"},
  31. {"01:23:45:67:89:AB:CD:EF", HardwareAddr{1, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, ""},
  32. {"01-23-45-67-89-AB-CD-EF", HardwareAddr{1, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, ""},
  33. {"0123.4567.89AB.CDEF", HardwareAddr{1, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, ""},
  34. }
  35. func match(err error, s string) bool {
  36. if s == "" {
  37. return err == nil
  38. }
  39. return err != nil && strings.Contains(err.Error(), s)
  40. }
  41. func TestMACParseString(t *testing.T) {
  42. for i, tt := range mactests {
  43. out, err := ParseMAC(tt.in)
  44. if !reflect.DeepEqual(out, tt.out) || !match(err, tt.err) {
  45. t.Errorf("ParseMAC(%q) = %v, %v, want %v, %v", tt.in, out, err, tt.out,
  46. tt.err)
  47. }
  48. if tt.err == "" {
  49. // Verify that serialization works too, and that it round-trips.
  50. s := out.String()
  51. out2, err := ParseMAC(s)
  52. if err != nil {
  53. t.Errorf("%d. ParseMAC(%q) = %v", i, s, err)
  54. continue
  55. }
  56. if !reflect.DeepEqual(out2, out) {
  57. t.Errorf("%d. ParseMAC(%q) = %v, want %v", i, s, out2, out)
  58. }
  59. }
  60. }
  61. }