f3-factory / fatfree-core

Fat-Free Framework core library
GNU General Public License v3.0
207 stars 88 forks source link

[REST] Set response headers in hive for unit tests #258

Closed nanawel closed 6 years ago

nanawel commented 6 years ago

Just like you can retrieve response data through $f3->get('RESPONSE'), it should be possible to retrieve headers with $f3->get('RESPONSE_HEADERS') (for example) in order to validate their content with unit tests.

Also, as a side note, that probably means that F3 should never call the header() function directly, but instead push headers to this reserved stack. In normal run, the headers would eventually then be sent via header(), but in simulated run (\Base::mock()) these data would be made available for validation in the test case.

I'm afraid to open a PR with such huge, possibily breaking change, so I'll be happy to get feedback from the community first. (maybe it has already been discussed?)

ikkez commented 6 years ago

For validating headers in a mocked run, you can simply use headers_list() to get all response headers which are going to be send for that test. Those headers are actually not sent to the browser as long as no content was sent. So you want to ensure this and that is pretty simple to achieve, since the internal router uses a buffer by default, so just set $f3->set('QUIET', TRUE); before you call $f3->mock(), fetch the headers and clean-up and return to normal.. just some lines like:

$f3->set('QUIET',TRUE);
$f3->route('GET /test',function($f3){
    header("Content-Type: application/json");
    echo json_encode(['foo'=>'bar']);
});
$f3->mock('GET /test');
$headers = headers_list();
header_remove();
$f3->set('QUIET',false);

header("Content-Type: text");
var_dump($headers);
var_dump($f3->get('RESPONSE'));

We use this method in the framework unit tests as well. yes maybe moving the header handling into a reserved stack is more clean, but it's actually not needed and also not reliable when you include and test 3rd party libs that run within your routes.. like dumping generated images or pdf files, authentication libs and such... they probably will use the header() function.

nanawel commented 6 years ago

Hi @ikkez, and thanks for your response. Well, when running unit tests with PHPUnit, calling headers() fails because PHPunit already has written data to output.

But I've found this thread that seems to be a good workaround: https://github.com/sebastianbergmann/phpunit/issues/720

I'll try the @runInSeparateProcess annotation as advised and see if it fixes this issue.

nanawel commented 6 years ago

Erf, it could have worked if only another error has not arised: https://github.com/sebastianbergmann/phpunit/issues/2739

So the only way to make it work I found was using PHPUnit's --stderr flag when running tests. That way the standard output is clear and PHP accepts to call header() without raising an error.

I'm closing this issue.