2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Tests for ../statslib.php
22 * @copyright 2012 Tyler Bannister
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') ||
die();
29 require_once($CFG->libdir
. '/adminlib.php');
30 require_once($CFG->libdir
. '/statslib.php');
31 require_once($CFG->libdir
. '/cronlib.php');
34 * Test functions that affect daily stats
36 class statslib_daily_testcase
extends advanced_testcase
{
37 /** The student role ID **/
40 /** The day to use for testing **/
41 const DAY
= 1272672000;
43 /** The timezone to use for testing **/
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');
49 /** @var array The replacements to be used when loading XML files **/
50 protected $replacements = null;
53 * Set up the database for tests
55 * This function is needed so that daily_log_provider has the before-test set up from setUp()
57 public function setUpDB() {
60 if ($DB->record_exists('user', array('username' => 'user1'))) {
64 $datagen = self
::getDataGenerator();
66 $user1 = $datagen->create_user(array('username'=>'user1'));
67 $user2 = $datagen->create_user(array('username'=>'user2'));
69 $course1 = $datagen->create_course(array('shortname'=>'course1'));
71 $success = enrol_try_internal_enrol($course1->id
, $user1->id
, 5);
74 trigger_error('User enrollment failed', E_USER_ERROR
);
77 $context = context_system
::instance();
78 role_assign(self
::STID
, $user2->id
, $context->id
);
80 $this->generate_replacement_list();
85 * - Allow changes to CFG->debug for testing purposes.
87 protected function setUp() {
91 // Settings to force statistic to run during testing
92 $CFG->timezone
= self
::TIMEZONE
;
93 $CFG->statsfirstrun
= 'all';
94 $CFG->statslastdaily
= 0;
95 $CFG->statslastexecution
= 0;
97 // Figure out the broken day start so I can figure out when to the start time should be
99 $offset = get_timezone_offset($CFG->timezone
);
100 $stime = $time +
$offset;
101 $stime = intval($stime / (60*60*24)) * 60*60*24;
104 $shour = intval(($time - $stime) / (60*60));
106 $CFG->statsruntimestarthour
= $shour;
107 $CFG->statsruntimestartminute
= 0;
111 $this->resetAfterTest(true);
114 protected function tearDown() {
115 // Reset the timeouts.
120 * Function to setup database.
122 * @param array $dataset An array of tables including the log table.
124 protected function prepare_db($dataset, $tables) {
127 foreach ($tables as $tablename) {
128 $DB->delete_records($tablename);
130 foreach ($dataset as $name => $table) {
132 if ($tablename == $name) {
134 $rows = $table->getRowCount();
136 for ($i = 0; $i < $rows; $i++
) {
137 $row = $table->getRow($i);
139 $DB->insert_record($tablename, $row, false, true);
147 * Load dataset from XML file
149 * @param string $file The name of the file to load
151 protected function generate_replacement_list() {
154 if ($this->replacements
!== null) {
158 $CFG->timezone
= self
::TIMEZONE
;
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'));
164 if (($guest === false) ||
($user1 === false) ||
($user2 === false)) {
165 trigger_error('User setup incomplete', E_USER_ERROR
);
168 $site = $DB->get_record('course', array('id' => SITEID
));
169 $course1 = $DB->get_record('course', array('shortname' => 'course1'));
171 if (($site === false) ||
($course1 === false)) {
172 trigger_error('Course setup incomplete', E_USER_ERROR
);
175 $offset = get_timezone_offset($CFG->timezone
);
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();
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),
192 '[guest_id]' => $guest->id
,
193 '[user1_id]' => $user1->id
,
194 '[user2_id]' => $user2->id
,
197 '[course1_id]' => $course1->id
,
198 '[site_id]' => SITEID
,
201 '[frontpage_roleid]' => (int) $CFG->defaultfrontpageroleid
,
202 '[guest_roleid]' => $gr->id
,
203 '[student_roleid]' => self
::STID
,
208 * Load dataset from XML file
210 * @param string $file The name of the file to load
212 protected function load_xml_data_file($file) {
213 static $replacements = null;
215 $raw = $this->createXMLDataSet($file);
216 $clean = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($raw);
218 foreach ($this->replacements
as $placeholder => $value) {
219 $clean->addFullReplacement($placeholder, $value);
222 $logs = new PHPUnit_Extensions_Database_DataSet_DataSetFilter($clean);
223 $logs->addIncludeTables(array('log'));
225 $stats = new PHPUnit_Extensions_Database_DataSet_DataSetFilter($clean);
226 $stats->addIncludeTables(array('stats_daily', 'stats_user_daily'));
228 return array($logs, $stats);
232 * Provides the log data for test_statslib_cron_daily
234 public function daily_log_provider() {
239 $tests = array('00', '01', '02', '03', '04', '05', '06', '07', '08');
243 foreach ($tests as $test) {
244 $dataset[] = $this->load_xml_data_file(__DIR__
."/fixtures/statslib-test{$test}.xml");
251 * Compare the expected stats to those in the database.
253 * @param array $stats An array of arrays of arrays of both types of stats
255 protected function verify_stats($expected, $output = '') {
258 // Note: We can not use $this->assertDataSetEqual($expected, $actual) because there's no
259 // $this->getConnection() in advanced_testcase.
261 foreach ($expected as $type => $table) {
262 $records = $DB->get_records($type);
264 $rows = $table->getRowCount();
266 $message = 'Incorrect number of results returned for '. $type;
269 $message .= "\nCron output:\n$output";
272 $this->assertEquals($rows, sizeof($records), $message);
274 for ($i = 0; $i < $rows; $i++
) {
275 $row = $table->getRow($i);
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));
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]);
298 * Test progress output when debug is on
300 public function test_statslib_progress_debug() {
303 $CFG->debug
= DEBUG_ALL
;
304 $this->expectOutputString('1:0 ');
305 stats_progress('init');
310 * Test progress output when debug is off
312 public function test_statslib_progress_no_debug() {
315 $CFG->debug
= DEBUG_NONE
;
316 $this->expectOutputString('.');
317 stats_progress('init');
322 * Test the function that gets the start date from the config
324 public function test_statslib_get_start_from() {
327 $dataset = $this->load_xml_data_file(__DIR__
."/fixtures/statslib-test01.xml");
329 $DB->delete_records('log');
331 // Don't ask. I don't think get_timezone_offset works correctly.
332 $day = self
::DAY
- get_timezone_offset($CFG->timezone
);
334 $CFG->statsfirstrun
= 'all';
335 // Allow 1 second difference in case we cross a second boundary.
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');
339 $this->prepare_db($dataset[0], array('log'));
340 $records = $DB->get_records('log');
342 $this->assertEquals($day +
14410, stats_get_start_from('daily'), 'Log entry start');
344 $CFG->statsfirstrun
= 'none';
345 $this->assertLessThanOrEqual(1, stats_get_start_from('daily') - strtotime('-3 days', $time), 'None start time');
347 $CFG->statsfirstrun
= 14515200;
348 $this->assertLessThanOrEqual(1, stats_get_start_from('daily') - ($time - (14515200)), 'Specified start time');
350 $this->prepare_db($dataset[1], array('stats_daily'));
351 $this->assertEquals($day +
(24 * 3600), stats_get_start_from('daily'), 'Daily stats start time');
355 * Test the function that calculates the start of the day
357 * NOTE: I don't think this is the way this function should work.
358 * This test documents the current functionality.
360 public function test_statslib_get_base_daily() {
363 for ($x = 0; $x < 24; $x +
= 1) {
366 $start = 1272672000 - ($x * 3600);
368 $start +
= (24 * 3600);
371 $this->assertEquals($start, stats_get_base_daily(1272686410), "Timezone $x check");
376 * Test the function that gets the start of the next day
378 public function test_statslib_get_next_day_start() {
382 $this->assertEquals(1272758400, stats_get_next_day_start(1272686410));
386 * Test the function that gets the action names
388 * Note: The function results depend on installed modules. The hard coded lists are the
389 * defaults for a new Moodle 2.3 install.
391 public function test_statslib_get_action_names() {
392 $basepostactions = array (
398 5 => 'edit sectionenrol',
406 13 => 'submit for grading',
409 16 => 'choose again',
410 17 => 'record delete',
411 18 => 'add discussion',
413 20 => 'delete discussion',
415 22 => 'move discussion',
418 25 => 'add category',
420 27 => 'approve entry',
421 28 => 'delete category',
422 29 => 'delete entry',
423 30 => 'edit category',
424 31 => 'update entry',
428 35 => 'close attempt',
430 37 => 'editquestions',
431 38 => 'delete attempt',
435 $baseviewactions = array (
439 3 => 'view submission',
440 4 => 'view feedback',
443 7 => 'view discussion',
458 $postactions = stats_get_action_names('post');
460 foreach ($basepostactions as $action) {
461 $this->assertContains($action, $postactions);
464 $viewactions = stats_get_action_names('view');
466 foreach ($baseviewactions as $action) {
467 $this->assertContains($action, $viewactions);
472 * Test the temporary table creation and deletion.
474 public function test_statslib_temp_table_create_and_drop() {
477 foreach ($this->tables
as $table) {
478 $this->assertFalse($DB->get_manager()->table_exists($table));
481 stats_temp_table_create();
483 foreach ($this->tables
as $table) {
484 $this->assertTrue($DB->get_manager()->table_exists($table));
487 stats_temp_table_drop();
489 foreach ($this->tables
as $table) {
490 $this->assertFalse($DB->get_manager()->table_exists($table));
495 * Test the temporary table creation and deletion.
497 * @depends test_statslib_temp_table_create_and_drop
499 public function test_statslib_temp_table_fill() {
502 $dataset = $this->load_xml_data_file(__DIR__
."/fixtures/statslib-test09.xml");
504 $this->prepare_db($dataset[0], array('log'));
506 $start = self
::DAY
- get_timezone_offset($CFG->timezone
);
507 $end = $start +
(24 * 3600);
509 stats_temp_table_create();
510 stats_temp_table_fill($start, $end);
512 $this->assertEquals(1, $DB->count_records('temp_log1'));
513 $this->assertEquals(1, $DB->count_records('temp_log2'));
515 stats_temp_table_drop();
519 * Test the temporary table creation and deletion.
521 * @depends test_statslib_temp_table_create_and_drop
523 public function test_statslib_temp_table_setup() {
527 $this->prepare_db($logs, array('log'));
529 stats_temp_table_create();
530 stats_temp_table_setup();
532 $this->assertEquals(1, $DB->count_records('temp_enroled'));
534 stats_temp_table_drop();
538 * Test the function that clean out the temporary tables.
540 * @depends test_statslib_temp_table_create_and_drop
542 public function test_statslib_temp_table_clean() {
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),
552 stats_temp_table_create();
554 foreach ($rows as $table => $row) {
555 $DB->insert_record_raw($table, $row);
556 $this->assertEquals(1, $DB->count_records($table));
559 stats_temp_table_clean();
561 foreach ($rows as $table => $row) {
562 $this->assertEquals(0, $DB->count_records($table));
565 $this->assertEquals(1, $DB->count_records('stats_daily'));
566 $this->assertEquals(1, $DB->count_records('stats_user_daily'));
568 stats_temp_table_drop();
572 * Test the daily stats function
574 * @depends test_statslib_get_base_daily
575 * @depends test_statslib_get_next_day_start
576 * @depends test_statslib_get_start_from
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
582 public function test_statslib_cron_daily($logs, $stats) {
585 $this->prepare_db($logs, array('log'));
587 // Stats cron daily uses mtrace, turn on buffering to silence output.
590 $output = ob_get_contents();
593 $this->verify_stats($stats, $output);
597 * Test the daily stats function
598 * @depends test_statslib_get_base_daily
599 * @depends test_statslib_get_next_day_start
601 public function test_statslib_cron_daily_no_default_profile_id() {
603 $CFG->defaultfrontpageroleid
= 0;
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();
612 $dataset = $this->load_xml_data_file(__DIR__
."/fixtures/statslib-test10.xml");
614 $this->prepare_db($dataset[0], array('log'));
616 // Stats cron daily uses mtrace, turn on buffering to silence output.
618 stats_cron_daily($maxdays=1);
619 $output = ob_get_contents();
622 $this->verify_stats($dataset[1], $output);