3 namespace Tests\Uploads;
5 use BookStack\Entities\Models\Page;
6 use Illuminate\Http\UploadedFile;
12 * Get the path to a file in the test-data-directory.
14 protected function getTestImageFilePath(?string $fileName = null): string
16 if (is_null($fileName)) {
17 $fileName = 'test-image.png';
20 return base_path('tests/test-data/' . $fileName);
24 * Creates a new temporary image file using the given name,
25 * with the content decoded from the given bas64 file name.
26 * Is generally used for testing sketchy files that could trip AV.
28 protected function newTestImageFromBase64(string $base64FileName, $imageFileName): UploadedFile
30 $imagePath = implode(DIRECTORY_SEPARATOR, [sys_get_temp_dir(), $imageFileName]);
31 $base64FilePath = $this->getTestImageFilePath($base64FileName);
32 $data = file_get_contents($base64FilePath);
33 $decoded = base64_decode($data);
34 file_put_contents($imagePath, $decoded);
36 return new UploadedFile($imagePath, $imageFileName, 'image/png', null, true);
40 * Get a test image that can be uploaded.
42 protected function getTestImage(string $fileName, ?string $testDataFileName = null): UploadedFile
44 return new UploadedFile($this->getTestImageFilePath($testDataFileName), $fileName, 'image/png', null, true);
48 * Get the raw file data for the test image.
50 * @return false|string
52 protected function getTestImageContent()
54 return file_get_contents($this->getTestImageFilePath());
58 * Get the path for a test image.
60 protected function getTestImagePath(string $type, string $fileName): string
62 return '/uploads/images/' . $type . '/' . date('Y-m') . '/' . $fileName;
66 * Uploads an image with the given name.
69 * @param int $uploadedTo
70 * @param string $contentType
72 * @return \Illuminate\Foundation\Testing\TestResponse
74 protected function uploadImage($name, $uploadedTo = 0, $contentType = 'image/png', ?string $testDataFileName = null)
76 $file = $this->getTestImage($name, $testDataFileName);
78 return $this->withHeader('Content-Type', $contentType)
79 ->call('POST', '/images/gallery', ['uploaded_to' => $uploadedTo], [], ['file' => $file], []);
83 * Upload a new gallery image.
84 * Returns the image name.
85 * Can provide a page to relate the image to.
87 * @param Page|null $page
89 * @return array{name: string, path: string, page: Page, response: stdClass}
91 protected function uploadGalleryImage(Page $page = null, ?string $testDataFileName = null)
94 $page = $this->entities->page();
97 $imageName = $testDataFileName ?? 'first-image.png';
98 $relPath = $this->getTestImagePath('gallery', $imageName);
99 $this->deleteImage($relPath);
101 $upload = $this->uploadImage($imageName, $page->id, 'image/png', $testDataFileName);
102 $upload->assertStatus(200);
105 'name' => $imageName,
108 'response' => json_decode($upload->getContent()),
113 * Delete an uploaded image.
115 protected function deleteImage(string $relPath)
117 $path = public_path($relPath);
118 if (file_exists($path)) {