Closed nanawel closed 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.
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.
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.
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 viaheader()
, 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?)