Coder Social home page Coder Social logo

bovigo / vfsstream Goto Github PK

View Code? Open in Web Editor NEW
1.4K 41.0 103.0 1.28 MB

vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with any unit test framework, like PHPUnit or SimpleTest.

License: BSD 3-Clause "New" or "Revised" License

PHP 100.00%
vfsstream php testing filesystem

vfsstream's Introduction

vfsStream

Tests Coverage Status Latest Stable Version Latest Unstable Version

vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with any unit test framework, like PHPUnit or SimpleTest.

Documentation

See the wiki.

Also you might want to check vfsStream examples.

vfsstream's People

Contributors

acoulton avatar alexpott avatar allejo avatar arvenil avatar bizurkur avatar dependabot[bot] avatar jaapio avatar jsmitty12 avatar kevinxucs avatar kornrunner avatar malkusch avatar mathieuk avatar merijnvdk avatar mikey179 avatar neclimdul avatar nikcorg avatar phil-davis avatar photodude avatar predakanga avatar remicollet avatar robocoder avatar samnela avatar sasezaki avatar sebkrueger avatar snapshotpl avatar sndsgd avatar szepeviktor avatar tiger-seo avatar valiodotch avatar voda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vfsstream's Issues

vfsStream with SQLite3

Don't know, if this is a vfsStream- or SQLite3-issue, but when I try to open a SQLite database it fails

require 'vfsStream/vfsStream.php';

\vfsStreamWrapper::register();
\vfsStream::create(array(), 'root', 0777);
$x = new \SQLite3('vfs://root/library.db');

Error

Fatal error: Uncaught exception 'Exception' with message 'Unable to open database: unable to open database file'

vfsStream::create() has issues with numeric directories

Ran into trouble while trying to use numeric directories:

$struct = array ('2011' => array('test.txt' => 'somecontent'));
vfsStream::Register();
$root = vfsStream::create($struct);
vfsStreamWrapper::setRoot($root);

echo file_exists("vfs://2011/test.txt") ? "Found" : "Not found";

This while the following would work:

$struct = array ('test2011' => array('test.txt' => 'somecontent'));
vfsStream::Register();
$root = vfsStream::create($struct);
vfsStreamWrapper::setRoot($root);

echo file_exists("vfs://test2011/test.txt") ? "Found" : "Not found";

The problem lies in that PHP will turn numeric array keys into integers (even when you explicitely specify them as strings) combined with the fact that vfsStreamAbstractContent.php does a type-aware comparison:

   public function appliesTo($name)
    {
        if ($name === $this->name) {
            return true;
        }

        return (substr($name, 0, strlen($this->name)) === $this->name && strpos($name, '/') !== false);
    }

prohibit aquiring locks when already locked / release lock on fclose()

UntTest Code and Case:

        VFS::getRoot()->getChild('registry')
                      ->getChild('packages')
                      ->getChild('testfile')                           // --> This is File
                      ->lock(LOCK_EX + LOCK_NB);

Code:

        if(!flock($fh, LOCK_EX + LOCK_NB))   // flock must return FALSE
        {
            fclose($fh);
            return false;
        }

proposed changes:

    /**
     * set lock status for stream
     *
     * @param   int   $operation
     * @return  bool
     * @since   0.10.0
     * @see     https://github.com/mikey179/vfsStream/issues/6
     */
    public function stream_lock($operation)
    {
        if($this->content->isLocked())
        {
            return false;
        }

        $this->content->lock($operation);
        return true;
    }

// AND fclose unlock file

    /**
     * closes the stream
     */
    public function stream_close()
    {
        $this->content->lock(LOCK_UN);
    }

Support of dot dirs "." & ".."

In real directories there are always two special dirs: "." & "..". vfsStream doesn't currently emulates this behavior. So code that should be aware of this specials dirs can not be tested correctly.

vfsStream::create() removes old structure

When using vfsStream::create(), the VFS is re-initialized each time. This is IMHO unexpected behaviour, as "create" is related to creating directories and files, not setting up the whole filesystem.

