Completed
Push — develop ( 2974ab...dcee28 )
by Schlaefer
02:44
created

testAddFailureFilenameToLong()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 14
rs 9.7998
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 Cake\Core\Configure;
17
use Cake\Core\Plugin;
18
use Cake\Filesystem\File;
19
use Cake\Http\Exception\UnauthorizedException;
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(UnauthorizedException::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 testRemoveExifData()
159
    {
160
        $this->loginJwt(1);
161
        unset($this->file);
162
        $this->file = new File(TMP . 'tmp_exif.jpg');
163
164
        $fixture = new File($path = Plugin::path('ImageUploader') . 'tests/Fixture/exif-with-location.jpg');
165
        $fixture->copy($this->file->path);
166
167
        $readExif = function (File $file) {
168
            //@codingStandardsIgnoreStart
169
            return @exif_read_data($file->path);
170
            //@codingStandardsIgnoreEnd
171
        };
172
        $exif = $readExif($this->file);
173
        $this->assertNotEmpty($exif['SectionsFound']);
174
        $this->assertContains('EXIF', $exif['SectionsFound']);
175
        $this->assertContains('IFD0', $exif['SectionsFound']);
176
177
        $this->upload($this->file);
178
179
        $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...
180
181
        $this->assertResponseCode(200);
182
183
        $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...
184
        $upload = $Uploads->find('all')->last();
185
186
        $exif = $readExif($upload->get('file'));
187
        $this->assertNotContains('EXIF', $exif['SectionsFound']);
188
        $this->assertNotContains('IFD0', $exif['SectionsFound']);
189
    }
190
191 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...
192
    {
193
        Configure::read('Saito.Settings.uploader')->setMaxNumberOfUploadsPerUser(1);
194
        $this->loginJwt(1);
195
196
        $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...
197
        $count = $Uploads->find()->count();
198
199
        $this->expectException(GenericApiException::class);
200
        $this->expectExceptionMessage('Error: Reached the maximal number of 1 uploads.');
201
202
        $this->upload($this->file);
203
204
        $this->assertEquals($count, $Uploads->find()->count());
205
    }
206
207 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...
208
    {
209
        Configure::read('Saito.Settings.uploader')
210
            ->setMaxNumberOfUploadsPerUser(10)
211
            ->addType('image/png', 10);
212
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: File size exceeds allowed limit of 10 Bytes.');
220
221
        $this->upload($this->file);
222
223
        $this->assertEquals($count, $Uploads->find()->count());
224
    }
225
226
    public function testAddFailureDoubleUpload()
227
    {
228
        $this->loginJwt(1);
229
        // Make sure to test a file that may get transformed on upload (e.g. PNG
230
        // to JEPG).
231
        $file = new File(TMP . 'my new-upload.png');
232
        $this->mockMediaFile($file);
233
        $this->upload($file);
234
235
        $this->expectException(GenericApiException::class);
236
        $this->expectExceptionCode(400);
237
        $this->expectExceptionMessage('File with same name already uploaded');
238
239
        $this->loginJwt(1);
240
        $this->upload($file);
241
242
        $file->delete();
243
    }
244
245
    public function testAddFailureFilenameToLong()
246
    {
247
        $this->loginJwt(1);
248
        $max = UploadsTable::FILENAME_MAXLENGTH;
249
        $file = new File(TMP . str_pad('', $max + 1, '0') . '.png');
250
        $this->mockMediaFile($file);
251
252
        $this->expectException(GenericApiException::class);
253
        $this->expectExceptionCode(400);
254
        $this->expectExceptionMessage((string)$max);
255
        $this->upload($file);
256
257
        $file->delete();
258
    }
259
260
    public function testIndexNoAuthorization()
261
    {
262
        $this->expectException(UnauthorizedException::class);
263
264
        $this->get('api/v2/uploads');
265
    }
266
267
    public function testIndexSuccess()
268
    {
269
        $this->loginJwt(3);
270
271
        $this->get('api/v2/uploads');
272
273
        $response = json_decode((string)$this->_response->getBody(), true);
274
275
        $this->assertResponseCode(200);
276
277
        $this->assertEquals(
278
            1526404380,
279
            strtotime($response['data'][0]['attributes']['created'])
280
        );
281
        unset($response['data'][0]['attributes']['created']);
282
283
        $expected = [
284
            'data' => [
285
                [
286
                    'id' => 2,
287
                    'type' => 'uploads',
288
                    'attributes' => [
289
                        'id' => 2,
290
                        'mime' => 'image/jpeg',
291
                        'name' => '3-another-upload.jpg',
292
                        'size' => 50000,
293
                        'thumbnail_url' => '/api/v2/uploads/thumb/2?h=be7ef71551c4245f82223d0c8e652eee',
294
                        'title' => '3-another-upload.jpg',
295
                        'url' => '/useruploads/3-another-upload.jpg',
296
                    ],
297
                ],
298
            ],
299
        ];
300
        $this->assertEquals($expected, $response);
301
    }
302
303
    public function testDeleteNoAuthorization()
304
    {
305
        $this->expectException(UnauthorizedException::class);
306
307
        $this->delete('api/v2/uploads/1');
308
    }
309
310
    public function testDeleteSuccess()
311
    {
312
        $this->loginJwt(1);
313
        $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...
314
        $upload = $Uploads->get(1);
315
        $this->assertNotEmpty($Uploads->get(1));
316
        $this->mockMediaFile($upload->get('file'));
317
318
        $this->delete('api/v2/uploads/1');
319
320
        $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...
321
322
        $this->assertResponseCode(204);
323
324
        $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...
325
    }
326
327
    public function testDeleteFailureUploadBelongsToDifferentUser()
328
    {
329
        $this->loginJwt(3);
330
331
        $this->expectException(SaitoForbiddenException::class);
332
333
        $this->delete('api/v2/uploads/1');
334
    }
335
336
    /**
337
     * Sends a file to upload api
338
     *
339
     * @param File $file The file to send
340
     */
341
    private function upload(File $file)
342
    {
343
        $data = [
344
            'upload' => [
345
                0 => [
346
                    'file' => [
347
                        'tmp_name' => $file->path,
348
                        'name' => $file->name() . '.' . $this->file->ext(),
349
                        'size' => $file->size(),
350
                        'type' => $file->mime(),
351
                    ]
352
                ]
353
            ]
354
        ];
355
        $this->post('api/v2/uploads.json', $data);
356
    }
357
}
358