registry_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright (C) 2019 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package registry
  7. import (
  8. "net"
  9. "testing"
  10. )
  11. func TestRegistry(t *testing.T) {
  12. r := New()
  13. want := func(i int) func(interface{}) bool {
  14. return func(x interface{}) bool { return x.(int) == i }
  15. }
  16. if res := r.Get("int", want(1)); res != nil {
  17. t.Error("unexpected")
  18. }
  19. r.Register("int", 1)
  20. r.Register("int", 11)
  21. r.Register("int4", 4)
  22. r.Register("int4", 44)
  23. r.Register("int6", 6)
  24. r.Register("int6", 66)
  25. if res := r.Get("int", want(1)).(int); res != 1 {
  26. t.Error("unexpected", res)
  27. }
  28. // int is prefix of int4, so returns 1
  29. if res := r.Get("int4", want(1)).(int); res != 1 {
  30. t.Error("unexpected", res)
  31. }
  32. r.Unregister("int", 1)
  33. if res := r.Get("int", want(1)).(int); res == 1 {
  34. t.Error("unexpected", res)
  35. }
  36. if res := r.Get("int6", want(6)).(int); res != 6 {
  37. t.Error("unexpected", res)
  38. }
  39. // Unregister 11, int should be impossible to find
  40. r.Unregister("int", 11)
  41. if res := r.Get("int", want(11)); res != nil {
  42. t.Error("unexpected")
  43. }
  44. // Unregister a second time does nothing.
  45. r.Unregister("int", 1)
  46. // Can have multiple of the same
  47. r.Register("int", 1)
  48. r.Register("int", 1)
  49. r.Unregister("int", 1)
  50. if res := r.Get("int4", want(1)).(int); res != 1 {
  51. t.Error("unexpected", res)
  52. }
  53. }
  54. func TestShortSchemeFirst(t *testing.T) {
  55. r := New()
  56. r.Register("foo", 0)
  57. r.Register("foobar", 1)
  58. // If we don't care about the value, we should get the one with "foo".
  59. res := r.Get("foo", func(interface{}) bool { return false })
  60. if res != 0 {
  61. t.Error("unexpected", res)
  62. }
  63. }
  64. func BenchmarkGet(b *testing.B) {
  65. r := New()
  66. for _, addr := range []string{"192.168.1.1", "172.1.1.1", "10.1.1.1"} {
  67. r.Register("tcp", &net.TCPAddr{IP: net.ParseIP(addr)})
  68. }
  69. b.ReportAllocs()
  70. b.ResetTimer()
  71. for i := 0; i < b.N; i++ {
  72. r.Get("tcp", func(x interface{}) bool {
  73. return x.(*net.TCPAddr).IP.IsUnspecified()
  74. })
  75. }
  76. }