Search code examples
phpphpunitvfs-stream

file_put_contents into vfsstream raises error `failed to open stream:`


I want to write UnitTests, mocking the Filesystem with vfs.

My test looks like this:

<?php
use org\bovigo\vfs\vfsStreamContent;
use PHPUnit\Framework\TestCase;
use org\bovigo\vfs\vfsStream;


class MyClassTest extends TestCase {

    private $vfs;

    function setUp() {

        ini_set("allow_url_fopen", true);
        $this->vfs = vfsStream::setup('root', 777);
        $sampledataDir = vfsStream::newDirectory('sampledata', 777)->at($this->vfs);
        vfsStream::copyFromFileSystem(realpath(__DIR__ . '/../sampledata'), $sampledataDir);
        $dataDir = vfsStream::newDirectory('data', 777)->at($this->vfs);
    }


    function tearDown() {

        unset($this->vfs);
    }


    function testSetup() {

        file_put_contents($this->vfs->url() . "/data/newFile.html", "stuff");
    }

}

The file_put_contents command is inserted here as a sample, it should come from the class I want to test. Unfortunatley I get an error:

file_put_contents(vfs://root/data/newFile.html): failed to open stream: "org\bovigo\vfs\vfsStreamWrapper::stream_open" call failed

Why? What am I doing wrong?


From composer.json

  "require-dev": {
    "mikey179/vfsstream": "^1.6",
    "phpunit/phpunit":  "^6.5.0"
  }

additional infos:

php --version
PHP 7.3.11-1~deb10u1 (cli) (built: Oct 26 2019 14:14:18) ( NTS )

Solution

  • I found it myself: I saved the wrong url, forgetting the root-dir.

    changing it to did the trick. Sometimes the most trivial things are the nastiest.

    
    file_put_contents($this->vfs->url() . "/root/data/newFile.html", "stuff");