Completed
Push — develop ( 9cebec...7bce74 )
by Schlaefer
02:44
created

testAddFailureDoubleUpload()   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 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 Saito\Exception\SaitoForbiddenException;
22
use Saito\Test\IntegrationTestCase;
23
24
class UploadsControllerTest extends IntegrationTestCase
25
{
26
    public $fixtures = [
27
        'app.Category',
28
        'app.Entry',
29
        'app.Setting',
30
        'app.User',
31
        'app.UserBlock',
32
        'app.UserIgnore',
33
        'app.UserRead',
34
        'app.UserOnline',
35
        'plugin.ImageUploader.Uploads',
36
    ];
37
38
    /**
39
     * @var File dummy file
40
     */
41
    private $file;
42
43
    public function setUp()
44
    {
45
        parent::setUp();
46
47
        $this->file = new File(TMP . 'my new-upload.png');
48
        $this->mockMediaFile($this->file);
49
    }
50
51
    public function tearDown()
52
    {
53
        $this->file->delete();
54
        unset($this->file);
55
56
        parent::tearDown();
57
    }
58
59
    public function testAddNotAuthorized()
60
    {
61
        $this->expectException(UnauthorizedException::class);
62
63
        $this->post('api/v2/uploads', []);
64
    }
65
66
    /**
67
     * png is successfully uploaded and converted to jpeg
68
     */
69
    public function testAddSuccess()
70
    {
71
        $this->loginJwt(1);
72
73
        $this->upload($this->file);
74
        $response = json_decode((string)$this->_response->getBody(), true);
75
76
        $this->assertResponseCode(200);
77
78
        $this->assertWithinRange(
79
            time(),
80
            strtotime($response['data']['attributes']['created']),
81
            3
82
        );
83
        unset($response['data']['attributes']['created']);
84
85
        $this->assertGreaterThan(0, $response['data']['attributes']['size']);
86
        unset($response['data']['attributes']['size']);
87
88
        $expected = [
89
            'data' => [
90
                'id' => 3,
91
                'type' => 'uploads',
92
                'attributes' => [
93
                    'id' => 3,
94
                    'mime' => 'image/jpeg',
95
                    'name' => '1_ebd536d37aff03f2b570329b20ece832.jpg',
96
                    'thumbnail_url' => '/api/v2/uploads/thumb/3?h=e1fddb2ea8f448fac14ec06b88d4ce94',
97
                    'title' => 'my new-upload.png',
98
                    'url' => '/useruploads/1_ebd536d37aff03f2b570329b20ece832.jpg',
99
                ],
100
            ],
101
        ];
102
        $this->assertEquals($expected, $response);
103
104
        $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...
105
        $upload = $Uploads->get(3);
106
107
        $this->assertSame('1_ebd536d37aff03f2b570329b20ece832.jpg', $upload->get('name'));
108
        $this->assertSame('image/jpeg', $upload->get('type'));
109
        $this->assertTrue($upload->get('file')->exists());
110
    }
111
112
    public function testAddSvg()
113
    {
114
        $this->loginJwt(1);
115
116
        $this->file = new File(TMP . 'tmp_svg.svg');
117
        $this->file->write('<?xml version="1.0" encoding="UTF-8" ?>
118
            <svg width="9" height="9" style="background:red;"></svg>');
119
        $this->upload($this->file);
120
121
        $response = json_decode((string)$this->_response->getBody(), true);
122
123
        $this->assertResponseCode(200);
124
125
        $this->assertWithinRange(
126
            time(),
127
            strtotime($response['data']['attributes']['created']),
128
            3
129
        );
130
        unset($response['data']['attributes']['created']);
131
132
        $expected = [
133
            'data' => [
134
                'id' => 3,
135
                'type' => 'uploads',
136
                'attributes' => [
137
                    'id' => 3,
138
                    'mime' => 'image/svg+xml',
139
                    'name' => '1_853fe7aa4ef213b0c11f4b739cf444a8.svg',
140
                    'size' => 108,
141
                    'thumbnail_url' => '/api/v2/uploads/thumb/3?h=1d57b148ad44d4caf90fa1cd98729678',
142
                    'title' => 'tmp_svg.svg',
143
                    'url' => '/useruploads/1_853fe7aa4ef213b0c11f4b739cf444a8.svg',
144
                ],
145
            ],
146
        ];
147
        $this->assertEquals($expected, $response);
148
149
        $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...
150
        $upload = $Uploads->get(3);
151
152
        $this->assertSame('1_853fe7aa4ef213b0c11f4b739cf444a8.svg', $upload->get('name'));
153
        $this->assertSame('image/svg+xml', $upload->get('type'));
154
        $this->assertTrue($upload->get('file')->exists());
155
    }
156
157
    public function testRemoveExifData()
158
    {
159
        $this->loginJwt(1);
160
        unset($this->file);
161
        $this->file = new File(TMP . 'tmp_exif.jpg');
162
163
        $fixture = new File($path = Plugin::path('ImageUploader') . 'tests/Fixture/exif-with-location.jpg');
164
        $fixture->copy($this->file->path);
165
166
        $readExif = function (File $file) {
167
            //@codingStandardsIgnoreStart
168
            return @exif_read_data($file->path);
169
            //@codingStandardsIgnoreEnd
170
        };
171
        $exif = $readExif($this->file);
172
        $this->assertNotEmpty($exif['SectionsFound']);
173
        $this->assertContains('EXIF', $exif['SectionsFound']);
174
        $this->assertContains('IFD0', $exif['SectionsFound']);
175
176
        $this->upload($this->file);
177
178
        $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...
179
180
        $this->assertResponseCode(200);
181
182
        $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...
183
        $upload = $Uploads->find('all')->last();
184
185
        $exif = $readExif($upload->get('file'));
186
        $this->assertNotContains('EXIF', $exif['SectionsFound']);
187
        $this->assertNotContains('IFD0', $exif['SectionsFound']);
188
    }
189
190 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...
191
    {
192
        Configure::read('Saito.Settings.uploader')->setMaxNumberOfUploadsPerUser(1);
193
        $this->loginJwt(1);
194
195
        $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...
196
        $count = $Uploads->find()->count();
197
198
        $this->expectException(GenericApiException::class);
199
        $this->expectExceptionMessage('Error: Reached the maximal number of 1 uploads.');
200
201
        $this->upload($this->file);
202
203
        $this->assertEquals($count, $Uploads->find()->count());
204
    }
205
206 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...
207
    {
208
        Configure::read('Saito.Settings.uploader')
209
            ->setMaxNumberOfUploadsPerUser(10)
210
            ->addType('image/png', 10);
211
212
        $this->loginJwt(1);
213
214
        $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...
215
        $count = $Uploads->find()->count();
216
217
        $this->expectException(GenericApiException::class);
218
        $this->expectExceptionMessage('Error: File size exceeds allowed limit of 10 Bytes.');
219
220
        $this->upload($this->file);
221
222
        $this->assertEquals($count, $Uploads->find()->count());
223
    }
224
225
    public function testAddFailureDoubleUpload()
226
    {
227
        $this->loginJwt(1);
228
        // Make sure to test a file that may get transformed on upload (e.g. PNG
229
        // to JEPG).
230
        $file = new File(TMP . 'my new-upload.png');
231
        $this->mockMediaFile($file);
232
        $this->upload($this->file);
233
234
        $this->expectException(GenericApiException::class);
235
        $this->expectExceptionCode(400);
236
        $this->expectExceptionMessage('File with same name already uploaded');
237
238
        $this->loginJwt(1);
239
        $this->upload($this->file);
240
241
        $file->delete();
242
    }
243
244
    public function testIndexNoAuthorization()
245
    {
246
        $this->expectException(UnauthorizedException::class);
247
248
        $this->get('api/v2/uploads');
249
    }
250
251
    public function testIndexSuccess()
252
    {
253
        $this->loginJwt(3);
254
255
        $this->get('api/v2/uploads');
256
257
        $response = json_decode((string)$this->_response->getBody(), true);
258
259
        $this->assertResponseCode(200);
260
261
        $this->assertEquals(
262
            1526404380,
263
            strtotime($response['data'][0]['attributes']['created'])
264
        );
265
        unset($response['data'][0]['attributes']['created']);
266
267
        $expected = [
268
            'data' => [
269
                [
270
                    'id' => 2,
271
                    'type' => 'uploads',
272
                    'attributes' => [
273
                        'id' => 2,
274
                        'mime' => 'image/jpeg',
275
                        'name' => '3-another-upload.jpg',
276
                        'size' => 50000,
277
                        'thumbnail_url' => '/api/v2/uploads/thumb/2?h=be7ef71551c4245f82223d0c8e652eee',
278
                        'title' => '3-another-upload.jpg',
279
                        'url' => '/useruploads/3-another-upload.jpg',
280
                    ],
281
                ],
282
            ],
283
        ];
284
        $this->assertEquals($expected, $response);
285
    }
286
287
    public function testDeleteNoAuthorization()
288
    {
289
        $this->expectException(UnauthorizedException::class);
290
291
        $this->delete('api/v2/uploads/1');
292
    }
293
294
    public function testDeleteSuccess()
295
    {
296
        $this->loginJwt(1);
297
        $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...
298
        $upload = $Uploads->get(1);
299
        $this->assertNotEmpty($Uploads->get(1));
300
        $this->mockMediaFile($upload->get('file'));
301
302
        $this->delete('api/v2/uploads/1');
303
304
        $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...
305
306
        $this->assertResponseCode(204);
307
308
        $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...
309
    }
310
311
    public function testDeleteFailureUploadBelongsToDifferentUser()
312
    {
313
        $this->loginJwt(3);
314
315
        $this->expectException(SaitoForbiddenException::class);
316
317
        $this->delete('api/v2/uploads/1');
318
    }
319
320
    /**
321
     * Sends a file to upload api
322
     *
323
     * @param File $file The file to send
324
     */
325
    private function upload(File $file)
326
    {
327
        $data = [
328
            'upload' => [
329
                0 => [
330
                    'file' => [
331
                        'tmp_name' => $file->path,
332
                        'name' => $file->name() . '.' . $this->file->ext(),
333
                        'size' => $file->size(),
334
                        'type' => $file->mime(),
335
                    ]
336
                ]
337
            ]
338
        ];
339
        $this->post('api/v2/uploads.json', $data);
340
    }
341
}
342