I propose to add a check to create() if the VFS has been set up, and then re-use that root, otherwise initialize it as it is currently.

Size limit (quota) for VFS

Hi!

In some cases it could be useful to set size limit for VFS (quota). Than I can test code which handles low level exceptions, for example when is_writable() on folder returns true, but file_put_contents return false in case of no space on disk. Currently I can't test this case - I cannot simulate via VSF situation, that is_writable() returns true, but file_put_contents generate false :/

greetings,
Damian

GD not working fully with vfs ?

Hi,

It seems that some gd functions are not really working well with GD. From what I tested, functions like imagejpeg (and probably imagepng, imagegif and other) and imagecreatefromjpeg (and imagecreatefrompng, ...) issue the error imagejpeg(): Unable to open 'vfs://root/ratio/narrow/0.jpg' for writing: No such file or directory with :

<?php
// ... vfsStream was already started in the setUp method
vfsStream::create(['ratio' => ['narrow' => []]);

$a = imagecreate(120, 80);
imagejpeg($a, vfsStream::url('root/ratio/narrow/0.jpg'));

And when fetching the result with imagecreatefromjpeg, I have the same error. But functions like getimagesize works for :

<?php
// ... vfsStream was already started in the setUp method
vfsStream::create(['ratio' => ['narrow' => []]);

$a = imagecreate(120, 80);
ob_start();
imagejpeg($a, vfsStream::url('root/ratio/narrow/0.jpg'));
vfsStream::create(['0.jpg' => ob_get_clean()], vfsStream::getRoot()->getChild('ratio/narrow'));

I don't know if it is because that GD supports or not the steam wrappers, but maybe those two tickets (#45056 and #39263) should be able to help you (As I'm not really on edge on things like wrappers, filesystems, ...) ?

Cheers.

mount/symlink within vfs

From https://code.google.com/p/bovigo/issues/detail?id=23

Feature request

I dont know, how difficult this is, or if its even possible, but I think, that would be a nice enhancement. I think of a similar feature, like the Phar::mount() [1] method in vfs.

As an example

vfsStream::mount('directory','file:///usr/share/php');

If this is also possible with phps "symlink()"-function, that will be nice, but I dont know how it works internally and I dont expect it ( http://bugs.php.net/bug.php?id=38025 )

[1] php.net/phar.mount

mkdir overwrites existing directories/files.

Contrary to file-based implementations of mkdir, vfsStream overwrites existing directories and files instead of triggering a warning and returning false.

Example:

<?php
require('vfsStream/vfsStream.php');
vfsStream::setup('root');
$dir = vfsStream::url('root/dir');
assert(mkdir($dir));
assert(!mkdir($dir)); // This assertion should succeed.

Investigate glob() with vfsStream urls

Check if and how glob() works with vfsStream urls.

Comment 1 by [email protected], Feb 16, 2011

Simple case:

$root = vfsStream::setup('example');

mkdir(vfsStream::url('example/test/'), 0777, TRUE);

$files = glob(vfsStream::url('example'), GLOB_MARK);

print_r($files); // prints out nothing but does not complain either

Comment 2 by [email protected], Feb 16, 2011

A simple workaround this problem is to use SPL's recursive iterators instead:

$dir_iterator = new RecursiveDirectoryIterator($dir);
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::CHILD_FIRST);

foreach ($iterator as $file) {
   echo $file, "\n";
}

Add support for streamWrapper::stream_cast($cast_as)

From: https://code.google.com/p/bovigo/issues/detail?id=22

In PHP 5.3 a new stream wrapper method was introduced, streamWrapper::stream_cast($cast_as). See http://php.net/manual/de/streamwrapper.stream-cast.php. vfsStream should support this, as for example gzopen() seems to rely on this.

Comment 1 by [email protected], Feb 16, 2011

I'm not sure it's possible to do anything about this. stream_cast is supposed to return a stream resource or FALSE. For example fopen returns a stream resource. But as far as I'm aware there is no way to create an artificial stream resource. Or maybe I just don't understand how it works..

Comment 2 by project member mikey179, Feb 16, 2011

Well, we'll find out when I start investigating (and possibly implementing) this issue. Of course it can turn out that I can't do anything about it, but we will see. :-)

