尝试使用VFSStream测试文件系统操作 [英] Trying to test filesystem operations with VFSStream

查看:74
本文介绍了尝试使用VFSStream测试文件系统操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用vfsStream模拟文件系统操作(实际上是从php://input读取),但是缺少像样的文档和示例确实妨碍了我.

I'm trying to mock a filesystem operation (well actually a read from php://input) with vfsStream but the lack of decent documentation and examples is really hampering me.

我正在测试的类中的相关代码如下:

The relevant code from the class I'm testing is as follows:

class RequestBody implements iface\request\RequestBody
{
    const
        REQ_PATH    = 'php://input',

    protected
        $requestHandle  = false;

    /**
     * Obtain a handle to the request body
     * 
     * @return resource a file pointer resource on success, or <b>FALSE</b> on error.
     */
    protected function getHandle ()
    {
        if (empty ($this -> requestHandle))
        {
            $this -> requestHandle  = fopen (static::REQ_PATH, 'rb');
        }
        return $this -> requestHandle;
    }
}

我在PHPUnit测试中使用的设置如下:

The setup I'm using in my PHPUnit test is as follows:

protected function configureMock ()
{
    $mock   = $this -> getMockBuilder ('\gordian\reefknot\http\request\RequestBody');

    $mock   -> setConstructorArgs (array ($this -> getMock ('\gordian\reefknot\http\iface\Request')))
            -> setMethods (array ('getHandle'));


    return $mock;
}

/**
 * Sets up the fixture, for example, opens a network connection.
 * This method is called before a test is executed.
 */
protected function setUp ()
{
    \vfsStreamWrapper::register();
    \vfsStream::setup ('testReqBody');

    $mock   = $this -> configureMock ();
    $this -> object = $mock -> getMock ();

    $this -> object -> expects ($this -> any ())
                    -> method ('getHandle')
                    -> will ($this -> returnCallback (function () {
                        return fopen ('vfs://testReqBody/data', 'rb');
                    }));
}

在实际测试中(该方法调用间接触发getHandle()的方法),我尝试设置VFS并运行如下的断言:

In an actual test (which calls a method which indirectly triggers getHandle()) I try to set up the VFS and run an assertion as follows:

public function testBodyParsedParsedTrue ()
{
    // Set up virtual data
    $fh     = fopen ('vfs://testReqBody/data', 'w');
    fwrite ($fh, 'test write 42');
    fclose ($fh);
    // Make assertion
    $this -> object -> methodThatTriggersGetHandle ();
    $this -> assertTrue ($this -> object -> methodToBeTested ());
}

这只会导致测试挂起.

This just causes the test to hang.

很显然,我在这里做错了什么,但是鉴于文档的状态,我无法弄清我打算做什么.这是由vfsstream引起的,还是phpunit在嘲笑我需要在这里查看的东西?

Obviously I'm doing something very wrong here, but given the state of the documentation I'm unable to work out what it is I'm meant to be doing. Is this something caused by vfsstream, or is phpunit mocking the thing I need to be looking at here?

推荐答案

那么...如何测试流? vfsStream所做的只是为文件系统操作提供一个自定义的流包装器.您并不需要成熟的vfsStream库来模拟单个流参数的行为-这不是正确的解决方案.相反,您需要编写和注册自己的一次性流包装器,因为您没有尝试模拟文件系统操作.

So ... how to test with streams? All vfsStream does is provide a custom stream wrapper for file system operations. You don't need the full-blown vfsStream library just to mock the behavior of a single stream argument -- it's not the correct solution. Instead, you need to write and register your own one-off stream wrapper because you aren't trying to mock file system operations.

假设您有以下简单的类要测试:

Say you have the following simple class to test:

class ClassThatNeedsStream {
    private $bodyStream;
    public function __construct($bodyStream) {
        $this->bodyStream = $bodyStream;
    }
    public function doSomethingWithStream() {
        return stream_get_contents($this->bodyStream);
    }
}

在现实生活中,您会这样做:

In real life you do:

$phpInput = fopen('php://input', 'r');
new ClassThatNeedsStream($phpInput);

因此,为了进行测试,我们创建了自己的流包装器,该包装器将使我们能够控制传入的流的行为.由于自定义流包装器是一个很大的话题,因此我不能赘述. 但是基本上,过程是这样的:

So to test it, we create our own stream wrapper that will allow us to control the behavior of the stream we pass in. I can't go into too much detail because custom stream wrappers are a large topic. But basically the process goes like this:

  1. 创建自定义流包装器
  2. 使用PHP注册该流包装器
  3. 使用注册的流包装器方案打开资源流

因此您的自定义流看起来像:

So your custom stream looks something like:

class TestingStreamStub {

    public $context;
    public static $position = 0;
    public static $body = '';

    public function stream_open($path, $mode, $options, &$opened_path) {
        return true;
    }

    public function stream_read($bytes) {
        $chunk = substr(static::$body, static::$position, $bytes);
        static::$position += strlen($chunk);
        return $chunk;
    }

    public function stream_write($data) {
        return strlen($data);
    }

    public function stream_eof() {
        return static::$position >= strlen(static::$body);
    }

    public function stream_tell() {
        return static::$position;
    }

    public function stream_close() {
        return null;
    }
}

然后在您的测试用例中,您将执行以下操作:

Then in your test case you would do this:

public function testSomething() {
    stream_wrapper_register('streamTest', 'TestingStreamStub');
    TestingStreamStub::$body = 'my custom stream contents';
    $stubStream = fopen('streamTest://whatever', 'r+');

    $myClass = new ClassThatNeedsStream($stubStream);
    $this->assertEquals(
        'my custom stream contents',
        $myClass->doSomethingWithStream()
    );

    stream_wrapper_unregister('streamTest');
}

然后,您可以简单地更改我在流包装器中定义的静态属性,以更改读取流后返回的数据.或者,扩展您的基本流包装器类并注册它,以提供不同的测试方案.

Then, you can simply change the static properties I've defined in the stream wrapper to change what data comes back from reading the stream. Or, extend your base stream wrapper class and register it instead to provide different scenarios for tests.

这是一个非常基本的介绍,但重点是:除非您要模拟实际的文件系统操作,否则不要使用vfsStream -这就是它的设计目的.否则,编写一个自定义的流包装器进行测试.

This is a very basic intro, but the point is this: don't use vfsStream unless you're mocking actual filesystem operations -- that's what it's designed for. Otherwise, write a custom stream wrapper for testing.

PHP提供了原型流包装器类来帮助您入门: http://www.php.net/manual/en/class.streamwrapper.php

PHP provides a prototype stream wrapper class to get you started: http://www.php.net/manual/en/class.streamwrapper.php

这篇关于尝试使用VFSStream测试文件系统操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