Proyectos de Subversion Moodle

Rev

Rev 11 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
declare(strict_types = 1);
18
 
19
namespace core_h5p;
20
 
21
use core_h5p\local\library\autoloader;
22
 
23
/**
24
 * Test class covering the H5P helper.
25
 *
26
 * @package    core_h5p
27
 * @category   test
28
 * @copyright  2019 Sara Arjona <sara@moodle.com>
29
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30
 * @covers     \core_h5p\helper
31
 */
1441 ariadna 32
final class helper_test extends \advanced_testcase {
1 efrain 33
 
34
    /**
35
     * Register the H5P autoloader
36
     */
37
    protected function setUp(): void {
1441 ariadna 38
        parent::setUp();
1 efrain 39
        autoloader::register();
40
    }
41
 
42
    /**
43
     * Test the behaviour of get_display_options().
44
     *
45
     * @dataProvider display_options_provider
46
     * @param  bool   $frame     Whether the frame should be displayed or not
47
     * @param  bool   $export    Whether the export action button should be displayed or not
48
     * @param  bool   $embed     Whether the embed action button should be displayed or not
49
     * @param  bool   $copyright Whether the copyright action button should be displayed or not
50
     * @param  int    $expected The expectation with the displayoptions value
51
     */
52
    public function test_display_options(bool $frame, bool $export, bool $embed, bool $copyright, int $expected): void {
53
        $this->setRunTestInSeparateProcess(true);
54
        $this->resetAfterTest();
55
 
56
        $factory = new \core_h5p\factory();
57
        $core = $factory->get_core();
58
        $config = (object)[
59
            'frame' => $frame,
60
            'export' => $export,
61
            'embed' => $embed,
62
            'copyright' => $copyright,
63
        ];
64
 
65
        // Test getting display options.
66
        $displayoptions = helper::get_display_options($core, $config);
67
        $this->assertEquals($expected, $displayoptions);
68
 
69
        // Test decoding display options.
70
        $decoded = helper::decode_display_options($core, $expected);
71
        $this->assertEquals($decoded->export, $config->export);
72
        $this->assertEquals($decoded->embed, $config->embed);
73
        $this->assertEquals($decoded->copyright, $config->copyright);
74
    }
75
 
76
    /**
77
     * Data provider for test_get_display_options().
78
     *
79
     * @return array
80
     */
1441 ariadna 81
    public static function display_options_provider(): array {
1 efrain 82
        return [
83
            'All display options disabled' => [
84
                false,
85
                false,
86
                false,
87
                false,
88
                15,
89
            ],
90
            'All display options enabled' => [
91
                true,
92
                true,
93
                true,
94
                true,
95
                0,
96
            ],
97
            'Frame disabled and the rest enabled' => [
98
                false,
99
                true,
100
                true,
101
                true,
102
                0,
103
            ],
104
            'Only export enabled' => [
105
                false,
106
                true,
107
                false,
108
                false,
109
                12,
110
            ],
111
            'Only embed enabled' => [
112
                false,
113
                false,
114
                true,
115
                false,
116
                10,
117
            ],
118
            'Only copyright enabled' => [
119
                false,
120
                false,
121
                false,
122
                true,
123
                6,
124
            ],
125
        ];
126
    }
127
 
128
    /**
129
     * Test the behaviour of save_h5p() when there are some missing libraries in the system.
130
     * @runInSeparateProcess
131
     */
132
    public function test_save_h5p_missing_libraries(): void {
133
        $this->resetAfterTest();
134
        $factory = new \core_h5p\factory();
135
 
136
        // Create a user.
137
        $user = $this->getDataGenerator()->create_user();
138
        $this->setUser($user);
139
 
140
        // This is a valid .H5P file.
1441 ariadna 141
        $path = self::get_fixture_path(__NAMESPACE__, 'greeting-card.h5p');
1 efrain 142
        $file = helper::create_fake_stored_file_from_path($path, (int)$user->id);
143
        $factory->get_framework()->set_file($file);
144
 
145
        $config = (object)[
146
            'frame' => 1,
147
            'export' => 1,
148
            'embed' => 0,
149
            'copyright' => 0,
150
        ];
151
 
152
        // There are some missing libraries in the system, so an error should be returned.
153
        $h5pid = helper::save_h5p($factory, $file, $config);
154
        $this->assertFalse($h5pid);
155
        $errors = $factory->get_framework()->getMessages('error');
156
        $this->assertCount(1, $errors);
157
        $error = reset($errors);
158
        $this->assertEquals('missing-main-library', $error->code);
159
        $this->assertEquals('Missing main library H5P.GreetingCard 1.0', $error->message);
160
    }
161
 
162
    /**
163
     * Test the behaviour of save_h5p() when the libraries exist in the system.
164
     * @runInSeparateProcess
165
     */
166
    public function test_save_h5p_existing_libraries(): void {
167
        global $DB;
168
 
169
        $this->resetAfterTest();
170
        $factory = new \core_h5p\factory();
171
 
172
        // Create a user.
173
        $user = $this->getDataGenerator()->create_user();
174
        $this->setUser($user);
175
 
176
        // This is a valid .H5P file.
1441 ariadna 177
        $path = self::get_fixture_path(__NAMESPACE__, 'greeting-card.h5p');
1 efrain 178
        $file = helper::create_fake_stored_file_from_path($path, (int)$user->id);
179
        $factory->get_framework()->set_file($file);
180
 
181
        $config = (object)[
182
            'frame' => 1,
183
            'export' => 1,
184
            'embed' => 0,
185
            'copyright' => 0,
186
        ];
187
        // The required libraries exist in the system before saving the .h5p file.
188
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
189
        $lib = $generator->create_library_record('H5P.GreetingCard', 'GreetingCard', 1, 0);
190
        $h5pid = helper::save_h5p($factory, $file, $config);
191
        $this->assertNotEmpty($h5pid);
192
 
193
        // No errors are raised.
194
        $errors = $factory->get_framework()->getMessages('error');
195
        $this->assertCount(0, $errors);
196
 
197
        // And the content in the .h5p file has been saved as expected.
198
        $h5p = $DB->get_record('h5p', ['id' => $h5pid]);
199
        $this->assertEquals($lib->id, $h5p->mainlibraryid);
200
        $this->assertEquals(helper::get_display_options($factory->get_core(), $config), $h5p->displayoptions);
201
        $this->assertStringContainsString('Hello world!', $h5p->jsoncontent);
202
    }
203
 
204
    /**
205
     * Test the behaviour of save_h5p() when the H5P file contains metadata.
206
     *
207
     * @runInSeparateProcess
208
     */
209
    public function test_save_h5p_metadata(): void {
210
        global $DB;
211
 
212
        $this->resetAfterTest();
213
        $factory = new \core_h5p\factory();
214
 
215
        // Create a user.
216
        $user = $this->getDataGenerator()->create_user();
217
        $this->setUser($user);
218
 
219
        // This is a valid .H5P file.
1441 ariadna 220
        $path = self::get_fixture_path(__NAMESPACE__, 'guess-the-answer.h5p');
1 efrain 221
        $file = helper::create_fake_stored_file_from_path($path, (int)$user->id);
222
        $factory->get_framework()->set_file($file);
223
 
224
        $config = (object)[
225
            'frame' => 1,
226
            'export' => 1,
227
            'embed' => 0,
228
            'copyright' => 1,
229
        ];
230
        // The required libraries exist in the system before saving the .h5p file.
231
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
232
        $lib = $generator->create_library_record('H5P.GuessTheAnswer', 'Guess the Answer', 1, 5);
233
        $generator->create_library_record('H5P.Image', 'Image', 1, 1);
234
        $generator->create_library_record('FontAwesome', 'Font Awesome', 4, 5);
235
        $h5pid = helper::save_h5p($factory, $file, $config);
236
        $this->assertNotEmpty($h5pid);
237
 
238
        // No errors are raised.
239
        $errors = $factory->get_framework()->getMessages('error');
240
        $this->assertCount(0, $errors);
241
 
242
        // And the content in the .h5p file has been saved as expected.
243
        $h5p = $DB->get_record('h5p', ['id' => $h5pid]);
244
        $this->assertEquals($lib->id, $h5p->mainlibraryid);
245
        $this->assertEquals(helper::get_display_options($factory->get_core(), $config), $h5p->displayoptions);
246
        $this->assertStringContainsString('Which fruit is this?', $h5p->jsoncontent);
247
        // Metadata has been also saved.
248
        $this->assertStringContainsString('This is licence extras information added for testing purposes.', $h5p->jsoncontent);
249
        $this->assertStringContainsString('H5P Author', $h5p->jsoncontent);
250
        $this->assertStringContainsString('Add metadata information', $h5p->jsoncontent);
251
    }
252
 
253
    /**
254
     * Test the behaviour of save_h5p() when the .h5p file is invalid.
255
     * @runInSeparateProcess
256
     */
257
    public function test_save_h5p_invalid_file(): void {
258
        $this->resetAfterTest();
259
        $factory = new \core_h5p\factory();
260
 
261
        // Create a user.
262
        $user = $this->getDataGenerator()->create_user();
263
        $this->setUser($user);
264
 
265
        // Prepare an invalid .H5P file.
1441 ariadna 266
        $path = self::get_fixture_path(__NAMESPACE__, 'h5ptest.zip');
1 efrain 267
        $file = helper::create_fake_stored_file_from_path($path, (int)$user->id);
268
        $factory->get_framework()->set_file($file);
269
        $config = (object)[
270
            'frame' => 1,
271
            'export' => 1,
272
            'embed' => 0,
273
            'copyright' => 0,
274
        ];
275
 
276
        // When saving an invalid .h5p file, an error should be raised.
277
        $h5pid = helper::save_h5p($factory, $file, $config);
278
        $this->assertFalse($h5pid);
279
        $errors = $factory->get_framework()->getMessages('error');
280
        $this->assertCount(2, $errors);
281
 
282
        $expectederrorcodes = ['invalid-content-folder', 'invalid-h5p-json-file'];
283
        foreach ($errors as $error) {
284
            $this->assertContains($error->code, $expectederrorcodes);
285
        }
286
    }
287
 
288
    /**
289
     * Test the behaviour of can_deploy_package().
290
     */
291
    public function test_can_deploy_package(): void {
292
        $this->resetAfterTest();
293
        $factory = new \core_h5p\factory();
294
 
295
        // Create a user.
296
        $user = $this->getDataGenerator()->create_user();
297
        $admin = get_admin();
298
 
299
        // Prepare a valid .H5P file.
1441 ariadna 300
        $path = self::get_fixture_path(__NAMESPACE__, 'greeting-card.h5p');
1 efrain 301
 
302
        // Files created by users can't be deployed.
303
        $file = helper::create_fake_stored_file_from_path($path, (int)$user->id);
304
        $factory->get_framework()->set_file($file);
305
        $candeploy = helper::can_deploy_package($file);
306
        $this->assertFalse($candeploy);
307
 
308
        // Files created by admins can be deployed, even when the current user is not the admin.
309
        $this->setUser($user);
310
        $file = helper::create_fake_stored_file_from_path($path, (int)$admin->id);
311
        $factory->get_framework()->set_file($file);
312
        $candeploy = helper::can_deploy_package($file);
313
        $this->assertTrue($candeploy);
11 efrain 314
 
315
        $usertobedeleted = $this->getDataGenerator()->create_user();
316
        $this->setUser($usertobedeleted);
317
        $file = helper::create_fake_stored_file_from_path($path, (int)$usertobedeleted->id);
318
        $factory->get_framework()->set_file($file);
319
        // Then we delete this user.
320
        $this->setAdminUser();
321
        delete_user($usertobedeleted);
322
        $candeploy = helper::can_deploy_package($file);
323
        $this->assertTrue($candeploy); // We can update as admin.
1 efrain 324
    }
325
 
326
    /**
327
     * Test the behaviour of can_update_library().
328
     */
329
    public function test_can_update_library(): void {
330
        $this->resetAfterTest();
331
        $factory = new \core_h5p\factory();
332
 
333
        // Create a user.
334
        $user = $this->getDataGenerator()->create_user();
335
        $admin = get_admin();
336
 
337
        // Prepare a valid .H5P file.
1441 ariadna 338
        $path = self::get_fixture_path(__NAMESPACE__, 'greeting-card.h5p');
1 efrain 339
 
340
        // Libraries can't be updated when the file has been created by users.
341
        $file = helper::create_fake_stored_file_from_path($path, (int)$user->id);
342
        $factory->get_framework()->set_file($file);
343
        $candeploy = helper::can_update_library($file);
344
        $this->assertFalse($candeploy);
345
 
346
        // Libraries can be updated when the file has been created by admin, even when the current user is not the admin.
347
        $this->setUser($user);
348
        $file = helper::create_fake_stored_file_from_path($path, (int)$admin->id);
349
        $factory->get_framework()->set_file($file);
350
        $candeploy = helper::can_update_library($file);
351
        $this->assertTrue($candeploy);
11 efrain 352
 
353
        $usertobedeleted = $this->getDataGenerator()->create_user();
354
        $this->setUser($usertobedeleted);
355
        $file = helper::create_fake_stored_file_from_path($path, (int)$usertobedeleted->id);
356
        $factory->get_framework()->set_file($file);
357
        // Then we delete this user.
358
        $this->setAdminUser();
359
        delete_user($usertobedeleted);
360
        $canupdate = helper::can_update_library($file);
361
        $this->assertTrue($canupdate); // We can update as admin.
1 efrain 362
    }
363
 
364
    /**
365
     * Test the behaviour of get_messages().
366
     */
367
    public function test_get_messages(): void {
368
        $this->resetAfterTest();
369
 
370
        $factory = new \core_h5p\factory();
371
        $messages = new \stdClass();
372
 
373
        helper::get_messages($messages, $factory);
374
        $this->assertTrue(empty($messages->error));
375
        $this->assertTrue(empty($messages->info));
376
 
377
        // Add an some messages manually and check they are still there.
378
        $messages->error = [];
379
        $messages->error['error1'] = 'Testing ERROR message';
380
        $messages->info = [];
381
        $messages->info['info1'] = 'Testing INFO message';
382
        $messages->info['info2'] = 'Testing INFO message';
383
        helper::get_messages($messages, $factory);
384
        $this->assertCount(1, $messages->error);
385
        $this->assertCount(2, $messages->info);
386
 
387
        // When saving an invalid .h5p file, 6 errors should be raised.
1441 ariadna 388
        $path = self::get_fixture_path(__NAMESPACE__, 'h5ptest.zip');
1 efrain 389
        $file = helper::create_fake_stored_file_from_path($path);
390
        $factory->get_framework()->set_file($file);
391
        $config = (object)[
392
            'frame' => 1,
393
            'export' => 1,
394
            'embed' => 0,
395
            'copyright' => 0,
396
        ];
397
        $h5pid = helper::save_h5p($factory, $file, $config);
398
        $this->assertFalse($h5pid);
399
        helper::get_messages($messages, $factory);
400
        $this->assertCount(7, $messages->error);
401
        $this->assertCount(2, $messages->info);
402
    }
403
 
404
    /**
405
     * Test the behaviour of get_export_info().
406
     */
407
    public function test_get_export_info(): void {
408
         $this->resetAfterTest();
409
 
410
        $filename = 'guess-the-answer.h5p';
411
        $syscontext = \context_system::instance();
412
 
413
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
414
        $deployedfile = $generator->create_export_file($filename,
415
            $syscontext->id,
416
            file_storage::COMPONENT,
417
            file_storage::EXPORT_FILEAREA);
418
 
419
        // Test scenario 1: Get export information from correct filename.
420
        $helperfile = helper::get_export_info($deployedfile['filename']);
421
        $this->assertEquals($deployedfile['filename'], $helperfile['filename']);
422
        $this->assertEquals($deployedfile['filepath'], $helperfile['filepath']);
423
        $this->assertEquals($deployedfile['filesize'], $helperfile['filesize']);
424
        $this->assertEquals($deployedfile['timemodified'], $helperfile['timemodified']);
425
        $this->assertEquals($deployedfile['fileurl'], $helperfile['fileurl']);
426
 
427
        // Test scenario 2: Get export information from correct filename and url.
428
        $url = \moodle_url::make_pluginfile_url(
429
            $syscontext->id,
430
            file_storage::COMPONENT,
431
            'unittest',
432
            0,
433
            '/',
434
            $deployedfile['filename'],
435
            false,
436
            true
437
        );
438
        $helperfile = helper::get_export_info($deployedfile['filename'], $url);
439
        $this->assertEquals($url, $helperfile['fileurl']);
440
 
441
        // Test scenario 3: Get export information from correct filename and factory.
442
        $factory = new \core_h5p\factory();
443
        $helperfile = helper::get_export_info($deployedfile['filename'], null, $factory);
444
        $this->assertEquals($deployedfile['filename'], $helperfile['filename']);
445
        $this->assertEquals($deployedfile['filepath'], $helperfile['filepath']);
446
        $this->assertEquals($deployedfile['filesize'], $helperfile['filesize']);
447
        $this->assertEquals($deployedfile['timemodified'], $helperfile['timemodified']);
448
        $this->assertEquals($deployedfile['fileurl'], $helperfile['fileurl']);
449
 
450
        // Test scenario 4: Get export information from wrong filename.
451
        $helperfile = helper::get_export_info('nofileexist.h5p', $url);
452
        $this->assertNull($helperfile);
453
    }
454
 
455
    /**
456
     * Test the parse_js_array function with a range of content.
457
     *
458
     * @dataProvider parse_js_array_provider
459
     * @param string $content
460
     * @param array $expected
461
     */
462
    public function test_parse_js_array(string $content, array $expected): void {
463
        $this->assertEquals($expected, helper::parse_js_array($content));
464
    }
465
 
466
    /**
467
     * Data provider for test_parse_js_array().
468
     *
469
     * @return array
470
     */
1441 ariadna 471
    public static function parse_js_array_provider(): array {
1 efrain 472
        $lines = [
473
            "{",
474
            "  missingTranslation: '[Missing translation :key]',",
475
            "  loading: 'Loading, please wait...',",
476
            "  selectLibrary: 'Select the library you wish to use for your content.',",
477
            "}",
478
        ];
479
        $expected = [
480
            'missingTranslation' => '[Missing translation :key]',
481
            'loading' => 'Loading, please wait...',
482
            'selectLibrary' => 'Select the library you wish to use for your content.',
483
        ];
484
        return [
485
            'Strings with \n' => [
486
                implode("\n", $lines),
487
                $expected,
488
            ],
489
            'Strings with \r\n' => [
490
                implode("\r\n", $lines),
491
                $expected,
492
            ],
493
            'Strings with \r' => [
494
                implode("\r", $lines),
495
                $expected,
496
            ],
497
        ];
498
    }
499
}