Feature Request: method to print directory structure

For debugging purposes it would be REALLY useful to have a method to pretty print the current directory structure.

If one already exists and I've just missed it, change this request to 'document pretty printing method'

Resolve path not called everywhere its needed

the resolve path method for using relative paths isn't called in several places its required.

mkdir doesn't use it

added

$path = $this->resolvePath($path);

on line 517 before

$path = vfsStream::path($path);
if (null === self::$root) {
self::$root = vfsStream::newDirectory($path, $permissions);
return true;
}

rename doesn't use it for the destination path

replaced:

    $srcRealPath = $this->resolvePath(vfsStream::path($path_from));
    $dstRealPath = vfsStream::path($path_to);

with:

    $srcRealPath = $this->resolvePath(vfsStream::path($path_from));
    $dstRealPath = $this->resolvePath(vfsStream::path($path_to));

on line 472

There are probable other places its missing from as well, however I've not yet come across them in my usage. I will update this with any more I come across.

Bug in chmod

Tests:

Debian 6, PHP 5.3.3-7:

<?php
mkdir(__DIR__ . '/test/');
touch(__DIR__ . '/test/test.file');
$status1 = @chmod(__DIR__ . '/test/', 0444);
$status2 = @chmod(__DIR__ . '/test/test.file', 0777);
var_dump($status1, $status2);

The result:

stalxed@pc:~$ php test.php
bool(true)
bool(false)

Windows 8, PHP 5.4.11:

<?php
use org\bovigo\vfs\vfsStream;

class ChmodTest extends PHPUnit_Framework_TestCase
{
    public function testParentDirectoryModeSet444()
    {
        $structure = array(
            'test' => array(
                'test.file' => ''
            )
        );
        $root = vfsStream::setup('root', null, $structure);
        $root->getChild('test')->chmod(0444);

        $status = @chmod(vfsStream::url('root/test/test.file'), 0777);

        $this->assertFalse($status);
    }
}

test fails!
Result in Zend Studio:
http://screens.stalxed.ru/1/19852%5F2013%2D02%2D164%2Epng

Difference between real file system and vfs with RecursiveDirectoryIterator

I got the difference between real file system and vfs when I used RecursiveDirectoryIterator. On real file system filelist has '.' or '..', but vfs does not have them.

File system: ext4
PHP: 5.3.10-1ubuntu3.4

Reproducing Code

    // create real file
    $path = TESTPATH . 'tmp/Core/AbstractFactory';
    @mkdir($path, 0777, true);
    file_put_contents("$path/test.php", '');
    file_put_contents("$path/other.php", '');
    file_put_contents("$path/Invalid.csv", '');
    @mkdir(TESTPATH . 'tmp/Core/AnEmptyFolder', 0777, true);
    $path = TESTPATH . 'tmp/Core';
    file_put_contents("$path/badlocation.php", '');

    $path = TESTPATH . 'tmp';
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path),
                                              RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($iterator as $path) {
      echo $path, PHP_EOL;
    }

    // use vfs
    vfsStream::setup();
    $structure = array(
      'Core' => array(
        'AbstractFactory' => array(
          'test.php'    => 'some text content',
          'other.php'   => 'Some more text content',
          'Invalid.csv' => 'Something else',
         ),
        'AnEmptyFolder'   => array(),
        'badlocation.php' => 'some bad content',
      )
    );
    $root = vfsStream::create($structure);
    $rootPath = vfsStream::url($root->getName());

    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootPath),
                                              RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($iterator as $path) {
      echo $path, PHP_EOL;
    }

Result

