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
namespace core_h5p;
18
 
19
use core_collator;
20
use Moodle\H5PCore;
21
use Moodle\H5PDisplayOptionBehaviour;
22
 
23
// phpcs:disable moodle.NamingConventions.ValidFunctionName.LowercaseMethod
24
 
25
/**
26
 *
27
 * Test class covering the H5PFrameworkInterface interface implementation.
28
 *
29
 * @package    core_h5p
30
 * @category   test
31
 * @copyright  2019 Mihail Geshoski <mihail@moodle.com>
32
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33
 * @covers     \core_h5p\framework
34
 * @runTestsInSeparateProcesses
35
 */
1441 ariadna 36
final class framework_test extends \advanced_testcase {
1 efrain 37
 
38
    /** @var \core_h5p\framework */
39
    private $framework;
40
 
41
    /**
42
     * Set up function for tests.
43
     */
44
    public function setUp(): void {
1441 ariadna 45
        parent::setUp();
1 efrain 46
        $factory = new \core_h5p\factory();
47
        $this->framework = $factory->get_framework();
48
    }
49
 
50
    /**
51
     * Test the behaviour of getPlatformInfo().
52
     */
11 efrain 53
    public function test_getPlatformInfo(): void {
1 efrain 54
        global $CFG;
55
 
56
        $platforminfo = $this->framework->getPlatformInfo();
57
 
58
        $expected = array(
59
            'name' => 'Moodle',
60
            'version' => $CFG->version,
61
            'h5pVersion' => $CFG->version
62
        );
63
 
64
        $this->assertEquals($expected, $platforminfo);
65
    }
66
 
67
    /**
68
     * Test the behaviour of fetchExternalData() when the store path is not defined.
69
     *
70
     * This test is intensive and requires downloading content of an external file,
71
     * therefore it might take longer time to execute.
72
     * In order to execute this test PHPUNIT_LONGTEST should be set to true in phpunit.xml or directly in config.php.
73
     */
11 efrain 74
    public function test_fetchExternalData_no_path_defined(): void {
1 efrain 75
 
76
        if (!PHPUNIT_LONGTEST) {
77
            $this->markTestSkipped('PHPUNIT_LONGTEST is not defined');
78
        }
79
 
80
        $this->resetAfterTest();
81
 
82
        $library = 'H5P.Accordion';
83
        // Provide a valid URL to an external H5P content.
84
        $url = $this->getExternalTestFileUrl('/'.$library.'.h5p');
85
 
86
        // Test fetching an external H5P content without defining a path to where the file should be stored.
87
        $data = $this->framework->fetchExternalData($url, null, true);
88
 
89
        // The response should not be empty and return true if the file was successfully downloaded.
90
        $this->assertNotEmpty($data);
91
        $this->assertTrue($data);
92
 
93
        $h5pfolderpath = $this->framework->getUploadedH5pFolderPath();
94
        // The uploaded file should exist on the filesystem.
95
        $this->assertTrue(file_exists($h5pfolderpath . '.h5p'));
96
    }
97
 
98
    /**
99
     * Test the behaviour of fetchExternalData() when the store path is defined.
100
     *
101
     * This test is intensive and requires downloading content of an external file,
102
     * therefore it might take longer time to execute.
103
     * In order to execute this test PHPUNIT_LONGTEST should be set to true in phpunit.xml or directly in config.php.
104
     */
11 efrain 105
    public function test_fetchExternalData_path_defined(): void {
1 efrain 106
        global $CFG;
107
 
108
        if (!PHPUNIT_LONGTEST) {
109
            $this->markTestSkipped('PHPUNIT_LONGTEST is not defined');
110
        }
111
 
112
        $this->resetAfterTest();
113
 
114
        $library = 'H5P.Accordion';
115
        // Provide a valid URL to an external H5P content.
116
        $url = $this->getExternalTestFileUrl('/'.$library.'.h5p');
117
 
118
        $h5pfolderpath = $CFG->tempdir . uniqid('/h5p-');
119
 
120
        $data = $this->framework->fetchExternalData($url, null, true, $h5pfolderpath . '.h5p');
121
 
122
        // The response should not be empty and return true if the content has been successfully saved to a file.
123
        $this->assertNotEmpty($data);
124
        $this->assertTrue($data);
125
 
126
        // The uploaded file should exist on the filesystem.
127
        $this->assertTrue(file_exists($h5pfolderpath . '.h5p'));
128
    }
129
 
130
    /**
131
     * Test the behaviour of fetchExternalData() when the URL is pointing to an external file that is
132
     * not an h5p content.
133
     *
134
     * This test is intensive and requires downloading content of an external file,
135
     * therefore it might take longer time to execute.
136
     * In order to execute this test PHPUNIT_LONGTEST should be set to true in phpunit.xml or directly in config.php.
137
     */
11 efrain 138
    public function test_fetchExternalData_url_not_h5p(): void {
1 efrain 139
 
140
        if (!PHPUNIT_LONGTEST) {
141
            // This test is intensive and requires downloading the content of an external file.
142
            $this->markTestSkipped('PHPUNIT_LONGTEST is not defined');
143
        }
144
 
145
        $this->resetAfterTest();
146
 
147
        // Provide an URL to an external file that is not an H5P content file.
148
        $url = $this->getExternalTestFileUrl('/h5pcontenttypes.json');
149
 
150
        $data = $this->framework->fetchExternalData($url, null, true);
151
 
152
        // The response should not be empty and return true if the content has been successfully saved to a file.
153
        $this->assertNotEmpty($data);
154
        $this->assertTrue($data);
155
 
156
        // The uploaded file should exist on the filesystem with it's original extension.
157
        // NOTE: The file would be later validated by the H5P Validator.
158
        $h5pfolderpath = $this->framework->getUploadedH5pFolderPath();
159
        $this->assertTrue(file_exists($h5pfolderpath . '.json'));
160
    }
161
 
162
    /**
163
     * Test the behaviour of fetchExternalData() when the URL is invalid.
164
     */
11 efrain 165
    public function test_fetchExternalData_url_invalid(): void {
1 efrain 166
        // Provide an invalid URL to an external file.
167
        $url = "someprotocol://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
168
 
169
        $data = $this->framework->fetchExternalData($url, null, true);
170
 
171
        // The response should be empty.
172
        $this->assertEmpty($data);
173
    }
174
 
175
    /**
176
     * Test the behaviour of setLibraryTutorialUrl().
177
     */
11 efrain 178
    public function test_setLibraryTutorialUrl(): void {
1 efrain 179
        global $DB;
180
 
181
        $this->resetAfterTest();
182
 
183
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
184
 
185
        // Create several libraries records.
186
        $lib1 = $generator->create_library_record('Library1', 'Lib1', 1, 0, 1, '', null, 'http://tutorial1.org',
187
            'http://example.org');
188
        $lib2 = $generator->create_library_record('Library2', 'Lib2', 2, 0, 1, '', null, 'http://tutorial2.org');
189
        $lib3 = $generator->create_library_record('Library3', 'Lib3', 3, 0);
190
 
191
        // Check only lib1 tutorial URL is updated.
192
        $url = 'https://newtutorial.cat';
193
        $this->framework->setLibraryTutorialUrl($lib1->machinename, $url);
194
 
195
        $libraries = $DB->get_records('h5p_libraries');
196
        $this->assertEquals($libraries[$lib1->id]->tutorial, $url);
197
        $this->assertNotEquals($libraries[$lib2->id]->tutorial, $url);
198
 
199
        // Check lib1 tutorial URL is set to null.
200
        $this->framework->setLibraryTutorialUrl($lib1->machinename, null);
201
 
202
        $libraries = $DB->get_records('h5p_libraries');
203
        $this->assertCount(3, $libraries);
204
        $this->assertNull($libraries[$lib1->id]->tutorial);
205
 
206
        // Check no tutorial URL is set if library name doesn't exist.
207
        $this->framework->setLibraryTutorialUrl('Unexisting library', $url);
208
 
209
        $libraries = $DB->get_records('h5p_libraries');
210
        $this->assertCount(3, $libraries);
211
        $this->assertNull($libraries[$lib1->id]->tutorial);
212
        $this->assertEquals($libraries[$lib2->id]->tutorial, 'http://tutorial2.org');
213
        $this->assertNull($libraries[$lib3->id]->tutorial);
214
 
215
        // Check tutorial is set as expected when it was null.
216
        $this->framework->setLibraryTutorialUrl($lib3->machinename, $url);
217
 
218
        $libraries = $DB->get_records('h5p_libraries');
219
        $this->assertEquals($libraries[$lib3->id]->tutorial, $url);
220
        $this->assertNull($libraries[$lib1->id]->tutorial);
221
        $this->assertEquals($libraries[$lib2->id]->tutorial, 'http://tutorial2.org');
222
    }
223
 
224
    /**
225
     * Test the behaviour of setErrorMessage().
226
     */
11 efrain 227
    public function test_setErrorMessage(): void {
1 efrain 228
        // Set an error message and an error code.
229
        $message = "Error message";
230
        $code = '404';
231
 
232
        // Set an error message.
233
        $this->framework->setErrorMessage($message, $code);
234
 
235
        // Get the error messages.
236
        $errormessages = $this->framework->getMessages('error');
237
 
238
        $expected = new \stdClass();
239
        $expected->code = 404;
240
        $expected->message = 'Error message';
241
 
242
        $this->assertEquals($expected, $errormessages[0]);
243
    }
244
 
245
    /**
246
     * Test the behaviour of setInfoMessage().
247
     */
11 efrain 248
    public function test_setInfoMessage(): void {
1 efrain 249
        $message = "Info message";
250
 
251
        // Set an info message.
252
        $this->framework->setInfoMessage($message);
253
 
254
        // Get the info messages.
255
        $infomessages = $this->framework->getMessages('info');
256
 
257
        $expected = 'Info message';
258
 
259
        $this->assertEquals($expected, $infomessages[0]);
260
    }
261
 
262
    /**
263
     * Test the behaviour of getMessages() when requesting the info messages.
264
     */
11 efrain 265
    public function test_getMessages_info(): void {
1 efrain 266
        // Set an info message.
267
        $this->framework->setInfoMessage("Info message");
268
        // Set an error message.
269
        $this->framework->setErrorMessage("Error message 1", 404);
270
 
271
        // Get the info messages.
272
        $infomessages = $this->framework->getMessages('info');
273
 
274
        $expected = 'Info message';
275
 
276
        // Make sure that only the info message has been returned.
277
        $this->assertCount(1, $infomessages);
278
        $this->assertEquals($expected, $infomessages[0]);
279
 
280
        $infomessages = $this->framework->getMessages('info');
281
 
282
        // Make sure the info messages have now been removed.
283
        $this->assertEmpty($infomessages);
284
    }
285
 
286
    /**
287
     * Test the behaviour of getMessages() when requesting the error messages.
288
     */
11 efrain 289
    public function test_getMessages_error(): void {
1 efrain 290
        // Set an info message.
291
        $this->framework->setInfoMessage("Info message");
292
        // Set an error message.
293
        $this->framework->setErrorMessage("Error message 1", 404);
294
        // Set another error message.
295
        $this->framework->setErrorMessage("Error message 2", 403);
296
 
297
        // Get the error messages.
298
        $errormessages = $this->framework->getMessages('error');
299
 
300
        // Make sure that only the error messages are being returned.
301
        $this->assertEquals(2, count($errormessages));
302
 
303
        $expected1 = (object) [
304
            'code' => 404,
305
            'message' => 'Error message 1'
306
        ];
307
 
308
        $expected2 = (object) [
309
            'code' => 403,
310
            'message' => 'Error message 2'
311
        ];
312
 
313
        $this->assertEquals($expected1, $errormessages[0]);
314
        $this->assertEquals($expected2, $errormessages[1]);
315
 
316
        $errormessages = $this->framework->getMessages('error');
317
 
318
        // Make sure the info messages have now been removed.
319
        $this->assertEmpty($errormessages);
320
    }
321
 
322
    /**
323
     * Test the behaviour of t() when translating existing string that does not require any arguments.
324
     */
11 efrain 325
    public function test_t_existing_string_no_args(): void {
1 efrain 326
        // Existing language string without passed arguments.
327
        $translation = $this->framework->t('No copyright information available for this content.');
328
 
329
        // Make sure the string translation has been returned.
330
        $this->assertEquals('No copyright information available for this content.', $translation);
331
    }
332
 
333
    /**
334
     * Test the behaviour of t() when translating existing string that does require parameters.
335
     */
11 efrain 336
    public function test_t_existing_string_args(): void {
1 efrain 337
        // Existing language string with passed arguments.
338
        $translation = $this->framework->t('Illegal option %option in %library',
339
            ['%option' => 'example', '%library' => 'Test library']);
340
 
341
        // Make sure the string translation has been returned.
342
        $this->assertEquals('Illegal option example in Test library', $translation);
343
    }
344
 
345
    /**
346
     * Test the behaviour of t() when translating non-existent string.
347
     */
11 efrain 348
    public function test_t_non_existent_string(): void {
1 efrain 349
        // Non-existing language string.
350
        $message = 'Random message %option';
351
 
352
        $translation = $this->framework->t($message);
353
 
354
        // Make sure a debugging message is triggered.
355
        $this->assertDebuggingCalled("String translation cannot be found. Please add a string definition for '" .
356
            $message . "' in the core_h5p component.");
357
        // As the string does not exist in the mapping array, make sure the passed message is returned.
358
        $this->assertEquals($message, $translation);
359
    }
360
 
361
    /**
362
     * Test the behaviour of getLibraryFileUrl() when requesting a file URL from an existing library and
363
     * the folder name is parsable.
364
     **/
11 efrain 365
    public function test_getLibraryFileUrl(): void {
1 efrain 366
        global $CFG;
367
 
368
        $this->resetAfterTest();
369
 
370
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
371
        // Create a library record.
372
        $lib = $generator->create_library_record('Library', 'Lib', 1, 1);
373
 
374
        $expected = "{$CFG->wwwroot}/pluginfile.php/1/core_h5p/libraries/{$lib->id}/Library-1.1/library.json";
375
 
376
        // Get the URL of a file from an existing library. The provided folder name is parsable.
377
        $actual = $this->framework->getLibraryFileUrl('Library-1.1', 'library.json');
378
 
379
        // Make sure the expected URL is returned.
380
        $this->assertEquals($expected, $actual);
381
    }
382
 
383
    /**
384
     * Test the behaviour of getLibraryFileUrl() when requesting a file URL from a non-existent library and
385
     * the folder name is parsable.
386
     **/
11 efrain 387
    public function test_getLibraryFileUrl_non_existent_library(): void {
1 efrain 388
        $this->resetAfterTest();
389
 
390
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
391
        // Create a library record.
392
        $generator->create_library_record('Library', 'Lib', 1, 1);
393
 
394
        // Get the URL of a file from a non-existent library. The provided folder name is parsable.
395
        $actual = $this->framework->getLibraryFileUrl('Library2-1.1', 'library.json');
396
 
397
        // Make sure a debugging message is triggered.
398
        $this->assertDebuggingCalled('The library "Library2-1.1" does not exist.');
399
 
400
        // Make sure that an URL is not returned.
401
        $this->assertEquals(null, $actual);
402
    }
403
 
404
    /**
405
     * Test the behaviour of getLibraryFileUrl() when requesting a file URL from an existing library and
406
     * the folder name is not parsable.
407
     **/
11 efrain 408
    public function test_getLibraryFileUrl_not_parsable_folder_name(): void {
1 efrain 409
        $this->resetAfterTest();
410
 
411
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
412
        // Create a library record.
413
        $generator->create_library_record('Library', 'Lib', 1, 1);
414
 
415
        // Get the URL of a file from an existing library. The provided folder name is not parsable.
416
        $actual = $this->framework->getLibraryFileUrl('Library1.1', 'library.json');
417
 
418
        // Make sure a debugging message is triggered.
419
        $this->assertDebuggingCalled(
420
            'The provided string value "Library1.1" is not a valid name for a library folder.');
421
 
422
        // Make sure that an URL is not returned.
423
        $this->assertEquals(null, $actual);
424
    }
425
 
426
    /**
427
     * Test the behaviour of getLibraryFileUrl() when requesting a file URL from a library that has multiple
428
     * versions and the folder name is parsable.
429
     **/
11 efrain 430
    public function test_getLibraryFileUrl_library_has_multiple_versions(): void {
1 efrain 431
        global $CFG;
432
 
433
        $this->resetAfterTest();
434
 
435
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
436
        // Create library records with a different minor version.
437
        $lib1 = $generator->create_library_record('Library', 'Lib', 1, 1);
438
        $lib2 = $generator->create_library_record('Library', 'Lib', 1, 3);
439
 
440
        $expected = "{$CFG->wwwroot}/pluginfile.php/1/core_h5p/libraries/{$lib2->id}/Library-1.3/library.json";
441
 
442
        // Get the URL of a file from an existing library (Library 1.3). The provided folder name is parsable.
443
        $actual = $this->framework->getLibraryFileUrl('Library-1.3', 'library.json');
444
 
445
        // Make sure the proper URL (from the requested library version) is returned.
446
        $this->assertEquals($expected, $actual);
447
    }
448
 
449
    /**
450
     * Test the behaviour of getLibraryFileUrl() when requesting a file URL from a library that has multiple
451
     * patch versions and the folder name is parsable.
452
     **/
11 efrain 453
    public function test_getLibraryFileUrl_library_has_multiple_patch_versions(): void {
1 efrain 454
        global $CFG;
455
 
456
        $this->resetAfterTest();
457
 
458
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
459
        // Create library records with a different patch version.
460
        $lib1 = $generator->create_library_record('Library', 'Lib', 1, 1, 2);
461
        $lib2 = $generator->create_library_record('Library', 'Lib', 1, 1, 4);
462
        $lib3 = $generator->create_library_record('Library', 'Lib', 1, 1, 3);
463
 
464
        $expected = "{$CFG->wwwroot}/pluginfile.php/1/core_h5p/libraries/{$lib2->id}/Library-1.1/library.json";
465
 
466
        // Get the URL of a file from an existing library. The provided folder name is parsable.
467
        $actual = $this->framework->getLibraryFileUrl('Library-1.1', 'library.json');
468
 
469
        // Make sure the proper URL (from the latest library patch) is returned.
470
        $this->assertEquals($expected, $actual);
471
    }
472
 
473
    /**
474
     * Test the behaviour of getLibraryFileUrl() when requesting a file URL from a sub-folder
475
     * of an existing library and the folder name is parsable.
476
     **/
11 efrain 477
    public function test_getLibraryFileUrl_library_subfolder(): void {
1 efrain 478
        global $CFG;
479
 
480
        $this->resetAfterTest();
481
 
482
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
483
        // Create a library record.
484
        $lib = $generator->create_library_record('Library', 'Lib', 1, 1);
485
 
486
        $expected = "{$CFG->wwwroot}/pluginfile.php/1/core_h5p/libraries/{$lib->id}/Library-1.1/css/example.css";
487
 
488
        // Get the URL of a file from a sub-folder from an existing library. The provided folder name is parsable.
489
        $actual = $this->framework->getLibraryFileUrl('Library-1.1/css', 'example.css');
490
 
491
        // Make sure the proper URL is returned.
492
        $this->assertEquals($expected, $actual);
493
    }
494
 
495
    /**
496
     * Test the behaviour of loadAddons().
497
     */
11 efrain 498
    public function test_loadAddons(): void {
1 efrain 499
        $this->resetAfterTest();
500
 
501
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
502
 
503
        // Create a Library addon (1.1).
504
        $generator->create_library_record('Library', 'Lib', 1, 1, 2,
505
            '', '/regex1/');
506
        // Create a Library addon (1.3).
507
        $generator->create_library_record('Library', 'Lib', 1, 3, 2,
508
            '', '/regex2/');
509
        // Create a Library addon (1.2).
510
        $generator->create_library_record('Library', 'Lib', 1, 2, 2,
511
            '', '/regex3/');
512
        // Create a Library1 addon (1.2)
513
        $generator->create_library_record('Library1', 'Lib1', 1, 2, 2,
514
            '', '/regex11/');
515
 
516
        // Load the latest version of each addon.
517
        $addons = $this->framework->loadAddons();
518
 
519
        // The addons array should return 2 results (Library and Library1 addon).
520
        $this->assertCount(2, $addons);
521
 
522
        // Ensure the addons array is consistently ordered before asserting their contents.
523
        core_collator::asort_array_of_arrays_by_key($addons, 'machineName');
524
        [$addonone, $addontwo] = array_values($addons);
525
 
526
        // Make sure the version 1.3 is the latest 'Library' addon version.
527
        $this->assertEquals('Library', $addonone['machineName']);
528
        $this->assertEquals(1, $addonone['majorVersion']);
529
        $this->assertEquals(3, $addonone['minorVersion']);
530
 
531
        // Make sure the version 1.2 is the latest 'Library1' addon version.
532
        $this->assertEquals('Library1', $addontwo['machineName']);
533
        $this->assertEquals(1, $addontwo['majorVersion']);
534
        $this->assertEquals(2, $addontwo['minorVersion']);
535
    }
536
 
537
    /**
538
     * Test the behaviour of loadLibraries().
539
     */
11 efrain 540
    public function test_loadLibraries(): void {
1 efrain 541
        $this->resetAfterTest();
542
 
543
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
544
 
545
        // Generate h5p related data.
546
        $generator->generate_h5p_data();
547
 
548
        // Load all libraries.
549
        $libraries = $this->framework->loadLibraries();
550
 
551
        // Make sure all libraries are returned.
552
        $this->assertNotEmpty($libraries);
553
        $this->assertCount(6, $libraries);
554
        $this->assertEquals('MainLibrary', $libraries['MainLibrary'][0]->machine_name);
555
        $this->assertEquals('1', $libraries['MainLibrary'][0]->major_version);
556
        $this->assertEquals('0', $libraries['MainLibrary'][0]->minor_version);
557
        $this->assertEquals('1', $libraries['MainLibrary'][0]->patch_version);
558
    }
559
 
560
    /**
561
     * Test the behaviour of test_getLibraryId() when requesting an existing machine name.
562
     */
11 efrain 563
    public function test_getLibraryId_existing_machine_name(): void {
1 efrain 564
        $this->resetAfterTest();
565
 
566
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
567
 
568
        // Create a library.
569
        $lib = $generator->create_library_record('Library', 'Lib', 1, 1, 2);
570
 
571
        // Request the library ID of the library with machine name 'Library'.
572
        $libraryid = $this->framework->getLibraryId('Library');
573
 
574
        // Make sure the library ID is being returned.
575
        $this->assertNotFalse($libraryid);
576
        $this->assertEquals($lib->id, $libraryid);
577
    }
578
 
579
    /**
580
     * Test the behaviour of test_getLibraryId() when requesting a non-existent machine name.
581
     */
11 efrain 582
    public function test_getLibraryId_non_existent_machine_name(): void {
1 efrain 583
        $this->resetAfterTest();
584
 
585
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
586
 
587
        // Create a library.
588
        $generator->create_library_record('Library', 'Lib', 1, 1, 2);
589
 
590
        // Request the library ID of the library with machinename => 'TestLibrary' (non-existent).
591
        $libraryid = $this->framework->getLibraryId('TestLibrary');
592
 
593
        // Make sure the library ID not being returned.
594
        $this->assertFalse($libraryid);
595
    }
596
 
597
    /**
598
     * Test the behaviour of test_getLibraryId() when requesting a non-existent major version.
599
     */
11 efrain 600
    public function test_getLibraryId_non_existent_major_version(): void {
1 efrain 601
        $this->resetAfterTest();
602
 
603
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
604
 
605
        // Create a library.
606
        $generator->create_library_record('Library', 'Lib', 1, 1, 2);
607
 
608
        // Request the library ID of the library with machine name => 'Library', majorversion => 2 (non-existent).
609
        $libraryid = $this->framework->getLibraryId('Library', 2);
610
 
611
        // Make sure the library ID not being returned.
612
        $this->assertFalse($libraryid);
613
    }
614
 
615
    /**
616
     * Test the behaviour of test_getLibraryId() when requesting a non-existent minor version.
617
     */
11 efrain 618
    public function test_getLibraryId_non_existent_minor_version(): void {
1 efrain 619
        $this->resetAfterTest();
620
 
621
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
622
 
623
        // Create a library.
624
        $generator->create_library_record('Library', 'Lib', 1, 1, 2);
625
 
626
        // Request the library ID of the library with machine name => 'Library',
627
        // majorversion => 1,  minorversion => 2 (non-existent).
628
        $libraryid = $this->framework->getLibraryId('Library', 1, 2);
629
 
630
        // Make sure the library ID not being returned.
631
        $this->assertFalse($libraryid);
632
    }
633
 
634
    /**
635
     * Test the behaviour of isPatchedLibrary().
636
     *
637
     * @dataProvider isPatchedLibrary_provider
638
     * @param array $libraryrecords Array containing data for the library creation
639
     * @param array $testlibrary Array containing the test library data
640
     * @param bool $expected The expectation whether the library is patched or not
641
     **/
642
    public function test_isPatchedLibrary(array $libraryrecords, array $testlibrary, bool $expected): void {
643
        $this->resetAfterTest();
644
 
645
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
646
 
647
        foreach ($libraryrecords as $library) {
648
            call_user_func_array([$generator, 'create_library_record'], $library);
649
        }
650
 
651
        $this->assertEquals($expected, $this->framework->isPatchedLibrary($testlibrary));
652
    }
653
 
654
    /**
655
     * Data provider for test_isPatchedLibrary().
656
     *
657
     * @return array
658
     */
1441 ariadna 659
    public static function isPatchedLibrary_provider(): array {
1 efrain 660
        return [
661
            'Unpatched library. No different versioning' => [
662
                [
663
                    ['TestLibrary', 'Test', 1, 1, 2],
664
                ],
665
                [
666
                    'machineName' => 'TestLibrary',
667
                    'majorVersion' => 1,
668
                    'minorVersion' => 1,
669
                    'patchVersion' => 2
670
                ],
671
                false,
672
            ],
673
            'Major version identical; Minor version identical; Patch version newer' => [
674
                [
675
                    ['TestLibrary', 'Test', 1, 1, 2],
676
                ],
677
                [
678
                    'machineName' => 'TestLibrary',
679
                    'majorVersion' => 1,
680
                    'minorVersion' => 1,
681
                    'patchVersion' => 3
682
                ],
683
                true,
684
            ],
685
            'Major version identical; Minor version newer; Patch version newer' => [
686
                [
687
                    ['TestLibrary', 'Test', 1, 1, 2],
688
                ],
689
                [
690
                    'machineName' => 'TestLibrary',
691
                    'majorVersion' => 1,
692
                    'minorVersion' => 2,
693
                    'patchVersion' => 3
694
                ],
695
                false,
696
            ],
697
            'Major version identical; Minor version identical; Patch version older' => [
698
                [
699
                    ['TestLibrary', 'Test', 1, 1, 2],
700
                ],
701
                [
702
                    'machineName' => 'TestLibrary',
703
                    'majorVersion' => 1,
704
                    'minorVersion' => 1,
705
                    'patchVersion' => 1
706
                ],
707
                false,
708
            ],
709
            'Major version identical; Minor version newer; Patch version older' => [
710
                [
711
                    ['TestLibrary', 'Test', 1, 1, 2],
712
                ],
713
                [
714
                    'machineName' => 'TestLibrary',
715
                    'majorVersion' => 1,
716
                    'minorVersion' => 2,
717
                    'patchVersion' => 1
718
                ],
719
                false,
720
            ],
721
            'Major version newer; Minor version identical; Patch version older' => [
722
                [
723
                    ['TestLibrary', 'Test', 1, 1, 2],
724
                ],
725
                [
726
                    'machineName' => 'TestLibrary',
727
                    'majorVersion' => 2,
728
                    'minorVersion' => 1,
729
                    'patchVersion' => 1
730
                ],
731
                false,
732
            ],
733
            'Major version newer; Minor version identical; Patch version newer' => [
734
                [
735
                    ['TestLibrary', 'Test', 1, 1, 2],
736
                ],
737
                [
738
                    'machineName' => 'TestLibrary',
739
                    'majorVersion' => 2,
740
                    'minorVersion' => 1,
741
                    'patchVersion' => 3
742
                ],
743
                false,
744
            ],
745
 
746
            'Major version older; Minor version identical; Patch version older' => [
747
                [
748
                    ['TestLibrary', 'Test', 1, 1, 2],
749
                ],
750
                [
751
                    'machineName' => 'TestLibrary',
752
                    'majorVersion' => 0,
753
                    'minorVersion' => 1,
754
                    'patchVersion' => 1
755
                ],
756
                false,
757
            ],
758
            'Major version older; Minor version identical; Patch version newer' => [
759
                [
760
                    ['TestLibrary', 'Test', 1, 1, 2],
761
                ],
762
                [
763
                    'machineName' => 'TestLibrary',
764
                    'majorVersion' => 0,
765
                    'minorVersion' => 1,
766
                    'patchVersion' => 3
767
                ],
768
                false,
769
            ],
770
        ];
771
    }
772
 
773
    /**
774
     * Test the behaviour of isInDevMode().
775
     */
11 efrain 776
    public function test_isInDevMode(): void {
1 efrain 777
        $isdevmode = $this->framework->isInDevMode();
778
 
779
        $this->assertFalse($isdevmode);
780
    }
781
 
782
    /**
783
     * Test the behaviour of mayUpdateLibraries().
784
     */
785
    public function test_mayUpdateLibraries(): void {
786
        global $DB;
787
 
788
        $this->resetAfterTest();
789
 
790
        // Create some users.
791
        $contextsys = \context_system::instance();
792
        $user = $this->getDataGenerator()->create_user();
793
        $admin = get_admin();
794
        $managerrole = $DB->get_record('role', ['shortname' => 'manager'], '*', MUST_EXIST);
795
        $studentrole = $DB->get_record('role', ['shortname' => 'student'], '*', MUST_EXIST);
796
        $manager = $this->getDataGenerator()->create_user();
797
        role_assign($managerrole->id, $manager->id, $contextsys);
798
 
799
        // Create a course with a label and enrol the user.
800
        $course = $this->getDataGenerator()->create_course();
801
        $label = $this->getDataGenerator()->create_module('label', ['course' => $course->id]);
802
        list(, $labelcm) = get_course_and_cm_from_instance($label->id, 'label');
803
        $contextlabel = \context_module::instance($labelcm->id);
804
        $this->getDataGenerator()->enrol_user($user->id, $course->id, 'student');
805
 
806
        // Create the .h5p file.
1441 ariadna 807
        $path = self::get_fixture_path(__NAMESPACE__, 'h5ptest.zip');
1 efrain 808
 
809
        // Admin and manager should have permission to update libraries.
810
        $file = helper::create_fake_stored_file_from_path($path, $admin->id, $contextsys);
811
        $this->framework->set_file($file);
812
        $mayupdatelib = $this->framework->mayUpdateLibraries();
813
        $this->assertTrue($mayupdatelib);
814
 
815
        $file = helper::create_fake_stored_file_from_path($path, $manager->id, $contextsys);
816
        $this->framework->set_file($file);
817
        $mayupdatelib = $this->framework->mayUpdateLibraries();
818
        $this->assertTrue($mayupdatelib);
819
 
820
        // By default, normal user hasn't permission to update libraries (in both contexts, system and module label).
821
        $file = helper::create_fake_stored_file_from_path($path, $user->id, $contextsys);
822
        $this->framework->set_file($file);
823
        $mayupdatelib = $this->framework->mayUpdateLibraries();
824
        $this->assertFalse($mayupdatelib);
825
 
826
        $file = helper::create_fake_stored_file_from_path($path, $user->id, $contextlabel);
827
        $this->framework->set_file($file);
828
        $mayupdatelib = $this->framework->mayUpdateLibraries();
829
        $this->assertFalse($mayupdatelib);
830
 
831
        // If the current user (admin) can update libraries, the method should return true (even if the file userid hasn't the
832
        // required capabilility in the file context).
833
        $file = helper::create_fake_stored_file_from_path($path, $admin->id, $contextlabel);
834
        $this->framework->set_file($file);
835
        $mayupdatelib = $this->framework->mayUpdateLibraries();
836
        $this->assertTrue($mayupdatelib);
837
 
838
        // If the update capability is assigned to the user, they should be able to update the libraries (only in the context
839
        // where the capability has been assigned).
840
        $file = helper::create_fake_stored_file_from_path($path, $user->id, $contextlabel);
841
        $this->framework->set_file($file);
842
        $mayupdatelib = $this->framework->mayUpdateLibraries();
843
        $this->assertFalse($mayupdatelib);
844
        assign_capability('moodle/h5p:updatelibraries', CAP_ALLOW, $studentrole->id, $contextlabel);
845
        $mayupdatelib = $this->framework->mayUpdateLibraries();
846
        $this->assertTrue($mayupdatelib);
847
        $file = helper::create_fake_stored_file_from_path($path, $user->id, $contextsys);
848
        $this->framework->set_file($file);
849
        $mayupdatelib = $this->framework->mayUpdateLibraries();
850
        $this->assertFalse($mayupdatelib);
851
    }
852
 
853
    /**
854
     * Test the behaviour of get_file() and set_file().
855
     */
856
    public function test_get_file(): void {
857
        $this->resetAfterTest();
858
 
859
        // Create some users.
860
        $contextsys = \context_system::instance();
861
        $user = $this->getDataGenerator()->create_user();
862
 
863
        // The H5P file.
1441 ariadna 864
        $path = self::get_fixture_path(__NAMESPACE__, 'h5ptest.zip');
1 efrain 865
 
866
        // An error should be raised when it's called before initialitzing it.
867
        $this->expectException('coding_exception');
868
        $this->expectExceptionMessage('Using get_file() before file is set');
869
        $this->framework->get_file();
870
 
871
        // Check the value when only path and user are set.
872
        $file = helper::create_fake_stored_file_from_path($path, $user->id);
873
        $this->framework->set_file($file);
874
        $file = $this->framework->get_file();
875
        $this->assertEquals($user->id, $$file->get_userid());
876
        $this->assertEquals($contextsys->id, $file->get_contextid());
877
 
878
        // Check the value when also the context is set.
879
        $course = $this->getDataGenerator()->create_course();
880
        $contextcourse = \context_course::instance($course->id);
881
        $file = helper::create_fake_stored_file_from_path($path, $user->id, $contextcourse);
882
        $this->framework->set_file($file);
883
        $file = $this->framework->get_file();
884
        $this->assertEquals($user->id, $$file->get_userid());
885
        $this->assertEquals($contextcourse->id, $file->get_contextid());
886
    }
887
 
888
    /**
889
     * Test the behaviour of saveLibraryData() when saving data for a new library.
890
     */
11 efrain 891
    public function test_saveLibraryData_new_library(): void {
1 efrain 892
        global $DB;
893
 
894
        $this->resetAfterTest();
895
 
896
        $librarydata = array(
897
            'title' => 'Test',
898
            'machineName' => 'TestLibrary',
899
            'majorVersion' => '1',
900
            'minorVersion' => '0',
901
            'patchVersion' => '2',
902
            'runnable' => 1,
903
            'fullscreen' => 1,
904
            'preloadedJs' => array(
905
                array(
906
                    'path' => 'js/name.min.js'
907
                )
908
            ),
909
            'preloadedCss' => array(
910
                array(
911
                    'path' => 'css/name.css'
912
                )
913
            ),
914
            'dropLibraryCss' => array(
915
                array(
916
                    'machineName' => 'Name2'
917
                )
918
            )
919
        );
920
 
921
        // Create a new library.
922
        $this->framework->saveLibraryData($librarydata);
923
 
924
        $library = $DB->get_record('h5p_libraries', ['machinename' => $librarydata['machineName']]);
925
 
926
        // Make sure the library data was properly saved.
927
        $this->assertNotEmpty($library);
928
        $this->assertNotEmpty($librarydata['libraryId']);
929
        $this->assertEquals($librarydata['title'], $library->title);
930
        $this->assertEquals($librarydata['machineName'], $library->machinename);
931
        $this->assertEquals($librarydata['majorVersion'], $library->majorversion);
932
        $this->assertEquals($librarydata['minorVersion'], $library->minorversion);
933
        $this->assertEquals($librarydata['patchVersion'], $library->patchversion);
934
        $this->assertEquals($librarydata['preloadedJs'][0]['path'], $library->preloadedjs);
935
        $this->assertEquals($librarydata['preloadedCss'][0]['path'], $library->preloadedcss);
936
        $this->assertEquals($librarydata['dropLibraryCss'][0]['machineName'], $library->droplibrarycss);
937
    }
938
 
939
    /**
940
     * Test the behaviour of saveLibraryData() when saving (updating) data for an existing library.
941
     */
11 efrain 942
    public function test_saveLibraryData_existing_library(): void {
1 efrain 943
        global $DB;
944
 
945
        $this->resetAfterTest();
946
 
947
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
948
 
949
        // Create a library record.
950
        $library = $generator->create_library_record('TestLibrary', 'Test', 1, 0, 2);
951
 
952
        $librarydata = array(
953
            'libraryId' => $library->id,
954
            'title' => 'Test1',
955
            'machineName' => 'TestLibrary',
956
            'majorVersion' => '1',
957
            'minorVersion' => '2',
958
            'patchVersion' => '2',
959
            'runnable' => 1,
960
            'fullscreen' => 1,
961
            'preloadedJs' => array(
962
                array(
963
                    'path' => 'js/name.min.js'
964
                )
965
            ),
966
            'preloadedCss' => array(
967
                array(
968
                    'path' => 'css/name.css'
969
                )
970
            ),
971
            'dropLibraryCss' => array(
972
                array(
973
                    'machineName' => 'Name2'
974
                )
975
            )
976
        );
977
 
978
        // Update the library.
979
        $this->framework->saveLibraryData($librarydata, false);
980
 
981
        $library = $DB->get_record('h5p_libraries', ['machinename' => $librarydata['machineName']]);
982
 
983
        // Make sure the library data was properly updated.
984
        $this->assertNotEmpty($library);
985
        $this->assertNotEmpty($librarydata['libraryId']);
986
        $this->assertEquals($librarydata['title'], $library->title);
987
        $this->assertEquals($librarydata['machineName'], $library->machinename);
988
        $this->assertEquals($librarydata['majorVersion'], $library->majorversion);
989
        $this->assertEquals($librarydata['minorVersion'], $library->minorversion);
990
        $this->assertEquals($librarydata['patchVersion'], $library->patchversion);
991
        $this->assertEquals($librarydata['preloadedJs'][0]['path'], $library->preloadedjs);
992
        $this->assertEquals($librarydata['preloadedCss'][0]['path'], $library->preloadedcss);
993
        $this->assertEquals($librarydata['dropLibraryCss'][0]['machineName'], $library->droplibrarycss);
994
    }
995
 
996
    /**
997
     * Test the behaviour of insertContent().
998
     */
11 efrain 999
    public function test_insertContent(): void {
1 efrain 1000
        global $DB;
1001
 
1002
        $this->resetAfterTest();
1003
 
1004
        $content = array(
1005
            'params' => json_encode(['param1' => 'Test']),
1006
            'library' => array(
1007
                'libraryId' => 1
1008
            ),
1009
            'disable' => 8
1010
        );
1011
 
1012
        // Insert h5p content.
1013
        $contentid = $this->framework->insertContent($content);
1014
 
1015
        // Get the entered content from the db.
1016
        $dbcontent = $DB->get_record('h5p', ['id' => $contentid]);
1017
 
1018
        // Make sure the h5p content was properly inserted.
1019
        $this->assertNotEmpty($dbcontent);
1020
        $this->assertEquals($content['params'], $dbcontent->jsoncontent);
1021
        $this->assertEquals($content['library']['libraryId'], $dbcontent->mainlibraryid);
1022
        $this->assertEquals($content['disable'], $dbcontent->displayoptions);
1023
    }
1024
 
1025
    /**
1026
     * Test the behaviour of insertContent().
1027
     */
11 efrain 1028
    public function test_insertContent_latestlibrary(): void {
1 efrain 1029
        global $DB;
1030
 
1031
        $this->resetAfterTest();
1032
 
1033
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1034
        // Create a library record.
1035
        $lib = $generator->create_library_record('TestLibrary', 'Test', 1, 1, 2);
1036
 
1037
        $content = array(
1038
            'params' => json_encode(['param1' => 'Test']),
1039
            'library' => array(
1040
                'libraryId' => 0,
1041
                'machineName' => 'TestLibrary',
1042
            ),
1043
            'disable' => 8
1044
        );
1045
 
1046
        // Insert h5p content.
1047
        $contentid = $this->framework->insertContent($content);
1048
 
1049
        // Get the entered content from the db.
1050
        $dbcontent = $DB->get_record('h5p', ['id' => $contentid]);
1051
 
1052
        // Make sure the h5p content was properly inserted.
1053
        $this->assertNotEmpty($dbcontent);
1054
        $this->assertEquals($content['params'], $dbcontent->jsoncontent);
1055
        $this->assertEquals($content['disable'], $dbcontent->displayoptions);
1056
        // As the libraryId was empty, the latest library has been used.
1057
        $this->assertEquals($lib->id, $dbcontent->mainlibraryid);
1058
    }
1059
 
1060
    /**
1061
     * Test the behaviour of updateContent().
1062
     */
11 efrain 1063
    public function test_updateContent(): void {
1 efrain 1064
        global $DB;
1065
 
1066
        $this->resetAfterTest();
1067
 
1068
        /** @var \core_h5p_generator $generator */
1069
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1070
 
1071
        // Create a library record.
1072
        $lib = $generator->create_library_record('TestLibrary', 'Test', 1, 1, 2);
1073
 
1074
        // Create an h5p content with 'TestLibrary' as it's main library.
1075
        $contentid = $generator->create_h5p_record($lib->id);
1076
 
1077
        $content = array(
1078
            'id' => $contentid,
1079
            'params' => json_encode(['param2' => 'Test2']),
1080
            'library' => array(
1081
                'libraryId' => $lib->id
1082
            ),
1083
            'disable' => 8
1084
        );
1085
 
1086
        // Update the h5p content.
1087
        $this->framework->updateContent($content);
1088
 
1089
        $h5pcontent = $DB->get_record('h5p', ['id' => $contentid]);
1090
 
1091
        // Make sure the h5p content was properly updated.
1092
        $this->assertNotEmpty($h5pcontent);
1093
        $this->assertNotEmpty($h5pcontent->pathnamehash);
1094
        $this->assertNotEmpty($h5pcontent->contenthash);
1095
        $this->assertEquals($content['params'], $h5pcontent->jsoncontent);
1096
        $this->assertEquals($content['library']['libraryId'], $h5pcontent->mainlibraryid);
1097
        $this->assertEquals($content['disable'], $h5pcontent->displayoptions);
1098
    }
1099
 
1100
    /**
1101
     * Test the behaviour of updateContent() with metadata.
1102
     */
1103
    public function test_updateContent_withmetadata(): void {
1104
        global $DB;
1105
 
1106
        $this->resetAfterTest();
1107
 
1108
        /** @var \core_h5p_generator $generator */
1109
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1110
 
1111
        // Create a library record.
1112
        $lib = $generator->create_library_record('TestLibrary', 'Test', 1, 1, 2);
1113
 
1114
        // Create an h5p content with 'TestLibrary' as it's main library.
1115
        $contentid = $generator->create_h5p_record($lib->id);
1116
 
1117
        $params = ['param2' => 'Test2'];
1118
        $metadata = [
1119
            'license' => 'CC BY',
1120
            'licenseVersion' => '4.0',
1121
            'yearFrom' => 2000,
1122
            'yearTo' => 2023,
1123
            'defaultLanguage' => 'ca',
1124
        ];
1125
        $content = [
1126
            'id' => $contentid,
1127
            'params' => json_encode($params),
1128
            'library' => [
1129
                'libraryId' => $lib->id,
1130
            ],
1131
            'disable' => 8,
1132
            'metadata' => $metadata,
1133
        ];
1134
 
1135
        // Update the h5p content.
1136
        $this->framework->updateContent($content);
1137
 
1138
        $h5pcontent = $DB->get_record('h5p', ['id' => $contentid]);
1139
 
1140
        // Make sure the h5p content was properly updated.
1141
        $this->assertNotEmpty($h5pcontent);
1142
        $this->assertNotEmpty($h5pcontent->pathnamehash);
1143
        $this->assertNotEmpty($h5pcontent->contenthash);
1144
        $this->assertEquals(json_encode(array_merge($params, ['metadata' => $metadata])), $h5pcontent->jsoncontent);
1145
        $this->assertEquals($content['library']['libraryId'], $h5pcontent->mainlibraryid);
1146
        $this->assertEquals($content['disable'], $h5pcontent->displayoptions);
1147
    }
1148
 
1149
    /**
1150
     * Test the behaviour of saveLibraryDependencies().
1151
     */
11 efrain 1152
    public function test_saveLibraryDependencies(): void {
1 efrain 1153
        global $DB;
1154
 
1155
        $this->resetAfterTest();
1156
 
1157
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1158
 
1159
        // Create a library 'Library'.
1160
        $library = $generator->create_library_record('Library', 'Title');
1161
        // Create a library 'DependencyLibrary1'.
1162
        $dependency1 = $generator->create_library_record('DependencyLibrary1', 'DependencyTitle1');
1163
        // Create a library 'DependencyLibrary2'.
1164
        $dependency2 = $generator->create_library_record('DependencyLibrary2', 'DependencyTitle2');
1165
 
1166
        $dependencies = array(
1167
            array(
1168
                'machineName' => $dependency1->machinename,
1169
                'majorVersion' => $dependency1->majorversion,
1170
                'minorVersion' => $dependency1->minorversion
1171
            ),
1172
            array(
1173
                'machineName' => $dependency2->machinename,
1174
                'majorVersion' => $dependency2->majorversion,
1175
                'minorVersion' => $dependency2->minorversion
1176
            ),
1177
        );
1178
 
1179
        // Set 'DependencyLibrary1' and 'DependencyLibrary2' as library dependencies of 'Library'.
1180
        $this->framework->saveLibraryDependencies($library->id, $dependencies, 'preloaded');
1181
 
1182
        $libdependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library->id], 'id ASC');
