Introduction
This is the first post of the new “Under the hood” series where I’ll try to explain how things work behind the scenes. I am going to pick topics from my day to day work from various areas like Laravel, JavaScript, Vue.js etc.
Testing file upload
It is quite common that a web application has file upload, so we want to cover this functionality with tests. Laravel offers a method to create a fake upload file using the following method: UploadedFile::fake()->image(‘avatar.jpg’); For more information about how to test file upload please check the Laravel documentation here.
Let’s see how the UploadedFile::fake() works. The fake method simply creates and returns a new instance of the Testing\FileFactory class:
public static function fake()
{
return new Testing\FileFactory;
}
The FileFactory
The FileFactory has two public methods, we can create a generic file with a given name and file size, or we can create an image with specific width and height.
Create
This method creates a temporary file with the php’s built in tmpfile() function. This resource is used to instantiate a new Testing\File, set the name of the file and the desired file size.
public function create($name, $kilobytes = 0)
{
return tap(new File($name, tmpfile()), function ($file) use ($kilobytes) {
$file->sizeToReport = $kilobytes * 1024;
});
}
This newly created File is going to be used when you make a post request from the test case, like this:
$response = $this->json('POST', '/avatar', ['avatar' => $file,]);
Image
The basic principle of the image method is similar to the create, but it actually creates a black image with the given dimensions:
public function image($name, $width = 10, $height = 10)
{
return new File($name, $this->generateImage(
$width, $height, Str::endsWith(Str::lower($name), ['.jpg', '.jpeg']) ? 'jpeg' : 'png'
));
}
The image is being generated in the generateImage method. As of the time of writing the image generation support png and jpeg images. It also creates a temporary file, generates the image according to the $type argument and writes the content to the temporary file.
protected function generateImage($width, $height, $type)
{
return tap(tmpfile(), function ($temp) use ($width, $height, $type) {
ob_start();
$image = imagecreatetruecolor($width, $height);
switch ($type) {
case 'jpeg':
imagejpeg($image);
break;
case 'png':
imagepng($image);
break;
}
fwrite($temp, ob_get_clean());
});
}
Using the fake uploaded file makes it is easy to test the file and image uploads. I hope this article was useful to understand how it works.
The post Under the hood: How fake uploaded files work in Laravel appeared first on 42 Coders.
Top comments (0)