/tests/tmp/Core/badlocation.php
/tests/tmp/Core/..
/tests/tmp/Core/AnEmptyFolder
/tests/tmp/Core/AbstractFactory/Invalid.csv
/tests/tmp/Core/AbstractFactory/other.php
/tests/tmp/Core/AbstractFactory/test.php
/tests/tmp/Core/AbstractFactory/..
/tests/tmp/Core/AbstractFactory
/tests/tmp/Core
/tests/tmp/.
/tests/tmp/..
vfs://root/Core/AbstractFactory/test.php
vfs://root/Core/AbstractFactory/other.php
vfs://root/Core/AbstractFactory/Invalid.csv
vfs://root/Core/AbstractFactory
vfs://root/Core/AnEmptyFolder
vfs://root/Core/badlocation.php
vfs://root/Core

vfsStreamDirectory::hasChild() gives false positives for nested paths

Currently vfsStreamDirectory::hasChild() and getChild() can give false positives in certain circumstances with nested paths.

The issue is that multi-level paths are not properly compared in vfsStreamAbstractContent.php so that characters within a directory name can be treated as though they were a directory separator.

For eg:

$root = vfsStream::setup('root');
$path = vfsStream::url('root/subdir1/subdir2/foo');
mkdir($path, '0700',true);

// This is true:
echo $root->hasChild('subdir1/subdir2/foo');

// But so is this:
echo $root->hasChild('subdir1.subdir2/foo');

// And this:
echo $root->hasChild('subdir1Xsubdir2/foo');

I only noticed this because I changed my folder naming strategy to move from www/foo/bar/com/page/path/data.html to be www.foo.bar.com/page/path/data.html and tests that should have failed still passed!

I have a patch and will submit in a sec - just need to grab the issue number.

Dublicated name for root and subfolder

I just finish debugging a weird error within my testsuite and it seems that vsfStream has a problem when a folder with the same name as the root name is created within. Here is a short example what I mean:

public function testVsfStreamNotWorking() {
    vfsStream::setup('testFolder');
    $tmpRootDir = vfsStream::url('testFolder');

    mkdir($tmpRootDir . '/testFolder/subTestFolder', 0777, true);

    $expectedOutput = array(
        'testFolder' => array(
            'testFolder' => array(
                'subTestFolder' => array()
            )
        )
    );

    $this->assertEquals($expectedOutput, vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure());
}

This test fails. If I rename one of the two testFolder, it works. As said, it took me quiet some time to realize what is happening, as the tests were working with the real filesystem and only failing when vsfStream is used.

How to do an unlink?

In my unit test, I am testing a delete() method in a class, which internally calls unlink(). I'm getting a fatal error when this runs though, and I'm not sure where I've gone wrong.

public function testDeleteSuccess()
{
$root = vfsStream::setup('testDir');

    $hash = md5(microtime());
    $content = 'some content';
    $tmpfile = vfsStream::newFile($hash);
    $tmpfile->setContent($content);

    $root->addChild($tmpfile);
    $this->assertTrue($root->hasChild($hash));

    $file = new MyClass(vfsStream::url($hash));
    $this->assertEquals(TRUE, $file->delete());
    $this->assertFalse($root->hasChild($hash));
}

When $MyClass::delete() is called, I get the following:

Fatal error: Call to a member function isWritable() on a non-object in /site/vendor/vfsStream/src/main/php/org/bovigo/vfs/vfsStreamWrapper.php on line 691

Here's the relevant part of the trace:

0.1154 4645844 13. MyClassTest->testDeleteSuccess() /usr/share/pear/PHPUnit/Framework/TestCase.php:969
0.1198 5128700 14. MyClass->delete() /path/to/tests/MyClassTest.php:157
0.1199 5128804 15. unlink('vfs://9f2964e0276829d96c9bf1ed1695229f') /path/to/MyClass.inc:80
0.1199 5129388 16. org\bovigo\vfs\vfsStreamWrapper->unlink($path = 'vfs://9f2964e0276829d96c9bf1ed1695229f') /path/to/MyClass.inc:80
0.1200 5129504 17. org\bovigo\vfs\vfsStreamWrapper->doUnlink($path = '9f2964e0276829d96c9bf1ed1695229f') /site/vendor/vfsStream/src/main/php/org/bovigo/vfs/vfsStreamWrapper.php:671

