eacc7a3fbf4278d3b3bed50e3e8f225e5fd86ce3
[moodle.git] / lib / tests / completionlib_test.php
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/>.
17 /**
18  * Completion tests.
19  *
20  * @package    core_completion
21  * @category   phpunit
22  * @copyright  2008 Sam Marshall
23  * @copyright  2013 Frédéric Massart
24  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  */
27 defined('MOODLE_INTERNAL') || die();
29 global $CFG;
30 require_once($CFG->libdir.'/completionlib.php');
32 class core_completionlib_testcase extends advanced_testcase {
33     protected $course;
34     protected $user;
35     protected $module1;
36     protected $module2;
38     protected function mock_setup() {
39         global $DB, $CFG, $USER;
41         $this->resetAfterTest();
43         $DB = $this->createMock(get_class($DB));
44         $CFG->enablecompletion = COMPLETION_ENABLED;
45         $USER = (object)array('id' =>314159);
46     }
48     /**
49      * Create course with user and activities.
50      */
51     protected function setup_data() {
52         global $DB, $CFG;
54         $this->resetAfterTest();
56         // Enable completion before creating modules, otherwise the completion data is not written in DB.
57         $CFG->enablecompletion = true;
59         // Create a course with activities.
60         $this->course = $this->getDataGenerator()->create_course(array('enablecompletion' => true));
61         $this->user = $this->getDataGenerator()->create_user();
62         $this->getDataGenerator()->enrol_user($this->user->id, $this->course->id);
64         $this->module1 = $this->getDataGenerator()->create_module('forum', array('course' => $this->course->id));
65         $this->module2 = $this->getDataGenerator()->create_module('forum', array('course' => $this->course->id));
66     }
68     /**
69      * Asserts that two variables are equal.
70      *
71      * @param  mixed   $expected
72      * @param  mixed   $actual
73      * @param  string  $message
74      * @param  float   $delta
75      * @param  integer $maxDepth
76      * @param  boolean $canonicalize
77      * @param  boolean $ignoreCase
78      */
79     public static function assertEquals($expected, $actual, string $message = '', float $delta = 0, int $maxDepth = 10,
80                                         bool $canonicalize = false, bool $ignoreCase = false): void {
81         // Nasty cheating hack: prevent random failures on timemodified field.
82         if (is_object($expected) and is_object($actual)) {
83             if (property_exists($expected, 'timemodified') and property_exists($actual, 'timemodified')) {
84                 if ($expected->timemodified + 1 == $actual->timemodified) {
85                     $expected = clone($expected);
86                     $expected->timemodified = $actual->timemodified;
87                 }
88             }
89         }
90         parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
91     }
93     public function test_is_enabled() {
94         global $CFG;
95         $this->mock_setup();
97         // Config alone.
98         $CFG->enablecompletion = COMPLETION_DISABLED;
99         $this->assertEquals(COMPLETION_DISABLED, completion_info::is_enabled_for_site());
100         $CFG->enablecompletion = COMPLETION_ENABLED;
101         $this->assertEquals(COMPLETION_ENABLED, completion_info::is_enabled_for_site());
103         // Course.
104         $course = (object)array('id' =>13);
105         $c = new completion_info($course);
106         $course->enablecompletion = COMPLETION_DISABLED;
107         $this->assertEquals(COMPLETION_DISABLED, $c->is_enabled());
108         $course->enablecompletion = COMPLETION_ENABLED;
109         $this->assertEquals(COMPLETION_ENABLED, $c->is_enabled());
110         $CFG->enablecompletion = COMPLETION_DISABLED;
111         $this->assertEquals(COMPLETION_DISABLED, $c->is_enabled());
113         // Course and CM.
114         $cm = new stdClass();
115         $cm->completion = COMPLETION_TRACKING_MANUAL;
116         $this->assertEquals(COMPLETION_DISABLED, $c->is_enabled($cm));
117         $CFG->enablecompletion = COMPLETION_ENABLED;
118         $course->enablecompletion = COMPLETION_DISABLED;
119         $this->assertEquals(COMPLETION_DISABLED, $c->is_enabled($cm));
120         $course->enablecompletion = COMPLETION_ENABLED;
121         $this->assertEquals(COMPLETION_TRACKING_MANUAL, $c->is_enabled($cm));
122         $cm->completion = COMPLETION_TRACKING_NONE;
123         $this->assertEquals(COMPLETION_TRACKING_NONE, $c->is_enabled($cm));
124         $cm->completion = COMPLETION_TRACKING_AUTOMATIC;
125         $this->assertEquals(COMPLETION_TRACKING_AUTOMATIC, $c->is_enabled($cm));
126     }
128     public function test_update_state() {
129         $this->mock_setup();
131         $mockbuilder = $this->getMockBuilder('completion_info');
132         $mockbuilder->setMethods(array('is_enabled', 'get_data', 'internal_get_state', 'internal_set_data',
133                                        'user_can_override_completion'));
134         $mockbuilder->setConstructorArgs(array((object)array('id' => 42)));
135         $c = $mockbuilder->getMock();
136         $cm = (object)array('id'=>13, 'course'=>42);
138         // Not enabled, should do nothing.
139         $c->expects($this->at(0))
140             ->method('is_enabled')
141             ->with($cm)
142             ->will($this->returnValue(false));
143         $c->update_state($cm);
145         // Enabled, but current state is same as possible result, do nothing.
146         $current = (object)array('completionstate' => COMPLETION_COMPLETE, 'overrideby' => null);
147         $c->expects($this->at(0))
148             ->method('is_enabled')
149             ->with($cm)
150             ->will($this->returnValue(true));
151         $c->expects($this->at(1))
152             ->method('get_data')
153             ->with($cm, false, 0)
154             ->will($this->returnValue($current));
155         $c->update_state($cm, COMPLETION_COMPLETE);
157         // Enabled, but current state is a specific one and new state is just
158         // complete, so do nothing.
159         $current->completionstate = COMPLETION_COMPLETE_PASS;
160         $c->expects($this->at(0))
161             ->method('is_enabled')
162             ->with($cm)
163             ->will($this->returnValue(true));
164         $c->expects($this->at(1))
165             ->method('get_data')
166             ->with($cm, false, 0)
167             ->will($this->returnValue($current));
168         $c->update_state($cm, COMPLETION_COMPLETE);
170         // Manual, change state (no change).
171         $cm = (object)array('id'=>13, 'course'=>42, 'completion'=>COMPLETION_TRACKING_MANUAL);
172         $current->completionstate=COMPLETION_COMPLETE;
173         $c->expects($this->at(0))
174             ->method('is_enabled')
175             ->with($cm)
176             ->will($this->returnValue(true));
177         $c->expects($this->at(1))
178             ->method('get_data')
179             ->with($cm, false, 0)
180             ->will($this->returnValue($current));
181         $c->update_state($cm, COMPLETION_COMPLETE);
183         // Manual, change state (change).
184         $c->expects($this->at(0))
185             ->method('is_enabled')
186             ->with($cm)
187             ->will($this->returnValue(true));
188         $c->expects($this->at(1))
189             ->method('get_data')
190             ->with($cm, false, 0)
191             ->will($this->returnValue($current));
192         $changed = clone($current);
193         $changed->timemodified = time();
194         $changed->completionstate = COMPLETION_INCOMPLETE;
195         $comparewith = new phpunit_constraint_object_is_equal_with_exceptions($changed);
196         $comparewith->add_exception('timemodified', 'assertGreaterThanOrEqual');
197         $c->expects($this->at(2))
198             ->method('internal_set_data')
199             ->with($cm, $comparewith);
200         $c->update_state($cm, COMPLETION_INCOMPLETE);
202         // Auto, change state.
203         $cm = (object)array('id'=>13, 'course'=>42, 'completion'=>COMPLETION_TRACKING_AUTOMATIC);
204         $current = (object)array('completionstate' => COMPLETION_COMPLETE, 'overrideby' => null);
205         $c->expects($this->at(0))
206             ->method('is_enabled')
207             ->with($cm)
208             ->will($this->returnValue(true));
209         $c->expects($this->at(1))
210             ->method('get_data')
211             ->with($cm, false, 0)
212             ->will($this->returnValue($current));
213         $c->expects($this->at(2))
214             ->method('internal_get_state')
215             ->will($this->returnValue(COMPLETION_COMPLETE_PASS));
216         $changed = clone($current);
217         $changed->timemodified = time();
218         $changed->completionstate = COMPLETION_COMPLETE_PASS;
219         $comparewith = new phpunit_constraint_object_is_equal_with_exceptions($changed);
220         $comparewith->add_exception('timemodified', 'assertGreaterThanOrEqual');
221         $c->expects($this->at(3))
222             ->method('internal_set_data')
223             ->with($cm, $comparewith);
224         $c->update_state($cm, COMPLETION_COMPLETE_PASS);
226         // Manual tracking, change state by overriding it manually.
227         $cm = (object)array('id' => 13, 'course' => 42, 'completion' => COMPLETION_TRACKING_MANUAL);
228         $current = (object)array('completionstate' => COMPLETION_INCOMPLETE, 'overrideby' => null);
229         $c->expects($this->at(0))
230             ->method('is_enabled')
231             ->with($cm)
232             ->will($this->returnValue(true));
233         $c->expects($this->at(1)) // Pretend the user has the required capability for overriding completion statuses.
234             ->method('user_can_override_completion')
235             ->will($this->returnValue(true));
236         $c->expects($this->at(2))
237             ->method('get_data')
238             ->with($cm, false, 100)
239             ->will($this->returnValue($current));
240         $changed = clone($current);
241         $changed->timemodified = time();
242         $changed->completionstate = COMPLETION_COMPLETE;
243         $changed->overrideby = 314159;
244         $comparewith = new phpunit_constraint_object_is_equal_with_exceptions($changed);
245         $comparewith->add_exception('timemodified', 'assertGreaterThanOrEqual');
246         $c->expects($this->at(3))
247             ->method('internal_set_data')
248             ->with($cm, $comparewith);
249         $c->update_state($cm, COMPLETION_COMPLETE, 100, true);
250         // And confirm that the status can be changed back to incomplete without an override.
251         $c->update_state($cm, COMPLETION_INCOMPLETE, 100);
252         $c->expects($this->at(0))
253             ->method('get_data')
254             ->with($cm, false, 100)
255             ->will($this->returnValue($current));
256         $c->get_data($cm, false, 100);
258         // Auto, change state via override, incomplete to complete.
259         $cm = (object)array('id' => 13, 'course' => 42, 'completion' => COMPLETION_TRACKING_AUTOMATIC);
260         $current = (object)array('completionstate' => COMPLETION_INCOMPLETE, 'overrideby' => null);
261         $c->expects($this->at(0))
262             ->method('is_enabled')
263             ->with($cm)
264             ->will($this->returnValue(true));
265         $c->expects($this->at(1)) // Pretend the user has the required capability for overriding completion statuses.
266             ->method('user_can_override_completion')
267             ->will($this->returnValue(true));
268         $c->expects($this->at(2))
269             ->method('get_data')
270             ->with($cm, false, 100)
271             ->will($this->returnValue($current));
272         $changed = clone($current);
273         $changed->timemodified = time();
274         $changed->completionstate = COMPLETION_COMPLETE;
275         $changed->overrideby = 314159;
276         $comparewith = new phpunit_constraint_object_is_equal_with_exceptions($changed);
277         $comparewith->add_exception('timemodified', 'assertGreaterThanOrEqual');
278         $c->expects($this->at(3))
279             ->method('internal_set_data')
280             ->with($cm, $comparewith);
281         $c->update_state($cm, COMPLETION_COMPLETE, 100, true);
282         $c->expects($this->at(0))
283             ->method('get_data')
284             ->with($cm, false, 100)
285             ->will($this->returnValue($changed));
286         $c->get_data($cm, false, 100);
288         // Now confirm that the status cannot be changed back to incomplete without an override.
289         // I.e. test that automatic completion won't trigger a change back to COMPLETION_INCOMPLETE when overridden.
290         $c->update_state($cm, COMPLETION_INCOMPLETE, 100);
291         $c->expects($this->at(0))
292             ->method('get_data')
293             ->with($cm, false, 100)
294             ->will($this->returnValue($changed));
295         $c->get_data($cm, false, 100);
297         // Now confirm the status can be changed back from complete to incomplete using an override.
298         $cm = (object)array('id' => 13, 'course' => 42, 'completion' => COMPLETION_TRACKING_AUTOMATIC);
299         $current = (object)array('completionstate' => COMPLETION_COMPLETE, 'overrideby' => 2);
300         $c->expects($this->at(0))
301             ->method('is_enabled')
302             ->with($cm)
303             ->will($this->returnValue(true));
304         $c->expects($this->at(1)) // Pretend the user has the required capability for overriding completion statuses.
305         ->method('user_can_override_completion')
306             ->will($this->returnValue(true));
307         $c->expects($this->at(2))
308             ->method('get_data')
309             ->with($cm, false, 100)
310             ->will($this->returnValue($current));
311         $changed = clone($current);
312         $changed->timemodified = time();
313         $changed->completionstate = COMPLETION_INCOMPLETE;
314         $changed->overrideby = 314159;
315         $comparewith = new phpunit_constraint_object_is_equal_with_exceptions($changed);
316         $comparewith->add_exception('timemodified', 'assertGreaterThanOrEqual');
317         $c->expects($this->at(3))
318             ->method('internal_set_data')
319             ->with($cm, $comparewith);
320         $c->update_state($cm, COMPLETION_INCOMPLETE, 100, true);
321         $c->expects($this->at(0))
322             ->method('get_data')
323             ->with($cm, false, 100)
324             ->will($this->returnValue($changed));
325         $c->get_data($cm, false, 100);
326     }
328     /**
329      * Data provider for test_internal_get_state().
330      *
331      * @return array[]
332      */
333     public function internal_get_state_provider() {
334         return [
335             'View required, but not viewed yet' => [
336                 COMPLETION_VIEW_REQUIRED, 1, '', COMPLETION_INCOMPLETE
337             ],
338             'View not required and not viewed yet' => [
339                 COMPLETION_VIEW_NOT_REQUIRED, 1, '', COMPLETION_INCOMPLETE
340             ],
341             'View not required, grade required but no grade yet, $cm->modname not set' => [
342                 COMPLETION_VIEW_NOT_REQUIRED, 1, 'modname', COMPLETION_INCOMPLETE
343             ],
344             'View not required, grade required but no grade yet, $cm->course not set' => [
345                 COMPLETION_VIEW_NOT_REQUIRED, 1, 'course', COMPLETION_INCOMPLETE
346             ],
347             'View not required, grade not required' => [
348                 COMPLETION_VIEW_NOT_REQUIRED, 0, '', COMPLETION_COMPLETE
349             ],
350         ];
351     }
353     /**
354      * Test for completion_info::get_state().
355      *
356      * @dataProvider internal_get_state_provider
357      * @param int $completionview
358      * @param int $completionusegrade
359      * @param string $unsetfield
360      * @param int $expectedstate
361      */
362     public function test_internal_get_state(int $completionview, int $completionusegrade, string $unsetfield, int $expectedstate) {
363         $this->setup_data();
365         /** @var \mod_assign_generator $assigngenerator */
366         $assigngenerator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
367         $assign = $assigngenerator->create_instance([
368             'course' => $this->course->id,
369             'completion' => COMPLETION_ENABLED,
370             'completionview' => $completionview,
371             'completionusegrade' => $completionusegrade,
372         ]);
374         $userid = $this->user->id;
375         $this->setUser($userid);
377         $cm = get_coursemodule_from_instance('assign', $assign->id);
378         if ($unsetfield) {
379             unset($cm->$unsetfield);
380         }
381         // If view is required, but they haven't viewed it yet.
382         $current = (object)['viewed' => COMPLETION_NOT_VIEWED];
384         $completioninfo = new completion_info($this->course);
385         $this->assertEquals($expectedstate, $completioninfo->internal_get_state($cm, $userid, $current));
386     }
388     /**
389      * Covers the case where internal_get_state() is being called for a user different from the logged in user.
390      */
391     public function test_internal_get_state_with_different_user() {
392         $this->setup_data();
394         /** @var \mod_assign_generator $assigngenerator */
395         $assigngenerator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
396         $assign = $assigngenerator->create_instance([
397             'course' => $this->course->id,
398             'completion' => COMPLETION_ENABLED,
399             'completionusegrade' => 1,
400         ]);
402         $userid = $this->user->id;
404         $cm = get_coursemodule_from_instance('assign', $assign->id);
405         $usercm = cm_info::create($cm, $userid);
407         // Create a teacher account.
408         $teacher = $this->getDataGenerator()->create_user();
409         $this->getDataGenerator()->enrol_user($teacher->id, $this->course->id, 'editingteacher');
410         // Log in as the teacher.
411         $this->setUser($teacher);
413         // Grade the student for this assignment.
414         $assign = new assign($usercm->context, $cm, $cm->course);
415         $data = (object)[
416             'sendstudentnotifications' => false,
417             'attemptnumber' => 1,
418             'grade' => 90,
419         ];
420         $assign->save_grade($userid, $data);
422         // The target user already received a grade, so internal_get_state should be already complete.
423         $completioninfo = new completion_info($this->course);
424         $this->assertEquals(COMPLETION_COMPLETE, $completioninfo->internal_get_state($cm, $userid, null));
426         // As the teacher which does not have a grade in this cm, internal_get_state should return incomplete.
427         $this->assertEquals(COMPLETION_INCOMPLETE, $completioninfo->internal_get_state($cm, $teacher->id, null));
428     }
430     public function test_set_module_viewed() {
431         $this->mock_setup();
433         $mockbuilder = $this->getMockBuilder('completion_info');
434         $mockbuilder->setMethods(array('is_enabled', 'get_data', 'internal_set_data', 'update_state'));
435         $mockbuilder->setConstructorArgs(array((object)array('id' => 42)));
436         $c = $mockbuilder->getMock();
437         $cm = (object)array('id'=>13, 'course'=>42);
439         // Not tracking completion, should do nothing.
440         $cm->completionview = COMPLETION_VIEW_NOT_REQUIRED;
441         $c->set_module_viewed($cm);
443         // Tracking completion but completion is disabled, should do nothing.
444         $cm->completionview = COMPLETION_VIEW_REQUIRED;
445         $c->expects($this->at(0))
446             ->method('is_enabled')
447             ->with($cm)
448             ->will($this->returnValue(false));
449         $c->set_module_viewed($cm);
451         // Now it's enabled, we expect it to get data. If data already has
452         // viewed, still do nothing.
453         $c->expects($this->at(0))
454             ->method('is_enabled')
455             ->with($cm)
456             ->will($this->returnValue(true));
457         $c->expects($this->at(1))
458             ->method('get_data')
459             ->with($cm, 0)
460             ->will($this->returnValue((object)array('viewed'=>COMPLETION_VIEWED)));
461         $c->set_module_viewed($cm);
463         // OK finally one that hasn't been viewed, now it should set it viewed
464         // and update state.
465         $c->expects($this->at(0))
466             ->method('is_enabled')
467             ->with($cm)
468             ->will($this->returnValue(true));
469         $c->expects($this->at(1))
470             ->method('get_data')
471             ->with($cm, false, 1337)
472             ->will($this->returnValue((object)array('viewed'=>COMPLETION_NOT_VIEWED)));
473         $c->expects($this->at(2))
474             ->method('internal_set_data')
475             ->with($cm, (object)array('viewed'=>COMPLETION_VIEWED));
476         $c->expects($this->at(3))
477             ->method('update_state')
478             ->with($cm, COMPLETION_COMPLETE, 1337);
479         $c->set_module_viewed($cm, 1337);
480     }
482     public function test_count_user_data() {
483         global $DB;
484         $this->mock_setup();
486         $course = (object)array('id'=>13);
487         $cm = (object)array('id'=>42);
489         /** @var $DB PHPUnit_Framework_MockObject_MockObject */
490         $DB->expects($this->at(0))
491             ->method('get_field_sql')
492             ->will($this->returnValue(666));
494         $c = new completion_info($course);
495         $this->assertEquals(666, $c->count_user_data($cm));
496     }
498     public function test_delete_all_state() {
499         global $DB;
500         $this->mock_setup();
502         $course = (object)array('id'=>13);
503         $cm = (object)array('id'=>42, 'course'=>13);
504         $c = new completion_info($course);
506         // Check it works ok without data in session.
507         /** @var $DB PHPUnit_Framework_MockObject_MockObject */
508         $DB->expects($this->at(0))
509             ->method('delete_records')
510             ->with('course_modules_completion', array('coursemoduleid'=>42))
511             ->will($this->returnValue(true));
512         $c->delete_all_state($cm);
513     }
515     public function test_reset_all_state() {
516         global $DB;
517         $this->mock_setup();
519         $mockbuilder = $this->getMockBuilder('completion_info');
520         $mockbuilder->setMethods(array('delete_all_state', 'get_tracked_users', 'update_state'));
521         $mockbuilder->setConstructorArgs(array((object)array('id' => 42)));
522         $c = $mockbuilder->getMock();
524         $cm = (object)array('id'=>13, 'course'=>42, 'completion'=>COMPLETION_TRACKING_AUTOMATIC);
526         /** @var $DB PHPUnit_Framework_MockObject_MockObject */
527         $DB->expects($this->at(0))
528             ->method('get_recordset')
529             ->will($this->returnValue(
530                 new core_completionlib_fake_recordset(array((object)array('id'=>1, 'userid'=>100), (object)array('id'=>2, 'userid'=>101)))));
532         $c->expects($this->at(0))
533             ->method('delete_all_state')
534             ->with($cm);
536         $c->expects($this->at(1))
537             ->method('get_tracked_users')
538             ->will($this->returnValue(array(
539             (object)array('id'=>100, 'firstname'=>'Woot', 'lastname'=>'Plugh'),
540             (object)array('id'=>201, 'firstname'=>'Vroom', 'lastname'=>'Xyzzy'))));
542         $c->expects($this->at(2))
543             ->method('update_state')
544             ->with($cm, COMPLETION_UNKNOWN, 100);
545         $c->expects($this->at(3))
546             ->method('update_state')
547             ->with($cm, COMPLETION_UNKNOWN, 101);
548         $c->expects($this->at(4))
549             ->method('update_state')
550             ->with($cm, COMPLETION_UNKNOWN, 201);
552         $c->reset_all_state($cm);
553     }
555     /**
556      * Data provider for test_get_data().
557      *
558      * @return array[]
559      */
560     public function get_data_provider() {
561         return [
562             'No completion record' => [
563                 false, false, false, COMPLETION_INCOMPLETE
564             ],
565             'Not completed' => [
566                 false, false, true, COMPLETION_INCOMPLETE
567             ],
568             'Completed' => [
569                 false, false, true, COMPLETION_COMPLETE
570             ],
571             'Whole course, complete' => [
572                 true, false, true, COMPLETION_COMPLETE
573             ],
574             'Get data for another user, result should be not cached' => [
575                 false, true, true,  COMPLETION_INCOMPLETE
576             ],
577         ];
578     }
580     /**
581      * Tests for completion_info::get_data().
582      *
583      * @dataProvider get_data_provider
584      * @param bool $wholecourse Whole course parameter for get_data().
585      * @param bool $sameuser Whether the user calling get_data() is the user itself.
586      * @param bool $hasrecord Whether to create a course_modules_completion record.
587      * @param int $completion The completion state expected.
588      */
589     public function test_get_data(bool $wholecourse, bool $sameuser, bool $hasrecord, int $completion) {
590         global $DB;
592         $this->setup_data();
593         $user = $this->user;
595         /** @var \mod_choice_generator $choicegenerator */
596         $choicegenerator = $this->getDataGenerator()->get_plugin_generator('mod_choice');
597         $choice = $choicegenerator->create_instance([
598             'course' => $this->course->id,
599             'completion' => true,
600             'completionview' => true,
601         ]);
603         $cm = get_coursemodule_from_instance('choice', $choice->id);
605         // Let's manually create a course completion record instead of going thru the hoops to complete an activity.
606         if ($hasrecord) {
607             $cmcompletionrecord = (object)[
608                 'coursemoduleid' => $cm->id,
609                 'userid' => $user->id,
610                 'completionstate' => $completion,
611                 'viewed' => 0,
612                 'overrideby' => null,
613                 'timemodified' => 0,
614             ];
615             $DB->insert_record('course_modules_completion', $cmcompletionrecord);
616         }
618         // Whether we expect for the returned completion data to be stored in the cache.
619         $iscached = true;
621         if (!$sameuser) {
622             $iscached = false;
623             $this->setAdminUser();
624         } else {
625             $this->setUser($user);
626         }
628         // Mock other completion data.
629         $completioninfo = new completion_info($this->course);
631         $result = $completioninfo->get_data($cm, $wholecourse, $user->id);
632         // Course module ID of the returned completion data must match this activity's course module ID.
633         $this->assertEquals($cm->id, $result->coursemoduleid);
634         // User ID of the returned completion data must match the user's ID.
635         $this->assertEquals($user->id, $result->userid);
636         // The completion state of the returned completion data must match the expected completion state.
637         $this->assertEquals($completion, $result->completionstate);
639         // If the user has no completion record, then the default record should be returned.
640         if (!$hasrecord) {
641             $iscached = false;
642             $this->assertEquals(0, $result->id);
643         }
645         // Check caching.
646         $key = "{$user->id}_{$this->course->id}";
647         $cache = cache::make('core', 'completion');
648         if ($iscached) {
649             // If we expect this to be cached, then fetching the result must match the cached data.
650             $this->assertEquals($result, (object)$cache->get($key)[$cm->id]);
652             // Check cached data for other course modules in the course.
653             // The sample module created in setup_data() should suffice to confirm this.
654             if ($wholecourse) {
655                 $this->assertArrayHasKey($this->module1->id, $cache->get($key));
656             } else {
657                 $this->assertArrayNotHasKey($this->module1->id, $cache->get($key));
658             }
659         } else {
660             // Otherwise, this should not be cached.
661             $this->assertFalse($cache->get($key));
662         }
663     }
665     public function test_internal_set_data() {
666         global $DB;
667         $this->setup_data();
669         $this->setUser($this->user);
670         $completionauto = array('completion' => COMPLETION_TRACKING_AUTOMATIC);
671         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $this->course->id), $completionauto);
672         $cm = get_coursemodule_from_instance('forum', $forum->id);
673         $c = new completion_info($this->course);
675         // 1) Test with new data.
676         $data = new stdClass();
677         $data->id = 0;
678         $data->userid = $this->user->id;
679         $data->coursemoduleid = $cm->id;
680         $data->completionstate = COMPLETION_COMPLETE;
681         $data->timemodified = time();
682         $data->viewed = COMPLETION_NOT_VIEWED;
683         $data->overrideby = null;
685         $c->internal_set_data($cm, $data);
686         $d1 = $DB->get_field('course_modules_completion', 'id', array('coursemoduleid' => $cm->id));
687         $this->assertEquals($d1, $data->id);
688         $cache = cache::make('core', 'completion');
689         // Cache was not set for another user.
690         $this->assertEquals(array('cacherev' => $this->course->cacherev, $cm->id => $data),
691             $cache->get($data->userid . '_' . $cm->course));
693         // 2) Test with existing data and for different user.
694         $forum2 = $this->getDataGenerator()->create_module('forum', array('course' => $this->course->id), $completionauto);
695         $cm2 = get_coursemodule_from_instance('forum', $forum2->id);
696         $newuser = $this->getDataGenerator()->create_user();
698         $d2 = new stdClass();
699         $d2->id = 7;
700         $d2->userid = $newuser->id;
701         $d2->coursemoduleid = $cm2->id;
702         $d2->completionstate = COMPLETION_COMPLETE;
703         $d2->timemodified = time();
704         $d2->viewed = COMPLETION_NOT_VIEWED;
705         $d2->overrideby = null;
706         $c->internal_set_data($cm2, $d2);
707         // Cache for current user returns the data.
708         $cachevalue = $cache->get($data->userid . '_' . $cm->course);
709         $this->assertEquals($data, $cachevalue[$cm->id]);
710         // Cache for another user is not filled.
711         $this->assertEquals(false, $cache->get($d2->userid . '_' . $cm2->course));
713         // 3) Test where it THINKS the data is new (from cache) but actually
714         //    in the database it has been set since.
715         // 1) Test with new data.
716         $forum3 = $this->getDataGenerator()->create_module('forum', array('course' => $this->course->id), $completionauto);
717         $cm3 = get_coursemodule_from_instance('forum', $forum3->id);
718         $newuser2 = $this->getDataGenerator()->create_user();
719         $d3 = new stdClass();
720         $d3->id = 13;
721         $d3->userid = $newuser2->id;
722         $d3->coursemoduleid = $cm3->id;
723         $d3->completionstate = COMPLETION_COMPLETE;
724         $d3->timemodified = time();
725         $d3->viewed = COMPLETION_NOT_VIEWED;
726         $d3->overrideby = null;
727         $DB->insert_record('course_modules_completion', $d3);
728         $c->internal_set_data($cm, $data);
729     }
731     public function test_get_progress_all() {
732         global $DB;
733         $this->mock_setup();
735         $mockbuilder = $this->getMockBuilder('completion_info');
736         $mockbuilder->setMethods(array('get_tracked_users'));
737         $mockbuilder->setConstructorArgs(array((object)array('id' => 42)));
738         $c = $mockbuilder->getMock();
740         // 1) Basic usage.
741         $c->expects($this->at(0))
742             ->method('get_tracked_users')
743             ->with(false,  array(),  0,  '',  '',  '',  null)
744             ->will($this->returnValue(array(
745                 (object)array('id'=>100, 'firstname'=>'Woot', 'lastname'=>'Plugh'),
746                 (object)array('id'=>201, 'firstname'=>'Vroom', 'lastname'=>'Xyzzy'))));
747         $DB->expects($this->at(0))
748             ->method('get_in_or_equal')
749             ->with(array(100, 201))
750             ->will($this->returnValue(array(' IN (100, 201)', array())));
751         $progress1 = (object)array('userid'=>100, 'coursemoduleid'=>13);
752         $progress2 = (object)array('userid'=>201, 'coursemoduleid'=>14);
753         $DB->expects($this->at(1))
754             ->method('get_recordset_sql')
755             ->will($this->returnValue(new core_completionlib_fake_recordset(array($progress1, $progress2))));
757         $this->assertEquals(array(
758                 100 => (object)array('id'=>100, 'firstname'=>'Woot', 'lastname'=>'Plugh',
759                     'progress'=>array(13=>$progress1)),
760                 201 => (object)array('id'=>201, 'firstname'=>'Vroom', 'lastname'=>'Xyzzy',
761                     'progress'=>array(14=>$progress2)),
762             ), $c->get_progress_all(false));
764         // 2) With more than 1, 000 results.
765         $tracked = array();
766         $ids = array();
767         $progress = array();
768         for ($i = 100; $i<2000; $i++) {
769             $tracked[] = (object)array('id'=>$i, 'firstname'=>'frog', 'lastname'=>$i);
770             $ids[] = $i;
771             $progress[] = (object)array('userid'=>$i, 'coursemoduleid'=>13);
772             $progress[] = (object)array('userid'=>$i, 'coursemoduleid'=>14);
773         }
774         $c->expects($this->at(0))
775             ->method('get_tracked_users')
776             ->with(true,  3,  0,  '',  '',  '',  null)
777             ->will($this->returnValue($tracked));
778         $DB->expects($this->at(0))
779             ->method('get_in_or_equal')
780             ->with(array_slice($ids, 0, 1000))
781             ->will($this->returnValue(array(' IN whatever', array())));
782         $DB->expects($this->at(1))
783             ->method('get_recordset_sql')
784             ->will($this->returnValue(new core_completionlib_fake_recordset(array_slice($progress, 0, 1000))));
786         $DB->expects($this->at(2))
787             ->method('get_in_or_equal')
788             ->with(array_slice($ids, 1000))
789             ->will($this->returnValue(array(' IN whatever2', array())));
790         $DB->expects($this->at(3))
791             ->method('get_recordset_sql')
792             ->will($this->returnValue(new core_completionlib_fake_recordset(array_slice($progress, 1000))));
794         $result = $c->get_progress_all(true, 3);
795         $resultok = true;
796         $resultok  =  $resultok && ($ids == array_keys($result));
798         foreach ($result as $userid => $data) {
799             $resultok  =  $resultok && $data->firstname == 'frog';
800             $resultok  =  $resultok && $data->lastname == $userid;
801             $resultok  =  $resultok && $data->id == $userid;
802             $cms = $data->progress;
803             $resultok =  $resultok && (array(13, 14) == array_keys($cms));
804             $resultok =  $resultok && ((object)array('userid'=>$userid, 'coursemoduleid'=>13) == $cms[13]);
805             $resultok =  $resultok && ((object)array('userid'=>$userid, 'coursemoduleid'=>14) == $cms[14]);
806         }
807         $this->assertTrue($resultok);
808     }
810     public function test_inform_grade_changed() {
811         $this->mock_setup();
813         $mockbuilder = $this->getMockBuilder('completion_info');
814         $mockbuilder->setMethods(array('is_enabled', 'update_state'));
815         $mockbuilder->setConstructorArgs(array((object)array('id' => 42)));
816         $c = $mockbuilder->getMock();
818         $cm = (object)array('course'=>42, 'id'=>13, 'completion'=>0, 'completiongradeitemnumber'=>null);
819         $item = (object)array('itemnumber'=>3,  'gradepass'=>1,  'hidden'=>0);
820         $grade = (object)array('userid'=>31337,  'finalgrade'=>0,  'rawgrade'=>0);
822         // Not enabled (should do nothing).
823         $c->expects($this->at(0))
824             ->method('is_enabled')
825             ->with($cm)
826             ->will($this->returnValue(false));
827         $c->inform_grade_changed($cm, $item, $grade, false);
829         // Enabled but still no grade completion required,  should still do nothing.
830         $c->expects($this->at(0))
831             ->method('is_enabled')
832             ->with($cm)
833             ->will($this->returnValue(true));
834         $c->inform_grade_changed($cm, $item, $grade, false);
836         // Enabled and completion required but item number is wrong,  does nothing.
837         $cm = (object)array('course'=>42, 'id'=>13, 'completion'=>0, 'completiongradeitemnumber'=>7);
838         $c->expects($this->at(0))
839             ->method('is_enabled')
840             ->with($cm)
841             ->will($this->returnValue(true));
842         $c->inform_grade_changed($cm, $item, $grade, false);
844         // Enabled and completion required and item number right. It is supposed
845         // to call update_state with the new potential state being obtained from
846         // internal_get_grade_state.
847         $cm = (object)array('course'=>42, 'id'=>13, 'completion'=>0, 'completiongradeitemnumber'=>3);
848         $grade = (object)array('userid'=>31337,  'finalgrade'=>1,  'rawgrade'=>0);
849         $c->expects($this->at(0))
850             ->method('is_enabled')
851             ->with($cm)
852             ->will($this->returnValue(true));
853         $c->expects($this->at(1))
854             ->method('update_state')
855             ->with($cm, COMPLETION_COMPLETE_PASS, 31337)
856             ->will($this->returnValue(true));
857         $c->inform_grade_changed($cm, $item, $grade, false);
859         // Same as above but marked deleted. It is supposed to call update_state
860         // with new potential state being COMPLETION_INCOMPLETE.
861         $cm = (object)array('course'=>42, 'id'=>13, 'completion'=>0, 'completiongradeitemnumber'=>3);
862         $grade = (object)array('userid'=>31337,  'finalgrade'=>1,  'rawgrade'=>0);
863         $c->expects($this->at(0))
864             ->method('is_enabled')
865             ->with($cm)
866             ->will($this->returnValue(true));
867         $c->expects($this->at(1))
868             ->method('update_state')
869             ->with($cm, COMPLETION_INCOMPLETE, 31337)
870             ->will($this->returnValue(true));
871         $c->inform_grade_changed($cm, $item, $grade, true);
872     }
874     public function test_internal_get_grade_state() {
875         $this->mock_setup();
877         $item = new stdClass;
878         $grade = new stdClass;
880         $item->gradepass = 4;
881         $item->hidden = 0;
882         $grade->rawgrade = 4.0;
883         $grade->finalgrade = null;
885         // Grade has pass mark and is not hidden,  user passes.
886         $this->assertEquals(
887             COMPLETION_COMPLETE_PASS,
888             completion_info::internal_get_grade_state($item, $grade));
890         // Same but user fails.
891         $grade->rawgrade = 3.9;
892         $this->assertEquals(
893             COMPLETION_COMPLETE_FAIL,
894             completion_info::internal_get_grade_state($item, $grade));
896         // User fails on raw grade but passes on final.
897         $grade->finalgrade = 4.0;
898         $this->assertEquals(
899             COMPLETION_COMPLETE_PASS,
900             completion_info::internal_get_grade_state($item, $grade));
902         // Item is hidden.
903         $item->hidden = 1;
904         $this->assertEquals(
905             COMPLETION_COMPLETE,
906             completion_info::internal_get_grade_state($item, $grade));
908         // Item isn't hidden but has no pass mark.
909         $item->hidden = 0;
910         $item->gradepass = 0;
911         $this->assertEquals(
912             COMPLETION_COMPLETE,
913             completion_info::internal_get_grade_state($item, $grade));
914     }
916     public function test_get_activities() {
917         global $CFG;
918         $this->resetAfterTest();
920         // Enable completion before creating modules, otherwise the completion data is not written in DB.
921         $CFG->enablecompletion = true;
923         // Create a course with mixed auto completion data.
924         $course = $this->getDataGenerator()->create_course(array('enablecompletion' => true));
925         $completionauto = array('completion' => COMPLETION_TRACKING_AUTOMATIC);
926         $completionmanual = array('completion' => COMPLETION_TRACKING_MANUAL);
927         $completionnone = array('completion' => COMPLETION_TRACKING_NONE);
928         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course->id), $completionauto);
929         $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id), $completionauto);
930         $data = $this->getDataGenerator()->create_module('data', array('course' => $course->id), $completionmanual);
932         $forum2 = $this->getDataGenerator()->create_module('forum', array('course' => $course->id), $completionnone);
933         $page2 = $this->getDataGenerator()->create_module('page', array('course' => $course->id), $completionnone);
934         $data2 = $this->getDataGenerator()->create_module('data', array('course' => $course->id), $completionnone);
936         // Create data in another course to make sure it's not considered.
937         $course2 = $this->getDataGenerator()->create_course(array('enablecompletion' => true));
938         $c2forum = $this->getDataGenerator()->create_module('forum', array('course' => $course2->id), $completionauto);
939         $c2page = $this->getDataGenerator()->create_module('page', array('course' => $course2->id), $completionmanual);
940         $c2data = $this->getDataGenerator()->create_module('data', array('course' => $course2->id), $completionnone);
942         $c = new completion_info($course);
943         $activities = $c->get_activities();
944         $this->assertCount(3, $activities);
945         $this->assertTrue(isset($activities[$forum->cmid]));
946         $this->assertSame($forum->name, $activities[$forum->cmid]->name);
947         $this->assertTrue(isset($activities[$page->cmid]));
948         $this->assertSame($page->name, $activities[$page->cmid]->name);
949         $this->assertTrue(isset($activities[$data->cmid]));
950         $this->assertSame($data->name, $activities[$data->cmid]->name);
952         $this->assertFalse(isset($activities[$forum2->cmid]));
953         $this->assertFalse(isset($activities[$page2->cmid]));
954         $this->assertFalse(isset($activities[$data2->cmid]));
955     }
957     public function test_has_activities() {
958         global $CFG;
959         $this->resetAfterTest();
961         // Enable completion before creating modules, otherwise the completion data is not written in DB.
962         $CFG->enablecompletion = true;
964         // Create a course with mixed auto completion data.
965         $course = $this->getDataGenerator()->create_course(array('enablecompletion' => true));
966         $course2 = $this->getDataGenerator()->create_course(array('enablecompletion' => true));
967         $completionauto = array('completion' => COMPLETION_TRACKING_AUTOMATIC);
968         $completionnone = array('completion' => COMPLETION_TRACKING_NONE);
969         $c1forum = $this->getDataGenerator()->create_module('forum', array('course' => $course->id), $completionauto);
970         $c2forum = $this->getDataGenerator()->create_module('forum', array('course' => $course2->id), $completionnone);
972         $c1 = new completion_info($course);
973         $c2 = new completion_info($course2);
975         $this->assertTrue($c1->has_activities());
976         $this->assertFalse($c2->has_activities());
977     }
979     /**
980      * Test that data is cleaned up when we delete courses that are set as completion criteria for other courses
981      *
982      * @return void
983      */
984     public function test_course_delete_prerequisite() {
985         global $DB;
987         $this->setup_data();
989         $courseprerequisite = $this->getDataGenerator()->create_course(['enablecompletion' => true]);
991         $criteriadata = (object) [
992             'id' => $this->course->id,
993             'criteria_course' => [$courseprerequisite->id],
994         ];
996         /** @var completion_criteria_course $criteria */
997         $criteria = completion_criteria::factory(['criteriatype' => COMPLETION_CRITERIA_TYPE_COURSE]);
998         $criteria->update_config($criteriadata);
1000         // Sanity test.
1001         $this->assertTrue($DB->record_exists('course_completion_criteria', [
1002             'course' => $this->course->id,
1003             'criteriatype' => COMPLETION_CRITERIA_TYPE_COURSE,
1004             'courseinstance' => $courseprerequisite->id,
1005         ]));
1007         // Deleting the prerequisite course should remove the completion criteria.
1008         delete_course($courseprerequisite, false);
1010         $this->assertFalse($DB->record_exists('course_completion_criteria', [
1011             'course' => $this->course->id,
1012             'criteriatype' => COMPLETION_CRITERIA_TYPE_COURSE,
1013             'courseinstance' => $courseprerequisite->id,
1014         ]));
1015     }
1017     /**
1018      * Test course module completion update event.
1019      */
1020     public function test_course_module_completion_updated_event() {
1021         global $USER, $CFG;
1023         $this->setup_data();
1025         $this->setAdminUser();
1027         $completionauto = array('completion' => COMPLETION_TRACKING_AUTOMATIC);
1028         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $this->course->id), $completionauto);
1030         $c = new completion_info($this->course);
1031         $activities = $c->get_activities();
1032         $this->assertEquals(1, count($activities));
1033         $this->assertTrue(isset($activities[$forum->cmid]));
1034         $this->assertEquals($activities[$forum->cmid]->name, $forum->name);
1036         $current = $c->get_data($activities[$forum->cmid], false, $this->user->id);
1037         $current->completionstate = COMPLETION_COMPLETE;
1038         $current->timemodified = time();
1039         $sink = $this->redirectEvents();
1040         $c->internal_set_data($activities[$forum->cmid], $current);
1041         $events = $sink->get_events();
1042         $event = reset($events);
1043         $this->assertInstanceOf('\core\event\course_module_completion_updated', $event);
1044         $this->assertEquals($forum->cmid, $event->get_record_snapshot('course_modules_completion', $event->objectid)->coursemoduleid);
1045         $this->assertEquals($current, $event->get_record_snapshot('course_modules_completion', $event->objectid));
1046         $this->assertEquals(context_module::instance($forum->cmid), $event->get_context());
1047         $this->assertEquals($USER->id, $event->userid);
1048         $this->assertEquals($this->user->id, $event->relateduserid);
1049         $this->assertInstanceOf('moodle_url', $event->get_url());
1050         $this->assertEventLegacyData($current, $event);
1051     }
1053     /**
1054      * Test course completed event.
1055      */
1056     public function test_course_completed_event() {
1057         global $USER;
1059         $this->setup_data();
1060         $this->setAdminUser();
1062         $completionauto = array('completion' => COMPLETION_TRACKING_AUTOMATIC);
1063         $ccompletion = new completion_completion(array('course' => $this->course->id, 'userid' => $this->user->id));
1065         // Mark course as complete and get triggered event.
1066         $sink = $this->redirectEvents();
1067         $ccompletion->mark_complete();
1068         $events = $sink->get_events();
1069         $event = reset($events);
1071         $this->assertInstanceOf('\core\event\course_completed', $event);
1072         $this->assertEquals($this->course->id, $event->get_record_snapshot('course_completions', $event->objectid)->course);
1073         $this->assertEquals($this->course->id, $event->courseid);
1074         $this->assertEquals($USER->id, $event->userid);
1075         $this->assertEquals($this->user->id, $event->relateduserid);
1076         $this->assertEquals(context_course::instance($this->course->id), $event->get_context());
1077         $this->assertInstanceOf('moodle_url', $event->get_url());
1078         $data = $ccompletion->get_record_data();
1079         $this->assertEventLegacyData($data, $event);
1080     }
1082     /**
1083      * Test course completed message.
1084      */
1085     public function test_course_completed_message() {
1086         $this->setup_data();
1087         $this->setAdminUser();
1089         $completionauto = array('completion' => COMPLETION_TRACKING_AUTOMATIC);
1090         $ccompletion = new completion_completion(array('course' => $this->course->id, 'userid' => $this->user->id));
1092         // Mark course as complete and get the message.
1093         $sink = $this->redirectMessages();
1094         $ccompletion->mark_complete();
1095         $messages = $sink->get_messages();
1096         $sink->close();
1098         $this->assertCount(1, $messages);
1099         $message = array_pop($messages);
1101         $this->assertEquals(core_user::get_noreply_user()->id, $message->useridfrom);
1102         $this->assertEquals($this->user->id, $message->useridto);
1103         $this->assertEquals('coursecompleted', $message->eventtype);
1104         $this->assertEquals(get_string('coursecompleted', 'completion'), $message->subject);
1105         $this->assertStringContainsString($this->course->fullname, $message->fullmessage);
1106     }
1108     /**
1109      * Test course completed event.
1110      */
1111     public function test_course_completion_updated_event() {
1112         $this->setup_data();
1113         $coursecontext = context_course::instance($this->course->id);
1114         $coursecompletionevent = \core\event\course_completion_updated::create(
1115                 array(
1116                     'courseid' => $this->course->id,
1117                     'context' => $coursecontext
1118                     )
1119                 );
1121         // Mark course as complete and get triggered event.
1122         $sink = $this->redirectEvents();
1123         $coursecompletionevent->trigger();
1124         $events = $sink->get_events();
1125         $event = array_pop($events);
1126         $sink->close();
1128         $this->assertInstanceOf('\core\event\course_completion_updated', $event);
1129         $this->assertEquals($this->course->id, $event->courseid);
1130         $this->assertEquals($coursecontext, $event->get_context());
1131         $this->assertInstanceOf('moodle_url', $event->get_url());
1132         $expectedlegacylog = array($this->course->id, 'course', 'completion updated', 'completion.php?id='.$this->course->id);
1133         $this->assertEventLegacyLogData($expectedlegacylog, $event);
1134     }
1136     public function test_completion_can_view_data() {
1137         $this->setup_data();
1139         $student = $this->getDataGenerator()->create_user();
1140         $this->getDataGenerator()->enrol_user($student->id, $this->course->id);
1142         $this->setUser($student);
1143         $this->assertTrue(completion_can_view_data($student->id, $this->course->id));
1144         $this->assertFalse(completion_can_view_data($this->user->id, $this->course->id));
1145     }
1147     /**
1148      * Data provider for test_get_grade_completion().
1149      *
1150      * @return array[]
1151      */
1152     public function get_grade_completion_provider() {
1153         return [
1154             'Grade not required' => [false, false, null, moodle_exception::class, null],
1155             'Grade required, but has no grade yet' => [true, false, null, null, COMPLETION_INCOMPLETE],
1156             'Grade required, grade received' => [true, true, null, null, COMPLETION_COMPLETE],
1157             'Grade required, passing grade received' => [true, true, 70, null, COMPLETION_COMPLETE_PASS],
1158             'Grade required, failing grade received' => [true, true, 80, null, COMPLETION_COMPLETE_FAIL],
1159         ];
1160     }
1162     /**
1163      * Test for \completion_info::get_grade_completion().
1164      *
1165      * @dataProvider get_grade_completion_provider
1166      * @param bool $completionusegrade Whether the test activity has grade completion requirement.
1167      * @param bool $hasgrade Whether to set grade for the user in this activity.
1168      * @param int|null $passinggrade Passing grade to set for the test activity.
1169      * @param string|null $expectedexception Expected exception.
1170      * @param int|null $expectedresult The expected completion status.
1171      */
1172     public function test_get_grade_completion(bool $completionusegrade, bool $hasgrade, ?int $passinggrade, ?string $expectedexception,
1173             ?int $expectedresult) {
1174         $this->setup_data();
1176         /** @var \mod_assign_generator $assigngenerator */
1177         $assigngenerator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
1178         $assign = $assigngenerator->create_instance([
1179             'course' => $this->course->id,
1180             'completion' => COMPLETION_ENABLED,
1181             'completionusegrade' => $completionusegrade,
1182             'gradepass' => $passinggrade,
1183         ]);
1185         $cm = cm_info::create(get_coursemodule_from_instance('assign', $assign->id));
1186         if ($completionusegrade && $hasgrade) {
1187             $assigninstance = new assign($cm->context, $cm, $this->course);
1188             $grade = $assigninstance->get_user_grade($this->user->id, true);
1189             $grade->grade = 75;
1190             $assigninstance->update_grade($grade);
1191         }
1193         $completioninfo = new completion_info($this->course);
1194         if ($expectedexception) {
1195             $this->expectException($expectedexception);
1196         }
1197         $gradecompletion = $completioninfo->get_grade_completion($cm, $this->user->id);
1198         $this->assertEquals($expectedresult, $gradecompletion);
1199     }
1202 class core_completionlib_fake_recordset implements Iterator {
1203     protected $closed;
1204     protected $values, $index;
1206     public function __construct($values) {
1207         $this->values = $values;
1208         $this->index = 0;
1209     }
1211     public function current() {
1212         return $this->values[$this->index];
1213     }
1215     public function key() {
1216         return $this->values[$this->index];
1217     }
1219     public function next() {
1220         $this->index++;
1221     }
1223     public function rewind() {
1224         $this->index = 0;
1225     }
1227     public function valid() {
1228         return count($this->values) > $this->index;
1229     }
1231     public function close() {
1232         $this->closed = true;
1233     }
1235     public function was_closed() {
1236         return $this->closed;
1237     }