weekly release 3.7dev
[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');
92927fba 32require_once(__DIR__ . '/fixtures/stats_events.php');
c0f00c5f
TB
33
34/**
d53111c0 35 * Test functions that affect daily stats.
c0f00c5f 36 */
d53111c0 37class core_statslib_testcase extends advanced_testcase {
c0f00c5f 38 /** The day to use for testing **/
67690cfa
TB
39 const DAY = 1272672000;
40
41 /** The timezone to use for testing **/
42 const TIMEZONE = 0;
c0f00c5f
TB
43
44 /** @var array The list of temporary tables created for the statistic calculations **/
45 protected $tables = array('temp_log1', 'temp_log2', 'temp_stats_daily', 'temp_stats_user_daily');
46
47 /** @var array The replacements to be used when loading XML files **/
48 protected $replacements = null;
49
c0f00c5f
TB
50
51 /**
52 * Setup function
53 * - Allow changes to CFG->debug for testing purposes.
54 */
55 protected function setUp() {
ba923f4f 56 global $CFG, $DB;
c0f00c5f
TB
57 parent::setUp();
58
d53111c0 59 // Settings to force statistic to run during testing.
d6e7a63d
PS
60 $this->setTimezone(self::TIMEZONE);
61 core_date::set_default_server_timezone();
c0f00c5f
TB
62 $CFG->statsfirstrun = 'all';
63 $CFG->statslastdaily = 0;
67690cfa 64
d53111c0 65 // Figure out the broken day start so I can figure out when to the start time should be.
67690cfa 66 $time = time();
d6e7a63d
PS
67 // This nonsense needs to be rewritten.
68 $date = new DateTime('now', core_date::get_server_timezone_object());
69 $offset = $date->getOffset();
67690cfa
TB
70 $stime = $time + $offset;
71 $stime = intval($stime / (60*60*24)) * 60*60*24;
72 $stime -= $offset;
73
74 $shour = intval(($time - $stime) / (60*60));
75
ba923f4f
EV
76 if ($DB->record_exists('user', array('username' => 'user1'))) {
77 return;
78 }
79
80 // Set up the database.
81 $datagen = self::getDataGenerator();
82
83 $user1 = $datagen->create_user(array('username'=>'user1'));
84 $user2 = $datagen->create_user(array('username'=>'user2'));
85
86 $course1 = $datagen->create_course(array('shortname'=>'course1'));
73f755a7 87 $datagen->enrol_user($user1->id, $course1->id);
ba923f4f
EV
88
89 $this->generate_replacement_list();
c0f00c5f 90
ba923f4f 91 // Reset between tests.
d53111c0 92 $this->resetAfterTest();
c0f00c5f
TB
93 }
94
95 /**
96 * Function to setup database.
97 *
98 * @param array $dataset An array of tables including the log table.
d53111c0 99 * @param array $tables
c0f00c5f
TB
100 */
101 protected function prepare_db($dataset, $tables) {
102 global $DB;
103
104 foreach ($tables as $tablename) {
105 $DB->delete_records($tablename);
106
107 foreach ($dataset as $name => $table) {
108
109 if ($tablename == $name) {
110
111 $rows = $table->getRowCount();
112
113 for ($i = 0; $i < $rows; $i++) {
114 $row = $table->getRow($i);
115
116 $DB->insert_record($tablename, $row, false, true);
117 }
118 }
119 }
120 }
121 }
122
123 /**
d53111c0 124 * Load dataset from XML file.
c0f00c5f
TB
125 */
126 protected function generate_replacement_list() {
127 global $CFG, $DB;
128
129 if ($this->replacements !== null) {
130 return;
131 }
132
d6e7a63d 133 $this->setTimezone(self::TIMEZONE);
67690cfa 134
c0f00c5f
TB
135 $guest = $DB->get_record('user', array('id' => $CFG->siteguest));
136 $user1 = $DB->get_record('user', array('username' => 'user1'));
137 $user2 = $DB->get_record('user', array('username' => 'user2'));
138
139 if (($guest === false) || ($user1 === false) || ($user2 === false)) {
140 trigger_error('User setup incomplete', E_USER_ERROR);
141 }
142
143 $site = $DB->get_record('course', array('id' => SITEID));
144 $course1 = $DB->get_record('course', array('shortname' => 'course1'));
145
146 if (($site === false) || ($course1 === false)) {
147 trigger_error('Course setup incomplete', E_USER_ERROR);
148 }
149
150 $start = stats_get_base_daily(self::DAY + 3600);
151 $startnolog = stats_get_base_daily(stats_get_start_from('daily'));
152 $gr = get_guest_role();
73f755a7 153 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
c0f00c5f
TB
154
155 $this->replacements = array(
d53111c0
PS
156 // Start and end times.
157 '[start_0]' => $start - 14410, // 4 hours before.
158 '[start_1]' => $start + 14410, // 4 hours after.
c0f00c5f
TB
159 '[start_2]' => $start + 14420,
160 '[start_3]' => $start + 14430,
d53111c0 161 '[start_4]' => $start + 100800, // 28 hours after.
c0f00c5f
TB
162 '[end]' => stats_get_next_day_start($start),
163 '[end_no_logs]' => stats_get_next_day_start($startnolog),
164
d53111c0 165 // User ids.
c0f00c5f
TB
166 '[guest_id]' => $guest->id,
167 '[user1_id]' => $user1->id,
168 '[user2_id]' => $user2->id,
169
d53111c0 170 // Course ids.
c0f00c5f
TB
171 '[course1_id]' => $course1->id,
172 '[site_id]' => SITEID,
173
d53111c0 174 // Role ids.
c0f00c5f
TB
175 '[frontpage_roleid]' => (int) $CFG->defaultfrontpageroleid,
176 '[guest_roleid]' => $gr->id,
73f755a7 177 '[student_roleid]' => $studentrole->id,
c0f00c5f
TB
178 );
179 }
180
181 /**
d53111c0 182 * Load dataset from XML file.
c0f00c5f
TB
183 *
184 * @param string $file The name of the file to load
d53111c0 185 * @return array
c0f00c5f
TB
186 */
187 protected function load_xml_data_file($file) {
188 static $replacements = null;
189
190 $raw = $this->createXMLDataSet($file);
801a372d 191 $clean = new PHPUnit\DbUnit\DataSet\ReplacementDataSet($raw);
c0f00c5f
TB
192
193 foreach ($this->replacements as $placeholder => $value) {
194 $clean->addFullReplacement($placeholder, $value);
195 }
196
796e48a5 197 $logs = new PHPUnit\DbUnit\DataSet\Filter($clean);
c0f00c5f
TB
198 $logs->addIncludeTables(array('log'));
199
796e48a5 200 $stats = new PHPUnit\DbUnit\DataSet\Filter($clean);
c0f00c5f
TB
201 $stats->addIncludeTables(array('stats_daily', 'stats_user_daily'));
202
203 return array($logs, $stats);
204 }
205
206 /**
d53111c0 207 * Provides the log data for test_statslib_cron_daily.
ba923f4f
EV
208 *
209 * @return array of fixture XML log file names.
c0f00c5f
TB
210 */
211 public function daily_log_provider() {
ba923f4f
EV
212 $logfiles = array();
213 $fileno = array('00', '01', '02', '03', '04', '05', '06', '07', '08');
c0f00c5f 214
ba923f4f
EV
215 foreach ($fileno as $no) {
216 $logfiles[] = array("statslib-test{$no}.xml");
c0f00c5f
TB
217 }
218
ba923f4f 219 return $logfiles;
c0f00c5f
TB
220 }
221
222 /**
223 * Compare the expected stats to those in the database.
224 *
d53111c0
PS
225 * @param array $expected
226 * @param string $output
c0f00c5f 227 */
12ccfc12 228 protected function verify_stats($expected, $output = '') {
c0f00c5f
TB
229 global $DB;
230
231 // Note: We can not use $this->assertDataSetEqual($expected, $actual) because there's no
232 // $this->getConnection() in advanced_testcase.
233
234 foreach ($expected as $type => $table) {
235 $records = $DB->get_records($type);
236
237 $rows = $table->getRowCount();
238
12ccfc12
TB
239 $message = 'Incorrect number of results returned for '. $type;
240
241 if ($output != '') {
242 $message .= "\nCron output:\n$output";
243 }
244
d53111c0 245 $this->assertCount($rows, $records, $message);
c0f00c5f
TB
246
247 for ($i = 0; $i < $rows; $i++) {
248 $row = $table->getRow($i);
249 $found = 0;
250
251 foreach ($records as $key => $record) {
252 $record = (array) $record;
253 unset($record['id']);
254 $diff = array_merge(array_diff_assoc($row, $record),
255 array_diff_assoc($record, $row));
256
257 if (empty($diff)) {
258 $found = $key;
259 break;
260 }
261 }
12ccfc12 262
c0f00c5f
TB
263 $this->assertGreaterThan(0, $found, 'Expected log '. var_export($row, true)
264 ." was not found in $type ". var_export($records, true));
265 unset($records[$found]);
266 }
267 }
268 }
269
270 /**
d53111c0 271 * Test progress output when debug is on.
c0f00c5f
TB
272 */
273 public function test_statslib_progress_debug() {
96f81ea3 274 set_debugging(DEBUG_ALL);
c0f00c5f
TB
275 $this->expectOutputString('1:0 ');
276 stats_progress('init');
277 stats_progress('1');
96f81ea3 278 $this->resetDebugging();
c0f00c5f
TB
279 }
280
281 /**
d53111c0 282 * Test progress output when debug is off.
c0f00c5f
TB
283 */
284 public function test_statslib_progress_no_debug() {
96f81ea3 285 set_debugging(DEBUG_NONE);
c0f00c5f
TB
286 $this->expectOutputString('.');
287 stats_progress('init');
288 stats_progress('1');
96f81ea3 289 $this->resetDebugging();
c0f00c5f
TB
290 }
291
292 /**
d53111c0 293 * Test the function that gets the start date from the config.
c0f00c5f
TB
294 */
295 public function test_statslib_get_start_from() {
296 global $CFG, $DB;
297
298 $dataset = $this->load_xml_data_file(__DIR__."/fixtures/statslib-test01.xml");
c0f00c5f
TB
299 $DB->delete_records('log');
300
d6e7a63d
PS
301 $date = new DateTime('now', core_date::get_server_timezone_object());
302 $day = self::DAY - $date->getOffset();
67690cfa 303
c0f00c5f
TB
304 $CFG->statsfirstrun = 'all';
305 // Allow 1 second difference in case we cross a second boundary.
594d66c2 306 // Note: within 3 days of a DST change - -3 days != 3 * 24 hours (it may be more or less).
f978c334 307 $this->assertLessThanOrEqual(1, stats_get_start_from('daily') - strtotime('-3 days', time()), 'All start time');
c0f00c5f
TB
308
309 $this->prepare_db($dataset[0], array('log'));
310 $records = $DB->get_records('log');
311
67690cfa 312 $this->assertEquals($day + 14410, stats_get_start_from('daily'), 'Log entry start');
c0f00c5f
TB
313
314 $CFG->statsfirstrun = 'none';
f978c334 315 $this->assertLessThanOrEqual(1, stats_get_start_from('daily') - strtotime('-3 days', time()), 'None start time');
c0f00c5f
TB
316
317 $CFG->statsfirstrun = 14515200;
f978c334 318 $this->assertLessThanOrEqual(1, stats_get_start_from('daily') - (time() - (14515200)), 'Specified start time');
c0f00c5f
TB
319
320 $this->prepare_db($dataset[1], array('stats_daily'));
f978c334 321 $this->assertEquals($day + DAYSECS, stats_get_start_from('daily'), 'Daily stats start time');
92927fba
322
323 // New log stores.
324 $this->preventResetByRollback();
325
326 $this->assertFileExists("$CFG->dirroot/$CFG->admin/tool/log/store/standard/version.php");
327 set_config('enabled_stores', 'logstore_standard', 'tool_log');
328 set_config('buffersize', 0, 'logstore_standard');
329 set_config('logguests', 1, 'logstore_standard');
330 get_log_manager(true);
331
332 $this->assertEquals(0, $DB->count_records('logstore_standard_log'));
333
334 $DB->delete_records('stats_daily');
335 $CFG->statsfirstrun = 'all';
336 $firstoldtime = $DB->get_field_sql('SELECT MIN(time) FROM {log}');
337
338 $this->assertEquals($firstoldtime, stats_get_start_from('daily'));
339
d504e920 340 $time = time() - 5;
92927fba 341 \core_tests\event\create_executed::create(array('context' => context_system::instance()))->trigger();
d504e920
AN
342 $DB->set_field('logstore_standard_log', 'timecreated', $time++, [
343 'eventname' => '\\core_tests\\event\\create_executed',
344 ]);
345
92927fba 346 \core_tests\event\read_executed::create(array('context' => context_system::instance()))->trigger();
d504e920
AN
347 $DB->set_field('logstore_standard_log', 'timecreated', $time++, [
348 'eventname' => '\\core_tests\\event\\read_executed',
349 ]);
350
92927fba 351 \core_tests\event\update_executed::create(array('context' => context_system::instance()))->trigger();
d504e920
AN
352 $DB->set_field('logstore_standard_log', 'timecreated', $time++, [
353 'eventname' => '\\core_tests\\event\\update_executed',
354 ]);
355
92927fba 356 \core_tests\event\delete_executed::create(array('context' => context_system::instance()))->trigger();
d504e920
AN
357 $DB->set_field('logstore_standard_log', 'timecreated', $time++, [
358 'eventname' => '\\core_tests\\event\\delete_executed',
359 ]);
92927fba 360
8dcb7ae6 361 $DB->set_field('logstore_standard_log', 'origin', 'web', array());
d504e920 362 $logs = $DB->get_records('logstore_standard_log', null, 'timecreated ASC');
92927fba
363 $this->assertCount(4, $logs);
364
365 $firstnew = reset($logs);
366 $this->assertGreaterThan($firstoldtime, $firstnew->timecreated);
367 $DB->set_field('logstore_standard_log', 'timecreated', 10, array('id' => $firstnew->id));
368 $this->assertEquals(10, stats_get_start_from('daily'));
369
370 $DB->set_field('logstore_standard_log', 'timecreated', $firstnew->timecreated, array('id' => $firstnew->id));
371 $DB->delete_records('log');
372 $this->assertEquals($firstnew->timecreated, stats_get_start_from('daily'));
373
374 set_config('enabled_stores', '', 'tool_log');
375 get_log_manager(true);
c0f00c5f
TB
376 }
377
378 /**
d53111c0 379 * Test the function that calculates the start of the day.
67690cfa
TB
380 *
381 * NOTE: I don't think this is the way this function should work.
382 * This test documents the current functionality.
c0f00c5f
TB
383 */
384 public function test_statslib_get_base_daily() {
385 global $CFG;
386
d6e7a63d
PS
387 for ($x = 0; $x < 13; $x += 1) {
388 $this->setTimezone($x);
67690cfa
TB
389
390 $start = 1272672000 - ($x * 3600);
391 if ($x >= 20) {
392 $start += (24 * 3600);
393 }
394
395 $this->assertEquals($start, stats_get_base_daily(1272686410), "Timezone $x check");
396 }
c0f00c5f
TB
397 }
398
399 /**
d53111c0 400 * Test the function that gets the start of the next day.
c0f00c5f
TB
401 */
402 public function test_statslib_get_next_day_start() {
d6e7a63d 403 $this->setTimezone(0);
c0f00c5f 404 $this->assertEquals(1272758400, stats_get_next_day_start(1272686410));
3b873397
AG
405
406 // Try setting timezone to some place in the US.
407 $this->setTimezone('America/New_York', 'America/New_York');
408 // Then set the time for midnight before daylight savings.
409 // 1425790800 is midnight in New York (2015-03-08) Daylight saving will occur in 2 hours time.
410 // 1425873600 is midnight the next day.
411 $this->assertEquals(1425873600, stats_get_next_day_start(1425790800));
412 $this->assertEquals(23, ((1425873600 - 1425790800) / 60 ) / 60);
413 // Then set the time for midnight before daylight savings ends.
414 // 1446350400 is midnight in New York (2015-11-01) Daylight saving will finish in 2 hours time.
415 // 1446440400 is midnight the next day.
416 $this->assertEquals(1446440400, stats_get_next_day_start(1446350400));
417 $this->assertEquals(25, ((1446440400 - 1446350400) / 60 ) / 60);
418 // The next day should be normal.
419 $this->assertEquals(1446526800, stats_get_next_day_start(1446440400));
420 $this->assertEquals(24, ((1446526800 - 1446440400) / 60 ) / 60);
c0f00c5f
TB
421 }
422
423 /**
d53111c0 424 * Test the function that gets the action names.
c0f00c5f
TB
425 *
426 * Note: The function results depend on installed modules. The hard coded lists are the
427 * defaults for a new Moodle 2.3 install.
428 */
429 public function test_statslib_get_action_names() {
430 $basepostactions = array (
431 0 => 'add',
432 1 => 'delete',
433 2 => 'edit',
434 3 => 'add mod',
435 4 => 'delete mod',
436 5 => 'edit sectionenrol',
437 6 => 'loginas',
438 7 => 'new',
439 8 => 'unenrol',
440 9 => 'update',
441 10 => 'update mod',
442 11 => 'upload',
443 12 => 'submit',
444 13 => 'submit for grading',
445 14 => 'talk',
446 15 => 'choose',
447 16 => 'choose again',
448 17 => 'record delete',
449 18 => 'add discussion',
450 19 => 'add post',
451 20 => 'delete discussion',
452 21 => 'delete post',
453 22 => 'move discussion',
454 23 => 'prune post',
455 24 => 'update post',
456 25 => 'add category',
457 26 => 'add entry',
458 27 => 'approve entry',
459 28 => 'delete category',
460 29 => 'delete entry',
461 30 => 'edit category',
462 31 => 'update entry',
463 32 => 'end',
464 33 => 'start',
465 34 => 'attempt',
466 35 => 'close attempt',
467 36 => 'preview',
468 37 => 'editquestions',
469 38 => 'delete attempt',
470 39 => 'manualgrade',
471 );
472
473 $baseviewactions = array (
474 0 => 'view',
475 1 => 'view all',
476 2 => 'history',
477 3 => 'view submission',
478 4 => 'view feedback',
479 5 => 'print',
480 6 => 'report',
481 7 => 'view discussion',
482 8 => 'search',
483 9 => 'forum',
484 10 => 'forums',
485 11 => 'subscribers',
486 12 => 'view forum',
487 13 => 'view entry',
488 14 => 'review',
489 15 => 'pre-view',
490 16 => 'download',
491 17 => 'view form',
492 18 => 'view graph',
493 19 => 'view report',
494 );
495
496 $postactions = stats_get_action_names('post');
497
498 foreach ($basepostactions as $action) {
499 $this->assertContains($action, $postactions);
500 }
501
502 $viewactions = stats_get_action_names('view');
503
504 foreach ($baseviewactions as $action) {
505 $this->assertContains($action, $viewactions);
506 }
507 }
508
509 /**
510 * Test the temporary table creation and deletion.
511 */
512 public function test_statslib_temp_table_create_and_drop() {
513 global $DB;
514
515 foreach ($this->tables as $table) {
516 $this->assertFalse($DB->get_manager()->table_exists($table));
517 }
518
519 stats_temp_table_create();
520
521 foreach ($this->tables as $table) {
522 $this->assertTrue($DB->get_manager()->table_exists($table));
523 }
524
525 stats_temp_table_drop();
526
527 foreach ($this->tables as $table) {
528 $this->assertFalse($DB->get_manager()->table_exists($table));
529 }
530 }
531
532 /**
533 * Test the temporary table creation and deletion.
534 *
535 * @depends test_statslib_temp_table_create_and_drop
536 */
537 public function test_statslib_temp_table_fill() {
92927fba 538 global $CFG, $DB, $USER;
c0f00c5f
TB
539
540 $dataset = $this->load_xml_data_file(__DIR__."/fixtures/statslib-test09.xml");
541
542 $this->prepare_db($dataset[0], array('log'));
543
d6e7a63d
PS
544 // This nonsense needs to be rewritten.
545 $date = new DateTime('now', core_date::get_server_timezone_object());
546 $start = self::DAY - $date->getOffset();
67690cfa
TB
547 $end = $start + (24 * 3600);
548
c0f00c5f 549 stats_temp_table_create();
67690cfa 550 stats_temp_table_fill($start, $end);
c0f00c5f
TB
551
552 $this->assertEquals(1, $DB->count_records('temp_log1'));
553 $this->assertEquals(1, $DB->count_records('temp_log2'));
554
555 stats_temp_table_drop();
92927fba
556
557 // New log stores.
558 $this->preventResetByRollback();
559 stats_temp_table_create();
560
561 $course = $this->getDataGenerator()->create_course();
562 $context = context_course::instance($course->id);
563 $fcontext = context_course::instance(SITEID);
564 $user = $this->getDataGenerator()->create_user();
565 $this->setUser($user);
566
567 $this->assertFileExists("$CFG->dirroot/$CFG->admin/tool/log/store/standard/version.php");
568 set_config('enabled_stores', 'logstore_standard', 'tool_log');
569 set_config('buffersize', 0, 'logstore_standard');
570 set_config('logguests', 1, 'logstore_standard');
571 get_log_manager(true);
572
573 $DB->delete_records('logstore_standard_log');
574
575 \core_tests\event\create_executed::create(array('context' => $fcontext, 'courseid' => SITEID))->trigger();
576 \core_tests\event\read_executed::create(array('context' => $context, 'courseid' => $course->id))->trigger();
577 \core_tests\event\update_executed::create(array('context' => context_system::instance()))->trigger();
578 \core_tests\event\delete_executed::create(array('context' => context_system::instance()))->trigger();
579
580 \core\event\user_loggedin::create(
581 array(
582 'userid' => $USER->id,
583 'objectid' => $USER->id,
584 'other' => array('username' => $USER->username),
585 )
586 )->trigger();
587
588 $DB->set_field('logstore_standard_log', 'timecreated', 10);
589
590 $this->assertEquals(5, $DB->count_records('logstore_standard_log'));
591
592 \core_tests\event\delete_executed::create(array('context' => context_system::instance()))->trigger();
593 \core_tests\event\delete_executed::create(array('context' => context_system::instance()))->trigger();
594
8dcb7ae6
PS
595 // Fake the origin of events.
596 $DB->set_field('logstore_standard_log', 'origin', 'web', array());
597
92927fba
598 $this->assertEquals(7, $DB->count_records('logstore_standard_log'));
599
600 stats_temp_table_fill(9, 11);
601
602 $logs1 = $DB->get_records('temp_log1');
603 $logs2 = $DB->get_records('temp_log2');
604 $this->assertCount(5, $logs1);
605 $this->assertCount(5, $logs2);
606 // The order of records in the temp tables is not guaranteed...
607
608 $viewcount = 0;
609 $updatecount = 0;
610 $logincount = 0;
611 foreach ($logs1 as $log) {
612 if ($log->course == $course->id) {
613 $this->assertEquals('view', $log->action);
614 $viewcount++;
615 } else {
616 $this->assertTrue(in_array($log->action, array('update', 'login')));
617 if ($log->action === 'update') {
618 $updatecount++;
619 } else {
620 $logincount++;
621 }
622 $this->assertEquals(SITEID, $log->course);
623 }
624 $this->assertEquals($user->id, $log->userid);
625 }
626 $this->assertEquals(1, $viewcount);
627 $this->assertEquals(3, $updatecount);
628 $this->assertEquals(1, $logincount);
629
630 set_config('enabled_stores', '', 'tool_log');
631 get_log_manager(true);
632 stats_temp_table_drop();
c0f00c5f
TB
633 }
634
635 /**
636 * Test the temporary table creation and deletion.
637 *
638 * @depends test_statslib_temp_table_create_and_drop
639 */
640 public function test_statslib_temp_table_setup() {
641 global $DB;
642
643 $logs = array();
644 $this->prepare_db($logs, array('log'));
645
646 stats_temp_table_create();
647 stats_temp_table_setup();
648
649 $this->assertEquals(1, $DB->count_records('temp_enroled'));
650
651 stats_temp_table_drop();
652 }
653
654 /**
655 * Test the function that clean out the temporary tables.
656 *
657 * @depends test_statslib_temp_table_create_and_drop
658 */
659 public function test_statslib_temp_table_clean() {
660 global $DB;
661
662 $rows = array(
663 'temp_log1' => array('id' => 1, 'course' => 1),
664 'temp_log2' => array('id' => 1, 'course' => 1),
665 'temp_stats_daily' => array('id' => 1, 'courseid' => 1),
666 'temp_stats_user_daily' => array('id' => 1, 'courseid' => 1),
667 );
668
669 stats_temp_table_create();
670
671 foreach ($rows as $table => $row) {
672 $DB->insert_record_raw($table, $row);
673 $this->assertEquals(1, $DB->count_records($table));
674 }
675
676 stats_temp_table_clean();
677
678 foreach ($rows as $table => $row) {
679 $this->assertEquals(0, $DB->count_records($table));
680 }
681
682 $this->assertEquals(1, $DB->count_records('stats_daily'));
683 $this->assertEquals(1, $DB->count_records('stats_user_daily'));
684
685 stats_temp_table_drop();
686 }
687
688 /**
d53111c0 689 * Test the daily stats function.
c0f00c5f
TB
690 *
691 * @depends test_statslib_get_base_daily
692 * @depends test_statslib_get_next_day_start
67690cfa 693 * @depends test_statslib_get_start_from
c0f00c5f
TB
694 * @depends test_statslib_temp_table_create_and_drop
695 * @depends test_statslib_temp_table_setup
696 * @depends test_statslib_temp_table_fill
697 * @dataProvider daily_log_provider
698 */
ba923f4f 699 public function test_statslib_cron_daily($xmlfile) {
67690cfa 700 global $CFG, $DB;
c0f00c5f 701
ba923f4f
EV
702 $dataset = $this->load_xml_data_file(__DIR__."/fixtures/{$xmlfile}");
703
704 list($logs, $stats) = $dataset;
c0f00c5f
TB
705 $this->prepare_db($logs, array('log'));
706
707 // Stats cron daily uses mtrace, turn on buffering to silence output.
708 ob_start();
709 stats_cron_daily(1);
12ccfc12 710 $output = ob_get_contents();
c0f00c5f
TB
711 ob_end_clean();
712
12ccfc12 713 $this->verify_stats($stats, $output);
c0f00c5f
TB
714 }
715
716 /**
d53111c0
PS
717 * Test the daily stats function.
718 *
c0f00c5f
TB
719 * @depends test_statslib_get_base_daily
720 * @depends test_statslib_get_next_day_start
721 */
722 public function test_statslib_cron_daily_no_default_profile_id() {
723 global $CFG, $DB;
724 $CFG->defaultfrontpageroleid = 0;
725
726 $course1 = $DB->get_record('course', array('shortname' => 'course1'));
727 $guestid = $CFG->siteguest;
728 $start = stats_get_base_daily(1272758400);
729 $end = stats_get_next_day_start($start);
730 $fpid = (int) $CFG->defaultfrontpageroleid;
731 $gr = get_guest_role();
732
733 $dataset = $this->load_xml_data_file(__DIR__."/fixtures/statslib-test10.xml");
734
c0f00c5f
TB
735 $this->prepare_db($dataset[0], array('log'));
736
737 // Stats cron daily uses mtrace, turn on buffering to silence output.
738 ob_start();
739 stats_cron_daily($maxdays=1);
12ccfc12 740 $output = ob_get_contents();
c0f00c5f
TB
741 ob_end_clean();
742
12ccfc12 743 $this->verify_stats($dataset[1], $output);
c0f00c5f
TB
744 }
745}