2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Unit tests for the user profile condition.
20 * @package availability_profile
21 * @copyright 2014 The Open University
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 use availability_profile\condition;
30 * Unit tests for the user profile condition.
32 * @package availability_profile
33 * @copyright 2014 The Open University
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 class availability_profile_condition_testcase extends advanced_testcase {
37 /** @var profile_define_text Profile field for testing */
38 protected $profilefield;
40 /** @var array Array of user IDs for whome we already set the profile field */
41 protected $setusers = array();
43 /** @var condition Current condition */
45 /** @var \core_availability\info Current info */
48 public function setUp() {
51 $this->resetAfterTest();
53 // Add a custom profile field type. The API for doing this is indescribably
54 // horrid and tightly intertwined with the form UI, so it's best to add
55 // it directly in database.
56 $DB->insert_record('user_info_field', array(
57 'shortname' => 'frogtype', 'name' => 'Type of frog', 'categoryid' => 1,
58 'datatype' => 'text'));
59 $this->profilefield = $DB->get_record('user_info_field',
60 array('shortname' => 'frogtype'));
62 // Clear static cache.
63 \availability_profile\condition::wipe_static_cache();
65 // Load the mock info class so that it can be used.
66 require_once($CFG->dirroot . '/availability/tests/fixtures/mock_info.php');
70 * Tests constructing and using date condition as part of tree.
72 public function test_in_tree() {
75 $this->setAdminUser();
77 $info = new \core_availability\mock_info();
79 $structure = (object)array('op' => '|', 'show' => true, 'c' => array(
80 (object)array('type' => 'profile',
81 'op' => condition::OP_IS_EQUAL_TO,
82 'cf' => 'frogtype', 'v' => 'tree')));
83 $tree = new \core_availability\tree($structure);
85 // Initial check (user does not have custom field).
86 $result = $tree->check_available(false, $info, true, $USER->id);
87 $this->assertFalse($result->is_available());
90 $this->set_field($USER->id, 'tree');
93 $result = $tree->check_available(false, $info, true, $USER->id);
94 $this->assertTrue($result->is_available());
98 * Tests the constructor including error conditions. Also tests the
99 * string conversion feature (intended for debugging only).
101 public function test_constructor() {
103 $structure = new stdClass();
105 $cond = new condition($structure);
107 } catch (coding_exception $e) {
108 $this->assertContains('Missing or invalid ->op', $e->getMessage());
112 $structure->op = 'isklingonfor';
114 $cond = new condition($structure);
116 } catch (coding_exception $e) {
117 $this->assertContains('Missing or invalid ->op', $e->getMessage());
121 $structure->op = condition::OP_IS_EQUAL_TO;
123 $cond = new condition($structure);
125 } catch (coding_exception $e) {
126 $this->assertContains('Missing or invalid ->v', $e->getMessage());
129 // Invalid value (not string).
130 $structure->v = false;
132 $cond = new condition($structure);
134 } catch (coding_exception $e) {
135 $this->assertContains('Missing or invalid ->v', $e->getMessage());
139 $structure->op = condition::OP_IS_EMPTY;
141 $cond = new condition($structure);
143 } catch (coding_exception $e) {
144 $this->assertContains('Unexpected ->v', $e->getMessage());
148 $structure->op = condition::OP_IS_EQUAL_TO;
149 $structure->v = 'flying';
151 $cond = new condition($structure);
153 } catch (coding_exception $e) {
154 $this->assertContains('Missing ->sf or ->cf', $e->getMessage());
157 // Invalid field (not string).
160 $cond = new condition($structure);
162 } catch (coding_exception $e) {
163 $this->assertContains('Invalid ->sf', $e->getMessage());
167 $structure->sf = 'department';
168 $structure->cf = 'frogtype';
170 $cond = new condition($structure);
172 } catch (coding_exception $e) {
173 $this->assertContains('Both ->sf and ->cf', $e->getMessage());
176 // Invalid ->cf field (not string).
177 unset($structure->sf);
178 $structure->cf = false;
180 $cond = new condition($structure);
182 } catch (coding_exception $e) {
183 $this->assertContains('Invalid ->cf', $e->getMessage());
186 // Valid examples (checks values are correctly included).
187 $structure->cf = 'frogtype';
188 $cond = new condition($structure);
189 $this->assertEquals('{profile:*frogtype isequalto flying}', (string)$cond);
191 unset($structure->v);
192 $structure->op = condition::OP_IS_EMPTY;
193 $cond = new condition($structure);
194 $this->assertEquals('{profile:*frogtype isempty}', (string)$cond);
196 unset($structure->cf);
197 $structure->sf = 'department';
198 $cond = new condition($structure);
199 $this->assertEquals('{profile:department isempty}', (string)$cond);
203 * Tests the save() function.
205 public function test_save() {
206 $structure = (object)array('cf' => 'frogtype', 'op' => condition::OP_IS_EMPTY);
207 $cond = new condition($structure);
208 $structure->type = 'profile';
209 $this->assertEquals($structure, $cond->save());
211 $structure = (object)array('cf' => 'frogtype', 'op' => condition::OP_ENDS_WITH,
213 $cond = new condition($structure);
214 $structure->type = 'profile';
215 $this->assertEquals($structure, $cond->save());
219 * Tests the is_available function. There is no separate test for
220 * get_full_information because that function is called from is_available
221 * and we test its values here.
223 public function test_is_available() {
224 global $USER, $SITE, $DB;
225 $this->setAdminUser();
226 $info = new \core_availability\mock_info();
228 // Prepare to test with all operators against custom field using all
229 // combinations of NOT and true/false states..
231 $structure = (object)array('cf' => 'frogtype');
233 $structure->op = condition::OP_IS_NOT_EMPTY;
234 $cond = new condition($structure);
235 $this->assert_is_available_result(false, '~Type of frog.*is not empty~',
236 $cond, $info, $USER->id);
237 $this->set_field($USER->id, 'poison dart');
238 $this->assert_is_available_result(true, '~Type of frog.*is empty~',
239 $cond, $info, $USER->id);
241 $structure->op = condition::OP_IS_EMPTY;
242 $cond = new condition($structure);
243 $this->assert_is_available_result(false, '~.*Type of frog.*is empty~',
244 $cond, $info, $USER->id);
245 $this->set_field($USER->id, null);
246 $this->assert_is_available_result(true, '~.*Type of frog.*is not empty~',
247 $cond, $info, $USER->id);
248 $this->set_field($USER->id, '');
249 $this->assert_is_available_result(true, '~.*Type of frog.*is not empty~',
250 $cond, $info, $USER->id);
252 $structure->op = condition::OP_CONTAINS;
253 $structure->v = 'llf';
254 $cond = new condition($structure);
255 $this->assert_is_available_result(false, '~Type of frog.*contains.*llf~',
256 $cond, $info, $USER->id);
257 $this->set_field($USER->id, 'bullfrog');
258 $this->assert_is_available_result(true, '~Type of frog.*does not contain.*llf~',
259 $cond, $info, $USER->id);
261 $structure->op = condition::OP_DOES_NOT_CONTAIN;
262 $cond = new condition($structure);
263 $this->assert_is_available_result(false, '~Type of frog.*does not contain.*llf~',
264 $cond, $info, $USER->id);
265 $this->set_field($USER->id, 'goliath');
266 $this->assert_is_available_result(true, '~Type of frog.*contains.*llf~',
267 $cond, $info, $USER->id);
269 $structure->op = condition::OP_IS_EQUAL_TO;
270 $structure->v = 'Kermit';
271 $cond = new condition($structure);
272 $this->assert_is_available_result(false, '~Type of frog.*is <.*Kermit~',
273 $cond, $info, $USER->id);
274 $this->set_field($USER->id, 'Kermit');
275 $this->assert_is_available_result(true, '~Type of frog.*is not.*Kermit~',
276 $cond, $info, $USER->id);
278 $structure->op = condition::OP_STARTS_WITH;
279 $structure->v = 'Kerm';
280 $cond = new condition($structure);
281 $this->assert_is_available_result(true, '~Type of frog.*does not start.*Kerm~',
282 $cond, $info, $USER->id);
283 $this->set_field($USER->id, 'Keroppi');
284 $this->assert_is_available_result(false, '~Type of frog.*starts.*Kerm~',
285 $cond, $info, $USER->id);
287 $structure->op = condition::OP_ENDS_WITH;
288 $structure->v = 'ppi';
289 $cond = new condition($structure);
290 $this->assert_is_available_result(true, '~Type of frog.*does not end.*ppi~',
291 $cond, $info, $USER->id);
292 $this->set_field($USER->id, 'Kermit');
293 $this->assert_is_available_result(false, '~Type of frog.*ends.*ppi~',
294 $cond, $info, $USER->id);
296 // Also test is_available for a different (not current) user.
297 $generator = $this->getDataGenerator();
298 $user = $generator->create_user();
299 $structure->op = condition::OP_CONTAINS;
300 $structure->v = 'rne';
301 $cond = new condition($structure);
302 $this->assertFalse($cond->is_available(false, $info, true, $user->id));
303 $this->set_field($user->id, 'horned');
304 $this->assertTrue($cond->is_available(false, $info, true, $user->id));
306 // Now check with a standard field (department).
307 $structure = (object)array('op' => condition::OP_IS_EQUAL_TO,
308 'sf' => 'department', 'v' => 'Cheese Studies');
309 $cond = new condition($structure);
310 $this->assertFalse($cond->is_available(false, $info, true, $USER->id));
311 $this->assertFalse($cond->is_available(false, $info, true, $user->id));
313 // Check the message (should be using lang string with capital, which
314 // is evidence that it called the right function to get the name).
315 $information = $cond->get_description(false, false, $info);
316 $this->assertRegExp('~Department~', $information);
318 // Set the field to true for both users and retry.
319 $DB->set_field('user', 'department', 'Cheese Studies', array('id' => $user->id));
320 $USER->department = 'Cheese Studies';
321 $this->assertTrue($cond->is_available(false, $info, true, $USER->id));
322 $this->assertTrue($cond->is_available(false, $info, true, $user->id));
326 * Tests what happens with custom fields that are text areas. These should
327 * not be offered in the menu because their data is not included in user
330 public function test_custom_textarea_field() {
331 global $USER, $SITE, $DB;
332 $this->setAdminUser();
333 $info = new \core_availability\mock_info();
335 // Add custom textarea type.
336 $DB->insert_record('user_info_field', array(
337 'shortname' => 'longtext', 'name' => 'Long text', 'categoryid' => 1,
338 'datatype' => 'textarea'));
339 $customfield = $DB->get_record('user_info_field',
340 array('shortname' => 'longtext'));
342 // The list of fields should include the text field added in setUp(),
343 // but should not include the textarea field added just now.
344 $fields = condition::get_custom_profile_fields();
345 $this->assertEquals(array('frogtype'), array_keys($fields));
349 * Sets the custom profile field used for testing.
351 * @param int $userid User id
352 * @param string|null $value Field value or null to clear
353 * @param int $fieldid Field id or 0 to use default one
355 protected function set_field($userid, $value, $fieldid = 0) {
359 $fieldid = $this->profilefield->id;
361 $alreadyset = array_key_exists($userid, $this->setusers);
362 if (is_null($value)) {
363 $DB->delete_records('user_info_data',
364 array('userid' => $userid, 'fieldid' => $fieldid));
365 unset($this->setusers[$userid]);
366 } else if ($alreadyset) {
367 $DB->set_field('user_info_data', 'data', $value,
368 array('userid' => $userid, 'fieldid' => $fieldid));
370 $DB->insert_record('user_info_data', array('userid' => $userid,
371 'fieldid' => $fieldid, 'data' => $value));
372 $this->setusers[$userid] = true;
377 * Checks the result of is_available. This function is to save duplicated
378 * code; it does two checks (the normal is_available with $not set to true
379 * and set to false). Whichever result is expected to be true, it checks
380 * $information ends up as empty string for that one, and as a regex match
383 * @param bool $yes If the positive test is expected to return true
384 * @param string $failpattern Regex pattern to match text when it returns false
385 * @param condition $cond Condition
386 * @param \core_availability\info $info Information about current context
387 * @param int $userid User id
389 protected function assert_is_available_result($yes, $failpattern, condition $cond,
390 \core_availability\info $info, $userid) {
391 // Positive (normal) test.
392 $this->assertEquals($yes, $cond->is_available(false, $info, true, $userid),
393 'Failed checking normal (positive) result');
395 $information = $cond->get_description(false, false, $info);
396 $this->assertRegExp($failpattern, $information);
399 // Negative (NOT) test.
400 $this->assertEquals(!$yes, $cond->is_available(true, $info, true, $userid),
401 'Failed checking NOT (negative) result');
403 $information = $cond->get_description(false, true, $info);
404 $this->assertRegExp($failpattern, $information);
409 * Tests the filter_users (bulk checking) function.
411 public function test_filter_users() {
413 $this->resetAfterTest();
414 $CFG->enableavailability = true;
416 // Erase static cache before test.
417 condition::wipe_static_cache();
419 // Make a test course and some users.
420 $generator = $this->getDataGenerator();
421 $course = $generator->create_course();
422 $student1 = $generator->create_user(array('institution' => 'Unseen University'));
423 $student2 = $generator->create_user(array('institution' => 'Hogwarts'));
424 $student3 = $generator->create_user(array('institution' => 'Unseen University'));
426 foreach (array($student1, $student2, $student3) as $student) {
427 $generator->enrol_user($student->id, $course->id);
428 $allusers[$student->id] = $student;
430 $this->set_field($student1->id, 'poison dart');
431 $this->set_field($student2->id, 'poison dart');
432 $info = new \core_availability\mock_info($course);
433 $checker = new \core_availability\capability_checker($info->get_context());
435 // Test standard field condition (positive and negative).
436 $cond = new condition((object)array('sf' => 'institution', 'op' => 'contains', 'v' => 'Unseen'));
437 $result = array_keys($cond->filter_user_list($allusers, false, $info, $checker));
439 $this->assertEquals(array($student1->id, $student3->id), $result);
440 $result = array_keys($cond->filter_user_list($allusers, true, $info, $checker));
442 $this->assertEquals(array($student2->id), $result);
444 // Test custom field condition.
445 $cond = new condition((object)array('cf' => 'frogtype', 'op' => 'contains', 'v' => 'poison'));
446 $result = array_keys($cond->filter_user_list($allusers, false, $info, $checker));
448 $this->assertEquals(array($student1->id, $student2->id), $result);
449 $result = array_keys($cond->filter_user_list($allusers, true, $info, $checker));
451 $this->assertEquals(array($student3->id), $result);
455 * Tests getting user list SQL. This is a different test from the above because
456 * there is some additional code in this function so more variants need testing.
458 public function test_get_user_list_sql() {
460 $this->resetAfterTest();
461 $CFG->enableavailability = true;
463 // Erase static cache before test.
464 condition::wipe_static_cache();
466 // For testing, make another info field with default value.
467 $DB->insert_record('user_info_field', array(
468 'shortname' => 'tonguestyle', 'name' => 'Tongue style', 'categoryid' => 1,
469 'datatype' => 'text', 'defaultdata' => 'Slimy'));
470 $otherprofilefield = $DB->get_record('user_info_field',
471 array('shortname' => 'tonguestyle'));
473 // Make a test course and some users.
474 $generator = $this->getDataGenerator();
475 $course = $generator->create_course();
476 $student1 = $generator->create_user(array('institution' => 'Unseen University'));
477 $student2 = $generator->create_user(array('institution' => 'Hogwarts'));
478 $student3 = $generator->create_user(array('institution' => 'Unseen University'));
479 $student4 = $generator->create_user(array('institution' => '0'));
481 foreach (array($student1, $student2, $student3, $student4) as $student) {
482 $generator->enrol_user($student->id, $course->id);
483 $allusers[$student->id] = $student;
485 $this->set_field($student1->id, 'poison dart');
486 $this->set_field($student2->id, 'poison dart');
487 $this->set_field($student3->id, 'Rough', $otherprofilefield->id);
488 $this->info = new \core_availability\mock_info($course);
490 // Test standard field condition (positive).
491 $this->cond = new condition((object)array('sf' => 'institution',
492 'op' => condition::OP_CONTAINS, 'v' => 'Univ'));
493 $this->assert_user_list_sql_results(array($student1->id, $student3->id));
495 // Now try it negative.
496 $this->assert_user_list_sql_results(array($student2->id, $student4->id), true);
498 // Try all the other condition types.
499 $this->cond = new condition((object)array('sf' => 'institution',
500 'op' => condition::OP_DOES_NOT_CONTAIN, 'v' => 's'));
501 $this->assert_user_list_sql_results(array($student4->id));
502 $this->cond = new condition((object)array('sf' => 'institution',
503 'op' => condition::OP_IS_EQUAL_TO, 'v' => 'Hogwarts'));
504 $this->assert_user_list_sql_results(array($student2->id));
505 $this->cond = new condition((object)array('sf' => 'institution',
506 'op' => condition::OP_STARTS_WITH, 'v' => 'U'));
507 $this->assert_user_list_sql_results(array($student1->id, $student3->id));
508 $this->cond = new condition((object)array('sf' => 'institution',
509 'op' => condition::OP_ENDS_WITH, 'v' => 'rts'));
510 $this->assert_user_list_sql_results(array($student2->id));
511 $this->cond = new condition((object)array('sf' => 'institution',
512 'op' => condition::OP_IS_EMPTY));
513 $this->assert_user_list_sql_results(array($student4->id));
514 $this->cond = new condition((object)array('sf' => 'institution',
515 'op' => condition::OP_IS_NOT_EMPTY));
516 $this->assert_user_list_sql_results(array($student1->id, $student2->id, $student3->id));
518 // Try with a custom field condition that doesn't have a default.
519 $this->cond = new condition((object)array('cf' => 'frogtype',
520 'op' => condition::OP_CONTAINS, 'v' => 'poison'));
521 $this->assert_user_list_sql_results(array($student1->id, $student2->id));
522 $this->cond = new condition((object)array('cf' => 'frogtype',
523 'op' => condition::OP_IS_EMPTY));
524 $this->assert_user_list_sql_results(array($student3->id, $student4->id));
526 // Try with one that does have a default.
527 $this->cond = new condition((object)array('cf' => 'tonguestyle',
528 'op' => condition::OP_STARTS_WITH, 'v' => 'Sli'));
529 $this->assert_user_list_sql_results(array($student1->id, $student2->id,
531 $this->cond = new condition((object)array('cf' => 'tonguestyle',
532 'op' => condition::OP_IS_EMPTY));
533 $this->assert_user_list_sql_results(array());
537 * Convenience function. Gets the user list SQL and runs it, then checks
540 * @param array $expected Array of expected user ids
541 * @param bool $not True if using NOT condition
543 private function assert_user_list_sql_results(array $expected, $not = false) {
545 list ($sql, $params) = $this->cond->get_user_list_sql($not, $this->info, true);
546 $result = $DB->get_fieldset_sql($sql, $params);
548 $this->assertEquals($expected, $result);