1183
 
1184
        // Make sure the library dependencies for 'Library' are properly set.
1185
        $this->assertEquals(2, count($libdependencies));
1186
        $this->assertEquals($dependency1->id, reset($libdependencies)->requiredlibraryid);
1187
        $this->assertEquals($dependency2->id, end($libdependencies)->requiredlibraryid);
1188
    }
1189
 
1190
    /**
1191
     * Test the behaviour of deleteContentData().
1192
     */
11 efrain 1193
    public function test_deleteContentData(): void {
1 efrain 1194
        global $DB;
1195
 
1196
        $this->resetAfterTest();
1197
 
1198
        /** @var \core_h5p_generator $generator */
1199
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1200
        // For the mod_h5pactivity component, the activity needs to be created too.
1201
        $course = $this->getDataGenerator()->create_course();
1202
        $user = $this->getDataGenerator()->create_and_enrol($course, 'student');
1203
        $this->setUser($user);
1204
        $activity = $this->getDataGenerator()->create_module('h5pactivity', ['course' => $course]);
1205
        $activitycontext = \context_module::instance($activity->cmid);
1206
        $filerecord = [
1207
            'contextid' => $activitycontext->id,
1208
            'component' => 'mod_h5pactivity',
1209
            'filearea' => 'package',
1210
            'itemid' => 0,
1211
            'filepath' => '/',
1212
            'filename' => 'dummy.h5p',
1213
            'addxapistate' => true,
1214
        ];
1215
 
1216
        // Generate some h5p related data.
1217
        $data = $generator->generate_h5p_data(false, $filerecord);
1218
        $h5pid = $data->h5pcontent->h5pid;
1219
 
1220
        // Make sure the particular h5p content exists in the DB.
1221
        $this->assertNotEmpty($DB->get_record('h5p', ['id' => $h5pid]));
1222
        // Make sure the content libraries exists in the DB.
1223
        $this->assertCount(5, $DB->get_records('h5p_contents_libraries', ['h5pid' => $h5pid]));
1224
        // Make sure the particular xAPI state exists in the DB.
1225
        $records = $DB->get_records('xapi_states');
1226
        $record = reset($records);
1227
        $this->assertCount(1, $records);
1228
        $this->assertNotNull($record->statedata);
1229
 
1230
        // Delete the h5p content and it's related data.
1231
        $this->framework->deleteContentData($h5pid);
1232
 
1233
        // The particular h5p content should no longer exist in the db.
1234
        $this->assertEmpty($DB->get_record('h5p', ['id' => $h5pid]));
1235
        // The particular content libraries should no longer exist in the db.
1236
        $this->assertEmpty($DB->get_record('h5p_contents_libraries', ['h5pid' => $h5pid]));
1237
        // The xAPI state should be reseted.
1238
        $records = $DB->get_records('xapi_states');
1239
        $record = reset($records);
1240
        $this->assertCount(1, $records);
1241
        $this->assertNull($record->statedata);
1242
    }
