Skip to content

Commit

Permalink
Tests Redirection and removes unused code
Browse files Browse the repository at this point in the history
  • Loading branch information
EwenQuim committed Feb 1, 2024
1 parent 3bca4bd commit de399bf
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 15 deletions.
14 changes: 1 addition & 13 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ type ContextNoBody struct {
}

func (c ContextNoBody) Body() (any, error) {
slog.Warn("this method should not be called. It probably happened because you passed the context to another controller with the Pass method.")
slog.Warn("this method should not be called. It probably happened because you passed the context to another controller.")
return body[map[string]any](c)
}

Expand All @@ -131,18 +131,6 @@ func (c ContextNoBody) MustBody() any {
return b
}

// SafeShallowCopy returns a safe shallow copy of the context.
// It allows to modify the base context while modifying the request context.
// It is data-safe, meaning that any sensitive data will not be shared between the original context and the copy.
func (c *ContextWithBody[B]) SafeShallowCopy() *ContextWithBody[B] {
c.pathParams = nil
c.body = nil
c.request = nil
c.response = nil

return c
}

// SetStatus sets the status code of the response.
// Alias to http.ResponseWriter.WriteHeader.
func (c ContextNoBody) SetStatus(code int) {
Expand Down
27 changes: 25 additions & 2 deletions ctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ func TestMainLang(t *testing.T) {
require.Equal(t, c.MainLocale(), "fr-CH")
}

func TestClassicContext_Body(t *testing.T) {
func TestContextNoBody_Body(t *testing.T) {
body := `{"name":"John","age":30}`
r := httptest.NewRequest("GET", "/", strings.NewReader(body))
ctx := ContextNoBody{
Expand All @@ -403,7 +403,7 @@ func TestClassicContext_Body(t *testing.T) {
}), res)
}

func TestClassicContext_MustBody(t *testing.T) {
func TestContextNoBody_MustBody(t *testing.T) {
t.Run("can read JSON body", func(t *testing.T) {
body := `{"name":"John","age":30}`
r := httptest.NewRequest("GET", "/", strings.NewReader(body))
Expand All @@ -430,3 +430,26 @@ func TestClassicContext_MustBody(t *testing.T) {
})
})
}

func TestContextNoBody_Redirect(t *testing.T) {
s := NewServer()

Get(s, "/", func(c ContextNoBody) (any, error) {
return c.Redirect(301, "/foo")
})

Get(s, "/foo", func(c ContextNoBody) (ans, error) {
return ans{Ans: "foo"}, nil
})

t.Run("can redirect", func(t *testing.T) {
r := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()

s.Mux.ServeHTTP(w, r)

require.Equal(t, 301, w.Code)
require.Equal(t, "/foo", w.Header().Get("Location"))
require.Equal(t, "<a href=\"/foo\">Moved Permanently</a>.\n\n", w.Body.String())
})
}

0 comments on commit de399bf

Please sign in to comment.