consistent_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (c) 2024, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package discovery
  20. import (
  21. "strconv"
  22. "testing"
  23. "time"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server/psinet"
  25. )
  26. func TestConsistentHashingDiscovery(t *testing.T) {
  27. serverIPs, err := nRandomIPs(100)
  28. if err != nil {
  29. t.Fatalf("nRandomIPs failed %s", err)
  30. }
  31. servers := make([]*psinet.DiscoveryServer, len(serverIPs))
  32. for i := 0; i < len(servers); i++ {
  33. servers[i] = newDiscoveryServer(strconv.Itoa(i), []time.Time{{}, time.Now().Add(1 * time.Hour)})
  34. }
  35. c, err := NewConsistentHashingDiscovery()
  36. if err != nil {
  37. t.Fatalf("newConsistentHashingDiscovery failed %s", err)
  38. }
  39. c.serversChanged(servers)
  40. // For a single IP address value, only one server in a set of discovery
  41. // servers should be discoverable.
  42. discoveredServers := make(map[string]bool)
  43. clientIP, err := randomIP()
  44. if err != nil {
  45. t.Fatalf("randomIP failed %s", err)
  46. }
  47. for i := 0; i < 1000; i++ {
  48. for _, server := range c.selectServers(clientIP) {
  49. discoveredServers[server.EncodedServerEntry] = true
  50. }
  51. }
  52. if len(discoveredServers) != 1 {
  53. t.Fatalf("expected to discover 1 server but discovered %d", len(discoveredServers))
  54. }
  55. }