1243
 
1244
    /**
1245
     * Test the behaviour of resetContentUserData().
1246
     */
11 efrain 1247
    public function test_resetContentUserData(): void {
1 efrain 1248
        global $DB;
1249
 
1250
        $this->resetAfterTest();
1251
 
1252
        /** @var \core_h5p_generator $generator */
1253
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1254
        // For the mod_h5pactivity component, the activity needs to be created too.
1255
        $course = $this->getDataGenerator()->create_course();
1256
        $user = $this->getDataGenerator()->create_and_enrol($course, 'student');
1257
        $this->setUser($user);
1258
        $activity = $this->getDataGenerator()->create_module('h5pactivity', ['course' => $course]);
1259
        $activitycontext = \context_module::instance($activity->cmid);
1260
        $filerecord = [
1261
            'contextid' => $activitycontext->id,
1262
            'component' => 'mod_h5pactivity',
1263
            'filearea' => 'package',
1264
            'itemid' => 0,
1265
            'filepath' => '/',
1266
            'filename' => 'dummy.h5p',
1267
            'addxapistate' => true,
1268
        ];
1269
 
1270
        // Generate some h5p related data.
1271
        $data = $generator->generate_h5p_data(false, $filerecord);
1272
        $h5pid = $data->h5pcontent->h5pid;
1273
 
1274
        // Make sure the H5P content, libraries and xAPI state exist in the DB.
1275
        $this->assertNotEmpty($DB->get_record('h5p', ['id' => $h5pid]));
1276
        $this->assertCount(5, $DB->get_records('h5p_contents_libraries', ['h5pid' => $h5pid]));
1277
        $records = $DB->get_records('xapi_states');
1278
        $record = reset($records);
1279
        $this->assertCount(1, $records);
1280
        $this->assertNotNull($record->statedata);
1281
 
1282
        // Reset the user data associated to this H5P content.
1283
        $this->framework->resetContentUserData($h5pid);
1284
 
1285
        // The H5P content should still exist in the db.
1286
        $this->assertNotEmpty($DB->get_record('h5p', ['id' => $h5pid]));
1287
        // The particular content libraries should still exist in the db.
1288
        $this->assertCount(5, $DB->get_records('h5p_contents_libraries', ['h5pid' => $h5pid]));
1289
        // The xAPI state should still exist in the db, but should be reset.
1290
        $records = $DB->get_records('xapi_states');
1291
        $record = reset($records);
1292
        $this->assertCount(1, $records);
1293
        $this->assertNull($record->statedata);
1294
    }
