MDL-51266 unittest: replaced low level phpunit_util calls
[moodle.git] / lib / phpunit / tests / advanced_test.php
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/>.
17 /**
18  * PHPUnit integration tests
19  *
20  * @package    core
21  * @category   phpunit
22  * @copyright  2012 Petr Skoda {@link http://skodak.org}
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
29 /**
30  * Test advanced_testcase extra features.
31  *
32  * @package    core
33  * @category   phpunit
34  * @copyright  2012 Petr Skoda {@link http://skodak.org}
35  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36  */
37 class core_phpunit_advanced_testcase extends advanced_testcase {
39     public function test_debugging() {
40         global $CFG;
41         $this->resetAfterTest();
43         debugging('hokus');
44         $this->assertDebuggingCalled();
45         debugging('pokus');
46         $this->assertDebuggingCalled('pokus');
47         debugging('pokus', DEBUG_MINIMAL);
48         $this->assertDebuggingCalled('pokus', DEBUG_MINIMAL);
49         $this->assertDebuggingNotCalled();
51         debugging('a');
52         debugging('b', DEBUG_MINIMAL);
53         debugging('c', DEBUG_DEVELOPER);
54         $debuggings = $this->getDebuggingMessages();
55         $this->assertCount(3, $debuggings);
56         $this->assertSame('a', $debuggings[0]->message);
57         $this->assertSame(DEBUG_NORMAL, $debuggings[0]->level);
58         $this->assertSame('b', $debuggings[1]->message);
59         $this->assertSame(DEBUG_MINIMAL, $debuggings[1]->level);
60         $this->assertSame('c', $debuggings[2]->message);
61         $this->assertSame(DEBUG_DEVELOPER, $debuggings[2]->level);
63         $this->resetDebugging();
64         $this->assertDebuggingNotCalled();
65         $debuggings = $this->getDebuggingMessages();
66         $this->assertCount(0, $debuggings);
68         set_debugging(DEBUG_NONE);
69         debugging('hokus');
70         $this->assertDebuggingNotCalled();
71         set_debugging(DEBUG_DEVELOPER);
72     }
74     public function test_set_user() {
75         global $USER, $DB;
77         $this->assertEquals(0, $USER->id);
78         $this->assertSame($_SESSION['USER'], $USER);
79         $this->assertSame($GLOBALS['USER'], $USER);
81         $user = $DB->get_record('user', array('id'=>2));
82         $this->assertNotEmpty($user);
83         $this->setUser($user);
84         $this->assertEquals(2, $USER->id);
85         $this->assertEquals(2, $_SESSION['USER']->id);
86         $this->assertSame($_SESSION['USER'], $USER);
87         $this->assertSame($GLOBALS['USER'], $USER);
89         $USER->id = 3;
90         $this->assertEquals(3, $USER->id);
91         $this->assertEquals(3, $_SESSION['USER']->id);
92         $this->assertSame($_SESSION['USER'], $USER);
93         $this->assertSame($GLOBALS['USER'], $USER);
95         \core\session\manager::set_user($user);
96         $this->assertEquals(2, $USER->id);
97         $this->assertEquals(2, $_SESSION['USER']->id);
98         $this->assertSame($_SESSION['USER'], $USER);
99         $this->assertSame($GLOBALS['USER'], $USER);
101         $USER = $DB->get_record('user', array('id'=>1));
102         $this->assertNotEmpty($USER);
103         $this->assertEquals(1, $USER->id);
104         $this->assertEquals(1, $_SESSION['USER']->id);
105         $this->assertSame($_SESSION['USER'], $USER);
106         $this->assertSame($GLOBALS['USER'], $USER);
108         $this->setUser(null);
109         $this->assertEquals(0, $USER->id);
110         $this->assertSame($_SESSION['USER'], $USER);
111         $this->assertSame($GLOBALS['USER'], $USER);
112     }
114     public function test_set_admin_user() {
115         global $USER;
117         $this->resetAfterTest();
119         $this->setAdminUser();
120         $this->assertEquals($USER->id, 2);
121         $this->assertTrue(is_siteadmin());
122     }
124     public function test_set_guest_user() {
125         global $USER;
127         $this->resetAfterTest();
129         $this->setGuestUser();
130         $this->assertEquals($USER->id, 1);
131         $this->assertTrue(isguestuser());
132     }
134     public function test_database_reset() {
135         global $DB;
137         $this->resetAfterTest();
139         $this->preventResetByRollback();
141         $this->assertEquals(1, $DB->count_records('course')); // Only frontpage in new site.
143         // This is weird table - id is NOT a sequence here.
144         $this->assertEquals(0, $DB->count_records('context_temp'));
145         $DB->import_record('context_temp', array('id'=>5, 'path'=>'/1/2', 'depth'=>2));
146         $record = $DB->get_record('context_temp', array());
147         $this->assertEquals(5, $record->id);
149         $this->assertEquals(0, $DB->count_records('user_preferences'));
150         $originaldisplayid = $DB->insert_record('user_preferences', array('userid'=>2, 'name'=> 'phpunittest', 'value'=>'x'));
151         $this->assertEquals(1, $DB->count_records('user_preferences'));
153         $numcourses = $DB->count_records('course');
154         $course = $this->getDataGenerator()->create_course();
155         $this->assertEquals($numcourses + 1, $DB->count_records('course'));
157         $this->assertEquals(2, $DB->count_records('user'));
158         $DB->delete_records('user', array('id'=>1));
159         $this->assertEquals(1, $DB->count_records('user'));
161         $this->resetAllData();
163         $this->assertEquals(1, $DB->count_records('course')); // Only frontpage in new site.
164         $this->assertEquals(0, $DB->count_records('context_temp')); // Only frontpage in new site.
166         $numcourses = $DB->count_records('course');
167         $course = $this->getDataGenerator()->create_course();
168         $this->assertEquals($numcourses + 1, $DB->count_records('course'));
170         $displayid = $DB->insert_record('user_preferences', array('userid'=>2, 'name'=> 'phpunittest', 'value'=>'x'));
171         $this->assertEquals($originaldisplayid, $displayid);
173         $this->assertEquals(2, $DB->count_records('user'));
174         $DB->delete_records('user', array('id'=>2));
175         $user = $this->getDataGenerator()->create_user();
176         $this->assertEquals(2, $DB->count_records('user'));
177         $this->assertGreaterThan(2, $user->id);
179         $this->resetAllData();
181         $numcourses = $DB->count_records('course');
182         $course = $this->getDataGenerator()->create_course();
183         $this->assertEquals($numcourses + 1, $DB->count_records('course'));
185         $this->assertEquals(2, $DB->count_records('user'));
186         $DB->delete_records('user', array('id'=>2));
188         $this->resetAllData();
190         $numcourses = $DB->count_records('course');
191         $course = $this->getDataGenerator()->create_course();
192         $this->assertEquals($numcourses + 1, $DB->count_records('course'));
194         $this->assertEquals(2, $DB->count_records('user'));
195     }
197     public function test_change_detection() {
198         global $DB, $CFG, $COURSE, $SITE, $USER;
200         $this->preventResetByRollback();
201         self::resetAllData(true);
203         // Database change.
204         $this->assertEquals(1, $DB->get_field('user', 'confirmed', array('id'=>2)));
205         $DB->set_field('user', 'confirmed', 0, array('id'=>2));
206         try {
207             self::resetAllData(true);
208         } catch (Exception $e) {
209             $this->assertInstanceOf('PHPUnit_Framework_Error_Warning', $e);
210         }
211         $this->assertEquals(1, $DB->get_field('user', 'confirmed', array('id'=>2)));
213         // Config change.
214         $CFG->xx = 'yy';
215         unset($CFG->admin);
216         $CFG->rolesactive = 0;
217         try {
218             self::resetAllData(true);
219         } catch (Exception $e) {
220             $this->assertInstanceOf('PHPUnit_Framework_Error_Warning', $e);
221             $this->assertContains('xx', $e->getMessage());
222             $this->assertContains('admin', $e->getMessage());
223             $this->assertContains('rolesactive', $e->getMessage());
224         }
225         $this->assertFalse(isset($CFG->xx));
226         $this->assertTrue(isset($CFG->admin));
227         $this->assertEquals(1, $CFG->rolesactive);
229         // _GET change.
230         $_GET['__somethingthatwillnotnormallybepresent__'] = 'yy';
231         self::resetAllData(true);
233         $this->assertEquals(array(), $_GET);
235         // _POST change.
236         $_POST['__somethingthatwillnotnormallybepresent2__'] = 'yy';
237         self::resetAllData(true);
238         $this->assertEquals(array(), $_POST);
240         // _FILES change.
241         $_FILES['__somethingthatwillnotnormallybepresent3__'] = 'yy';
242         self::resetAllData(true);
243         $this->assertEquals(array(), $_FILES);
245         // _REQUEST change.
246         $_REQUEST['__somethingthatwillnotnormallybepresent4__'] = 'yy';
247         self::resetAllData(true);
248         $this->assertEquals(array(), $_REQUEST);
250         // Silent changes.
251         $_SERVER['xx'] = 'yy';
252         self::resetAllData(true);
253         $this->assertFalse(isset($_SERVER['xx']));
255         // COURSE change.
256         $SITE->id = 10;
257         $COURSE = new stdClass();
258         $COURSE->id = 7;
259         try {
260             self::resetAllData(true);
261         } catch (Exception $e) {
262             $this->assertInstanceOf('PHPUnit_Framework_Error_Warning', $e);
263             $this->assertEquals(1, $SITE->id);
264             $this->assertSame($SITE, $COURSE);
265             $this->assertSame($SITE, $COURSE);
266         }
268         // USER change.
269         $this->setUser(2);
270         try {
271             self::resetAllData(true);
272         } catch (Exception $e) {
273             $this->assertInstanceOf('PHPUnit_Framework_Error_Warning', $e);
274             $this->assertEquals(0, $USER->id);
275         }
276     }
278     public function test_getDataGenerator() {
279         $generator = $this->getDataGenerator();
280         $this->assertInstanceOf('testing_data_generator', $generator);
281     }
283     public function test_database_mock1() {
284         global $DB;
286         try {
287             $DB->get_record('pokus', array());
288             $this->fail('Exception expected when accessing non existent table');
289         } catch (moodle_exception $e) {
290             $this->assertInstanceOf('dml_exception', $e);
291         }
292         $DB = $this->getMock(get_class($DB));
293         $this->assertNull($DB->get_record('pokus', array()));
294         // Rest continues after reset.
295     }
297     public function test_database_mock2() {
298         global $DB;
300         // Now the database should be back to normal.
301         $this->assertFalse($DB->get_record('user', array('id'=>9999)));
302     }
304     public function test_load_dataset() {
305         global $DB;
307         $this->resetAfterTest();
309         $this->assertFalse($DB->record_exists('user', array('id'=>5)));
310         $this->assertFalse($DB->record_exists('user', array('id'=>7)));
311         $dataset = $this->createXMLDataSet(__DIR__.'/fixtures/sample_dataset.xml');
312         $this->loadDataSet($dataset);
313         $this->assertTrue($DB->record_exists('user', array('id'=>5)));
314         $this->assertTrue($DB->record_exists('user', array('id'=>7)));
315         $user5 = $DB->get_record('user', array('id'=>5));
316         $user7 = $DB->get_record('user', array('id'=>7));
317         $this->assertSame('john.doe', $user5->username);
318         $this->assertSame('jane.doe', $user7->username);
320         $dataset = $this->createCsvDataSet(array('user'=>__DIR__.'/fixtures/sample_dataset.csv'));
321         $this->loadDataSet($dataset);
322         $this->assertEquals(8, $DB->get_field('user', 'id', array('username'=>'pepa.novak')));
323         $this->assertEquals(9, $DB->get_field('user', 'id', array('username'=>'bozka.novakova')));
325         $data = array(
326             'user' => array(
327                 array('username', 'email'),
328                 array('top.secret', 'top@example.com'),
329                 array('low.secret', 'low@example.com'),
330             ),
331         );
332         $dataset = $this->createArrayDataSet($data);
333         $this->loadDataSet($dataset);
334         $this->assertTrue($DB->record_exists('user', array('email'=>'top@example.com')));
335         $this->assertTrue($DB->record_exists('user', array('email'=>'low@example.com')));
337         $data = array(
338             'user' => array(
339                 array('username'=>'noidea', 'email'=>'noidea@example.com'),
340                 array('username'=>'onemore', 'email'=>'onemore@example.com'),
341             ),
342         );
343         $dataset = $this->createArrayDataSet($data);
344         $this->loadDataSet($dataset);
345         $this->assertTrue($DB->record_exists('user', array('username'=>'noidea')));
346         $this->assertTrue($DB->record_exists('user', array('username'=>'onemore')));
347     }
349     public function test_assert_time_current() {
350         $this->assertTimeCurrent(time());
352         $this->setCurrentTimeStart();
353         $this->assertTimeCurrent(time());
354         sleep(2);
355         $this->assertTimeCurrent(time());
356         $this->assertTimeCurrent(time()-1);
358         try {
359             $this->setCurrentTimeStart();
360             $this->assertTimeCurrent(time()+10);
361             $this->fail('Failed assert expected');
362         } catch (Exception $e) {
363             $this->assertInstanceOf('PHPUnit_Framework_ExpectationFailedException', $e);
364         }
366         try {
367             $this->setCurrentTimeStart();
368             $this->assertTimeCurrent(time()-10);
369             $this->fail('Failed assert expected');
370         } catch (Exception $e) {
371             $this->assertInstanceOf('PHPUnit_Framework_ExpectationFailedException', $e);
372         }
373     }
375     public function test_message_processors_reset() {
376         global $DB;
378         $this->resetAfterTest(true);
380         // Get all processors first.
381         $processors1 = get_message_processors();
383         // Add a new message processor and get all processors again.
384         $processor = new stdClass();
385         $processor->name = 'test_processor';
386         $processor->enabled = 1;
387         $DB->insert_record('message_processors', $processor);
389         $processors2 = get_message_processors();
391         // Assert that new processor still haven't been added to the list.
392         $this->assertSame($processors1, $processors2);
394         // Reset message processors data.
395         $processors3 = get_message_processors(false, true);
396         // Now, list of processors should not be the same any more,
397         // And we should have one more message processor in the list.
398         $this->assertNotSame($processors1, $processors3);
399         $this->assertEquals(count($processors1) + 1, count($processors3));
400     }
402     public function test_message_redirection() {
403         $this->preventResetByRollback(); // Messaging is not compatible with transactions...
404         $this->resetAfterTest(false);
406         $user1 = $this->getDataGenerator()->create_user();
407         $user2 = $this->getDataGenerator()->create_user();
409         // Any core message will do here.
410         $message1 = new stdClass();
411         $message1->component         = 'moodle';
412         $message1->name              = 'instantmessage';
413         $message1->userfrom          = $user1;
414         $message1->userto            = $user2;
415         $message1->subject           = 'message subject 1';
416         $message1->fullmessage       = 'message body';
417         $message1->fullmessageformat = FORMAT_MARKDOWN;
418         $message1->fullmessagehtml   = '<p>message body</p>';
419         $message1->smallmessage      = 'small message';
420         $message1->notification      = 0;
422         $message2 = new stdClass();
423         $message2->component         = 'moodle';
424         $message2->name              = 'instantmessage';
425         $message2->userfrom          = $user2;
426         $message2->userto            = $user1;
427         $message2->subject           = 'message subject 2';
428         $message2->fullmessage       = 'message body';
429         $message2->fullmessageformat = FORMAT_MARKDOWN;
430         $message2->fullmessagehtml   = '<p>message body</p>';
431         $message2->smallmessage      = 'small message';
432         $message2->notification      = 0;
434         // There should be debugging message without redirection.
435         $mailsink = $this->redirectEmails();
436         $mailsink->close();
437         message_send($message1);
438         $this->assertDebuggingCalled(null, null, 'message_send() must print debug message that messaging is disabled in phpunit tests.');
440         // Sink should catch messages.
441         $sink = $this->redirectMessages();
442         $mid1 = message_send($message1);
443         $mid2 = message_send($message2);
445         $this->assertDebuggingNotCalled('message redirection must prevent debug messages from the message_send()');
446         $this->assertEquals(2, $sink->count());
447         $this->assertGreaterThanOrEqual(1, $mid1);
448         $this->assertGreaterThanOrEqual($mid1, $mid2);
450         $messages = $sink->get_messages();
451         $this->assertInternalType('array', $messages);
452         $this->assertCount(2, $messages);
453         $this->assertEquals($mid1, $messages[0]->id);
454         $this->assertEquals($message1->userto->id, $messages[0]->useridto);
455         $this->assertEquals($message1->userfrom->id, $messages[0]->useridfrom);
456         $this->assertEquals($message1->smallmessage, $messages[0]->smallmessage);
457         $this->assertEquals($mid2, $messages[1]->id);
458         $this->assertEquals($message2->userto->id, $messages[1]->useridto);
459         $this->assertEquals($message2->userfrom->id, $messages[1]->useridfrom);
460         $this->assertEquals($message2->smallmessage, $messages[1]->smallmessage);
462         // Test resetting.
463         $sink->clear();
464         $messages = $sink->get_messages();
465         $this->assertInternalType('array', $messages);
466         $this->assertCount(0, $messages);
468         message_send($message1);
469         $messages = $sink->get_messages();
470         $this->assertInternalType('array', $messages);
471         $this->assertCount(1, $messages);
473         // Test closing.
474         $sink->close();
475         $messages = $sink->get_messages();
476         $this->assertInternalType('array', $messages);
477         $this->assertCount(1, $messages, 'Messages in sink are supposed to stay there after close');
479         // Test debugging is enabled again.
480         message_send($message1);
481         $this->assertDebuggingCalled(null, null, 'message_send() must print debug message that messaging is disabled in phpunit tests.');
483         // Test invalid names and components.
485         $sink = $this->redirectMessages();
487         $message3 = new stdClass();
488         $message3->component         = 'xxxx_yyyyy';
489         $message3->name              = 'instantmessage';
490         $message3->userfrom          = $user2;
491         $message3->userto            = $user1;
492         $message3->subject           = 'message subject 2';
493         $message3->fullmessage       = 'message body';
494         $message3->fullmessageformat = FORMAT_MARKDOWN;
495         $message3->fullmessagehtml   = '<p>message body</p>';
496         $message3->smallmessage      = 'small message';
497         $message3->notification      = 0;
499         try {
500             message_send($message3);
501             $this->fail('coding expcetion expected if invalid component specified');
502         } catch (moodle_exception $e) {
503             $this->assertInstanceOf('coding_exception', $e);
504         }
506         $message3->component = 'moodle';
507         $message3->name      = 'yyyyyy';
508         try {
509             message_send($message3);
510             $this->fail('coding expcetion expected if invalid name specified');
511         } catch (moodle_exception $e) {
512             $this->assertInstanceOf('coding_exception', $e);
513         }
515         message_send($message1);
516         $this->assertEquals(1, $sink->count());
518         // Test if sink can be carried over to next test.
519         $this->assertTrue(phpunit_util::is_redirecting_messages());
520         return $sink;
521     }
523     /**
524      * @depends test_message_redirection
525      */
526     public function test_message_redirection_noreset($sink) {
527         $this->preventResetByRollback(); // Messaging is not compatible with transactions...
528         $this->resetAfterTest();
530         $this->assertTrue(phpunit_util::is_redirecting_messages());
531         $this->assertEquals(1, $sink->count());
533         $message = new stdClass();
534         $message->component         = 'moodle';
535         $message->name              = 'instantmessage';
536         $message->userfrom          = get_admin();
537         $message->userto            = get_admin();
538         $message->subject           = 'message subject 1';
539         $message->fullmessage       = 'message body';
540         $message->fullmessageformat = FORMAT_MARKDOWN;
541         $message->fullmessagehtml   = '<p>message body</p>';
542         $message->smallmessage      = 'small message';
543         $message->notification      = 0;
545         message_send($message);
546         $this->assertEquals(2, $sink->count());
547     }
549     /**
550      * @depends test_message_redirection_noreset
551      */
552     public function test_message_redirection_reset() {
553         $this->assertFalse(phpunit_util::is_redirecting_messages(), 'Test reset must stop message redirection.');
554     }
556     public function test_set_timezone() {
557         global $CFG;
558         $this->resetAfterTest();
560         $this->assertSame('Australia/Perth', $CFG->timezone);
561         $this->assertSame('Australia/Perth', date_default_timezone_get());
563         $this->setTimezone('Pacific/Auckland', 'Europe/Prague');
564         $this->assertSame('Pacific/Auckland', $CFG->timezone);
565         $this->assertSame('Pacific/Auckland', date_default_timezone_get());
567         $this->setTimezone('99', 'Europe/Prague');
568         $this->assertSame('99', $CFG->timezone);
569         $this->assertSame('Europe/Prague', date_default_timezone_get());
571         $this->setTimezone('xxx', 'Europe/Prague');
572         $this->assertSame('xxx', $CFG->timezone);
573         $this->assertSame('Europe/Prague', date_default_timezone_get());
575         $this->setTimezone();
576         $this->assertSame('Australia/Perth', $CFG->timezone);
577         $this->assertSame('Australia/Perth', date_default_timezone_get());
579         try {
580             $this->setTimezone('Pacific/Auckland', '');
581         } catch (Exception $e) {
582             $this->assertInstanceOf('PHPUnit_Framework_Error_Warning', $e);
583         }
585         try {
586             $this->setTimezone('Pacific/Auckland', 'xxxx');
587         } catch (Exception $e) {
588             $this->assertInstanceOf('PHPUnit_Framework_Error_Warning', $e);
589         }
591         try {
592             $this->setTimezone('Pacific/Auckland', null);
593         } catch (Exception $e) {
594             $this->assertInstanceOf('PHPUnit_Framework_Error_Warning', $e);
595         }
597     }
599     public function test_locale_reset() {
600         global $CFG;
602         $this->resetAfterTest();
604         // If this fails self::resetAllData(); must be updated.
605         $this->assertSame('en_AU.UTF-8', get_string('locale', 'langconfig'));
606         $this->assertSame('English_Australia.1252', get_string('localewin', 'langconfig'));
608         if ($CFG->ostype === 'WINDOWS') {
609             $this->assertSame('English_Australia.1252', setlocale(LC_TIME, 0));
610             setlocale(LC_TIME, 'English_USA.1252');
611         } else {
612             $this->assertSame('en_AU.UTF-8', setlocale(LC_TIME, 0));
613             setlocale(LC_TIME, 'en_US.UTF-8');
614         }
616         try {
617             self::resetAllData(true);
618         } catch (Exception $e) {
619             $this->assertInstanceOf('PHPUnit_Framework_Error_Warning', $e);
620         }
622         if ($CFG->ostype === 'WINDOWS') {
623             $this->assertSame('English_Australia.1252', setlocale(LC_TIME, 0));
624         } else {
625             $this->assertSame('en_AU.UTF-8', setlocale(LC_TIME, 0));
626         }
628         if ($CFG->ostype === 'WINDOWS') {
629             $this->assertSame('English_Australia.1252', setlocale(LC_TIME, 0));
630             setlocale(LC_TIME, 'English_USA.1252');
631         } else {
632             $this->assertSame('en_AU.UTF-8', setlocale(LC_TIME, 0));
633             setlocale(LC_TIME, 'en_US.UTF-8');
634         }
636         self::resetAllData(false);
638         if ($CFG->ostype === 'WINDOWS') {
639             $this->assertSame('English_Australia.1252', setlocale(LC_TIME, 0));
640         } else {
641             $this->assertSame('en_AU.UTF-8', setlocale(LC_TIME, 0));
642         }
643     }