Testing CSV output in Drupal 8 with BrowserTestBase
Share:
In a recent project we were outputting CSV and wanted to test that the file contents were valid.
Read on for a quick tip on how to achieve this with Drupal 8's BrowserTestBase
by
Lee Rowlands
/ 20 October 2017
Basically, the easiest way to validate and parse CSV in PHP is with the built in fgetcsv function.
So how do you go about using that inside a functional test - in that instance we're not dealing with a file so its not your ordinary approach for fgetcsv.
The answer is to create a stream wrapper in memory, and use fgetcsv on that.
The code looks something like this:
$response = $this->getSession()
->getDriver()
->getContent();
// Put contents into a memory stream and use fgetcsv to parse.
$stream = fopen('php://memory', 'r+');
fwrite($stream, $response);
rewind($stream);
$records = [];
// Get the header row.
$header = fgetcsv($stream);
while ($row = fgetcsv($stream)) {
$records[] = $row;
}
fclose($stream);
There you have it, you now have the header in $header and the rows in $rows and can do any manner of asserts that you need to validate the CSV generation works as expected.
Tagged
Drupal 8, Testing, Functional Testing
Posted by
Lee Rowlands
Senior Drupal Developer
Dated 20 October 2017
Add new comment