[ Index ]

PHP Cross Reference of moodle-2.8

title

Body

[close]

/course/tests/ -> externallib_test.php (source)

   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   * External course functions unit tests
  19   *
  20   * @package    core_course
  21   * @category   external
  22   * @copyright  2012 Jerome Mouneyrac
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  global $CFG;
  29  
  30  require_once($CFG->dirroot . '/webservice/tests/helpers.php');
  31  
  32  /**
  33   * External course functions unit tests
  34   *
  35   * @package    core_course
  36   * @category   external
  37   * @copyright  2012 Jerome Mouneyrac
  38   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  39   */
  40  class core_course_externallib_testcase extends externallib_advanced_testcase {
  41  
  42      /**
  43       * Tests set up
  44       */
  45      protected function setUp() {
  46          global $CFG;
  47          require_once($CFG->dirroot . '/course/externallib.php');
  48      }
  49  
  50      /**
  51       * Tidy up open files that may be left open.
  52       */
  53      protected function tearDown() {
  54          gc_collect_cycles();
  55      }
  56  
  57      /**
  58       * Test create_categories
  59       */
  60      public function test_create_categories() {
  61  
  62          global $DB;
  63  
  64          $this->resetAfterTest(true);
  65  
  66          // Set the required capabilities by the external function
  67          $contextid = context_system::instance()->id;
  68          $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
  69  
  70          // Create base categories.
  71          $category1 = new stdClass();
  72          $category1->name = 'Root Test Category 1';
  73          $category2 = new stdClass();
  74          $category2->name = 'Root Test Category 2';
  75          $category2->idnumber = 'rootcattest2';
  76          $category2->desc = 'Description for root test category 1';
  77          $category2->theme = 'base';
  78          $categories = array(
  79              array('name' => $category1->name, 'parent' => 0),
  80              array('name' => $category2->name, 'parent' => 0, 'idnumber' => $category2->idnumber,
  81                  'description' => $category2->desc, 'theme' => $category2->theme)
  82          );
  83  
  84          $createdcats = core_course_external::create_categories($categories);
  85  
  86          // We need to execute the return values cleaning process to simulate the web service server.
  87          $createdcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdcats);
  88  
  89          // Initially confirm that base data was inserted correctly.
  90          $this->assertEquals($category1->name, $createdcats[0]['name']);
  91          $this->assertEquals($category2->name, $createdcats[1]['name']);
  92  
  93          // Save the ids.
  94          $category1->id = $createdcats[0]['id'];
  95          $category2->id = $createdcats[1]['id'];
  96  
  97          // Create on sub category.
  98          $category3 = new stdClass();
  99          $category3->name = 'Sub Root Test Category 3';
 100          $subcategories = array(
 101              array('name' => $category3->name, 'parent' => $category1->id)
 102          );
 103  
 104          $createdsubcats = core_course_external::create_categories($subcategories);
 105  
 106          // We need to execute the return values cleaning process to simulate the web service server.
 107          $createdsubcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdsubcats);
 108  
 109          // Confirm that sub categories were inserted correctly.
 110          $this->assertEquals($category3->name, $createdsubcats[0]['name']);
 111  
 112          // Save the ids.
 113          $category3->id = $createdsubcats[0]['id'];
 114  
 115          // Calling the ws function should provide a new sortorder to give category1,
 116          // category2, category3. New course categories are ordered by id not name.
 117          $category1 = $DB->get_record('course_categories', array('id' => $category1->id));
 118          $category2 = $DB->get_record('course_categories', array('id' => $category2->id));
 119          $category3 = $DB->get_record('course_categories', array('id' => $category3->id));
 120  
 121          // sortorder sequence (and sortorder) must be:
 122          // category 1
 123          //   category 3
 124          // category 2
 125          $this->assertGreaterThan($category1->sortorder, $category3->sortorder);
 126          $this->assertGreaterThan($category3->sortorder, $category2->sortorder);
 127  
 128          // Call without required capability
 129          $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
 130          $this->setExpectedException('required_capability_exception');
 131          $createdsubcats = core_course_external::create_categories($subcategories);
 132  
 133      }
 134  
 135      /**
 136       * Test delete categories
 137       */
 138      public function test_delete_categories() {
 139          global $DB;
 140  
 141          $this->resetAfterTest(true);
 142  
 143          // Set the required capabilities by the external function
 144          $contextid = context_system::instance()->id;
 145          $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
 146  
 147          $category1  = self::getDataGenerator()->create_category();
 148          $category2  = self::getDataGenerator()->create_category(
 149                  array('parent' => $category1->id));
 150          $category3  = self::getDataGenerator()->create_category();
 151          $category4  = self::getDataGenerator()->create_category(
 152                  array('parent' => $category3->id));
 153          $category5  = self::getDataGenerator()->create_category(
 154                  array('parent' => $category4->id));
 155  
 156          //delete category 1 and 2 + delete category 4, category 5 moved under category 3
 157          core_course_external::delete_categories(array(
 158              array('id' => $category1->id, 'recursive' => 1),
 159              array('id' => $category4->id)
 160          ));
 161  
 162          //check $category 1 and 2 are deleted
 163          $notdeletedcount = $DB->count_records_select('course_categories',
 164              'id IN ( ' . $category1->id . ',' . $category2->id . ',' . $category4->id . ')');
 165          $this->assertEquals(0, $notdeletedcount);
 166  
 167          //check that $category5 as $category3 for parent
 168          $dbcategory5 = $DB->get_record('course_categories', array('id' => $category5->id));
 169          $this->assertEquals($dbcategory5->path, $category3->path . '/' . $category5->id);
 170  
 171           // Call without required capability
 172          $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
 173          $this->setExpectedException('required_capability_exception');
 174          $createdsubcats = core_course_external::delete_categories(
 175                  array(array('id' => $category3->id)));
 176      }
 177  
 178      /**
 179       * Test get categories
 180       */
 181      public function test_get_categories() {
 182          global $DB;
 183  
 184          $this->resetAfterTest(true);
 185  
 186          $generatedcats = array();
 187          $category1data['idnumber'] = 'idnumbercat1';
 188          $category1data['name'] = 'Category 1 for PHPunit test';
 189          $category1data['description'] = 'Category 1 description';
 190          $category1data['descriptionformat'] = FORMAT_MOODLE;
 191          $category1  = self::getDataGenerator()->create_category($category1data);
 192          $generatedcats[$category1->id] = $category1;
 193          $category2  = self::getDataGenerator()->create_category(
 194                  array('parent' => $category1->id));
 195          $generatedcats[$category2->id] = $category2;
 196          $category6  = self::getDataGenerator()->create_category(
 197                  array('parent' => $category1->id, 'visible' => 0));
 198          $generatedcats[$category6->id] = $category6;
 199          $category3  = self::getDataGenerator()->create_category();
 200          $generatedcats[$category3->id] = $category3;
 201          $category4  = self::getDataGenerator()->create_category(
 202                  array('parent' => $category3->id));
 203          $generatedcats[$category4->id] = $category4;
 204          $category5  = self::getDataGenerator()->create_category(
 205                  array('parent' => $category4->id));
 206          $generatedcats[$category5->id] = $category5;
 207  
 208          // Set the required capabilities by the external function.
 209          $context = context_system::instance();
 210          $roleid = $this->assignUserCapability('moodle/category:manage', $context->id);
 211  
 212          // Retrieve category1 + sub-categories except not visible ones
 213          $categories = core_course_external::get_categories(array(
 214              array('key' => 'id', 'value' => $category1->id),
 215              array('key' => 'visible', 'value' => 1)), 1);
 216  
 217          // We need to execute the return values cleaning process to simulate the web service server.
 218          $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
 219  
 220          // Check we retrieve the good total number of categories.
 221          $this->assertEquals(2, count($categories));
 222  
 223          // Check the return values
 224          foreach ($categories as $category) {
 225              $generatedcat = $generatedcats[$category['id']];
 226              $this->assertEquals($category['idnumber'], $generatedcat->idnumber);
 227              $this->assertEquals($category['name'], $generatedcat->name);
 228              $this->assertEquals($category['description'], $generatedcat->description);
 229              $this->assertEquals($category['descriptionformat'], FORMAT_HTML);
 230          }
 231  
 232          // Check different params.
 233          $categories = core_course_external::get_categories(array(
 234              array('key' => 'id', 'value' => $category1->id),
 235              array('key' => 'idnumber', 'value' => $category1->idnumber),
 236              array('key' => 'visible', 'value' => 1)), 0);
 237  
 238          // We need to execute the return values cleaning process to simulate the web service server.
 239          $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
 240  
 241          $this->assertEquals(1, count($categories));
 242  
 243          // Retrieve categories from parent.
 244          $categories = core_course_external::get_categories(array(
 245              array('key' => 'parent', 'value' => $category3->id)), 1);
 246          $this->assertEquals(2, count($categories));
 247  
 248          // Retrieve all categories.
 249          $categories = core_course_external::get_categories();
 250  
 251          // We need to execute the return values cleaning process to simulate the web service server.
 252          $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
 253  
 254          $this->assertEquals($DB->count_records('course_categories'), count($categories));
 255  
 256          // Call without required capability (it will fail cause of the search on idnumber).
 257          $this->unassignUserCapability('moodle/category:manage', $context->id, $roleid);
 258          $this->setExpectedException('moodle_exception');
 259          $categories = core_course_external::get_categories(array(
 260              array('key' => 'id', 'value' => $category1->id),
 261              array('key' => 'idnumber', 'value' => $category1->idnumber),
 262              array('key' => 'visible', 'value' => 1)), 0);
 263      }
 264  
 265      /**
 266       * Test update_categories
 267       */
 268      public function test_update_categories() {
 269          global $DB;
 270  
 271          $this->resetAfterTest(true);
 272  
 273          // Set the required capabilities by the external function
 274          $contextid = context_system::instance()->id;
 275          $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
 276  
 277          // Create base categories.
 278          $category1data['idnumber'] = 'idnumbercat1';
 279          $category1data['name'] = 'Category 1 for PHPunit test';
 280          $category1data['description'] = 'Category 1 description';
 281          $category1data['descriptionformat'] = FORMAT_MOODLE;
 282          $category1  = self::getDataGenerator()->create_category($category1data);
 283          $category2  = self::getDataGenerator()->create_category(
 284                  array('parent' => $category1->id));
 285          $category3  = self::getDataGenerator()->create_category();
 286          $category4  = self::getDataGenerator()->create_category(
 287                  array('parent' => $category3->id));
 288          $category5  = self::getDataGenerator()->create_category(
 289                  array('parent' => $category4->id));
 290  
 291          // We update all category1 attribut.
 292          // Then we move cat4 and cat5 parent: cat3 => cat1
 293          $categories = array(
 294              array('id' => $category1->id,
 295                  'name' => $category1->name . '_updated',
 296                  'idnumber' => $category1->idnumber . '_updated',
 297                  'description' => $category1->description . '_updated',
 298                  'descriptionformat' => FORMAT_HTML,
 299                  'theme' => $category1->theme),
 300              array('id' => $category4->id, 'parent' => $category1->id));
 301  
 302          core_course_external::update_categories($categories);
 303  
 304          // Check the values were updated.
 305          $dbcategories = $DB->get_records_select('course_categories',
 306                  'id IN (' . $category1->id . ',' . $category2->id . ',' . $category2->id
 307                  . ',' . $category3->id . ',' . $category4->id . ',' . $category5->id .')');
 308          $this->assertEquals($category1->name . '_updated',
 309                  $dbcategories[$category1->id]->name);
 310          $this->assertEquals($category1->idnumber . '_updated',
 311                  $dbcategories[$category1->id]->idnumber);
 312          $this->assertEquals($category1->description . '_updated',
 313                  $dbcategories[$category1->id]->description);
 314          $this->assertEquals(FORMAT_HTML, $dbcategories[$category1->id]->descriptionformat);
 315  
 316          // Check that category4 and category5 have been properly moved.
 317          $this->assertEquals('/' . $category1->id . '/' . $category4->id,
 318                  $dbcategories[$category4->id]->path);
 319          $this->assertEquals('/' . $category1->id . '/' . $category4->id . '/' . $category5->id,
 320                  $dbcategories[$category5->id]->path);
 321  
 322          // Call without required capability.
 323          $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
 324          $this->setExpectedException('required_capability_exception');
 325          core_course_external::update_categories($categories);
 326      }
 327  
 328      /**
 329       * Test create_courses
 330       */
 331      public function test_create_courses() {
 332          global $DB;
 333  
 334          $this->resetAfterTest(true);
 335  
 336          // Enable course completion.
 337          set_config('enablecompletion', 1);
 338  
 339          // Set the required capabilities by the external function
 340          $contextid = context_system::instance()->id;
 341          $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
 342          $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
 343  
 344          $category  = self::getDataGenerator()->create_category();
 345  
 346          // Create base categories.
 347          $course1['fullname'] = 'Test course 1';
 348          $course1['shortname'] = 'Testcourse1';
 349          $course1['categoryid'] = $category->id;
 350          $course2['fullname'] = 'Test course 2';
 351          $course2['shortname'] = 'Testcourse2';
 352          $course2['categoryid'] = $category->id;
 353          $course2['idnumber'] = 'testcourse2idnumber';
 354          $course2['summary'] = 'Description for course 2';
 355          $course2['summaryformat'] = FORMAT_MOODLE;
 356          $course2['format'] = 'weeks';
 357          $course2['showgrades'] = 1;
 358          $course2['newsitems'] = 3;
 359          $course2['startdate'] = 1420092000; // 01/01/2015
 360          $course2['numsections'] = 4;
 361          $course2['maxbytes'] = 100000;
 362          $course2['showreports'] = 1;
 363          $course2['visible'] = 0;
 364          $course2['hiddensections'] = 0;
 365          $course2['groupmode'] = 0;
 366          $course2['groupmodeforce'] = 0;
 367          $course2['defaultgroupingid'] = 0;
 368          $course2['enablecompletion'] = 1;
 369          $course2['completionnotify'] = 1;
 370          $course2['lang'] = 'en';
 371          $course2['forcetheme'] = 'base';
 372          $course3['fullname'] = 'Test course 3';
 373          $course3['shortname'] = 'Testcourse3';
 374          $course3['categoryid'] = $category->id;
 375          $course3['format'] = 'topics';
 376          $course3options = array('numsections' => 8,
 377              'hiddensections' => 1,
 378              'coursedisplay' => 1);
 379          $course3['courseformatoptions'] = array();
 380          foreach ($course3options as $key => $value) {
 381              $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
 382          }
 383          $courses = array($course1, $course2, $course3);
 384  
 385          $createdcourses = core_course_external::create_courses($courses);
 386  
 387          // We need to execute the return values cleaning process to simulate the web service server.
 388          $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
 389  
 390          // Check that right number of courses were created.
 391          $this->assertEquals(3, count($createdcourses));
 392  
 393          // Check that the courses were correctly created.
 394          foreach ($createdcourses as $createdcourse) {
 395              $courseinfo = course_get_format($createdcourse['id'])->get_course();
 396  
 397              if ($createdcourse['shortname'] == $course2['shortname']) {
 398                  $this->assertEquals($courseinfo->fullname, $course2['fullname']);
 399                  $this->assertEquals($courseinfo->shortname, $course2['shortname']);
 400                  $this->assertEquals($courseinfo->category, $course2['categoryid']);
 401                  $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
 402                  $this->assertEquals($courseinfo->summary, $course2['summary']);
 403                  $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
 404                  $this->assertEquals($courseinfo->format, $course2['format']);
 405                  $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
 406                  $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
 407                  $this->assertEquals($courseinfo->startdate, $course2['startdate']);
 408                  $this->assertEquals($courseinfo->numsections, $course2['numsections']);
 409                  $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
 410                  $this->assertEquals($courseinfo->showreports, $course2['showreports']);
 411                  $this->assertEquals($courseinfo->visible, $course2['visible']);
 412                  $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
 413                  $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
 414                  $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
 415                  $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
 416                  $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
 417                  $this->assertEquals($courseinfo->lang, $course2['lang']);
 418  
 419                  if (!empty($CFG->allowcoursethemes)) {
 420                      $this->assertEquals($courseinfo->theme, $course2['forcetheme']);
 421                  }
 422  
 423                  // We enabled completion at the beginning of the test.
 424                  $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
 425  
 426              } else if ($createdcourse['shortname'] == $course1['shortname']) {
 427                  $courseconfig = get_config('moodlecourse');
 428                  $this->assertEquals($courseinfo->fullname, $course1['fullname']);
 429                  $this->assertEquals($courseinfo->shortname, $course1['shortname']);
 430                  $this->assertEquals($courseinfo->category, $course1['categoryid']);
 431                  $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
 432                  $this->assertEquals($courseinfo->format, $courseconfig->format);
 433                  $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
 434                  $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
 435                  $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
 436                  $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
 437                  $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
 438                  $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
 439                  $this->assertEquals($courseinfo->defaultgroupingid, 0);
 440              } else if ($createdcourse['shortname'] == $course3['shortname']) {
 441                  $this->assertEquals($courseinfo->fullname, $course3['fullname']);
 442                  $this->assertEquals($courseinfo->shortname, $course3['shortname']);
 443                  $this->assertEquals($courseinfo->category, $course3['categoryid']);
 444                  $this->assertEquals($courseinfo->format, $course3['format']);
 445                  $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
 446                  $this->assertEquals($courseinfo->numsections, $course3options['numsections']);
 447                  $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
 448              } else {
 449                  throw moodle_exception('Unexpected shortname');
 450              }
 451          }
 452  
 453          // Call without required capability
 454          $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
 455          $this->setExpectedException('required_capability_exception');
 456          $createdsubcats = core_course_external::create_courses($courses);
 457      }
 458  
 459      /**
 460       * Test delete_courses
 461       */
 462      public function test_delete_courses() {
 463          global $DB, $USER;
 464  
 465          $this->resetAfterTest(true);
 466  
 467          // Admin can delete a course.
 468          $this->setAdminUser();
 469          // Validate_context() will fail as the email is not set by $this->setAdminUser().
 470          $USER->email = '[email protected]';
 471  
 472          $course1  = self::getDataGenerator()->create_course();
 473          $course2  = self::getDataGenerator()->create_course();
 474          $course3  = self::getDataGenerator()->create_course();
 475  
 476          // Delete courses.
 477          core_course_external::delete_courses(array($course1->id, $course2->id));
 478  
 479          // Check $course 1 and 2 are deleted.
 480          $notdeletedcount = $DB->count_records_select('course',
 481              'id IN ( ' . $course1->id . ',' . $course2->id . ')');
 482          $this->assertEquals(0, $notdeletedcount);
 483  
 484           // Fail when the user is not allow to access the course (enrolled) or is not admin.
 485          $this->setGuestUser();
 486          $this->setExpectedException('require_login_exception');
 487          $createdsubcats = core_course_external::delete_courses(array($course3->id));
 488      }
 489  
 490      /**
 491       * Test get_courses
 492       */
 493      public function test_get_courses () {
 494          global $DB;
 495  
 496          $this->resetAfterTest(true);
 497  
 498          $generatedcourses = array();
 499          $coursedata['idnumber'] = 'idnumbercourse1';
 500          $coursedata['fullname'] = 'Course 1 for PHPunit test';
 501          $coursedata['summary'] = 'Course 1 description';
 502          $coursedata['summaryformat'] = FORMAT_MOODLE;
 503          $course1  = self::getDataGenerator()->create_course($coursedata);
 504          $generatedcourses[$course1->id] = $course1;
 505          $course2  = self::getDataGenerator()->create_course();
 506          $generatedcourses[$course2->id] = $course2;
 507          $course3  = self::getDataGenerator()->create_course(array('format' => 'topics'));
 508          $generatedcourses[$course3->id] = $course3;
 509  
 510          // Set the required capabilities by the external function.
 511          $context = context_system::instance();
 512          $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
 513          $this->assignUserCapability('moodle/course:update',
 514                  context_course::instance($course1->id)->id, $roleid);
 515          $this->assignUserCapability('moodle/course:update',
 516                  context_course::instance($course2->id)->id, $roleid);
 517          $this->assignUserCapability('moodle/course:update',
 518                  context_course::instance($course3->id)->id, $roleid);
 519  
 520          $courses = core_course_external::get_courses(array('ids' =>
 521              array($course1->id, $course2->id)));
 522  
 523          // We need to execute the return values cleaning process to simulate the web service server.
 524          $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
 525  
 526          // Check we retrieve the good total number of categories.
 527          $this->assertEquals(2, count($courses));
 528  
 529          foreach ($courses as $course) {
 530              $dbcourse = $generatedcourses[$course['id']];
 531              $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
 532              $this->assertEquals($course['fullname'], $dbcourse->fullname);
 533              $this->assertEquals($course['summary'], $dbcourse->summary);
 534              $this->assertEquals($course['summaryformat'], FORMAT_HTML);
 535              $this->assertEquals($course['shortname'], $dbcourse->shortname);
 536              $this->assertEquals($course['categoryid'], $dbcourse->category);
 537              $this->assertEquals($course['format'], $dbcourse->format);
 538              $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
 539              $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
 540              $this->assertEquals($course['startdate'], $dbcourse->startdate);
 541              $this->assertEquals($course['numsections'], $dbcourse->numsections);
 542              $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
 543              $this->assertEquals($course['showreports'], $dbcourse->showreports);
 544              $this->assertEquals($course['visible'], $dbcourse->visible);
 545              $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
 546              $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
 547              $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
 548              $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
 549              $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
 550              $this->assertEquals($course['lang'], $dbcourse->lang);
 551              $this->assertEquals($course['forcetheme'], $dbcourse->theme);
 552              $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
 553              if ($dbcourse->format === 'topics') {
 554                  $this->assertEquals($course['courseformatoptions'], array(
 555                      array('name' => 'numsections', 'value' => $dbcourse->numsections),
 556                      array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
 557                      array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
 558                  ));
 559              }
 560          }
 561  
 562          // Get all courses in the DB
 563          $courses = core_course_external::get_courses(array());
 564  
 565          // We need to execute the return values cleaning process to simulate the web service server.
 566          $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
 567  
 568          $this->assertEquals($DB->count_records('course'), count($courses));
 569      }
 570  
 571      /**
 572       * Test get_course_contents
 573       */
 574      public function test_get_course_contents() {
 575          $this->resetAfterTest(true);
 576  
 577          $course  = self::getDataGenerator()->create_course();
 578          $forumdescription = 'This is the forum description';
 579          $forum = $this->getDataGenerator()->create_module('forum',
 580              array('course'=>$course->id, 'intro' => $forumdescription),
 581              array('showdescription' => true));
 582          $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
 583          $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
 584          $datacm = get_coursemodule_from_instance('page', $data->id);
 585          $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
 586          $pagecm = get_coursemodule_from_instance('page', $page->id);
 587          $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
 588                  So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
 589          $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
 590              'intro' => $labeldescription));
 591          $labelcm = get_coursemodule_from_instance('label', $label->id);
 592          $url = $this->getDataGenerator()->create_module('url', array('course' => $course->id,
 593              'name' => 'URL: % & $ ../'));
 594  
 595          // Set the required capabilities by the external function.
 596          $context = context_course::instance($course->id);
 597          $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
 598          $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
 599  
 600          $sections = core_course_external::get_course_contents($course->id, array());
 601  
 602          // We need to execute the return values cleaning process to simulate the web service server.
 603          $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
 604  
 605          // Check that forum and label descriptions are correctly returned.
 606          $firstsection = array_pop($sections);
 607          $modinfo = get_fast_modinfo($course);
 608          $testexecuted = 0;
 609          foreach($firstsection['modules'] as $module) {
 610              if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
 611                  $cm = $modinfo->cms[$forumcm->id];
 612                  $formattedtext = format_text($cm->content, FORMAT_HTML,
 613                      array('noclean' => true, 'para' => false, 'filter' => false));
 614                  $this->assertEquals($formattedtext, $module['description']);
 615                  $testexecuted = $testexecuted + 1;
 616              } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
 617                  $cm = $modinfo->cms[$labelcm->id];
 618                  $formattedtext = format_text($cm->content, FORMAT_HTML,
 619                      array('noclean' => true, 'para' => false, 'filter' => false));
 620                  $this->assertEquals($formattedtext, $module['description']);
 621                  $testexecuted = $testexecuted + 1;
 622              }
 623          }
 624          $this->assertEquals(2, $testexecuted);
 625  
 626          // Check that the only return section has the 5 created modules
 627          $this->assertEquals(5, count($firstsection['modules']));
 628      }
 629  
 630      /**
 631       * Test duplicate_course
 632       */
 633      public function test_duplicate_course() {
 634          $this->resetAfterTest(true);
 635  
 636          // Create one course with three modules.
 637          $course  = self::getDataGenerator()->create_course();
 638          $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
 639          $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
 640          $forumcontext = context_module::instance($forum->cmid);
 641          $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
 642          $datacontext = context_module::instance($data->cmid);
 643          $datacm = get_coursemodule_from_instance('page', $data->id);
 644          $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
 645          $pagecontext = context_module::instance($page->cmid);
 646          $pagecm = get_coursemodule_from_instance('page', $page->id);
 647  
 648          // Set the required capabilities by the external function.
 649          $coursecontext = context_course::instance($course->id);
 650          $categorycontext = context_coursecat::instance($course->category);
 651          $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
 652          $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
 653          $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
 654          $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
 655          $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
 656          // Optional capabilities to copy user data.
 657          $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
 658          $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
 659  
 660          $newcourse['fullname'] = 'Course duplicate';
 661          $newcourse['shortname'] = 'courseduplicate';
 662          $newcourse['categoryid'] = $course->category;
 663          $newcourse['visible'] = true;
 664          $newcourse['options'][] = array('name' => 'users', 'value' => true);
 665  
 666          $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
 667                  $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
 668  
 669          // We need to execute the return values cleaning process to simulate the web service server.
 670          $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
 671  
 672          // Check that the course has been duplicated.
 673          $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
 674      }
 675  
 676      /**
 677       * Test update_courses
 678       */
 679      public function test_update_courses() {
 680          global $DB, $CFG, $USER, $COURSE;
 681  
 682          // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
 683          // trick because we are both updating and getting (for testing) course information
 684          // in the same request and core_course_external::update_courses()
 685          // is overwriting $COURSE all over the time with OLD values, so later
 686          // use of get_course() fetches those OLD values instead of the updated ones.
 687          // See MDL-39723 for more info.
 688          $origcourse = clone($COURSE);
 689  
 690          $this->resetAfterTest(true);
 691  
 692          // Set the required capabilities by the external function.
 693          $contextid = context_system::instance()->id;
 694          $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
 695          $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
 696          $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
 697          $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
 698          $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
 699          $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
 700          $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
 701          $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
 702  
 703          // Create category and course.
 704          $category1  = self::getDataGenerator()->create_category();
 705          $category2  = self::getDataGenerator()->create_category();
 706          $originalcourse1 = self::getDataGenerator()->create_course();
 707          self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
 708          $originalcourse2 = self::getDataGenerator()->create_course();
 709          self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
 710  
 711          // Course values to be updated.
 712          $course1['id'] = $originalcourse1->id;
 713          $course1['fullname'] = 'Updated test course 1';
 714          $course1['shortname'] = 'Udestedtestcourse1';
 715          $course1['categoryid'] = $category1->id;
 716          $course2['id'] = $originalcourse2->id;
 717          $course2['fullname'] = 'Updated test course 2';
 718          $course2['shortname'] = 'Updestedtestcourse2';
 719          $course2['categoryid'] = $category2->id;
 720          $course2['idnumber'] = 'Updatedidnumber2';
 721          $course2['summary'] = 'Updaated description for course 2';
 722          $course2['summaryformat'] = FORMAT_HTML;
 723          $course2['format'] = 'topics';
 724          $course2['showgrades'] = 1;
 725          $course2['newsitems'] = 3;
 726          $course2['startdate'] = 1420092000; // 01/01/2015.
 727          $course2['numsections'] = 4;
 728          $course2['maxbytes'] = 100000;
 729          $course2['showreports'] = 1;
 730          $course2['visible'] = 0;
 731          $course2['hiddensections'] = 0;
 732          $course2['groupmode'] = 0;
 733          $course2['groupmodeforce'] = 0;
 734          $course2['defaultgroupingid'] = 0;
 735          $course2['enablecompletion'] = 1;
 736          $course2['lang'] = 'en';
 737          $course2['forcetheme'] = 'base';
 738          $courses = array($course1, $course2);
 739  
 740          $updatedcoursewarnings = core_course_external::update_courses($courses);
 741          $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
 742  
 743          // Check that right number of courses were created.
 744          $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
 745  
 746          // Check that the courses were correctly created.
 747          foreach ($courses as $course) {
 748              $courseinfo = course_get_format($course['id'])->get_course();
 749              if ($course['id'] == $course2['id']) {
 750                  $this->assertEquals($course2['fullname'], $courseinfo->fullname);
 751                  $this->assertEquals($course2['shortname'], $courseinfo->shortname);
 752                  $this->assertEquals($course2['categoryid'], $courseinfo->category);
 753                  $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
 754                  $this->assertEquals($course2['summary'], $courseinfo->summary);
 755                  $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
 756                  $this->assertEquals($course2['format'], $courseinfo->format);
 757                  $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
 758                  $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
 759                  $this->assertEquals($course2['startdate'], $courseinfo->startdate);
 760                  $this->assertEquals($course2['numsections'], $courseinfo->numsections);
 761                  $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
 762                  $this->assertEquals($course2['showreports'], $courseinfo->showreports);
 763                  $this->assertEquals($course2['visible'], $courseinfo->visible);
 764                  $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
 765                  $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
 766                  $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
 767                  $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
 768                  $this->assertEquals($course2['lang'], $courseinfo->lang);
 769  
 770                  if (!empty($CFG->allowcoursethemes)) {
 771                      $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
 772                  }
 773  
 774                  if (completion_info::is_enabled_for_site()) {
 775                      $this->assertEquals($course2['enabledcompletion'], $courseinfo->enablecompletion);
 776                  }
 777              } else if ($course['id'] == $course1['id']) {
 778                  $this->assertEquals($course1['fullname'], $courseinfo->fullname);
 779                  $this->assertEquals($course1['shortname'], $courseinfo->shortname);
 780                  $this->assertEquals($course1['categoryid'], $courseinfo->category);
 781                  $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
 782                  $this->assertEquals('topics', $courseinfo->format);
 783                  $this->assertEquals(5, $courseinfo->numsections);
 784                  $this->assertEquals(0, $courseinfo->newsitems);
 785                  $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
 786              } else {
 787                  throw moodle_exception('Unexpected shortname');
 788              }
 789          }
 790  
 791          $courses = array($course1);
 792          // Try update course without update capability.
 793          $user = self::getDataGenerator()->create_user();
 794          $this->setUser($user);
 795          $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
 796          self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
 797          $updatedcoursewarnings = core_course_external::update_courses($courses);
 798          $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
 799  
 800          // Try update course category without capability.
 801          $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
 802          $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
 803          $user = self::getDataGenerator()->create_user();
 804          $this->setUser($user);
 805          self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
 806          $course1['categoryid'] = $category2->id;
 807          $courses = array($course1);
 808          $updatedcoursewarnings = core_course_external::update_courses($courses);
 809          $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
 810  
 811          // Try update course fullname without capability.
 812          $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
 813          $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
 814          $user = self::getDataGenerator()->create_user();
 815          $this->setUser($user);
 816          self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
 817          $updatedcoursewarnings = core_course_external::update_courses($courses);
 818          $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
 819          $course1['fullname'] = 'Testing fullname without permission';
 820          $courses = array($course1);
 821          $updatedcoursewarnings = core_course_external::update_courses($courses);
 822          $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
 823  
 824          // Try update course shortname without capability.
 825          $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
 826          $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
 827          $user = self::getDataGenerator()->create_user();
 828          $this->setUser($user);
 829          self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
 830          $updatedcoursewarnings = core_course_external::update_courses($courses);
 831          $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
 832          $course1['shortname'] = 'Testing shortname without permission';
 833          $courses = array($course1);
 834          $updatedcoursewarnings = core_course_external::update_courses($courses);
 835          $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
 836  
 837          // Try update course idnumber without capability.
 838          $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
 839          $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
 840          $user = self::getDataGenerator()->create_user();
 841          $this->setUser($user);
 842          self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
 843          $updatedcoursewarnings = core_course_external::update_courses($courses);
 844          $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
 845          $course1['idnumber'] = 'NEWIDNUMBER';
 846          $courses = array($course1);
 847          $updatedcoursewarnings = core_course_external::update_courses($courses);
 848          $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
 849  
 850          // Try update course summary without capability.
 851          $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
 852          $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
 853          $user = self::getDataGenerator()->create_user();
 854          $this->setUser($user);
 855          self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
 856          $updatedcoursewarnings = core_course_external::update_courses($courses);
 857          $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
 858          $course1['summary'] = 'New summary';
 859          $courses = array($course1);
 860          $updatedcoursewarnings = core_course_external::update_courses($courses);
 861          $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
 862  
 863          // Try update course with invalid summary format.
 864          $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
 865          $user = self::getDataGenerator()->create_user();
 866          $this->setUser($user);
 867          self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
 868          $updatedcoursewarnings = core_course_external::update_courses($courses);
 869          $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
 870          $course1['summaryformat'] = 10;
 871          $courses = array($course1);
 872          $updatedcoursewarnings = core_course_external::update_courses($courses);
 873          $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
 874  
 875          // Try update course visibility without capability.
 876          $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
 877          $user = self::getDataGenerator()->create_user();
 878          $this->setUser($user);
 879          self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
 880          $course1['summaryformat'] = FORMAT_MOODLE;
 881          $courses = array($course1);
 882          $updatedcoursewarnings = core_course_external::update_courses($courses);
 883          $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
 884          $course1['visible'] = 0;
 885          $courses = array($course1);
 886          $updatedcoursewarnings = core_course_external::update_courses($courses);
 887          $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
 888      }
 889  
 890      /**
 891       * Test delete course_module.
 892       */
 893      public function test_delete_modules() {
 894          global $DB;
 895  
 896          // Ensure we reset the data after this test.
 897          $this->resetAfterTest(true);
 898  
 899          // Create a user.
 900          $user = self::getDataGenerator()->create_user();
 901  
 902          // Set the tests to run as the user.
 903          self::setUser($user);
 904  
 905          // Create a course to add the modules.
 906          $course = self::getDataGenerator()->create_course();
 907  
 908          // Create two test modules.
 909          $record = new stdClass();
 910          $record->course = $course->id;
 911          $module1 = self::getDataGenerator()->create_module('forum', $record);
 912          $module2 = self::getDataGenerator()->create_module('assign', $record);
 913  
 914          // Check the forum was correctly created.
 915          $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
 916  
 917          // Check the assignment was correctly created.
 918          $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
 919  
 920          // Check data exists in the course modules table.
 921          $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
 922                  array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
 923  
 924          // Enrol the user in the course.
 925          $enrol = enrol_get_plugin('manual');
 926          $enrolinstances = enrol_get_instances($course->id, true);
 927          foreach ($enrolinstances as $courseenrolinstance) {
 928              if ($courseenrolinstance->enrol == "manual") {
 929                  $instance = $courseenrolinstance;
 930                  break;
 931              }
 932          }
 933          $enrol->enrol_user($instance, $user->id);
 934  
 935          // Assign capabilities to delete module 1.
 936          $modcontext = context_module::instance($module1->cmid);
 937          $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
 938  
 939          // Assign capabilities to delete module 2.
 940          $modcontext = context_module::instance($module2->cmid);
 941          $newrole = create_role('Role 2', 'role2', 'Role 2 description');
 942          $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
 943  
 944          // Deleting these module instances.
 945          core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
 946  
 947          // Check the forum was deleted.
 948          $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
 949  
 950          // Check the assignment was deleted.
 951          $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
 952  
 953          // Check we retrieve no data in the course modules table.
 954          $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
 955                  array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
 956  
 957          // Call with non-existent course module id and ensure exception thrown.
 958          try {
 959              core_course_external::delete_modules(array('1337'));
 960              $this->fail('Exception expected due to missing course module.');
 961          } catch (dml_missing_record_exception $e) {
 962              $this->assertEquals('invalidrecord', $e->errorcode);
 963          }
 964  
 965          // Create two modules.
 966          $module1 = self::getDataGenerator()->create_module('forum', $record);
 967          $module2 = self::getDataGenerator()->create_module('assign', $record);
 968  
 969          // Since these modules were recreated the user will not have capabilities
 970          // to delete them, ensure exception is thrown if they try.
 971          try {
 972              core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
 973              $this->fail('Exception expected due to missing capability.');
 974          } catch (moodle_exception $e) {
 975              $this->assertEquals('nopermissions', $e->errorcode);
 976          }
 977  
 978          // Unenrol user from the course.
 979          $enrol->unenrol_user($instance, $user->id);
 980  
 981          // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
 982          try {
 983              core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
 984              $this->fail('Exception expected due to being unenrolled from the course.');
 985          } catch (moodle_exception $e) {
 986              $this->assertEquals('requireloginerror', $e->errorcode);
 987          }
 988      }
 989  
 990      /**
 991       * Test import_course into an empty course
 992       */
 993      public function test_import_course_empty() {
 994          global $USER;
 995  
 996          $this->resetAfterTest(true);
 997  
 998          $course1  = self::getDataGenerator()->create_course();
 999          $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1000          $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1001  
1002          $course2  = self::getDataGenerator()->create_course();
1003  
1004          $course1cms = get_fast_modinfo($course1->id)->get_cms();
1005          $course2cms = get_fast_modinfo($course2->id)->get_cms();
1006  
1007          // Verify the state of the courses before we do the import.
1008          $this->assertCount(2, $course1cms);
1009          $this->assertEmpty($course2cms);
1010  
1011          // Setup the user to run the operation (ugly hack because validate_context() will
1012          // fail as the email is not set by $this->setAdminUser()).
1013          $this->setAdminUser();
1014          $USER->email = '[email protected]';
1015  
1016          // Import from course1 to course2.
1017          core_course_external::import_course($course1->id, $course2->id, 0);
1018  
1019          // Verify that now we have two modules in both courses.
1020          $course1cms = get_fast_modinfo($course1->id)->get_cms();
1021          $course2cms = get_fast_modinfo($course2->id)->get_cms();
1022          $this->assertCount(2, $course1cms);
1023          $this->assertCount(2, $course2cms);
1024  
1025          // Verify that the names transfered across correctly.
1026          foreach ($course2cms as $cm) {
1027              if ($cm->modname === 'page') {
1028                  $this->assertEquals($cm->name, $page->name);
1029              } else if ($cm->modname === 'forum') {
1030                  $this->assertEquals($cm->name, $forum->name);
1031              } else {
1032                  $this->fail('Unknown CM found.');
1033              }
1034          }
1035      }
1036  
1037      /**
1038       * Test import_course into an filled course
1039       */
1040      public function test_import_course_filled() {
1041          global $USER;
1042  
1043          $this->resetAfterTest(true);
1044  
1045          // Add forum and page to course1.
1046          $course1  = self::getDataGenerator()->create_course();
1047          $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1048          $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1049  
1050          // Add quiz to course 2.
1051          $course2  = self::getDataGenerator()->create_course();
1052          $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1053  
1054          $course1cms = get_fast_modinfo($course1->id)->get_cms();
1055          $course2cms = get_fast_modinfo($course2->id)->get_cms();
1056  
1057          // Verify the state of the courses before we do the import.
1058          $this->assertCount(2, $course1cms);
1059          $this->assertCount(1, $course2cms);
1060  
1061          // Setup the user to run the operation (ugly hack because validate_context() will
1062          // fail as the email is not set by $this->setAdminUser()).
1063          $this->setAdminUser();
1064          $USER->email = '[email protected]';
1065  
1066          // Import from course1 to course2 without deleting content.
1067          core_course_external::import_course($course1->id, $course2->id, 0);
1068  
1069          $course2cms = get_fast_modinfo($course2->id)->get_cms();
1070  
1071          // Verify that now we have three modules in course2.
1072          $this->assertCount(3, $course2cms);
1073  
1074          // Verify that the names transfered across correctly.
1075          foreach ($course2cms as $cm) {
1076              if ($cm->modname === 'page') {
1077                  $this->assertEquals($cm->name, $page->name);
1078              } else if ($cm->modname === 'forum') {
1079                  $this->assertEquals($cm->name, $forum->name);
1080              } else if ($cm->modname === 'quiz') {
1081                  $this->assertEquals($cm->name, $quiz->name);
1082              } else {
1083                  $this->fail('Unknown CM found.');
1084              }
1085          }
1086      }
1087  
1088      /**
1089       * Test import_course with only blocks set to backup
1090       */
1091      public function test_import_course_blocksonly() {
1092          global $USER, $DB;
1093  
1094          $this->resetAfterTest(true);
1095  
1096          // Add forum and page to course1.
1097          $course1  = self::getDataGenerator()->create_course();
1098          $course1ctx = context_course::instance($course1->id);
1099          $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1100          $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1101  
1102          $course2  = self::getDataGenerator()->create_course();
1103          $course2ctx = context_course::instance($course2->id);
1104          $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1105          $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1106  
1107          // Setup the user to run the operation (ugly hack because validate_context() will
1108          // fail as the email is not set by $this->setAdminUser()).
1109          $this->setAdminUser();
1110          $USER->email = '[email protected]';
1111  
1112          // Import from course1 to course2 without deleting content, but excluding
1113          // activities.
1114          $options = array(
1115              array('name' => 'activities', 'value' => 0),
1116              array('name' => 'blocks', 'value' => 1),
1117              array('name' => 'filters', 'value' => 0),
1118          );
1119  
1120          core_course_external::import_course($course1->id, $course2->id, 0, $options);
1121  
1122          $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1123          $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1124          // Check that course modules haven't changed, but that blocks have.
1125          $this->assertEquals($initialcmcount, $newcmcount);
1126          $this->assertEquals(($initialblockcount + 1), $newblockcount);
1127      }
1128  
1129      /**
1130       * Test import_course into an filled course, deleting content.
1131       */
1132      public function test_import_course_deletecontent() {
1133          global $USER;
1134          $this->resetAfterTest(true);
1135  
1136          // Add forum and page to course1.
1137          $course1  = self::getDataGenerator()->create_course();
1138          $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1139          $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1140  
1141          // Add quiz to course 2.
1142          $course2  = self::getDataGenerator()->create_course();
1143          $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1144  
1145          $course1cms = get_fast_modinfo($course1->id)->get_cms();
1146          $course2cms = get_fast_modinfo($course2->id)->get_cms();
1147  
1148          // Verify the state of the courses before we do the import.
1149          $this->assertCount(2, $course1cms);
1150          $this->assertCount(1, $course2cms);
1151  
1152          // Setup the user to run the operation (ugly hack because validate_context() will
1153          // fail as the email is not set by $this->setAdminUser()).
1154          $this->setAdminUser();
1155          $USER->email = '[email protected]';
1156  
1157          // Import from course1 to course2,  deleting content.
1158          core_course_external::import_course($course1->id, $course2->id, 1);
1159  
1160          $course2cms = get_fast_modinfo($course2->id)->get_cms();
1161  
1162          // Verify that now we have two modules in course2.
1163          $this->assertCount(2, $course2cms);
1164  
1165          // Verify that the course only contains the imported modules.
1166          foreach ($course2cms as $cm) {
1167              if ($cm->modname === 'page') {
1168                  $this->assertEquals($cm->name, $page->name);
1169              } else if ($cm->modname === 'forum') {
1170                  $this->assertEquals($cm->name, $forum->name);
1171              } else {
1172                  $this->fail('Unknown CM found: '.$cm->name);
1173              }
1174          }
1175      }
1176  
1177      /**
1178       * Ensure import_course handles incorrect deletecontent option correctly.
1179       */
1180      public function test_import_course_invalid_deletecontent_option() {
1181          $this->resetAfterTest(true);
1182  
1183          $course1  = self::getDataGenerator()->create_course();
1184          $course2  = self::getDataGenerator()->create_course();
1185  
1186          $this->setExpectedException('moodle_exception', get_string('invalidextparam', 'webservice', -1));
1187          // Import from course1 to course2, with invalid option
1188          core_course_external::import_course($course1->id, $course2->id, -1);;
1189      }
1190  }


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1