Renamed Test to Request

This commit is contained in:
Eduard Urbach 2024-03-27 11:36:12 +01:00
parent 271e1cd5bd
commit cf3daa1f1b
Signed by: akyoto
GPG Key ID: C874F672B1AF20C0
2 changed files with 15 additions and 11 deletions

View File

@ -21,9 +21,9 @@ type Server interface {
Get(path string, handler Handler)
Post(path string, handler Handler)
Put(path string, handler Handler)
Request(method string, path string, body io.Reader) Response
Router() *router.Router[Handler]
Run(address string) error
Test(method string, path string, body io.Reader) Response
Use(handlers ...Handler)
}
@ -85,6 +85,17 @@ func (s *server) Put(path string, handler Handler) {
s.Router().Add("PUT", path, handler)
}
// Request performs a synthetic request and returns the response.
// This function keeps the response in memory so it's slightly slower than a real request.
// However it is very useful inside tests where you don't want to spin up a real web server.
func (s *server) Request(method string, path string, body io.Reader) Response {
ctx := s.newContext()
ctx.method = method
ctx.path = path
s.handleRequest(ctx, method, path, io.Discard)
return ctx.Response()
}
// Run starts the server on the given address.
func (s *server) Run(address string) error {
listener, err := net.Listen("tcp", address)
@ -185,14 +196,7 @@ func (s *server) handleRequest(ctx *context, method string, path string, writer
}
}
func (s *server) Test(method string, path string, body io.Reader) Response {
ctx := s.newContext()
ctx.method = method
ctx.path = path
s.handleRequest(ctx, method, path, io.Discard)
return ctx.Response()
}
// newContext allocates a new context with the default state.
func (s *server) newContext() *context {
return &context{
server: s,

View File

@ -14,7 +14,7 @@ func TestBytes(t *testing.T) {
return ctx.Bytes([]byte("Hello"))
})
response := s.Test("GET", "/", nil)
response := s.Request("GET", "/", nil)
assert.Equal(t, response.Status(), 200)
assert.DeepEqual(t, response.Body(), []byte("Hello"))
}
@ -26,7 +26,7 @@ func TestString(t *testing.T) {
return ctx.String("Hello")
})
response := s.Test("GET", "/", nil)
response := s.Request("GET", "/", nil)
assert.Equal(t, response.Status(), 200)
assert.DeepEqual(t, response.Body(), []byte("Hello"))
}