I am new to Codeception and I am researching using it to run our integration / acceptance test suite (currently some phpunit scripts...). It seems like a very interesting tool but I've run into an issue that could prevent us from using it.
I'm trying to find a way to inject a middleware or create a module that will allow me to strip the JSON protection string from our server's response before it's decoded by the REST module.
The JSON is prefixed with ")]}', "
to make the object invalid, which protects against a type of CSRF vulnerability in some browsers, but it breaks json_decode()
(intentionally) and the Codeception REST validation methods.
I'm looking for a way to modify the response, to strip off the prefix, before the test suite begins using the data. Does anyone know if that's possible? Or if there are any built-in ways to work with or rewrite response bodies?
Unfortunately, removing the prefix from the server output is not an option. Thanks for any advice!
You can modify HTTP response content before it is parsed by REST module.
REST module uses PhpBrowser
or some Framefork module as HTTP-client. So to remove JSON protection string you need to create your own module that extends PhpBrowser
and overrides _getResponseContent()
method and then use this module in REST module config as dependency.
Let's assume I have REST method http://example.dev/api/v1/test
that returns following JSON string with protection prefix
)]}'
{"test":"smest"}
/tests/api.suite.yml
class_name: ApiTester
modules:
enabled:
- REST:
depends: \Helper\MyPhpBrowser
url: 'http://example.dev/api/v1/'
- \Helper\Api
/tests/_support/Helper/MyPhpBrowser.php
<?php
namespace Helper;
class MyPhpBrowser extends \Codeception\Module\PhpBrowser
{
public function _getResponseContent()
{
$rawContent = (string)$this->client->getInternalResponse()->getContent();
// Here we're going to delete protection prefix from response content
$rawContent = preg_replace("/^\)\]\}'
/", "", $rawContent);
return $rawContent;
}
}
/api/smestCept.php
<?php
$I = new ApiTester($scenario);
$I->sendGET('test');
$I->seeResponseContainsJson(['test' => 'smest']);
Result
$ codecept run api smestCept.php
Codeception PHP Testing Framework v2.2.4
Powered by PHPUnit 4.8.27 by Sebastian Bergmann and contributors.
Api Tests (1) -------------------------------------
✔ smestCept: (0.29s)
---------------------------------------------------
Time: 579 ms, Memory: 12.50MB
OK (1 test, 1 assertion)