Easiest way to simulate no free disk space situation?

后端 未结 13 746
执笔经年
执笔经年 2021-02-03 20:11

I need to test my web app in a scenario where there’s no disk space remaining, i.e. I cannot write any more files. But I don’t want to fill my hard drive with junk just to make

13条回答
  •  迷失自我
    2021-02-03 20:50

    No need to use a prefilled dummy filesystem.
    Use disk_free_space() to mock the FileSystem

    disk_free_space() - Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.

    To simulate, just wrap the function into a FileSystem Class. Then inject it to your class doing the saving as a dependency and check if the drive is full before you do the actual saving. In your UnitTest, just swap out the regular class with the class mocking a full file system and you're done. This way you don't have to recreate the full disk drive or keep the drive with your project files all the time whenever you want to rerun your test, e.g.

    class MyFileSystem
    {
        public static function df($drive)
        {
            return disk_free_space($drive);
        }
    }
    

    and to simulate a full FileSystem do

    class MyFileSystemFull
    {
        public static function df($drive)
        {
            return 0;
        }
    }
    

    If you want to overload the function to return 0 at all times, you could use the RunKit Pecl extension and do:

    runkit_function_redefine('disk_free_space','string','return 0;');
    

    As an alternative look into vfsStream:

    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.

提交回复
热议问题