Completed
Push — develop ( 15b1f0...3fa33d )
by Schlaefer
02:30
created

UploadsControllerTest::testAddMimeTypeConversion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Saito - The Threaded Web Forum
7
 *
8
 * @copyright Copyright (c) the Saito Project Developers
9
 * @link https://github.com/Schlaefer/Saito
10
 * @license http://opensource.org/licenses/MIT
11
 */
12
13
namespace ImageUploader\Test\TestCase\Controller;
14
15
use Api\Error\Exception\GenericApiException;
16
use Authentication\Authenticator\UnauthenticatedException;
17
use Cake\Core\Configure;
18
use Cake\Core\Plugin;
19
use Cake\Filesystem\File;
20
use Cake\ORM\TableRegistry;
21
use ImageUploader\Model\Table\UploadsTable;
22
use Saito\Exception\SaitoForbiddenException;
23
use Saito\Test\IntegrationTestCase;
24
25
class UploadsControllerTest extends IntegrationTestCase
26
{
27
    public $fixtures = [
28
        'app.Category',
29
        'app.Entry',
30
        'app.Setting',
31
        'app.User',
32
        'app.UserBlock',
33
        'app.UserIgnore',
34
        'app.UserRead',
35
        'app.UserOnline',
36
        'plugin.ImageUploader.Uploads',
37
    ];
38
39
    /**
40
     * @var File dummy file
41
     */
42
    private $file;
43
44
    public function setUp()
45
    {
46
        parent::setUp();
47
48
        $this->file = new File(TMP . 'my new-upload.png');
49
        $this->mockMediaFile($this->file);
50
    }
51
52
    public function tearDown()
53
    {
54
        $this->file->delete();
55
        unset($this->file);
56
57
        parent::tearDown();
58
    }
59
60
    public function testAddNotAuthorized()
61
    {
62
        $this->expectException(UnauthenticatedException::class);
63
64
        $this->post('api/v2/uploads', []);
65
    }
66
67
    /**
68
     * png is successfully uploaded and converted to jpeg
69
     */
70
    public function testAddSuccess()
71
    {
72
        $this->loginJwt(1);
73
74
        $this->upload($this->file);
75
        $response = json_decode((string)$this->_response->getBody(), true);
76
77
        $this->assertResponseCode(200);
78
79
        $this->assertWithinRange(
80
            time(),
81
            strtotime($response['data']['attributes']['created']),
82
            3
83
        );
84
        unset($response['data']['attributes']['created']);
85
86
        $this->assertGreaterThan(0, $response['data']['attributes']['size']);
87
        unset($response['data']['attributes']['size']);
88
89
        $expected = [
90
            'data' => [
91
                'id' => 3,
92
                'type' => 'uploads',
93
                'attributes' => [
94
                    'id' => 3,
95
                    'mime' => 'image/jpeg',
96
                    'name' => '1_ebd536d37aff03f2b570329b20ece832.jpg',
97
                    'thumbnail_url' => '/api/v2/uploads/thumb/3?h=e1fddb2ea8f448fac14ec06b88d4ce94',
98
                    'title' => 'my new-upload.png',
99
                    'url' => '/useruploads/1_ebd536d37aff03f2b570329b20ece832.jpg',
100
                ],
101
            ],
102
        ];
103
        $this->assertEquals($expected, $response);
104
105
        $Uploads = TableRegistry::get('ImageUploader.Uploads');
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\TableRegistry::get() has been deprecated with message: 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
106
        $upload = $Uploads->get(3);
107
108
        $this->assertSame('1_ebd536d37aff03f2b570329b20ece832.jpg', $upload->get('name'));
109
        $this->assertSame('image/jpeg', $upload->get('type'));
110
        $this->assertTrue($upload->get('file')->exists());
111
    }
112
113
    public function testAddSvg()
114
    {
115
        $this->loginJwt(1);
116
117
        $this->file = new File(TMP . 'tmp_svg.svg');
118
        $this->file->write('<?xml version="1.0" encoding="UTF-8" ?>
119
            <svg width="9" height="9" style="background:red;"></svg>');
120
        $this->upload($this->file);
121
122
        $response = json_decode((string)$this->_response->getBody(), true);
123
124
        $this->assertResponseCode(200);
125
126
        $this->assertWithinRange(
127
            time(),
128
            strtotime($response['data']['attributes']['created']),
129
            3
130
        );
131
        unset($response['data']['attributes']['created']);
132
133
        $expected = [
134
            'data' => [
135
                'id' => 3,
136
                'type' => 'uploads',
137
                'attributes' => [
138
                    'id' => 3,
139
                    'mime' => 'image/svg+xml',
140
                    'name' => '1_853fe7aa4ef213b0c11f4b739cf444a8.svg',
141
                    'size' => 108,
142
                    'thumbnail_url' => '/api/v2/uploads/thumb/3?h=1d57b148ad44d4caf90fa1cd98729678',
143
                    'title' => 'tmp_svg.svg',
144
                    'url' => '/useruploads/1_853fe7aa4ef213b0c11f4b739cf444a8.svg',
145
                ],
146
            ],
147
        ];
148
        $this->assertEquals($expected, $response);
149
150
        $Uploads = TableRegistry::get('ImageUploader.Uploads');
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\TableRegistry::get() has been deprecated with message: 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
151
        $upload = $Uploads->get(3);
152
153
        $this->assertSame('1_853fe7aa4ef213b0c11f4b739cf444a8.svg', $upload->get('name'));
154
        $this->assertSame('image/svg+xml', $upload->get('type'));
155
        $this->assertTrue($upload->get('file')->exists());
156
    }
157
158
    public function testAddMimeTypeConversion()
159
    {
160
        $this->loginJwt(1);
161
162
        $this->file = new File(TMP . 'test.mp4');
163
        $fixture = new File(Plugin::path('ImageUploader') . 'tests/Fixture/test-application-octo.mp4');
164
        $fixture->copy($this->file->path);
165
        $this->assertEquals('application/octet-stream', $this->file->mime());
166
167
        $this->upload($this->file);
168
169
        $this->assertResponseOk();
170
171
        $Uploads = TableRegistry::get('ImageUploader.Uploads');
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\TableRegistry::get() has been deprecated with message: 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
172
        $upload = $Uploads->get(3);
173
        $this->assertSame('test.mp4', $upload->get('title'));
174
        $this->assertSame('video/mp4', $upload->get('type'));
175
    }
176
177
    public function testRemoveExifData()
178
    {
179
        $this->loginJwt(1);
180
        unset($this->file);
181
        $this->file = new File(TMP . 'tmp_exif.jpg');
182
183
        $fixture = new File($path = Plugin::path('ImageUploader') . 'tests/Fixture/exif-with-location.jpg');
184
        $fixture->copy($this->file->path);
185
186
        $readExif = function (File $file) {
187
            //@codingStandardsIgnoreStart
188
            return @exif_read_data($file->path);
189
            //@codingStandardsIgnoreEnd
190
        };
191
        $exif = $readExif($this->file);
192
        $this->assertNotEmpty($exif['SectionsFound']);
193
        $this->assertContains('EXIF', $exif['SectionsFound']);
194
        $this->assertContains('IFD0', $exif['SectionsFound']);
195
196
        $this->upload($this->file);
197
198
        $response = json_decode((string)$this->_response->getBody(), true);
0 ignored issues
show
Unused Code introduced by
$response is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
199
200
        $this->assertResponseCode(200);
201
202
        $Uploads = TableRegistry::get('ImageUploader.Uploads');
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\TableRegistry::get() has been deprecated with message: 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
203
        $upload = $Uploads->find('all')->last();
204
205
        $exif = $readExif($upload->get('file'));
206
        $this->assertNotContains('EXIF', $exif['SectionsFound']);
207
        $this->assertNotContains('IFD0', $exif['SectionsFound']);
208
    }
209
210 View Code Duplication
    public function testAddFailureMaxUploadsPerUser()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
211
    {
212
        Configure::read('Saito.Settings.uploader')->setMaxNumberOfUploadsPerUser(1);
213
        $this->loginJwt(1);
214
215
        $Uploads = TableRegistry::get('ImageUploader.Uploads');
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\TableRegistry::get() has been deprecated with message: 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
216
        $count = $Uploads->find()->count();
217
218
        $this->expectException(GenericApiException::class);
219
        $this->expectExceptionMessage('Error: Reached the maximal number of 1 uploads.');
220
221
        $this->upload($this->file);
222
223
        $this->assertEquals($count, $Uploads->find()->count());
224
    }
225
226 View Code Duplication
    public function testAddFailureMaxDocumentSize()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
227
    {
228
        Configure::read('Saito.Settings.uploader')
229
            ->setMaxNumberOfUploadsPerUser(10)
230
            ->addType('image/png', 10);
231
232
        $this->loginJwt(1);
233
234
        $Uploads = TableRegistry::get('ImageUploader.Uploads');
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\TableRegistry::get() has been deprecated with message: 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
235
        $count = $Uploads->find()->count();
236
237
        $this->expectException(GenericApiException::class);
238
        $this->expectExceptionMessage('Error: File size exceeds allowed limit of 10 Bytes.');
239
240
        $this->upload($this->file);
241
242
        $this->assertEquals($count, $Uploads->find()->count());
243
    }
244
245
    public function testAddFailureDoubleUpload()
246
    {
247
        $this->loginJwt(1);
248
        // Make sure to test a file that may get transformed on upload (e.g. PNG
249
        // to JEPG).
250
        $file = new File(TMP . 'my new-upload.png');
251
        $this->mockMediaFile($file);
252
        $this->upload($file);
253
254
        $this->expectException(GenericApiException::class);
255
        $this->expectExceptionCode(400);
256
        $this->expectExceptionMessage('File with same name already uploaded');
257
258
        $this->loginJwt(1);
259
        $this->upload($file);
260
261
        $file->delete();
262
    }
263
264
    public function testAddFailureFilenameToLong()
265
    {
266
        $this->loginJwt(1);
267
        $max = UploadsTable::FILENAME_MAXLENGTH;
268
        $file = new File(TMP . str_pad('', $max + 1, '0') . '.png');
269
        $this->mockMediaFile($file);
270
271
        $this->expectException(GenericApiException::class);
272
        $this->expectExceptionCode(400);
273
        $this->expectExceptionMessage((string)$max);
274
        $this->upload($file);
275
276
        $file->delete();
277
    }
278
279
    public function testIndexNoAuthorization()
280
    {
281
        $this->expectException(UnauthenticatedException::class);
282
283
        $this->get('api/v2/uploads');
284
    }
285
286
    public function testIndexSuccess()
287
    {
288
        $this->loginJwt(3);
289
290
        $this->get('api/v2/uploads');
291
292
        $response = json_decode((string)$this->_response->getBody(), true);
293
294
        $this->assertResponseCode(200);
295
296
        $this->assertEquals(
297
            1526404380,
298
            strtotime($response['data'][0]['attributes']['created'])
299
        );
300
        unset($response['data'][0]['attributes']['created']);
301
302
        $expected = [
303
            'data' => [
304
                [
305
                    'id' => 2,
306
                    'type' => 'uploads',
307
                    'attributes' => [
308
                        'id' => 2,
309
                        'mime' => 'image/jpeg',
310
                        'name' => '3-another-upload.jpg',
311
                        'size' => 50000,
312
                        'thumbnail_url' => '/api/v2/uploads/thumb/2?h=be7ef71551c4245f82223d0c8e652eee',
313
                        'title' => '3-another-upload.jpg',
314
                        'url' => '/useruploads/3-another-upload.jpg',
315
                    ],
316
                ],
317
            ],
318
        ];
319
        $this->assertEquals($expected, $response);
320
    }
321
322
    public function testDeleteNoAuthorization()
323
    {
324
        $this->expectException(UnauthenticatedException::class);
325
326
        $this->delete('api/v2/uploads/1');
327
    }
328
329
    public function testDeleteSuccess()
330
    {
331
        $this->loginJwt(1);
332
        $Uploads = TableRegistry::get('ImageUploader.Uploads');
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\TableRegistry::get() has been deprecated with message: 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
333
        $upload = $Uploads->get(1);
334
        $this->assertNotEmpty($Uploads->get(1));
335
        $this->mockMediaFile($upload->get('file'));
336
337
        $this->delete('api/v2/uploads/1');
338
339
        $response = json_decode((string)$this->_response->getBody(), true);
0 ignored issues
show
Unused Code introduced by
$response is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
340
341
        $this->assertResponseCode(204);
342
343
        $this->assertFalse($Uploads->exists(1));
0 ignored issues
show
Documentation introduced by
1 is of type integer, but the function expects a array|object<ArrayAccess>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
344
    }
345
346
    public function testDeleteFailureUploadBelongsToDifferentUser()
347
    {
348
        $this->loginJwt(3);
349
350
        $this->expectException(SaitoForbiddenException::class);
351
352
        $this->delete('api/v2/uploads/1');
353
    }
354
355
    /**
356
     * Sends a file to upload api
357
     *
358
     * @param File $file The file to send
359
     */
360
    private function upload(File $file)
361
    {
362
        $data = [
363
            'upload' => [
364
                0 => [
365
                    'file' => [
366
                        'tmp_name' => $file->path,
367
                        'name' => $file->name() . '.' . $file->ext(),
368
                        'size' => $file->size(),
369
                        'type' => $file->mime(),
370
                    ]
371
                ]
372
            ]
373
        ];
374
        $this->post('api/v2/uploads.json', $data);
375
    }
376
}
377