I was trying to figure out the best way to test the myfputcsv() function I posted yesterday. Reading the data from disc before comparing it seemed like a step where errors could creep in, but there was no obvious way round that, as the purpose of the function is to write to disc.
Then I realised I could use PHP’s (fairly) new IO streams to dump the function’s output to a temporary buffer, and read it back in for comparison. Not perfect, but it removes concerns about file mutexes, permissions, unique filenames, etc. and speeds up the tests, as they never touch disc.
It wasn’t worth building on top of PHPUnit for this… checking failure conditions can wait for another day. I just wrote a quick script that compares the output of fputcsv() and myfputcsv(). (And it worked - I’ve already fixed two errors in yesterday’s post).
This is the first time I’ve reached for php://memory. It’s obviously useful for testing code that writes to disc, but I’m now wondering where else it might come in handy.
<?php
require_once 'myfputcsv.php';
function write( $function, $array )
{
$fp = fopen( 'php://memory', 'w+' );
$function( $fp, $array );
rewind( $fp );
return fread( $fp, 1024 );
}
function test( $array )
{
$fputcsv = write( 'fputcsv', $array );
$myfputcsv = write( 'myfputcsv', $array );
if ( assert( '$fputcsv === $myfputcsv' ) )
{
echo "OK" . PHP_EOL;
}
}
test( array() );
test( array( "Hello", "World" ) );
test( array( "He\nllo", "World" ) );
test( array( "He\\"llo", "World" ) );
test( array( "He llo", "World" ) );
test( array( "He\tllo", "World" ) );
test( array( "He\"\"llo", "World" ) );
test( array( "He,llo", "World" ) );