Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

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

   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', 'lang',
 100                  'template', 'days', '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          $survey1->lang = '';
 113  
 114          $survey2->coursemodule = $survey2->cmid;
 115          $survey2->introformat = 1;
 116          $survey2->surveydone = 0;
 117          $survey2->section = 0;
 118          $survey2->visible = true;
 119          $survey2->groupmode = 0;
 120          $survey2->groupingid = 0;
 121          $tempo = $DB->get_field("survey", "intro", array("id" => $survey2->template));
 122          $survey2->intro = nl2br(get_string($tempo, "survey"));
 123          $survey2->introfiles = [];
 124          $survey2->lang = '';
 125  
 126          foreach ($expectedfields as $field) {
 127              $expected1[$field] = $survey1->{$field};
 128              $expected2[$field] = $survey2->{$field};
 129          }
 130  
 131          $expectedsurveys = array($expected2, $expected1);
 132  
 133          // Call the external function passing course ids.
 134          $result = mod_survey_external::get_surveys_by_courses(array($course2->id, $this->course->id));
 135          $result = \external_api::clean_returnvalue($returndescription, $result);
 136  
 137          $this->assertEquals($expectedsurveys, $result['surveys']);
 138          $this->assertCount(0, $result['warnings']);
 139  
 140          // Call the external function without passing course id.
 141          $result = mod_survey_external::get_surveys_by_courses();
 142          $result = \external_api::clean_returnvalue($returndescription, $result);
 143          $this->assertEquals($expectedsurveys, $result['surveys']);
 144          $this->assertCount(0, $result['warnings']);
 145  
 146          // Unenrol user from second course and alter expected surveys.
 147          $enrol->unenrol_user($instance2, $this->student->id);
 148          array_shift($expectedsurveys);
 149  
 150          // Call the external function without passing course id.
 151          $result = mod_survey_external::get_surveys_by_courses();
 152          $result = \external_api::clean_returnvalue($returndescription, $result);
 153          $this->assertEquals($expectedsurveys, $result['surveys']);
 154  
 155          // Call for the second course we unenrolled the user from, expected warning.
 156          $result = mod_survey_external::get_surveys_by_courses(array($course2->id));
 157          $this->assertCount(1, $result['warnings']);
 158          $this->assertEquals('1', $result['warnings'][0]['warningcode']);
 159          $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
 160  
 161          // Now, try as a teacher for getting all the additional fields.
 162          self::setUser($this->teacher);
 163  
 164          $additionalfields = array('timecreated', 'timemodified', 'section', 'visible', 'groupmode', 'groupingid');
 165  
 166          foreach ($additionalfields as $field) {
 167              $expectedsurveys[0][$field] = $survey1->{$field};
 168          }
 169  
 170          $result = mod_survey_external::get_surveys_by_courses();
 171          $result = \external_api::clean_returnvalue($returndescription, $result);
 172          $this->assertEquals($expectedsurveys, $result['surveys']);
 173  
 174          // Admin also should get all the information.
 175          self::setAdminUser();
 176  
 177          $result = mod_survey_external::get_surveys_by_courses(array($this->course->id));
 178          $result = \external_api::clean_returnvalue($returndescription, $result);
 179          $this->assertEquals($expectedsurveys, $result['surveys']);
 180  
 181          // Now, prohibit capabilities.
 182          $this->setUser($this->student);
 183          $contextcourse1 = \context_course::instance($this->course->id);
 184          // Prohibit capability = mod/survey:participate on Course1 for students.
 185          assign_capability('mod/survey:participate', CAP_PROHIBIT, $this->studentrole->id, $contextcourse1->id);
 186          accesslib_clear_all_caches_for_unit_testing();
 187  
 188          $surveys = mod_survey_external::get_surveys_by_courses(array($this->course->id));
 189          $surveys = \external_api::clean_returnvalue(mod_survey_external::get_surveys_by_courses_returns(), $surveys);
 190          $this->assertFalse(isset($surveys['surveys'][0]['intro']));
 191      }
 192  
 193      /**
 194       * Test view_survey
 195       */
 196      public function test_view_survey() {
 197          global $DB;
 198  
 199          // Test invalid instance id.
 200          try {
 201              mod_survey_external::view_survey(0);
 202              $this->fail('Exception expected due to invalid mod_survey instance id.');
 203          } catch (\moodle_exception $e) {
 204              $this->assertEquals('invalidrecord', $e->errorcode);
 205          }
 206  
 207          // Test not-enrolled user.
 208          $usernotenrolled = self::getDataGenerator()->create_user();
 209          $this->setUser($usernotenrolled);
 210          try {
 211              mod_survey_external::view_survey($this->survey->id);
 212              $this->fail('Exception expected due to not enrolled user.');
 213          } catch (\moodle_exception $e) {
 214              $this->assertEquals('requireloginerror', $e->errorcode);
 215          }
 216  
 217          // Test user with full capabilities.
 218          $this->setUser($this->student);
 219  
 220          // Trigger and capture the event.
 221          $sink = $this->redirectEvents();
 222  
 223          $result = mod_survey_external::view_survey($this->survey->id);
 224          $result = \external_api::clean_returnvalue(mod_survey_external::view_survey_returns(), $result);
 225          $this->assertTrue($result['status']);
 226  
 227          $events = $sink->get_events();
 228          $this->assertCount(1, $events);
 229          $event = array_shift($events);
 230  
 231          // Checking that the event contains the expected values.
 232          $this->assertInstanceOf('\mod_survey\event\course_module_viewed', $event);
 233          $this->assertEquals($this->context, $event->get_context());
 234          $moodlesurvey = new \moodle_url('/mod/survey/view.php', array('id' => $this->cm->id));
 235          $this->assertEquals($moodlesurvey, $event->get_url());
 236          $this->assertEventContextNotUsed($event);
 237          $this->assertNotEmpty($event->get_name());
 238  
 239          // Test user with no capabilities.
 240          // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
 241          assign_capability('mod/survey:participate', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
 242          accesslib_clear_all_caches_for_unit_testing();
 243  
 244          try {
 245              mod_survey_external::view_survey($this->survey->id);
 246              $this->fail('Exception expected due to missing capability.');
 247          } catch (\moodle_exception $e) {
 248              $this->assertEquals('nopermissions', $e->errorcode);
 249          }
 250  
 251      }
 252  
 253      /**
 254       * Test get_questions
 255       */
 256      public function test_get_questions() {
 257          global $DB;
 258  
 259          // Test user with full capabilities.
 260          $this->setUser($this->student);
 261  
 262          // Build our expectation array.
 263          $expectedquestions = array();
 264          $questions = survey_get_questions($this->survey);
 265          foreach ($questions as $q) {
 266              if ($q->type >= 0) {
 267                  $expectedquestions[$q->id] = $q;
 268                  if ($q->multi) {
 269                      $subquestions = survey_get_subquestions($q);
 270                      foreach ($subquestions as $sq) {
 271                          $expectedquestions[$sq->id] = $sq;
 272                      }
 273                  }
 274              }
 275          }
 276  
 277          $result = mod_survey_external::get_questions($this->survey->id);
 278          $result = \external_api::clean_returnvalue(mod_survey_external::get_questions_returns(), $result);
 279  
 280          // Check we receive the same questions.
 281          $this->assertCount(0, $result['warnings']);
 282          foreach ($result['questions'] as $q) {
 283              $this->assertEquals(get_string($expectedquestions[$q['id']]->text, 'survey'), $q['text']);
 284              $this->assertEquals(get_string($expectedquestions[$q['id']]->shorttext, 'survey'), $q['shorttext']);
 285              $this->assertEquals($expectedquestions[$q['id']]->multi, $q['multi']);
 286              $this->assertEquals($expectedquestions[$q['id']]->type, $q['type']);
 287              // Parent questions must have parent eq to 0.
 288              if ($q['multi']) {
 289                  $this->assertEquals(0, $q['parent']);
 290                  $this->assertEquals(get_string($expectedquestions[$q['id']]->options, 'survey'), $q['options']);
 291              }
 292          }
 293  
 294          // Test user with no capabilities.
 295          // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
 296          assign_capability('mod/survey:participate', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
 297          accesslib_clear_all_caches_for_unit_testing();
 298  
 299          try {
 300              mod_survey_external::get_questions($this->survey->id);
 301              $this->fail('Exception expected due to missing capability.');
 302          } catch (\moodle_exception $e) {
 303              $this->assertEquals('nopermissions', $e->errorcode);
 304          }
 305      }
 306  
 307      /**
 308       * Test submit_answers
 309       */
 310      public function test_submit_answers() {
 311          global $DB;
 312  
 313          // Test user with full capabilities.
 314          $this->setUser($this->student);
 315  
 316          // Build our questions and responses array.
 317          $realquestions = array();
 318          $questions = survey_get_questions($this->survey);
 319          $i = 5;
 320          foreach ($questions as $q) {
 321              if ($q->type >= 0) {
 322                  if ($q->multi) {
 323                      $subquestions = survey_get_subquestions($q);
 324                      foreach ($subquestions as $sq) {
 325                          $realquestions[] = array(
 326                              'key' => 'q' . $sq->id,
 327                              'value' => $i % 5 + 1   // Values between 1 and 5.
 328                          );
 329                          $i++;
 330                      }
 331                  } else {
 332                      $realquestions[] = array(
 333                          'key' => 'q' . $q->id,
 334                          'value' => $i % 5 + 1
 335                      );
 336                      $i++;
 337                  }
 338              }
 339          }
 340  
 341          $result = mod_survey_external::submit_answers($this->survey->id, $realquestions);
 342          $result = \external_api::clean_returnvalue(mod_survey_external::submit_answers_returns(), $result);
 343  
 344          $this->assertTrue($result['status']);
 345          $this->assertCount(0, $result['warnings']);
 346  
 347          $dbanswers = $DB->get_records_menu('survey_answers', array('survey' => $this->survey->id), '', 'question, answer1');
 348          foreach ($realquestions as $q) {
 349              $id = str_replace('q', '', $q['key']);
 350              $this->assertEquals($q['value'], $dbanswers[$id]);
 351          }
 352  
 353          // Submit again, we expect an error here.
 354          try {
 355              mod_survey_external::submit_answers($this->survey->id, $realquestions);
 356              $this->fail('Exception expected due to answers already submitted.');
 357          } catch (\moodle_exception $e) {
 358              $this->assertEquals('alreadysubmitted', $e->errorcode);
 359          }
 360  
 361          // Test user with no capabilities.
 362          // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
 363          assign_capability('mod/survey:participate', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
 364          accesslib_clear_all_caches_for_unit_testing();
 365  
 366          try {
 367              mod_survey_external::submit_answers($this->survey->id, $realquestions);
 368              $this->fail('Exception expected due to missing capability.');
 369          } catch (\moodle_exception $e) {
 370              $this->assertEquals('nopermissions', $e->errorcode);
 371          }
 372  
 373          // Test not-enrolled user.
 374          $usernotenrolled = self::getDataGenerator()->create_user();
 375          $this->setUser($usernotenrolled);
 376          try {
 377              mod_survey_external::submit_answers($this->survey->id, $realquestions);
 378              $this->fail('Exception expected due to not enrolled user.');
 379          } catch (\moodle_exception $e) {
 380              $this->assertEquals('requireloginerror', $e->errorcode);
 381          }
 382      }
 383  
 384  }