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]

   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 mod_chat functions unit tests
  19   *
  20   * @package    mod_chat
  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  
  33  /**
  34   * External mod_chat functions unit tests
  35   *
  36   * @package    mod_chat
  37   * @category   external
  38   * @copyright  2015 Juan Leyva <juan@moodle.com>
  39   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  40   * @since      Moodle 3.0
  41   */
  42  class mod_chat_external_testcase extends externallib_advanced_testcase {
  43  
  44      /**
  45       * Test login user
  46       */
  47      public function test_login_user() {
  48          global $DB;
  49  
  50          $this->resetAfterTest(true);
  51  
  52          // Setup test data.
  53          $this->setAdminUser();
  54          $course = $this->getDataGenerator()->create_course();
  55          $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id));
  56  
  57          $user = self::getDataGenerator()->create_user();
  58          $this->setUser($user);
  59          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
  60          $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id);
  61  
  62          $result = mod_chat_external::login_user($chat->id);
  63          $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
  64  
  65          // Test session started.
  66          $sid = $DB->get_field('chat_users', 'sid', array('userid' => $user->id, 'chatid' => $chat->id));
  67          $this->assertEquals($result['chatsid'], $sid);
  68  
  69      }
  70  
  71      /**
  72       * Test get chat users
  73       */
  74      public function test_get_chat_users() {
  75          global $DB;
  76  
  77          $this->resetAfterTest(true);
  78  
  79          // Setup test data.
  80          $this->setAdminUser();
  81          $course = $this->getDataGenerator()->create_course();
  82          $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id));
  83  
  84          $user1 = self::getDataGenerator()->create_user();
  85          $user2 = self::getDataGenerator()->create_user();
  86  
  87          $this->setUser($user1);
  88          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
  89          $this->getDataGenerator()->enrol_user($user1->id, $course->id, $studentrole->id);
  90          $this->getDataGenerator()->enrol_user($user2->id, $course->id, $studentrole->id);
  91  
  92          $result = mod_chat_external::login_user($chat->id);
  93          $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
  94  
  95          $this->setUser($user2);
  96          $result = mod_chat_external::login_user($chat->id);
  97          $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
  98  
  99          // Get users.
 100          $result = mod_chat_external::get_chat_users($result['chatsid']);
 101          $result = external_api::clean_returnvalue(mod_chat_external::get_chat_users_returns(), $result);
 102  
 103          // Check correct users.
 104          $this->assertCount(2, $result['users']);
 105          $found = 0;
 106          foreach ($result['users'] as $user) {
 107              if ($user['id'] == $user1->id or $user['id'] == $user2->id) {
 108                  $found++;
 109              }
 110          }
 111          $this->assertEquals(2, $found);
 112  
 113      }
 114  
 115      /**
 116       * Test send and get chat messages
 117       */
 118      public function test_send_get_chat_message() {
 119          global $DB;
 120  
 121          $this->resetAfterTest(true);
 122  
 123          // Setup test data.
 124          $this->setAdminUser();
 125          $course = $this->getDataGenerator()->create_course();
 126          $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id));
 127  
 128          $user = self::getDataGenerator()->create_user();
 129          $this->setUser($user);
 130          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
 131          $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id);
 132  
 133          $result = mod_chat_external::login_user($chat->id);
 134          $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
 135          $chatsid = $result['chatsid'];
 136  
 137          $result = mod_chat_external::send_chat_message($chatsid, 'hello!');
 138          $result = external_api::clean_returnvalue(mod_chat_external::send_chat_message_returns(), $result);
 139  
 140          // Test messages received.
 141  
 142          $result = mod_chat_external::get_chat_latest_messages($chatsid, 0);
 143          $result = external_api::clean_returnvalue(mod_chat_external::get_chat_latest_messages_returns(), $result);
 144  
 145          foreach ($result['messages'] as $message) {
 146              // Ommit system messages, like user just joined in.
 147              if ($message['system']) {
 148                  continue;
 149              }
 150              $this->assertEquals('hello!', $message['message']);
 151          }
 152      }
 153  
 154      /**
 155       * Test view_chat
 156       */
 157      public function test_view_chat() {
 158          global $DB;
 159  
 160          $this->resetAfterTest(true);
 161  
 162          // Setup test data.
 163          $this->setAdminUser();
 164          $course = $this->getDataGenerator()->create_course();
 165          $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id));
 166          $context = context_module::instance($chat->cmid);
 167          $cm = get_coursemodule_from_instance('chat', $chat->id);
 168  
 169          // Test invalid instance id.
 170          try {
 171              mod_chat_external::view_chat(0);
 172              $this->fail('Exception expected due to invalid mod_chat instance id.');
 173          } catch (moodle_exception $e) {
 174              $this->assertEquals('invalidrecord', $e->errorcode);
 175          }
 176  
 177          // Test not-enrolled user.
 178          $user = self::getDataGenerator()->create_user();
 179          $this->setUser($user);
 180          try {
 181              mod_chat_external::view_chat($chat->id);
 182              $this->fail('Exception expected due to not enrolled user.');
 183          } catch (moodle_exception $e) {
 184              $this->assertEquals('requireloginerror', $e->errorcode);
 185          }
 186  
 187          // Test user with full capabilities.
 188          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
 189          $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id);
 190  
 191          // Trigger and capture the event.
 192          $sink = $this->redirectEvents();
 193  
 194          $result = mod_chat_external::view_chat($chat->id);
 195          $result = external_api::clean_returnvalue(mod_chat_external::view_chat_returns(), $result);
 196  
 197          $events = $sink->get_events();
 198          $this->assertCount(1, $events);
 199          $event = array_shift($events);
 200  
 201          // Checking that the event contains the expected values.
 202          $this->assertInstanceOf('\mod_chat\event\course_module_viewed', $event);
 203          $this->assertEquals($context, $event->get_context());
 204          $moodlechat = new \moodle_url('/mod/chat/view.php', array('id' => $cm->id));
 205          $this->assertEquals($moodlechat, $event->get_url());
 206          $this->assertEventContextNotUsed($event);
 207          $this->assertNotEmpty($event->get_name());
 208  
 209          // Test user with no capabilities.
 210          // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
 211          assign_capability('mod/chat:chat', CAP_PROHIBIT, $studentrole->id, $context->id);
 212          accesslib_clear_all_caches_for_unit_testing();
 213  
 214          try {
 215              mod_chat_external::view_chat($chat->id);
 216              $this->fail('Exception expected due to missing capability.');
 217          } catch (moodle_exception $e) {
 218              $this->assertEquals('nopermissions', $e->errorcode);
 219          }
 220      }
 221  
 222      /**
 223       * Test get_chats_by_courses
 224       */
 225      public function test_get_chats_by_courses() {
 226          global $DB, $USER, $CFG;
 227          $this->resetAfterTest(true);
 228          $this->setAdminUser();
 229  
 230          // Set global chat method.
 231          $CFG->chat_method = 'header_js';
 232  
 233          $course1 = self::getDataGenerator()->create_course();
 234          $chatoptions1 = array(
 235                                'course' => $course1->id,
 236                                'name' => 'First Chat'
 237                               );
 238          $chat1 = self::getDataGenerator()->create_module('chat', $chatoptions1);
 239          $course2 = self::getDataGenerator()->create_course();
 240          $chatoptions2 = array(
 241                                'course' => $course2->id,
 242                                'name' => 'Second Chat'
 243                               );
 244          $chat2 = self::getDataGenerator()->create_module('chat', $chatoptions2);
 245          $student1 = $this->getDataGenerator()->create_user();
 246          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
 247  
 248          // Enroll Student1 in Course1.
 249          self::getDataGenerator()->enrol_user($student1->id,  $course1->id, $studentrole->id);
 250          $this->setUser($student1);
 251  
 252          $chats = mod_chat_external::get_chats_by_courses();
 253          // We need to execute the return values cleaning process to simulate the web service server.
 254          $chats = external_api::clean_returnvalue(mod_chat_external::get_chats_by_courses_returns(), $chats);
 255          $this->assertCount(1, $chats['chats']);
 256          $this->assertEquals('First Chat', $chats['chats'][0]['name']);
 257          // We see 12 fields.
 258          $this->assertCount(12, $chats['chats'][0]);
 259  
 260          // As Student you cannot see some chat properties like 'section'.
 261          $this->assertFalse(isset($chats['chats'][0]['section']));
 262  
 263          // Student1 is not enrolled in course2. The webservice will return a warning!
 264          $chats = mod_chat_external::get_chats_by_courses(array($course2->id));
 265          // We need to execute the return values cleaning process to simulate the web service server.
 266          $chats = external_api::clean_returnvalue(mod_chat_external::get_chats_by_courses_returns(), $chats);
 267          $this->assertCount(0, $chats['chats']);
 268          $this->assertEquals(1, $chats['warnings'][0]['warningcode']);
 269  
 270          // Now as admin.
 271          $this->setAdminUser();
 272          // As Admin we can see this chat.
 273          $chats = mod_chat_external::get_chats_by_courses(array($course2->id));
 274          // We need to execute the return values cleaning process to simulate the web service server.
 275          $chats = external_api::clean_returnvalue(mod_chat_external::get_chats_by_courses_returns(), $chats);
 276  
 277          $this->assertCount(1, $chats['chats']);
 278          $this->assertEquals('Second Chat', $chats['chats'][0]['name']);
 279          $this->assertEquals('header_js', $chats['chats'][0]['chatmethod']);
 280          // We see 17 fields.
 281          $this->assertCount(17, $chats['chats'][0]);
 282          // As an Admin you can see some chat properties like 'section'.
 283          $this->assertEquals(0, $chats['chats'][0]['section']);
 284  
 285          // Enrol student in the second course.
 286          self::getDataGenerator()->enrol_user($student1->id,  $course2->id, $studentrole->id);
 287          $this->setUser($student1);
 288          $chats = mod_chat_external::get_chats_by_courses();
 289          $chats = external_api::clean_returnvalue(mod_chat_external::get_chats_by_courses_returns(), $chats);
 290          $this->assertCount(2, $chats['chats']);
 291  
 292      }
 293  
 294      /**
 295       * Test get_sessions_empty_chat
 296       */
 297      public function test_get_sessions_empty_chat() {
 298          global $DB;
 299  
 300          $this->resetAfterTest(true);
 301  
 302          // Setup test data.
 303          $this->setAdminUser();
 304          $course = $this->getDataGenerator()->create_course();
 305          $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id));
 306  
 307          $result = mod_chat_external::get_sessions($chat->id);
 308          $result = external_api::clean_returnvalue(mod_chat_external::get_sessions_returns(), $result);
 309          $this->assertEmpty($result['sessions']);
 310          $this->assertEmpty($result['warnings']);
 311      }
 312  
 313  
 314      /**
 315       * Test get_sessions_no_permissions_for_student
 316       */
 317      public function test_get_sessions_no_permissions_for_student() {
 318          global $DB;
 319  
 320          $this->resetAfterTest(true);
 321  
 322          // Setup test data.
 323          $this->setAdminUser();
 324          $course = $this->getDataGenerator()->create_course();
 325          // Disable logs for students.
 326          $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id, 'studentlogs' => 0));
 327          // The admin has permissions to check logs.
 328          $result = mod_chat_external::get_sessions($chat->id);
 329          $result = external_api::clean_returnvalue(mod_chat_external::get_sessions_returns(), $result);
 330          $this->assertEmpty($result['sessions']);
 331          $this->assertEmpty($result['warnings']);
 332  
 333          $user = self::getDataGenerator()->create_user();
 334          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
 335          unassign_capability('mod/chat:readlog', $studentrole->id);
 336          accesslib_clear_all_caches_for_unit_testing();
 337  
 338          $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id);
 339          $this->setUser($user);
 340          // Students don't have permissions.
 341          $this->expectException('moodle_exception');
 342          mod_chat_external::get_sessions($chat->id);
 343      }
 344  
 345      /**
 346       * Test get_sessions_not_completed_session
 347       */
 348      public function test_get_sessions_not_completed_session() {
 349          global $DB;
 350  
 351          $this->resetAfterTest(true);
 352  
 353          // Setup test data.
 354          $this->setAdminUser();
 355          $course = $this->getDataGenerator()->create_course();
 356          $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id));
 357  
 358          $user = self::getDataGenerator()->create_user();
 359          $this->setUser($user);
 360          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
 361          $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id);
 362  
 363          // Start a chat and send just one message.
 364          $result = mod_chat_external::login_user($chat->id);
 365          $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
 366          $chatsid = $result['chatsid'];
 367          $result = mod_chat_external::send_chat_message($chatsid, 'hello!');
 368          $result = external_api::clean_returnvalue(mod_chat_external::send_chat_message_returns(), $result);
 369  
 370          // Check session is not marked as completed so it is not returned.
 371          $result = mod_chat_external::get_sessions($chat->id);
 372          $result = external_api::clean_returnvalue(mod_chat_external::get_sessions_returns(), $result);
 373          $this->assertEmpty($result['sessions']);
 374          $this->assertEmpty($result['warnings']);
 375  
 376          // Pass showall parameter to indicate that we want not completed sessions.
 377          $result = mod_chat_external::get_sessions($chat->id, 0, true);
 378          $result = external_api::clean_returnvalue(mod_chat_external::get_sessions_returns(), $result);
 379          $this->assertCount(1, $result['sessions']); // One session.
 380          $this->assertFalse($result['sessions'][0]['iscomplete']); // Session not complete.
 381          $this->assertEmpty($result['warnings']);
 382      }
 383  
 384      /**
 385       * Test get_sessions_completed_session
 386       */
 387      public function test_get_sessions_completed_session() {
 388          global $DB;
 389  
 390          $this->resetAfterTest(true);
 391  
 392          // Setup test data.
 393          $this->setAdminUser();
 394          $course = $this->getDataGenerator()->create_course();
 395          $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id));
 396  
 397          $user1 = self::getDataGenerator()->create_user();
 398          $user2 = self::getDataGenerator()->create_user();
 399          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
 400          $this->getDataGenerator()->enrol_user($user1->id, $course->id, $studentrole->id);
 401          $this->getDataGenerator()->enrol_user($user2->id, $course->id, $studentrole->id);
 402  
 403          // Start a chat and completeit.
 404          $this->setUser($user1);
 405          $result = mod_chat_external::login_user($chat->id);
 406          $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
 407          $chatsid = $result['chatsid'];
 408          $result = mod_chat_external::send_chat_message($chatsid, 'hello!');
 409          $result = external_api::clean_returnvalue(mod_chat_external::send_chat_message_returns(), $result);
 410          $this->setUser($user2);
 411          $result = mod_chat_external::login_user($chat->id);
 412          $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
 413          $chatsid = $result['chatsid'];
 414          $result = mod_chat_external::send_chat_message($chatsid, 'hello to you!');
 415          $result = external_api::clean_returnvalue(mod_chat_external::send_chat_message_returns(), $result);
 416          // Need to change first messages and last message times to mark the session completed.
 417          // We receive 4 messages (2 system messages that indicates user joined and the 2 messages sent by the users).
 418          $messages = $DB->get_records('chat_messages', array('chatid' => $chat->id));
 419          // Messages just one hour ago and 70 seconds between them.
 420          $timegap = 0;
 421          $timenow = time();
 422          foreach ($messages as $message) {
 423              $DB->set_field('chat_messages', 'timestamp', $timenow - HOURSECS + $timegap, array('id' => $message->id));
 424              $timegap += 70;
 425          }
 426          // Check session is completed.
 427          $result = mod_chat_external::get_sessions($chat->id);
 428          $result = external_api::clean_returnvalue(mod_chat_external::get_sessions_returns(), $result);
 429          $this->assertCount(1, $result['sessions']); // One session.
 430          $this->assertTrue($result['sessions'][0]['iscomplete']); // Session complete.
 431          // The session started when user1 entered the chat.
 432          $this->assertEquals($timenow - HOURSECS, $result['sessions'][0]['sessionstart']);
 433          $this->assertEmpty($result['warnings']);
 434      }
 435  
 436      /**
 437       * Test get_session_messages
 438       */
 439      public function test_get_session_messages() {
 440          global $DB;
 441  
 442          $this->resetAfterTest(true);
 443  
 444          // Setup test data.
 445          $this->setAdminUser();
 446          $course = $this->getDataGenerator()->create_course();
 447          $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id));
 448  
 449          $user1 = self::getDataGenerator()->create_user();
 450          $user2 = self::getDataGenerator()->create_user();
 451          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
 452          $this->getDataGenerator()->enrol_user($user1->id, $course->id, $studentrole->id);
 453          $this->getDataGenerator()->enrol_user($user2->id, $course->id, $studentrole->id);
 454  
 455          // Start a chat and send a few messages.
 456          $this->setUser($user1);
 457          $result = mod_chat_external::login_user($chat->id);
 458          $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
 459          $chatsid = $result['chatsid'];
 460          mod_chat_external::send_chat_message($chatsid, 'hello!');
 461          mod_chat_external::send_chat_message($chatsid, 'bye bye!');
 462  
 463          $this->setUser($user2);
 464          $result = mod_chat_external::login_user($chat->id);
 465          $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
 466          $chatsid = $result['chatsid'];
 467          mod_chat_external::send_chat_message($chatsid, 'greetings!');
 468  
 469          // Pass showall parameter to indicate that we want not completed sessions.
 470          $result = mod_chat_external::get_sessions($chat->id, 0, true);
 471          $result = external_api::clean_returnvalue(mod_chat_external::get_sessions_returns(), $result);
 472          $this->assertCount(1, $result['sessions']); // One session.
 473  
 474          $sessionstart = $result['sessions'][0]['sessionstart'];
 475          $sessionend = $result['sessions'][0]['sessionend'];
 476          $result = mod_chat_external::get_session_messages($chat->id, $sessionstart, $sessionend);
 477          $result = external_api::clean_returnvalue(mod_chat_external::get_session_messages_returns(), $result);
 478          $this->assertCount(5, $result['messages']); // 2 system + 3 personal messages.
 479          $found = 0;
 480          foreach ($result['messages'] as $message) {
 481              if (!$message['issystem']) {
 482                  if ($message['userid'] == $user1->id) {
 483                      if ($message['message'] != 'hello!') {
 484                          $this->assertEquals('bye bye!', $message['message']);
 485                          $found++;
 486                      }
 487                  } else {
 488                      $this->assertEquals($user2->id, $message['userid']);
 489                      $this->assertEquals('greetings!', $message['message']);
 490                      $found++;
 491                  }
 492              }
 493          }
 494          $this->assertEquals(2, $found);
 495      }
 496  }