function StreamWrapperTest::testReadWrite

Same name in other branches
  1. 4.0.x modules/stream_wrapper_example/tests/src/Kernel/StreamWrapperTest.php \Drupal\Tests\stream_wrapper_example\Kernel\StreamWrapperTest::testReadWrite()

Test functions on a URI.

File

modules/stream_wrapper_example/tests/src/Kernel/StreamWrapperTest.php, line 58

Class

StreamWrapperTest
Test of the Session Stream Wrapper Class.

Namespace

Drupal\Tests\stream_wrapper_example\Kernel

Code

public function testReadWrite() {
    $this->resetStore();
    $uri = 'session://drupal.txt';
    $this->assertFileDoesNotExist($uri, "File {$uri} should not exist yet.");
    $handle = fopen($uri, 'wb');
    $this->assertNotEmpty($handle, "Handle for {$uri} should be non-empty.");
    $buffer = "Ain't seen nothin' yet!\n";
    // Original session class gets an error here,
    // "...stream_write wrote 10 bytes more data than requested".
    // Does not matter for our demo, so repress error reporting here.".
    $old = error_reporting(E_ERROR);
    $bytes_written = @fwrite($handle, $buffer);
    error_reporting($old);
    $this->assertNotFalse($bytes_written, "Write to {$uri} succeeded.");
    $result = fclose($handle);
    $this->assertNotFalse($result, "Closed {$uri}.");
    $this->assertFileExists($uri, "File {$uri} should now exist.");
    $this->assertDirectoryDoesNotExist($uri, "{$uri} is not a directory.");
    $this->assertTrue(is_file($uri), "{$uri} is a file.");
    $contents = file_get_contents($uri);
    // The example implementation calls HTML::escape() on output. We reverse it
    // well enough for our sample data (this code is not I18n safe).
    $contents = Html::decodeEntities($contents);
    $this->assertEquals($buffer, $contents, "Data for {$uri} should make the round trip.");
}