1295
 
1296
    /**
1297
     * Test the behaviour of deleteLibraryUsage().
1298
     */
11 efrain 1299
    public function test_deleteLibraryUsage(): void {
1 efrain 1300
        global $DB;
1301
 
1302
        $this->resetAfterTest();
1303
 
1304
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1305
 
1306
        // Generate some h5p related data.
1307
        $data = $generator->generate_h5p_data();
1308
        $h5pid = $data->h5pcontent->h5pid;
1309
 
1310
        // Get the h5p content libraries from the DB.
1311
        $h5pcontentlibraries = $DB->get_records('h5p_contents_libraries', ['h5pid' => $h5pid]);
1312
 
1313
        // The particular h5p content should have 5 content libraries.
1314
        $this->assertNotEmpty($h5pcontentlibraries);
1315
        $this->assertCount(5, $h5pcontentlibraries);
1316
 
1317
        // Delete the h5p content and it's related data.
1318
        $this->framework->deleteLibraryUsage($h5pid);
1319
 
1320
        // Get the h5p content libraries from the DB.
1321
        $h5pcontentlibraries = $DB->get_record('h5p_contents_libraries', ['h5pid' => $h5pid]);
1322
 
1323
        // The particular h5p content libraries should no longer exist in the db.
1324
        $this->assertEmpty($h5pcontentlibraries);
1325
    }
