nord_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package integration
  2. import (
  3. "encoding/json"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "strings"
  8. "testing"
  9. )
  10. func stubNordAPI(t *testing.T, handler http.HandlerFunc) {
  11. t.Helper()
  12. previous := nordAPIBase
  13. server := httptest.NewServer(handler)
  14. nordAPIBase = server.URL
  15. t.Cleanup(func() {
  16. nordAPIBase = previous
  17. server.Close()
  18. })
  19. }
  20. func TestNordCountriesOnlyRequestsNordLynxServerCountries(t *testing.T) {
  21. stubNordAPI(t, func(w http.ResponseWriter, req *http.Request) {
  22. if req.URL.Path != "/v1/servers/countries" {
  23. t.Errorf("country path = %q", req.URL.Path)
  24. }
  25. if got := req.URL.Query().Get("filters[servers_technologies][identifier]"); got != "wireguard_udp" {
  26. t.Errorf("NordLynx technology filter = %q", got)
  27. }
  28. w.Header().Set("Content-Type", "application/json")
  29. _, _ = io.WriteString(w, `[{"id":228,"name":"United States","code":"US"}]`)
  30. })
  31. got, err := (&NordService{}).GetCountries()
  32. if err != nil {
  33. t.Fatal(err)
  34. }
  35. if !strings.Contains(got, `"code":"US"`) {
  36. t.Fatalf("countries = %s", got)
  37. }
  38. }
  39. func TestNordServersPreserveLowLoadServers(t *testing.T) {
  40. stubNordAPI(t, func(w http.ResponseWriter, req *http.Request) {
  41. if req.URL.Path != "/v2/servers" {
  42. t.Errorf("server path = %q", req.URL.Path)
  43. }
  44. if got := req.URL.Query().Get("filters[country_id]"); got != "225" {
  45. t.Errorf("country filter = %q", got)
  46. }
  47. if got := req.URL.Query().Get("filters[servers_technologies][identifier]"); got != "wireguard_udp" {
  48. t.Errorf("NordLynx technology filter = %q", got)
  49. }
  50. w.Header().Set("Content-Type", "application/json")
  51. _, _ = io.WriteString(w, `{"servers":[{"id":1,"load":0},{"id":2,"load":4}]}`)
  52. })
  53. got, err := (&NordService{}).GetServers("225")
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. var payload struct {
  58. Servers []struct {
  59. Load int `json:"load"`
  60. } `json:"servers"`
  61. }
  62. if err := json.Unmarshal([]byte(got), &payload); err != nil {
  63. t.Fatal(err)
  64. }
  65. if len(payload.Servers) != 2 || payload.Servers[0].Load != 0 || payload.Servers[1].Load != 4 {
  66. t.Fatalf("servers = %+v", payload.Servers)
  67. }
  68. }