Passed
Push — main ( 101f2d...06b8a6 )
by Emil
25:10
created

UploadManagerTest::testConstructorException()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 2
eloc 7
nc 2
nop 0
dl 0
loc 19
rs 10
c 1
b 1
f 0
1
<?php
2
3
namespace App\Tests;
4
5
use App\UploadManager;
6
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
7
use Symfony\Component\HttpFoundation\File\UploadedFile;
8
9
class UploadManagerTest extends WebTestCase
10
{
11
    private UploadManager $uploadManager;
12
    private string $testDir;
13
14
    /**
15
     * setUp
16
     *
17
     * Add client startup to setup
18
     *
19
     * @return void
20
     */
21
    protected function setUp(): void
22
    {
23
        parent::setUp(); // Call parent setup
24
25
        // Setup a temporary directory for testing
26
        $this->testDir = __DIR__ . '/_temp/upload_manager_test';
27
28
        $this->testDir = rtrim($this->testDir, '/');
29
30
        if (!is_dir($this->testDir)) {
31
            mkdir($this->testDir, 0777, true);
32
        }
33
34
        // Instantiate UploadManager with test directory
35
        $this->uploadManager = new UploadManager($this->testDir);
36
    }
37
38
    /**
39
     * tearDown
40
     *
41
     * @return void
42
     */
43
    protected function tearDown(): void
44
    {
45
        $this->deleteDirectory($this->testDir);
46
47
        parent::tearDown();
48
    }
49
50
    /**
51
     * deleteDirectory
52
     *
53
     * Recursively delete a directory and its contents
54
     *
55
     * @param  string $dir
56
     * @return void
57
     */
58
    private function deleteDirectory(string $dir): void
59
    {
60
        if (!is_dir($dir)) {
61
            return;
62
        }
63
64
        $files = array_diff(scandir($dir), ['.', '..']);
65
66
        foreach ($files as $file) {
67
            $filePath = $dir . DIRECTORY_SEPARATOR . $file;
68
            (is_dir($filePath)) ? $this->deleteDirectory($filePath) : unlink($filePath);
69
        }
70
71
        rmdir($dir);
72
    }
73
74
    /**
75
     * testCreateObject
76
     *
77
     * Construct object and verify that the object has the expected
78
     * properties, use no arguments.
79
     *
80
     * @return void
81
     */
82
    public function testCreateObject(): void
83
    {
84
        $uploadManager = new UploadManager($this->testDir);
85
        $this->assertInstanceOf(UploadManager::class, $uploadManager);
86
    }
87
88
    /**
89
     * testGetters
90
     *
91
     * @return void
92
     */
93
    public function testGetters(): void
94
    {
95
        $uploadManager = new UploadManager($this->testDir);
96
97
        $targetPath = $uploadManager->getTargetPath();
98
        $this->assertEquals($this->testDir, $targetPath);
99
100
        $targetDirectory = $uploadManager->getTargetDirectory();
101
        $this->assertEquals('uploads', $targetDirectory);
102
103
        $targetDirectoryPath = $uploadManager->getTargetDirectoryPath();
104
        $this->assertEquals($this->testDir.'uploads', $targetDirectoryPath);
105
    }
106
107
    /**
108
     * testSaveUploadedFile
109
     *
110
     * @return void
111
     */
112
    public function testSaveUploadedFile(): void
113
    {
114
        // Create a mock UploadedFile
115
        $file = $this->createMock(UploadedFile::class);
116
        $file->method('isValid')->willReturn(true);
117
        $file->method('getMimeType')->willReturn('image/jpeg');
118
        $file->method('getClientOriginalName')->willReturn('test_image.jpg');
119
        $file->method('guessExtension')->willReturn('jpg');
120
121
        // Mock move method
122
        $file->expects($this->once())
123
            ->method('move')
124
            ->with(
125
                $this->equalTo($this->uploadManager->getTargetDirectoryPath()),
126
                $this->callback(function ($filename) {
127
                    return preg_match('/^test_image-.*\.jpg$/', $filename) === 1;
128
                })
129
            );
130
131
        $fileTypesSupported = ['image/jpeg', 'image/png'];
132
133
        $result = $this->uploadManager->saveUploadedFile($file, $fileTypesSupported);
134
135
        $this->assertNotNull($result);
136
        $this->assertStringContainsString('/uploads/', /** @scrutinizer ignore-type */ $result);
137
    }
138
139
    /**
140
     * testSaveUploadedFileInvalidFileType
141
     *
142
     * @return void
143
     */
144
    public function testSaveUploadedFileInvalidFileType(): void
145
    {
146
        // Create a mock UploadedFile
147
        $file = $this->createMock(UploadedFile::class);
148
        $file->method('isValid')->willReturn(true);
149
        $file->method('getMimeType')->willReturn('image/jpeg');
150
        $file->method('getClientOriginalName')->willReturn('test.jpg');
151
        $file->method('guessExtension')->willReturn('jpg');
152
153
        $fileTypesSupported = ['image/png'];
154
155
        // Expect a RuntimeException for invalid file type
156
        $this->expectException(\RuntimeException::class);
157
        $this->expectExceptionMessage('Invalid file type. Filetype of image/jpeg is not allowed.');
158
159
        // Call the method - should throw exception
160
        $this->uploadManager->saveUploadedFile($file, $fileTypesSupported);
161
    }
162
163
    /**
164
     * testSaveUploadedFileMoveException
165
     *
166
     * @return void
167
     */
168
    public function testSaveUploadedFileMoveException(): void
169
    {
170
        // Create a mock UploadedFile
171
        $file = $this->createMock(UploadedFile::class);
172
        $file->method('isValid')->willReturn(true);
173
        $file->method('getMimeType')->willReturn('image/jpeg');
174
        $file->method('getClientOriginalName')->willReturn('test.jpg');
175
        $file->method('guessExtension')->willReturn('jpg');
176
177
        // Simulate exception during move
178
        $file->expects($this->once())
179
             ->method('move')
180
             ->will($this->throwException(new \Exception('Move failed')));
181
182
        $fileTypesSupported = ['image/jpeg'];
183
184
        // Expect a RuntimeException with specific message
185
        $this->expectException(\RuntimeException::class);
186
        $this->expectExceptionMessage('Error uploading file: Move failed');
187
188
        $this->uploadManager->saveUploadedFile($file, $fileTypesSupported);
189
    }
190
191
    /**
192
     * testDeleteUploadedFile
193
     *
194
     * @return void
195
     */
196
    public function testDeleteUploadedFile(): void
197
    {
198
        // Create a dummy file
199
        $filePath = '/uploads/testfile.txt';
200
        $fullPath = $this->testDir . $filePath;
201
        if (!is_dir(dirname($fullPath))) {
202
            mkdir(dirname($fullPath), 0777, true);
203
        }
204
        file_put_contents($fullPath, 'test');
205
206
        $result = $this->uploadManager->deleteUploadedFile($filePath);
207
208
        $this->assertTrue($result);
209
        $this->assertFalse(file_exists($fullPath));
210
211
        // Test if the file don't exists
212
        $result = $this->uploadManager->deleteUploadedFile($filePath);
213
214
        $this->assertFalse($result);
215
    }
216
}
217