PHP Warning with include_path() and stream_resolve_include_path()

From https://code.google.com/p/bovigo/issues/detail?id=24

What steps will reproduce the problem?
To reproduce it, Ive use the interactive console (php -a)

php > require 'vfsStream.php';
php > vfsStreamWrapper::register();
php > mkdir('vfs://just/a/path',0777,true);
php > set_include_path('vfs://just/a');
php > $a = stream_resolve_include_path('path/unknownFile.php');
PHP Warning:   No such file or directory in .../vfsStreamWrapper.php on line 658
PHP Stack trace:
PHP   1. {main}() php shell code:0
PHP   2. stream_resolve_include_path() php shell code:1
PHP   3. vfsStreamWrapper->url_stat() .../vfsStreamWrapper.php:0
PHP   4. trigger_error() .../vfsStreamWrapper.php:658

What version of the product are you using? On what operating system?
Version 0.8.0 (from SVN) with PHP5.3 on Ubuntu 10.10

Please provide any additional information below.
Maybe this has something to do with #3?

Add support for fileatime() and filectime()

vfsStream should support usage of fileatime() and filectime() as well. Updates should be done the following way, quoting http://www.aquaphoenix.com/ref/gnu_c_library/libc_166.html

When an existing file is opened, its attribute change time and modification time fields are updated. Reading
from a file updates its access time attribute, and writing updates its modification time.

When a file is created, all three timestamps for that file are set to the current time. In addition, the attribute
change time and modification time fields of the directory that contains the new entry are updated.

Adding a new name for a file with the link function updates the attribute change time field of the file being linked,
and both the attribute change time and modification time fields of the directory containing the new name. These
same fields are affected if a file name is deleted with unlink, remove, or rmdir. Renaming a file with rename
affects only the attribute change time and modification time fields of the two parent directories involved, and not
the times for the file being renamed.

Changing attributes of a file (for example, with chmod) updates its attribute change time field.

Check parent directory for permissions

When accessing a file permissions of the directory the file is inside are not considered correctly, e.g. you can read from a file in a directory you don't have read permissions for). In order to behave properly and mimic real file system behaviour this must be changed.

flock $wouldblock parameter is always zero

To see the issue we should extend this test:
https://github.com/mikey179/vfsStream/blob/f4622c8a7f26d28df8c61916c8c4596e787e5c7f/src/test/php/org/bovigo/vfs/vfsStreamWrapperFlockTestCase.php#L303

$this->assertFalse(flock($fp2, LOCK_SH + LOCK_NB, $block));
$this->assertEquals($block, 1);

After a change phpunit does not pass:

There was 1 failure:

1) org\bovigo\vfs\vfsStreamWrapperFlockTestCase::canNotAquireSharedLockIfAlreadyExclusivelyLockedOnOtherFileHandler
Failed asserting that 0 matches expected 1.

/home/vfsStream/src/test/php/org/bovigo/vfs/vfsStreamWrapperFlockTestCase.php:304

FAILURES!
Tests: 326, Assertions: 1247, Failures: 1, Skipped: 5.

Tested on Centos6

Flock implementation doesn't work correctly

Each call of flock on the same file handler, firstly releases the lock and then tries to acquire it again.

<?php
$f = fopen('/tmp/file.lock', 'c');
var_dump(flock($f, LOCK_EX)); // outputs true
var_dump(flock($f, LOCK_EX)); // outputs true
var_dump(flock($f, LOCK_SH)); // outputs true
fclose($f);

In documentation http://www.php.net/manual/en/function.flock.php you can read warning

Assigning another value to handle argument in subsequent code will release the lock.

So for the same file handler (in one threaded application) each flock call will always return true. Locking mechanism is designed for running multiple processes at once, or if you open multiple file handlers to file.

