laravel / ideas

Issues board used for Laravel internals discussions.
939 stars 28 forks source link

[Proposal] Create a fake file with specific content (from other file) #1751

Open daniel-werner opened 5 years ago

daniel-werner commented 5 years ago

I've recently had a use case to test the file upload with Laravel, and wanted to use UploadedFile::fake()->create('document.txt', $sizeInKilobytes); but in my case the content of the file was stored in the database, so it was necessary to make assertions that the specific content has been saved to the database. I've implemented it for my test, based on the generateImage method of the FileFactory:

protected function generateFromFile($fileName)
    {
        return new File(basename($fileName), tap(tmpfile(), function ($temp) use ($fileName) {
            ob_start();
            echo file_get_contents($fileName);
            fwrite($temp, ob_get_clean());
        }));
    }

I'd like to get your opinion on this, if it seems useful, I can create a pull request for it.

Best, Daniel

drbyte commented 5 years ago

Can the use of ob_xxxx functions be avoided? ie: file_get_contents returns the content as a string, so could be stuffed into a variable instead.

Or (granted, I've never tried the following) can you nest it as file_put_contents($temp, file_get_contents($fileName));

daniel-werner commented 5 years ago

@drbyte Good idea! file_put_contents might not work as it expects a file name as a first argument and $temp is a resource, but it could work simply like: fwrite($temp, file_get_contents($fileName))