first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
@@ -0,0 +1,236 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_backup;
use async_helper;
use backup;
use backup_controller;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
/**
* Asyncronhous helper tests.
*
* @package core_backup
* @covers \async_helper
* @copyright 2018 Matt Porritt <mattp@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class async_helper_test extends \advanced_testcase {
/**
* Tests sending message for asynchronous backup.
*/
public function test_send_message(): void {
global $DB, $USER;
$this->preventResetByRollback();
$this->resetAfterTest(true);
$this->setAdminUser();
set_config('backup_async_message_users', '1', 'backup');
set_config('backup_async_message_subject', 'Moodle {operation} completed sucessfully', 'backup');
set_config('backup_async_message',
'Dear {user_firstname} {user_lastname}, your {operation} (ID: {backupid}) has completed successfully!',
'backup');
set_config('allowedemaildomains', 'example.com');
$generator = $this->getDataGenerator();
$course = $generator->create_course(); // Create a course with some availability data set.
$user2 = $generator->create_user(array('firstname' => 'test', 'lastname' => 'human', 'maildisplay' => 1));
$generator->enrol_user($user2->id, $course->id, 'editingteacher');
$DB->set_field_select('message_processors', 'enabled', 0, "name <> 'email'");
set_user_preference('message_provider_moodle_asyncbackupnotification', 'email', $user2);
// Make the backup controller for an async backup.
$bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
backup::INTERACTIVE_YES, backup::MODE_ASYNC, $user2->id);
$bc->finish_ui();
$backupid = $bc->get_backupid();
$bc->destroy();
$sink = $this->redirectEmails();
// Send message.
$asynchelper = new async_helper('backup', $backupid);
$messageid = $asynchelper->send_message();
$emails = $sink->get_messages();
$this->assertCount(1, $emails);
$email = reset($emails);
$this->assertGreaterThan(0, $messageid);
$sink->clear();
$this->assertSame($USER->email, $email->from);
$this->assertSame($user2->email, $email->to);
$this->assertSame('Moodle Backup completed sucessfully', $email->subject);
// Assert body placeholders have all been replaced.
$this->assertStringContainsString('Dear test human, your Backup', $email->body);
$this->assertStringContainsString("(ID: {$backupid})", $email->body);
$this->assertStringNotContainsString('{', $email->body);
}
/**
* Tests getting the asynchronous backup table items.
*/
public function test_get_async_backups(): void {
global $DB, $CFG, $USER, $PAGE;
$this->resetAfterTest(true);
$this->setAdminUser();
$CFG->enableavailability = true;
$CFG->enablecompletion = true;
// Create a course with some availability data set.
$generator = $this->getDataGenerator();
$course = $generator->create_course(
array('format' => 'topics', 'numsections' => 3,
'enablecompletion' => COMPLETION_ENABLED),
array('createsections' => true));
$forum = $generator->create_module('forum', array(
'course' => $course->id));
$forum2 = $generator->create_module('forum', array(
'course' => $course->id, 'completion' => COMPLETION_TRACKING_MANUAL));
// We need a grade, easiest is to add an assignment.
$assignrow = $generator->create_module('assign', array(
'course' => $course->id));
$assign = new \assign(\context_module::instance($assignrow->cmid), false, false);
$item = $assign->get_grade_item();
// Make a test grouping as well.
$grouping = $generator->create_grouping(array('courseid' => $course->id,
'name' => 'Grouping!'));
$availability = '{"op":"|","show":false,"c":[' .
'{"type":"completion","cm":' . $forum2->cmid .',"e":1},' .
'{"type":"grade","id":' . $item->id . ',"min":4,"max":94},' .
'{"type":"grouping","id":' . $grouping->id . '}' .
']}';
$DB->set_field('course_modules', 'availability', $availability, array(
'id' => $forum->cmid));
$DB->set_field('course_sections', 'availability', $availability, array(
'course' => $course->id, 'section' => 1));
// Make the backup controller for an async backup.
$bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
backup::INTERACTIVE_YES, backup::MODE_ASYNC, $USER->id);
$bc->finish_ui();
$bc->destroy();
unset($bc);
$coursecontext = \context_course::instance($course->id);
$result = \async_helper::get_async_backups('course', $coursecontext->instanceid);
$this->assertEquals(1, count($result));
$this->assertEquals('backup.mbz', $result[0]->filename);
}
/**
* Tests getting the backup record.
*/
public function test_get_backup_record(): void {
global $USER;
$this->resetAfterTest();
$this->setAdminUser();
$generator = $this->getDataGenerator();
$course = $generator->create_course();
// Create the initial backupcontoller.
$bc = new \backup_controller(\backup::TYPE_1COURSE, $course->id, \backup::FORMAT_MOODLE,
\backup::INTERACTIVE_NO, \backup::MODE_COPY, $USER->id, \backup::RELEASESESSION_YES);
$backupid = $bc->get_backupid();
$bc->destroy();
$copyrec = \async_helper::get_backup_record($backupid);
$this->assertEquals($backupid, $copyrec->backupid);
}
/**
* Tests is async pending conditions.
*/
public function test_is_async_pending(): void {
global $USER;
$this->resetAfterTest();
$this->setAdminUser();
$generator = $this->getDataGenerator();
$course = $generator->create_course();
set_config('enableasyncbackup', '0');
$ispending = async_helper::is_async_pending($course->id, 'course', 'backup');
// Should be false as there are no backups and async backup is false.
$this->assertFalse($ispending);
// Create the initial backupcontoller.
$bc = new \backup_controller(\backup::TYPE_1COURSE, $course->id, \backup::FORMAT_MOODLE,
\backup::INTERACTIVE_NO, \backup::MODE_ASYNC, $USER->id, \backup::RELEASESESSION_YES);
$bc->destroy();
$ispending = async_helper::is_async_pending($course->id, 'course', 'backup');
// Should be false as there as async backup is false.
$this->assertFalse($ispending);
set_config('enableasyncbackup', '1');
// Should be true as there as async backup is true and there is a pending backup.
$this->assertFalse($ispending);
}
/**
* Tests is async pending conditions for course copies.
*/
public function test_is_async_pending_copy(): void {
global $USER;
$this->resetAfterTest();
$this->setAdminUser();
$generator = $this->getDataGenerator();
$course = $generator->create_course();
set_config('enableasyncbackup', '0');
$ispending = async_helper::is_async_pending($course->id, 'course', 'backup');
// Should be false as there are no copies and async backup is false.
$this->assertFalse($ispending);
// Create the initial backupcontoller.
$bc = new \backup_controller(\backup::TYPE_1COURSE, $course->id, \backup::FORMAT_MOODLE,
\backup::INTERACTIVE_NO, \backup::MODE_COPY, $USER->id, \backup::RELEASESESSION_YES);
$bc->destroy();
$ispending = async_helper::is_async_pending($course->id, 'course', 'backup');
// Should be True as this a copy operation.
$this->assertTrue($ispending);
set_config('enableasyncbackup', '1');
$ispending = async_helper::is_async_pending($course->id, 'course', 'backup');
// Should be true as there as async backup is true and there is a pending copy.
$this->assertTrue($ispending);
}
}
@@ -0,0 +1,83 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_backup;
use backup_course_task;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
require_once($CFG->dirroot . '/backup/moodle2/backup_course_task.class.php');
/**
* Tests for encoding content links in backup_course_task.
*
* The code that this tests is actually in backup/moodle2/backup_course_task.class.php,
* but there is no place for unit tests near there, and perhaps one day it will
* be refactored so it becomes more generic.
*
* @package core_backup
* @category test
* @copyright 2013 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class backup_encode_content_test extends \basic_testcase {
/**
* Test the encode_content_links method for course.
*/
public function test_course_encode_content_links(): void {
global $CFG;
$httpsroot = "https://moodle.org";
$httproot = "http://moodle.org";
$oldroot = $CFG->wwwroot;
// HTTPS root and links of both types in content.
$CFG->wwwroot = $httpsroot;
$encoded = backup_course_task::encode_content_links(
$httproot . '/course/view.php?id=123, ' .
$httpsroot . '/course/view.php?id=123, ' .
$httpsroot . '/grade/index.php?id=123, ' .
$httpsroot . '/grade/report/index.php?id=123, ' .
$httpsroot . '/badges/view.php?type=2&id=123, ' .
$httpsroot . '/user/index.php?id=123, ' .
$httpsroot . '/pluginfile.php/123 and ' .
urlencode($httpsroot . '/pluginfile.php/123') . '.'
);
$this->assertEquals('$@COURSEVIEWBYID*123@$, $@COURSEVIEWBYID*123@$, $@GRADEINDEXBYID*123@$, ' .
'$@GRADEREPORTINDEXBYID*123@$, $@BADGESVIEWBYID*123@$, $@USERINDEXVIEWBYID*123@$, ' .
'$@PLUGINFILEBYCONTEXT*123@$ and $@PLUGINFILEBYCONTEXTURLENCODED*123@$.', $encoded);
// HTTP root and links of both types in content.
$CFG->wwwroot = $httproot;
$encoded = backup_course_task::encode_content_links(
$httproot . '/course/view.php?id=123, ' .
$httpsroot . '/course/view.php?id=123, ' .
$httproot . '/grade/index.php?id=123, ' .
$httproot . '/grade/report/index.php?id=123, ' .
$httproot . '/badges/view.php?type=2&id=123, ' .
$httproot . '/user/index.php?id=123, ' .
$httproot . '/pluginfile.php/123 and ' .
urlencode($httproot . '/pluginfile.php/123') . '.'
);
$this->assertEquals('$@COURSEVIEWBYID*123@$, $@COURSEVIEWBYID*123@$, $@GRADEINDEXBYID*123@$, ' .
'$@GRADEREPORTINDEXBYID*123@$, $@BADGESVIEWBYID*123@$, $@USERINDEXVIEWBYID*123@$, ' .
'$@PLUGINFILEBYCONTEXT*123@$ and $@PLUGINFILEBYCONTEXTURLENCODED*123@$.', $encoded);
$CFG->wwwroot = $oldroot;
}
}
@@ -0,0 +1,155 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Test the convert helper.
*
* @package core_backup
* @category test
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_backup;
use backup;
use convert_helper;
defined('MOODLE_INTERNAL') || die();
// Include all the needed stuff
global $CFG;
require_once($CFG->dirroot . '/backup/util/helper/convert_helper.class.php');
/**
* Test the convert helper.
*
* @package core_backup
* @category test
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class converterhelper_test extends \basic_testcase {
public function test_choose_conversion_path(): void {
// no converters available
$descriptions = array();
$path = testable_convert_helper::choose_conversion_path(backup::FORMAT_MOODLE1, $descriptions);
$this->assertEquals($path, array());
// missing source and/or targets
$descriptions = array(
// some custom converter
'exporter' => array(
'from' => backup::FORMAT_MOODLE1,
'to' => 'some_custom_format',
'cost' => 10,
),
// another custom converter
'converter' => array(
'from' => 'yet_another_crazy_custom_format',
'to' => backup::FORMAT_MOODLE,
'cost' => 10,
),
);
$path = testable_convert_helper::choose_conversion_path(backup::FORMAT_MOODLE1, $descriptions);
$this->assertEquals($path, array());
$path = testable_convert_helper::choose_conversion_path('some_other_custom_format', $descriptions);
$this->assertEquals($path, array());
// single step conversion
$path = testable_convert_helper::choose_conversion_path('yet_another_crazy_custom_format', $descriptions);
$this->assertEquals($path, array('converter'));
// no conversion needed - this is supposed to be detected by the caller
$path = testable_convert_helper::choose_conversion_path(backup::FORMAT_MOODLE, $descriptions);
$this->assertEquals($path, array());
// two alternatives
$descriptions = array(
// standard moodle 1.9 -> 2.x converter
'moodle1' => array(
'from' => backup::FORMAT_MOODLE1,
'to' => backup::FORMAT_MOODLE,
'cost' => 10,
),
// alternative moodle 1.9 -> 2.x converter
'alternative' => array(
'from' => backup::FORMAT_MOODLE1,
'to' => backup::FORMAT_MOODLE,
'cost' => 8,
)
);
$path = testable_convert_helper::choose_conversion_path(backup::FORMAT_MOODLE1, $descriptions);
$this->assertEquals($path, array('alternative'));
// complex case
$descriptions = array(
// standard moodle 1.9 -> 2.x converter
'moodle1' => array(
'from' => backup::FORMAT_MOODLE1,
'to' => backup::FORMAT_MOODLE,
'cost' => 10,
),
// alternative moodle 1.9 -> 2.x converter
'alternative' => array(
'from' => backup::FORMAT_MOODLE1,
'to' => backup::FORMAT_MOODLE,
'cost' => 8,
),
// custom converter from 1.9 -> custom 'CFv1' format
'cc1' => array(
'from' => backup::FORMAT_MOODLE1,
'to' => 'CFv1',
'cost' => 2,
),
// custom converter from custom 'CFv1' format -> moodle 2.0 format
'cc2' => array(
'from' => 'CFv1',
'to' => backup::FORMAT_MOODLE,
'cost' => 5,
),
// custom converter from CFv1 -> CFv2 format
'cc3' => array(
'from' => 'CFv1',
'to' => 'CFv2',
'cost' => 2,
),
// custom converter from CFv2 -> moodle 2.0 format
'cc4' => array(
'from' => 'CFv2',
'to' => backup::FORMAT_MOODLE,
'cost' => 2,
),
);
// ask the helper to find the most effective way
$path = testable_convert_helper::choose_conversion_path(backup::FORMAT_MOODLE1, $descriptions);
$this->assertEquals($path, array('cc1', 'cc3', 'cc4'));
}
}
/**
* Provides access to the protected methods we need to test
*/
class testable_convert_helper extends convert_helper {
public static function choose_conversion_path($format, array $descriptions) {
return parent::choose_conversion_path($format, $descriptions);
}
}
@@ -0,0 +1,838 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_backup;
use backup;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
require_once($CFG->libdir . '/completionlib.php');
/**
* Course copy tests.
*
* @package core_backup
* @copyright 2020 onward The Moodle Users Association <https://moodleassociation.org/>
* @author Matt Porritt <mattp@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \copy_helper
*/
class copy_helper_test extends \advanced_testcase {
/**
*
* @var \stdClass Course used for testing.
*/
protected $course;
/**
*
* @var int User used to perform backups.
*/
protected $userid;
/**
*
* @var array Ids of users in test course.
*/
protected $courseusers;
/**
*
* @var array Names of the created activities.
*/
protected $activitynames;
/**
* Set up tasks for all tests.
*/
protected function setUp(): void {
global $DB, $CFG, $USER;
$this->resetAfterTest(true);
$CFG->enableavailability = true;
$CFG->enablecompletion = true;
// Create a course with some availability data set.
$generator = $this->getDataGenerator();
$course = $generator->create_course(
array('format' => 'topics', 'numsections' => 3,
'enablecompletion' => COMPLETION_ENABLED),
array('createsections' => true));
$forum = $generator->create_module('forum', array(
'course' => $course->id));
$forum2 = $generator->create_module('forum', array(
'course' => $course->id, 'completion' => COMPLETION_TRACKING_MANUAL));
// We need a grade, easiest is to add an assignment.
$assignrow = $generator->create_module('assign', array(
'course' => $course->id));
$assign = new \assign(\context_module::instance($assignrow->cmid), false, false);
$item = $assign->get_grade_item();
// Make a test grouping as well.
$grouping = $generator->create_grouping(array('courseid' => $course->id,
'name' => 'Grouping!'));
// Create some users.
$user1 = $generator->create_user();
$user2 = $generator->create_user();
$user3 = $generator->create_user();
$user4 = $generator->create_user();
$this->courseusers = array(
$user1->id, $user2->id, $user3->id, $user4->id
);
// Enrol users into the course.
$generator->enrol_user($user1->id, $course->id, 'student');
$generator->enrol_user($user2->id, $course->id, 'editingteacher');
$generator->enrol_user($user3->id, $course->id, 'manager');
$generator->enrol_user($user4->id, $course->id, 'editingteacher');
$generator->enrol_user($user4->id, $course->id, 'manager');
$availability = '{"op":"|","show":false,"c":[' .
'{"type":"completion","cm":' . $forum2->cmid .',"e":1},' .
'{"type":"grade","id":' . $item->id . ',"min":4,"max":94},' .
'{"type":"grouping","id":' . $grouping->id . '}' .
']}';
$DB->set_field('course_modules', 'availability', $availability, array(
'id' => $forum->cmid));
$DB->set_field('course_sections', 'availability', $availability, array(
'course' => $course->id, 'section' => 1));
// Add some user data to the course.
$discussion = $generator->get_plugin_generator('mod_forum')->create_discussion(['course' => $course->id,
'forum' => $forum->id, 'userid' => $user1->id, 'timemodified' => time(),
'name' => 'Frog']);
$generator->get_plugin_generator('mod_forum')->create_post(['discussion' => $discussion->id, 'userid' => $user1->id]);
$this->course = $course;
$this->userid = $USER->id; // Admin.
$this->activitynames = array(
$forum->name,
$forum2->name,
$assignrow->name
);
// Set the user doing the backup to be a manager in the course.
// By default Managers can restore courses AND users, teachers can only do users.
$this->setUser($user3);
// Disable all loggers.
$CFG->backup_error_log_logger_level = backup::LOG_NONE;
$CFG->backup_output_indented_logger_level = backup::LOG_NONE;
$CFG->backup_file_logger_level = backup::LOG_NONE;
$CFG->backup_database_logger_level = backup::LOG_NONE;
$CFG->backup_file_logger_level_extra = backup::LOG_NONE;
}
/**
* Test process form data with invalid data.
*
* @covers ::process_formdata
*/
public function test_process_formdata_missing_fields(): void {
$this->expectException(\moodle_exception::class);
\copy_helper::process_formdata(new \stdClass);
}
/**
* Test processing form data.
*
* @covers ::process_formdata
*/
public function test_process_formdata(): void {
$validformdata = [
'courseid' => 1729,
'fullname' => 'Taxicab Numbers',
'shortname' => 'Taxi101',
'category' => 2,
'visible' => 1,
'startdate' => 87539319,
'enddate' => 6963472309248,
'idnumber' => 1730,
'userdata' => 1
];
$roles = [
'role_one' => 1,
'role_two' => 2,
'role_three' => 0
];
$expected = (object)array_merge($validformdata, ['keptroles' => []]);
$expected->keptroles = [1, 2];
$processed = \copy_helper::process_formdata(
(object)array_merge(
$validformdata,
$roles,
['extra' => 'stuff', 'remove' => 'this'])
);
$this->assertEquals($expected, $processed);
}
/**
* Test orphaned controller cleanup.
*
* @covers ::cleanup_orphaned_copy_controllers
*/
public function test_cleanup_orphaned_copy_controllers(): void {
global $DB;
// Mock up the form data.
$formdata = new \stdClass;
$formdata->courseid = $this->course->id;
$formdata->fullname = 'foo';
$formdata->shortname = 'data1';
$formdata->category = 1;
$formdata->visible = 1;
$formdata->startdate = 1582376400;
$formdata->enddate = 0;
$formdata->idnumber = 123;
$formdata->userdata = 1;
$formdata->role_1 = 1;
$formdata->role_3 = 3;
$formdata->role_5 = 5;
$copies = [];
for ($i = 0; $i < 5; $i++) {
$formdata->shortname = 'data' . $i;
$copies[] = \copy_helper::create_copy($formdata);
}
// Delete one of the restore controllers. Simulates a situation where copy creation
// interrupted and the restore controller never gets created.
$DB->delete_records('backup_controllers', ['backupid' => $copies[0]['restoreid']]);
// Set a backup/restore controller pair to be in an intermediate state.
\backup_controller::load_controller($copies[2]['backupid'])->set_status(backup::STATUS_FINISHED_OK);
// Set a backup/restore controller pair to completed.
\backup_controller::load_controller($copies[3]['backupid'])->set_status(backup::STATUS_FINISHED_OK);
\restore_controller::load_controller($copies[3]['restoreid'])->set_status(backup::STATUS_FINISHED_OK);
// Set a backup/restore controller pair to have a failed backup.
\backup_controller::load_controller($copies[4]['backupid'])->set_status(backup::STATUS_FINISHED_ERR);
// Create some backup/restore controllers that are unrelated to course copies.
$bc = new \backup_controller(backup::TYPE_1COURSE, 1, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_ASYNC,
2, backup::RELEASESESSION_YES);
$rc = new \restore_controller('restore-test-1729', 1, backup::INTERACTIVE_NO, backup::MODE_ASYNC, 1, 2);
$rc->save_controller();
$unrelatedvanillacontrollers = ['backupid' => $bc->get_backupid(), 'restoreid' => $rc->get_restoreid()];
$bc = new \backup_controller(backup::TYPE_1COURSE, 1, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_ASYNC,
2, backup::RELEASESESSION_YES);
$rc = new \restore_controller('restore-test-1729', 1, backup::INTERACTIVE_NO, backup::MODE_ASYNC, 1, 2);
$bc->set_status(backup::STATUS_FINISHED_OK);
$rc->set_status(backup::STATUS_FINISHED_OK);
$unrelatedfinishedcontrollers = ['backupid' => $bc->get_backupid(), 'restoreid' => $rc->get_restoreid()];
$bc = new \backup_controller(backup::TYPE_1COURSE, 1, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_ASYNC,
2, backup::RELEASESESSION_YES);
$rc = new \restore_controller('restore-test-1729', 1, backup::INTERACTIVE_NO, backup::MODE_ASYNC, 1, 2);
$bc->set_status(backup::STATUS_FINISHED_ERR);
$rc->set_status(backup::STATUS_FINISHED_ERR);
$unrelatedfailedcontrollers = ['backupid' => $bc->get_backupid(), 'restoreid' => $rc->get_restoreid()];
// Clean up the backup_controllers table.
$records = $DB->get_records('backup_controllers', null, '', 'id, backupid, status, operation, purpose, timecreated');
\copy_helper::cleanup_orphaned_copy_controllers($records, 0);
// Retrieve them again and check.
$records = $DB->get_records('backup_controllers', null, '', 'backupid, status');
// Verify the backup associated with the deleted restore is marked as failed.
$this->assertEquals(backup::STATUS_FINISHED_ERR, $records[$copies[0]['backupid']]->status);
// Verify other controllers remain untouched.
$this->assertEquals(backup::STATUS_AWAITING, $records[$copies[1]['backupid']]->status);
$this->assertEquals(backup::STATUS_REQUIRE_CONV, $records[$copies[1]['restoreid']]->status);
$this->assertEquals(backup::STATUS_FINISHED_OK, $records[$copies[2]['backupid']]->status);
$this->assertEquals(backup::STATUS_REQUIRE_CONV, $records[$copies[2]['restoreid']]->status);
$this->assertEquals(backup::STATUS_FINISHED_OK, $records[$copies[3]['restoreid']]->status);
$this->assertEquals(backup::STATUS_FINISHED_OK, $records[$copies[3]['backupid']]->status);
// Verify that the restore associated with the failed backup is also marked as failed.
$this->assertEquals(backup::STATUS_FINISHED_ERR, $records[$copies[4]['restoreid']]->status);
// Verify that the unrelated controllers remain unchanged.
$this->assertEquals(backup::STATUS_AWAITING, $records[$unrelatedvanillacontrollers['backupid']]->status);
$this->assertEquals(backup::STATUS_REQUIRE_CONV, $records[$unrelatedvanillacontrollers['restoreid']]->status);
$this->assertEquals(backup::STATUS_FINISHED_OK, $records[$unrelatedfinishedcontrollers['backupid']]->status);
$this->assertEquals(backup::STATUS_FINISHED_OK, $records[$unrelatedfinishedcontrollers['restoreid']]->status);
$this->assertEquals(backup::STATUS_FINISHED_ERR, $records[$unrelatedfailedcontrollers['backupid']]->status);
$this->assertEquals(backup::STATUS_FINISHED_ERR, $records[$unrelatedfailedcontrollers['restoreid']]->status);
}
/**
* Test creating a course copy.
*
* @covers ::create_copy
*/
public function test_create_copy(): void {
// Mock up the form data.
$formdata = new \stdClass;
$formdata->courseid = $this->course->id;
$formdata->fullname = 'foo';
$formdata->shortname = 'bar';
$formdata->category = 1;
$formdata->visible = 1;
$formdata->startdate = 1582376400;
$formdata->enddate = 0;
$formdata->idnumber = 123;
$formdata->userdata = 1;
$formdata->role_1 = 1;
$formdata->role_3 = 3;
$formdata->role_5 = 5;
$copydata = \copy_helper::process_formdata($formdata);
$result = \copy_helper::create_copy($copydata);
// Load the controllers, to extract the data we need.
$bc = \backup_controller::load_controller($result['backupid']);
$rc = \restore_controller::load_controller($result['restoreid']);
// Check the backup controller.
$this->assertEquals(backup::MODE_COPY, $bc->get_mode());
$this->assertEquals($this->course->id, $bc->get_courseid());
$this->assertEquals(backup::TYPE_1COURSE, $bc->get_type());
// Check the restore controller.
$newcourseid = $rc->get_courseid();
$newcourse = get_course($newcourseid);
$this->assertEquals(get_string('copyingcourse', 'backup'), $newcourse->fullname);
$this->assertEquals(get_string('copyingcourseshortname', 'backup'), $newcourse->shortname);
$this->assertEquals(backup::MODE_COPY, $rc->get_mode());
$this->assertEquals($newcourseid, $rc->get_courseid());
// Check the created ad-hoc task.
$now = time();
$task = \core\task\manager::get_next_adhoc_task($now);
$this->assertInstanceOf('\\core\\task\\asynchronous_copy_task', $task);
$this->assertEquals($result, (array)$task->get_custom_data());
\core\task\manager::adhoc_task_complete($task);
}
/**
* Test getting the current copies.
*
* @covers ::get_copies
*/
public function test_get_copies(): void {
global $USER;
// Mock up the form data.
$formdata = new \stdClass;
$formdata->courseid = $this->course->id;
$formdata->fullname = 'foo';
$formdata->shortname = 'bar';
$formdata->category = 1;
$formdata->visible = 1;
$formdata->startdate = 1582376400;
$formdata->enddate = 0;
$formdata->idnumber = '';
$formdata->userdata = 1;
$formdata->role_1 = 1;
$formdata->role_3 = 3;
$formdata->role_5 = 5;
$formdata2 = clone($formdata);
$formdata2->shortname = 'tree';
// Create some copies.
$copydata = \copy_helper::process_formdata($formdata);
$result = \copy_helper::create_copy($copydata);
// Backup, awaiting.
$copies = \copy_helper::get_copies($USER->id);
$this->assertEquals($result['backupid'], $copies[0]->backupid);
$this->assertEquals($result['restoreid'], $copies[0]->restoreid);
$this->assertEquals(\backup::STATUS_AWAITING, $copies[0]->status);
$this->assertEquals(\backup::OPERATION_BACKUP, $copies[0]->operation);
$bc = \backup_controller::load_controller($result['backupid']);
// Backup, in progress.
$bc->set_status(\backup::STATUS_EXECUTING);
$copies = \copy_helper::get_copies($USER->id);
$this->assertEquals($result['backupid'], $copies[0]->backupid);
$this->assertEquals($result['restoreid'], $copies[0]->restoreid);
$this->assertEquals(\backup::STATUS_EXECUTING, $copies[0]->status);
$this->assertEquals(\backup::OPERATION_BACKUP, $copies[0]->operation);
// Restore, ready to process.
$bc->set_status(\backup::STATUS_FINISHED_OK);
$copies = \copy_helper::get_copies($USER->id);
$this->assertEquals(null, $copies[0]->backupid);
$this->assertEquals($result['restoreid'], $copies[0]->restoreid);
$this->assertEquals(\backup::STATUS_REQUIRE_CONV, $copies[0]->status);
$this->assertEquals(\backup::OPERATION_RESTORE, $copies[0]->operation);
// No records.
$bc->set_status(\backup::STATUS_FINISHED_ERR);
$copies = \copy_helper::get_copies($USER->id);
$this->assertEmpty($copies);
$copydata2 = \copy_helper::process_formdata($formdata2);
$result2 = \copy_helper::create_copy($copydata2);
// Set the second copy to be complete.
$bc = \backup_controller::load_controller($result2['backupid']);
$bc->set_status(\backup::STATUS_FINISHED_OK);
// Set the restore to be finished.
$rc = \backup_controller::load_controller($result2['restoreid']);
$rc->set_status(\backup::STATUS_FINISHED_OK);
// No records.
$copies = \copy_helper::get_copies($USER->id);
$this->assertEmpty($copies);
}
/**
* Test getting the current copies when they are in an invalid state.
*
* @covers ::get_copies
*/
public function test_get_copies_invalid_state(): void {
global $DB, $USER;
// Mock up the form data.
$formdata = new \stdClass;
$formdata->courseid = $this->course->id;
$formdata->fullname = 'foo';
$formdata->shortname = 'bar';
$formdata->category = 1;
$formdata->visible = 1;
$formdata->startdate = 1582376400;
$formdata->enddate = 0;
$formdata->idnumber = '';
$formdata->userdata = 1;
$formdata->role_1 = 1;
$formdata->role_3 = 3;
$formdata->role_5 = 5;
$formdata2 = clone ($formdata);
$formdata2->shortname = 'tree';
// Create some copies.
$copydata = \copy_helper::process_formdata($formdata);
$result = \copy_helper::create_copy($copydata);
$copydata2 = \copy_helper::process_formdata($formdata2);
$result2 = \copy_helper::create_copy($copydata2);
$copies = \copy_helper::get_copies($USER->id);
// Verify get_copies gives back both backup controllers.
$this->assertEqualsCanonicalizing([$result['backupid'], $result2['backupid']], array_column($copies, 'backupid'));
// Set one of the backup controllers to failed, this should cause it to not be present.
\backup_controller::load_controller($result['backupid'])->set_status(backup::STATUS_FINISHED_ERR);
$copies = \copy_helper::get_copies($USER->id);
// Verify there is only one backup listed, and that it is not the failed one.
$this->assertEqualsCanonicalizing([$result2['backupid']], array_column($copies, 'backupid'));
// Set the controller back to awaiting.
\backup_controller::load_controller($result['backupid'])->set_status(backup::STATUS_AWAITING);
$copies = \copy_helper::get_copies($USER->id);
// Verify both backup controllers are back.
$this->assertEqualsCanonicalizing([$result['backupid'], $result2['backupid']], array_column($copies, 'backupid'));
// Delete the restore controller for one of the copies, this should cause it to not be present.
$DB->delete_records('backup_controllers', ['backupid' => $result['restoreid']]);
$copies = \copy_helper::get_copies($USER->id);
// Verify there is only one backup listed, and that it is not the failed one.
$this->assertEqualsCanonicalizing([$result2['backupid']], array_column($copies, 'backupid'));
}
/**
* Test getting the current copies for specific course.
*
* @covers ::get_copies
*/
public function test_get_copies_course(): void {
global $USER;
// Mock up the form data.
$formdata = new \stdClass;
$formdata->courseid = $this->course->id;
$formdata->fullname = 'foo';
$formdata->shortname = 'bar';
$formdata->category = 1;
$formdata->visible = 1;
$formdata->startdate = 1582376400;
$formdata->enddate = 0;
$formdata->idnumber = '';
$formdata->userdata = 1;
$formdata->role_1 = 1;
$formdata->role_3 = 3;
$formdata->role_5 = 5;
// Create some copies.
$copydata = \copy_helper::process_formdata($formdata);
\copy_helper::create_copy($copydata);
// No copies match this course id.
$copies = \copy_helper::get_copies($USER->id, ($this->course->id + 1));
$this->assertEmpty($copies);
}
/**
* Test getting the current copies if course has been deleted.
*
* @covers ::get_copies
*/
public function test_get_copies_course_deleted(): void {
global $USER;
// Mock up the form data.
$formdata = new \stdClass;
$formdata->courseid = $this->course->id;
$formdata->fullname = 'foo';
$formdata->shortname = 'bar';
$formdata->category = 1;
$formdata->visible = 1;
$formdata->startdate = 1582376400;
$formdata->enddate = 0;
$formdata->idnumber = '';
$formdata->userdata = 1;
$formdata->role_1 = 1;
$formdata->role_3 = 3;
$formdata->role_5 = 5;
// Create some copies.
$copydata = \copy_helper::process_formdata($formdata);
\copy_helper::create_copy($copydata);
delete_course($this->course->id, false);
// No copies match this course id as it has been deleted.
$copies = \copy_helper::get_copies($USER->id, ($this->course->id));
$this->assertEmpty($copies);
}
/**
* Test course copy.
*/
public function test_course_copy(): void {
global $DB;
// Mock up the form data.
$formdata = new \stdClass;
$formdata->courseid = $this->course->id;
$formdata->fullname = 'copy course';
$formdata->shortname = 'copy course short';
$formdata->category = 1;
$formdata->visible = 0;
$formdata->startdate = 1582376400;
$formdata->enddate = 1582386400;
$formdata->idnumber = 123;
$formdata->userdata = 1;
$formdata->role_1 = 1;
$formdata->role_3 = 3;
$formdata->role_5 = 5;
// Create the course copy records and associated ad-hoc task.
$copydata = \copy_helper::process_formdata($formdata);
$copyids = \copy_helper::create_copy($copydata);
$courseid = $this->course->id;
// We are expecting trace output during this test.
$this->expectOutputRegex("/$courseid/");
// Execute adhoc task.
$now = time();
$task = \core\task\manager::get_next_adhoc_task($now);
$this->assertInstanceOf('\\core\\task\\asynchronous_copy_task', $task);
$task->execute();
\core\task\manager::adhoc_task_complete($task);
$postbackuprec = $DB->get_record('backup_controllers', array('backupid' => $copyids['backupid']));
$postrestorerec = $DB->get_record('backup_controllers', array('backupid' => $copyids['restoreid']));
// Check backup was completed successfully.
$this->assertEquals(backup::STATUS_FINISHED_OK, $postbackuprec->status);
$this->assertEquals(1.0, $postbackuprec->progress);
// Check restore was completed successfully.
$this->assertEquals(backup::STATUS_FINISHED_OK, $postrestorerec->status);
$this->assertEquals(1.0, $postrestorerec->progress);
// Check the restored course itself.
$coursecontext = \context_course::instance($postrestorerec->itemid);
$users = get_enrolled_users($coursecontext);
$modinfo = get_fast_modinfo($postrestorerec->itemid);
$forums = $modinfo->get_instances_of('forum');
$forum = reset($forums);
$discussions = forum_get_discussions($forum);
$course = $modinfo->get_course();
$this->assertEquals($formdata->startdate, $course->startdate);
$this->assertEquals($formdata->enddate, $course->enddate);
$this->assertEquals('copy course', $course->fullname);
$this->assertEquals('copy course short', $course->shortname);
$this->assertEquals(0, $course->visible);
$this->assertEquals(123, $course->idnumber);
foreach ($modinfo->get_cms() as $cm) {
$this->assertContains($cm->get_formatted_name(), $this->activitynames);
}
foreach ($this->courseusers as $user) {
$this->assertEquals($user, $users[$user]->id);
}
$this->assertEquals(count($this->courseusers), count($users));
$this->assertEquals(2, count($discussions));
}
/**
* Test course copy, not including any users (or data).
*/
public function test_course_copy_no_users(): void {
global $DB;
// Mock up the form data.
$formdata = new \stdClass;
$formdata->courseid = $this->course->id;
$formdata->fullname = 'copy course';
$formdata->shortname = 'copy course short';
$formdata->category = 1;
$formdata->visible = 0;
$formdata->startdate = 1582376400;
$formdata->enddate = 1582386400;
$formdata->idnumber = 123;
$formdata->userdata = 1;
$formdata->role_1 = 0;
$formdata->role_3 = 0;
$formdata->role_5 = 0;
// Create the course copy records and associated ad-hoc task.
$copydata = \copy_helper::process_formdata($formdata);
$copyids = \copy_helper::create_copy($copydata);
$courseid = $this->course->id;
// We are expecting trace output during this test.
$this->expectOutputRegex("/$courseid/");
// Execute adhoc task.
$now = time();
$task = \core\task\manager::get_next_adhoc_task($now);
$this->assertInstanceOf('\\core\\task\\asynchronous_copy_task', $task);
$task->execute();
\core\task\manager::adhoc_task_complete($task);
$postrestorerec = $DB->get_record('backup_controllers', array('backupid' => $copyids['restoreid']));
// Check the restored course itself.
$coursecontext = \context_course::instance($postrestorerec->itemid);
$users = get_enrolled_users($coursecontext);
$modinfo = get_fast_modinfo($postrestorerec->itemid);
$forums = $modinfo->get_instances_of('forum');
$forum = reset($forums);
$discussions = forum_get_discussions($forum);
$course = $modinfo->get_course();
$this->assertEquals($formdata->startdate, $course->startdate);
$this->assertEquals($formdata->enddate, $course->enddate);
$this->assertEquals('copy course', $course->fullname);
$this->assertEquals('copy course short', $course->shortname);
$this->assertEquals(0, $course->visible);
$this->assertEquals(123, $course->idnumber);
foreach ($modinfo->get_cms() as $cm) {
$this->assertContains($cm->get_formatted_name(), $this->activitynames);
}
// Should be no discussions as the user that made them wasn't included.
$this->assertEquals(0, count($discussions));
// There should only be one user in the new course, and that's the user who did the copy.
$this->assertEquals(1, count($users));
$this->assertEquals($this->courseusers[2], $users[$this->courseusers[2]]->id);
}
/**
* Test course copy, including students and their data.
*/
public function test_course_copy_students_data(): void {
global $DB;
// Mock up the form data.
$formdata = new \stdClass;
$formdata->courseid = $this->course->id;
$formdata->fullname = 'copy course';
$formdata->shortname = 'copy course short';
$formdata->category = 1;
$formdata->visible = 0;
$formdata->startdate = 1582376400;
$formdata->enddate = 1582386400;
$formdata->idnumber = 123;
$formdata->userdata = 1;
$formdata->role_1 = 0;
$formdata->role_3 = 0;
$formdata->role_5 = 5;
// Create the course copy records and associated ad-hoc task.
$copydata = \copy_helper::process_formdata($formdata);
$copyids = \copy_helper::create_copy($copydata);
$courseid = $this->course->id;
// We are expecting trace output during this test.
$this->expectOutputRegex("/$courseid/");
// Execute adhoc task.
$now = time();
$task = \core\task\manager::get_next_adhoc_task($now);
$this->assertInstanceOf('\\core\\task\\asynchronous_copy_task', $task);
$task->execute();
\core\task\manager::adhoc_task_complete($task);
$postrestorerec = $DB->get_record('backup_controllers', array('backupid' => $copyids['restoreid']));
// Check the restored course itself.
$coursecontext = \context_course::instance($postrestorerec->itemid);
$users = get_enrolled_users($coursecontext);
$modinfo = get_fast_modinfo($postrestorerec->itemid);
$forums = $modinfo->get_instances_of('forum');
$forum = reset($forums);
$discussions = forum_get_discussions($forum);
$course = $modinfo->get_course();
$this->assertEquals($formdata->startdate, $course->startdate);
$this->assertEquals($formdata->enddate, $course->enddate);
$this->assertEquals('copy course', $course->fullname);
$this->assertEquals('copy course short', $course->shortname);
$this->assertEquals(0, $course->visible);
$this->assertEquals(123, $course->idnumber);
foreach ($modinfo->get_cms() as $cm) {
$this->assertContains($cm->get_formatted_name(), $this->activitynames);
}
// Should be no discussions as the user that made them wasn't included.
$this->assertEquals(2, count($discussions));
// There should only be two users in the new course. The copier and one student.
$this->assertEquals(2, count($users));
$this->assertEquals($this->courseusers[2], $users[$this->courseusers[2]]->id);
$this->assertEquals($this->courseusers[0], $users[$this->courseusers[0]]->id);
}
/**
* Test course copy, not including any users (or data).
*/
public function test_course_copy_no_data(): void {
global $DB;
// Mock up the form data.
$formdata = new \stdClass;
$formdata->courseid = $this->course->id;
$formdata->fullname = 'copy course';
$formdata->shortname = 'copy course short';
$formdata->category = 1;
$formdata->visible = 0;
$formdata->startdate = 1582376400;
$formdata->enddate = 1582386400;
$formdata->idnumber = 123;
$formdata->userdata = 0;
$formdata->role_1 = 1;
$formdata->role_3 = 3;
$formdata->role_5 = 5;
// Create the course copy records and associated ad-hoc task.
$copydata = \copy_helper::process_formdata($formdata);
$copyids = \copy_helper::create_copy($copydata);
$courseid = $this->course->id;
// We are expecting trace output during this test.
$this->expectOutputRegex("/$courseid/");
// Execute adhoc task.
$now = time();
$task = \core\task\manager::get_next_adhoc_task($now);
$this->assertInstanceOf('\\core\\task\\asynchronous_copy_task', $task);
$task->execute();
\core\task\manager::adhoc_task_complete($task);
$postrestorerec = $DB->get_record('backup_controllers', array('backupid' => $copyids['restoreid']));
// Check the restored course itself.
$coursecontext = \context_course::instance($postrestorerec->itemid);
$users = get_enrolled_users($coursecontext);
get_fast_modinfo($postrestorerec->itemid, 0, true);
$modinfo = get_fast_modinfo($postrestorerec->itemid);
$forums = $modinfo->get_instances_of('forum');
$forum = reset($forums);
$discussions = forum_get_discussions($forum);
$course = $modinfo->get_course();
$this->assertEquals($formdata->startdate, $course->startdate);
$this->assertEquals($formdata->enddate, $course->enddate);
$this->assertEquals('copy course', $course->fullname);
$this->assertEquals('copy course short', $course->shortname);
$this->assertEquals(0, $course->visible);
$this->assertEquals(123, $course->idnumber);
foreach ($modinfo->get_cms() as $cm) {
$this->assertContains($cm->get_formatted_name(), $this->activitynames);
}
// Should be no discussions as the user data wasn't included.
$this->assertEquals(0, count($discussions));
// There should only be all users in the new course.
$this->assertEquals(count($this->courseusers), count($users));
}
/**
* Test instantiation with incomplete formdata.
*/
public function test_malformed_instantiation(): void {
// Mock up the form data, missing things so we get an exception.
$formdata = new \stdClass;
$formdata->courseid = $this->course->id;
$formdata->fullname = 'copy course';
$formdata->shortname = 'copy course short';
$formdata->category = 1;
// Expect and exception as form data is incomplete.
$this->expectException(\moodle_exception::class);
$copydata = \copy_helper::process_formdata($formdata);
\copy_helper::create_copy($copydata);
}
}
@@ -0,0 +1,520 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for backups cron helper.
*
* @package core_backup
* @category test
* @copyright 2012 Frédéric Massart <fred@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_backup;
use backup;
use backup_cron_automated_helper;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php');
require_once($CFG->dirroot . '/backup/util/interfaces/checksumable.class.php');
require_once("$CFG->dirroot/backup/backup.class.php");
/**
* Unit tests for backups cron helper.
*
* @package core_backup
* @category test
* @copyright 2012 Frédéric Massart <fred@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cronhelper_test extends \advanced_testcase {
/**
* Test {@link backup_cron_automated_helper::calculate_next_automated_backup}.
*/
public function test_next_automated_backup(): void {
global $CFG;
$this->resetAfterTest();
set_config('backup_auto_active', '1', 'backup');
$this->setTimezone('Australia/Perth');
// Notes
// - backup_auto_weekdays starts on Sunday
// - Tests cannot be done in the past
// - Only the DST on the server side is handled.
// Every Tue and Fri at 11pm.
set_config('backup_auto_weekdays', '0010010', 'backup');
set_config('backup_auto_hour', '23', 'backup');
set_config('backup_auto_minute', '0', 'backup');
$timezone = 99; // Ignored, everything is calculated in server timezone!!!
$now = strtotime('next Monday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('2-23:00', date('w-H:i', $next));
$now = strtotime('next Tuesday 18:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('2-23:00', date('w-H:i', $next));
$now = strtotime('next Wednesday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('5-23:00', date('w-H:i', $next));
$now = strtotime('next Thursday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('5-23:00', date('w-H:i', $next));
$now = strtotime('next Friday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('5-23:00', date('w-H:i', $next));
$now = strtotime('next Saturday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('2-23:00', date('w-H:i', $next));
$now = strtotime('next Sunday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('2-23:00', date('w-H:i', $next));
// Every Sun and Sat at 12pm.
set_config('backup_auto_weekdays', '1000001', 'backup');
set_config('backup_auto_hour', '0', 'backup');
set_config('backup_auto_minute', '0', 'backup');
$now = strtotime('next Monday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('6-00:00', date('w-H:i', $next));
$now = strtotime('next Tuesday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('6-00:00', date('w-H:i', $next));
$now = strtotime('next Wednesday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('6-00:00', date('w-H:i', $next));
$now = strtotime('next Thursday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('6-00:00', date('w-H:i', $next));
$now = strtotime('next Friday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('6-00:00', date('w-H:i', $next));
$now = strtotime('next Saturday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('0-00:00', date('w-H:i', $next));
$now = strtotime('next Sunday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('6-00:00', date('w-H:i', $next));
// Every Sun at 4am.
set_config('backup_auto_weekdays', '1000000', 'backup');
set_config('backup_auto_hour', '4', 'backup');
set_config('backup_auto_minute', '0', 'backup');
$now = strtotime('next Monday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('0-04:00', date('w-H:i', $next));
$now = strtotime('next Tuesday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('0-04:00', date('w-H:i', $next));
$now = strtotime('next Wednesday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('0-04:00', date('w-H:i', $next));
$now = strtotime('next Thursday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('0-04:00', date('w-H:i', $next));
$now = strtotime('next Friday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('0-04:00', date('w-H:i', $next));
$now = strtotime('next Saturday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('0-04:00', date('w-H:i', $next));
$now = strtotime('next Sunday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('0-04:00', date('w-H:i', $next));
// Every day but Wed at 8:30pm.
set_config('backup_auto_weekdays', '1110111', 'backup');
set_config('backup_auto_hour', '20', 'backup');
set_config('backup_auto_minute', '30', 'backup');
$now = strtotime('next Monday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('1-20:30', date('w-H:i', $next));
$now = strtotime('next Tuesday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('2-20:30', date('w-H:i', $next));
$now = strtotime('next Wednesday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('4-20:30', date('w-H:i', $next));
$now = strtotime('next Thursday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('4-20:30', date('w-H:i', $next));
$now = strtotime('next Friday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('5-20:30', date('w-H:i', $next));
$now = strtotime('next Saturday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('6-20:30', date('w-H:i', $next));
$now = strtotime('next Sunday 17:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('0-20:30', date('w-H:i', $next));
// Sun, Tue, Thu, Sat at 12pm.
set_config('backup_auto_weekdays', '1010101', 'backup');
set_config('backup_auto_hour', '0', 'backup');
set_config('backup_auto_minute', '0', 'backup');
$now = strtotime('next Monday 13:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('2-00:00', date('w-H:i', $next));
$now = strtotime('next Tuesday 13:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('4-00:00', date('w-H:i', $next));
$now = strtotime('next Wednesday 13:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('4-00:00', date('w-H:i', $next));
$now = strtotime('next Thursday 13:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('6-00:00', date('w-H:i', $next));
$now = strtotime('next Friday 13:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('6-00:00', date('w-H:i', $next));
$now = strtotime('next Saturday 13:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('0-00:00', date('w-H:i', $next));
$now = strtotime('next Sunday 13:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('2-00:00', date('w-H:i', $next));
// None.
set_config('backup_auto_weekdays', '0000000', 'backup');
set_config('backup_auto_hour', '15', 'backup');
set_config('backup_auto_minute', '30', 'backup');
$now = strtotime('next Sunday 13:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals('0', $next);
// Playing with timezones.
set_config('backup_auto_weekdays', '1111111', 'backup');
set_config('backup_auto_hour', '20', 'backup');
set_config('backup_auto_minute', '00', 'backup');
$this->setTimezone('Australia/Perth');
$now = strtotime('18:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals(date('w-20:00'), date('w-H:i', $next));
$this->setTimezone('Europe/Brussels');
$now = strtotime('18:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals(date('w-20:00'), date('w-H:i', $next));
$this->setTimezone('America/New_York');
$now = strtotime('18:00:00');
$next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now);
$this->assertEquals(date('w-20:00'), date('w-H:i', $next));
}
/**
* Test {@link backup_cron_automated_helper::get_backups_to_delete}.
*/
public function test_get_backups_to_delete(): void {
$this->resetAfterTest();
// Active only backup_auto_max_kept config to 2 days.
set_config('backup_auto_max_kept', '2', 'backup');
set_config('backup_auto_delete_days', '0', 'backup');
set_config('backup_auto_min_kept', '0', 'backup');
// No backups to delete.
$backupfiles = array(
'1000000000' => 'file1.mbz',
'1000432000' => 'file3.mbz'
);
$deletedbackups = testable_backup_cron_automated_helper::testable_get_backups_to_delete($backupfiles, 1000432000);
$this->assertFalse($deletedbackups);
// Older backup to delete.
$backupfiles['1000172800'] = 'file2.mbz';
$deletedbackups = testable_backup_cron_automated_helper::testable_get_backups_to_delete($backupfiles, 1000432000);
$this->assertEquals(1, count($deletedbackups));
$this->assertArrayHasKey('1000000000', $backupfiles);
$this->assertEquals('file1.mbz', $backupfiles['1000000000']);
// Activate backup_auto_max_kept to 5 days and backup_auto_delete_days to 10 days.
set_config('backup_auto_max_kept', '5', 'backup');
set_config('backup_auto_delete_days', '10', 'backup');
set_config('backup_auto_min_kept', '0', 'backup');
// No backups to delete. Timestamp is 1000000000 + 10 days.
$backupfiles['1000432001'] = 'file4.mbz';
$backupfiles['1000864000'] = 'file5.mbz';
$deletedbackups = testable_backup_cron_automated_helper::testable_get_backups_to_delete($backupfiles, 1000864000);
$this->assertFalse($deletedbackups);
// One old backup to delete. Timestamp is 1000000000 + 10 days + 1 second.
$deletedbackups = testable_backup_cron_automated_helper::testable_get_backups_to_delete($backupfiles, 1000864001);
$this->assertEquals(1, count($deletedbackups));
$this->assertArrayHasKey('1000000000', $backupfiles);
$this->assertEquals('file1.mbz', $backupfiles['1000000000']);
// Two old backups to delete. Timestamp is 1000000000 + 12 days + 1 second.
$deletedbackups = testable_backup_cron_automated_helper::testable_get_backups_to_delete($backupfiles, 1001036801);
$this->assertEquals(2, count($deletedbackups));
$this->assertArrayHasKey('1000000000', $backupfiles);
$this->assertEquals('file1.mbz', $backupfiles['1000000000']);
$this->assertArrayHasKey('1000172800', $backupfiles);
$this->assertEquals('file2.mbz', $backupfiles['1000172800']);
// Activate backup_auto_max_kept to 5 days, backup_auto_delete_days to 10 days and backup_auto_min_kept to 2.
set_config('backup_auto_max_kept', '5', 'backup');
set_config('backup_auto_delete_days', '10', 'backup');
set_config('backup_auto_min_kept', '2', 'backup');
// Three instead of four old backups are deleted. Timestamp is 1000000000 + 16 days.
$deletedbackups = testable_backup_cron_automated_helper::testable_get_backups_to_delete($backupfiles, 1001382400);
$this->assertEquals(3, count($deletedbackups));
$this->assertArrayHasKey('1000000000', $backupfiles);
$this->assertEquals('file1.mbz', $backupfiles['1000000000']);
$this->assertArrayHasKey('1000172800', $backupfiles);
$this->assertEquals('file2.mbz', $backupfiles['1000172800']);
$this->assertArrayHasKey('1000432000', $backupfiles);
$this->assertEquals('file3.mbz', $backupfiles['1000432000']);
// Three instead of all five backups are deleted. Timestamp is 1000000000 + 60 days.
$deletedbackups = testable_backup_cron_automated_helper::testable_get_backups_to_delete($backupfiles, 1005184000);
$this->assertEquals(3, count($deletedbackups));
$this->assertArrayHasKey('1000000000', $backupfiles);
$this->assertEquals('file1.mbz', $backupfiles['1000000000']);
$this->assertArrayHasKey('1000172800', $backupfiles);
$this->assertEquals('file2.mbz', $backupfiles['1000172800']);
$this->assertArrayHasKey('1000432000', $backupfiles);
$this->assertEquals('file3.mbz', $backupfiles['1000432000']);
}
/**
* Test {@link backup_cron_automated_helper::is_course_modified}.
*/
public function test_is_course_modified(): void {
$this->resetAfterTest();
$this->preventResetByRollback();
set_config('enabled_stores', 'logstore_standard', 'tool_log');
set_config('buffersize', 0, 'logstore_standard');
set_config('logguests', 1, 'logstore_standard');
$course = $this->getDataGenerator()->create_course();
// New courses should be backed up.
$this->assertTrue(testable_backup_cron_automated_helper::testable_is_course_modified($course->id, 0));
$timepriortobackup = time();
$this->waitForSecond();
$otherarray = [
'format' => backup::FORMAT_MOODLE,
'mode' => backup::MODE_GENERAL,
'interactive' => backup::INTERACTIVE_YES,
'type' => backup::TYPE_1COURSE,
];
$event = \core\event\course_backup_created::create([
'objectid' => $course->id,
'context' => \context_course::instance($course->id),
'other' => $otherarray
]);
$event->trigger();
// If the only action since last backup was a backup then no backup.
$this->assertFalse(testable_backup_cron_automated_helper::testable_is_course_modified($course->id, $timepriortobackup));
$course->groupmode = SEPARATEGROUPS;
$course->groupmodeforce = true;
update_course($course);
// Updated courses should be backed up.
$this->assertTrue(testable_backup_cron_automated_helper::testable_is_course_modified($course->id, $timepriortobackup));
}
/**
* Create courses and backup records for tests.
*
* @return array Created courses.
*/
private function course_setup() {
global $DB;
// Create test courses.
$course1 = $this->getDataGenerator()->create_course(array('timecreated' => 1553402000)); // Newest.
$course2 = $this->getDataGenerator()->create_course(array('timecreated' => 1552179600));
$course3 = $this->getDataGenerator()->create_course(array('timecreated' => 1552179600));
$course4 = $this->getDataGenerator()->create_course(array('timecreated' => 1552179600));
// Create backup course records for the courses that need them.
$backupcourse3 = new \stdClass;
$backupcourse3->courseid = $course3->id;
$backupcourse3->laststatus = testable_backup_cron_automated_helper::BACKUP_STATUS_OK;
$backupcourse3->nextstarttime = 1554822160;
$DB->insert_record('backup_courses', $backupcourse3);
$backupcourse4 = new \stdClass;
$backupcourse4->courseid = $course4->id;
$backupcourse4->laststatus = testable_backup_cron_automated_helper::BACKUP_STATUS_OK;
$backupcourse4->nextstarttime = 1554858160;
$DB->insert_record('backup_courses', $backupcourse4);
return array($course1, $course2, $course3, $course4);
}
/**
* Test the selection and ordering of courses to be backed up.
*/
public function test_get_courses(): void {
$this->resetAfterTest();
list($course1, $course2, $course3, $course4) = $this->course_setup();
$now = 1559215025;
// Get the courses in order.
$courseset = testable_backup_cron_automated_helper::testable_get_courses($now);
$coursearray = array();
foreach ($courseset as $course) {
if ($course->id != SITEID) { // Skip system course for test.
$coursearray[] = $course->id;
}
}
$courseset->close();
// First should be course 1, it is the more recently modified without a backup.
$this->assertEquals($course1->id, $coursearray[0]);
// Second should be course 2, it is the next more recently modified without a backup.
$this->assertEquals($course2->id, $coursearray[1]);
// Third should be course 3, it is the course with the oldest backup.
$this->assertEquals($course3->id, $coursearray[2]);
// Fourth should be course 4, it is the course with the newest backup.
$this->assertEquals($course4->id, $coursearray[3]);
}
/**
* Test the selection and ordering of courses to be backed up.
* Where it is not yet time to start backups for courses with existing backups.
*/
public function test_get_courses_starttime(): void {
$this->resetAfterTest();
list($course1, $course2, $course3, $course4) = $this->course_setup();
$now = 1554858000;
// Get the courses in order.
$courseset = testable_backup_cron_automated_helper::testable_get_courses($now);
$coursearray = array();
foreach ($courseset as $course) {
if ($course->id != SITEID) { // Skip system course for test.
$coursearray[] = $course->id;
}
}
$courseset->close();
// Should only be two courses.
// First should be course 1, it is the more recently modified without a backup.
$this->assertEquals($course1->id, $coursearray[0]);
// Second should be course 2, it is the next more recently modified without a backup.
$this->assertEquals($course2->id, $coursearray[1]);
}
}
/**
* Provides access to protected methods we want to explicitly test
*
* @copyright 2015 Jean-Philippe Gaudreau <jp.gaudreau@umontreal.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class testable_backup_cron_automated_helper extends backup_cron_automated_helper {
/**
* Provides access to protected method get_backups_to_remove.
*
* @param array $backupfiles Existing backup files
* @param int $now Starting time of the process
* @return array Backup files to remove
*/
public static function testable_get_backups_to_delete($backupfiles, $now) {
return parent::get_backups_to_delete($backupfiles, $now);
}
/**
* Provides access to protected method get_backups_to_remove.
*
* @param int $courseid course id to check
* @param int $since timestamp, from which to check
*
* @return bool true if the course was modified, false otherwise. This also returns false if no readers are enabled. This is
* intentional, since we cannot reliably determine if any modification was made or not.
*/
public static function testable_is_course_modified($courseid, $since) {
return parent::is_course_modified($courseid, $since);
}
/**
* Provides access to protected method get_courses.
*
* @param int $now Timestamp to use.
* @return moodle_recordset The returned courses as a Moodle recordest.
*/
public static function testable_get_courses($now) {
return parent::get_courses($now);
}
}
+200
View File
@@ -0,0 +1,200 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package core_backup
* @category test
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_backup;
use restore_decode_rule;
use restore_decode_rule_exception;
defined('MOODLE_INTERNAL') || die();
// Include all the needed stuff
global $CFG;
require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
/**
* Restore_decode tests (both rule and content)
*
* @package core_backup
* @category test
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class decode_test extends \basic_testcase {
/**
* test restore_decode_rule class
*/
function test_restore_decode_rule(): void {
// Test various incorrect constructors
try {
$dr = new restore_decode_rule('28 HJH', '/index.php', array());
$this->assertTrue(false, 'restore_decode_rule_exception exception expected');
} catch (\Exception $e) {
$this->assertTrue($e instanceof restore_decode_rule_exception);
$this->assertEquals($e->errorcode, 'decode_rule_incorrect_name');
$this->assertEquals($e->a, '28 HJH');
}
try {
$dr = new restore_decode_rule('HJHJhH', '/index.php', array());
$this->assertTrue(false, 'restore_decode_rule_exception exception expected');
} catch (\Exception $e) {
$this->assertTrue($e instanceof restore_decode_rule_exception);
$this->assertEquals($e->errorcode, 'decode_rule_incorrect_name');
$this->assertEquals($e->a, 'HJHJhH');
}
try {
$dr = new restore_decode_rule('', '/index.php', array());
$this->assertTrue(false, 'restore_decode_rule_exception exception expected');
} catch (\Exception $e) {
$this->assertTrue($e instanceof restore_decode_rule_exception);
$this->assertEquals($e->errorcode, 'decode_rule_incorrect_name');
$this->assertEquals($e->a, '');
}
try {
$dr = new restore_decode_rule('TESTRULE', 'index.php', array());
$this->assertTrue(false, 'restore_decode_rule_exception exception expected');
} catch (\Exception $e) {
$this->assertTrue($e instanceof restore_decode_rule_exception);
$this->assertEquals($e->errorcode, 'decode_rule_incorrect_urltemplate');
$this->assertEquals($e->a, 'index.php');
}
try {
$dr = new restore_decode_rule('TESTRULE', '', array());
$this->assertTrue(false, 'restore_decode_rule_exception exception expected');
} catch (\Exception $e) {
$this->assertTrue($e instanceof restore_decode_rule_exception);
$this->assertEquals($e->errorcode, 'decode_rule_incorrect_urltemplate');
$this->assertEquals($e->a, '');
}
try {
$dr = new restore_decode_rule('TESTRULE', '/course/view.php?id=$1&c=$2$3', array('test1', 'test2'));
$this->assertTrue(false, 'restore_decode_rule_exception exception expected');
} catch (\Exception $e) {
$this->assertTrue($e instanceof restore_decode_rule_exception);
$this->assertEquals($e->errorcode, 'decode_rule_mappings_incorrect_count');
$this->assertEquals($e->a->placeholders, 3);
$this->assertEquals($e->a->mappings, 2);
}
try {
$dr = new restore_decode_rule('TESTRULE', '/course/view.php?id=$5&c=$4$1', array('test1', 'test2', 'test3'));
$this->assertTrue(false, 'restore_decode_rule_exception exception expected');
} catch (\Exception $e) {
$this->assertTrue($e instanceof restore_decode_rule_exception);
$this->assertEquals($e->errorcode, 'decode_rule_nonconsecutive_placeholders');
$this->assertEquals($e->a, '1, 4, 5');
}
try {
$dr = new restore_decode_rule('TESTRULE', '/course/view.php?id=$0&c=$3$2', array('test1', 'test2', 'test3'));
$this->assertTrue(false, 'restore_decode_rule_exception exception expected');
} catch (\Exception $e) {
$this->assertTrue($e instanceof restore_decode_rule_exception);
$this->assertEquals($e->errorcode, 'decode_rule_nonconsecutive_placeholders');
$this->assertEquals($e->a, '0, 2, 3');
}
try {
$dr = new restore_decode_rule('TESTRULE', '/course/view.php?id=$1&c=$3$3', array('test1', 'test2', 'test3'));
$this->assertTrue(false, 'restore_decode_rule_exception exception expected');
} catch (\Exception $e) {
$this->assertTrue($e instanceof restore_decode_rule_exception);
$this->assertEquals($e->errorcode, 'decode_rule_duplicate_placeholders');
$this->assertEquals($e->a, '1, 3, 3');
}
// Provide some example content and test the regexp is calculated ok
$content = '$@TESTRULE*22*33*44@$';
$linkname = 'TESTRULE';
$urltemplate= '/course/view.php?id=$1&c=$3$2';
$mappings = array('test1', 'test2', 'test3');
$result = '1/course/view.php?id=44&c=8866';
$dr = new mock_restore_decode_rule($linkname, $urltemplate, $mappings);
$this->assertEquals($dr->decode($content), $result);
$content = '$@TESTRULE*22*33*44@$ñ$@TESTRULE*22*33*44@$';
$linkname = 'TESTRULE';
$urltemplate= '/course/view.php?id=$1&c=$3$2';
$mappings = array('test1', 'test2', 'test3');
$result = '1/course/view.php?id=44&c=8866ñ1/course/view.php?id=44&c=8866';
$dr = new mock_restore_decode_rule($linkname, $urltemplate, $mappings);
$this->assertEquals($dr->decode($content), $result);
$content = 'ñ$@TESTRULE*22*0*44@$ñ$@TESTRULE*22*33*44@$ñ';
$linkname = 'TESTRULE';
$urltemplate= '/course/view.php?id=$1&c=$3$2';
$mappings = array('test1', 'test2', 'test3');
$result = 'ñ0/course/view.php?id=22&c=440ñ1/course/view.php?id=44&c=8866ñ';
$dr = new mock_restore_decode_rule($linkname, $urltemplate, $mappings);
$this->assertEquals($dr->decode($content), $result);
}
/**
* test restore_decode_content class
*/
function test_restore_decode_content(): void {
// TODO: restore_decode_content tests
}
/**
* test restore_decode_processor class
*/
function test_restore_decode_processor(): void {
// TODO: restore_decode_processor tests
}
}
/**
* Mockup restore_decode_rule for testing purposes
*/
class mock_restore_decode_rule extends restore_decode_rule {
/**
* Originally protected, make it public
*/
public function get_calculated_regexp() {
return parent::get_calculated_regexp();
}
/**
* Simply map each itemid by its double
*/
protected function get_mapping($itemname, $itemid) {
return $itemid * 2;
}
/**
* Simply prefix with '0' non-mapped results and with '1' mapped ones
*/
protected function apply_modifications($toreplace, $mappingsok) {
return ($mappingsok ? '1' : '0') . $toreplace;
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_backup;
defined('MOODLE_INTERNAL') || die();
// Include all the needed stuff.
global $CFG;
require_once($CFG->dirroot . '/backup/util/interfaces/checksumable.class.php');
require_once($CFG->dirroot . '/backup/backup.class.php');
require_once($CFG->dirroot . '/backup/util/helper/backup_helper.class.php');
require_once($CFG->dirroot . '/backup/util/helper/backup_general_helper.class.php');
/**
* backup_helper tests (all)
*
* @package core_backup
* @category test
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class helper_test extends \basic_testcase {
/*
* test backup_helper class
*/
function test_backup_helper(): void {
}
/*
* test backup_general_helper class
*/
function test_backup_general_helper(): void {
}
}
@@ -0,0 +1,70 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_backup;
use restore_log_rule;
defined('MOODLE_INTERNAL') || die();
// Include all the needed stuff
global $CFG;
require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
/**
* Test the backup and restore of logs using rules.
*
* @package core_backup
* @category test
* @copyright 2015 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class restore_log_rule_test extends \basic_testcase {
function test_process_keeps_log_unmodified(): void {
// Prepare a tiny log entry.
$originallog = new \stdClass();
$originallog->url = 'original';
$originallog->info = 'original';
$log = clone($originallog);
// Process it with a tiny log rule, only modifying url and info.
$lr = new restore_log_rule('test', 'test', 'changed', 'changed');
$result = $lr->process($log);
// The log has been processed.
$this->assertEquals('changed', $result->url);
$this->assertEquals('changed', $result->info);
// But the original log has been kept unmodified by the process() call.
$this->assertEquals($originallog, $log);
}
public function test_build_regexp(): void {
$original = 'Any (string) with [placeholders] like {this} and {this}. [end].';
$expectation = '~Any \(string\) with (.*) like (.*) and (.*)\. (.*)\.~';
$lr = new restore_log_rule('this', 'doesnt', 'matter', 'here');
$class = new \ReflectionClass('restore_log_rule');
$method = $class->getMethod('extract_tokens');
$tokens = $method->invoke($lr, $original);
$method = $class->getMethod('build_regexp');
$this->assertSame($expectation, $method->invoke($lr, $original, $tokens));
}
}
@@ -0,0 +1,137 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Tests for restore_structure_parser_processor class.
*
* @package core_backup
* @category test
* @copyright 2017 Dmitrii Metelkin (dmitriim@catalyst-au.net)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
require_once($CFG->dirroot . '/backup/util/helper/restore_structure_parser_processor.class.php');
/**
* Tests for restore_structure_parser_processor class.
*
* @package core_backup
* @copyright 2017 Dmitrii Metelkin (dmitriim@catalyst-au.net)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class restore_structure_parser_processor_test extends advanced_testcase {
/**
* Initial set up.
*/
public function setUp(): void {
parent::setUp();
$this->resetAfterTest(true);
}
/**
* Data provider for ::test_process_cdata.
*
* @return array
*/
public function process_cdata_data_provider() {
return array(
array(null, null, true),
array("$@NULL@$", null, true),
array("$@NULL@$ ", "$@NULL@$ ", true),
array(1, 1, true),
array(" ", " ", true),
array("1", "1", true),
array("$@FILEPHP@$1.jpg", "$@FILEPHP@$1.jpg", true),
array(
"http://test.test/$@SLASH@$",
"http://test.test/$@SLASH@$",
true
),
array(
"<a href='$@FILEPHP@$1.jpg'>Image</a>",
"<a href='http://test.test/file.php/11.jpg'>Image</a>",
true
),
array(
"<a href='$@FILEPHP@$$@SLASH@$1.jpg'>Image</a>",
"<a href='http://test.test/file.php/1/1.jpg'>Image</a>",
true
),
array(
"<a href='$@FILEPHP@$$@SLASH@$$@SLASH@$1.jpg'>Image</a>",
"<a href='http://test.test/file.php/1//1.jpg'>Image</a>",
true
),
array(
"<a href='$@FILEPHP@$1.jpg'>Image</a>",
"<a href='http://test.test/file.php?file=%2F11.jpg'>Image</a>",
false
),
array(
"<a href='$@FILEPHP@$$@SLASH@$1.jpg'>Image</a>",
"<a href='http://test.test/file.php?file=%2F1%2F1.jpg'>Image</a>",
false
),
array(
"<a href='$@FILEPHP@$$@SLASH@$$@SLASH@$1.jpg'>Image</a>",
"<a href='http://test.test/file.php?file=%2F1%2F%2F1.jpg'>Image</a>",
false
),
array(
"<a href='$@FILEPHP@$$@SLASH@$1.jpg$@FORCEDOWNLOAD@$'>Image</a>",
"<a href='http://test.test/file.php/1/1.jpg?forcedownload=1'>Image</a>",
true
),
array(
"<a href='$@FILEPHP@$$@SLASH@$1.jpg$@FORCEDOWNLOAD@$'>Image</a>",
"<a href='http://test.test/file.php?file=%2F1%2F1.jpg&amp;forcedownload=1'>Image</a>",
false
),
array(
"<iframe src='$@H5PEMBED@$?url=testurl'></iframe>",
"<iframe src='http://test.test/h5p/embed.php?url=testurl'></iframe>",
true
),
);
}
/**
* Test that restore_structure_parser_processor replaces $@FILEPHP@$ to correct file php links.
*
* @dataProvider process_cdata_data_provider
* @param string $content Testing content.
* @param string $expected Expected result.
* @param bool $slasharguments A value for $CFG->slasharguments setting.
*/
public function test_process_cdata($content, $expected, $slasharguments): void {
global $CFG;
$CFG->slasharguments = $slasharguments;
$CFG->wwwroot = 'http://test.test';
$processor = new restore_structure_parser_processor(1, 1);
$this->assertEquals($expected, $processor->process_cdata($content));
}
}