Completed
Pull Request — master (#289)
by Ingo
02:07
created

AssetAdminTest::tearDown()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 1
eloc 5
nc 1
nop 0
1
<?php
2
3
namespace SilverStripe\AssetAdmin\Tests\Controller;
4
5
use SilverStripe\AssetAdmin\Tests\Controller\AssetAdminTest\FileExtension;
6
use SilverStripe\AssetAdmin\Tests\Controller\AssetAdminTest\FolderExtension;
7
use SilverStripe\Assets\File;
8
use SilverStripe\Assets\Folder;
9
use SilverStripe\Assets\Tests\Storage\AssetStoreTest\TestAssetStore;
10
use SilverStripe\Control\Director;
11
use SilverStripe\Control\Session;
12
use SilverStripe\Dev\FunctionalTest;
13
use SilverStripe\ORM\Versioning\Versioned;
14
use SilverStripe\Security\SecurityToken;
15
16
/**
17
 * Tests {@see AssetAdmin}
18
 */
19
class AssetAdminTest extends FunctionalTest
20
{
21
22
    protected static $fixture_file = 'AssetAdminTest.yml';
23
24
    /**
25
     * @var Session
26
     */
27
    protected $session = null;
28
29
    public function setUp()
30
    {
31
        parent::setUp();
32
33
        TestAssetStore::activate('AssetAdminTest');
34
        $memberID = $this->logInWithPermission('ADMIN');
35
        $this->session = Session::create(array('loggedInAs' => $memberID));
36
37
        File::add_extension(FileExtension::class);
38
        Folder::add_extension(FolderExtension::class);
39
40
        // Create a test folders for each of the fixture references
41
        foreach (File::get()->filter('ClassName', Folder::class) as $folder) {
42
            /** @var Folder $folder */
43
            $folder->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
44
        }
45
46
        // Create a test files for each of the fixture references
47
        $content = str_repeat('x', 1000000);
48
        foreach (File::get()->exclude('ClassName', Folder::class) as $file) {
49
            /** @var File $file */
50
            $file->setFromString($content, $file->generateFilename());
51
            $file->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
52
        }
53
54
        // Override FunctionalTest defaults
55
        SecurityToken::enable();
56
        $this->session->inst_set('SecurityID', SecurityToken::inst()->getValue());
57
    }
58
59
    public function tearDown()
60
    {
61
        File::remove_extension(FileExtension::class);
62
        Folder::remove_extension(FolderExtension::class);
63
64
        TestAssetStore::reset();
65
        parent::tearDown();
66
    }
67
68
69
    public function testApiHistory()
70
    {
71
        $file = $this->objFromFixture(File::class, 'file1');
72
        $response = Director::test(
73
            'admin/assets/api/history?fileId='. $file->ID,
74
            null,
75
            $this->session,
76
            'GET'
77
        );
78
79
        $this->assertFalse($response->isError());
80
81
        $body = json_decode($response->getBody(), true);
82
83
        $this->assertArrayHasKey('summary', $body[0]);
84
        $this->assertArrayHasKey('versionid', $body[0]);
85
        $this->assertArrayHasKey('summary', $body[0]);
86
87
        // test permission filtering and
88
    }
89
90
91
    public function testItCreatesFolder()
92
    {
93
        $folder1 = $this->objFromFixture(Folder::class, 'folder1');
94
95
        $response = Director::test(
96
            'admin/assets/api/createFolder',
97
            [
98
                'ParentID' => $folder1->ID,
99
                'Name' => 'testItCreatesFolder',
100
                'SecurityID' => SecurityToken::inst()->getValue(),
101
            ],
102
            $this->session,
103
            'POST'
104
        );
105
        $this->assertFalse($response->isError());
106
        $responseData = json_decode($response->getBody(), true);
107
        $newFolder = Folder::get()->byID($responseData['id']);
108
        $this->assertNotNull($newFolder);
109
        $this->assertEquals($folder1->ID, $newFolder->ParentID);
110
        $this->assertEquals('testItCreatesFolder', $newFolder->Name);
111
    }
112
113 View Code Duplication
    public function testItRestrictsCreateFolderByCanCreate()
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...
114
    {
115
        $folder = $this->objFromFixture(Folder::class, 'folder1');
116
117
        $response = Director::test(
118
            'admin/assets/api/createFolder',
119
            [
120
                'ParentID' => $folder->ID,
121
                'Name' => 'disallowCanCreate',
122
                'SecurityID' => SecurityToken::inst()->getValue(),
123
            ],
124
            $this->session,
125
            'POST'
126
        );
127
        $this->assertTrue($response->isError());
128
        $this->assertEquals(403, $response->getStatusCode());
129
    }
130
131 View Code Duplication
    public function testItRestrictsCreateFolderByCanAddChildren()
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...
132
    {
133
        $folder = $this->objFromFixture(Folder::class, 'disallowCanAddChildren');
134
135
        $response = Director::test(
136
            'admin/assets/api/createFolder',
137
            [
138
                'ParentID' => $folder->ID,
139
                'Name' => 'testItRestrictsCreateFolderByCanAddChildren',
140
                'SecurityID' => SecurityToken::inst()->getValue(),
141
            ],
142
            $this->session,
143
            'POST'
144
        );
145
        $this->assertTrue($response->isError());
146
        $this->assertEquals(403, $response->getStatusCode());
147
    }
148
149
    public function testItCreatesFile()
0 ignored issues
show
Coding Style introduced by
testItCreatesFile uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
150
    {
151
        $folder1 = $this->objFromFixture(Folder::class, 'folder1');
152
153
        /** @skipUpgrade */
154
        $fileData = array('Upload' => $this->getUploadFile('Upload', 'testItCreatesFile.txt'));
155
        $_FILES = $fileData;
156
        $postedData = array_merge(
157
            $fileData,
158
            [
159
                    'ParentID' => $folder1->ID,
160
                    'SecurityID' => SecurityToken::inst()->getValue(),
161
                ]
162
        );
163
        $response = Director::test(
164
            'admin/assets/api/createFile',
165
            $postedData,
166
            $this->session,
167
            'POST'
168
        );
169
        $this->assertFalse($response->isError());
170
        $responseData = json_decode($response->getBody(), true);
171
        $newFile = File::get()->byID($responseData[0]['id']);
172
        $this->assertNotNull($newFile);
173
        $this->assertEquals($folder1->ID, $newFile->ParentID);
174
        $this->assertEquals('testItCreatesFile.txt', $newFile->Name);
175
176
        // Test that duplicate uploads are renamed
177
        $response = Director::test(
178
            'admin/assets/api/createFile',
179
            $postedData,
180
            $this->session,
181
            'POST'
182
        );
183
        $this->assertFalse($response->isError());
184
        $responseData = json_decode($response->getBody(), true);
185
        $newFile2 = File::get()->byID($responseData[0]['id']);
186
        $this->assertNotNull($newFile2);
187
        $this->assertEquals($folder1->ID, $newFile2->ParentID);
188
        $this->assertNotEquals($newFile->ID, $newFile2->ID);
189
        $this->assertEquals('testItCreatesFile-v2.txt', $newFile2->Name);
190
    }
191
192 View Code Duplication
    public function testItRestrictsCreateFileOnCanCreate()
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...
Coding Style introduced by
testItRestrictsCreateFileOnCanCreate uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
193
    {
194
        $folder = $this->objFromFixture(Folder::class, 'folder1');
195
196
        $fileData = array('Upload' => $this->getUploadFile('Upload', 'disallowCanCreate.txt'));
197
        $_FILES = $fileData;
198
        $response = Director::test(
199
            'admin/assets/api/createFile',
200
            array_merge(
201
                $fileData,
202
                [
203
                    'ParentID' => $folder->ID,
204
                    'SecurityID' => SecurityToken::inst()->getValue(),
205
                ]
206
            ),
207
            $this->session,
208
            'POST'
209
        );
210
        $this->assertTrue($response->isError());
211
        $this->assertEquals(403, $response->getStatusCode());
212
    }
213
214 View Code Duplication
    public function testItRestrictsCreateFileOnCanAddChildren()
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...
Coding Style introduced by
testItRestrictsCreateFileOnCanAddChildren uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
215
    {
216
        $folder = $this->objFromFixture(Folder::class, 'disallowCanAddChildren');
217
218
        /** @skipUpgrade */
219
        $fileData = array('Upload' => $this->getUploadFile('Upload', 'test.txt'));
220
        $_FILES = $fileData;
221
        $response = Director::test(
222
            'admin/assets/api/createFile',
223
            array_merge(
224
                $fileData,
225
                [
226
                    'ParentID' => $folder->ID,
227
                    'SecurityID' => SecurityToken::inst()->getValue(),
228
                ]
229
            ),
230
            $this->session,
231
            'POST'
232
        );
233
        $this->assertTrue($response->isError());
234
        $this->assertEquals(403, $response->getStatusCode());
235
    }
236
237
    public function testItRestrictsCreateFileOnExtension()
0 ignored issues
show
Coding Style introduced by
testItRestrictsCreateFileOnExtension uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
238
    {
239
        $folder1 = $this->objFromFixture(
240
            Folder::class,
241
            'folder1'
242
        );
243
244
        /** @skipUpgrade */
245
        $fileData = array('Upload' => $this->getUploadFile('Upload', 'disallowed.php'));
246
        $_FILES = $fileData;
247
        $response = Director::test(
248
            'admin/assets/api/createFile',
249
            array_merge(
250
                $fileData,
251
                [
252
                    'ParentID' => $folder1->ID,
253
                    'SecurityID' => SecurityToken::inst()->getValue(),
254
                ]
255
            ),
256
            $this->session,
257
            'POST'
258
        );
259
        $this->assertTrue($response->isError());
260
        $this->assertEquals(400, $response->getStatusCode());
261
        $responseData = json_decode($response->getBody(), true);
262
        $this->assertContains(
263
            'Extension is not allowed',
264
            $responseData['message']['value']
265
        );
266
    }
267
268
    public function testItFiltersByDateInSearch()
269
    {
270
        $file1 = $this->objFromFixture(File::class, 'file1');
271
        $file2 = $this->objFromFixture(File::class, 'file2');
272
273
        // Force creation times
274
        $file1->Created = '2014-01-05 23:11:39';
275
        $file1->write();
276
        $file2->Created = '2014-01-06 12:00:00';
277
        $file2->write();
278
279
        // Mock searches for 4th Jan
280
        $results = $this->getResultsForSearch([
281
            'CreatedFrom' => '2014-01-04',
282
            'CreatedTo' => '2014-01-04'
283
        ]);
284
        $this->assertEquals(count($results['files']), 0);
285
286
        // Mock searches for 5th Jan
287
        $results = $this->getResultsForSearch([
288
            'CreatedFrom' => '2014-01-05',
289
            'CreatedTo' => '2014-01-05'
290
        ]);
291
        $this->assertEquals(count($results['files']), 1);
292
        $this->assertContains($file1->ID, array_column($results['files'], 'id'));
293
294
295
        // Mock searches for 5th-6th Jan
296
        $results = $this->getResultsForSearch([
297
            'CreatedFrom' => '2014-01-05',
298
            'CreatedTo' => '2014-01-06'
299
        ]);
300
        $this->assertEquals(count($results['files']), 2);
301
        $this->assertContains($file1->ID, array_column($results['files'], 'id'));
302
        $this->assertContains($file2->ID, array_column($results['files'], 'id'));
303
304
        // Mock searches for 6th Jan
305
        $results = $this->getResultsForSearch([
306
            'CreatedFrom' => '2014-01-06',
307
            'CreatedTo' => '2014-01-06'
308
        ]);
309
        $this->assertEquals(count($results['files']), 1);
310
        $this->assertContains($file2->ID, array_column($results['files'], 'id'));
311
312
        // Mock searches for 7th Jan
313
        $results = $this->getResultsForSearch([
314
            'CreatedFrom' => '2014-01-07',
315
            'CreatedTo' => '2014-01-07'
316
        ]);
317
        $this->assertEquals(count($results['files']), 0);
318
    }
319
320
321
    public function testItDoesNotFilterByDefaultInSearch()
322
    {
323
        $rootfile = $this->objFromFixture(File::class, 'rootfile');
324
        $file1 = $this->objFromFixture(File::class, 'file1');
325
        $folder1 = $this->objFromFixture(Folder::class, 'folder1');
326
327
        $results = $this->getResultsForSearch();
328
        $this->assertContains(
329
            $rootfile->ID,
330
            array_column($results['files'], 'id'),
331
            'Contains top level file'
332
        );
333
        $this->assertContains(
334
            $folder1->ID,
335
            array_column($results['files'], 'id'),
336
            'Contains top level folder'
337
        );
338
        $this->assertContains(
339
            $file1->ID,
340
            array_column($results['files'], 'id'),
341
            'Contains files in subfolder'
342
        );
343
    }
344
345
    public function testItFiltersByParentInSearch()
346
    {
347
        $file1 = $this->objFromFixture(File::class, 'file1');
348
        $file2 = $this->objFromFixture(File::class, 'file2');
349
        $file1Folder = $file1->Parent();
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on SilverStripe\ORM\DataObject. Did you maybe mean parentClass()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
350
        $file2Folder = $file2->Parent();
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on SilverStripe\ORM\DataObject. Did you maybe mean parentClass()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
351
352
        $results = $this->getResultsForSearch(['Name' => $file1->Name, 'ParentID' => $file1Folder->ID]);
353
        $this->assertEquals(count($results['files']), 1);
354
        $this->assertContains(
355
            $file1->ID,
356
            array_column($results['files'], 'id'),
357
            'Returns file when contained in correct folder'
358
        );
359
360
        $results = $this->getResultsForSearch(['Name' => $file1->Name, 'ParentID' => $file2Folder->ID]);
361
        $this->assertEquals(
362
            count($results['files']),
363
            0,
364
            'Does not return file when contained in different folder'
365
        );
366
    }
367
368
    public function testItFiltersByNameInSearch()
369
    {
370
        $file1 = $this->objFromFixture(File::class, 'file1');
371
372
        $results = $this->getResultsForSearch(['Name' => $file1->Name]);
373
        $this->assertEquals(
374
            count($results['files']),
375
            1,
376
            'Finds by Name property'
377
        );
378
        $this->assertContains($file1->ID, array_column($results['files'], 'id'));
379
380
        $results = $this->getResultsForSearch(['Name' => 'First']);
381
        $this->assertEquals(
382
            count($results['files']),
383
            1,
384
            'Finds by Title property'
385
        );
386
        $this->assertContains($file1->ID, array_column($results['files'], 'id'));
387
    }
388
389
    public function testItRestrictsViewInSearch()
390
    {
391
        $allowedFile = $this->objFromFixture(File::class, 'file1');
392
        $disallowedFile = $this->objFromFixture(File::class, 'disallowCanView');
393
394
        $results = $this->getResultsForSearch(['Name' => $allowedFile->Name]);
395
        $this->assertEquals(count($results['files']), 1);
396
        $this->assertContains($allowedFile->ID, array_column($results['files'], 'id'));
397
398
        $results = $this->getResultsForSearch(['Name' => $disallowedFile->Name]);
399
        $this->assertEquals(count($results['files']), 0);
400
    }
401
402
    public function testItRestrictsViewInReadFolder()
403
    {
404
        $folder1 = $this->objFromFixture(Folder::class, 'folder1');
405
        $allowedFile = $this->objFromFixture(File::class, 'file1');
406
        $disallowedFile = $this->objFromFixture(File::class, 'disallowCanView');
407
408
        $response = $this->get('admin/assets/api/readFolder?' . http_build_query(['id' => $folder1->ID]));
409
        $files = json_decode($response->getBody(), true);
410
        $this->assertArrayHasKey('files', $files);
411
        $ids = array_map(function ($file) {
412
            return $file['id'];
413
        }, $files['files']);
414
        $this->assertContains($allowedFile->ID, $ids);
415
        $this->assertEquals($allowedFile->ParentID, $folder1->ID);
416
        $this->assertNotContains($disallowedFile->ID, $ids);
417
        $this->assertEquals($disallowedFile->ParentID, $folder1->ID);
418
    }
419
420
    public function testItRestrictsUpdateFile()
421
    {
422
        $allowedFile = $this->objFromFixture(File::class, 'file1');
423
        $disallowedFile = $this->objFromFixture(File::class, 'disallowCanEdit');
424
425
        $response = Director::test(
426
            'admin/assets/fileEditForm',
427
            [
428
                'action_save' => 1,
429
                'ID' => $allowedFile->ID,
430
                'Name' => 'disallowCanEdit.txt',
431
                'Title' => 'new',
432
                'SecurityID' => SecurityToken::inst()->getValue(),
433
            ],
434
            $this->session
435
        );
436
        $this->assertFalse($response->isError());
437
438
        $response = Director::test(
439
            'admin/assets/fileEditForm',
440
            [
441
                'action_save' => 1,
442
                'ID' => $disallowedFile->ID,
443
                'Title' => 'new',
444
                'SecurityID' => SecurityToken::inst()->getValue(),
445
            ],
446
            $this->session
447
        );
448
        $this->assertTrue($response->isError());
449
    }
450
451
    public function testItRestrictsDelete()
452
    {
453
        $allowedFile = $this->objFromFixture(File::class, 'file1');
454
        $disallowedFile = $this->objFromFixture(File::class, 'disallowCanDelete');
455
456
        $response = Director::test(
457
            'admin/assets/api/delete',
458
            null,
459
            $this->session,
460
            'DELETE',
461
            http_build_query([
462
                'ids' => [$allowedFile->ID, $disallowedFile->ID],
463
                'SecurityID' => SecurityToken::inst()->getValue(),
464
            ])
465
        );
466
        $this->assertTrue($response->isError());
467
468
        $response = Director::test(
469
            'admin/assets/api/delete',
470
            null,
471
            $this->session,
472
            'DELETE',
473
            http_build_query([
474
                'ids' => [$allowedFile->ID],
475
                'SecurityID' => SecurityToken::inst()->getValue(),
476
            ])
477
        );
478
        $this->assertFalse($response->isError());
479
    }
480
481
    /**
482
     * @param array $params
483
     * @return array
484
     */
485
    protected function getResultsForSearch($params = array())
486
    {
487
        $response = $this->get('admin/assets/api/search?' . http_build_query($params));
488
        $this->assertFalse($response->isError());
489
490
        return json_decode($response->getBody(), true);
491
    }
492
493
    /**
494
     * @param string $paramName
495
     * @param string $tmpFileName
496
     * @return array Emulating an entry in the $_FILES superglobal
497
     */
498
    protected function getUploadFile($paramName, $tmpFileName = 'AssetAdminTest.txt')
0 ignored issues
show
Unused Code introduced by
The parameter $paramName is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
499
    {
500
        $tmpFilePath = TEMP_FOLDER . '/' . $tmpFileName;
501
        $tmpFileContent = '';
502
        for ($i = 0; $i < 10000; $i++) {
503
            $tmpFileContent .= '0';
504
        }
505
        file_put_contents($tmpFilePath, $tmpFileContent);
506
507
        // emulates the $_FILES array
508
        return array(
509
            'name' => $tmpFileName,
510
            'type' => 'text/plaintext',
511
            'size' => filesize($tmpFilePath),
512
            'tmp_name' => $tmpFilePath,
513
            'error' => UPLOAD_ERR_OK,
514
        );
515
    }
516
}
517