httpmock icon indicating copy to clipboard operation
httpmock copied to clipboard

MinTimes and MaxTimes responder invocations

Open ilya-hontarau opened this issue 1 year ago • 5 comments

As I can see, there is no way to set upper bound and lower bound of responder invocations, only Once() and exact amount with Times(). What do you think about adding these helper functions, like MinTimes() and MaxTimes()?

ilya-hontarau avatar Aug 29 '23 12:08 ilya-hontarau

Hello, and what should reply httpmock before MinTimes() invocations are reached?

maxatome avatar Sep 05 '23 14:09 maxatome

@maxatome I would expect the same behavior it has now for Times(), throwing panic

ilya-hontarau avatar Sep 06 '23 10:09 ilya-hontarau

Hello, do you have a use case for this behavior? As you will receive errors for the first MinTimes()-1 calls before receiving the first good response.

maxatome avatar Sep 06 '23 12:09 maxatome

As you will receive errors for the first MinTimes()-1 calls before receiving the first good response.

What I thought, this check can be placed in a defer function, so it can assert in the end of the execution that min times isn't reached.

do you have a use case

I can see it useful, when testing logic with a undetermenistic behaivor, as example logic of pereodic pulling, retries.

ilya-hontarau avatar Sep 06 '23 13:09 ilya-hontarau

As a Responder is a function (for historical reasons) it is not possible without doing dirty things to know how many times a Responder has been called.

But you can have a specific function to "track" a responder:

func Track(calls *int, r Responder) Responder {
	return func(req *http.Request) (*http.Response, error) {
		*calls++
		return r(req)
	}
}

this way you can know how many times it has been called, but explicitly:

var num int
r := Track(&num, httpmock.NewStringResponder(200, "OK))
httpmock.RegisterResponder("GET", "/foo", r)
httpmock.RegisterResponder("GET", "/bar", r)
// do your calls
fmt.Printf("The responder has been called %d times\n", num)

note that if you want to know how many times a URL has been mocked, you can simply use GetCallCountInfo.

maxatome avatar Sep 06 '23 16:09 maxatome