|
| 1 | +package filters //nolint:testpackage // Testing private utility functions. |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "testing" |
| 8 | + |
| 9 | + "github.com/google/uuid" |
| 10 | + "github.com/stretchr/testify/assert" |
| 11 | + "github.com/stretchr/testify/require" |
| 12 | +) |
| 13 | + |
| 14 | +func TestClients(t *testing.T) { |
| 15 | + tests := []struct { |
| 16 | + getClient func(t *testing.T, orgID uuid.UUID, expectedAllow AllowList) (Client, func()) |
| 17 | + clientName string |
| 18 | + }{ |
| 19 | + { |
| 20 | + clientName: "deeproxyClient", |
| 21 | + getClient: func(t *testing.T, orgID uuid.UUID, expectedAllow AllowList) (Client, func()) { |
| 22 | + t.Helper() |
| 23 | + |
| 24 | + s := setupServer(t, orgID, expectedAllow) |
| 25 | + cleanup := func() { |
| 26 | + s.Close() |
| 27 | + } |
| 28 | + c := NewDeeproxyClient(Config{BaseURL: s.URL, IsFedRamp: true}, WithHTTPClient(s.Client())) |
| 29 | + |
| 30 | + return c, cleanup |
| 31 | + }, |
| 32 | + }, |
| 33 | + { |
| 34 | + clientName: "fakeClient", |
| 35 | + getClient: func(t *testing.T, _ uuid.UUID, expectedAllow AllowList) (Client, func()) { |
| 36 | + t.Helper() |
| 37 | + |
| 38 | + c := NewFakeClient(expectedAllow) |
| 39 | + |
| 40 | + return c, func() {} |
| 41 | + }, |
| 42 | + }, |
| 43 | + } |
| 44 | + |
| 45 | + for _, testData := range tests { |
| 46 | + t.Run(testData.clientName+": GetFilters", func(t *testing.T) { |
| 47 | + orgID := uuid.New() |
| 48 | + expectedAllow := AllowList{ |
| 49 | + ConfigFiles: []string{"package.json"}, |
| 50 | + Extensions: []string{".ts", ".js"}, |
| 51 | + } |
| 52 | + client, cleanup := testData.getClient(t, orgID, expectedAllow) |
| 53 | + defer cleanup() |
| 54 | + |
| 55 | + allow, err := client.GetFilters(t.Context(), orgID) |
| 56 | + require.NoError(t, err) |
| 57 | + |
| 58 | + assert.Equal(t, expectedAllow, allow) |
| 59 | + }) |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +func setupServer(t *testing.T, orgID uuid.UUID, expectedAllow AllowList) *httptest.Server { |
| 64 | + t.Helper() |
| 65 | + ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 66 | + expectedURL := getFilterURL("", orgID, true) |
| 67 | + assert.Equal(t, expectedURL, r.URL.Path) |
| 68 | + assert.Equal(t, orgID.String(), r.Header.Get("snyk-org-name")) |
| 69 | + w.Header().Set("Content-Type", "application/json") |
| 70 | + if err := json.NewEncoder(w).Encode(expectedAllow); err != nil { |
| 71 | + http.Error(w, "failed to encode response", http.StatusInternalServerError) |
| 72 | + return |
| 73 | + } |
| 74 | + })) |
| 75 | + ts.Start() |
| 76 | + return ts |
| 77 | +} |
0 commit comments