forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
externallib_test.php
4221 lines (3619 loc) · 197 KB
/
externallib_test.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* External course functions unit tests
*
* @package core_course
* @category external
* @copyright 2012 Jerome Mouneyrac
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use \core_external\external_api;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
/**
* External course functions unit tests
*
* @package core_course
* @category external
* @copyright 2012 Jerome Mouneyrac
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class externallib_test extends externallib_advanced_testcase {
/**
* Tests set up
*/
protected function setUp(): void {
global $CFG;
require_once($CFG->dirroot . '/course/externallib.php');
parent::setUp();
}
/**
* Test create_categories
*/
public function test_create_categories(): void {
global $DB;
$this->resetAfterTest(true);
// Set the required capabilities by the external function
$contextid = context_system::instance()->id;
$roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
// Create base categories.
$category1 = new stdClass();
$category1->name = 'Root Test Category 1';
$category2 = new stdClass();
$category2->name = 'Root Test Category 2';
$category2->idnumber = 'rootcattest2';
$category2->desc = 'Description for root test category 1';
$category2->theme = 'classic';
$categories = array(
array('name' => $category1->name, 'parent' => 0),
array('name' => $category2->name, 'parent' => 0, 'idnumber' => $category2->idnumber,
'description' => $category2->desc, 'theme' => $category2->theme)
);
$createdcats = core_course_external::create_categories($categories);
// We need to execute the return values cleaning process to simulate the web service server.
$createdcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdcats);
// Initially confirm that base data was inserted correctly.
$this->assertEquals($category1->name, $createdcats[0]['name']);
$this->assertEquals($category2->name, $createdcats[1]['name']);
// Save the ids.
$category1->id = $createdcats[0]['id'];
$category2->id = $createdcats[1]['id'];
// Create on sub category.
$category3 = new stdClass();
$category3->name = 'Sub Root Test Category 3';
$subcategories = array(
array('name' => $category3->name, 'parent' => $category1->id)
);
$createdsubcats = core_course_external::create_categories($subcategories);
// We need to execute the return values cleaning process to simulate the web service server.
$createdsubcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdsubcats);
// Confirm that sub categories were inserted correctly.
$this->assertEquals($category3->name, $createdsubcats[0]['name']);
// Save the ids.
$category3->id = $createdsubcats[0]['id'];
// Calling the ws function should provide a new sortorder to give category1,
// category2, category3. New course categories are ordered by id not name.
$category1 = $DB->get_record('course_categories', array('id' => $category1->id));
$category2 = $DB->get_record('course_categories', array('id' => $category2->id));
$category3 = $DB->get_record('course_categories', array('id' => $category3->id));
// sortorder sequence (and sortorder) must be:
// category 1
// category 3
// category 2
$this->assertGreaterThan($category1->sortorder, $category3->sortorder);
$this->assertGreaterThan($category3->sortorder, $category2->sortorder);
// Call without required capability
$this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
$this->expectException('required_capability_exception');
$createdsubcats = core_course_external::create_categories($subcategories);
}
/**
* Test delete categories
*/
public function test_delete_categories(): void {
global $DB;
$this->resetAfterTest(true);
// Set the required capabilities by the external function
$contextid = context_system::instance()->id;
$roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
$category1 = self::getDataGenerator()->create_category();
$category2 = self::getDataGenerator()->create_category(
array('parent' => $category1->id));
$category3 = self::getDataGenerator()->create_category();
$category4 = self::getDataGenerator()->create_category(
array('parent' => $category3->id));
$category5 = self::getDataGenerator()->create_category(
array('parent' => $category4->id));
//delete category 1 and 2 + delete category 4, category 5 moved under category 3
core_course_external::delete_categories(array(
array('id' => $category1->id, 'recursive' => 1),
array('id' => $category4->id)
));
//check $category 1 and 2 are deleted
$notdeletedcount = $DB->count_records_select('course_categories',
'id IN ( ' . $category1->id . ',' . $category2->id . ',' . $category4->id . ')');
$this->assertEquals(0, $notdeletedcount);
//check that $category5 as $category3 for parent
$dbcategory5 = $DB->get_record('course_categories', array('id' => $category5->id));
$this->assertEquals($dbcategory5->path, $category3->path . '/' . $category5->id);
// Call without required capability
$this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
$this->expectException('required_capability_exception');
$createdsubcats = core_course_external::delete_categories(
array(array('id' => $category3->id)));
}
/**
* Test get categories
*/
public function test_get_categories(): void {
global $DB;
$this->resetAfterTest(true);
$generatedcats = array();
$category1data['idnumber'] = 'idnumbercat1';
$category1data['name'] = 'Category 1 for PHPunit test';
$category1data['description'] = 'Category 1 description';
$category1data['descriptionformat'] = FORMAT_MOODLE;
$category1 = self::getDataGenerator()->create_category($category1data);
$generatedcats[$category1->id] = $category1;
$category2 = self::getDataGenerator()->create_category(
array('parent' => $category1->id));
$generatedcats[$category2->id] = $category2;
$category6 = self::getDataGenerator()->create_category(
array('parent' => $category1->id, 'visible' => 0));
$generatedcats[$category6->id] = $category6;
$category3 = self::getDataGenerator()->create_category();
$generatedcats[$category3->id] = $category3;
$category4 = self::getDataGenerator()->create_category(
array('parent' => $category3->id));
$generatedcats[$category4->id] = $category4;
$category5 = self::getDataGenerator()->create_category(
array('parent' => $category4->id));
$generatedcats[$category5->id] = $category5;
// Set the required capabilities by the external function.
$context = context_system::instance();
$roleid = $this->assignUserCapability('moodle/category:manage', $context->id);
$this->assignUserCapability('moodle/category:viewhiddencategories', $context->id, $roleid);
// Retrieve category1 + sub-categories except not visible ones
$categories = core_course_external::get_categories(array(
array('key' => 'id', 'value' => $category1->id),
array('key' => 'visible', 'value' => 1)), 1);
// We need to execute the return values cleaning process to simulate the web service server.
$categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
// Check we retrieve the good total number of categories.
$this->assertEquals(2, count($categories));
// Check the return values
foreach ($categories as $category) {
$generatedcat = $generatedcats[$category['id']];
$this->assertEquals($category['idnumber'], $generatedcat->idnumber);
$this->assertEquals($category['name'], $generatedcat->name);
// Description was converted to the HTML format.
$this->assertEquals($category['description'], format_text($generatedcat->description, FORMAT_MOODLE, array('para' => false)));
$this->assertEquals($category['descriptionformat'], FORMAT_HTML);
}
// Check categories by ids.
$ids = implode(',', array_keys($generatedcats));
$categories = core_course_external::get_categories(array(
array('key' => 'ids', 'value' => $ids)), 0);
// We need to execute the return values cleaning process to simulate the web service server.
$categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
// Check we retrieve the good total number of categories.
$this->assertEquals(6, count($categories));
// Check ids.
$returnedids = [];
foreach ($categories as $category) {
$returnedids[] = $category['id'];
}
// Sort the arrays upon comparision.
$this->assertEqualsCanonicalizing(array_keys($generatedcats), $returnedids);
// Check different params.
$categories = core_course_external::get_categories(array(
array('key' => 'id', 'value' => $category1->id),
array('key' => 'ids', 'value' => $category1->id),
array('key' => 'idnumber', 'value' => $category1->idnumber),
array('key' => 'visible', 'value' => 1)), 0);
// We need to execute the return values cleaning process to simulate the web service server.
$categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
$this->assertEquals(1, count($categories));
// Same query, but forcing a parameters clean.
$categories = core_course_external::get_categories(array(
array('key' => 'id', 'value' => "$category1->id"),
array('key' => 'idnumber', 'value' => $category1->idnumber),
array('key' => 'name', 'value' => $category1->name . "<br/>"),
array('key' => 'visible', 'value' => '1')), 0);
$categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
$this->assertEquals(1, count($categories));
// Retrieve categories from parent.
$categories = core_course_external::get_categories(array(
array('key' => 'parent', 'value' => $category3->id)), 1);
$categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
$this->assertEquals(2, count($categories));
// Retrieve all categories.
$categories = core_course_external::get_categories();
// We need to execute the return values cleaning process to simulate the web service server.
$categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
$this->assertEquals($DB->count_records('course_categories'), count($categories));
$this->unassignUserCapability('moodle/category:viewhiddencategories', $context->id, $roleid);
// Ensure maxdepthcategory is 2 and retrieve all categories without category:viewhiddencategories capability.
// It should retrieve all visible categories as well.
set_config('maxcategorydepth', 2);
$categories = core_course_external::get_categories();
// We need to execute the return values cleaning process to simulate the web service server.
$categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
$this->assertEquals($DB->count_records('course_categories', array('visible' => 1)), count($categories));
// Call without required capability (it will fail cause of the search on idnumber).
$this->expectException('moodle_exception');
$categories = core_course_external::get_categories(array(
array('key' => 'id', 'value' => $category1->id),
array('key' => 'idnumber', 'value' => $category1->idnumber),
array('key' => 'visible', 'value' => 1)), 0);
}
/**
* Test update_categories
*/
public function test_update_categories(): void {
global $DB;
$this->resetAfterTest(true);
// Set the required capabilities by the external function
$contextid = context_system::instance()->id;
$roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
// Create base categories.
$category1data['idnumber'] = 'idnumbercat1';
$category1data['name'] = 'Category 1 for PHPunit test';
$category1data['description'] = 'Category 1 description';
$category1data['descriptionformat'] = FORMAT_MOODLE;
$category1 = self::getDataGenerator()->create_category($category1data);
$category2 = self::getDataGenerator()->create_category(
array('parent' => $category1->id));
$category3 = self::getDataGenerator()->create_category();
$category4 = self::getDataGenerator()->create_category(
array('parent' => $category3->id));
$category5 = self::getDataGenerator()->create_category(
array('parent' => $category4->id));
// We update all category1 attribut.
// Then we move cat4 and cat5 parent: cat3 => cat1
$categories = array(
array('id' => $category1->id,
'name' => $category1->name . '_updated',
'idnumber' => $category1->idnumber . '_updated',
'description' => $category1->description . '_updated',
'descriptionformat' => FORMAT_HTML,
'theme' => $category1->theme),
array('id' => $category4->id, 'parent' => $category1->id));
core_course_external::update_categories($categories);
// Check the values were updated.
$dbcategories = $DB->get_records_select('course_categories',
'id IN (' . $category1->id . ',' . $category2->id . ',' . $category2->id
. ',' . $category3->id . ',' . $category4->id . ',' . $category5->id .')');
$this->assertEquals($category1->name . '_updated',
$dbcategories[$category1->id]->name);
$this->assertEquals($category1->idnumber . '_updated',
$dbcategories[$category1->id]->idnumber);
$this->assertEquals($category1->description . '_updated',
$dbcategories[$category1->id]->description);
$this->assertEquals(FORMAT_HTML, $dbcategories[$category1->id]->descriptionformat);
// Check that category4 and category5 have been properly moved.
$this->assertEquals('/' . $category1->id . '/' . $category4->id,
$dbcategories[$category4->id]->path);
$this->assertEquals('/' . $category1->id . '/' . $category4->id . '/' . $category5->id,
$dbcategories[$category5->id]->path);
// Call without required capability.
$this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
$this->expectException('required_capability_exception');
core_course_external::update_categories($categories);
}
/**
* Test update_categories method for moving categories
*/
public function test_update_categories_moving(): void {
$this->resetAfterTest();
// Create data.
$categorya = self::getDataGenerator()->create_category([
'name' => 'CAT_A',
]);
$categoryasub = self::getDataGenerator()->create_category([
'name' => 'SUBCAT_A',
'parent' => $categorya->id
]);
$categoryb = self::getDataGenerator()->create_category([
'name' => 'CAT_B',
]);
// Create a new test user.
$testuser = self::getDataGenerator()->create_user();
$this->setUser($testuser);
// Set the capability for CAT_A only.
$contextcata = context_coursecat::instance($categorya->id);
$roleid = $this->assignUserCapability('moodle/category:manage', $contextcata->id);
// Then we move SUBCAT_A parent: CAT_A => CAT_B.
$categories = [
[
'id' => $categoryasub->id,
'parent' => $categoryb->id
]
];
$this->expectException('required_capability_exception');
core_course_external::update_categories($categories);
}
/**
* Test create_courses numsections
*/
public function test_create_course_numsections(): void {
global $DB;
$this->resetAfterTest(true);
// Set the required capabilities by the external function.
$contextid = context_system::instance()->id;
$roleid = $this->assignUserCapability('moodle/course:create', $contextid);
$this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
$numsections = 10;
$category = self::getDataGenerator()->create_category();
// Create base categories.
$course1['fullname'] = 'Test course 1';
$course1['shortname'] = 'Testcourse1';
$course1['categoryid'] = $category->id;
$course1['courseformatoptions'][] = array('name' => 'numsections', 'value' => $numsections);
$courses = array($course1);
$createdcourses = core_course_external::create_courses($courses);
foreach ($createdcourses as $createdcourse) {
$existingsections = $DB->get_records('course_sections', array('course' => $createdcourse['id']));
$modinfo = get_fast_modinfo($createdcourse['id']);
$sections = $modinfo->get_section_info_all();
$this->assertEquals(count($sections), $numsections + 1); // Includes generic section.
$this->assertEquals(count($existingsections), $numsections + 1); // Includes generic section.
}
}
/**
* Test create_courses
*/
public function test_create_courses(): void {
global $DB;
$this->resetAfterTest(true);
// Enable course completion.
set_config('enablecompletion', 1);
// Enable course themes.
set_config('allowcoursethemes', 1);
// Custom fields.
$fieldcategory = self::getDataGenerator()->create_custom_field_category(['name' => 'Other fields']);
$fieldtext = self::getDataGenerator()->create_custom_field([
'categoryid' => $fieldcategory->get('id'), 'name' => 'Text', 'shortname' => 'text', 'type' => 'text',
]);
$fieldtextarea = self::getDataGenerator()->create_custom_field([
'categoryid' => $fieldcategory->get('id'), 'name' => 'Textarea', 'shortname' => 'textarea', 'type' => 'textarea',
]);
// Set the required capabilities by the external function
$contextid = context_system::instance()->id;
$roleid = $this->assignUserCapability('moodle/course:create', $contextid);
$this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
$this->assignUserCapability('moodle/course:setforcedlanguage', $contextid, $roleid);
$category = self::getDataGenerator()->create_category();
// Create base categories.
$course1['fullname'] = 'Test course 1';
$course1['shortname'] = 'Testcourse1';
$course1['categoryid'] = $category->id;
$course2['fullname'] = 'Test course 2';
$course2['shortname'] = 'Testcourse2';
$course2['categoryid'] = $category->id;
$course2['idnumber'] = 'testcourse2idnumber';
$course2['summary'] = 'Description for course 2';
$course2['summaryformat'] = FORMAT_MOODLE;
$course2['format'] = 'weeks';
$course2['showgrades'] = 1;
$course2['newsitems'] = 3;
$course2['startdate'] = 1420092000; // 01/01/2015.
$course2['enddate'] = 1422669600; // 01/31/2015.
$course2['numsections'] = 4;
$course2['maxbytes'] = 100000;
$course2['showreports'] = 1;
$course2['visible'] = 0;
$course2['hiddensections'] = 0;
$course2['groupmode'] = 0;
$course2['groupmodeforce'] = 0;
$course2['defaultgroupingid'] = 0;
$course2['enablecompletion'] = 1;
$course2['completionnotify'] = 1;
$course2['lang'] = 'en';
$course2['forcetheme'] = 'classic';
$course2['courseformatoptions'][] = array('name' => 'automaticenddate', 'value' => 0);
$course3['fullname'] = 'Test course 3';
$course3['shortname'] = 'Testcourse3';
$course3['categoryid'] = $category->id;
$course3['format'] = 'topics';
$course3options = array('numsections' => 8,
'hiddensections' => 1,
'coursedisplay' => 1);
$course3['courseformatoptions'] = array();
foreach ($course3options as $key => $value) {
$course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
}
$course4['fullname'] = 'Test course with custom fields';
$course4['shortname'] = 'Testcoursecustomfields';
$course4['categoryid'] = $category->id;
$course4['customfields'] = [
['shortname' => $fieldtext->get('shortname'), 'value' => 'And I want to tell you so much'],
['shortname' => $fieldtextarea->get('shortname'), 'value' => 'I love you'],
];
$courses = array($course4, $course1, $course2, $course3);
$createdcourses = core_course_external::create_courses($courses);
// We need to execute the return values cleaning process to simulate the web service server.
$createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
// Check that right number of courses were created.
$this->assertEquals(4, count($createdcourses));
// Check that the courses were correctly created.
foreach ($createdcourses as $createdcourse) {
$courseinfo = course_get_format($createdcourse['id'])->get_course();
if ($createdcourse['shortname'] == $course2['shortname']) {
$this->assertEquals($courseinfo->fullname, $course2['fullname']);
$this->assertEquals($courseinfo->shortname, $course2['shortname']);
$this->assertEquals($courseinfo->category, $course2['categoryid']);
$this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
$this->assertEquals($courseinfo->summary, $course2['summary']);
$this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
$this->assertEquals($courseinfo->format, $course2['format']);
$this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
$this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
$this->assertEquals($courseinfo->startdate, $course2['startdate']);
$this->assertEquals($courseinfo->enddate, $course2['enddate']);
$this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(), $course2['numsections']);
$this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
$this->assertEquals($courseinfo->showreports, $course2['showreports']);
$this->assertEquals($courseinfo->visible, $course2['visible']);
$this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
$this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
$this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
$this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
$this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
$this->assertEquals($courseinfo->lang, $course2['lang']);
$this->assertEquals($courseinfo->theme, $course2['forcetheme']);
// We enabled completion at the beginning of the test.
$this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
} else if ($createdcourse['shortname'] == $course1['shortname']) {
$courseconfig = get_config('moodlecourse');
$this->assertEquals($courseinfo->fullname, $course1['fullname']);
$this->assertEquals($courseinfo->shortname, $course1['shortname']);
$this->assertEquals($courseinfo->category, $course1['categoryid']);
$this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
$this->assertEquals($courseinfo->format, $courseconfig->format);
$this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
$this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
$this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
$this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
$this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
$this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
$this->assertEquals($courseinfo->defaultgroupingid, 0);
} else if ($createdcourse['shortname'] == $course3['shortname']) {
$this->assertEquals($courseinfo->fullname, $course3['fullname']);
$this->assertEquals($courseinfo->shortname, $course3['shortname']);
$this->assertEquals($courseinfo->category, $course3['categoryid']);
$this->assertEquals($courseinfo->format, $course3['format']);
$this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
$this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(),
$course3options['numsections']);
$this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
} else if ($createdcourse['shortname'] == $course4['shortname']) {
$this->assertEquals($courseinfo->fullname, $course4['fullname']);
$this->assertEquals($courseinfo->shortname, $course4['shortname']);
$this->assertEquals($courseinfo->category, $course4['categoryid']);
$handler = core_course\customfield\course_handler::create();
$customfields = $handler->export_instance_data_object($createdcourse['id']);
$this->assertEquals((object) [
'text' => 'And I want to tell you so much',
'textarea' => '<div class="text_to_html">I love you</div>',
], $customfields);
} else {
throw new moodle_exception('Unexpected shortname');
}
}
// Call without required capability
$this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
$this->expectException('required_capability_exception');
$createdsubcats = core_course_external::create_courses($courses);
}
/**
* Data provider for testing empty fields produce expected exceptions
*
* @see test_create_courses_empty_field
* @see test_update_courses_empty_field
*
* @return array
*/
public static function course_empty_field_provider(): array {
return [
[[
'fullname' => '',
'shortname' => 'ws101',
], 'fullname'],
[[
'fullname' => ' ',
'shortname' => 'ws101',
], 'fullname'],
[[
'fullname' => 'Web Services',
'shortname' => '',
], 'shortname'],
[[
'fullname' => 'Web Services',
'shortname' => ' ',
], 'shortname'],
];
}
/**
* Test creating courses with empty fields throws an exception
*
* @param array $course
* @param string $expectedemptyfield
*
* @dataProvider course_empty_field_provider
*/
public function test_create_courses_empty_field(array $course, string $expectedemptyfield): void {
$this->resetAfterTest();
$this->setAdminUser();
// Create a category for the new course.
$course['categoryid'] = $this->getDataGenerator()->create_category()->id;
$this->expectException(moodle_exception::class);
$this->expectExceptionMessageMatches("/{$expectedemptyfield}/");
core_course_external::create_courses([$course]);
}
/**
* Test updating courses with empty fields returns warnings
*
* @param array $course
* @param string $expectedemptyfield
*
* @dataProvider course_empty_field_provider
*/
public function test_update_courses_empty_field(array $course, string $expectedemptyfield): void {
$this->resetAfterTest();
$this->setAdminUser();
// Create a course to update.
$course['id'] = $this->getDataGenerator()->create_course()->id;
$result = core_course_external::update_courses([$course]);
$result = core_course_external::clean_returnvalue(core_course_external::update_courses_returns(), $result);
$this->assertCount(1, $result['warnings']);
$warning = reset($result['warnings']);
$this->assertEquals('errorinvalidparam', $warning['warningcode']);
$this->assertStringContainsString($expectedemptyfield, $warning['message']);
}
/**
* Test delete_courses
*/
public function test_delete_courses(): void {
global $DB, $USER;
$this->resetAfterTest(true);
// Admin can delete a course.
$this->setAdminUser();
// Validate_context() will fail as the email is not set by $this->setAdminUser().
$USER->email = '[email protected]';
$course1 = self::getDataGenerator()->create_course();
$course2 = self::getDataGenerator()->create_course();
$course3 = self::getDataGenerator()->create_course();
// Delete courses.
$result = core_course_external::delete_courses(array($course1->id, $course2->id));
$result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
// Check for 0 warnings.
$this->assertEquals(0, count($result['warnings']));
// Check $course 1 and 2 are deleted.
$notdeletedcount = $DB->count_records_select('course',
'id IN ( ' . $course1->id . ',' . $course2->id . ')');
$this->assertEquals(0, $notdeletedcount);
// Try to delete non-existent course.
$result = core_course_external::delete_courses(array($course1->id));
$result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
// Check for 1 warnings.
$this->assertEquals(1, count($result['warnings']));
// Try to delete Frontpage course.
$result = core_course_external::delete_courses(array(0));
$result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
// Check for 1 warnings.
$this->assertEquals(1, count($result['warnings']));
// Fail when the user has access to course (enrolled) but does not have permission or is not admin.
$student1 = self::getDataGenerator()->create_user();
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
$this->getDataGenerator()->enrol_user($student1->id,
$course3->id,
$studentrole->id);
$this->setUser($student1);
$result = core_course_external::delete_courses(array($course3->id));
$result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
// Check for 1 warnings.
$this->assertEquals(1, count($result['warnings']));
// Fail when the user is not allow to access the course (enrolled) or is not admin.
$this->setGuestUser();
$this->expectException('require_login_exception');
$result = core_course_external::delete_courses(array($course3->id));
$result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
}
/**
* Test get_courses
*/
public function test_get_courses(): void {
global $DB;
$this->resetAfterTest(true);
$generatedcourses = array();
$coursedata['idnumber'] = 'idnumbercourse1';
// Adding tags here to check that format_string is applied.
$coursedata['fullname'] = '<b>Course 1 for PHPunit test</b>';
$coursedata['shortname'] = '<b>Course 1 for PHPunit test</b>';
$coursedata['summary'] = 'Course 1 description';
$coursedata['summaryformat'] = FORMAT_MOODLE;
$course1 = self::getDataGenerator()->create_course($coursedata);
$fieldcategory = self::getDataGenerator()->create_custom_field_category(
['name' => 'Other fields']);
$customfield = ['shortname' => 'test', 'name' => 'Custom field', 'type' => 'text',
'categoryid' => $fieldcategory->get('id')];
$field = self::getDataGenerator()->create_custom_field($customfield);
$customfieldvalue = ['shortname' => 'test', 'value' => 'Test value'];
$generatedcourses[$course1->id] = $course1;
$course2 = self::getDataGenerator()->create_course();
$generatedcourses[$course2->id] = $course2;
$course3 = self::getDataGenerator()->create_course(array('format' => 'topics'));
$generatedcourses[$course3->id] = $course3;
$course4 = self::getDataGenerator()->create_course(['customfields' => [$customfieldvalue]]);
$generatedcourses[$course4->id] = $course4;
// Set the required capabilities by the external function.
$context = context_system::instance();
$roleid = $this->assignUserCapability('moodle/course:view', $context->id);
$this->assignUserCapability('moodle/course:update',
context_course::instance($course1->id)->id, $roleid);
$this->assignUserCapability('moodle/course:update',
context_course::instance($course2->id)->id, $roleid);
$this->assignUserCapability('moodle/course:update',
context_course::instance($course3->id)->id, $roleid);
$this->assignUserCapability('moodle/course:update',
context_course::instance($course4->id)->id, $roleid);
$courses = core_course_external::get_courses(array('ids' =>
array($course1->id, $course2->id, $course4->id)));
// We need to execute the return values cleaning process to simulate the web service server.
$courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
// Check we retrieve the good total number of courses.
$this->assertEquals(3, count($courses));
foreach ($courses as $course) {
$coursecontext = context_course::instance($course['id']);
$dbcourse = $generatedcourses[$course['id']];
$this->assertEquals($course['idnumber'], $dbcourse->idnumber);
$this->assertEquals(
$course['fullname'],
\core_external\util::format_string($dbcourse->fullname, $coursecontext->id)
);
$this->assertEquals(
$course['displayname'],
\core_external\util::format_string(get_course_display_name_for_list($dbcourse), $coursecontext->id)
);
// Summary was converted to the HTML format.
$this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false)));
$this->assertEquals($course['summaryformat'], FORMAT_HTML);
$this->assertEquals($course['shortname'], \core_external\util::format_string($dbcourse->shortname, $coursecontext->id));
$this->assertEquals($course['categoryid'], $dbcourse->category);
$this->assertEquals($course['format'], $dbcourse->format);
$this->assertEquals($course['showgrades'], $dbcourse->showgrades);
$this->assertEquals($course['newsitems'], $dbcourse->newsitems);
$this->assertEquals($course['startdate'], $dbcourse->startdate);
$this->assertEquals($course['enddate'], $dbcourse->enddate);
$this->assertEquals($course['numsections'], course_get_format($dbcourse)->get_last_section_number());
$this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
$this->assertEquals($course['showreports'], $dbcourse->showreports);
$this->assertEquals($course['visible'], $dbcourse->visible);
$this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
$this->assertEquals($course['groupmode'], $dbcourse->groupmode);
$this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
$this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
$this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
$this->assertEquals($course['lang'], $dbcourse->lang);
$this->assertEquals($course['forcetheme'], $dbcourse->theme);
$this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
if ($dbcourse->format === 'topics') {
$this->assertEquals($course['courseformatoptions'], array(
array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
));
}
// Assert custom field that we previously added to test course 4.
if ($dbcourse->id == $course4->id) {
$this->assertEquals([
'shortname' => $customfield['shortname'],
'name' => $customfield['name'],
'type' => $customfield['type'],
'value' => $customfieldvalue['value'],
'valueraw' => $customfieldvalue['value'],
], $course['customfields'][0]);
}
}
// Get all courses in the DB
$courses = core_course_external::get_courses(array());
// We need to execute the return values cleaning process to simulate the web service server.
$courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
$this->assertEquals($DB->count_records('course'), count($courses));
}
/**
* Test retrieving courses returns custom field data
*/
public function test_get_courses_customfields(): void {
$this->resetAfterTest();
$this->setAdminUser();
$fieldcategory = $this->getDataGenerator()->create_custom_field_category([]);
$datefield = $this->getDataGenerator()->create_custom_field([
'categoryid' => $fieldcategory->get('id'),
'shortname' => 'mydate',
'name' => 'My date',
'type' => 'date',
]);
$newcourse = $this->getDataGenerator()->create_course(['customfields' => [
[
'shortname' => $datefield->get('shortname'),
'value' => 1580389200, // 30/01/2020 13:00 GMT.
],
]]);
$courses = external_api::clean_returnvalue(
core_course_external::get_courses_returns(),
core_course_external::get_courses(['ids' => [$newcourse->id]])
);
$this->assertCount(1, $courses);
$course = reset($courses);
$this->assertArrayHasKey('customfields', $course);
$this->assertCount(1, $course['customfields']);
// Assert the received custom field, "value" containing a human-readable version and "valueraw" the unmodified version.
$this->assertEquals([
'name' => $datefield->get('name'),
'shortname' => $datefield->get('shortname'),
'type' => $datefield->get('type'),
'value' => userdate(1580389200),
'valueraw' => 1580389200,
], reset($course['customfields']));
// Set the multilang filter to apply to strings + reset filer caches.
filter_set_global_state('multilang', TEXTFILTER_ON);
filter_set_applies_to_strings('multilang', true);
\filter_manager::reset_caches();
// Let's create a custom field (number), and test the placeholders/multilang display.
/** @var core_customfield_generator $cfgenerator */
$cfgenerator = $this->getDataGenerator()->get_plugin_generator('core_customfield');
$numberfieldata = [
'categoryid' => $fieldcategory->get('id'),
'name' => 'Price',
'shortname' => 'price',
'type' => 'number',
'configdata' => [
'display' => '{value}',
'decimalplaces' => 2,
],
];
// Create a number custom field with default display template.
$numberfield = $cfgenerator->create_field($numberfieldata);
$cfgenerator->add_instance_data($numberfield, $newcourse->id, 15);
// Create a number custom field with multilang display template.
$numberfieldata['name'] = 'Price (multilang)';
$numberfieldata['shortname'] = 'pricemultilang';
$numberfieldata['configdata']['display'] = '<span lang="en" class="multilang">$ {value}</span>'
. '<span lang="es" class="multilang">€ {value}</span>';
$numberfield1 = $cfgenerator->create_field($numberfieldata);
$cfgenerator->add_instance_data($numberfield1, $newcourse->id, 20);
$courses = external_api::clean_returnvalue(
core_course_external::get_courses_returns(),
core_course_external::get_courses(['ids' => [$newcourse->id]])
);
$course = reset($courses);
$this->assertCount(3, $course['customfields']);
// Assert the received number custom fields display placeholders correctly with multilang filter when applied.
$this->assertEquals('15.00', $course['customfields'][1]['value']);
$this->assertEquals('$ 20.00', $course['customfields'][2]['value']);
}
/**
* Test get_courses without capability
*/
public function test_get_courses_without_capability(): void {
$this->resetAfterTest(true);
$course1 = $this->getDataGenerator()->create_course();
$this->setUser($this->getDataGenerator()->create_user());
// No permissions are required to get the site course.
$courses = core_course_external::get_courses(array('ids' => [SITEID]));
$courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
$this->assertEquals(1, count($courses));
$this->assertEquals('PHPUnit test site', $courses[0]['fullname']);
$this->assertEquals('site', $courses[0]['format']);
// Requesting course without being enrolled or capability to view it will throw an exception.
try {
core_course_external::get_courses(array('ids' => [$course1->id]));
$this->fail('Exception expected');
} catch (moodle_exception $e) {
$this->assertEquals(1, preg_match('/Course or activity not accessible. \(Not enrolled\)/', $e->getMessage()));
}
}
/**
* Test search_courses
*/
public function test_search_courses(): void {
global $DB;
$this->resetAfterTest(true);
$this->setAdminUser();
$generatedcourses = array();
$coursedata1['fullname'] = 'FIRST COURSE';
$course1 = self::getDataGenerator()->create_course($coursedata1);
$page = new moodle_page();
$page->set_course($course1);
$page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
$coursedata2['fullname'] = 'SECOND COURSE';
$course2 = self::getDataGenerator()->create_course($coursedata2);
$page = new moodle_page();
$page->set_course($course2);
$page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
// Search by name.
$results = core_course_external::search_courses('search', 'FIRST');
$results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
$this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
$this->assertCount(1, $results['courses']);
// Create the forum.
$record = new stdClass();
$record->introformat = FORMAT_HTML;
$record->course = $course2->id;
// Set Aggregate type = Average of ratings.