|
| 1 | +package httpmw |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "net/http" |
| 7 | + "net/http/httptest" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/go-chi/chi/v5" |
| 11 | + "github.com/stretchr/testify/assert" |
| 12 | + "github.com/stretchr/testify/require" |
| 13 | + |
| 14 | + "github.com/coder/coder/codersdk" |
| 15 | +) |
| 16 | + |
| 17 | +const ( |
| 18 | + testParam = "workspaceagent" |
| 19 | + testWorkspaceAgentID = "8a70c576-12dc-42bc-b791-112a32b5bd43" |
| 20 | +) |
| 21 | + |
| 22 | +func TestParseUUID_Valid(t *testing.T) { |
| 23 | + t.Parallel() |
| 24 | + |
| 25 | + rw := httptest.NewRecorder() |
| 26 | + r := httptest.NewRequest("GET", "/{workspaceagent}", nil) |
| 27 | + |
| 28 | + ctx := chi.NewRouteContext() |
| 29 | + ctx.URLParams.Add(testParam, testWorkspaceAgentID) |
| 30 | + r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, ctx)) |
| 31 | + |
| 32 | + parsed, ok := parseUUID(rw, r, "workspaceagent") |
| 33 | + assert.True(t, ok, "UUID should be parsed") |
| 34 | + assert.Equal(t, testWorkspaceAgentID, parsed.String()) |
| 35 | +} |
| 36 | + |
| 37 | +func TestParseUUID_Invalid(t *testing.T) { |
| 38 | + t.Parallel() |
| 39 | + |
| 40 | + rw := httptest.NewRecorder() |
| 41 | + r := httptest.NewRequest("GET", "/{workspaceagent}", nil) |
| 42 | + |
| 43 | + ctx := chi.NewRouteContext() |
| 44 | + ctx.URLParams.Add(testParam, "wrong-id") |
| 45 | + r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, ctx)) |
| 46 | + |
| 47 | + _, ok := parseUUID(rw, r, "workspaceagent") |
| 48 | + assert.False(t, ok, "UUID should not be parsed") |
| 49 | + assert.Equal(t, http.StatusBadRequest, rw.Code) |
| 50 | + |
| 51 | + var response codersdk.Response |
| 52 | + err := json.Unmarshal(rw.Body.Bytes(), &response) |
| 53 | + require.NoError(t, err) |
| 54 | + assert.Contains(t, response.Message, `Invalid UUID "wrong-id"`) |
| 55 | +} |
0 commit comments