donatj / mock-webserver

Simple mock web server in PHP for unit testing.
MIT License
131 stars 21 forks source link

Simulate slow responses #38

Closed arondeparon closed 2 years ago

arondeparon commented 2 years ago

It would be great it there would be a way to simulate slow responses (IE: by manually adding a sleep()) call to it.

As it stands right now, it does not look like there is any way to do this. Is this something that could be considered?

arondeparon commented 2 years ago

I decided to experiment a bit and found a way to do this using a custom Response object:

class SlowResponse extends Response
{
    private int $delay = 0;

    /**
     * Set the delay in milliseconds
     *
     * @param int $delay
     *
     * @return void
     */
    public function setDelay(int $delay)
    {
        $this->delay = $delay;
    }

    public function getBody(RequestInfo $request)
    {
        // convert delay (milliseconds) to microseconds
        usleep($this->delay * 1000);

        return parent::getBody($request);
    }

}

With this approach you can simply add a SlowResponse object to a path and you should be good to go.

donatj commented 2 years ago

I reopened this because it's a feature request I get pretty often in talking to people.

I still wonder about adding actual slowdown to testing and the potential harms that comes with that, but there's a certain case of testing that it would certainly help.

arondeparon commented 2 years ago

Yeah, slowing down tests is a bit of an edge case 😏

What I use this for right now is to simulate slow or unreachable connections in integration tests that rely on external API's. In such cases I don't want an external service to bring mine down, and want to handle these errors elegantly.

donatj commented 2 years ago

Took me a little bit, but I've got a similar but a little more featureful solution in #41