-
I am trying to provide iris support for oapi-codegen, I think I got most of the work done but I always get Here is some code: func (r *RequestBuilder) GoWithHTTPHandler(t *testing.T, handler http.Handler) *CompletedRequest {
if r.Error != nil {
// Fail the test if we had an error
t.Errorf("error constructing request: %s", r.Error)
return nil
}
var bodyReader io.Reader
if r.Body != nil {
bodyReader = bytes.NewReader(r.Body)
}
req := httptest.NewRequest(r.Method, r.Path, bodyReader)
for h, v := range r.Headers {
req.Header.Add(h, v)
}
if host, ok := r.Headers["Host"]; ok {
req.Host = host
}
for _, c := range r.Cookies {
req.AddCookie(c)
}
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return &CompletedRequest{
Recorder: rec,
}
} func doGet(t *testing.T, i *iris.Application, rawURL string) *httptest.ResponseRecorder {
u, err := url.Parse(rawURL)
if err != nil {
t.Fatalf("Invalid url: %s", rawURL)
}
response := testutil.NewRequest().Get(u.RequestURI()).WithHost(u.Host).WithAcceptJson().GoWithIrisHandler(t, i)
return response.Recorder
}
func TestOapiRequestValidator(t *testing.T) {
i := iris.New()
called := false
// Install a request handler for /resource. We want to make sure it doesn't
// get called.
i.Get("/resource", func(c iris.Context) {
called = true
})
// Let's send the request to the wrong server, this should fail validation
{
rec := doGet(t, i, "http://not.deepmap.ai/resource")
assert.Equal(t, http.StatusBadRequest, rec.Code)
assert.False(t, called, "Handler should not have been called")
} It will always panic on ServerHTTP. |
Beta Was this translation helpful? Give feedback.
Answered by
kataras
May 27, 2023
Replies: 1 comment
-
Hello @Ns2Kracy, func TestOapiRequestValidator(t *testing.T) {
i := iris.New()
called := false
// Install a request handler for /resource. We want to make sure it doesn't
// get called.
i.Get("/resource", func(c iris.Context) {
called = true
})
// HERE: call i.Build() before tests.
if err := i.Build(); err != nil {
t.Fatal(err)
}
// Let's send the request to the wrong server, this should fail validation
{
rec := doGet(t, i, "http://not.deepmap.ai/resource")
assert.Equal(t, http.StatusBadRequest, rec.Code)
assert.False(t, called, "Handler should not have been called")
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Ns2Kracy
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @Ns2Kracy,