donatj / mock-webserver

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

Convert index script output to JSON #5

Closed dsheiko closed 6 years ago

dsheiko commented 6 years ago

If you did output request details

Requesting: http://127.0.0.1:8123/endpoint?get=foobar

{
    "_GET": {
        "get": "foobar"
    },

as JSON we then would be able to run assertions over it. E.g.

<?php
$rsp = $this->client->request("GET", $url, [ "headers" => ["X-Foo" => "..."] ]);
$body = \json_decode((string)$rsp->getBody());
$this->assertEquals("...", $body->HEADERS->X-Foo);
donatj commented 6 years ago

1. It already does that on requests you don't set the body for.

<?php

use donatj\MockWebServer\MockWebServer;

require 'vendor/autoload.php';

$server = new MockWebServer();
$server->start();

$content = file_get_contents($server->getServerRoot() . '/foobar');

print_r($content);

Outputs

{
    "_GET": [],
    "_POST": [],
    "_FILES": [],
    "_COOKIE": [],
    "HEADERS": {
        "Host": "127.0.0.1:55260",
        "Connection": "close"
    },
    "METHOD": "GET",
    "INPUT": "",
    "PARSED_INPUT": [],
    "REQUEST_URI": "\/foobar",
    "PARSED_REQUEST_URI": {
        "path": "\/foobar"
    }
}

2. I think you'd be better served by using getLastRequest

getLastRequest gives you an array detailing the last request and works even if you set a custom body for the response.

<?php

use donatj\MockWebServer\MockWebServer;
use donatj\MockWebServer\Response;

require 'vendor/autoload.php';

$server = new MockWebServer();
$server->start();

// Get cURL resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server->getUrlOfResponse(new Response('foo')));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "X-Foo: ...",
    ]
);
$resp = curl_exec($ch);

print_r($server->getLastRequest()['HEADERS']);

Outputs:

Array
(
    [Host] => 127.0.0.1:55479
    [Accept] => */*
    [X-Foo] => ...
)
donatj commented 6 years ago

I'm keeping this open until I better document this to make it clearer… But I would like to know if this solves your issue?

dsheiko commented 6 years ago

Thank you, it works to me.