1326
 
1327
    /**
1328
     * Test the behaviour of test_saveLibraryUsage().
1329
     */
11 efrain 1330
    public function test_saveLibraryUsage(): void {
1 efrain 1331
        global $DB;
1332
 
1333
        $this->resetAfterTest();
1334
 
1335
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1336
 
1337
        // Create a library 'Library'.
1338
        $library = $generator->create_library_record('Library', 'Title');
1339
        // Create a library 'DependencyLibrary1'.
1340
        $dependency1 = $generator->create_library_record('DependencyLibrary1', 'DependencyTitle1');
1341
        // Create a library 'DependencyLibrary2'.
1342
        $dependency2 = $generator->create_library_record('DependencyLibrary2', 'DependencyTitle2');
1343
        // Create an h5p content with 'Library' as it's main library.
1344
        $contentid = $generator->create_h5p_record($library->id);
1345
 
1346
        $dependencies = array(
1347
            array(
1348
                'library' => array(
1349
                    'libraryId' => $dependency1->id,
1350
                    'machineName' => $dependency1->machinename,
1351
                    'dropLibraryCss' => $dependency1->droplibrarycss
1352
                ),
1353
                'type' => 'preloaded',
1354
                'weight' => 1
1355
            ),
1356
            array(
1357
                'library' => array(
1358
                    'libraryId' => $dependency2->id,
1359
                    'machineName' => $dependency2->machinename,
1360
                    'dropLibraryCss' => $dependency2->droplibrarycss
1361
                ),
1362
                'type' => 'preloaded',
1363
                'weight' => 2
1364
            ),
1365
        );
1366
 
1367
        // Save 'DependencyLibrary1' and 'DependencyLibrary2' as h5p content libraries.
1368
        $this->framework->saveLibraryUsage($contentid, $dependencies);
1369
 
1370
        // Get the h5p content libraries from the DB.
1371
        $libdependencies = $DB->get_records('h5p_contents_libraries', ['h5pid' => $contentid], 'id ASC');
1372
 
1373
        // Make sure that 'DependencyLibrary1' and 'DependencyLibrary2' are properly set as h5p content libraries.
1374
        $this->assertEquals(2, count($libdependencies));
1375
        $this->assertEquals($dependency1->id, reset($libdependencies)->libraryid);
1376
        $this->assertEquals($dependency2->id, end($libdependencies)->libraryid);
1377
    }
1378
 
1379
    /**
1380
     * Test the behaviour of getLibraryUsage() without skipping a particular h5p content.
1381
     */
11 efrain 1382
    public function test_getLibraryUsage_no_skip_content(): void {
1 efrain 1383
        $this->resetAfterTest();
1384
 
1385
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1386
 
1387
        // Generate h5p related data.
1388
        $generateddata = $generator->generate_h5p_data();
1389
        // The Id of the library 'Library1'.
1390
        $library1id = $generateddata->lib1->data->id;
1391
        // The Id of the library 'Library2'.
1392
        $library2id = $generateddata->lib2->data->id;
1393
        // The Id of the library 'Library5'.
1394
        $library5id = $generateddata->lib5->data->id;
1395
 
1396
        // Get the library usage for 'Library1' (do not skip content).
1397
        $data = $this->framework->getLibraryUsage($library1id);
1398
 
1399
        $expected = array(
1400
            'content' => 1,
1401
            'libraries' => 1
1402
        );
1403
 
1404
        // Make sure 'Library1' is used by 1 content and is a dependency to 1 library.
1405
        $this->assertEquals($expected, $data);
1406
 
1407
        // Get the library usage for 'Library2' (do not skip content).
1408
        $data = $this->framework->getLibraryUsage($library2id);
1409
 
1410
        $expected = array(
1411
            'content' => 1,
1412
            'libraries' => 2,
1413
        );
1414
 
1415
        // Make sure 'Library2' is used by 1 content and is a dependency to 2 libraries.
1416
        $this->assertEquals($expected, $data);
1417
 
1418
         // Get the library usage for 'Library5' (do not skip content).
1419
        $data = $this->framework->getLibraryUsage($library5id);
1420
 
1421
        $expected = array(
1422
            'content' => 0,
1423
            'libraries' => 1,
1424
        );
1425
 
1426
        // Make sure 'Library5' is not used by any content and is a dependency to 1 library.
1427
        $this->assertEquals($expected, $data);
1428
    }
1429
 
1430
    /**
1431
     * Test the behaviour of getLibraryUsage() when skipping a particular content.
1432
     */
11 efrain 1433
    public function test_getLibraryUsage_skip_content(): void {
1 efrain 1434
        $this->resetAfterTest();
1435
 
1436
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1437
 
1438
        // Generate h5p related data.
1439
        $generateddata = $generator->generate_h5p_data();
1440
        // The Id of the library 'Library1'.
1441
        $library1id = $generateddata->lib1->data->id;
1442
 
1443
        // Get the library usage for 'Library1' (skip content).
1444
        $data = $this->framework->getLibraryUsage($library1id, true);
1445
        $expected = array(
1446
            'content' => -1,
1447
            'libraries' => 1,
1448
        );
1449
 
1450
        // Make sure 'Library1' is a dependency to 1 library.
1451
        $this->assertEquals($expected, $data);
1452
    }
1453
 
1454
    /**
1455
     * Test the behaviour of loadLibrary() when requesting an existing library.
1456
     */
11 efrain 1457
    public function test_loadLibrary_existing_library(): void {
1 efrain 1458
        $this->resetAfterTest();
1459
 
1460
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1461
 
1462
        // Generate h5p related data.
1463
        $generateddata = $generator->generate_h5p_data();
1464
        // The library data of 'Library1'.
1465
        $library1 = $generateddata->lib1->data;
1466
        // The library data of 'Library5'.
1467
        $library5 = $generateddata->lib5->data;
1468
 
1469
        // The preloaded dependencies.
1470
        $preloadeddependencies = array();
1471
 
1472
        foreach ($generateddata->lib1->dependencies as $preloadeddependency) {
1473
            $preloadeddependencies[] = array(
1474
                'machineName' => $preloadeddependency->machinename,
1475
                'majorVersion' => $preloadeddependency->majorversion,
1476
                'minorVersion' => $preloadeddependency->minorversion
1477
            );
1478
        }
1479
 
1480
        // Create a dynamic dependency.
1481
        $generator->create_library_dependency_record($library1->id, $library5->id, 'dynamic');
1482
 
1483
        $dynamicdependencies[] = array(
1484
            'machineName' => $library5->machinename,
1485
            'majorVersion' => $library5->majorversion,
1486
            'minorVersion' => $library5->minorversion
1487
        );
1488
 
1489
        // Load 'Library1' data.
1490
        $data = $this->framework->loadLibrary($library1->machinename, $library1->majorversion,
1491
            $library1->minorversion);
1492
 
1493
        $expected = array(
1494
            'libraryId' => $library1->id,
1495
            'title' => $library1->title,
1496
            'machineName' => $library1->machinename,
1497
            'majorVersion' => $library1->majorversion,
1498
            'minorVersion' => $library1->minorversion,
1499
            'patchVersion' => $library1->patchversion,
1500
            'runnable' => $library1->runnable,
1501
            'fullscreen' => $library1->fullscreen,
1502
            'embedTypes' => $library1->embedtypes,
1503
            'preloadedJs' => $library1->preloadedjs,
1504
            'preloadedCss' => $library1->preloadedcss,
1505
            'dropLibraryCss' => $library1->droplibrarycss,
1506
            'semantics' => $library1->semantics,
1507
            'preloadedDependencies' => $preloadeddependencies,
1508
            'dynamicDependencies' => $dynamicdependencies
1509
        );
1510
 
1511
        // Make sure the 'Library1' data is properly loaded.
1512
        $this->assertEquals($expected, $data);
1513
    }
1514
 
1515
    /**
1516
     * Test the behaviour of loadLibrary() when requesting a non-existent library.
1517
     */
11 efrain 1518
    public function test_loadLibrary_non_existent_library(): void {
1 efrain 1519
        $this->resetAfterTest();
1520
 
1521
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1522
 
1523
        // Generate h5p related data.
1524
        $generator->generate_h5p_data();
1525
 
1526
        // Attempt to load a non-existent library.
1527
        $data = $this->framework->loadLibrary('MissingLibrary', 1, 2);
1528
 
1529
        // Make sure nothing is loaded.
1530
        $this->assertFalse($data);
1531
    }
1532
 
1533
    /**
1534
     * Test the behaviour of loadLibrarySemantics().
1535
     *
1536
     * @dataProvider loadLibrarySemantics_provider
1537
     * @param array $libraryrecords Array containing data for the library creation
1538
     * @param array $testlibrary Array containing the test library data
1539
     * @param string $expected The expected semantics value
1540
     **/
