libopenapi-validator icon indicating copy to clipboard operation
libopenapi-validator copied to clipboard

Question / feature proposal: Using the validator with `httptest.ResponseRecorder`

Open jamietanna opened this issue 2 years ago • 5 comments

I'm looking at adding libopenapi to https://gitlab.com/jamietanna/httptest-openapi, a library I've got for writing (unit) tests with Go's net/http handlers by validating the response matches an OpenAPI spec.

I've looked at using this library to give me full OpenAPI 3.0 and 3.1 support, instead of Kin's OpenAPI 3.0 only, but noticed that I couldn't use it right away.

In the test code i.e. https://gitlab.com/jamietanna/httptest-openapi/-/blob/v0.3.0/openapi3/validator.go?ref_type=tags#L95 we only have access to a httptest.ResponseRecorder whereas the library expects an http.Response.

Would it be of interest to add support for providing a httptest.ResponseRecorder or should I instead look at how to convert between the two types?

jamietanna avatar Dec 08 '23 21:12 jamietanna

I guess I could pass in a httptest.ResponseRecorder but couldn't remember whether they're safe for production use cases, as the middleware is expected for prod code

jamietanna avatar Dec 08 '23 21:12 jamietanna

Hi Jamie,

I'm not quite sure what you mean, would you be able to help me understand?

I'd be happy to help add in support to allow you get this working, I just need more help understanding the use case.

daveshanley avatar Dec 09 '23 09:12 daveshanley

Hey, thank you! That'll teach me from raising an issue on mobile :sweat_smile:

I'd originally phrased the question correctly, then second-guessed myself, and amended it.

I've amended the description to note that I'm actually trying to use this with httptest.ResponseRecorder, not for use with a http.Response.

jamietanna avatar Dec 09 '23 10:12 jamietanna

I can't see why not, I used the httptest.ResponseRecorder in the tests myself. I will have a look at the code and see how much work it would be.

daveshanley avatar Dec 12 '23 15:12 daveshanley

Still learning how to use libopenapi for testing but this example seems to work:

  • https://pkg.go.dev/github.com/pb33f/libopenapi-validator#example-NewValidator-ValidateHttpRequestResponse

Specific snippet:

// 7. Validate!
valid, validationErrs := docValidator.ValidateHttpRequestResponse(request, recorder.Result())

hsanson avatar Feb 12 '25 02:02 hsanson