Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 310 and 311] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  namespace mod_survey;
  18  
  19  use externallib_advanced_testcase;
  20  use mod_survey_external;
  21  
  22  defined('MOODLE_INTERNAL') || die();
  23  
  24  global $CFG;
  25  
  26  require_once($CFG->dirroot . '/webservice/tests/helpers.php');
  27  require_once($CFG->dirroot . '/mod/survey/lib.php');
  28  
  29  /**
  30   * Survey module external functions tests
  31   *
  32   * @package    mod_survey
  33   * @category   external
  34   * @copyright  2015 Juan Leyva <juan@moodle.com>
  35   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36   * @since      Moodle 3.0
  37   */
  38  class externallib_test extends externallib_advanced_testcase {
  39  
  40      /**
  41       * Set up for every test
  42       */
  43      public function setUp(): void {
  44          global $DB;
  45          $this->resetAfterTest();
  46          $this->setAdminUser();
  47  
  48          // Setup test data.
  49          $this->course = $this->getDataGenerator()->create_course();
  50          $this->survey = $this->getDataGenerator()->create_module('survey', array('course' => $this->course->id));
  51          $this->context = \context_module::instance($this->survey->cmid);
  52          $this->cm = get_coursemodule_from_instance('survey', $this->survey->id);
  53  
  54          // Create users.
  55          $this->student = self::getDataGenerator()->create_user();
  56          $this->teacher = self::getDataGenerator()->create_user();
  57  
  58          // Users enrolments.
  59          $this->studentrole = $DB->get_record('role', array('shortname' => 'student'));
  60          $this->teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
  61          $this->getDataGenerator()->enrol_user($this->student->id, $this->course->id, $this->studentrole->id, 'manual');
  62          $this->getDataGenerator()->enrol_user($this->teacher->id, $this->course->id, $this->teacherrole->id, 'manual');
  63      }
  64  
  65  
  66      /*
  67       * Test get surveys by courses
  68       */
  69      public function test_mod_survey_get_surveys_by_courses() {
  70          global $DB;
  71  
  72          // Create additional course.
  73          $course2 = self::getDataGenerator()->create_course();
  74  
  75          // Second survey.
  76          $record = new \stdClass();
  77          $record->course = $course2->id;
  78          $survey2 = self::getDataGenerator()->create_module('survey', $record);
  79          // Force empty intro.
  80          $DB->set_field('survey', 'intro', '', array('id' => $survey2->id));
  81  
  82          // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
  83          $enrol = enrol_get_plugin('manual');
  84          $enrolinstances = enrol_get_instances($course2->id, true);
  85          foreach ($enrolinstances as $courseenrolinstance) {
  86              if ($courseenrolinstance->enrol == "manual") {
  87                  $instance2 = $courseenrolinstance;
  88                  break;
  89              }
  90          }
  91          $enrol->enrol_user($instance2, $this->student->id, $this->studentrole->id);
  92  
  93          self::setUser($this->student);
  94  
  95          $returndescription = mod_survey_external::get_surveys_by_courses_returns();
  96  
  97          // Create what we expect to be returned when querying the two courses.
  98          // First for the student user.
  99          $expectedfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'introfiles', 'template', 'days',
 100                                  'questions', 'surveydone');
 101  
 102          // Add expected coursemodule and data.
 103          $survey1 = $this->survey;
 104          $survey1->coursemodule = $survey1->cmid;
 105          $survey1->introformat = 1;
 106          $survey1->surveydone = 0;
 107          $survey1->section = 0;
 108          $survey1->visible = true;
 109          $survey1->groupmode = 0;
 110          $survey1->groupingid = 0;
 111          $survey1->introfiles = [];
 112  
 113          $survey2->coursemodule = $survey2->cmid;
 114          $survey2->introformat = 1;
 115          $survey2->surveydone = 0;
 116          $survey2->section = 0;
 117          $survey2->visible = true;
 118          $survey2->groupmode = 0;
 119          $survey2->groupingid = 0;
 120          $tempo = $DB->get_field("survey", "intro", array("id" => $survey2->template));
 121          $survey2->intro = nl2br(get_string($tempo, "survey"));
 122          $survey2->introfiles = [];
 123  
 124          foreach ($expectedfields as $field) {
 125              $expected1[$field] = $survey1->{$field};
 126              $expected2[$field] = $survey2->{$field};
 127          }
 128  
 129          $expectedsurveys = array($expected2, $expected1);
 130  
 131          // Call the external function passing course ids.
 132          $result = mod_survey_external::get_surveys_by_courses(array($course2->id, $this->course->id));
 133          $result = \external_api::clean_returnvalue($returndescription, $result);
 134  
 135          $this->assertEquals($expectedsurveys, $result['surveys']);
 136          $this->assertCount(0, $result['warnings']);
 137  
 138          // Call the external function without passing course id.
 139          $result = mod_survey_external::get_surveys_by_courses();
 140          $result = \external_api::clean_returnvalue($returndescription, $result);
 141          $this->assertEquals($expectedsurveys, $result['surveys']);
 142          $this->assertCount(0, $result['warnings']);
 143  
 144          // Unenrol user from second course and alter expected surveys.
 145          $enrol->unenrol_user($instance2, $this->student->id);
 146          array_shift($expectedsurveys);
 147  
 148          // Call the external function without passing course id.
 149          $result = mod_survey_external::get_surveys_by_courses();
 150          $result = \external_api::clean_returnvalue($returndescription, $result);
 151          $this->assertEquals($expectedsurveys, $result['surveys']);
 152  
 153          // Call for the second course we unenrolled the user from, expected warning.
 154          $result = mod_survey_external::get_surveys_by_courses(array($course2->id));
 155          $this->assertCount(1, $result['warnings']);
 156          $this->assertEquals('1', $result['warnings'][0]['warningcode']);
 157          $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
 158  
 159          // Now, try as a teacher for getting all the additional fields.
 160          self::setUser($this->teacher);
 161  
 162          $additionalfields = array('timecreated', 'timemodified', 'section', 'visible', 'groupmode', 'groupingid');
 163  
 164          foreach ($additionalfields as $field) {
 165              $expectedsurveys[0][$field] = $survey1->{$field};
 166          }
 167  
 168          $result = mod_survey_external::get_surveys_by_courses();
 169          $result = \external_api::clean_returnvalue($returndescription, $result);
 170          $this->assertEquals($expectedsurveys, $result['surveys']);
 171  
 172          // Admin also should get all the information.
 173          self::setAdminUser();
 174  
 175          $result = mod_survey_external::get_surveys_by_courses(array($this->course->id));
 176          $result = \external_api::clean_returnvalue($returndescription, $result);
 177          $this->assertEquals($expectedsurveys, $result['surveys']);
 178  
 179          // Now, prohibit capabilities.
 180          $this->setUser($this->student);
 181          $contextcourse1 = \context_course::instance($this->course->id);
 182          // Prohibit capability = mod/survey:participate on Course1 for students.
 183          assign_capability('mod/survey:participate', CAP_PROHIBIT, $this->studentrole->id, $contextcourse1->id);
 184          accesslib_clear_all_caches_for_unit_testing();
 185  
 186          $surveys = mod_survey_external::get_surveys_by_courses(array($this->course->id));
 187          $surveys = \external_api::clean_returnvalue(mod_survey_external::get_surveys_by_courses_returns(), $surveys);
 188          $this->assertFalse(isset($surveys['surveys'][0]['intro']));
 189      }
 190  
 191      /**
 192       * Test view_survey
 193       */
 194      public function test_view_survey() {
 195          global $DB;
 196  
 197          // Test invalid instance id.
 198          try {
 199              mod_survey_external::view_survey(0);
 200              $this->fail('Exception expected due to invalid mod_survey instance id.');
 201          } catch (\moodle_exception $e) {
 202              $this->assertEquals('invalidrecord', $e->errorcode);
 203          }
 204  
 205          // Test not-enrolled user.
 206          $usernotenrolled = self::getDataGenerator()->create_user();
 207          $this->setUser($usernotenrolled);
 208          try {
 209              mod_survey_external::view_survey($this->survey->id);
 210              $this->fail('Exception expected due to not enrolled user.');
 211          } catch (\moodle_exception $e) {
 212              $this->assertEquals('requireloginerror', $e->errorcode);
 213          }
 214  
 215          // Test user with full capabilities.
 216          $this->setUser($this->student);
 217  
 218          // Trigger and capture the event.
 219          $sink = $this->redirectEvents();
 220  
 221          $result = mod_survey_external::view_survey($this->survey->id);
 222          $result = \external_api::clean_returnvalue(mod_survey_external::view_survey_returns(), $result);
 223          $this->assertTrue($result['status']);
 224  
 225          $events = $sink->get_events();
 226          $this->assertCount(1, $events);
 227          $event = array_shift($events);
 228  
 229          // Checking that the event contains the expected values.
 230          $this->assertInstanceOf('\mod_survey\event\course_module_viewed', $event);
 231          $this->assertEquals($this->context, $event->get_context());
 232          $moodlesurvey = new \moodle_url('/mod/survey/view.php', array('id' => $this->cm->id));
 233          $this->assertEquals($moodlesurvey, $event->get_url());
 234          $this->assertEventContextNotUsed($event);
 235          $this->assertNotEmpty($event->get_name());
 236  
 237          // Test user with no capabilities.
 238          // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
 239          assign_capability('mod/survey:participate', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
 240          accesslib_clear_all_caches_for_unit_testing();
 241  
 242          try {
 243              mod_survey_external::view_survey($this->survey->id);
 244              $this->fail('Exception expected due to missing capability.');
 245          } catch (\moodle_exception $e) {
 246              $this->assertEquals('nopermissions', $e->errorcode);
 247          }
 248  
 249      }
 250  
 251      /**
 252       * Test get_questions
 253       */
 254      public function test_get_questions() {
 255          global $DB;
 256  
 257          // Test user with full capabilities.
 258          $this->setUser($this->student);
 259  
 260          // Build our expectation array.
 261          $expectedquestions = array();
 262          $questions = survey_get_questions($this->survey);
 263          foreach ($questions as $q) {
 264              if ($q->type >= 0) {
 265                  $expectedquestions[$q->id] = $q;
 266                  if ($q->multi) {
 267                      $subquestions = survey_get_subquestions($q);
 268                      foreach ($subquestions as $sq) {
 269                          $expectedquestions[$sq->id] = $sq;
 270                      }
 271                  }
 272              }
 273          }
 274  
 275          $result = mod_survey_external::get_questions($this->survey->id);
 276          $result = \external_api::clean_returnvalue(mod_survey_external::get_questions_returns(), $result);
 277  
 278          // Check we receive the same questions.
 279          $this->assertCount(0, $result['warnings']);
 280          foreach ($result['questions'] as $q) {
 281              $this->assertEquals(get_string($expectedquestions[$q['id']]->text, 'survey'), $q['text']);
 282              $this->assertEquals(get_string($expectedquestions[$q['id']]->shorttext, 'survey'), $q['shorttext']);
 283              $this->assertEquals($expectedquestions[$q['id']]->multi, $q['multi']);
 284              $this->assertEquals($expectedquestions[$q['id']]->type, $q['type']);
 285              // Parent questions must have parent eq to 0.
 286              if ($q['multi']) {
 287                  $this->assertEquals(0, $q['parent']);
 288                  $this->assertEquals(get_string($expectedquestions[$q['id']]->options, 'survey'), $q['options']);
 289              }
 290          }
 291  
 292          // Test user with no capabilities.
 293          // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
 294          assign_capability('mod/survey:participate', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
 295          accesslib_clear_all_caches_for_unit_testing();
 296  
 297          try {
 298              mod_survey_external::get_questions($this->survey->id);
 299              $this->fail('Exception expected due to missing capability.');
 300          } catch (\moodle_exception $e) {
 301              $this->assertEquals('nopermissions', $e->errorcode);
 302          }
 303      }
 304  
 305      /**
 306       * Test submit_answers
 307       */
 308      public function test_submit_answers() {
 309          global $DB;
 310  
 311          // Test user with full capabilities.
 312          $this->setUser($this->student);
 313  
 314          // Build our questions and responses array.
 315          $realquestions = array();
 316          $questions = survey_get_questions($this->survey);
 317          $i = 5;
 318          foreach ($questions as $q) {
 319              if ($q->type >= 0) {
 320                  if ($q->multi) {
 321                      $subquestions = survey_get_subquestions($q);
 322                      foreach ($subquestions as $sq) {
 323                          $realquestions[] = array(
 324                              'key' => 'q' . $sq->id,
 325                              'value' => $i % 5 + 1   // Values between 1 and 5.
 326                          );
 327                          $i++;
 328                      }
 329                  } else {
 330                      $realquestions[] = array(
 331                          'key' => 'q' . $q->id,
 332                          'value' => $i % 5 + 1
 333                      );
 334                      $i++;
 335                  }
 336              }
 337          }
 338  
 339          $result = mod_survey_external::submit_answers($this->survey->id, $realquestions);
 340          $result = \external_api::clean_returnvalue(mod_survey_external::submit_answers_returns(), $result);
 341  
 342          $this->assertTrue($result['status']);
 343          $this->assertCount(0, $result['warnings']);
 344  
 345          $dbanswers = $DB->get_records_menu('survey_answers', array('survey' => $this->survey->id), '', 'question, answer1');
 346          foreach ($realquestions as $q) {
 347              $id = str_replace('q', '', $q['key']);
 348              $this->assertEquals($q['value'], $dbanswers[$id]);
 349          }
 350  
 351          // Submit again, we expect an error here.
 352          try {
 353              mod_survey_external::submit_answers($this->survey->id, $realquestions);
 354              $this->fail('Exception expected due to answers already submitted.');
 355          } catch (\moodle_exception $e) {
 356              $this->assertEquals('alreadysubmitted', $e->errorcode);
 357          }
 358  
 359          // Test user with no capabilities.
 360          // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
 361          assign_capability('mod/survey:participate', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
 362          accesslib_clear_all_caches_for_unit_testing();
 363  
 364          try {
 365              mod_survey_external::submit_answers($this->survey->id, $realquestions);
 366              $this->fail('Exception expected due to missing capability.');
 367          } catch (\moodle_exception $e) {
 368              $this->assertEquals('nopermissions', $e->errorcode);
 369          }
 370  
 371          // Test not-enrolled user.
 372          $usernotenrolled = self::getDataGenerator()->create_user();
 373          $this->setUser($usernotenrolled);
 374          try {
 375              mod_survey_external::submit_answers($this->survey->id, $realquestions);
 376              $this->fail('Exception expected due to not enrolled user.');
 377          } catch (\moodle_exception $e) {
 378              $this->assertEquals('requireloginerror', $e->errorcode);
 379          }
 380      }
 381  
 382  }