1541
    public function test_loadLibrarySemantics(array $libraryrecords, array $testlibrary, string $expected): void {
1542
        $this->resetAfterTest();
1543
 
1544
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1545
 
1546
        foreach ($libraryrecords as $library) {
1547
            call_user_func_array([$generator, 'create_library_record'], $library);
1548
        }
1549
 
1550
        $this->assertEquals($expected, $this->framework->loadLibrarySemantics(
1551
            $testlibrary['machinename'], $testlibrary['majorversion'], $testlibrary['minorversion']));
1552
    }
1553
 
1554
    /**
1555
     * Data provider for test_loadLibrarySemantics().
1556
     *
1557
     * @return array
1558
     */
1441 ariadna 1559
    public static function loadLibrarySemantics_provider(): array {
1 efrain 1560
 
1561
        $semantics = json_encode(
1562
            [
1563
                'type' => 'text',
1564
                'name' => 'text',
1565
                'label' => 'Plain text',
1566
                'description' => 'Please add some text'
1567
            ]
1568
        );
1569
 
1570
        return [
1571
            'Library with semantics' => [
1572
                [
1573
                    ['Library1', 'Lib1', 1, 1, 2, $semantics],
1574
                ],
1575
                [
1576
                    'machinename' => 'Library1',
1577
                    'majorversion' => 1,
1578
                    'minorversion' => 1
1579
                ],
1580
                $semantics,
1581
            ],
1582
            'Library without semantics' => [
1583
                [
1584
                    ['Library2', 'Lib2', 1, 2, 2, ''],
1585
                ],
1586
                [
1587
                    'machinename' => 'Library2',
1588
                    'majorversion' => 1,
1589
                    'minorversion' => 2
1590
                ],
1591
                '',
1592
            ]
1593
        ];
1594
    }
1595
 
1596
    /**
1597
     * Test the behaviour of alterLibrarySemantics().
1598
     */
11 efrain 1599
    public function test_alterLibrarySemantics(): void {
1 efrain 1600
        global $DB;
1601
 
1602
        $this->resetAfterTest();
1603
 
1604
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1605
 
1606
        $semantics = json_encode(
1607
            array(
1608
                'type' => 'text',
1609
                'name' => 'text',
1610
                'label' => 'Plain text',
1611
                'description' => 'Please add some text'
1612
            )
1613
        );
1614
 
1615
        // Create a library 'Library1' with semantics.
1616
        $library1 = $generator->create_library_record('Library1', 'Lib1', 1, 1, 2, $semantics);
1617
 
1618
        $updatedsemantics = array(
1619
            'type' => 'text',
1620
            'name' => 'updated text',
1621
            'label' => 'Updated text',
1622
            'description' => 'Please add some text'
1623
        );
1624
 
1625
        // Alter the semantics of 'Library1'.
1626
        $this->framework->alterLibrarySemantics($updatedsemantics, 'Library1', 1, 1);
1627
 
1628
        // Get the semantics of 'Library1' from the DB.
1629
        $currentsemantics = $DB->get_field('h5p_libraries', 'semantics', array('id' => $library1->id));
1630
 
1631
        // The semantics for Library1 shouldn't be updated.
1632
        $this->assertEquals($semantics, $currentsemantics);
1633
    }
1634
 
1635
    /**
1636
     * Test the behaviour of deleteLibraryDependencies() when requesting to delete the
1637
     * dependencies of an existing library.
1638
     */
11 efrain 1639
    public function test_deleteLibraryDependencies_existing_library(): void {
1 efrain 1640
        global $DB;
1641
 
1642
        $this->resetAfterTest();
1643
 
1644
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1645
 
1646
        // Generate h5p related data.
1647
        $data = $generator->generate_h5p_data();
1648
        // The data of the library 'Library1'.
1649
        $library1 = $data->lib1->data;
1650
 
1651
        // Get the dependencies of 'Library1'.
1652
        $dependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library1->id]);
1653
        // The 'Library1' should have 3 dependencies ('Library2', 'Library3', 'Library4').
1654
        $this->assertCount(3, $dependencies);
1655
 
1656
        // Delete the dependencies of 'Library1'.
1657
        $this->framework->deleteLibraryDependencies($library1->id);
1658
 
1659
        $dependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library1->id]);
1660
        // The 'Library1' should have 0 dependencies.
1661
        $this->assertCount(0, $dependencies);
1662
    }
1663
 
1664
    /**
1665
     * Test the behaviour of deleteLibraryDependencies() when requesting to delete the
1666
     * dependencies of a non-existent library.
1667
     */
11 efrain 1668
    public function test_deleteLibraryDependencies_non_existent_library(): void {
1 efrain 1669
        global $DB;
1670
 
1671
        $this->resetAfterTest();
1672
 
1673
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1674
 
1675
        // Generate h5p related data.
1676
        $data = $generator->generate_h5p_data();
1677
        // The data of the library 'Library1'.
1678
        $library1 = $data->lib1->data;
1679
 
1680
        // Get the dependencies of 'Library1'.
1681
        $dependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library1->id]);
1682
        // The 'Library1' should have 3 dependencies ('Library2', 'Library3', 'Library4').
1683
        $this->assertCount(3, $dependencies);
1684
 
1685
        // Delete the dependencies of a non-existent library.
1686
        $this->framework->deleteLibraryDependencies(0);
1687
 
1688
        $dependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library1->id]);
1689
        // The 'Library1' should have 3 dependencies.
1690
        $this->assertCount(3, $dependencies);
1691
    }
1692
 
1693
    /**
1694
     * Test the behaviour of deleteLibrary().
1695
     */
11 efrain 1696
    public function test_deleteLibrary(): void {
1 efrain 1697
        global $DB;
1698
 
1699
        $this->resetAfterTest();
1700
 
1701
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1702
 
1703
        // Generate h5p related data.
1704
        $data = $generator->generate_h5p_data(true);
1705
        // The data of the 'Library1' library.
1706
        $library1 = $data->lib1->data;
1707
 
1708
        // Get the library dependencies of 'Library1'.
1709
        $dependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library1->id]);
1710
 
1711
        // The 'Library1' should have 3 library dependencies ('Library2', 'Library3', 'Library4').
1712
        $this->assertCount(3, $dependencies);
1713
 
1714
        // Return the created 'Library1' files.
1715
        $libraryfiles = $DB->get_records('files',
1716
            array(
1717
                'component' => \core_h5p\file_storage::COMPONENT,
1718
                'filearea' => \core_h5p\file_storage::LIBRARY_FILEAREA,
1719
                'itemid' => $library1->id
1720
            )
1721
        );
1722
 
1723
        // The library ('Library1') should have 7 related folders/files.
1724
        $this->assertCount(7, $libraryfiles);
1725
 
1726
        // Delete the library.
1727
        $this->framework->deleteLibrary($library1);
1728
 
1729
        $lib1 = $DB->get_record('h5p_libraries', ['machinename' => $library1->machinename]);
1730
        $dependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library1->id]);
1731
        $libraryfiles = $DB->get_records('files',
1732
            array(
1733
                'component' => \core_h5p\file_storage::COMPONENT,
1734
                'filearea' => \core_h5p\file_storage::LIBRARY_FILEAREA,
1735
                'itemid' => $library1->id
1736
            )
1737
        );
1738
 
1739
        // The 'Library1' should not exist.
1740
        $this->assertEmpty($lib1);
1741
        // The library ('Library1')  should have 0 dependencies.
1742
        $this->assertCount(0, $dependencies);
1743
        // The library (library1) should have 0 related folders/files.
1744
        $this->assertCount(0, $libraryfiles);
1745
    }
1746
 
1747
    /**
1748
     * Test the behaviour of loadContent().
1749
     */
11 efrain 1750
    public function test_loadContent(): void {
1 efrain 1751
        global $DB;
1752
 
1753
        $this->resetAfterTest();
1754
 
1755
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1756
 
1757
        // Generate h5p related data.
1758
        $data = $generator->generate_h5p_data();
1759
        // The Id of the created h5p content.
1760
        $h5pid = $data->h5pcontent->h5pid;
1761
        // Get the h5p content data from the DB.
1762
        $h5p = $DB->get_record('h5p', ['id' => $h5pid]);
1763
        // The data of content's main library ('MainLibrary').
1764
        $mainlibrary = $data->mainlib->data;
1765
 
1766
        // Load the h5p content.
1767
        $content = $this->framework->loadContent($h5pid);
1768
 
1769
        $expected = array(
1770
            'id' => $h5p->id,
1771
            'params' => $h5p->jsoncontent,
1772
            'embedType' => 'iframe',
1773
            'disable' => $h5p->displayoptions,
1774
            'title' => $mainlibrary->title,
1775
            'slug' => H5PCore::slugify($mainlibrary->title) . '-' . $h5p->id,
1776
            'filtered' => $h5p->filtered,
1777
            'libraryId' => $mainlibrary->id,
1778
            'libraryName' => $mainlibrary->machinename,
1779
            'libraryMajorVersion' => $mainlibrary->majorversion,
1780
            'libraryMinorVersion' => $mainlibrary->minorversion,
1781
            'libraryEmbedTypes' => $mainlibrary->embedtypes,
1782
            'libraryFullscreen' => $mainlibrary->fullscreen,
1783
            'metadata' => '',
1784
            'pathnamehash' => $h5p->pathnamehash
1785
        );
1786
 
1787
        $params = json_decode($h5p->jsoncontent);
1788
        if (empty($params->metadata)) {
1789
            $params->metadata = new \stdClass();
1790
        }
1791
        $expected['metadata'] = $params->metadata;
1792
        $expected['params'] = json_encode($params->params ?? $params);
1793
 
1794
        // The returned content should match the expected array.
1795
        $this->assertEquals($expected, $content);
1796
    }
1797
 
1798
    /**
1799
     * Test the behaviour of loadContentDependencies() when requesting content dependencies
1800
     * without specifying the dependency type.
1801
     */
11 efrain 1802
    public function test_loadContentDependencies_no_type_defined(): void {
1 efrain 1803
        $this->resetAfterTest();
1804
 
1805
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1806
 
1807
        // Generate h5p related data.
1808
        $data = $generator->generate_h5p_data();
1809
        // The Id of the h5p content.
1810
        $h5pid = $data->h5pcontent->h5pid;
1811
        // The content dependencies.
1812
        $dependencies = $data->h5pcontent->contentdependencies;
1813
 
1814
        // Add Library5 as a content dependency (dynamic dependency type).
1815
        $library5 = $data->lib5->data;
1816
        $generator->create_contents_libraries_record($h5pid, $library5->id, 'dynamic');
1817
 
1818
        // Get all content dependencies.
1819
        $contentdependencies = $this->framework->loadContentDependencies($h5pid);
1820
 
1821
        $expected = array();
1822
        foreach ($dependencies as $dependency) {
1823
            $expected[$dependency->machinename] = array(
1824
                'libraryId' => $dependency->id,
1825
                'machineName' => $dependency->machinename,
1826
                'majorVersion' => $dependency->majorversion,
1827
                'minorVersion' => $dependency->minorversion,
1828
                'patchVersion' => $dependency->patchversion,
1829
                'preloadedCss' => $dependency->preloadedcss,
1830
                'preloadedJs' => $dependency->preloadedjs,
1831
                'dropCss' => '0',
1832
                'dependencyType' => 'preloaded'
1833
            );
1834
        }
1835
 
1836
        $expected = array_merge($expected,
1837
            array(
1838
                'Library5' => array(
1839
                    'libraryId' => $library5->id,
1840
                    'machineName' => $library5->machinename,
1841
                    'majorVersion' => $library5->majorversion,
1842
                    'minorVersion' => $library5->minorversion,
1843
                    'patchVersion' => $library5->patchversion,
1844
                    'preloadedCss' => $library5->preloadedcss,
1845
                    'preloadedJs' => $library5->preloadedjs,
1846
                    'dropCss' => '0',
1847
                    'dependencyType' => 'dynamic'
1848
                )
1849
            )
1850
        );
1851
 
1852
        // The loaded content dependencies should return 6 libraries.
1853
        $this->assertCount(6, $contentdependencies);
1854
        $this->assertEquals($expected, $contentdependencies);
1855
    }
1856
 
1857
    /**
1858
     * Test the behaviour of loadContentDependencies() when requesting content dependencies
1859
     * with specifying the dependency type.
1860
     */