<?php
$f1 = fopen('/tmp/file.lock', 'c');
$f2 = fopen('/tmp/file.lock', 'c');
var_dump(flock($f1, LOCK_EX | LOCK_NB)); // outputs true
var_dump(flock($f2, LOCK_EX | LOCK_NB)); // outputs false
var_dump(flock($f2, LOCK_SH | LOCK_NB)); // outputs false
fclose($f1);
fclose($f2);

Below is a test program which will show differences between real file locking and locking mechanism in vfsStream.

<?php
require_once('vendor/autoload.php');

use org\bovigo\vfs;

function testFlockLock($handle, $lock) {
  $output = array();
  $output[] = $handle;
  $output[] = $lock & LOCK_EX ? "LOCK_EX" : "LOCK_SH";
  $output[] = flock($handle, $lock | LOCK_NB) ? "success" : "fail";
  echo join(' ', $output)."\n";
}

function testFlockUnlock($handle) {
  $output[] = $handle;
  $output[] = "LOCK_UN";
  $output[] = flock($handle, LOCK_UN) ? "success" : "fail";
  echo join(' ', $output)."\n";
}

vfs\vfsStream::setup('tmp');

$files = array();
$files[] = '/tmp/file.lock';
$files[] = vfs\vfsStream::url('tmp/file.flock');
foreach ($files as $file) {
  $handle1 = fopen($file, 'c');
  $handle2 = fopen($file, 'c');

  echo $file."\n";
  testFlockLock($handle1, LOCK_SH);
  testFlockLock($handle1, LOCK_SH);
  testFlockLock($handle1, LOCK_EX);
  testFlockLock($handle1, LOCK_EX);
  testFlockLock($handle1, LOCK_SH);
  testFlockUnlock($handle1);
  testFlockLock($handle1, LOCK_EX);
  testFlockLock($handle1, LOCK_EX);
  echo "\n";

  testFlockLock($handle2, LOCK_EX);
  testFlockLock($handle2, LOCK_SH);
  testFlockLock($handle2, LOCK_EX);
  echo "\n";

  testFlockUnlock($handle1);
  testFlockUnlock($handle2, LOCK_UN);
  testFlockLock($handle1, LOCK_SH);
  testFlockLock($handle2, LOCK_SH);
  testFlockLock($handle2, LOCK_EX);
  testFlockUnlock($handle1);
  testFlockUnlock($handle2);
  testFlockLock($handle1, LOCK_EX);
  testFlockLock($handle2, LOCK_SH);
  echo "\n";
}

Output is:

/tmp/file.lock
Resource id #18 LOCK_SH success
Resource id #18 LOCK_SH success
Resource id #18 LOCK_EX success
Resource id #18 LOCK_EX success
Resource id #18 LOCK_SH success
Resource id #18 LOCK_UN success
Resource id #18 LOCK_EX success
Resource id #18 LOCK_EX success

Resource id #19 LOCK_EX fail
Resource id #19 LOCK_SH fail
Resource id #19 LOCK_EX fail

Resource id #18 LOCK_UN success
Resource id #19 LOCK_UN success
Resource id #18 LOCK_SH success
Resource id #19 LOCK_SH success
Resource id #19 LOCK_EX fail
Resource id #18 LOCK_UN success
Resource id #19 LOCK_UN success
Resource id #18 LOCK_EX success
Resource id #19 LOCK_SH fail

vfs://tmp/file.flock
Resource id #21 LOCK_SH success
Resource id #21 LOCK_SH success
Resource id #21 LOCK_EX fail
Resource id #21 LOCK_EX fail
Resource id #21 LOCK_SH success
Resource id #21 LOCK_UN success
Resource id #21 LOCK_EX success
Resource id #21 LOCK_EX fail

Resource id #22 LOCK_EX fail
Resource id #22 LOCK_SH fail
Resource id #22 LOCK_EX fail

Resource id #21 LOCK_UN success
Resource id #22 LOCK_UN success
Resource id #21 LOCK_SH success
Resource id #22 LOCK_SH success
Resource id #22 LOCK_EX fail
Resource id #21 LOCK_UN success
Resource id #22 LOCK_UN success
Resource id #21 LOCK_EX success
Resource id #22 LOCK_SH fail

