Proyectos de Subversion Moodle

Rev

Rev 11 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
namespace availability_profile;
18
 
19
/**
20
 * Unit tests for the user profile condition.
21
 *
22
 * @package availability_profile
23
 * @copyright 2014 The Open University
24
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25
 */
1441 ariadna 26
final class condition_test extends \advanced_testcase {
1 efrain 27
    /** @var profile_define_text Profile field for testing */
28
    protected $profilefield;
29
 
30
    /** @var array Array of user IDs for whome we already set the profile field */
31
    protected $setusers = array();
32
 
33
    /** @var condition Current condition */
34
    private $cond;
35
    /** @var \core_availability\info Current info */
36
    private $info;
37
 
38
    public function setUp(): void {
39
        global $DB, $CFG;
1441 ariadna 40
        parent::setUp();
1 efrain 41
 
42
        $this->resetAfterTest();
43
 
44
        // Add a custom profile field type.
45
        $this->profilefield = $this->getDataGenerator()->create_custom_profile_field(array(
46
                'shortname' => 'frogtype', 'name' => 'Type of frog',
47
                'datatype' => 'text'));
48
 
49
        // Clear static cache.
50
        \availability_profile\condition::wipe_static_cache();
51
 
52
        // Load the mock info class so that it can be used.
53
        require_once($CFG->dirroot . '/availability/tests/fixtures/mock_info.php');
54
    }
55
 
56
    /**
57
     * Tests constructing and using date condition as part of tree.
58
     */
11 efrain 59
    public function test_in_tree(): void {
1 efrain 60
        global $USER;
61
 
62
        $this->setAdminUser();
63
 
64
        $info = new \core_availability\mock_info();
65
 
66
        $structure = (object)array('op' => '|', 'show' => true, 'c' => array(
67
                (object)array('type' => 'profile',
68
                        'op' => condition::OP_IS_EQUAL_TO,
69
                        'cf' => 'frogtype', 'v' => 'tree')));
70
        $tree = new \core_availability\tree($structure);
71
 
72
        // Initial check (user does not have custom field).
73
        $result = $tree->check_available(false, $info, true, $USER->id);
74
        $this->assertFalse($result->is_available());
75
 
76
        // Set field.
77
        $this->set_field($USER->id, 'tree');
78
 
79
        // Now it's true!
80
        $result = $tree->check_available(false, $info, true, $USER->id);
81
        $this->assertTrue($result->is_available());
82
    }
83
 
84
    /**
85
     * Tests the constructor including error conditions. Also tests the
86
     * string conversion feature (intended for debugging only).
87
     */
11 efrain 88
    public function test_constructor(): void {
1 efrain 89
        // No parameters.
90
        $structure = new \stdClass();
91
        try {
92
            $cond = new condition($structure);
93
            $this->fail();
94
        } catch (\coding_exception $e) {
95
            $this->assertStringContainsString('Missing or invalid ->op', $e->getMessage());
96
        }
97
 
98
        // Invalid op.
99
        $structure->op = 'isklingonfor';
100
        try {
101
            $cond = new condition($structure);
102
            $this->fail();
103
        } catch (\coding_exception $e) {
104
            $this->assertStringContainsString('Missing or invalid ->op', $e->getMessage());
105
        }
106
 
107
        // Missing value.
108
        $structure->op = condition::OP_IS_EQUAL_TO;
109
        try {
110
            $cond = new condition($structure);
111
            $this->fail();
112
        } catch (\coding_exception $e) {
113
            $this->assertStringContainsString('Missing or invalid ->v', $e->getMessage());
114
        }
115
 
116
        // Invalid value (not string).
117
        $structure->v = false;
118
        try {
119
            $cond = new condition($structure);
120
            $this->fail();
121
        } catch (\coding_exception $e) {
122
            $this->assertStringContainsString('Missing or invalid ->v', $e->getMessage());
123
        }
124
 
125
        // Unexpected value.
126
        $structure->op = condition::OP_IS_EMPTY;
127
        try {
128
            $cond = new condition($structure);
129
            $this->fail();
130
        } catch (\coding_exception $e) {
131
            $this->assertStringContainsString('Unexpected ->v', $e->getMessage());
132
        }
133
 
134
        // Missing field.
135
        $structure->op = condition::OP_IS_EQUAL_TO;
136
        $structure->v = 'flying';
137
        try {
138
            $cond = new condition($structure);
139
            $this->fail();
140
        } catch (\coding_exception $e) {
141
            $this->assertStringContainsString('Missing ->sf or ->cf', $e->getMessage());
142
        }
143
 
144
        // Invalid field (not string).
145
        $structure->sf = 42;
146
        try {
147
            $cond = new condition($structure);
148
            $this->fail();
149
        } catch (\coding_exception $e) {
150
            $this->assertStringContainsString('Invalid ->sf', $e->getMessage());
151
        }
152
 
153
        // Both fields.
154
        $structure->sf = 'department';
155
        $structure->cf = 'frogtype';
156
        try {
157
            $cond = new condition($structure);
158
            $this->fail();
159
        } catch (\coding_exception $e) {
160
            $this->assertStringContainsString('Both ->sf and ->cf', $e->getMessage());
161
        }
162
 
163
        // Invalid ->cf field (not string).
164
        unset($structure->sf);
165
        $structure->cf = false;
166
        try {
167
            $cond = new condition($structure);
168
            $this->fail();
169
        } catch (\coding_exception $e) {
170
            $this->assertStringContainsString('Invalid ->cf', $e->getMessage());
171
        }
172
 
173
        // Valid examples (checks values are correctly included).
174
        $structure->cf = 'frogtype';
175
        $cond = new condition($structure);
176
        $this->assertEquals('{profile:*frogtype isequalto flying}', (string)$cond);
177
 
178
        unset($structure->v);
179
        $structure->op = condition::OP_IS_EMPTY;
180
        $cond = new condition($structure);
181
        $this->assertEquals('{profile:*frogtype isempty}', (string)$cond);
182
 
183
        unset($structure->cf);
184
        $structure->sf = 'department';
185
        $cond = new condition($structure);
186
        $this->assertEquals('{profile:department isempty}', (string)$cond);
187
    }
188
 
189
    /**
190
     * Tests the save() function.
191
     */
11 efrain 192
    public function test_save(): void {
1 efrain 193
        $structure = (object)array('cf' => 'frogtype', 'op' => condition::OP_IS_EMPTY);
194
        $cond = new condition($structure);
195
        $structure->type = 'profile';
196
        $this->assertEquals($structure, $cond->save());
197
 
198
        $structure = (object)array('cf' => 'frogtype', 'op' => condition::OP_ENDS_WITH,
199
                'v' => 'bouncy');
200
        $cond = new condition($structure);
201
        $structure->type = 'profile';
202
        $this->assertEquals($structure, $cond->save());
203
    }
204
 
205
    /**
206
     * Tests the is_available function. There is no separate test for
207
     * get_full_information because that function is called from is_available
208
     * and we test its values here.
209
     */
11 efrain 210
    public function test_is_available(): void {
1 efrain 211
        global $USER, $SITE, $DB;
212
        $this->setAdminUser();
213
        $info = new \core_availability\mock_info();
214
 
215
        // Prepare to test with all operators against custom field using all
216
        // combinations of NOT and true/false states..
217
        $information = 'x';
218
        $structure = (object)array('cf' => 'frogtype');
219
 
220
        $structure->op = condition::OP_IS_NOT_EMPTY;
221
        $cond = new condition($structure);
222
        $this->assert_is_available_result(false, '~Type of frog.*is not empty~',
223
                $cond, $info, $USER->id);
224
        $this->set_field($USER->id, 'poison dart');
225
        $this->assert_is_available_result(true, '~Type of frog.*is empty~',
226
                $cond, $info, $USER->id);
227
 
228
        $structure->op = condition::OP_IS_EMPTY;
229
        $cond = new condition($structure);
230
        $this->assert_is_available_result(false, '~.*Type of frog.*is empty~',
231
                $cond, $info, $USER->id);
232
        $this->set_field($USER->id, null);
233
        $this->assert_is_available_result(true, '~.*Type of frog.*is not empty~',
234
                $cond, $info, $USER->id);
235
        $this->set_field($USER->id, '');
236
        $this->assert_is_available_result(true, '~.*Type of frog.*is not empty~',
237
                $cond, $info, $USER->id);
238
 
239
        $structure->op = condition::OP_CONTAINS;
240
        $structure->v = 'llf';
241
        $cond = new condition($structure);
242
        $this->assert_is_available_result(false, '~Type of frog.*contains.*llf~',
243
                $cond, $info, $USER->id);
244
        $this->set_field($USER->id, 'bullfrog');
245
        $this->assert_is_available_result(true, '~Type of frog.*does not contain.*llf~',
246
                $cond, $info, $USER->id);
247
 
248
        $structure->op = condition::OP_DOES_NOT_CONTAIN;
249
        $cond = new condition($structure);
250
        $this->assert_is_available_result(false, '~Type of frog.*does not contain.*llf~',
251
                $cond, $info, $USER->id);
252
        $this->set_field($USER->id, 'goliath');
253
        $this->assert_is_available_result(true, '~Type of frog.*contains.*llf~',
254
                $cond, $info, $USER->id);
255
 
256
        $structure->op = condition::OP_IS_EQUAL_TO;
257
        $structure->v = 'Kermit';
258
        $cond = new condition($structure);
259
        $this->assert_is_available_result(false, '~Type of frog.*is <.*Kermit~',
260
                $cond, $info, $USER->id);
261
        $this->set_field($USER->id, 'Kermit');
262
        $this->assert_is_available_result(true, '~Type of frog.*is not.*Kermit~',
263
                $cond, $info, $USER->id);
264
 
265
        $structure->op = condition::OP_STARTS_WITH;
266
        $structure->v = 'Kerm';
267
        $cond = new condition($structure);
268
        $this->assert_is_available_result(true, '~Type of frog.*does not start.*Kerm~',
269
                $cond, $info, $USER->id);
270
        $this->set_field($USER->id, 'Keroppi');
271
        $this->assert_is_available_result(false, '~Type of frog.*starts.*Kerm~',
272
                $cond, $info, $USER->id);
273
 
274
        $structure->op = condition::OP_ENDS_WITH;
275
        $structure->v = 'ppi';
276
        $cond = new condition($structure);
277
        $this->assert_is_available_result(true, '~Type of frog.*does not end.*ppi~',
278
                $cond, $info, $USER->id);
279
        $this->set_field($USER->id, 'Kermit');
280
        $this->assert_is_available_result(false, '~Type of frog.*ends.*ppi~',
281
                $cond, $info, $USER->id);
282
 
283
        // Also test is_available for a different (not current) user.
284
        $generator = $this->getDataGenerator();
285
        $user = $generator->create_user();
286
        $structure->op = condition::OP_CONTAINS;
287
        $structure->v = 'rne';
288
        $cond = new condition($structure);
289
        $this->assertFalse($cond->is_available(false, $info, true, $user->id));
290
        $this->set_field($user->id, 'horned');
291
        $this->assertTrue($cond->is_available(false, $info, true, $user->id));
292
 
293
        // Now check with a standard field (department).
294
        $structure = (object)array('op' => condition::OP_IS_EQUAL_TO,
295
                'sf' => 'department', 'v' => 'Cheese Studies');
296
        $cond = new condition($structure);
297
        $this->assertFalse($cond->is_available(false, $info, true, $USER->id));
298
        $this->assertFalse($cond->is_available(false, $info, true, $user->id));
299
 
300
        // Check the message (should be using lang string with capital, which
301
        // is evidence that it called the right function to get the name).
302
        $information = $cond->get_description(false, false, $info);
303
        $information = \core_availability\info::format_info($information, $info->get_course());
304
        $this->assertMatchesRegularExpression('~Department~', $information);
305
 
306
        // Set the field to true for both users and retry.
307
        $DB->set_field('user', 'department', 'Cheese Studies', array('id' => $user->id));
308
        $USER->department = 'Cheese Studies';
309
        $this->assertTrue($cond->is_available(false, $info, true, $USER->id));
310
        $this->assertTrue($cond->is_available(false, $info, true, $user->id));
311
    }
312
 
313
    /**
314
     * Tests what happens with custom fields that are text areas. These should
315
     * not be offered in the menu because their data is not included in user
316
     * object
317
     */
11 efrain 318
    public function test_custom_textarea_field(): void {
1 efrain 319
        global $USER, $SITE, $DB;
320
        $this->setAdminUser();
321
        $info = new \core_availability\mock_info();
322
 
323
        // Add custom textarea type.
324
        $customfield = $this->getDataGenerator()->create_custom_profile_field(array(
325
                'shortname' => 'longtext', 'name' => 'Long text',
326
                'datatype' => 'textarea'));
327
 
328
        // The list of fields should include the text field added in setUp(),
329
        // but should not include the textarea field added just now.
330
        $fields = condition::get_custom_profile_fields();
331
        $this->assertArrayHasKey('frogtype', $fields);
332
        $this->assertArrayNotHasKey('longtext', $fields);
333
    }
334
 
335
    /**
336
     * Sets the custom profile field used for testing.
337
     *
338
     * @param int $userid User id
339
     * @param string|null $value Field value or null to clear
340
     * @param int $fieldid Field id or 0 to use default one
341
     */
342
    protected function set_field($userid, $value, $fieldid = 0) {
343
        global $DB, $USER;
344
 
345
        if (!$fieldid) {
346
            $fieldid = $this->profilefield->id;
347
        }
348
        $alreadyset = array_key_exists($userid, $this->setusers);
349
        if (is_null($value)) {
350
            $DB->delete_records('user_info_data',
351
                    array('userid' => $userid, 'fieldid' => $fieldid));
352
            unset($this->setusers[$userid]);
353
        } else if ($alreadyset) {
354
            $DB->set_field('user_info_data', 'data', $value,
355
                    array('userid' => $userid, 'fieldid' => $fieldid));
356
        } else {
357
            $DB->insert_record('user_info_data', array('userid' => $userid,
358
                    'fieldid' => $fieldid, 'data' => $value));
359
            $this->setusers[$userid] = true;
360
        }
361
    }
362
 
363
    /**
364
     * Checks the result of is_available. This function is to save duplicated
365
     * code; it does two checks (the normal is_available with $not set to true
366
     * and set to false). Whichever result is expected to be true, it checks
367
     * $information ends up as empty string for that one, and as a regex match
368
     * for another one.
369
     *
370
     * @param bool $yes If the positive test is expected to return true
371
     * @param string $failpattern Regex pattern to match text when it returns false
372
     * @param condition $cond Condition
373
     * @param \core_availability\info $info Information about current context
374
     * @param int $userid User id
375
     */
376
    protected function assert_is_available_result($yes, $failpattern, condition $cond,
377
            \core_availability\info $info, $userid) {
378
        // Positive (normal) test.
379
        $this->assertEquals($yes, $cond->is_available(false, $info, true, $userid),
380
                'Failed checking normal (positive) result');
381
        if (!$yes) {
382
            $information = $cond->get_description(false, false, $info);
383
            $information = \core_availability\info::format_info($information, $info->get_course());
384
            $this->assertMatchesRegularExpression($failpattern, $information);
385
        }
386
 
387
        // Negative (NOT) test.
388
        $this->assertEquals(!$yes, $cond->is_available(true, $info, true, $userid),
389
                'Failed checking NOT (negative) result');
390
        if ($yes) {
391
            $information = $cond->get_description(false, true, $info);
392
            $information = \core_availability\info::format_info($information, $info->get_course());
393
            $this->assertMatchesRegularExpression($failpattern, $information);
394
        }
395
    }
396
 
397
    /**
398
     * Tests the filter_users (bulk checking) function.
399
     */
11 efrain 400
    public function test_filter_users(): void {
1 efrain 401
        global $DB, $CFG;
402
        $this->resetAfterTest();
403
        $CFG->enableavailability = true;
404
 
405
        // Erase static cache before test.
406
        condition::wipe_static_cache();
407
 
408
        // Make a test course and some users.
409
        $generator = $this->getDataGenerator();
410
        $course = $generator->create_course();
411
        $student1 = $generator->create_user(array('institution' => 'Unseen University'));
412
        $student2 = $generator->create_user(array('institution' => 'Hogwarts'));
413
        $student3 = $generator->create_user(array('institution' => 'Unseen University'));
414
        $allusers = array();
415
        foreach (array($student1, $student2, $student3) as $student) {
416
            $generator->enrol_user($student->id, $course->id);
417
            $allusers[$student->id] = $student;
418
        }
419
        $this->set_field($student1->id, 'poison dart');
420
        $this->set_field($student2->id, 'poison dart');
421
        $info = new \core_availability\mock_info($course);
422
        $checker = new \core_availability\capability_checker($info->get_context());
423
 
424
        // Test standard field condition (positive and negative).
425
        $cond = new condition((object)array('sf' => 'institution', 'op' => 'contains', 'v' => 'Unseen'));
426
        $result = array_keys($cond->filter_user_list($allusers, false, $info, $checker));
427
        ksort($result);
428
        $this->assertEquals(array($student1->id, $student3->id), $result);
429
        $result = array_keys($cond->filter_user_list($allusers, true, $info, $checker));
430
        ksort($result);
431
        $this->assertEquals(array($student2->id), $result);
432
 
433
        // Test custom field condition.
434
        $cond = new condition((object)array('cf' => 'frogtype', 'op' => 'contains', 'v' => 'poison'));
435
        $result = array_keys($cond->filter_user_list($allusers, false, $info, $checker));
436
        ksort($result);
437
        $this->assertEquals(array($student1->id, $student2->id), $result);
438
        $result = array_keys($cond->filter_user_list($allusers, true, $info, $checker));
439
        ksort($result);
440
        $this->assertEquals(array($student3->id), $result);
441
    }
442
 
443
    /**
444
     * Tests getting user list SQL. This is a different test from the above because
445
     * there is some additional code in this function so more variants need testing.
446
     */
11 efrain 447
    public function test_get_user_list_sql(): void {
1 efrain 448
        global $DB, $CFG;
449
        $this->resetAfterTest();
450
        $CFG->enableavailability = true;
451
 
452
        // Erase static cache before test.
453
        condition::wipe_static_cache();
454
 
455
        // For testing, make another info field with default value.
456
        $otherprofilefield = $this->getDataGenerator()->create_custom_profile_field(array(
457
                'shortname' => 'tonguestyle', 'name' => 'Tongue style',
458
                'datatype' => 'text', 'defaultdata' => 'Slimy'));
459
 
460
        // Make a test course and some users.
461
        $generator = $this->getDataGenerator();
462
        $course = $generator->create_course();
463
        $student1 = $generator->create_user(array('institution' => 'Unseen University'));
464
        $student2 = $generator->create_user(array('institution' => 'Hogwarts'));
465
        $student3 = $generator->create_user(array('institution' => 'Unseen University'));
466
        $student4 = $generator->create_user(array('institution' => '0'));
467
        $allusers = array();
468
        foreach (array($student1, $student2, $student3, $student4) as $student) {
469
            $generator->enrol_user($student->id, $course->id);
470
            $allusers[$student->id] = $student;
471
        }
472
        $this->set_field($student1->id, 'poison dart');
473
        $this->set_field($student2->id, 'poison dart');
474
        $this->set_field($student3->id, 'Rough', $otherprofilefield->id);
475
        $this->info = new \core_availability\mock_info($course);
476
 
477
        // Test standard field condition (positive).
478
        $this->cond = new condition((object)array('sf' => 'institution',
479
                'op' => condition::OP_CONTAINS, 'v' => 'Univ'));
480
        $this->assert_user_list_sql_results(array($student1->id, $student3->id));
481
 
482
        // Now try it negative.
483
        $this->assert_user_list_sql_results(array($student2->id, $student4->id), true);
484
 
485
        // Try all the other condition types.
486
        $this->cond = new condition((object)array('sf' => 'institution',
487
                'op' => condition::OP_DOES_NOT_CONTAIN, 'v' => 's'));
488
        $this->assert_user_list_sql_results(array($student4->id));
489
        $this->cond = new condition((object)array('sf' => 'institution',
490
                'op' => condition::OP_IS_EQUAL_TO, 'v' => 'Hogwarts'));
491
        $this->assert_user_list_sql_results(array($student2->id));
492
        $this->cond = new condition((object)array('sf' => 'institution',
493
                'op' => condition::OP_STARTS_WITH, 'v' => 'U'));
494
        $this->assert_user_list_sql_results(array($student1->id, $student3->id));
495
        $this->cond = new condition((object)array('sf' => 'institution',
496
                'op' => condition::OP_ENDS_WITH, 'v' => 'rts'));
497
        $this->assert_user_list_sql_results(array($student2->id));
498
        $this->cond = new condition((object)array('sf' => 'institution',
499
                'op' => condition::OP_IS_EMPTY));
500
        $this->assert_user_list_sql_results(array($student4->id));
501
        $this->cond = new condition((object)array('sf' => 'institution',
502
                'op' => condition::OP_IS_NOT_EMPTY));
503
        $this->assert_user_list_sql_results(array($student1->id, $student2->id, $student3->id));
504
 
505
        // Try with a custom field condition that doesn't have a default.
506
        $this->cond = new condition((object)array('cf' => 'frogtype',
507
                'op' => condition::OP_CONTAINS, 'v' => 'poison'));
508
        $this->assert_user_list_sql_results(array($student1->id, $student2->id));
509
        $this->cond = new condition((object)array('cf' => 'frogtype',
510
                'op' => condition::OP_IS_EMPTY));
511
        $this->assert_user_list_sql_results(array($student3->id, $student4->id));
512
 
513
        // Try with one that does have a default.
514
        $this->cond = new condition((object)array('cf' => 'tonguestyle',
515
                'op' => condition::OP_STARTS_WITH, 'v' => 'Sli'));
516
        $this->assert_user_list_sql_results(array($student1->id, $student2->id,
517
                $student4->id));
518
        $this->cond = new condition((object)array('cf' => 'tonguestyle',
519
                'op' => condition::OP_IS_EMPTY));
520
        $this->assert_user_list_sql_results(array());
521
    }
522
 
523
    /**
524
     * Convenience function. Gets the user list SQL and runs it, then checks
525
     * results.
526
     *
527
     * @param array $expected Array of expected user ids
528
     * @param bool $not True if using NOT condition
529
     */
530
    private function assert_user_list_sql_results(array $expected, $not = false) {
531
        global $DB;
532
        list ($sql, $params) = $this->cond->get_user_list_sql($not, $this->info, true);
533
        $result = $DB->get_fieldset_sql($sql, $params);
534
        sort($result);
535
        $this->assertEquals($expected, $result);
536
    }
537
}