0d91edb2a2ed3a2c1bfc278e4f605e0b48e47dc6
[moodle.git] / mod / feedback / tests / external_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  * Feedback module external functions tests
19  *
20  * @package    mod_feedback
21  * @category   external
22  * @copyright  2017 Juan Leyva <juan@moodle.com>
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  * @since      Moodle 3.3
25  */
27 defined('MOODLE_INTERNAL') || die();
29 global $CFG;
31 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
33 use mod_feedback\external\feedback_summary_exporter;
35 /**
36  * Feedback module external functions tests
37  *
38  * @package    mod_feedback
39  * @category   external
40  * @copyright  2017 Juan Leyva <juan@moodle.com>
41  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42  * @since      Moodle 3.3
43  */
44 class mod_feedback_external_testcase extends externallib_advanced_testcase {
46     /**
47      * Set up for every test
48      */
49     public function setUp() {
50         global $DB;
51         $this->resetAfterTest();
52         $this->setAdminUser();
54         // Setup test data.
55         $this->course = $this->getDataGenerator()->create_course();
56         $this->feedback = $this->getDataGenerator()->create_module('feedback', array('course' => $this->course->id));
57         $this->context = context_module::instance($this->feedback->cmid);
58         $this->cm = get_coursemodule_from_instance('feedback', $this->feedback->id);
60         // Create users.
61         $this->student = self::getDataGenerator()->create_user();
62         $this->teacher = self::getDataGenerator()->create_user();
64         // Users enrolments.
65         $this->studentrole = $DB->get_record('role', array('shortname' => 'student'));
66         $this->teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
67         $this->getDataGenerator()->enrol_user($this->student->id, $this->course->id, $this->studentrole->id, 'manual');
68         $this->getDataGenerator()->enrol_user($this->teacher->id, $this->course->id, $this->teacherrole->id, 'manual');
69     }
71     /**
72      * Helper method to add items to an existing feedback.
73      *
74      * @param stdClass  $feedback feedback instance
75      * @param integer $pagescount the number of pages we want in the feedback
76      * @return array list of items created
77      */
78     public function populate_feedback($feedback, $pagescount = 1) {
79         $feedbackgenerator = $this->getDataGenerator()->get_plugin_generator('mod_feedback');
80         $itemscreated = [];
82         // Create at least one page.
83         $itemscreated[] = $feedbackgenerator->create_item_label($feedback);
84         $itemscreated[] = $feedbackgenerator->create_item_info($feedback);
85         $itemscreated[] = $feedbackgenerator->create_item_numeric($feedback);
87         // Check if we want more pages.
88         for ($i = 1; $i < $pagescount; $i++) {
89             $itemscreated[] = $feedbackgenerator->create_item_pagebreak($feedback);
90             $itemscreated[] = $feedbackgenerator->create_item_multichoice($feedback);
91             $itemscreated[] = $feedbackgenerator->create_item_multichoicerated($feedback);
92             $itemscreated[] = $feedbackgenerator->create_item_textarea($feedback);
93             $itemscreated[] = $feedbackgenerator->create_item_textfield($feedback);
94             $itemscreated[] = $feedbackgenerator->create_item_numeric($feedback);
95         }
96         return $itemscreated;
97     }
100     /**
101      * Test test_mod_feedback_get_feedbacks_by_courses
102      */
103     public function test_mod_feedback_get_feedbacks_by_courses() {
104         global $DB;
106         // Create additional course.
107         $course2 = self::getDataGenerator()->create_course();
109         // Second feedback.
110         $record = new stdClass();
111         $record->course = $course2->id;
112         $feedback2 = self::getDataGenerator()->create_module('feedback', $record);
114         // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
115         $enrol = enrol_get_plugin('manual');
116         $enrolinstances = enrol_get_instances($course2->id, true);
117         foreach ($enrolinstances as $courseenrolinstance) {
118             if ($courseenrolinstance->enrol == "manual") {
119                 $instance2 = $courseenrolinstance;
120                 break;
121             }
122         }
123         $enrol->enrol_user($instance2, $this->student->id, $this->studentrole->id);
125         self::setUser($this->student);
127         $returndescription = mod_feedback_external::get_feedbacks_by_courses_returns();
129         // Create what we expect to be returned when querying the two courses.
130         // First for the student user.
131         $expectedfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'introfiles', 'anonymous',
132             'multiple_submit', 'autonumbering', 'page_after_submitformat', 'publish_stats', 'completionsubmit');
134         $properties = feedback_summary_exporter::read_properties_definition();
136         // Add expected coursemodule and data.
137         $feedback1 = $this->feedback;
138         $feedback1->coursemodule = $feedback1->cmid;
139         $feedback1->introformat = 1;
140         $feedback1->introfiles = [];
142         $feedback2->coursemodule = $feedback2->cmid;
143         $feedback2->introformat = 1;
144         $feedback2->introfiles = [];
146         foreach ($expectedfields as $field) {
147             if (!empty($properties[$field]) && $properties[$field]['type'] == PARAM_BOOL) {
148                 $feedback1->{$field} = (bool) $feedback1->{$field};
149                 $feedback2->{$field} = (bool) $feedback2->{$field};
150             }
151             $expected1[$field] = $feedback1->{$field};
152             $expected2[$field] = $feedback2->{$field};
153         }
155         $expectedfeedbacks = array($expected2, $expected1);
157         // Call the external function passing course ids.
158         $result = mod_feedback_external::get_feedbacks_by_courses(array($course2->id, $this->course->id));
159         $result = external_api::clean_returnvalue($returndescription, $result);
161         $this->assertEquals($expectedfeedbacks, $result['feedbacks']);
162         $this->assertCount(0, $result['warnings']);
164         // Call the external function without passing course id.
165         $result = mod_feedback_external::get_feedbacks_by_courses();
166         $result = external_api::clean_returnvalue($returndescription, $result);
167         $this->assertEquals($expectedfeedbacks, $result['feedbacks']);
168         $this->assertCount(0, $result['warnings']);
170         // Unenrol user from second course and alter expected feedbacks.
171         $enrol->unenrol_user($instance2, $this->student->id);
172         array_shift($expectedfeedbacks);
174         // Call the external function without passing course id.
175         $result = mod_feedback_external::get_feedbacks_by_courses();
176         $result = external_api::clean_returnvalue($returndescription, $result);
177         $this->assertEquals($expectedfeedbacks, $result['feedbacks']);
179         // Call for the second course we unenrolled the user from, expected warning.
180         $result = mod_feedback_external::get_feedbacks_by_courses(array($course2->id));
181         $this->assertCount(1, $result['warnings']);
182         $this->assertEquals('1', $result['warnings'][0]['warningcode']);
183         $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
185         // Now, try as a teacher for getting all the additional fields.
186         self::setUser($this->teacher);
188         $additionalfields = array('email_notification', 'site_after_submit', 'page_after_submit', 'timeopen', 'timeclose',
189             'timemodified', 'pageaftersubmitfiles');
191         $feedback1->pageaftersubmitfiles = [];
193         foreach ($additionalfields as $field) {
194             if (!empty($properties[$field]) && $properties[$field]['type'] == PARAM_BOOL) {
195                 $feedback1->{$field} = (bool) $feedback1->{$field};
196             }
197             $expectedfeedbacks[0][$field] = $feedback1->{$field};
198         }
199         $expectedfeedbacks[0]['page_after_submitformat'] = 1;
201         $result = mod_feedback_external::get_feedbacks_by_courses();
202         $result = external_api::clean_returnvalue($returndescription, $result);
203         $this->assertEquals($expectedfeedbacks, $result['feedbacks']);
205         // Admin also should get all the information.
206         self::setAdminUser();
208         $result = mod_feedback_external::get_feedbacks_by_courses(array($this->course->id));
209         $result = external_api::clean_returnvalue($returndescription, $result);
210         $this->assertEquals($expectedfeedbacks, $result['feedbacks']);
211     }
213     /**
214      * Test get_feedback_access_information function with basic defaults for student.
215      */
216     public function test_get_feedback_access_information_student() {
218         self::setUser($this->student);
219         $result = mod_feedback_external::get_feedback_access_information($this->feedback->id);
220         $result = external_api::clean_returnvalue(mod_feedback_external::get_feedback_access_information_returns(), $result);
222         $this->assertFalse($result['canviewanalysis']);
223         $this->assertFalse($result['candeletesubmissions']);
224         $this->assertFalse($result['canviewreports']);
225         $this->assertFalse($result['canedititems']);
226         $this->assertTrue($result['cancomplete']);
227         $this->assertTrue($result['cansubmit']);
228         $this->assertTrue($result['isempty']);
229         $this->assertTrue($result['isopen']);
230         $this->assertTrue($result['isanonymous']);
231         $this->assertFalse($result['isalreadysubmitted']);
232     }
234     /**
235      * Test get_feedback_access_information function with basic defaults for teacher.
236      */
237     public function test_get_feedback_access_information_teacher() {
239         self::setUser($this->teacher);
240         $result = mod_feedback_external::get_feedback_access_information($this->feedback->id);
241         $result = external_api::clean_returnvalue(mod_feedback_external::get_feedback_access_information_returns(), $result);
243         $this->assertTrue($result['canviewanalysis']);
244         $this->assertTrue($result['canviewreports']);
245         $this->assertTrue($result['canedititems']);
246         $this->assertTrue($result['candeletesubmissions']);
247         $this->assertFalse($result['cancomplete']);
248         $this->assertTrue($result['cansubmit']);
249         $this->assertTrue($result['isempty']);
250         $this->assertTrue($result['isopen']);
251         $this->assertTrue($result['isanonymous']);
252         $this->assertFalse($result['isalreadysubmitted']);
254         // Add some items to the feedback and check is not empty any more.
255         self::populate_feedback($this->feedback);
256         $result = mod_feedback_external::get_feedback_access_information($this->feedback->id);
257         $result = external_api::clean_returnvalue(mod_feedback_external::get_feedback_access_information_returns(), $result);
258         $this->assertFalse($result['isempty']);
259     }
261     /**
262      * Test view_feedback invalid id.
263      */
264     public function test_view_feedback_invalid_id() {
265         // Test invalid instance id.
266         $this->setExpectedException('moodle_exception');
267         mod_feedback_external::view_feedback(0);
268     }
269     /**
270      * Test view_feedback not enrolled user.
271      */
272     public function test_view_feedback_not_enrolled_user() {
273         $usernotenrolled = self::getDataGenerator()->create_user();
274         $this->setUser($usernotenrolled);
275         $this->setExpectedException('moodle_exception');
276         mod_feedback_external::view_feedback(0);
277     }
278     /**
279      * Test view_feedback no capabilities.
280      */
281     public function test_view_feedback_no_capabilities() {
282         // Test user with no capabilities.
283         // We need a explicit prohibit since this capability is allowed for students by default.
284         assign_capability('mod/feedback:view', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
285         accesslib_clear_all_caches_for_unit_testing();
286         $this->setExpectedException('moodle_exception');
287         mod_feedback_external::view_feedback(0);
288     }
289     /**
290      * Test view_feedback.
291      */
292     public function test_view_feedback() {
293         // Test user with full capabilities.
294         $this->setUser($this->student);
295         // Trigger and capture the event.
296         $sink = $this->redirectEvents();
297         $result = mod_feedback_external::view_feedback($this->feedback->id);
298         $result = external_api::clean_returnvalue(mod_feedback_external::view_feedback_returns(), $result);
299         $events = $sink->get_events();
300         $this->assertCount(1, $events);
301         $event = array_shift($events);
302         // Checking that the event contains the expected values.
303         $this->assertInstanceOf('\mod_feedback\event\course_module_viewed', $event);
304         $this->assertEquals($this->context, $event->get_context());
305         $moodledata = new \moodle_url('/mod/feedback/view.php', array('id' => $this->cm->id));
306         $this->assertEquals($moodledata, $event->get_url());
307         $this->assertEventContextNotUsed($event);
308         $this->assertNotEmpty($event->get_name());
309     }
311     /**
312      * Test get_current_completed_tmp.
313      */
314     public function test_get_current_completed_tmp() {
315         global $DB;
317         // Force non anonymous.
318         $DB->set_field('feedback', 'anonymous', 0, array('id' => $this->feedback->id));
319         // Add a completed_tmp record.
320         $record = [
321             'feedback' => $this->feedback->id,
322             'userid' => $this->student->id,
323             'guestid' => '',
324             'timemodified' => time() - DAYSECS,
325             'random_response' => 0,
326             'anonymous_response' => 2,
327             'courseid' => $this->course->id,
328         ];
329         $record['id'] = $DB->insert_record('feedback_completedtmp', (object) $record);
331         // Test user with full capabilities.
332         $this->setUser($this->student);
334         $result = mod_feedback_external::get_current_completed_tmp($this->feedback->id);
335         $result = external_api::clean_returnvalue(mod_feedback_external::get_current_completed_tmp_returns(), $result);
336         $this->assertEquals($record['id'], $result['feedback']['id']);
337     }
339     /**
340      * Test get_items.
341      */
342     public function test_get_items() {
343         // Test user with full capabilities.
344         $this->setUser($this->student);
346         // Add questions to the feedback, we are adding 2 pages of questions.
347         $itemscreated = self::populate_feedback($this->feedback, 2);
349         $result = mod_feedback_external::get_items($this->feedback->id);
350         $result = external_api::clean_returnvalue(mod_feedback_external::get_items_returns(), $result);
351         $this->assertCount(count($itemscreated), $result['items']);
352         $index = 1;
353         foreach ($result['items'] as $key => $item) {
354             if (is_numeric($itemscreated[$key])) {
355                 continue; // Page break.
356             }
357             // Cannot compare directly the exporter and the db object (exporter have more fields).
358             $this->assertEquals($itemscreated[$key]->id, $item['id']);
359             $this->assertEquals($itemscreated[$key]->typ, $item['typ']);
360             $this->assertEquals($itemscreated[$key]->name, $item['name']);
361             $this->assertEquals($itemscreated[$key]->label, $item['label']);
363             if ($item['hasvalue']) {
364                 $this->assertEquals($index, $item['itemnumber']);
365                 $index++;
366             }
367         }
368     }
370     /**
371      * Test launch_feedback.
372      */
373     public function test_launch_feedback() {
374         global $DB;
376         // Test user with full capabilities.
377         $this->setUser($this->student);
379         // Add questions to the feedback, we are adding 2 pages of questions.
380         $itemscreated = self::populate_feedback($this->feedback, 2);
382         // First try a feedback we didn't attempt.
383         $result = mod_feedback_external::launch_feedback($this->feedback->id);
384         $result = external_api::clean_returnvalue(mod_feedback_external::launch_feedback_returns(), $result);
385         $this->assertEquals(0, $result['gopage']);
387         // Now, try a feedback that we attempted.
388         // Force non anonymous.
389         $DB->set_field('feedback', 'anonymous', 0, array('id' => $this->feedback->id));
390         // Add a completed_tmp record.
391         $record = [
392             'feedback' => $this->feedback->id,
393             'userid' => $this->student->id,
394             'guestid' => '',
395             'timemodified' => time() - DAYSECS,
396             'random_response' => 0,
397             'anonymous_response' => 2,
398             'courseid' => $this->course->id,
399         ];
400         $record['id'] = $DB->insert_record('feedback_completedtmp', (object) $record);
402         // Add a response to the feedback for each question type with possible values.
403         $response = [
404             'course_id' => $this->course->id,
405             'item' => $itemscreated[1]->id, // First item is the info question.
406             'completed' => $record['id'],
407             'tmp_completed' => $record['id'],
408             'value' => 'A',
409         ];
410         $DB->insert_record('feedback_valuetmp', (object) $response);
411         $response = [
412             'course_id' => $this->course->id,
413             'item' => $itemscreated[2]->id, // Second item is the numeric question.
414             'completed' => $record['id'],
415             'tmp_completed' => $record['id'],
416             'value' => 5,
417         ];
418         $DB->insert_record('feedback_valuetmp', (object) $response);
420         $result = mod_feedback_external::launch_feedback($this->feedback->id);
421         $result = external_api::clean_returnvalue(mod_feedback_external::launch_feedback_returns(), $result);
422         $this->assertEquals(1, $result['gopage']);
423     }
425     /**
426      * Test get_page_items.
427      */
428     public function test_get_page_items() {
429         // Test user with full capabilities.
430         $this->setUser($this->student);
432         // Add questions to the feedback, we are adding 2 pages of questions.
433         $itemscreated = self::populate_feedback($this->feedback, 2);
435         // Retrieve first page.
436         $result = mod_feedback_external::get_page_items($this->feedback->id, 0);
437         $result = external_api::clean_returnvalue(mod_feedback_external::get_page_items_returns(), $result);
438         $this->assertCount(3, $result['items']);    // The first page has 3 items.
439         $this->assertTrue($result['hasnextpage']);
440         $this->assertFalse($result['hasprevpage']);
442         // Retrieve second page.
443         $result = mod_feedback_external::get_page_items($this->feedback->id, 1);
444         $result = external_api::clean_returnvalue(mod_feedback_external::get_page_items_returns(), $result);
445         $this->assertCount(5, $result['items']);    // The second page has 5 items (page break doesn't count).
446         $this->assertFalse($result['hasnextpage']);
447         $this->assertTrue($result['hasprevpage']);
448     }
450     /**
451      * Test process_page.
452      */
453     public function test_process_page() {
454         global $DB;
456         // Test user with full capabilities.
457         $this->setUser($this->student);
458         $pagecontents = 'You finished it!';
459         $DB->set_field('feedback', 'page_after_submit', $pagecontents, array('id' => $this->feedback->id));
461         // Add questions to the feedback, we are adding 2 pages of questions.
462         $itemscreated = self::populate_feedback($this->feedback, 2);
464         $data = [];
465         foreach ($itemscreated as $item) {
467             if (empty($item->hasvalue)) {
468                 continue;
469             }
471             switch ($item->typ) {
472                 case 'textarea':
473                 case 'textfield':
474                     $value = 'Lorem ipsum';
475                     break;
476                 case 'numeric':
477                     $value = 5;
478                     break;
479                 case 'multichoice':
480                     $value = '1';
481                     break;
482                 case 'multichoicerated':
483                     $value = '1';
484                     break;
485                 case 'info':
486                     $value = format_string($this->course->shortname, true, array('context' => $this->context));
487                     break;
488                 default:
489                     $value = '';
490             }
491             $data[] = ['name' => $item->typ . '_' . $item->id, 'value' => $value];
492         }
494         // Process first page.
495         $firstpagedata = [$data[0], $data[1]];
496         $result = mod_feedback_external::process_page($this->feedback->id, 0, $firstpagedata);
497         $result = external_api::clean_returnvalue(mod_feedback_external::process_page_returns(), $result);
498         $this->assertEquals(1, $result['jumpto']);
499         $this->assertFalse($result['completed']);
501         // Now, process the second page. But first we are going back to the first page.
502         $secondpagedata = [$data[2], $data[3], $data[4], $data[5], $data[6]];
503         $result = mod_feedback_external::process_page($this->feedback->id, 1, $secondpagedata, true);
504         $result = external_api::clean_returnvalue(mod_feedback_external::process_page_returns(), $result);
505         $this->assertFalse($result['completed']);
506         $this->assertEquals(0, $result['jumpto']);  // We jumped to the first page.
507         // Check the values were correctly saved.
508         $tmpitems = $DB->get_records('feedback_valuetmp');
509         $this->assertCount(7, $tmpitems);   // 2 from the first page + 5 from the second page.
511         // Go forward again (sending the same data).
512         $result = mod_feedback_external::process_page($this->feedback->id, 0, $firstpagedata);
513         $result = external_api::clean_returnvalue(mod_feedback_external::process_page_returns(), $result);
514         $this->assertEquals(1, $result['jumpto']);
515         $this->assertFalse($result['completed']);
516         $tmpitems = $DB->get_records('feedback_valuetmp');
517         $this->assertCount(7, $tmpitems);   // 2 from the first page + 5 from the second page.
519         // And finally, save everything! We are going to modify one previous recorded value.
520         $data[2]['value'] = 'b';
521         $secondpagedata = [$data[2], $data[3], $data[4], $data[5], $data[6]];
522         $result = mod_feedback_external::process_page($this->feedback->id, 1, $secondpagedata);
523         $result = external_api::clean_returnvalue(mod_feedback_external::process_page_returns(), $result);
524         $this->assertTrue($result['completed']);
525         $this->assertTrue(strpos($result['completionpagecontents'], $pagecontents) !== false);
526         // Check all the items were saved.
527         $items = $DB->get_records('feedback_value');
528         $this->assertCount(7, $items);
529         // Check if the one we modified was correctly saved.
530         $itemid = $itemscreated[4]->id;
531         $itemsaved = $DB->get_field('feedback_value', 'value', array('item' => $itemid));
532         $this->assertEquals('b', $itemsaved);
533     }
535     /**
536      * Test get_analysis.
537      */
538     public function test_get_analysis() {
539         // Test user with full capabilities.
540         $this->setUser($this->student);
542         // Create a very simple feedback.
543         $feedbackgenerator = $this->getDataGenerator()->get_plugin_generator('mod_feedback');
544         $numericitem = $feedbackgenerator->create_item_numeric($this->feedback);
545         $textfielditem = $feedbackgenerator->create_item_textfield($this->feedback);
547         $pagedata = [
548             ['name' => $numericitem->typ .'_'. $numericitem->id, 'value' => 5],
549             ['name' => $textfielditem->typ .'_'. $textfielditem->id, 'value' => 'abc'],
550         ];
551         // Process the feedback, there is only one page so the feedback will be completed.
552         $result = mod_feedback_external::process_page($this->feedback->id, 0, $pagedata);
553         $result = external_api::clean_returnvalue(mod_feedback_external::process_page_returns(), $result);
554         $this->assertTrue($result['completed']);
556         // Retrieve analysis.
557         $this->setUser($this->teacher);
558         $result = mod_feedback_external::get_analysis($this->feedback->id);
559         $result = external_api::clean_returnvalue(mod_feedback_external::get_analysis_returns(), $result);
560         $this->assertEquals(1, $result['completedcount']);  // 1 feedback completed.
561         $this->assertEquals(2, $result['itemscount']);  // 2 items in the feedback.
562         $this->assertCount(2, $result['itemsdata']);
563         $this->assertCount(1, $result['itemsdata'][0]['data']); // There are 1 response per item.
564         $this->assertCount(1, $result['itemsdata'][1]['data']);
565         // Check we receive the info the students filled.
566         foreach ($result['itemsdata'] as $data) {
567             if ($data['item']['id'] == $numericitem->id) {
568                 $this->assertEquals(5, $data['data'][0]);
569             } else {
570                 $this->assertEquals('abc', $data['data'][0]);
571             }
572         }
574         // Create another user / response.
575         $anotherstudent = self::getDataGenerator()->create_user();
576         $this->getDataGenerator()->enrol_user($anotherstudent->id, $this->course->id, $this->studentrole->id, 'manual');
577         $this->setUser($anotherstudent);
579         // Process the feedback, there is only one page so the feedback will be completed.
580         $result = mod_feedback_external::process_page($this->feedback->id, 0, $pagedata);
581         $result = external_api::clean_returnvalue(mod_feedback_external::process_page_returns(), $result);
582         $this->assertTrue($result['completed']);
584         // Retrieve analysis.
585         $this->setUser($this->teacher);
586         $result = mod_feedback_external::get_analysis($this->feedback->id);
587         $result = external_api::clean_returnvalue(mod_feedback_external::get_analysis_returns(), $result);
588         $this->assertEquals(2, $result['completedcount']);  // 2 feedback completed.
589         $this->assertEquals(2, $result['itemscount']);
590         $this->assertCount(2, $result['itemsdata'][0]['data']); // There are 2 responses per item.
591         $this->assertCount(2, $result['itemsdata'][1]['data']);
592     }
594     /**
595      * Test get_unfinished_responses.
596      */
597     public function test_get_unfinished_responses() {
598         // Test user with full capabilities.
599         $this->setUser($this->student);
601         // Create a very simple feedback.
602         $feedbackgenerator = $this->getDataGenerator()->get_plugin_generator('mod_feedback');
603         $numericitem = $feedbackgenerator->create_item_numeric($this->feedback);
604         $textfielditem = $feedbackgenerator->create_item_textfield($this->feedback);
605         $feedbackgenerator->create_item_pagebreak($this->feedback);
606         $labelitem = $feedbackgenerator->create_item_label($this->feedback);
607         $numericitem2 = $feedbackgenerator->create_item_numeric($this->feedback);
609         $pagedata = [
610             ['name' => $numericitem->typ .'_'. $numericitem->id, 'value' => 5],
611             ['name' => $textfielditem->typ .'_'. $textfielditem->id, 'value' => 'abc'],
612         ];
613         // Process the feedback, there are two pages so the feedback will be unfinished yet.
614         $result = mod_feedback_external::process_page($this->feedback->id, 0, $pagedata);
615         $result = external_api::clean_returnvalue(mod_feedback_external::process_page_returns(), $result);
616         $this->assertFalse($result['completed']);
618         // Retrieve the unfinished responses.
619         $result = mod_feedback_external::get_unfinished_responses($this->feedback->id);
620         $result = external_api::clean_returnvalue(mod_feedback_external::get_unfinished_responses_returns(), $result);
621         // Check that ids and responses match.
622         foreach ($result['responses'] as $r) {
623             if ($r['item'] == $numericitem->id) {
624                 $this->assertEquals(5, $r['value']);
625             } else {
626                 $this->assertEquals($textfielditem->id, $r['item']);
627                 $this->assertEquals('abc', $r['value']);
628             }
629         }
630     }
632     /**
633      * Test get_finished_responses.
634      */
635     public function test_get_finished_responses() {
636         // Test user with full capabilities.
637         $this->setUser($this->student);
639         // Create a very simple feedback.
640         $feedbackgenerator = $this->getDataGenerator()->get_plugin_generator('mod_feedback');
641         $numericitem = $feedbackgenerator->create_item_numeric($this->feedback);
642         $textfielditem = $feedbackgenerator->create_item_textfield($this->feedback);
644         $pagedata = [
645             ['name' => $numericitem->typ .'_'. $numericitem->id, 'value' => 5],
646             ['name' => $textfielditem->typ .'_'. $textfielditem->id, 'value' => 'abc'],
647         ];
649         // Process the feedback, there is only one page so the feedback will be completed.
650         $result = mod_feedback_external::process_page($this->feedback->id, 0, $pagedata);
651         $result = external_api::clean_returnvalue(mod_feedback_external::process_page_returns(), $result);
652         $this->assertTrue($result['completed']);
654         // Retrieve the responses.
655         $result = mod_feedback_external::get_finished_responses($this->feedback->id);
656         $result = external_api::clean_returnvalue(mod_feedback_external::get_finished_responses_returns(), $result);
657         // Check that ids and responses match.
658         foreach ($result['responses'] as $r) {
659             if ($r['item'] == $numericitem->id) {
660                 $this->assertEquals(5, $r['value']);
661             } else {
662                 $this->assertEquals($textfielditem->id, $r['item']);
663                 $this->assertEquals('abc', $r['value']);
664             }
665         }
666     }
668     /**
669      * Test get_non_respondents (student trying to get this information).
670      */
671     public function test_get_non_respondents_no_permissions() {
672         $this->setUser($this->student);
673         $this->setExpectedException('moodle_exception');
674         mod_feedback_external::get_non_respondents($this->feedback->id);
675     }
677     /**
678      * Test get_non_respondents from an anonymous feedback.
679      */
680     public function test_get_non_respondents_from_anonymous_feedback() {
681         $this->setUser($this->student);
682         $this->expectException('moodle_exception');
683         $this->expectExceptionMessage(get_string('anonymous', 'feedback'));
684         mod_feedback_external::get_non_respondents($this->feedback->id);
685     }
687     /**
688      * Test get_non_respondents.
689      */
690     public function test_get_non_respondents() {
691         global $DB;
693         // Force non anonymous.
694         $DB->set_field('feedback', 'anonymous', FEEDBACK_ANONYMOUS_NO, array('id' => $this->feedback->id));
696         // Create another student.
697         $anotherstudent = self::getDataGenerator()->create_user();
698         $this->getDataGenerator()->enrol_user($anotherstudent->id, $this->course->id, $this->studentrole->id, 'manual');
699         $this->setUser($anotherstudent);
701         // Test user with full capabilities.
702         $this->setUser($this->student);
704         // Create a very simple feedback.
705         $feedbackgenerator = $this->getDataGenerator()->get_plugin_generator('mod_feedback');
706         $numericitem = $feedbackgenerator->create_item_numeric($this->feedback);
708         $pagedata = [
709             ['name' => $numericitem->typ .'_'. $numericitem->id, 'value' => 5],
710         ];
712         // Process the feedback, there is only one page so the feedback will be completed.
713         $result = mod_feedback_external::process_page($this->feedback->id, 0, $pagedata);
714         $result = external_api::clean_returnvalue(mod_feedback_external::process_page_returns(), $result);
715         $this->assertTrue($result['completed']);
717         // Retrieve the non-respondent users.
718         $this->setUser($this->teacher);
719         $result = mod_feedback_external::get_non_respondents($this->feedback->id);
720         $result = external_api::clean_returnvalue(mod_feedback_external::get_non_respondents_returns(), $result);
721         $this->assertCount(0, $result['warnings']);
722         $this->assertCount(1, $result['users']);
723         $this->assertEquals($anotherstudent->id, $result['users'][0]['userid']);
725         // Create another student.
726         $anotherstudent2 = self::getDataGenerator()->create_user();
727         $this->getDataGenerator()->enrol_user($anotherstudent2->id, $this->course->id, $this->studentrole->id, 'manual');
728         $this->setUser($anotherstudent2);
729         $this->setUser($this->teacher);
730         $result = mod_feedback_external::get_non_respondents($this->feedback->id);
731         $result = external_api::clean_returnvalue(mod_feedback_external::get_non_respondents_returns(), $result);
732         $this->assertCount(0, $result['warnings']);
733         $this->assertCount(2, $result['users']);
735         // Test pagination.
736         $result = mod_feedback_external::get_non_respondents($this->feedback->id, 0, 'lastaccess', 0, 1);
737         $result = external_api::clean_returnvalue(mod_feedback_external::get_non_respondents_returns(), $result);
738         $this->assertCount(0, $result['warnings']);
739         $this->assertCount(1, $result['users']);
740     }
742     /**
743      * Helper function that completes the feedback for two students.
744      */
745     protected function complete_basic_feedback() {
746         global $DB;
748         $generator = $this->getDataGenerator();
749         // Create separated groups.
750         $DB->set_field('course', 'groupmode', SEPARATEGROUPS);
751         $DB->set_field('course', 'groupmodeforce', 1);
752         assign_capability('moodle/site:accessallgroups', CAP_PROHIBIT, $this->teacherrole->id, $this->context);
753         accesslib_clear_all_caches_for_unit_testing();
755         $group1 = $generator->create_group(array('courseid' => $this->course->id));
756         $group2 = $generator->create_group(array('courseid' => $this->course->id));
758         // Create another students.
759         $anotherstudent1 = self::getDataGenerator()->create_user();
760         $anotherstudent2 = self::getDataGenerator()->create_user();
761         $generator->enrol_user($anotherstudent1->id, $this->course->id, $this->studentrole->id, 'manual');
762         $generator->enrol_user($anotherstudent2->id, $this->course->id, $this->studentrole->id, 'manual');
764         $generator->create_group_member(array('groupid' => $group1->id, 'userid' => $this->student->id));
765         $generator->create_group_member(array('groupid' => $group1->id, 'userid' => $this->teacher->id));
766         $generator->create_group_member(array('groupid' => $group1->id, 'userid' => $anotherstudent1->id));
767         $generator->create_group_member(array('groupid' => $group2->id, 'userid' => $anotherstudent2->id));
769         // Test user with full capabilities.
770         $this->setUser($this->student);
772         // Create a very simple feedback.
773         $feedbackgenerator = $generator->get_plugin_generator('mod_feedback');
774         $numericitem = $feedbackgenerator->create_item_numeric($this->feedback);
775         $textfielditem = $feedbackgenerator->create_item_textfield($this->feedback);
777         $pagedata = [
778             ['name' => $numericitem->typ .'_'. $numericitem->id, 'value' => 5],
779             ['name' => $textfielditem->typ .'_'. $textfielditem->id, 'value' => 'abc'],
780         ];
782         // Process the feedback, there is only one page so the feedback will be completed.
783         $result = mod_feedback_external::process_page($this->feedback->id, 0, $pagedata);
784         $result = external_api::clean_returnvalue(mod_feedback_external::process_page_returns(), $result);
785         $this->assertTrue($result['completed']);
787         $this->setUser($anotherstudent1);
789         $pagedata = [
790             ['name' => $numericitem->typ .'_'. $numericitem->id, 'value' => 10],
791             ['name' => $textfielditem->typ .'_'. $textfielditem->id, 'value' => 'def'],
792         ];
794         $result = mod_feedback_external::process_page($this->feedback->id, 0, $pagedata);
795         $result = external_api::clean_returnvalue(mod_feedback_external::process_page_returns(), $result);
796         $this->assertTrue($result['completed']);
798         $this->setUser($anotherstudent2);
800         $pagedata = [
801             ['name' => $numericitem->typ .'_'. $numericitem->id, 'value' => 10],
802             ['name' => $textfielditem->typ .'_'. $textfielditem->id, 'value' => 'def'],
803         ];
805         $result = mod_feedback_external::process_page($this->feedback->id, 0, $pagedata);
806         $result = external_api::clean_returnvalue(mod_feedback_external::process_page_returns(), $result);
807         $this->assertTrue($result['completed']);
808     }
810     /**
811      * Test get_responses_analysis for anonymous feedback.
812      */
813     public function test_get_responses_analysis_anonymous() {
814         self::complete_basic_feedback();
816         // Retrieve the responses analysis.
817         $this->setUser($this->teacher);
818         $result = mod_feedback_external::get_responses_analysis($this->feedback->id);
819         $result = external_api::clean_returnvalue(mod_feedback_external::get_responses_analysis_returns(), $result);
820         $this->assertCount(0, $result['warnings']);
821         $this->assertEquals(0, $result['totalattempts']);
822         $this->assertEquals(2, $result['totalanonattempts']);   // Only see my groups.
824         foreach ($result['attempts'] as $attempt) {
825             $this->assertEmpty($attempt['userid']); // Is anonymous.
826         }
827     }
829     /**
830      * Test get_responses_analysis for non-anonymous feedback.
831      */
832     public function test_get_responses_analysis_non_anonymous() {
833         global $DB;
835         // Force non anonymous.
836         $DB->set_field('feedback', 'anonymous', FEEDBACK_ANONYMOUS_NO, array('id' => $this->feedback->id));
838         self::complete_basic_feedback();
839         // Retrieve the responses analysis.
840         $this->setUser($this->teacher);
841         $result = mod_feedback_external::get_responses_analysis($this->feedback->id);
842         $result = external_api::clean_returnvalue(mod_feedback_external::get_responses_analysis_returns(), $result);
843         $this->assertCount(0, $result['warnings']);
844         $this->assertEquals(2, $result['totalattempts']);
845         $this->assertEquals(0, $result['totalanonattempts']);   // Only see my groups.
847         foreach ($result['attempts'] as $attempt) {
848             $this->assertNotEmpty($attempt['userid']);  // Is not anonymous.
849         }
850     }
852     /**
853      * Test get_last_completed for feedback anonymous not completed.
854      */
855     public function test_get_last_completed_anonymous_not_completed() {
856         global $DB;
858         // Force anonymous.
859         $DB->set_field('feedback', 'anonymous', FEEDBACK_ANONYMOUS_YES, array('id' => $this->feedback->id));
861         // Test user with full capabilities that didn't complete the feedback.
862         $this->setUser($this->student);
864         $this->expectExceptionMessage(get_string('anonymous', 'feedback'));
865         $this->expectException('moodle_exception');
866         mod_feedback_external::get_last_completed($this->feedback->id);
867     }
869     /**
870      * Test get_last_completed for feedback anonymous and completed.
871      */
872     public function test_get_last_completed_anonymous_completed() {
873         global $DB;
875         // Force anonymous.
876         $DB->set_field('feedback', 'anonymous', FEEDBACK_ANONYMOUS_YES, array('id' => $this->feedback->id));
877         // Add one completion record..
878         $record = [
879             'feedback' => $this->feedback->id,
880             'userid' => $this->student->id,
881             'timemodified' => time() - DAYSECS,
882             'random_response' => 0,
883             'anonymous_response' => FEEDBACK_ANONYMOUS_YES,
884             'courseid' => $this->course->id,
885         ];
886         $record['id'] = $DB->insert_record('feedback_completed', (object) $record);
888         // Test user with full capabilities.
889         $this->setUser($this->student);
891         $this->expectExceptionMessage(get_string('anonymous', 'feedback'));
892         $this->expectException('moodle_exception');
893         mod_feedback_external::get_last_completed($this->feedback->id);
894     }
896     /**
897      * Test get_last_completed for feedback not anonymous and completed.
898      */
899     public function test_get_last_completed_not_anonymous_completed() {
900         global $DB;
902         // Force non anonymous.
903         $DB->set_field('feedback', 'anonymous', FEEDBACK_ANONYMOUS_NO, array('id' => $this->feedback->id));
904         // Add one completion record..
905         $record = [
906             'feedback' => $this->feedback->id,
907             'userid' => $this->student->id,
908             'timemodified' => time() - DAYSECS,
909             'random_response' => 0,
910             'anonymous_response' => FEEDBACK_ANONYMOUS_NO,
911             'courseid' => $this->course->id,
912         ];
913         $record['id'] = $DB->insert_record('feedback_completed', (object) $record);
915         // Test user with full capabilities.
916         $this->setUser($this->student);
917         $result = mod_feedback_external::get_last_completed($this->feedback->id);
918         $result = external_api::clean_returnvalue(mod_feedback_external::get_last_completed_returns(), $result);
919         $this->assertEquals($record, $result['completed']);
920     }
922     /**
923      * Test get_last_completed for feedback not anonymous and not completed.
924      */
925     public function test_get_last_completed_not_anonymous_not_completed() {
926         global $DB;
928         // Force anonymous.
929         $DB->set_field('feedback', 'anonymous', FEEDBACK_ANONYMOUS_NO, array('id' => $this->feedback->id));
931         // Test user with full capabilities that didn't complete the feedback.
932         $this->setUser($this->student);
934         $this->expectExceptionMessage(get_string('not_completed_yet', 'feedback'));
935         $this->expectException('moodle_exception');
936         mod_feedback_external::get_last_completed($this->feedback->id);
937     }