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