Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

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

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