11 efrain 1861
    public function test_loadContentDependencies_type_defined(): void {
1 efrain 1862
        $this->resetAfterTest();
1863
 
1864
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1865
 
1866
        // Generate h5p related data.
1867
        $data = $generator->generate_h5p_data();
1868
        // The Id of the h5p content.
1869
        $h5pid = $data->h5pcontent->h5pid;
1870
        // The content dependencies.
1871
        $dependencies = $data->h5pcontent->contentdependencies;
1872
 
1873
        // Add Library5 as a content dependency (dynamic dependency type).
1874
        $library5 = $data->lib5->data;
1875
        $generator->create_contents_libraries_record($h5pid, $library5->id, 'dynamic');
1876
 
1877
        // Load all content dependencies of dependency type 'preloaded'.
1878
        $preloadeddependencies = $this->framework->loadContentDependencies($h5pid, 'preloaded');
1879
 
1880
        $expected = array();
1881
        foreach ($dependencies as $dependency) {
1882
            $expected[$dependency->machinename] = array(
1883
                'libraryId' => $dependency->id,
1884
                'machineName' => $dependency->machinename,
1885
                'majorVersion' => $dependency->majorversion,
1886
                'minorVersion' => $dependency->minorversion,
1887
                'patchVersion' => $dependency->patchversion,
1888
                'preloadedCss' => $dependency->preloadedcss,
1889
                'preloadedJs' => $dependency->preloadedjs,
1890
                'dropCss' => '0',
1891
                'dependencyType' => 'preloaded'
1892
            );
1893
        }
1894
 
1895
        // The loaded content dependencies should return 5 libraries.
1896
        $this->assertCount(5, $preloadeddependencies);
1897
        $this->assertEquals($expected, $preloadeddependencies);
1898
 
1899
        // Load all content dependencies of dependency type 'dynamic'.
1900
        $dynamicdependencies = $this->framework->loadContentDependencies($h5pid, 'dynamic');
1901
 
1902
        $expected = array(
1903
            'Library5' => array(
1904
                'libraryId' => $library5->id,
1905
                'machineName' => $library5->machinename,
1906
                'majorVersion' => $library5->majorversion,
1907
                'minorVersion' => $library5->minorversion,
1908
                'patchVersion' => $library5->patchversion,
1909
                'preloadedCss' => $library5->preloadedcss,
1910
                'preloadedJs' => $library5->preloadedjs,
1911
                'dropCss' => '0',
1912
                'dependencyType' => 'dynamic'
1913
            )
1914
        );
1915
 
1916
        // The loaded content dependencies should now return 1 library.
1917
        $this->assertCount(1, $dynamicdependencies);
1918
        $this->assertEquals($expected, $dynamicdependencies);
1919
    }
1920
 
1921
    /**
1922
     * Test the behaviour of getOption().
1923
     */
1924
    public function test_getOption(): void {
1925
        $this->resetAfterTest();
1926
 
1927
        // Get value for display_option_download.
1928
        $value = $this->framework->getOption(H5PCore::DISPLAY_OPTION_DOWNLOAD);
1929
        $expected = H5PDisplayOptionBehaviour::CONTROLLED_BY_AUTHOR_DEFAULT_OFF;
1930
        $this->assertEquals($expected, $value);
1931
 
1932
        // Get value for display_option_embed using default value (it should be ignored).
1933
        $value = $this->framework->getOption(H5PCore::DISPLAY_OPTION_EMBED, H5PDisplayOptionBehaviour::NEVER_SHOW);
1934
        $expected = H5PDisplayOptionBehaviour::CONTROLLED_BY_AUTHOR_DEFAULT_OFF;
1935
        $this->assertEquals($expected, $value);
1936
 
1937
        // Get value for unexisting setting without default.
1938
        $value = $this->framework->getOption('unexistingsetting');
1939
        $expected = false;
1940
        $this->assertEquals($expected, $value);
1941
 
1942
        // Get value for unexisting setting with default.
1943
        $value = $this->framework->getOption('unexistingsetting', 'defaultvalue');
1944
        $expected = 'defaultvalue';
1945
        $this->assertEquals($expected, $value);
1946
    }
1947
 
1948
    /**
1949
     * Test the behaviour of setOption().
1950
     */
1951
    public function test_setOption(): void {
1952
        $this->resetAfterTest();
1953
 
1954
        // Set value for 'newsetting' setting.
1955
        $name = 'newsetting';
1956
        $value = $this->framework->getOption($name);
1957
        $this->assertEquals(false, $value);
1958
        $newvalue = 'value1';
1959
        $this->framework->setOption($name, $newvalue);
1960
        $value = $this->framework->getOption($name);
1961
        $this->assertEquals($newvalue, $value);
1962
 
1963
        // Set value for display_option_download and then get it again. Check it hasn't changed.
1964
        $name = H5PCore::DISPLAY_OPTION_DOWNLOAD;
1965
        $newvalue = H5PDisplayOptionBehaviour::NEVER_SHOW;
1966
        $this->framework->setOption($name, $newvalue);
1967
        $value = $this->framework->getOption($name);
1968
        $expected = H5PDisplayOptionBehaviour::CONTROLLED_BY_AUTHOR_DEFAULT_OFF;
1969
        $this->assertEquals($expected, $value);
1970
    }
1971
 
1972
    /**
1973
     * Test the behaviour of updateContentFields().
1974
     */
11 efrain 1975
    public function test_updateContentFields(): void {
1 efrain 1976
        global $DB;
1977
 
1978
        $this->resetAfterTest();
1979
 
1980
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
1981
 
1982
        // Create 'Library1' library.
1983
        $library1 = $generator->create_library_record('Library1', 'Lib1', 1, 1, 2);
1984
        // Create 'Library2' library.
1985
        $library2 = $generator->create_library_record('Library2', 'Lib2', 1, 1, 2);
1986
 
1987
        // Create an h5p content with 'Library1' as it's main library.
1988
        $h5pid = $generator->create_h5p_record($library1->id, 'iframe');
1989
 
1990
        $updatedata = array(
1991
            'jsoncontent' => json_encode(['value' => 'test']),
1992
            'mainlibraryid' => $library2->id
1993
        );
1994
 
1995
        // Update h5p content fields.
1996
        $this->framework->updateContentFields($h5pid, $updatedata);
1997
 
1998
        // Get the h5p content from the DB.
1999
        $h5p = $DB->get_record('h5p', ['id' => $h5pid]);
2000
 
2001
        $expected = json_encode(['value' => 'test']);
2002
 
2003
        // Make sure the h5p content fields are properly updated.
2004
        $this->assertEquals($expected, $h5p->jsoncontent);
2005
        $this->assertEquals($library2->id, $h5p->mainlibraryid);
2006
    }
2007
 
2008
    /**
2009
     * Test the behaviour of clearFilteredParameters().
2010
     */
11 efrain 2011
    public function test_clearFilteredParameters(): void {
1 efrain 2012
        global $DB;
2013
 
2014
        $this->resetAfterTest();
2015
 
2016
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
2017
 
2018
        // Create 3 libraries.
2019
        $library1 = $generator->create_library_record('Library1', 'Lib1', 1, 1, 2);
2020
        $library2 = $generator->create_library_record('Library2', 'Lib2', 1, 1, 2);
2021
        $library3 = $generator->create_library_record('Library3', 'Lib3', 1, 1, 2);
2022
 
2023
        // Create h5p content with 'Library1' as a main library.
2024
        $h5pcontentid1 = $generator->create_h5p_record($library1->id);
2025
        // Create h5p content with 'Library1' as a main library.
2026
        $h5pcontentid2 = $generator->create_h5p_record($library1->id);
2027
        // Create h5p content with 'Library2' as a main library.
2028
        $h5pcontentid3 = $generator->create_h5p_record($library2->id);
2029
        // Create h5p content with 'Library3' as a main library.
2030
        $h5pcontentid4 = $generator->create_h5p_record($library3->id);
2031
 
2032
        $h5pcontent1 = $DB->get_record('h5p', ['id' => $h5pcontentid1]);
2033
        $h5pcontent2 = $DB->get_record('h5p', ['id' => $h5pcontentid2]);
2034
        $h5pcontent3 = $DB->get_record('h5p', ['id' => $h5pcontentid3]);
2035
        $h5pcontent4 = $DB->get_record('h5p', ['id' => $h5pcontentid4]);
2036
 
2037
        // The filtered parameters should be present in each h5p content.
2038
        $this->assertNotEmpty($h5pcontent1->filtered);
2039
        $this->assertNotEmpty($h5pcontent2->filtered);
2040
        $this->assertNotEmpty($h5pcontent3->filtered);
2041
        $this->assertNotEmpty($h5pcontent4->filtered);
2042
 
2043
        // Clear the filtered parameters for contents that have library1 and library3 as
2044
        // their main library.
2045
        $this->framework->clearFilteredParameters([$library1->id, $library3->id]);
2046
 
2047
        $h5pcontent1 = $DB->get_record('h5p', ['id' => $h5pcontentid1]);
2048
        $h5pcontent2 = $DB->get_record('h5p', ['id' => $h5pcontentid2]);
2049
        $h5pcontent3 = $DB->get_record('h5p', ['id' => $h5pcontentid3]);
2050
        $h5pcontent4 = $DB->get_record('h5p', ['id' => $h5pcontentid4]);
2051
 
2052
        // The filtered parameters should be still present only for the content that has
2053
        // library 2 as a main library.
2054
        $this->assertEmpty($h5pcontent1->filtered);
2055
        $this->assertEmpty($h5pcontent2->filtered);
2056
        $this->assertNotEmpty($h5pcontent3->filtered);
2057
        $this->assertEmpty($h5pcontent4->filtered);
2058
    }
2059
 
2060
    /**
2061
     * Test the behaviour of getNumNotFiltered().
2062
     */
11 efrain 2063
    public function test_getNumNotFiltered(): void {
1 efrain 2064
        global $DB;
2065
 
2066
        $this->resetAfterTest();
2067
 
2068
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
2069
 
2070
        // Create 3 libraries.
2071
        $library1 = $generator->create_library_record('Library1', 'Lib1', 1, 1, 2);
2072
        $library2 = $generator->create_library_record('Library2', 'Lib2', 1, 1, 2);
2073
        $library3 = $generator->create_library_record('Library3', 'Lib3', 1, 1, 2);
2074
 
2075
        // Create h5p content with library1 as a main library.
2076
        $h5pcontentid1 = $generator->create_h5p_record($library1->id);
2077
        // Create h5p content with library1 as a main library.
2078
        $h5pcontentid2 = $generator->create_h5p_record($library1->id);
2079
        // Create h5p content with library2 as a main library.
2080
        $h5pcontentid3 = $generator->create_h5p_record($library2->id);
2081
        // Create h5p content with library3 as a main library.
2082
        $h5pcontentid4 = $generator->create_h5p_record($library3->id);
2083
 
2084
        $h5pcontent1 = $DB->get_record('h5p', ['id' => $h5pcontentid1]);
2085
        $h5pcontent2 = $DB->get_record('h5p', ['id' => $h5pcontentid2]);
2086
        $h5pcontent3 = $DB->get_record('h5p', ['id' => $h5pcontentid3]);
2087
        $h5pcontent4 = $DB->get_record('h5p', ['id' => $h5pcontentid4]);
2088
 
2089
        // The filtered parameters should be present in each h5p content.
2090
        $this->assertNotEmpty($h5pcontent1->filtered);
2091
        $this->assertNotEmpty($h5pcontent2->filtered);
2092
        $this->assertNotEmpty($h5pcontent3->filtered);
2093
        $this->assertNotEmpty($h5pcontent4->filtered);
2094
 
2095
        // Clear the filtered parameters for contents that have library1 and library3 as
2096
        // their main library.
2097
        $this->framework->clearFilteredParameters([$library1->id, $library3->id]);
2098
 
2099
        $countnotfiltered = $this->framework->getNumNotFiltered();
2100
 
2101
        // 3 contents don't have their parameters filtered.
2102
        $this->assertEquals(3, $countnotfiltered);
2103
    }
2104
 
2105
    /**
2106
     * Test the behaviour of getNumContent().
2107
     */
