3 namespace Tests\Uploads;
5 use BookStack\Entities\Models\Page;
6 use Illuminate\Http\UploadedFile;
11 * Get the path to a file in the test-data-directory.
13 protected function getTestImageFilePath(?string $fileName = null): string
15 if (is_null($fileName)) {
16 $fileName = 'test-image.png';
19 return base_path('tests/test-data/' . $fileName);
23 * Creates a new temporary image file using the given name,
24 * with the content decoded from the given bas64 file name.
25 * Is generally used for testing sketchy files that could trip AV.
27 protected function newTestImageFromBase64(string $base64FileName, $imageFileName): UploadedFile
29 $imagePath = implode(DIRECTORY_SEPARATOR, [sys_get_temp_dir(), $imageFileName]);
30 $base64FilePath = $this->getTestImageFilePath($base64FileName);
31 $data = file_get_contents($base64FilePath);
32 $decoded = base64_decode($data);
33 file_put_contents($imagePath, $decoded);
35 return new UploadedFile($imagePath, $imageFileName, 'image/png', null, true);
39 * Get a test image that can be uploaded.
41 protected function getTestImage(string $fileName, ?string $testDataFileName = null): UploadedFile
43 return new UploadedFile($this->getTestImageFilePath($testDataFileName), $fileName, 'image/png', null, true);
47 * Get the raw file data for the test image.
49 * @return false|string
51 protected function getTestImageContent()
53 return file_get_contents($this->getTestImageFilePath());
57 * Get the path for a test image.
59 protected function getTestImagePath(string $type, string $fileName): string
61 return '/uploads/images/' . $type . '/' . date('Y-m') . '/' . $fileName;
65 * Uploads an image with the given name.
68 * @param int $uploadedTo
69 * @param string $contentType
71 * @return \Illuminate\Foundation\Testing\TestResponse
73 protected function uploadImage($name, $uploadedTo = 0, $contentType = 'image/png', ?string $testDataFileName = null)
75 $file = $this->getTestImage($name, $testDataFileName);
77 return $this->withHeader('Content-Type', $contentType)
78 ->call('POST', '/images/gallery', ['uploaded_to' => $uploadedTo], [], ['file' => $file], []);
82 * Upload a new gallery image.
83 * Returns the image name.
84 * Can provide a page to relate the image to.
86 * @param Page|null $page
90 protected function uploadGalleryImage(Page $page = null, ?string $testDataFileName = null)
93 $page = Page::query()->first();
96 $imageName = $testDataFileName ?? 'first-image.png';
97 $relPath = $this->getTestImagePath('gallery', $imageName);
98 $this->deleteImage($relPath);
100 $upload = $this->uploadImage($imageName, $page->id, 'image/png', $testDataFileName);
101 $upload->assertStatus(200);
104 'name' => $imageName,
107 'response' => json_decode($upload->getContent()),
112 * Delete an uploaded image.
114 protected function deleteImage(string $relPath)
116 $path = public_path($relPath);
117 if (file_exists($path)) {