I'm currently finishing my proposition how to implement flock in vfsStream. I will push this soon.

PEAR channel down

Looks like the PEAR channel is not working.
Are there any mirrors?

vfsStreamFile with same names is not erased between two tests

In a phpunit test class I have the setup as shown below. If I run the tests like the result is, that in testRun() the SomeHook class added as a Child to the vfsRoot will have the same content which it had in testRunExceptionCaught().

$this->vfsRoot->hasChildren() returns false at the beginning of testRunExceptionCaught(). Are the vfsStreamFiles cached somewhere statically?

Running phpunit 3.7 with default settings.

    /**
     * @see parent::setUp
     */
    public function setUp() {
        $this->vfsRoot = vfs\vfsStream::setup(self::VFS_STREAM_ROOT);
        $this->vfsRootUrl = vfs\vfsStream::url(self::VFS_STREAM_ROOT);
    }

    /**
     * Tests if Exceptions thrown from hook instances are handled correctly.
     *
     * @return null
     */
    public function testRunExceptionCaught() {
        // Prepare Hook class which will throw an Exception on calling go().
        $hookFile = new vfs\vfsStreamFile('SomeHook.class.php');
        $hookFile->setContent(
            "<?php class SomeHook { function go() { throw new Exception('blah', 123); } }"
        );

        // Add dummy class files to vfs.
        $this->vfsRoot->addChild(new vfs\vfsStreamFile('GitPreReceiveHook.class.php'));
        $this->vfsRoot->addChild($hookFile);

        // Mock handleException() so exit() doesn't break the tests.
        $g = $this->getMockBuilder('GitHookProcessor')
            ->setMethods(array('handleException'))
            ->setConstructorArgs(array(GitHookProcessor::TYPE_PRE_RECEIVE))
            ->getMock();
        $g->expects($this->any())
            ->method('handleException')
            ->will($this->returnArgument(0));

        // Run.
        /* @var GitHookProcessor $g */
        $this->assertEquals(new Exception('blah', 123), $g->setHookPath($this->vfsRootUrl)->run());
    }

    /**
     * Tests if run() method works in properly prepared environment.
     *
     * @return null
     */
    public function testRun() {
        $hookFile = new vfs\vfsStreamFile('SomeHook.class.php');
        $hookFile->setContent("<?php class SomeHook { function go() { } }");
        $this->vfsRoot->addChild($hookFile);
        $this->vfsRoot->addChild(new vfs\vfsStreamFile('GitPreReceiveHook.class.php'));

        $g = new GitHookProcessor(GitHookProcessor::TYPE_PRE_RECEIVE);
        $this->assertNull($g->setHookPath($this->vfsRootUrl)->run());
    }

Replace vfsStreamContent to vfsStreamContainer for autocompletion

Please replace type hinting and return values for methods vfsStreamWrapper::setRoot(), vfsStreamWrapper::getRoot() from vfsStreamContent to vfsStreamContainer. This allows for autocompletion in contructions like this:

vfsStreamWrapper::getRoot()->hasChild('id')

Composer error : branch 1.3.x-dev doesn't exist

Composer throw an exception when we try to update the package.

[RuntimeException]                                                           
  Failed to clone http://github.com/mikey179/vfsStream.git via git, https and  
   http protocols, aborting.                                                   

  - git://github.com/mikey179/vfsStream.git                                    
    fatal: Not a git repository (or any of the parent directories): .git       

  - https://github.com/mikey179/vfsStream.git                                  
    fatal: Not a git repository (or any of the parent directories): .git       

  - http://github.com/mikey179/vfsStream.git                                   
    fatal: Not a git repository (or any of the parent directories): .git 

Error introduced in bfe5bcf

Bug in unlink

In method unlink(vfsStreamWrapper.php) there is a code:

$realPath = $this->resolvePath(vfsStream::path($path));
$content  = $this->getContent($realPath);
if (null === $content || $content->isWritable(vfsStream::getCurrentUser(), vfsStream::getCurrentGroup()) === false) {
    return false;
}