11 efrain 2108
    public function test_getNumContent(): void {
1 efrain 2109
        $this->resetAfterTest();
2110
 
2111
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
2112
 
2113
        // Generate h5p related data.
2114
        $data = $generator->generate_h5p_data();
2115
 
2116
        // The 'MainLibrary' library data.
2117
        $mainlibrary = $data->mainlib->data;
2118
 
2119
        // The 'Library1' library data.
2120
        $library1 = $data->lib1->data;
2121
 
2122
        // Create new h5p content with MainLibrary as a main library.
2123
        $generator->create_h5p_record($mainlibrary->id);
2124
 
2125
        // Get the number of h5p contents that are using 'MainLibrary' as their main library.
2126
        $countmainlib = $this->framework->getNumContent($mainlibrary->id);
2127
 
2128
        // Get the number of h5p contents that are using 'Library1' as their main library.
2129
        $countlib1 = $this->framework->getNumContent($library1->id);
2130
 
2131
        // Make sure that 2 contents are using MainLibrary as their main library.
2132
        $this->assertEquals(2, $countmainlib);
2133
        // Make sure that 0 contents are using Library1 as their main library.
2134
        $this->assertEquals(0, $countlib1);
2135
    }
2136
 
2137
    /**
2138
     * Test the behaviour of getNumContent() when certain contents are being skipped.
2139
     */
11 efrain 2140
    public function test_getNumContent_skip_content(): void {
1 efrain 2141
        $this->resetAfterTest();
2142
 
2143
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
2144
 
2145
        // Generate h5p related data.
2146
        $data = $generator->generate_h5p_data();
2147
 
2148
        // The 'MainLibrary' library data.
2149
        $mainlibrary = $data->mainlib->data;
2150
 
2151
        // Create new h5p content with MainLibrary as a main library.
2152
        $h5pcontentid = $generator->create_h5p_record($mainlibrary->id);
2153
 
2154
        // Get the number of h5p contents that are using 'MainLibrary' as their main library.
2155
        // Skip the newly created content $h5pcontentid.
2156
        $countmainlib = $this->framework->getNumContent($mainlibrary->id, [$h5pcontentid]);
2157
 
2158
        // Make sure that 1 content is returned instead of 2 ($h5pcontentid being skipped).
2159
        $this->assertEquals(1, $countmainlib);
2160
    }
2161
 
2162
    /**
2163
     * Test the behaviour of isContentSlugAvailable().
2164
     */
11 efrain 2165
    public function test_isContentSlugAvailable(): void {
1 efrain 2166
        $this->resetAfterTest();
2167
 
2168
        $slug = 'h5p-test-slug-1';
2169
 
2170
        // Currently this returns always true. The slug is generated as a unique value for
2171
        // each h5p content and it is not stored in the h5p content table.
2172
        $isslugavailable = $this->framework->isContentSlugAvailable($slug);
2173
 
2174
        $this->assertTrue($isslugavailable);
2175
    }
2176
 
2177
    /**
2178
     * Test that a record is stored for cached assets.
2179
     */
11 efrain 2180
    public function test_saveCachedAssets(): void {
1 efrain 2181
        global $DB;
2182
 
2183
        $this->resetAfterTest();
2184
 
2185
        $libraries = array(
2186
            array(
2187
                'machineName' => 'H5P.TestLib',
2188
                'libraryId' => 405,
2189
            ),
2190
            array(
2191
                'FontAwesome' => 'FontAwesome',
2192
                'libraryId' => 406,
2193
            ),
2194
            array(
2195
                'machineName' => 'H5P.SecondLib',
2196
                'libraryId' => 407,
2197
            ),
2198
        );
2199
 
2200
        $key = 'testhashkey';
2201
 
2202
        $this->framework->saveCachedAssets($key, $libraries);
2203
 
2204
        $records = $DB->get_records('h5p_libraries_cachedassets');
2205
 
2206
        $this->assertCount(3, $records);
2207
    }
2208
 
2209
    /**
2210
     * Test that the correct libraries are removed from the cached assets table
2211
     */
11 efrain 2212
    public function test_deleteCachedAssets(): void {
1 efrain 2213
        global $DB;
2214
 
2215
        $this->resetAfterTest();
2216
 
2217
        $libraries = array(
2218
            array(
2219
                'machineName' => 'H5P.TestLib',
2220
                'libraryId' => 405,
2221
            ),
2222
            array(
2223
                'FontAwesome' => 'FontAwesome',
2224
                'libraryId' => 406,
2225
            ),
2226
            array(
2227
                'machineName' => 'H5P.SecondLib',
2228
                'libraryId' => 407,
2229
            ),
2230
        );
2231
 
2232
        $key1 = 'testhashkey';
2233
        $this->framework->saveCachedAssets($key1, $libraries);
2234
 
2235
        $libraries = array(
2236
            array(
2237
                'machineName' => 'H5P.DiffLib',
2238
                'libraryId' => 408,
2239
            ),
2240
            array(
2241
                'FontAwesome' => 'FontAwesome',
2242
                'libraryId' => 406,
2243
            ),
2244
            array(
2245
                'machineName' => 'H5P.ThirdLib',
2246
                'libraryId' => 409,
2247
            ),
2248
        );
2249
 
2250
        $key2 = 'secondhashkey';
2251
        $this->framework->saveCachedAssets($key2, $libraries);
2252
 
2253
        $libraries = array(
2254
            array(
2255
                'machineName' => 'H5P.AnotherDiffLib',
2256
                'libraryId' => 410,
2257
            ),
2258
            array(
2259
                'FontAwesome' => 'NotRelated',
2260
                'libraryId' => 411,
2261
            ),
2262
            array(
2263
                'machineName' => 'H5P.ForthLib',
2264
                'libraryId' => 412,
2265
            ),
2266
        );
2267
 
2268
        $key3 = 'threeforthewin';
2269
        $this->framework->saveCachedAssets($key3, $libraries);
2270
 
2271
        $records = $DB->get_records('h5p_libraries_cachedassets');
2272
        $this->assertCount(9, $records);
2273
 
2274
        // Selecting one library id will result in all related library entries also being deleted.
2275
        // Going to use the FontAwesome library id. The first two hashes should be returned.
2276
        $hashes = $this->framework->deleteCachedAssets(406);
2277
        $this->assertCount(2, $hashes);
2278
        $index = array_search($key1, $hashes);
2279
        $this->assertEquals($key1, $hashes[$index]);
2280
        $index = array_search($key2, $hashes);
2281
        $this->assertEquals($key2, $hashes[$index]);
2282
        $index = array_search($key3, $hashes);
2283
        $this->assertFalse($index);
2284
 
2285
        // Check that the records have been removed as well.
2286
        $records = $DB->get_records('h5p_libraries_cachedassets');
2287
        $this->assertCount(3, $records);
2288
    }
2289
 
2290
    /**
2291
     * Test the behaviour of getLibraryContentCount().
2292
     */
11 efrain 2293
    public function test_getLibraryContentCount(): void {
1 efrain 2294
        $this->resetAfterTest();
2295
 
2296
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
2297
 
2298
        // Generate h5p related data.
2299
        $data = $generator->generate_h5p_data();
2300
 
2301
        // The 'MainLibrary' library data.
2302
        $mainlibrary = $data->mainlib->data;
2303
 
2304
        // The 'Library2' library data.
2305
        $library2 = $data->lib2->data;
2306
 
2307
        // Create new h5p content with Library2 as it's main library.
2308
        $generator->create_h5p_record($library2->id);
2309
 
2310
        // Create new h5p content with MainLibrary as it's main library.
2311
        $generator->create_h5p_record($mainlibrary->id);
2312
 
2313
        $countlibrarycontent = $this->framework->getLibraryContentCount();
2314
 
2315
        $expected = array(
2316
            "{$mainlibrary->machinename} {$mainlibrary->majorversion}.{$mainlibrary->minorversion}" => 2,
2317
            "{$library2->machinename} {$library2->majorversion}.{$library2->minorversion}" => 1,
2318
        );
2319
 
2320
        // MainLibrary and Library1 are currently main libraries to the existing h5p contents.
2321
        // Should return the number of cases where MainLibrary and Library1 are main libraries to an h5p content.
2322
        $this->assertEquals($expected, $countlibrarycontent);
2323
    }
2324
 
2325
    /**
2326
     * Test the behaviour of test_libraryHasUpgrade().
2327
     *
2328
     * @dataProvider libraryHasUpgrade_provider
2329
     * @param array $libraryrecords Array containing data for the library creation
2330
     * @param array $testlibrary Array containing the test library data
2331
     * @param bool $expected The expectation whether the library is patched or not
2332
     **/
2333
    public function test_libraryHasUpgrade(array $libraryrecords, array $testlibrary, bool $expected): void {
2334
        $this->resetAfterTest();
2335
 
2336
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
2337
 
2338
        foreach ($libraryrecords as $library) {
2339
            call_user_func_array([$generator, 'create_library_record'], $library);
2340
        }
2341
 
2342
        $this->assertEquals($expected, $this->framework->libraryHasUpgrade($testlibrary));
2343
    }
2344
 
2345
    /**
2346
     * Data provider for test_libraryHasUpgrade().
2347
     *
2348
     * @return array
2349
     */
1441 ariadna 2350
    public static function libraryHasUpgrade_provider(): array {
1 efrain 2351
        return [
2352
            'Lower major version; Identical lower version' => [
2353
                [
2354
                    ['Library', 'Lib', 2, 2],
2355
                ],
2356
                [
2357
                    'machineName' => 'Library',
2358
                    'majorVersion' => 1,
2359
                    'minorVersion' => 2
2360
                ],
2361
                true,
2362
            ],
2363
            'Major version identical; Lower minor version' => [
2364
                [
2365
                    ['Library', 'Lib', 2, 2],
2366
                ],
2367
                [
2368
                    'machineName' => 'Library',
2369
                    'majorVersion' => 2,
2370
                    'minorVersion' => 1
2371
                ],
2372
                true,
2373
            ],
2374
            'Major version identical; Minor version identical' => [
2375
                [
2376
                    ['Library', 'Lib', 2, 2],
2377
                ],
2378
                [
2379
                    'machineName' => 'Library',
2380
                    'majorVersion' => 2,
2381
                    'minorVersion' => 2
2382
                ],
2383
                false,
2384
            ],
2385
            'Major version higher; Minor version identical' => [
2386
                [
2387
                    ['Library', 'Lib', 2, 2],
2388
                ],
2389
                [
2390
                    'machineName' => 'Library',
2391
                    'majorVersion' => 3,
2392
                    'minorVersion' => 2
2393
                ],
2394
                false,
2395
            ],
2396
            'Major version identical; Minor version newer' => [
2397
                [
2398
                    ['Library', 'Lib', 2, 2],
2399
                ],
2400
                [
2401
                    'machineName' => 'Library',
2402
                    'majorVersion' => 2,
2403
                    'minorVersion' => 4
2404
                ],
2405
                false,
2406
            ]
2407
        ];
2408
    }
2409
 
2410
 
2411
    /**
2412
     * Test the behaviour of get_latest_library_version().
2413
     */
11 efrain 2414
    public function test_get_latest_library_version(): void {
1 efrain 2415
        global $DB;
2416
 
2417
        $this->resetAfterTest();
2418
 
2419
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
2420
        // Create a library record.
2421
        $machinename = 'TestLibrary';
2422
        $lib1 = $generator->create_library_record($machinename, 'Test', 1, 1, 2);
2423
        $lib2 = $generator->create_library_record($machinename, 'Test', 1, 2, 1);
2424
 
2425
        $content = array(
2426
            'params' => json_encode(['param1' => 'Test']),
2427
            'library' => array(
2428
                'libraryId' => 0,
2429
                'machineName' => 'TestLibrary',
2430
            ),
2431
            'disable' => 8
2432
        );
2433
 
2434
        // Get the latest id (at this point, should be lib2).
2435
        $latestlib = $this->framework->get_latest_library_version($machinename);
2436
        $this->assertEquals($lib2->id, $latestlib->id);
2437
 
2438
        // Get the latest id (at this point, should be lib3).
2439
        $lib3 = $generator->create_library_record($machinename, 'Test', 2, 1, 0);
2440
        $latestlib = $this->framework->get_latest_library_version($machinename);
2441
        $this->assertEquals($lib3->id, $latestlib->id);
2442
 
2443
        // Get the latest id (at this point, should be still lib3).
2444
        $lib4 = $generator->create_library_record($machinename, 'Test', 1, 1, 3);
2445
        $latestlib = $this->framework->get_latest_library_version($machinename);
2446
        $this->assertEquals($lib3->id, $latestlib->id);
2447
 
2448
        // Get the latest id (at this point, should be lib5).
2449
        $lib5 = $generator->create_library_record($machinename, 'Test', 2, 1, 6);
2450
        $latestlib = $this->framework->get_latest_library_version($machinename);
2451
        $this->assertEquals($lib5->id, $latestlib->id);
2452
    }
2453
}