1
0

cache_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright (C) 2015 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 http://mozilla.org/MPL/2.0/.
  6. package discover
  7. import (
  8. "reflect"
  9. "testing"
  10. "time"
  11. "github.com/syncthing/syncthing/lib/protocol"
  12. )
  13. func TestCacheUnique(t *testing.T) {
  14. direct0 := []string{"tcp://192.0.2.44:22000", "tcp://192.0.2.42:22000"} // prio 0
  15. direct1 := []string{"tcp://192.0.2.43:22000", "tcp://192.0.2.42:22000"} // prio 1
  16. // what we expect from just direct0
  17. direct0Sorted := []string{"tcp://192.0.2.42:22000", "tcp://192.0.2.44:22000"}
  18. // what we expect from direct0+direct1
  19. totalSorted := []string{
  20. // first prio 0, sorted
  21. "tcp://192.0.2.42:22000", "tcp://192.0.2.44:22000",
  22. // then prio 1
  23. "tcp://192.0.2.43:22000",
  24. // no duplicate .42
  25. }
  26. relays := []Relay{{URL: "relay://192.0.2.44:443"}, {URL: "tcp://192.0.2.45:443"}}
  27. c := NewCachingMux()
  28. c.ServeBackground()
  29. defer c.Stop()
  30. // Add a fake discovery service and verify we get it's answers through the
  31. // cache.
  32. f1 := &fakeDiscovery{direct0, relays}
  33. c.Add(f1, time.Minute, 0, 0)
  34. dir, rel, err := c.Lookup(protocol.LocalDeviceID)
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. if !reflect.DeepEqual(dir, direct0Sorted) {
  39. t.Errorf("Incorrect direct; %+v != %+v", dir, direct0Sorted)
  40. }
  41. if !reflect.DeepEqual(rel, relays) {
  42. t.Errorf("Incorrect relays; %+v != %+v", rel, relays)
  43. }
  44. // Add one more that answers in the same way and check that we don't
  45. // duplicate or otherwise mess up the responses now.
  46. f2 := &fakeDiscovery{direct1, relays}
  47. c.Add(f2, time.Minute, 0, 1)
  48. dir, rel, err = c.Lookup(protocol.LocalDeviceID)
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. if !reflect.DeepEqual(dir, totalSorted) {
  53. t.Errorf("Incorrect direct; %+v != %+v", dir, totalSorted)
  54. }
  55. if !reflect.DeepEqual(rel, relays) {
  56. t.Errorf("Incorrect relays; %+v != %+v", rel, relays)
  57. }
  58. }
  59. type fakeDiscovery struct {
  60. direct []string
  61. relays []Relay
  62. }
  63. func (f *fakeDiscovery) Lookup(deviceID protocol.DeviceID) (direct []string, relays []Relay, err error) {
  64. return f.direct, f.relays, nil
  65. }
  66. func (f *fakeDiscovery) Error() error {
  67. return nil
  68. }
  69. func (f *fakeDiscovery) String() string {
  70. return "fake"
  71. }
  72. func (f *fakeDiscovery) Cache() map[protocol.DeviceID]CacheEntry {
  73. return nil
  74. }