it checks the file permissions!
But, in unix system, when deleting files, check permissions on the parent directory(directory which contains the file).

Get object of vfsStreamFile to get the file content

I have created a directory structure like

$structure = array(
    'tmp' => array(
        // put an inner view in 'foo'
        'foo' => array(
            'inner_view.php' => '<strong><?= $this->inner_var; ?></strong>'
        ),
        'bar',
        // put an outer view in 'baz'
        'baz' => array(
            'outer_view.php' => '<div><?php echo $this->outer_var . " " . $this->__raw()->inner_view; ?></div>'
         ),
     )
);

    $this->root = vfsStream::setup('root', null, $structure);

Now how can I get the content. I am seeing the vfsStreamFile class. But wondering how is the way I can get the object of it from the directory . Didn't noticed any :( .

Doesn't support windows directory separator

Windows file systems use \ as a separator instead of / vfs doesn't work (and doesn't even throw an error) when a function eg mkdir is called using the windows file separator.

unlink empty directory

I've tried to learn TDD using PHPUnit with vfsStream. Using PHP's unlink in a directory normally raises up an warning ("Warning: unlink(/tmp/foo): Operation not permitted in ..."). Empty directories must be removed with rmdir. Doing the same with vfsStreamDirectory doesn't return an warning. I don't know if I'm missing something or if it's a real bug.

Test:

<?php
require 'vfsStream/vfsStream.php';
require '../Classes/Recursive/Delete.php';

class Recursive_Delete_Test extends PHPUnit_Framework_TestCase {
    public function testShouldRemoveAnEmptyDirectory()
    {
        vfsStream::setup();
        vfsStreamWrapper::getRoot()->addChild(vfsStream::newDirectory('dir'));
        $recursiveDelete = new Recursive_Delete(vfsStream::url('root/dir'));
        $recursiveDelete->delete();
        $this->assertFileNotExists(vfsStream::url('root/dir'));
    }
}

Production code:

<?php
class Recursive_Delete
 {
    private $_file;

    public function __construct($file)
    {
        $this->_file = $file;
    }

    public function delete()
    {
        unlink($this->_file);
    }
}

Thank you very much and sorry about my english.

Recursive delete for subdir which is read-only

Hello, I think this is a bug,
mkdir(vfsStream::url(self::ROOT_DIR . '/delete/recursive/external'), 0777, true);
touch(vfsStream::url(self::ROOT_DIR . '/delete/recursive/external/deepfile'));
chmod(vfsStream::url(self::ROOT_DIR . '/delete/recursive/external/deepfile'),0555); // read-only
$dir->truncate(vfsStream::url(self::ROOT_DIR . '/delete/recursive')); // do the same as rm -r /delete/recursive/*
$this->assertFalse(vfsStreamWrapper::getRoot()->hasChild('delete/recursive/external'));
$this->assertTrue(vfsStreamWrapper::getRoot()->hasChild('delete/recursive'));
This test is successful but this is wrong! Is vfsStream consider rights for children?

Weird filemtime behaviour

Create a file, get its last modified time, write new contents, get its last modified time again:

$structure = array(
            'ubertest.html' => 'This is a test page.'
);
$root = vfsStream::create($structure);

$mtime = filemtime(vfsStream::url('root/ubertest.html'));
usleep(2000000);
file_put_contents(vfsStream::url('root/ubertest.html'), 'BLAAAAH');
$mtime2 = filemtime(vfsStream::url('root/ubertest.html'));
$mtime3 = $root->getChild('ubertest.html')->filemtime();

$mtime3 will be correct (2 seconds later than $mtime), but $mtime2 is not (I get the same value as $mtime). It's as if the time value is cached when using filemtime. Looking at vfsStream's code, I can't see any obvious bugs, and with some trace code I realized vfsStreamAbstractContent::filemtime is only called twice! So I'm wondering if PHP is trying to do something clever behind my back and I need to setup something prior to running this code?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.