MDL-42084 Unit tests: Remove unnecessary 'clear time limit change' lines
[moodle.git] / lib / tests / statslib_test.php
CommitLineData
c0f00c5f
TB
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 * Tests for ../statslib.php
19 *
d53111c0
PS
20 * @package core_stats
21 * @category phpunit
c0f00c5f
TB
22 * @copyright 2012 Tyler Bannister
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26defined('MOODLE_INTERNAL') || die();
27
28global $CFG;
29require_once($CFG->libdir . '/adminlib.php');
30require_once($CFG->libdir . '/statslib.php');
613eebfc 31require_once($CFG->libdir . '/cronlib.php');
c0f00c5f
TB
32
33/**
d53111c0 34 * Test functions that affect daily stats.
c0f00c5f 35 */
d53111c0 36class core_statslib_testcase extends advanced_testcase {
c0f00c5f
TB
37 /** The student role ID **/
38 const STID = 5;
39
40 /** The day to use for testing **/
67690cfa
TB
41 const DAY = 1272672000;
42
43 /** The timezone to use for testing **/
44 const TIMEZONE = 0;
c0f00c5f
TB
45
46 /** @var array The list of temporary tables created for the statistic calculations **/
47 protected $tables = array('temp_log1', 'temp_log2', 'temp_stats_daily', 'temp_stats_user_daily');
48
49 /** @var array The replacements to be used when loading XML files **/
50 protected $replacements = null;
51
52 /**
d53111c0 53 * Set up the database for tests.
c0f00c5f
TB
54 *
55 * This function is needed so that daily_log_provider has the before-test set up from setUp()
56 */
d53111c0 57 protected function set_up_db() {
c0f00c5f
TB
58 global $DB;
59
60 if ($DB->record_exists('user', array('username' => 'user1'))) {
61 return;
62 }
63
64 $datagen = self::getDataGenerator();
65
66 $user1 = $datagen->create_user(array('username'=>'user1'));
67 $user2 = $datagen->create_user(array('username'=>'user2'));
68
69 $course1 = $datagen->create_course(array('shortname'=>'course1'));
70
71 $success = enrol_try_internal_enrol($course1->id, $user1->id, 5);
72
d53111c0 73 if (!$success) {
c0f00c5f
TB
74 trigger_error('User enrollment failed', E_USER_ERROR);
75 }
76
77 $context = context_system::instance();
78 role_assign(self::STID, $user2->id, $context->id);
79
80 $this->generate_replacement_list();
81 }
82
83 /**
84 * Setup function
85 * - Allow changes to CFG->debug for testing purposes.
86 */
87 protected function setUp() {
88 global $CFG;
89 parent::setUp();
90
d53111c0 91 // Settings to force statistic to run during testing.
67690cfa 92 $CFG->timezone = self::TIMEZONE;
c0f00c5f
TB
93 $CFG->statsfirstrun = 'all';
94 $CFG->statslastdaily = 0;
95 $CFG->statslastexecution = 0;
67690cfa 96
d53111c0 97 // Figure out the broken day start so I can figure out when to the start time should be.
67690cfa
TB
98 $time = time();
99 $offset = get_timezone_offset($CFG->timezone);
100 $stime = $time + $offset;
101 $stime = intval($stime / (60*60*24)) * 60*60*24;
102 $stime -= $offset;
103
104 $shour = intval(($time - $stime) / (60*60));
105
106 $CFG->statsruntimestarthour = $shour;
c0f00c5f
TB
107 $CFG->statsruntimestartminute = 0;
108
d53111c0 109 $this->set_up_db();
c0f00c5f 110
d53111c0 111 $this->resetAfterTest();
c0f00c5f
TB
112 }
113
114 /**
115 * Function to setup database.
116 *
117 * @param array $dataset An array of tables including the log table.
d53111c0 118 * @param array $tables
c0f00c5f
TB
119 */
120 protected function prepare_db($dataset, $tables) {
121 global $DB;
122
123 foreach ($tables as $tablename) {
124 $DB->delete_records($tablename);
125
126 foreach ($dataset as $name => $table) {
127
128 if ($tablename == $name) {
129
130 $rows = $table->getRowCount();
131
132 for ($i = 0; $i < $rows; $i++) {
133 $row = $table->getRow($i);
134
135 $DB->insert_record($tablename, $row, false, true);
136 }
137 }
138 }
139 }
140 }
141
142 /**
d53111c0 143 * Load dataset from XML file.
c0f00c5f
TB
144 */
145 protected function generate_replacement_list() {
146 global $CFG, $DB;
147
148 if ($this->replacements !== null) {
149 return;
150 }
151
67690cfa
TB
152 $CFG->timezone = self::TIMEZONE;
153
c0f00c5f
TB
154 $guest = $DB->get_record('user', array('id' => $CFG->siteguest));
155 $user1 = $DB->get_record('user', array('username' => 'user1'));
156 $user2 = $DB->get_record('user', array('username' => 'user2'));
157
158 if (($guest === false) || ($user1 === false) || ($user2 === false)) {
159 trigger_error('User setup incomplete', E_USER_ERROR);
160 }
161
162 $site = $DB->get_record('course', array('id' => SITEID));
163 $course1 = $DB->get_record('course', array('shortname' => 'course1'));
164
165 if (($site === false) || ($course1 === false)) {
166 trigger_error('Course setup incomplete', E_USER_ERROR);
167 }
168
67690cfa
TB
169 $offset = get_timezone_offset($CFG->timezone);
170
c0f00c5f
TB
171 $start = stats_get_base_daily(self::DAY + 3600);
172 $startnolog = stats_get_base_daily(stats_get_start_from('daily'));
173 $gr = get_guest_role();
174
175 $this->replacements = array(
d53111c0
PS
176 // Start and end times.
177 '[start_0]' => $start - 14410, // 4 hours before.
178 '[start_1]' => $start + 14410, // 4 hours after.
c0f00c5f
TB
179 '[start_2]' => $start + 14420,
180 '[start_3]' => $start + 14430,
d53111c0 181 '[start_4]' => $start + 100800, // 28 hours after.
c0f00c5f
TB
182 '[end]' => stats_get_next_day_start($start),
183 '[end_no_logs]' => stats_get_next_day_start($startnolog),
184
d53111c0 185 // User ids.
c0f00c5f
TB
186 '[guest_id]' => $guest->id,
187 '[user1_id]' => $user1->id,
188 '[user2_id]' => $user2->id,
189
d53111c0 190 // Course ids.
c0f00c5f
TB
191 '[course1_id]' => $course1->id,
192 '[site_id]' => SITEID,
193
d53111c0 194 // Role ids.
c0f00c5f
TB
195 '[frontpage_roleid]' => (int) $CFG->defaultfrontpageroleid,
196 '[guest_roleid]' => $gr->id,
197 '[student_roleid]' => self::STID,
198 );
199 }
200
201 /**
d53111c0 202 * Load dataset from XML file.
c0f00c5f
TB
203 *
204 * @param string $file The name of the file to load
d53111c0 205 * @return array
c0f00c5f
TB
206 */
207 protected function load_xml_data_file($file) {
208 static $replacements = null;
209
210 $raw = $this->createXMLDataSet($file);
211 $clean = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($raw);
212
213 foreach ($this->replacements as $placeholder => $value) {
214 $clean->addFullReplacement($placeholder, $value);
215 }
216
217 $logs = new PHPUnit_Extensions_Database_DataSet_DataSetFilter($clean);
218 $logs->addIncludeTables(array('log'));
219
220 $stats = new PHPUnit_Extensions_Database_DataSet_DataSetFilter($clean);
221 $stats->addIncludeTables(array('stats_daily', 'stats_user_daily'));
222
223 return array($logs, $stats);
224 }
225
226 /**
d53111c0 227 * Provides the log data for test_statslib_cron_daily.
c0f00c5f
TB
228 */
229 public function daily_log_provider() {
230 global $CFG, $DB;
231
d53111c0 232 $this->set_up_db();
c0f00c5f
TB
233
234 $tests = array('00', '01', '02', '03', '04', '05', '06', '07', '08');
235
236 $dataset = array();
237
238 foreach ($tests as $test) {
239 $dataset[] = $this->load_xml_data_file(__DIR__."/fixtures/statslib-test{$test}.xml");
240 }
241
242 return $dataset;
243 }
244
245 /**
246 * Compare the expected stats to those in the database.
247 *
d53111c0
PS
248 * @param array $expected
249 * @param string $output
c0f00c5f 250 */
12ccfc12 251 protected function verify_stats($expected, $output = '') {
c0f00c5f
TB
252 global $DB;
253
254 // Note: We can not use $this->assertDataSetEqual($expected, $actual) because there's no
255 // $this->getConnection() in advanced_testcase.
256
257 foreach ($expected as $type => $table) {
258 $records = $DB->get_records($type);
259
260 $rows = $table->getRowCount();
261
12ccfc12
TB
262 $message = 'Incorrect number of results returned for '. $type;
263
264 if ($output != '') {
265 $message .= "\nCron output:\n$output";
266 }
267
d53111c0 268 $this->assertCount($rows, $records, $message);
c0f00c5f
TB
269
270 for ($i = 0; $i < $rows; $i++) {
271 $row = $table->getRow($i);
272 $found = 0;
273
274 foreach ($records as $key => $record) {
275 $record = (array) $record;
276 unset($record['id']);
277 $diff = array_merge(array_diff_assoc($row, $record),
278 array_diff_assoc($record, $row));
279
280 if (empty($diff)) {
281 $found = $key;
282 break;
283 }
284 }
12ccfc12 285
c0f00c5f
TB
286 $this->assertGreaterThan(0, $found, 'Expected log '. var_export($row, true)
287 ." was not found in $type ". var_export($records, true));
288 unset($records[$found]);
289 }
290 }
291 }
292
293 /**
d53111c0 294 * Test progress output when debug is on.
c0f00c5f
TB
295 */
296 public function test_statslib_progress_debug() {
96f81ea3 297 set_debugging(DEBUG_ALL);
c0f00c5f
TB
298 $this->expectOutputString('1:0 ');
299 stats_progress('init');
300 stats_progress('1');
96f81ea3 301 $this->resetDebugging();
c0f00c5f
TB
302 }
303
304 /**
d53111c0 305 * Test progress output when debug is off.
c0f00c5f
TB
306 */
307 public function test_statslib_progress_no_debug() {
96f81ea3 308 set_debugging(DEBUG_NONE);
c0f00c5f
TB
309 $this->expectOutputString('.');
310 stats_progress('init');
311 stats_progress('1');
96f81ea3 312 $this->resetDebugging();
c0f00c5f
TB
313 }
314
315 /**
d53111c0 316 * Test the function that gets the start date from the config.
c0f00c5f
TB
317 */
318 public function test_statslib_get_start_from() {
319 global $CFG, $DB;
320
321 $dataset = $this->load_xml_data_file(__DIR__."/fixtures/statslib-test01.xml");
c0f00c5f
TB
322 $time = time();
323 $DB->delete_records('log');
324
67690cfa
TB
325 // Don't ask. I don't think get_timezone_offset works correctly.
326 $day = self::DAY - get_timezone_offset($CFG->timezone);
327
c0f00c5f
TB
328 $CFG->statsfirstrun = 'all';
329 // Allow 1 second difference in case we cross a second boundary.
594d66c2
DW
330 // Note: within 3 days of a DST change - -3 days != 3 * 24 hours (it may be more or less).
331 $this->assertLessThanOrEqual(1, stats_get_start_from('daily') - strtotime('-3 days', $time), 'All start time');
c0f00c5f
TB
332
333 $this->prepare_db($dataset[0], array('log'));
334 $records = $DB->get_records('log');
335
67690cfa 336 $this->assertEquals($day + 14410, stats_get_start_from('daily'), 'Log entry start');
c0f00c5f
TB
337
338 $CFG->statsfirstrun = 'none';
594d66c2 339 $this->assertLessThanOrEqual(1, stats_get_start_from('daily') - strtotime('-3 days', $time), 'None start time');
c0f00c5f
TB
340
341 $CFG->statsfirstrun = 14515200;
342 $this->assertLessThanOrEqual(1, stats_get_start_from('daily') - ($time - (14515200)), 'Specified start time');
343
344 $this->prepare_db($dataset[1], array('stats_daily'));
67690cfa 345 $this->assertEquals($day + (24 * 3600), stats_get_start_from('daily'), 'Daily stats start time');
c0f00c5f
TB
346 }
347
348 /**
d53111c0 349 * Test the function that calculates the start of the day.
67690cfa
TB
350 *
351 * NOTE: I don't think this is the way this function should work.
352 * This test documents the current functionality.
c0f00c5f
TB
353 */
354 public function test_statslib_get_base_daily() {
355 global $CFG;
356
67690cfa
TB
357 for ($x = 0; $x < 24; $x += 1) {
358 $CFG->timezone = $x;
359
360 $start = 1272672000 - ($x * 3600);
361 if ($x >= 20) {
362 $start += (24 * 3600);
363 }
364
365 $this->assertEquals($start, stats_get_base_daily(1272686410), "Timezone $x check");
366 }
c0f00c5f
TB
367 }
368
369 /**
d53111c0 370 * Test the function that gets the start of the next day.
c0f00c5f
TB
371 */
372 public function test_statslib_get_next_day_start() {
373 global $CFG;
374
375 $CFG->timezone = 0;
376 $this->assertEquals(1272758400, stats_get_next_day_start(1272686410));
377 }
378
379 /**
d53111c0 380 * Test the function that gets the action names.
c0f00c5f
TB
381 *
382 * Note: The function results depend on installed modules. The hard coded lists are the
383 * defaults for a new Moodle 2.3 install.
384 */
385 public function test_statslib_get_action_names() {
386 $basepostactions = array (
387 0 => 'add',
388 1 => 'delete',
389 2 => 'edit',
390 3 => 'add mod',
391 4 => 'delete mod',
392 5 => 'edit sectionenrol',
393 6 => 'loginas',
394 7 => 'new',
395 8 => 'unenrol',
396 9 => 'update',
397 10 => 'update mod',
398 11 => 'upload',
399 12 => 'submit',
400 13 => 'submit for grading',
401 14 => 'talk',
402 15 => 'choose',
403 16 => 'choose again',
404 17 => 'record delete',
405 18 => 'add discussion',
406 19 => 'add post',
407 20 => 'delete discussion',
408 21 => 'delete post',
409 22 => 'move discussion',
410 23 => 'prune post',
411 24 => 'update post',
412 25 => 'add category',
413 26 => 'add entry',
414 27 => 'approve entry',
415 28 => 'delete category',
416 29 => 'delete entry',
417 30 => 'edit category',
418 31 => 'update entry',
419 32 => 'end',
420 33 => 'start',
421 34 => 'attempt',
422 35 => 'close attempt',
423 36 => 'preview',
424 37 => 'editquestions',
425 38 => 'delete attempt',
426 39 => 'manualgrade',
427 );
428
429 $baseviewactions = array (
430 0 => 'view',
431 1 => 'view all',
432 2 => 'history',
433 3 => 'view submission',
434 4 => 'view feedback',
435 5 => 'print',
436 6 => 'report',
437 7 => 'view discussion',
438 8 => 'search',
439 9 => 'forum',
440 10 => 'forums',
441 11 => 'subscribers',
442 12 => 'view forum',
443 13 => 'view entry',
444 14 => 'review',
445 15 => 'pre-view',
446 16 => 'download',
447 17 => 'view form',
448 18 => 'view graph',
449 19 => 'view report',
450 );
451
452 $postactions = stats_get_action_names('post');
453
454 foreach ($basepostactions as $action) {
455 $this->assertContains($action, $postactions);
456 }
457
458 $viewactions = stats_get_action_names('view');
459
460 foreach ($baseviewactions as $action) {
461 $this->assertContains($action, $viewactions);
462 }
463 }
464
465 /**
466 * Test the temporary table creation and deletion.
467 */
468 public function test_statslib_temp_table_create_and_drop() {
469 global $DB;
470
471 foreach ($this->tables as $table) {
472 $this->assertFalse($DB->get_manager()->table_exists($table));
473 }
474
475 stats_temp_table_create();
476
477 foreach ($this->tables as $table) {
478 $this->assertTrue($DB->get_manager()->table_exists($table));
479 }
480
481 stats_temp_table_drop();
482
483 foreach ($this->tables as $table) {
484 $this->assertFalse($DB->get_manager()->table_exists($table));
485 }
486 }
487
488 /**
489 * Test the temporary table creation and deletion.
490 *
491 * @depends test_statslib_temp_table_create_and_drop
492 */
493 public function test_statslib_temp_table_fill() {
67690cfa 494 global $CFG, $DB;
c0f00c5f
TB
495
496 $dataset = $this->load_xml_data_file(__DIR__."/fixtures/statslib-test09.xml");
497
498 $this->prepare_db($dataset[0], array('log'));
499
67690cfa
TB
500 $start = self::DAY - get_timezone_offset($CFG->timezone);
501 $end = $start + (24 * 3600);
502
c0f00c5f 503 stats_temp_table_create();
67690cfa 504 stats_temp_table_fill($start, $end);
c0f00c5f
TB
505
506 $this->assertEquals(1, $DB->count_records('temp_log1'));
507 $this->assertEquals(1, $DB->count_records('temp_log2'));
508
509 stats_temp_table_drop();
510 }
511
512 /**
513 * Test the temporary table creation and deletion.
514 *
515 * @depends test_statslib_temp_table_create_and_drop
516 */
517 public function test_statslib_temp_table_setup() {
518 global $DB;
519
520 $logs = array();
521 $this->prepare_db($logs, array('log'));
522
523 stats_temp_table_create();
524 stats_temp_table_setup();
525
526 $this->assertEquals(1, $DB->count_records('temp_enroled'));
527
528 stats_temp_table_drop();
529 }
530
531 /**
532 * Test the function that clean out the temporary tables.
533 *
534 * @depends test_statslib_temp_table_create_and_drop
535 */
536 public function test_statslib_temp_table_clean() {
537 global $DB;
538
539 $rows = array(
540 'temp_log1' => array('id' => 1, 'course' => 1),
541 'temp_log2' => array('id' => 1, 'course' => 1),
542 'temp_stats_daily' => array('id' => 1, 'courseid' => 1),
543 'temp_stats_user_daily' => array('id' => 1, 'courseid' => 1),
544 );
545
546 stats_temp_table_create();
547
548 foreach ($rows as $table => $row) {
549 $DB->insert_record_raw($table, $row);
550 $this->assertEquals(1, $DB->count_records($table));
551 }
552
553 stats_temp_table_clean();
554
555 foreach ($rows as $table => $row) {
556 $this->assertEquals(0, $DB->count_records($table));
557 }
558
559 $this->assertEquals(1, $DB->count_records('stats_daily'));
560 $this->assertEquals(1, $DB->count_records('stats_user_daily'));
561
562 stats_temp_table_drop();
563 }
564
565 /**
d53111c0 566 * Test the daily stats function.
c0f00c5f
TB
567 *
568 * @depends test_statslib_get_base_daily
569 * @depends test_statslib_get_next_day_start
67690cfa 570 * @depends test_statslib_get_start_from
c0f00c5f
TB
571 * @depends test_statslib_temp_table_create_and_drop
572 * @depends test_statslib_temp_table_setup
573 * @depends test_statslib_temp_table_fill
574 * @dataProvider daily_log_provider
575 */
576 public function test_statslib_cron_daily($logs, $stats) {
67690cfa 577 global $CFG, $DB;
c0f00c5f 578
c0f00c5f
TB
579 $this->prepare_db($logs, array('log'));
580
581 // Stats cron daily uses mtrace, turn on buffering to silence output.
582 ob_start();
583 stats_cron_daily(1);
12ccfc12 584 $output = ob_get_contents();
c0f00c5f
TB
585 ob_end_clean();
586
12ccfc12 587 $this->verify_stats($stats, $output);
c0f00c5f
TB
588 }
589
590 /**
d53111c0
PS
591 * Test the daily stats function.
592 *
c0f00c5f
TB
593 * @depends test_statslib_get_base_daily
594 * @depends test_statslib_get_next_day_start
595 */
596 public function test_statslib_cron_daily_no_default_profile_id() {
597 global $CFG, $DB;
598 $CFG->defaultfrontpageroleid = 0;
599
600 $course1 = $DB->get_record('course', array('shortname' => 'course1'));
601 $guestid = $CFG->siteguest;
602 $start = stats_get_base_daily(1272758400);
603 $end = stats_get_next_day_start($start);
604 $fpid = (int) $CFG->defaultfrontpageroleid;
605 $gr = get_guest_role();
606
607 $dataset = $this->load_xml_data_file(__DIR__."/fixtures/statslib-test10.xml");
608
c0f00c5f
TB
609 $this->prepare_db($dataset[0], array('log'));
610
611 // Stats cron daily uses mtrace, turn on buffering to silence output.
612 ob_start();
613 stats_cron_daily($maxdays=1);
12ccfc12 614 $output = ob_get_contents();
c0f00c5f
TB
615 ob_end_clean();
616
12ccfc12 617 $this->verify_stats($dataset[1], $output);
c0f00c5f
TB
618 }
619}