donatj / mock-webserver

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

Add support for variance by HTTP verb #3

Closed BramRoets closed 6 years ago

BramRoets commented 6 years ago

Is it possible to add support for the HTTP verb ?

Something like:

$server->setResponseOfPath( '/api/v1/users/5', '[user object]', [], 200, 'PUT' );

donatj commented 6 years ago

@BramRoets Such that it only responds to that verb, or?

donatj commented 6 years ago

That should be doable in the near future.

In the meantime you can change the expected response of a path by calling setResponseOfPath more than once if that's a possibility for your code.

BramRoets commented 6 years ago

That it would only respond to this verb. I'm doing a get and put request to the same url but expect different responses. Thanks for the tip about setResponseOfPath

dezmound commented 6 years ago

Simple solution is change this line in RequestInfo class:

$this->parsedUri = parse_url($server['REQUEST_URI']);

like this:

$this->parsedUri = parse_url($server['REQUEST_URI']);
$this->parsedUri['path'] .= '.' . $server['REQUEST_METHOD'];

And change setResponseOfPath in MockWebServer like this:

/**
     * Set a specified path to provide a specific response
     *
     * @param string $path
     * @param \donatj\MockWebServer\ResponseInterface $response
     * @param string $method HTTP method
     * @return string
     */
    public function setResponseOfPath( $path, ResponseInterface $response, $method = 'GET' ) {
            $parse = parse_url($path);
            $path = $parse['path'] . '.' . $method;
        $ref = InternalServer::storeResponse($this->tmpDir, $response);

        $aliasPath = InternalServer::aliasPath($this->tmpDir, $path);

        if( !file_put_contents($aliasPath, $ref) ) {
            throw new \RuntimeException('Failed to store path alias');
        }

        return $this->getServerRoot() . $path;
    }

Now this functional available:

$this->_server->setResponseOfPath(
                '/tasks',
                new Response(
                    \yii\helpers\Json::encode(['name' => 'test']),
                    [ 'Cache-Control' => 'no-cache', 'Content-Type' => 'application/json' ],
                    201
                ),
                'POST'
            );
donatj commented 6 years ago

v2.0.0 is offically released. See the example here: methods.php