laraveltestinglaravel-10laravel-facadelaravel-storage

Laravel Storage facade - fake retrieving files from disk during tests


My application needs to retrieve periodically files from an sftp filesystem via console command.

Writing unit tests for this command I need to fake this filesystem during the retrieval of those files, but looking at the File Storage testing documentation it is possible only to fake the upload of files.

How can I achieve this? I need to run test to check lots of the command expected behaviors (handling file missing, wrong content, size, etc), it is obviously not feasible doing it manually, I need to automate those tests.

Update #1

Since the comand do a Storage::disk('sftp-disk)->files('path); to retrieve files, I tried with Storage::shouldReceive('files')->>andReturn(['file.xlsx']); but I get the following error:

  Received Mockery_2_Illuminate_Filesystem_FilesystemManager::disk(), but no expectations were specified

Solution

  • Storage::fake() is not just for use with testing file uploads. The documentation was simply showing how well they work together to test file uploads.

    Storage::fake() is used to setup a directory on your local disk for your test suite to use. This helps keep you from modifying your actual defined storage disks.

    So, in your example, you have a sftp-disk disk defined that I assume is backed by an sftp connection. By calling Storage::fake('sftp-disk'), your test will swap out your sftp connection with a local filesystem disk, and now any work you do with your sftp-disk will now hit the local filesystem instead of reaching out to your sftp connection.

    The disk will be empty after you call Storage::fake(), so you'll need prepare it however you need based on the test you're trying to run. For example, if you need the file.xlsx file to exist, you'll need to create the file on your faked disk before you run the code that expects it to exist.

    public function test_when_file_is_missing() {
        Storage::fake('sftp-disk');
        
        // Run code under test that expects file.xlsx to exist
    
        // Make assertions on what should happen when expected file.xlsx is missing
    }
    
    public function test_when_file_exists() {
        Storage::fake('sftp-disk');
    
        // Create the expected file the faked sftp-disk.
        Storage::disk('sftp-disk')->put('file.xlsx', '');
        
        // Run code under test that expects file.xlsx to exist
    
        // Make assertions on what should happen when expected file.xlsx exists
    }