h2non / gock

HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽
https://pkg.go.dev/github.com/h2non/gock
MIT License
2.09k stars 107 forks source link

Response BodyGenerator() #110

Closed IktaS closed 1 year ago

IktaS commented 1 year ago

Adding ability to add BodyGenerator() for more customization in defining response body. I use this library a lot for unit testing, and one of the unit test I haven't been able to cover is in cases where we fail to call Read() from response body. We cannot add a simple mock io.ReadCloser interface that return an error when Read() is being called because Body are stored as a bytes buffer, and error are handled when creating new response body, so application level code will never encounter a faulty body.

This PR added a new Body type for Response, which is the BodyGenerator function, that takes in a function which returns an io.ReadCloser, which will be thing that will be returned as a response.

p.s. I wanted to have it cleaner by having a BodyRaw(io.ReadCloser) function, but cannot get it to work with multiple response, as it will return the same pointer to the underlying implementation of io.ReadCloser, which means after the first Read() to the response body, the second response body Read() function will be different, making the behaviour unexpected. If you guys know how to only accept io.ReadCloser interface and not a function to generate one (maybe using reflection), please let me know and I'll try to implement it here