Skip to main content
Start of main content.

Testing CSV output in Drupal 8 with BrowserTestBase

by lee.rowlands /

Share this post on social media

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

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.