Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

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

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