MDL-32569 convert remaining backup tests and drop old simpletests

This commit is contained in:
Petr Skoda
2012-04-21 16:24:33 +02:00
parent 10156165ae
commit bb7898c6ab
36 changed files with 239 additions and 5787 deletions
@@ -1,167 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
/*
* controller tests (all)
*/
class backup_controller_test extends UnitTestCase {
public static $includecoverage = array('backup/controller');
public static $excludecoverage = array('backup/controller/simpletest');
protected $moduleid; // course_modules id used for testing
protected $sectionid; // course_sections id used for testing
protected $courseid; // course id used for testing
protected $user; // user record used for testing
protected $todelete; // array of records to be deleted after tests
protected $errorlogloggerlevel; // To store level $CFG->backup_error_log_logger_level
protected $outputindentedloggerlevel; // To store level $CFG->backup_output_indented_logger_level
protected $fileloggerlevel; // To store level $CFG->backup_file_logger_level
protected $databaseloggerlevel; // To store level $CFG->backup_database_logger_level
protected $fileloggerlevelextra;// To store level $CFG->backup_file_logger_level_extra
function __construct() {
global $DB, $USER, $CFG;
$this->moduleid = 0;
$this->sectionid = 0;
$this->courseid = 0;
$this->userid = $USER->id;
$this->todelete = array();
// Check we have (at least) one course_module
if ($coursemodule = $DB->get_record('course_modules', array(), '*', IGNORE_MULTIPLE)) {
$this->moduleid = $coursemodule->id;
$this->sectionid = $coursemodule->section;
$this->courseid = $coursemodule->course;
}
// Avoid any logger to be created, we'll restore original settings on tearDown()
$this->errorlogloggerlevel = isset($CFG->backup_error_log_logger_level) ? $CFG->backup_error_log_logger_level : null;
$this->outputindentedloggerlevel = isset($CFG->backup_output_indented_logger_level) ? $CFG->backup_output_indented_logger_level : null;
$this->fileloggerlevel = isset($CFG->backup_file_logger_level) ? $CFG->backup_file_logger_level : null;
$this->databaseloggerlevel = isset($CFG->backup_database_logger_level) ? $CFG->backup_database_logger_level : null;
$this->fileloggerlevelextra = isset($CFG->backup_file_logger_level_extra) ? $CFG->backup_file_logger_level_extra : null;
parent::__construct();
}
function skip() {
$this->skipIf(empty($this->moduleid), 'backup_controller_test require at least one course module to exist');
$this->skipIf(empty($this->sectionid),'backup_controller_test require at least one course section to exist');
$this->skipIf(empty($this->courseid), 'backup_controller_test require at least one course to exist');
$this->skipIf(empty($this->userid),'backup_controller_test require one valid user to exist');
}
function setUp() {
global $CFG;
// 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;
}
function tearDown() {
global $DB, $CFG;
// Delete all the records marked to
foreach ($this->todelete as $todelete) {
$DB->delete_records($todelete[0], array('id' => $todelete[1]));
}
// Restore original file_logger levels
if ($this->errorlogloggerlevel !== null) {
$CFG->backup_error_log_logger_level = $this->errorlogloggerlevel;
} else {
unset($CFG->backup_error_log_logger_level);
}
if ($this->outputindentedloggerlevel !== null) {
$CFG->backup_output_indented_logger_level = $this->outputindentedloggerlevel;
} else {
unset($CFG->backup_output_indented_logger_level);
}
if ($this->fileloggerlevel !== null) {
$CFG->backup_file_logger_level = $this->fileloggerlevel;
} else {
unset($CFG->backup_file_logger_level);
}
if ($this->databaseloggerlevel !== null) {
$CFG->backup_database_logger_level = $this->databaseloggerlevel;
} else {
unset($CFG->backup_database_logger_level);
}
if ($this->fileloggerlevelextra !== null) {
$CFG->backup_file_logger_level_extra = $this->fileloggerlevelextra;
} else {
unset($CFG->backup_file_logger_level_extra);
}
}
/*
* test base_setting class
*/
function test_backup_controller() {
// Instantiate non interactive backup_controller
$bc = new mock_backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
$this->assertTrue($bc instanceof backup_controller);
$this->assertEqual($bc->get_status(), backup::STATUS_AWAITING);
// Instantiate interactive backup_controller
$bc = new mock_backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
backup::INTERACTIVE_YES, backup::MODE_GENERAL, $this->userid);
$this->assertTrue($bc instanceof backup_controller);
$this->assertEqual($bc->get_status(), backup::STATUS_SETTING_UI);
$this->assertEqual(strlen($bc->get_backupid()), 32); // is one md5
// Save and load one backup controller to check everything is in place
$bc = new mock_backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
$recid = $bc->save_controller();
$newbc = mock_backup_controller::load_controller($bc->get_backupid());
$this->assertTrue($newbc instanceof backup_controller); // This means checksum and load worked ok
$this->todelete[] = array('backup_controllers', $recid); // mark this record for deletion
}
}
/*
* helper extended @backup_controller class that makes some methods public for testing
*/
class mock_backup_controller extends backup_controller {
public function save_controller() {
parent::save_controller();
}
}
@@ -1,463 +0,0 @@
<?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 the moodle1 converter
*
* @package core
* @subpackage backup-convert
* @copyright 2011 Mark Nielsen <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/backup/converter/moodle1/lib.php');
class moodle1_converter_test extends UnitTestCase {
public static $includecoverage = array();
/** @var string the name of the directory containing the unpacked Moodle 1.9 backup */
protected $tempdir;
public function setUp() {
global $CFG;
$this->tempdir = convert_helper::generate_id('simpletest');
check_dir_exists("$CFG->tempdir/backup/$this->tempdir/course_files/sub1");
check_dir_exists("$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/7");
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/moodle.xml",
"$CFG->tempdir/backup/$this->tempdir/moodle.xml"
);
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif",
"$CFG->tempdir/backup/$this->tempdir/course_files/file1.gif"
);
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif",
"$CFG->tempdir/backup/$this->tempdir/course_files/sub1/file2.gif"
);
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif",
"$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/file1.gif"
);
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif",
"$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/icon.gif"
);
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif",
"$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/7/icon.gif"
);
}
public function tearDown() {
global $CFG;
if (empty($CFG->keeptempdirectoriesonbackup)) {
fulldelete("$CFG->tempdir/backup/$this->tempdir");
}
}
public function test_detect_format() {
$detected = moodle1_converter::detect_format($this->tempdir);
$this->assertEqual(backup::FORMAT_MOODLE1, $detected);
}
public function test_convert_factory() {
$converter = convert_factory::get_converter('moodle1', $this->tempdir);
$this->assertIsA($converter, 'moodle1_converter');
}
public function test_stash_storage_not_created() {
$converter = convert_factory::get_converter('moodle1', $this->tempdir);
$this->expectException('moodle1_convert_storage_exception');
$converter->set_stash('tempinfo', 12);
}
public function test_stash_requiring_empty_stash() {
$converter = convert_factory::get_converter('moodle1', $this->tempdir);
$converter->create_stash_storage();
$converter->set_stash('tempinfo', 12);
$this->expectException('moodle1_convert_empty_storage_exception');
try {
$converter->get_stash('anothertempinfo');
} catch (moodle1_convert_empty_storage_exception $e) {
// we must drop the storage here so we are able to re-create it in the next test
$converter->drop_stash_storage();
throw new moodle1_convert_empty_storage_exception('rethrowing');
}
}
public function test_stash_storage() {
$converter = convert_factory::get_converter('moodle1', $this->tempdir);
$converter->create_stash_storage();
// no implicit stashes
$stashes = $converter->get_stash_names();
$this->assertIsA($stashes, 'array');
$this->assertTrue(empty($stashes));
// test stashes without itemid
$converter->set_stash('tempinfo1', 12);
$converter->set_stash('tempinfo2', array('a' => 2, 'b' => 3));
$stashes = $converter->get_stash_names();
$this->assertIsA($stashes, 'array');
$this->assertEqual(2, count($stashes));
$this->assertTrue(in_array('tempinfo1', $stashes));
$this->assertTrue(in_array('tempinfo2', $stashes));
$this->assertIdentical(12, $converter->get_stash('tempinfo1'));
$this->assertIdentical(array('a' => 2, 'b' => 3), $converter->get_stash('tempinfo2'));
// overwriting a stashed value is allowed
$converter->set_stash('tempinfo1', '13');
$this->assertNotIdentical(13, $converter->get_stash('tempinfo1'));
$this->assertIdentical('13', $converter->get_stash('tempinfo1'));
// repeated reading is allowed
$this->assertIdentical('13', $converter->get_stash('tempinfo1'));
// storing empty array
$converter->set_stash('empty_array_stash', array());
$restored = $converter->get_stash('empty_array_stash');
//$this->assertIsA($restored, 'array'); // todo return null now, this needs MDL-27713 to be fixed, then uncomment
$this->assertTrue(empty($restored));
// test stashes with itemid
$converter->set_stash('tempinfo', 'Hello', 1);
$converter->set_stash('tempinfo', 'World', 2);
$this->assertIdentical('Hello', $converter->get_stash('tempinfo', 1));
$this->assertIdentical('World', $converter->get_stash('tempinfo', 2));
// test get_stash_itemids()
$ids = $converter->get_stash_itemids('course_fileref');
$this->assertIsA($ids, 'array');
$this->assertTrue(empty($ids));
$converter->set_stash('course_fileref', null, 34);
$converter->set_stash('course_fileref', null, 52);
$ids = $converter->get_stash_itemids('course_fileref');
$this->assertEqual(2, count($ids));
$this->assertTrue(in_array(34, $ids));
$this->assertTrue(in_array(52, $ids));
$converter->drop_stash_storage();
}
public function test_get_stash_or_default() {
$converter = convert_factory::get_converter('moodle1', $this->tempdir);
$converter->create_stash_storage();
$this->assertTrue(is_null($converter->get_stash_or_default('stashname')));
$this->assertTrue(is_null($converter->get_stash_or_default('stashname', 7)));
$this->assertTrue('default' === $converter->get_stash_or_default('stashname', 0, 'default'));
$this->assertTrue(array('foo', 'bar') === $converter->get_stash_or_default('stashname', 42, array('foo', 'bar')));
//$converter->set_stash('stashname', 0);
//$this->assertFalse(is_null($converter->get_stash_or_default('stashname'))); // todo returns true now, this needs MDL-27713 to be fixed
//$converter->set_stash('stashname', '');
//$this->assertFalse(is_null($converter->get_stash_or_default('stashname'))); // todo returns true now, this needs MDL-27713 to be fixed
//$converter->set_stash('stashname', array());
//$this->assertFalse(is_null($converter->get_stash_or_default('stashname'))); // todo returns true now, this needs MDL-27713 to be fixed
$converter->set_stash('stashname', 42);
$this->assertTrue(42 === $converter->get_stash_or_default('stashname'));
$this->assertTrue(is_null($converter->get_stash_or_default('stashname', 1)));
$this->assertTrue(42 === $converter->get_stash_or_default('stashname', 0, 61));
$converter->set_stash('stashname', array(42 => (object)array('id' => 42)), 18);
$stashed = $converter->get_stash_or_default('stashname', 18, 1984);
$this->assertIsA($stashed, 'array');
$this->assertTrue(is_object($stashed[42]));
$this->assertTrue($stashed[42]->id === 42);
$converter->drop_stash_storage();
}
public function test_get_contextid() {
$converter = convert_factory::get_converter('moodle1', $this->tempdir);
// stash storage must be created in advance
$converter->create_stash_storage();
// ids are generated on the first call
$id1 = $converter->get_contextid(CONTEXT_BLOCK, 10);
$id2 = $converter->get_contextid(CONTEXT_BLOCK, 11);
$id3 = $converter->get_contextid(CONTEXT_MODULE, 10);
$this->assertNotEqual($id1, $id2);
$this->assertNotEqual($id1, $id3);
$this->assertNotEqual($id2, $id3);
// and then re-used if called with the same params
$this->assertEqual($id1, $converter->get_contextid(CONTEXT_BLOCK, 10));
$this->assertEqual($id2, $converter->get_contextid(CONTEXT_BLOCK, 11));
$this->assertEqual($id3, $converter->get_contextid(CONTEXT_MODULE, 10));
// for system and course level, the instance is irrelevant
// as we need only one system and one course
$id1 = $converter->get_contextid(CONTEXT_COURSE);
$id2 = $converter->get_contextid(CONTEXT_COURSE, 10);
$id3 = $converter->get_contextid(CONTEXT_COURSE, 14);
$this->assertEqual($id1, $id2);
$this->assertEqual($id1, $id3);
$id1 = $converter->get_contextid(CONTEXT_SYSTEM);
$id2 = $converter->get_contextid(CONTEXT_SYSTEM, 11);
$id3 = $converter->get_contextid(CONTEXT_SYSTEM, 15);
$this->assertEqual($id1, $id2);
$this->assertEqual($id1, $id3);
$converter->drop_stash_storage();
}
public function test_get_nextid() {
$converter = convert_factory::get_converter('moodle1', $this->tempdir);
$id1 = $converter->get_nextid();
$id2 = $converter->get_nextid();
$id3 = $converter->get_nextid();
$this->assertTrue(0 < $id1);
$this->assertTrue($id1 < $id2);
$this->assertTrue($id2 < $id3);
}
public function test_migrate_file() {
// set-up the file manager
$converter = convert_factory::get_converter('moodle1', $this->tempdir);
$converter->create_stash_storage();
$contextid = $converter->get_contextid(CONTEXT_MODULE, 32);
$fileman = $converter->get_file_manager($contextid, 'mod_unittest', 'testarea');
// this fileman has not converted anything yet
$fileids = $fileman->get_fileids();
$this->assertIsA($fileids, 'array');
$this->assertEqual(0, count($fileids));
// try to migrate a non-existing directory
$returned = $fileman->migrate_directory('not/existing/directory');
$this->assertIsA($returned, 'array');
$this->assertEqual(0, count($returned));
$fileids = $fileman->get_fileids();
$this->assertIsA($fileids, 'array');
$this->assertEqual(0, count($fileids));
// migrate a single file
$fileman->itemid = 4;
$fileman->migrate_file('moddata/unittest/4/icon.gif');
$this->assertTrue(is_file($converter->get_workdir_path().'/files/4e/4ea114b0558f53e3af8dd9afc0e0810a95c2a724'));
// get the file id
$fileids = $fileman->get_fileids();
$this->assertIsA($fileids, 'array');
$this->assertEqual(1, count($fileids));
// migrate another single file into another file area
$fileman->filearea = 'anotherarea';
$fileman->itemid = 7;
$fileman->migrate_file('moddata/unittest/4/7/icon.gif', '/', 'renamed.gif');
// get the file records
$filerecordids = $converter->get_stash_itemids('files');
foreach ($filerecordids as $filerecordid) {
$filerecord = $converter->get_stash('files', $filerecordid);
$this->assertEqual('4ea114b0558f53e3af8dd9afc0e0810a95c2a724', $filerecord['contenthash']);
$this->assertEqual($contextid, $filerecord['contextid']);
$this->assertEqual('mod_unittest', $filerecord['component']);
if ($filerecord['filearea'] === 'testarea') {
$this->assertEqual(4, $filerecord['itemid']);
$this->assertEqual('icon.gif', $filerecord['filename']);
}
}
// explicitly clear the list of migrated files
$this->assertTrue(count($fileman->get_fileids()) > 0);
$fileman->reset_fileids();
$this->assertTrue(count($fileman->get_fileids()) == 0);
$converter->drop_stash_storage();
}
public function test_convert_path() {
$path = new convert_path('foo_bar', '/ROOT/THINGS/FOO/BAR');
$this->assertEqual('foo_bar', $path->get_name());
$this->assertEqual('/ROOT/THINGS/FOO/BAR', $path->get_path());
$this->assertEqual('process_foo_bar', $path->get_processing_method());
$this->assertEqual('on_foo_bar_start', $path->get_start_method());
$this->assertEqual('on_foo_bar_end', $path->get_end_method());
}
public function test_convert_path_implicit_recipes() {
$path = new convert_path('foo_bar', '/ROOT/THINGS/FOO/BAR');
$data = array(
'ID' => 76,
'ELOY' => 'stronk7',
'MARTIN' => 'moodler',
'EMPTY' => null,
);
// apply default recipes (converting keys to lowercase)
$data = $path->apply_recipes($data);
$this->assertEqual(4, count($data));
$this->assertEqual(76, $data['id']);
$this->assertEqual('stronk7', $data['eloy']);
$this->assertEqual('moodler', $data['martin']);
$this->assertIdentical(null, $data['empty']);
}
public function test_convert_path_explicit_recipes() {
$path = new convert_path(
'foo_bar', '/ROOT/THINGS/FOO/BAR',
array(
'newfields' => array(
'david' => 'mudrd8mz',
'petr' => 'skodak',
),
'renamefields' => array(
'empty' => 'nothing',
),
'dropfields' => array(
'id'
),
)
);
$data = array(
'ID' => 76,
'ELOY' => 'stronk7',
'MARTIN' => 'moodler',
'EMPTY' => null,
);
$data = $path->apply_recipes($data);
$this->assertEqual(5, count($data));
$this->assertFalse(array_key_exists('id', $data));
$this->assertEqual('stronk7', $data['eloy']);
$this->assertEqual('moodler', $data['martin']);
$this->assertEqual('mudrd8mz', $data['david']);
$this->assertEqual('skodak', $data['petr']);
$this->assertIdentical(null, $data['nothing']);
}
public function test_grouped_data_on_nongrouped_convert_path() {
// prepare some grouped data
$data = array(
'ID' => 77,
'NAME' => 'Pale lagers',
'BEERS' => array(
array(
'BEER' => array(
'ID' => 67,
'NAME' => 'Pilsner Urquell',
)
),
array(
'BEER' => array(
'ID' => 34,
'NAME' => 'Heineken',
)
),
)
);
// declare a non-grouped path
$path = new convert_path('beer_style', '/ROOT/BEER_STYLES/BEER_STYLE');
// an attempt to apply recipes throws exception because we do not expect grouped data
$this->expectException('convert_path_exception');
$data = $path->apply_recipes($data);
}
public function test_grouped_convert_path_with_recipes() {
// prepare some grouped data
$data = array(
'ID' => 77,
'NAME' => 'Pale lagers',
'BEERS' => array(
array(
'BEER' => array(
'ID' => 67,
'NAME' => 'Pilsner Urquell',
)
),
array(
'BEER' => array(
'ID' => 34,
'NAME' => 'Heineken',
)
),
)
);
// implict recipes work for grouped data if the path is declared as grouped
$path = new convert_path('beer_style', '/ROOT/BEER_STYLES/BEER_STYLE', array(), true);
$data = $path->apply_recipes($data);
$this->assertEqual('Heineken', $data['beers'][1]['beer']['name']);
// an attempt to provide explicit recipes on grouped elements throws exception
$this->expectException('convert_path_exception');
$path = new convert_path(
'beer_style', '/ROOT/BEER_STYLES/BEER_STYLE',
array(
'renamefields' => array(
'name' => 'beername', // note this is confusing recipe because the 'name' is used for both
// beer-style name ('Pale lagers') and beer name ('Pilsner Urquell')
)
), true);
}
public function test_referenced_course_files() {
$text = 'This is a text containing links to file.php
as it is parsed from the backup file. <br /><br /><img border="0" width="110" vspace="0" hspace="0" height="92" title="News" alt="News" src="$@FILEPHP@$$@SLASH@$pics$@SLASH@$news.gif" /><a href="$@FILEPHP@$$@SLASH@$pics$@SLASH@$news.gif$@FORCEDOWNLOAD@$">download image</a><br />
<br /><a href=\'$@FILEPHP@$$@SLASH@$MANUAL.DOC$@FORCEDOWNLOAD@$\'>download manual</a><br />';
$files = moodle1_converter::find_referenced_files($text);
$this->assertIsA($files, 'array');
$this->assertEqual(2, count($files));
$this->assertTrue(in_array('/pics/news.gif', $files));
$this->assertTrue(in_array('/MANUAL.DOC', $files));
$text = moodle1_converter::rewrite_filephp_usage($text, array('/pics/news.gif', '/another/file/notused.txt'), $files);
$this->assertEqual($text, 'This is a text containing links to file.php
as it is parsed from the backup file. <br /><br /><img border="0" width="110" vspace="0" hspace="0" height="92" title="News" alt="News" src="@@PLUGINFILE@@/pics/news.gif" /><a href="@@PLUGINFILE@@/pics/news.gif?forcedownload=1">download image</a><br />
<br /><a href=\'$@FILEPHP@$$@SLASH@$MANUAL.DOC$@FORCEDOWNLOAD@$\'>download manual</a><br />');
}
public function test_question_bank_conversion() {
global $CFG;
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/questions.xml",
"$CFG->tempdir/backup/$this->tempdir/moodle.xml"
);
$converter = convert_factory::get_converter('moodle1', $this->tempdir);
$converter->convert();
}
public function test_convert_run_convert() {
$converter = convert_factory::get_converter('moodle1', $this->tempdir);
$converter->convert();
}
public function test_inforef_manager() {
$converter = convert_factory::get_converter('moodle1', $this->tempdir);
$inforef = $converter->get_inforef_manager('unittest');
$inforef->add_ref('file', 45);
$inforef->add_refs('file', array(46, 47));
// todo test the write_refs() via some dummy xml_writer
$this->expectException('coding_exception');
$inforef->add_ref('unknown_referenced_item_name', 76);
}
}

Before

Width:  |  Height:  |  Size: 127 B

After

Width:  |  Height:  |  Size: 127 B

+7 -7
View File
@@ -42,27 +42,27 @@ class moodle1_converter_testcase extends advanced_testcase {
check_dir_exists("$CFG->tempdir/backup/$this->tempdir/course_files/sub1");
check_dir_exists("$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/7");
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/moodle.xml",
"$CFG->dirroot/backup/converter/moodle1/tests/fixtures/moodle.xml",
"$CFG->tempdir/backup/$this->tempdir/moodle.xml"
);
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif",
"$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif",
"$CFG->tempdir/backup/$this->tempdir/course_files/file1.gif"
);
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif",
"$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif",
"$CFG->tempdir/backup/$this->tempdir/course_files/sub1/file2.gif"
);
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif",
"$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif",
"$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/file1.gif"
);
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif",
"$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif",
"$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/icon.gif"
);
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif",
"$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif",
"$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/7/icon.gif"
);
}
@@ -450,7 +450,7 @@ as it is parsed from the backup file. <br /><br /><img border="0" width="110" vs
$this->resetAfterTest(true);
copy(
"$CFG->dirroot/backup/converter/moodle1/simpletest/files/questions.xml",
"$CFG->dirroot/backup/converter/moodle1/tests/fixtures/questions.xml",
"$CFG->tempdir/backup/$this->tempdir/moodle.xml"
);
$converter = convert_factory::get_converter('moodle1', $this->tempdir);
-228
View File
@@ -1,228 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
/*
* check tests (all)
*/
class backup_check_test extends UnitTestCase {
public static $includecoverage = array('backup/util/checks');
public static $excludecoverage = array('backup/util/checks/simpletest');
protected $moduleid; // course_modules id used for testing
protected $sectionid; // course_sections id used for testing
protected $courseid; // course id used for testing
protected $userid; // user record id
protected $errorlogloggerlevel; // To store $CFG->backup_error_log_logger_level
protected $fileloggerlevel; // To store level $CFG->backup_file_logger_level
protected $databaseloggerlevel; // To store $CFG->backup_database_logger_level
protected $outputindentedloggerlevel; // To store $CFG->backup_output_indented_logger_level
protected $fileloggerextra; // To store $CFG->backup_file_logger_extra
protected $fileloggerlevelextra; // To store level $CFG->backup_file_logger_level_extra
protected $debugging; // To store $CFG->debug
protected $debugdisplay; // To store $CFG->debugdisplay
function __construct() {
global $DB, $USER, $CFG;
$this->moduleid = 0;
$this->sectionid = 0;
$this->courseid = 0;
$this->userid = $USER->id;
// Check we have (at least) one course_module
if ($coursemodule = $DB->get_record('course_modules', array(), '*', IGNORE_MULTIPLE)) {
$this->moduleid = $coursemodule->id;
$this->sectionid = $coursemodule->section;
$this->courseid = $coursemodule->course;
}
parent::__construct();
}
function skip() {
$this->skipIf(empty($this->moduleid), 'backup_check_test require at least one course module to exist');
$this->skipIf(empty($this->sectionid),'backup_check_test require at least one course section to exist');
$this->skipIf(empty($this->courseid), 'backup_check_test require at least one course to exist');
$this->skipIf(empty($this->userid),'backup_check_test require one valid user to exist');
}
function setUp() {
global $CFG;
parent::setUp();
// Avoid any file logger to be created, we'll restore original settings on tearDown()
// Fetch the rest of CFG variables to be able to restore them after tests
// and normalize default values
$this->errorlogloggerlevel = isset($CFG->backup_error_log_logger_level) ? $CFG->backup_error_log_logger_level : null;
$CFG->backup_error_log_logger_level = backup::LOG_NONE;
$this->outputindentedloggerlevel = isset($CFG->backup_output_indented_logger_level) ? $CFG->backup_output_indented_logger_level : null;
$CFG->backup_output_indented_logger_level = backup::LOG_NONE;
$this->fileloggerlevel = isset($CFG->backup_file_logger_level) ? $CFG->backup_file_logger_level : null;
$CFG->backup_file_logger_level = backup::LOG_NONE;
$this->databaseloggerlevel = isset($CFG->backup_database_logger_level) ? $CFG->backup_database_logger_level : null;
$CFG->backup_database_logger_level = backup::LOG_NONE;
$this->fileloggerextra = isset($CFG->backup_file_logger_extra) ? $CFG->backup_file_logger_extra : null;
unset($CFG->backup_file_logger_extra);
$this->fileloggerlevelextra = isset($CFG->backup_file_logger_level_extra) ? $CFG->backup_file_logger_level_extra : null;
$CFG->backup_file_logger_level_extra = backup::LOG_NONE;
$this->debugging = isset($CFG->debug) ? $CFG->debug : null;
$this->debugdisplay = isset($CFG->debugdisplay) ? $CFG->debugdisplay : null;
}
function tearDown() {
global $CFG;
// Restore original file_logger levels
if ($this->errorlogloggerlevel !== null) {
$CFG->backup_error_log_logger_level = $this->errorlogloggerlevel;
} else {
unset($CFG->backup_error_log_logger_level);
}
if ($this->outputindentedloggerlevel !== null) {
$CFG->backup_output_indented_logger_level = $this->outputindentedloggerlevel;
} else {
unset($CFG->backup_output_indented_logger_level);
}
if ($this->fileloggerlevel !== null) {
$CFG->backup_file_logger_level = $this->fileloggerlevel;
} else {
unset($CFG->backup_file_logger_level);
}
if ($this->databaseloggerlevel !== null) {
$CFG->backup_database_logger_level = $this->databaseloggerlevel;
} else {
unset($CFG->backup_database_logger_level);
}
if ($this->fileloggerextra !== null) {
$CFG->backup_file_logger_extra = $this->fileloggerextra;
} else {
unset($CFG->backup_file_logger_extra);
}
if ($this->fileloggerlevelextra !== null) {
$CFG->backup_file_logger_level_extra = $this->fileloggerlevelextra;
} else {
unset($CFG->backup_file_logger_level_extra);
}
// Restore the rest of $CFG settings
if ($this->debugging !== null) {
$CFG->debug = $this->debugging;
} else {
unset($CFG->debug);
}
if ($this->debugdisplay !== null) {
$CFG->debugdisplay = $this->debugdisplay;
} else {
unset($CFG->debugdisplay);
}
parent::tearDown();
}
/*
* test backup_check class
*/
function test_backup_check() {
// Check against existing course module/section course or fail
$this->assertTrue(backup_check::check_id(backup::TYPE_1ACTIVITY, $this->moduleid));
$this->assertTrue(backup_check::check_id(backup::TYPE_1SECTION, $this->sectionid));
$this->assertTrue(backup_check::check_id(backup::TYPE_1COURSE, $this->courseid));
$this->assertTrue(backup_check::check_user($this->userid));
// Check agains non-existing course module/section/course (0)
try {
backup_check::check_id(backup::TYPE_1ACTIVITY, 0);
$this->assertTrue(false, 'backup_controller_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_controller_exception);
$this->assertEqual($e->errorcode, 'backup_check_module_not_exists');
}
try {
backup_check::check_id(backup::TYPE_1SECTION, 0);
$this->assertTrue(false, 'backup_controller_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_controller_exception);
$this->assertEqual($e->errorcode, 'backup_check_section_not_exists');
}
try {
backup_check::check_id(backup::TYPE_1COURSE, 0);
$this->assertTrue(false, 'backup_controller_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_controller_exception);
$this->assertEqual($e->errorcode, 'backup_check_course_not_exists');
}
// Try wrong type
try {
backup_check::check_id(12345678,0);
$this->assertTrue(false, 'backup_controller_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_controller_exception);
$this->assertEqual($e->errorcode, 'backup_check_incorrect_type');
}
// Test non-existing user
$userid = 0;
try {
backup_check::check_user($userid);
$this->assertTrue(false, 'backup_controller_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_controller_exception);
$this->assertEqual($e->errorcode, 'backup_check_user_not_exists');
}
// Security check tests
// Try to pass wrong controller
try {
backup_check::check_security(new stdclass(), true);
$this->assertTrue(false, 'backup_controller_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_controller_exception);
$this->assertEqual($e->errorcode, 'backup_check_security_requires_backup_controller');
}
// Pass correct controller, check must return true in any case with $apply enabled
// and $bc must continue being mock_backup_controller
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
$this->assertTrue(backup_check::check_security($bc, true));
$this->assertTrue($bc instanceof backup_controller);
}
}
-267
View File
@@ -1,267 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
/*
* dbops tests (all)
*/
class backup_dbops_test extends UnitTestCase {
public static $includecoverage = array('backup/util/dbops');
public static $excludecoverage = array('backup/util/dbops/simpletest');
protected $moduleid; // course_modules id used for testing
protected $sectionid; // course_sections id used for testing
protected $courseid; // course id used for testing
protected $user; // user record used for testing
protected $todelete; // array of records to be deleted after tests
protected $errorlogloggerlevel; // To store $CFG->backup_error_log_logger_level
protected $fileloggerlevel; // To store level $CFG->backup_file_logger_level
protected $databaseloggerlevel; // To store $CFG->backup_database_logger_level
protected $outputindentedloggerlevel; // To store $CFG->backup_output_indented_logger_level
protected $fileloggerextra; // To store $CFG->backup_file_logger_extra
protected $fileloggerlevelextra; // To store level $CFG->backup_file_logger_level_extra
protected $debugging; // To store $CFG->debug
protected $debugdisplay; // To store $CFG->debugdisplay
function __construct() {
global $DB, $USER, $CFG;
$this->moduleid = 0;
$this->sectionid = 0;
$this->courseid = 0;
$this->userid = $USER->id;
$this->todelete = array();
// Check we have (at least) one course_module
if ($coursemodule = $DB->get_record('course_modules', array(), '*', IGNORE_MULTIPLE)) {
$this->moduleid = $coursemodule->id;
$this->sectionid = $coursemodule->section;
$this->courseid = $coursemodule->course;
}
parent::__construct();
}
function setUp() {
global $CFG;
parent::setUp();
// Avoid any file logger to be created, we'll restore original settings on tearDown()
// Fetch the rest of CFG variables to be able to restore them after tests
// and normalize default values
$this->errorlogloggerlevel = isset($CFG->backup_error_log_logger_level) ? $CFG->backup_error_log_logger_level : null;
$CFG->backup_error_log_logger_level = backup::LOG_NONE;
$this->outputindentedloggerlevel = isset($CFG->backup_output_indented_logger_level) ? $CFG->backup_output_indented_logger_level : null;
$CFG->backup_output_indented_logger_level = backup::LOG_NONE;
$this->fileloggerlevel = isset($CFG->backup_file_logger_level) ? $CFG->backup_file_logger_level : null;
$CFG->backup_file_logger_level = backup::LOG_NONE;
$this->databaseloggerlevel = isset($CFG->backup_database_logger_level) ? $CFG->backup_database_logger_level : null;
$CFG->backup_database_logger_level = backup::LOG_NONE;
$this->fileloggerextra = isset($CFG->backup_file_logger_extra) ? $CFG->backup_file_logger_extra : null;
unset($CFG->backup_file_logger_extra);
$this->fileloggerlevelextra = isset($CFG->backup_file_logger_level_extra) ? $CFG->backup_file_logger_level_extra : null;
$CFG->backup_file_logger_level_extra = backup::LOG_NONE;
$this->debugging = isset($CFG->debug) ? $CFG->debug : null;
$this->debugdisplay = isset($CFG->debugdisplay) ? $CFG->debugdisplay : null;
}
function skip() {
$this->skipIf(empty($this->moduleid), 'backup_dbops_test require at least one course module to exist');
$this->skipIf(empty($this->sectionid),'backup_dbops_test require at least one course section to exist');
$this->skipIf(empty($this->courseid), 'backup_dbops_test require at least one course to exist');
$this->skipIf(empty($this->userid),'backup_dbops_test require one valid user to exist');
}
function tearDown() {
global $DB, $CFG;
// Delete all the records marked to
foreach ($this->todelete as $todelete) {
$DB->delete_records($todelete[0], array('id' => $todelete[1]));
}
// Restore original file_logger levels
if ($this->errorlogloggerlevel !== null) {
$CFG->backup_error_log_logger_level = $this->errorlogloggerlevel;
} else {
unset($CFG->backup_error_log_logger_level);
}
if ($this->outputindentedloggerlevel !== null) {
$CFG->backup_output_indented_logger_level = $this->outputindentedloggerlevel;
} else {
unset($CFG->backup_output_indented_logger_level);
}
if ($this->fileloggerlevel !== null) {
$CFG->backup_file_logger_level = $this->fileloggerlevel;
} else {
unset($CFG->backup_file_logger_level);
}
if ($this->databaseloggerlevel !== null) {
$CFG->backup_database_logger_level = $this->databaseloggerlevel;
} else {
unset($CFG->backup_database_logger_level);
}
if ($this->fileloggerextra !== null) {
$CFG->backup_file_logger_extra = $this->fileloggerextra;
} else {
unset($CFG->backup_file_logger_extra);
}
if ($this->fileloggerlevelextra !== null) {
$CFG->backup_file_logger_level_extra = $this->fileloggerlevelextra;
} else {
unset($CFG->backup_file_logger_level_extra);
}
// Restore the rest of $CFG settings
if ($this->debugging !== null) {
$CFG->debug = $this->debugging;
} else {
unset($CFG->debug);
}
if ($this->debugdisplay !== null) {
$CFG->debugdisplay = $this->debugdisplay;
} else {
unset($CFG->debugdisplay);
}
parent::tearDown();
}
/*
* test backup_ops class
*/
function test_backup_dbops() {
// Nothing to do here, abstract class + exception, will be tested by the rest
}
/*
* test backup_controller_dbops class
*/
function test_backup_controller_dbops() {
global $DB;
$dbman = $DB->get_manager(); // Going to use some database_manager services for testing
// Instantiate non interactive backup_controller
$bc = new mock_backup_controller4dbops(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
$this->assertTrue($bc instanceof backup_controller);
// Calculate checksum
$checksum = $bc->calculate_checksum();
$this->assertEqual(strlen($checksum), 32); // is one md5
// save controller
$recid = backup_controller_dbops::save_controller($bc, $checksum);
$this->assertTrue($recid);
$this->todelete[] = array('backup_controllers', $recid); // mark this record for deletion
// save it again (should cause update to happen)
$recid2 = backup_controller_dbops::save_controller($bc, $checksum);
$this->assertTrue($recid2);
$this->todelete[] = array('backup_controllers', $recid2); // mark this record for deletion
$this->assertEqual($recid, $recid2); // Same record in both save operations
// Try incorrect checksum
$bc = new mock_backup_controller4dbops(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
$checksum = $bc->calculate_checksum();
try {
$recid = backup_controller_dbops::save_controller($bc, 'lalala');
$this->assertTrue(false, 'backup_dbops_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_dbops_exception);
$this->assertEqual($e->errorcode, 'backup_controller_dbops_saving_checksum_mismatch');
}
// Try to save non backup_controller object
$bc = new stdclass();
try {
$recid = backup_controller_dbops::save_controller($bc, 'lalala');
$this->assertTrue(false, 'backup_controller_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_controller_exception);
$this->assertEqual($e->errorcode, 'backup_controller_expected');
}
// save and load controller (by backupid). Then compare
$bc = new mock_backup_controller4dbops(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
$checksum = $bc->calculate_checksum(); // Calculate checksum
$backupid = $bc->get_backupid();
$this->assertEqual(strlen($backupid), 32); // is one md5
$recid = backup_controller_dbops::save_controller($bc, $checksum); // save controller
$this->todelete[] = array('backup_controllers', $recid); // mark this record for deletion
$newbc = backup_controller_dbops::load_controller($backupid); // load controller
$this->assertTrue($newbc instanceof backup_controller);
$newchecksum = $newbc->calculate_checksum();
$this->assertEqual($newchecksum, $checksum);
// try to load non-existing controller
try {
$bc = backup_controller_dbops::load_controller('1234567890');
$this->assertTrue(false, 'backup_dbops_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_dbops_exception);
$this->assertEqual($e->errorcode, 'backup_controller_dbops_nonexisting');
}
// backup_ids_temp table tests
// If, for any reason table exists, drop it
if ($dbman->table_exists('backup_ids_temp')) {
$dbman->drop_table(new xmldb_table('backup_ids_temp'));
}
// Check backup_ids_temp table doesn't exist
$this->assertFalse($dbman->table_exists('backup_ids_temp'));
// Create and check it exists
backup_controller_dbops::create_backup_ids_temp_table('testingid');
$this->assertTrue($dbman->table_exists('backup_ids_temp'));
// Drop and check it doesn't exists anymore
backup_controller_dbops::drop_backup_ids_temp_table('testingid');
$this->assertFalse($dbman->table_exists('backup_ids_temp'));
}
}
class mock_backup_controller4dbops extends backup_controller {
/**
* Change standard behavior so the checksum is also stored and not onlt calculated
*/
public function calculate_checksum() {
$this->checksum = parent::calculate_checksum();
return $this->checksum;
}
}
@@ -1,52 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
//require_once($CFG->dirroot . '/backup/util/helper/backup_helper.class.php');
/*
* dbops tests (all)
*/
class backup_destinations_test extends UnitTestCase {
public static $includecoverage = array('backup/util/destinations');
public static $excludecoverage = array('backup/util/destinations/simpletest');
/*
* test backup_destination class
*/
function test_backup_destination() {
}
/*
* test backup_destination_osfs class
*/
function test_backup_destination_osfs() {
}
}
@@ -1,205 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/interfaces/checksumable.class.php');
require_once($CFG->dirroot . '/backup/backup.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/base_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/error_log_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/output_indented_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/database_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/file_logger.class.php');
require_once($CFG->dirroot . '/backup/util/factories/backup_factory.class.php');
/*
* backup_factory tests (all)
*/
class backup_factories_test extends UnitTestCase {
public static $includecoverage = array('backup/util/factories');
public static $excludecoverage = array('backup/util/factories/simpletest');
protected $errorlogloggerlevel; // To store $CFG->backup_error_log_logger_level
protected $fileloggerlevel; // To store level $CFG->backup_file_logger_level
protected $databaseloggerlevel; // To store $CFG->backup_database_logger_level
protected $outputindentedloggerlevel; // To store $CFG->backup_output_indented_logger_level
protected $fileloggerextra; // To store $CFG->backup_file_logger_extra
protected $fileloggerlevelextra; // To store level $CFG->backup_file_logger_level_extra
protected $debugging; // To store $CFG->debug
protected $debugdisplay; // To store $CFG->debugdisplay
function setUp() {
global $CFG;
parent::setUp();
// Avoid any file logger to be created, we'll restore original settings on tearDown()
// Fetch the rest of CFG variables to be able to restore them after tests
// and normalize default values
$this->errorlogloggerlevel = isset($CFG->backup_error_log_logger_level) ? $CFG->backup_error_log_logger_level : null;
$CFG->backup_error_log_logger_level = backup::LOG_NONE;
$this->outputindentedloggerlevel = isset($CFG->backup_output_indented_logger_level) ? $CFG->backup_output_indented_logger_level : null;
$CFG->backup_output_indented_logger_level = backup::LOG_NONE;
$this->fileloggerlevel = isset($CFG->backup_file_logger_level) ? $CFG->backup_file_logger_level : null;
$CFG->backup_file_logger_level = backup::LOG_NONE;
$this->databaseloggerlevel = isset($CFG->backup_database_logger_level) ? $CFG->backup_database_logger_level : null;
$CFG->backup_database_logger_level = backup::LOG_NONE;
$this->fileloggerextra = isset($CFG->backup_file_logger_extra) ? $CFG->backup_file_logger_extra : null;
unset($CFG->backup_file_logger_extra);
$this->fileloggerlevelextra = isset($CFG->backup_file_logger_level_extra) ? $CFG->backup_file_logger_level_extra : null;
$CFG->backup_file_logger_level_extra = backup::LOG_NONE;
$this->debugging = isset($CFG->debug) ? $CFG->debug : null;
$this->debugdisplay = isset($CFG->debugdisplay) ? $CFG->debugdisplay : null;
}
function tearDown() {
global $CFG;
// Restore original file_logger levels
if ($this->errorlogloggerlevel !== null) {
$CFG->backup_error_log_logger_level = $this->errorlogloggerlevel;
} else {
unset($CFG->backup_error_log_logger_level);
}
if ($this->outputindentedloggerlevel !== null) {
$CFG->backup_output_indented_logger_level = $this->outputindentedloggerlevel;
} else {
unset($CFG->backup_output_indented_logger_level);
}
if ($this->fileloggerlevel !== null) {
$CFG->backup_file_logger_level = $this->fileloggerlevel;
} else {
unset($CFG->backup_file_logger_level);
}
if ($this->databaseloggerlevel !== null) {
$CFG->backup_database_logger_level = $this->databaseloggerlevel;
} else {
unset($CFG->backup_database_logger_level);
}
if ($this->fileloggerextra !== null) {
$CFG->backup_file_logger_extra = $this->fileloggerextra;
} else {
unset($CFG->backup_file_logger_extra);
}
if ($this->fileloggerlevelextra !== null) {
$CFG->backup_file_logger_level_extra = $this->fileloggerlevelextra;
} else {
unset($CFG->backup_file_logger_level_extra);
}
// Restore the rest of $CFG settings
if ($this->debugging !== null) {
$CFG->debug = $this->debugging;
} else {
unset($CFG->debug);
}
if ($this->debugdisplay !== null) {
$CFG->debugdisplay = $this->debugdisplay;
} else {
unset($CFG->debugdisplay);
}
parent::tearDown();
}
/*
* test get_logger_chain() method
*/
function test_backup_factory() {
global $CFG;
// Default instantiate, all levels = backup::LOG_NONE
// With debugdisplay enabled
$CFG->debugdisplay = true;
$logger1 = backup_factory::get_logger_chain(backup::INTERACTIVE_YES, backup::EXECUTION_INMEDIATE, 'test');
$this->assertTrue($logger1 instanceof error_log_logger); // 1st logger is error_log_logger
$this->assertEqual($logger1->get_level(), backup::LOG_NONE);
$logger2 = $logger1->get_next();
$this->assertTrue($logger2 instanceof output_indented_logger); // 2nd logger is output_indented_logger
$this->assertEqual($logger2->get_level(), backup::LOG_NONE);
$logger3 = $logger2->get_next();
$this->assertTrue($logger3 instanceof file_logger); // 3rd logger is file_logger
$this->assertEqual($logger3->get_level(), backup::LOG_NONE);
$logger4 = $logger3->get_next();
$this->assertTrue($logger4 instanceof database_logger); // 4th logger is database_logger
$this->assertEqual($logger4->get_level(), backup::LOG_NONE);
$logger5 = $logger4->get_next();
$this->assertTrue($logger5 === null);
// With debugdisplay disabled
$CFG->debugdisplay = false;
$logger1 = backup_factory::get_logger_chain(backup::INTERACTIVE_YES, backup::EXECUTION_INMEDIATE, 'test');
$this->assertTrue($logger1 instanceof error_log_logger); // 1st logger is error_log_logger
$this->assertEqual($logger1->get_level(), backup::LOG_NONE);
$logger2 = $logger1->get_next();
$this->assertTrue($logger2 instanceof file_logger); // 2nd logger is file_logger
$this->assertEqual($logger2->get_level(), backup::LOG_NONE);
$logger3 = $logger2->get_next();
$this->assertTrue($logger3 instanceof database_logger); // 3rd logger is database_logger
$this->assertEqual($logger3->get_level(), backup::LOG_NONE);
$logger4 = $logger3->get_next();
$this->assertTrue($logger4 === null);
// Instantiate with debugging enabled and $CFG->backup_error_log_logger_level not set
$CFG->debugdisplay = true;
$CFG->debug = DEBUG_DEVELOPER;
unset($CFG->backup_error_log_logger_level);
$logger1 = backup_factory::get_logger_chain(backup::INTERACTIVE_YES, backup::EXECUTION_INMEDIATE, 'test');
$this->assertTrue($logger1 instanceof error_log_logger); // 1st logger is error_log_logger
$this->assertEqual($logger1->get_level(), backup::LOG_DEBUG); // and must have backup::LOG_DEBUG level
// Set $CFG->backup_error_log_logger_level to backup::LOG_WARNING and test again
$CFG->backup_error_log_logger_level = backup::LOG_WARNING;
$logger1 = backup_factory::get_logger_chain(backup::INTERACTIVE_YES, backup::EXECUTION_INMEDIATE, 'test');
$this->assertTrue($logger1 instanceof error_log_logger); // 1st logger is error_log_logger
$this->assertEqual($logger1->get_level(), backup::LOG_WARNING); // and must have backup::LOG_WARNING level
// Instantiate in non-interactive mode, output_indented_logger must be out
$logger1 = backup_factory::get_logger_chain(backup::INTERACTIVE_NO, backup::EXECUTION_INMEDIATE, 'test');
$logger2 = $logger1->get_next();
$this->assertTrue($logger2 instanceof file_logger); // 2nd logger is file_logger (output_indented_logger skiped)
// Define extra file logger and instantiate, should be 5th and last logger
$CFG->backup_file_logger_extra = '/tmp/test.html';
$CFG->backup_file_logger_level_extra = backup::LOG_NONE;
$logger1 = backup_factory::get_logger_chain(backup::INTERACTIVE_YES, backup::EXECUTION_INMEDIATE, 'test');
$logger2 = $logger1->get_next();
$logger3 = $logger2->get_next();
$logger4 = $logger3->get_next();
$logger5 = $logger4->get_next();
$this->assertTrue($logger5 instanceof file_logger); // 5rd logger is file_logger (extra)
$this->assertEqual($logger3->get_level(), backup::LOG_NONE);
$logger6 = $logger5->get_next();
$this->assertTrue($logger6 === null);
}
}
@@ -1,146 +0,0 @@
<?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 backup/util/helper/convert_helper.class.php
*
* @package core
* @subpackage backup-convert
* @copyright 2011 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/backup/util/helper/convert_helper.class.php');
/**
* 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);
}
}
/**
* Defines the test methods
*/
class convert_helper_test extends UnitTestCase {
public static $includecoverage = array();
public function test_choose_conversion_path() {
// no converters available
$descriptions = array();
$path = testable_convert_helper::choose_conversion_path(backup::FORMAT_MOODLE1, $descriptions);
$this->assertEqual($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->assertEqual($path, array());
$path = testable_convert_helper::choose_conversion_path('some_other_custom_format', $descriptions);
$this->assertEqual($path, array());
// single step conversion
$path = testable_convert_helper::choose_conversion_path('yet_another_crazy_custom_format', $descriptions);
$this->assertEqual($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->assertEqual($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->assertEqual($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->assertEqual($path, array('cc1', 'cc3', 'cc4'));
}
}
@@ -1,197 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
/*
* restore_decode tests (both rule and content)
*/
class restore_decode_test extends UnitTestCase {
public static $includecoverage = array(
'backup/util/helper/restore_decode_rule.class.php',
'backup/util/helper/restore_decode_content.class.php'
);
/*
* test restore_decode_rule class
*/
function test_restore_decode_rule() {
// 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->assertEqual($e->errorcode, 'decode_rule_incorrect_name');
$this->assertEqual($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->assertEqual($e->errorcode, 'decode_rule_incorrect_name');
$this->assertEqual($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->assertEqual($e->errorcode, 'decode_rule_incorrect_name');
$this->assertEqual($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->assertEqual($e->errorcode, 'decode_rule_incorrect_urltemplate');
$this->assertEqual($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->assertEqual($e->errorcode, 'decode_rule_incorrect_urltemplate');
$this->assertEqual($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->assertEqual($e->errorcode, 'decode_rule_mappings_incorrect_count');
$this->assertEqual($e->a->placeholders, 3);
$this->assertEqual($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->assertEqual($e->errorcode, 'decode_rule_nonconsecutive_placeholders');
$this->assertEqual($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->assertEqual($e->errorcode, 'decode_rule_nonconsecutive_placeholders');
$this->assertEqual($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->assertEqual($e->errorcode, 'decode_rule_duplicate_placeholders');
$this->assertEqual($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->assertEqual($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->assertEqual($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->assertEqual($dr->decode($content), $result);
}
/*
* test restore_decode_content class
*/
function test_restore_decode_content() {
// TODO: restore_decode_content tests
}
/*
* test restore_decode_processor class
*/
function test_restore_decode_processor() {
// 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;
}
}
@@ -1,55 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
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)
*/
class backup_helper_test extends UnitTestCase {
public static $includecoverage = array('backup/util/helper');
public static $excludecoverage = array('backup/util/helper/simpletest');
/*
* test backup_helper class
*/
function test_backup_helper() {
}
/*
* test backup_general_helper class
*/
function test_backup_general_helper() {
}
}
@@ -1,395 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/interfaces/checksumable.class.php');
require_once($CFG->dirroot . '/backup/backup.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/base_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/error_log_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/output_text_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/output_indented_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/database_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/file_logger.class.php');
/*
* logger tests (all)
*/
class logger_test extends UnitTestCase {
public static $includecoverage = array('backup/util/loggers');
public static $excludecoverage = array('backup/util/loggers/simpletest');
/*
* test base_logger class
*/
function test_base_logger() {
// Test logger with simple action (message * level)
$lo = new mock_base_logger1(backup::LOG_ERROR);
$msg = 13;
$this->assertEqual($lo->process($msg, backup::LOG_ERROR), $msg * backup::LOG_ERROR);
// With lowest level must resturn true
$lo = new mock_base_logger1(backup::LOG_ERROR);
$msg = 13;
$this->assertTrue($lo->process($msg, backup::LOG_DEBUG));
// Chain 2 loggers, we must get as result the result of the ineer one
$lo1 = new mock_base_logger1(backup::LOG_ERROR);
$lo2 = new mock_base_logger2(backup::LOG_ERROR);
$lo1->set_next($lo2);
$msg = 13;
$this->assertEqual($lo1->process($msg, backup::LOG_ERROR), $msg + backup::LOG_ERROR);
// Try circular reference
$lo1 = new mock_base_logger1(backup::LOG_ERROR);
try {
$lo1->set_next($lo1); //self
$this->assertTrue(false, 'base_logger_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_logger_exception);
$this->assertEqual($e->errorcode, 'logger_circular_reference');
$this->assertTrue($e->a instanceof stdclass);
$this->assertEqual($e->a->main, get_class($lo1));
$this->assertEqual($e->a->alreadyinchain, get_class($lo1));
}
$lo1 = new mock_base_logger1(backup::LOG_ERROR);
$lo2 = new mock_base_logger2(backup::LOG_ERROR);
$lo3 = new mock_base_logger3(backup::LOG_ERROR);
$lo1->set_next($lo2);
$lo2->set_next($lo3);
try {
$lo3->set_next($lo1);
$this->assertTrue(false, 'base_logger_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_logger_exception);
$this->assertEqual($e->errorcode, 'logger_circular_reference');
$this->assertTrue($e->a instanceof stdclass);
$this->assertEqual($e->a->main, get_class($lo1));
$this->assertEqual($e->a->alreadyinchain, get_class($lo3));
}
// Test stopper logger
$lo1 = new mock_base_logger1(backup::LOG_ERROR);
$lo2 = new mock_base_logger2(backup::LOG_ERROR);
$lo3 = new mock_base_logger3(backup::LOG_ERROR);
$lo1->set_next($lo2);
$lo2->set_next($lo3);
$this->assertFalse($lo1->process('test', backup::LOG_ERROR));
// Test checksum correct
$lo1 = new mock_base_logger1(backup::LOG_ERROR);
$lo1->is_checksum_correct(get_class($lo1) . '-' . backup::LOG_ERROR);
// Test get_levelstr()
$lo1 = new mock_base_logger1(backup::LOG_ERROR);
$this->assertEqual($lo1->get_levelstr(backup::LOG_NONE), 'undefined');
$this->assertEqual($lo1->get_levelstr(backup::LOG_ERROR), 'error');
$this->assertEqual($lo1->get_levelstr(backup::LOG_WARNING), 'warn');
$this->assertEqual($lo1->get_levelstr(backup::LOG_INFO), 'info');
$this->assertEqual($lo1->get_levelstr(backup::LOG_DEBUG), 'debug');
}
/*
* test error_log_logger class
*/
function test_error_log_logger() {
// Not much really to test, just intantiate and execute, should return true
$lo = new error_log_logger(backup::LOG_ERROR);
$this->assertTrue($lo instanceof error_log_logger);
$message = 'This log exists because you have run Moodle unit tests: Ignore it';
$result = $lo->process($message, backup::LOG_ERROR);
$this->assertTrue($result);
}
/*
* test output_text_logger class
*/
function test_output_text_logger() {
// Instantiate without date nor level output
$lo = new output_text_logger(backup::LOG_ERROR);
$this->assertTrue($lo instanceof output_text_logger);
$message = 'testing output_text_logger';
ob_start(); // Capture output
$result = $lo->process($message, backup::LOG_ERROR);
$contents = ob_get_contents();
ob_end_clean(); // End capture and discard
$this->assertTrue($result);
$this->assertTrue(strpos($contents, $message) !== false);
// Instantiate with date and level output
$lo = new output_text_logger(backup::LOG_ERROR, true, true);
$this->assertTrue($lo instanceof output_text_logger);
$message = 'testing output_text_logger';
ob_start(); // Capture output
$result = $lo->process($message, backup::LOG_ERROR);
$contents = ob_get_contents();
ob_end_clean(); // End capture and discard
$this->assertTrue($result);
$this->assertTrue(strpos($contents,'[') === 0);
$this->assertTrue(strpos($contents,'[error]') !== false);
$this->assertTrue(strpos($contents, $message) !== false);
$this->assertTrue(substr_count($contents , '] ') >= 2);
}
/*
* test output_indented_logger class
*/
function test_output_indented_logger() {
// Instantiate without date nor level output
$options = array('depth' => 2);
$lo = new output_indented_logger(backup::LOG_ERROR);
$this->assertTrue($lo instanceof output_indented_logger);
$message = 'testing output_indented_logger';
ob_start(); // Capture output
$result = $lo->process($message, backup::LOG_ERROR, $options);
$contents = ob_get_contents();
ob_end_clean(); // End capture and discard
$this->assertTrue($result);
if (defined('STDOUT')) {
$check = ' ';
} else {
$check = '&nbsp;&nbsp;';
}
$this->assertTrue(strpos($contents, str_repeat($check, $options['depth']) . $message) !== false);
// Instantiate with date and level output
$options = array('depth' => 3);
$lo = new output_indented_logger(backup::LOG_ERROR, true, true);
$this->assertTrue($lo instanceof output_indented_logger);
$message = 'testing output_indented_logger';
ob_start(); // Capture output
$result = $lo->process($message, backup::LOG_ERROR, $options);
$contents = ob_get_contents();
ob_end_clean(); // End capture and discard
$this->assertTrue($result);
$this->assertTrue(strpos($contents,'[') === 0);
$this->assertTrue(strpos($contents,'[error]') !== false);
$this->assertTrue(strpos($contents, $message) !== false);
$this->assertTrue(substr_count($contents , '] ') >= 2);
if (defined('STDOUT')) {
$check = ' ';
} else {
$check = '&nbsp;&nbsp;';
}
$this->assertTrue(strpos($contents, str_repeat($check, $options['depth']) . $message) !== false);
}
/*
* test database_logger class
*/
function test_database_logger() {
// Instantiate with date and level output (and with specs from the global moodle "log" table so checks will pass
$now = time();
$datecol = 'time';
$levelcol = 'action';
$messagecol = 'info';
$logtable = 'log';
$columns = array('url' => 'http://127.0.0.1');
$loglevel = backup::LOG_ERROR;
$lo = new mock_database_logger(backup::LOG_ERROR, $datecol, $levelcol, $messagecol, $logtable, $columns);
$this->assertTrue($lo instanceof database_logger);
$message = 'testing database_logger';
$result = $lo->process($message, $loglevel);
// Check everything is ready to be inserted to DB
$this->assertEqual($result['table'], $logtable);
$this->assertTrue($result['columns'][$datecol] >= $now);
$this->assertEqual($result['columns'][$levelcol], $loglevel);
$this->assertEqual($result['columns'][$messagecol], $message);
$this->assertEqual($result['columns']['url'], $columns['url']);
}
/*
* test file_logger class
*/
function test_file_logger() {
global $CFG;
$file = $CFG->tempdir . '/test/test_file_logger.txt';
// Remove the test dir and any content
@remove_dir(dirname($file));
// Recreate test dir
if (!check_dir_exists(dirname($file), true, true)) {
throw new moodle_exception('error_creating_temp_dir', 'error', dirname($file));
}
// Instantiate with date and level output, and also use the depth option
$options = array('depth' => 3);
$lo1 = new file_logger(backup::LOG_ERROR, true, true, $file);
$this->assertTrue($lo1 instanceof file_logger);
$message1 = 'testing file_logger';
$result = $lo1->process($message1, backup::LOG_ERROR, $options);
$this->assertTrue($result);
// Another file_logger is going towrite there too without closing
$options = array();
$lo2 = new file_logger(backup::LOG_WARNING, true, true, $file);
$this->assertTrue($lo2 instanceof file_logger);
$message2 = 'testing file_logger2';
$result = $lo2->process($message2, backup::LOG_WARNING, $options);
$this->assertTrue($result);
// Destruct loggers
$lo1 = null;
$lo2 = null;
// Load file results to analyze them
$fcontents = file_get_contents($file);
$acontents = explode(PHP_EOL, $fcontents); // Split by line
$this->assertTrue(strpos($acontents[0], $message1) !== false);
$this->assertTrue(strpos($acontents[0], '[error]') !== false);
$this->assertTrue(strpos($acontents[0], ' ') !== false);
$this->assertTrue(substr_count($acontents[0] , '] ') >= 2);
$this->assertTrue(strpos($acontents[1], $message2) !== false);
$this->assertTrue(strpos($acontents[1], '[warn]') !== false);
$this->assertTrue(strpos($acontents[1], ' ') === false);
$this->assertTrue(substr_count($acontents[1] , '] ') >= 2);
unlink($file); // delete file
// Try one html file
check_dir_exists($CFG->tempdir . '/test');
$file = $CFG->tempdir . '/test/test_file_logger.html';
$options = array('depth' => 1);
$lo = new file_logger(backup::LOG_ERROR, true, true, $file);
$this->assertTrue($lo instanceof file_logger);
$this->assertTrue(file_exists($file));
$message = 'testing file_logger';
$result = $lo->process($message, backup::LOG_ERROR, $options);
// Get file contents and inspect them
$fcontents = file_get_contents($file);
$this->assertTrue($result);
$this->assertTrue(strpos($fcontents, $message) !== false);
$this->assertTrue(strpos($fcontents, '[error]') !== false);
$this->assertTrue(strpos($fcontents, '&nbsp;&nbsp;') !== false);
$this->assertTrue(substr_count($fcontents , '] ') >= 2);
unlink($file); // delete file
// Instantiate, write something, force deletion, try to write again
check_dir_exists($CFG->tempdir . '/test');
$file = $CFG->tempdir . '/test/test_file_logger.html';
$lo = new mock_file_logger(backup::LOG_ERROR, true, true, $file);
$this->assertTrue(file_exists($file));
$message = 'testing file_logger';
$result = $lo->process($message, backup::LOG_ERROR);
fclose($lo->get_fhandle()); // close file
try {
$result = @$lo->process($message, backup::LOG_ERROR); // Try to write again
$this->assertTrue(false, 'base_logger_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_logger_exception);
$this->assertEqual($e->errorcode, 'error_writing_file');
}
// Instantiate without file
try {
$lo = new file_logger(backup::LOG_WARNING, true, true, '');
$this->assertTrue(false, 'base_logger_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_logger_exception);
$this->assertEqual($e->errorcode, 'missing_fullpath_parameter');
}
// Instantiate in (near) impossible path
$file = $CFG->tempdir . '/test_azby/test_file_logger.txt';
try {
$lo = new file_logger(backup::LOG_WARNING, true, true, $file);
$this->assertTrue(false, 'base_logger_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_logger_exception);
$this->assertEqual($e->errorcode, 'file_not_writable');
$this->assertEqual($e->a, $file);
}
// Instatiate one file logger with level = backup::LOG_NONE
$file = $CFG->tempdir . '/test/test_file_logger.txt';
$lo = new file_logger(backup::LOG_NONE, true, true, $file);
$this->assertTrue($lo instanceof file_logger);
$this->assertFalse(file_exists($file));
// Remove the test dir and any content
@remove_dir(dirname($file));
}
}
/*
* helper extended base_logger class that implements some methods for testing
* Simply return the product of message and level
*/
class mock_base_logger1 extends base_logger {
protected function action($message, $level, $options = null) {
return $message * $level; // Simply return that, for testing
}
public function get_levelstr($level) {
return parent::get_levelstr($level);
}
}
/*
* helper extended base_logger class that implements some methods for testing
* Simply return the sum of message and level
*/
class mock_base_logger2 extends base_logger {
protected function action($message, $level, $options = null) {
return $message + $level; // Simply return that, for testing
}
}
/*
* helper extended base_logger class that implements some methods for testing
* Simply return 8
*/
class mock_base_logger3 extends base_logger {
protected function action($message, $level, $options = null) {
return false; // Simply return false, for testing stopper
}
}
/*
* helper extended database_logger class that implements some methods for testing
* Returns the complete info that normally will be used by insert record calls
*/
class mock_database_logger extends database_logger {
protected function insert_log_record($table, $columns) {
return array('table' => $table, 'columns' => $columns);
}
}
/*
* helper extended file_logger class that implements some methods for testing
* Returns the, usually protected, fhandle
*/
class mock_file_logger extends file_logger {
function get_fhandle() {
return $this->fhandle;
}
}
-211
View File
@@ -1,211 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
/*
* plan tests (all)
*/
class backup_plan_test extends UnitTestCase {
public static $includecoverage = array('backup/util/plan');
public static $excludecoverage = array('backup/util/plan/simpletest');
protected $moduleid; // course_modules id used for testing
protected $sectionid; // course_sections id used for testing
protected $courseid; // course id used for testing
protected $user; // user record used for testing
function __construct() {
global $DB, $USER, $CFG;
$this->moduleid = 0;
$this->sectionid = 0;
$this->courseid = 0;
$this->userid = $USER->id;
$this->todelete = array();
// Check we have (at least) one course_module
if ($coursemodule = $DB->get_record('course_modules', array(), '*', IGNORE_MULTIPLE)) {
$this->moduleid = $coursemodule->id;
$this->sectionid = $coursemodule->section;
$this->courseid = $coursemodule->course;
}
// Avoid any logger to be created, we'll restore original settings on tearDown()
$this->errorlogloggerlevel = isset($CFG->backup_error_log_logger_level) ? $CFG->backup_error_log_logger_level : null;
$this->fileloggerlevel = isset($CFG->backup_file_logger_level) ? $CFG->backup_file_logger_level : null;
$this->databaseloggerlevel = isset($CFG->backup_database_logger_level) ? $CFG->backup_database_logger_level : null;
$this->fileloggerlevelextra = isset($CFG->backup_file_logger_level_extra) ? $CFG->backup_file_logger_level_extra : null;
parent::__construct();
}
function skip() {
$this->skipIf(empty($this->moduleid), 'backup_plan_test require at least one course module to exist');
$this->skipIf(empty($this->sectionid),'backup_plan_test require at least one course section to exist');
$this->skipIf(empty($this->courseid), 'backup_plan_test require at least one course to exist');
$this->skipIf(empty($this->userid),'backup_plan_test require one valid user to exist');
}
function setUp() {
global $CFG;
// Disable all loggers
$CFG->backup_error_log_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;
}
function tearDown() {
global $DB, $CFG;
// Delete all the records marked to
foreach ($this->todelete as $todelete) {
$DB->delete_records($todelete[0], array('id' => $todelete[1]));
}
// Restore original file_logger levels
if ($this->errorlogloggerlevel !== null) {
$CFG->backup_error_log_logger_level = $this->errorlogloggerlevel;
} else {
unset($CFG->backup_error_log_logger_level);
}
if ($this->fileloggerlevel !== null) {
$CFG->backup_file_logger_level = $this->fileloggerlevel;
} else {
unset($CFG->backup_file_logger_level);
}
if ($this->databaseloggerlevel !== null) {
$CFG->backup_database_logger_level = $this->databaseloggerlevel;
} else {
unset($CFG->backup_database_logger_level);
}
if ($this->fileloggerlevelextra !== null) {
$CFG->backup_file_logger_level_extra = $this->fileloggerlevelextra;
} else {
unset($CFG->backup_file_logger_level_extra);
}
}
/**
* test base_plan class
*/
function test_base_plan() {
// Instantiate
$bp = new mock_base_plan('name');
$this->assertTrue($bp instanceof base_plan);
$this->assertEqual($bp->get_name(), 'name');
$this->assertTrue(is_array($bp->get_settings()));
$this->assertEqual(count($bp->get_settings()), 0);
$this->assertTrue(is_array($bp->get_tasks()));
$this->assertEqual(count($bp->get_tasks()), 0);
}
/*
* test backup_plan class
*/
function test_backup_plan() {
// We need one (non interactive) controller for instatiating plan
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
// Instantiate one backup plan
$bp = new backup_plan($bc);
$this->assertTrue($bp instanceof backup_plan);
$this->assertEqual($bp->get_name(), 'backup_plan');
// Calculate checksum and check it
$checksum = $bp->calculate_checksum();
$this->assertTrue($bp->is_checksum_correct($checksum));
}
/**
* wrong base_plan class tests
*/
function test_base_plan_wrong() {
// We need one (non interactive) controller for instatiating plan
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
// Instantiate one backup plan
$bp = new backup_plan($bc);
// Add wrong task
try {
$bp->add_task(new stdclass());
$this->assertTrue(false, 'base_plan_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_plan_exception);
$this->assertEqual($e->errorcode, 'wrong_base_task_specified');
}
}
/**
* wrong backup_plan class tests
*/
function test_backup_plan_wrong() {
// Try to pass one wrong controller
try {
$bp = new backup_plan(new stdclass());
$this->assertTrue(false, 'backup_plan_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_plan_exception);
$this->assertEqual($e->errorcode, 'wrong_backup_controller_specified');
}
try {
$bp = new backup_plan(null);
$this->assertTrue(false, 'backup_plan_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_plan_exception);
$this->assertEqual($e->errorcode, 'wrong_backup_controller_specified');
}
// Try to build one non-existent format plan (when creating the controller)
// We need one (non interactive) controller for instatiating plan
try {
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, 'non_existing_format',
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
$this->assertTrue(false, 'backup_controller_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_controller_exception);
$this->assertEqual($e->errorcode, 'backup_check_unsupported_format');
$this->assertEqual($e->a, 'non_existing_format');
}
}
}
/**
* Instantiable class extending base_plan in order to be able to perform tests
*/
class mock_base_plan extends base_plan {
public function build() {
}
}
-336
View File
@@ -1,336 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/interfaces/checksumable.class.php');
require_once($CFG->dirroot . '/backup/util/interfaces/processable.class.php');
require_once($CFG->dirroot . '/backup/util/interfaces/annotable.class.php');
require_once($CFG->dirroot . '/backup/util/interfaces/executable.class.php');
require_once($CFG->dirroot . '/backup/backup.class.php');
require_once($CFG->dirroot . '/backup/util/factories/backup_factory.class.php');
require_once($CFG->dirroot . '/backup/util/helper/backup_array_iterator.class.php');
require_once($CFG->dirroot . '/backup/util/dbops/backup_dbops.class.php');
require_once($CFG->dirroot . '/backup/util/dbops/backup_controller_dbops.class.php');
require_once($CFG->dirroot . '/backup/util/dbops/backup_structure_dbops.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');
require_once($CFG->dirroot . '/backup/util/checks/backup_check.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/base_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/error_log_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/file_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/database_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/output_indented_logger.class.php');
require_once($CFG->dirroot . '/backup/util/xml/output/xml_output.class.php');
require_once($CFG->dirroot . '/backup/util/xml/output/file_xml_output.class.php');
require_once($CFG->dirroot . '/backup/util/xml/xml_writer.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_atom.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_attribute.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_final_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_nested_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_optigroup.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_processor.class.php');
require_once($CFG->dirroot . '/backup/util/structure/backup_attribute.class.php');
require_once($CFG->dirroot . '/backup/util/structure/backup_final_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/backup_nested_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/backup_optigroup.class.php');
require_once($CFG->dirroot . '/backup/util/structure/backup_optigroup_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/backup_structure_processor.class.php');
require_once($CFG->dirroot . '/backup/controller/backup_controller.class.php');
require_once($CFG->dirroot . '/backup/util/settings/base_setting.class.php');
require_once($CFG->dirroot . '/backup/util/settings/backup_setting.class.php');
require_once($CFG->dirroot . '/backup/util/settings/activity/activity_backup_setting.class.php');
require_once($CFG->dirroot . '/backup/util/plan/base_plan.class.php');
require_once($CFG->dirroot . '/backup/util/plan/backup_plan.class.php');
require_once($CFG->dirroot . '/backup/util/plan/base_task.class.php');
require_once($CFG->dirroot . '/backup/util/plan/backup_task.class.php');
require_once($CFG->dirroot . '/backup/util/plan/base_step.class.php');
require_once($CFG->dirroot . '/backup/util/plan/backup_step.class.php');
require_once($CFG->dirroot . '/backup/util/plan/backup_structure_step.class.php');
/*
* step tests (all)
*/
class backup_step_test extends UnitTestCase {
public static $includecoverage = array('backup/util/plan');
public static $excludecoverage = array('backup/util/plan/simpletest');
protected $moduleid; // course_modules id used for testing
protected $sectionid; // course_sections id used for testing
protected $courseid; // course id used for testing
protected $user; // user record used for testing
function __construct() {
global $DB, $USER, $CFG;
$this->moduleid = 0;
$this->sectionid = 0;
$this->courseid = 0;
$this->userid = $USER->id;
$this->todelete = array();
// Check we have (at least) one course_module
if ($coursemodule = $DB->get_record('course_modules', array(), '*', IGNORE_MULTIPLE)) {
$this->moduleid = $coursemodule->id;
$this->sectionid = $coursemodule->section;
$this->courseid = $coursemodule->course;
}
// Avoid any logger to be created, we'll restore original settings on tearDown()
$this->errorlogloggerlevel = isset($CFG->backup_error_log_logger_level) ? $CFG->backup_error_log_logger_level : null;
$this->fileloggerlevel = isset($CFG->backup_file_logger_level) ? $CFG->backup_file_logger_level : null;
$this->databaseloggerlevel = isset($CFG->backup_database_logger_level) ? $CFG->backup_database_logger_level : null;
$this->fileloggerlevelextra = isset($CFG->backup_file_logger_level_extra) ? $CFG->backup_file_logger_level_extra : null;
parent::__construct();
}
function skip() {
$this->skipIf(empty($this->moduleid), 'backup_step_test require at least one course module to exist');
$this->skipIf(empty($this->sectionid),'backup_step_test require at least one course section to exist');
$this->skipIf(empty($this->courseid), 'backup_step_test require at least one course to exist');
$this->skipIf(empty($this->userid),'backup_step_test require one valid user to exist');
}
function setUp() {
global $CFG;
// Disable all loggers
$CFG->backup_error_log_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;
}
function tearDown() {
global $DB, $CFG;
// Delete all the records marked to
foreach ($this->todelete as $todelete) {
$DB->delete_records($todelete[0], array('id' => $todelete[1]));
}
// Restore original file_logger levels
if ($this->errorlogloggerlevel !== null) {
$CFG->backup_error_log_logger_level = $this->errorlogloggerlevel;
} else {
unset($CFG->backup_error_log_logger_level);
}
if ($this->fileloggerlevel !== null) {
$CFG->backup_file_logger_level = $this->fileloggerlevel;
} else {
unset($CFG->backup_file_logger_level);
}
if ($this->databaseloggerlevel !== null) {
$CFG->backup_database_logger_level = $this->databaseloggerlevel;
} else {
unset($CFG->backup_database_logger_level);
}
if ($this->fileloggerlevelextra !== null) {
$CFG->backup_file_logger_level_extra = $this->fileloggerlevelextra;
} else {
unset($CFG->backup_file_logger_level_extra);
}
}
/**
* test base_step class
*/
function test_base_step() {
$bp = new mock_base_plan('planname'); // We need one plan
$bt = new mock_base_task('taskname', $bp); // We need one task
// Instantiate
$bs = new mock_base_step('stepname', $bt);
$this->assertTrue($bs instanceof base_step);
$this->assertEqual($bs->get_name(), 'stepname');
}
/*
* test backup_step class
*/
function test_backup_step() {
// We need one (non interactive) controller for instatiating plan
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
// We need one plan
$bp = new backup_plan($bc);
// We need one task
$bt = new mock_backup_task('taskname', $bp);
// Instantiate step
$bs = new mock_backup_step('stepname', $bt);
$this->assertTrue($bs instanceof backup_step);
$this->assertEqual($bs->get_name(), 'stepname');
}
/**
* test backup_structure_step class
*/
function test_backup_structure_step() {
global $CFG;
$file = $CFG->tempdir . '/test/test_backup_structure_step.txt';
// Remove the test dir and any content
@remove_dir(dirname($file));
// Recreate test dir
if (!check_dir_exists(dirname($file), true, true)) {
throw new moodle_exception('error_creating_temp_dir', 'error', dirname($file));
}
// We need one (non interactive) controller for instatiating plan
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
// We need one plan
$bp = new backup_plan($bc);
// We need one task with mocked basepath
$bt = new mock_backup_task_basepath('taskname');
$bp->add_task($bt);
// Instantiate backup_structure_step (and add it to task)
$bs = new mock_backup_structure_step('steptest', basename($file), $bt);
// Execute backup_structure_step
$bs->execute();
// Test file has been created
$this->assertTrue(file_exists($file));
// Some simple tests with contents
$contents = file_get_contents($file);
$this->assertTrue(strpos($contents, '<?xml version="1.0"') !== false);
$this->assertTrue(strpos($contents, '<test id="1">') !== false);
$this->assertTrue(strpos($contents, '<field1>value1</field1>') !== false);
$this->assertTrue(strpos($contents, '<field2>value2</field2>') !== false);
$this->assertTrue(strpos($contents, '</test>') !== false);
unlink($file); // delete file
// Remove the test dir and any content
@remove_dir(dirname($file));
}
/**
* wrong base_step class tests
*/
function test_base_step_wrong() {
// Try to pass one wrong task
try {
$bt = new mock_base_step('teststep', new stdclass());
$this->assertTrue(false, 'base_step_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_step_exception);
$this->assertEqual($e->errorcode, 'wrong_base_task_specified');
}
}
/**
* wrong backup_step class tests
*/
function test_backup_test_wrong() {
// Try to pass one wrong task
try {
$bt = new mock_backup_step('teststep', new stdclass());
$this->assertTrue(false, 'backup_step_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_step_exception);
$this->assertEqual($e->errorcode, 'wrong_backup_task_specified');
}
}
}
/**
* Instantiable class extending base_step in order to be able to perform tests
*/
class mock_base_step extends base_step {
public function execute() {
}
}
/**
* Instantiable class extending backup_step in order to be able to perform tests
*/
class mock_backup_step extends backup_step {
public function execute() {
}
}
/**
* Instantiable class extending backup_task in order to mockup get_taskbasepath()
*/
class mock_backup_task_basepath extends backup_task {
public function build() {
// Nothing to do
}
public function define_settings() {
// Nothing to do
}
public function get_taskbasepath() {
global $CFG;
return $CFG->tempdir . '/test';
}
}
/**
* Instantiable class extending backup_structure_step in order to be able to perform tests
*/
class mock_backup_structure_step extends backup_structure_step {
protected function define_structure() {
// Create really simple structure (1 nested with 1 attr and 2 fields)
$test = new backup_nested_element('test',
array('id'),
array('field1', 'field2')
);
$test->set_source_array(array(array('id' => 1, 'field1' => 'value1', 'field2' => 'value2')));
return $test;
}
}
/**
* Instantiable class extending activity_backup_setting to be added to task and perform tests
*/
class mock_fullpath_activity_setting extends activity_backup_setting {
public function process_change($setting, $ctype, $oldv) {
// Nothing to do
}
}
/**
* Instantiable class extending activity_backup_setting to be added to task and perform tests
*/
class mock_backupid_activity_setting extends activity_backup_setting {
public function process_change($setting, $ctype, $oldv) {
// Nothing to do
}
}
-236
View File
@@ -1,236 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/interfaces/checksumable.class.php');
require_once($CFG->dirroot . '/backup/util/interfaces/executable.class.php');
require_once($CFG->dirroot . '/backup/backup.class.php');
require_once($CFG->dirroot . '/backup/util/factories/backup_factory.class.php');
require_once($CFG->dirroot . '/backup/util/dbops/backup_dbops.class.php');
require_once($CFG->dirroot . '/backup/util/dbops/backup_controller_dbops.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');
require_once($CFG->dirroot . '/backup/util/checks/backup_check.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/base_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/error_log_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/file_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/database_logger.class.php');
require_once($CFG->dirroot . '/backup/util/loggers/output_indented_logger.class.php');
require_once($CFG->dirroot . '/backup/controller/backup_controller.class.php');
require_once($CFG->dirroot . '/backup/util/plan/base_plan.class.php');
require_once($CFG->dirroot . '/backup/util/plan/backup_plan.class.php');
require_once($CFG->dirroot . '/backup/util/plan/base_task.class.php');
require_once($CFG->dirroot . '/backup/util/plan/backup_task.class.php');
/*
* task tests (all)
*/
class backup_task_test extends UnitTestCase {
public static $includecoverage = array('backup/util/plan');
public static $excludecoverage = array('backup/util/plan/simpletest');
protected $moduleid; // course_modules id used for testing
protected $sectionid; // course_sections id used for testing
protected $courseid; // course id used for testing
protected $user; // user record used for testing
function __construct() {
global $DB, $USER, $CFG;
$this->moduleid = 0;
$this->sectionid = 0;
$this->courseid = 0;
$this->userid = $USER->id;
$this->todelete = array();
// Check we have (at least) one course_module
if ($coursemodule = $DB->get_record('course_modules', array(), '*', IGNORE_MULTIPLE)) {
$this->moduleid = $coursemodule->id;
$this->sectionid = $coursemodule->section;
$this->courseid = $coursemodule->course;
}
// Avoid any logger to be created, we'll restore original settings on tearDown()
$this->errorlogloggerlevel = isset($CFG->backup_error_log_logger_level) ? $CFG->backup_error_log_logger_level : null;
$this->fileloggerlevel = isset($CFG->backup_file_logger_level) ? $CFG->backup_file_logger_level : null;
$this->databaseloggerlevel = isset($CFG->backup_database_logger_level) ? $CFG->backup_database_logger_level : null;
$this->fileloggerlevelextra = isset($CFG->backup_file_logger_level_extra) ? $CFG->backup_file_logger_level_extra : null;
parent::__construct();
}
function skip() {
$this->skipIf(empty($this->moduleid), 'backup_task_test require at least one course module to exist');
$this->skipIf(empty($this->sectionid),'backup_task_test require at least one course section to exist');
$this->skipIf(empty($this->courseid), 'backup_task_test require at least one course to exist');
$this->skipIf(empty($this->userid),'backup_task_test require one valid user to exist');
}
function setUp() {
global $CFG;
// Disable all loggers
$CFG->backup_error_log_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;
}
function tearDown() {
global $DB, $CFG;
// Delete all the records marked to
foreach ($this->todelete as $todelete) {
$DB->delete_records($todelete[0], array('id' => $todelete[1]));
}
// Restore original file_logger levels
if ($this->errorlogloggerlevel !== null) {
$CFG->backup_error_log_logger_level = $this->errorlogloggerlevel;
} else {
unset($CFG->backup_error_log_logger_level);
}
if ($this->fileloggerlevel !== null) {
$CFG->backup_file_logger_level = $this->fileloggerlevel;
} else {
unset($CFG->backup_file_logger_level);
}
if ($this->databaseloggerlevel !== null) {
$CFG->backup_database_logger_level = $this->databaseloggerlevel;
} else {
unset($CFG->backup_database_logger_level);
}
if ($this->fileloggerlevelextra !== null) {
$CFG->backup_file_logger_level_extra = $this->fileloggerlevelextra;
} else {
unset($CFG->backup_file_logger_level_extra);
}
}
/**
* test base_task class
*/
function test_base_task() {
$bp = new mock_base_plan('planname'); // We need one plan
// Instantiate
$bt = new mock_base_task('taskname', $bp);
$this->assertTrue($bt instanceof base_task);
$this->assertEqual($bt->get_name(), 'taskname');
$this->assertTrue(is_array($bt->get_settings()));
$this->assertEqual(count($bt->get_settings()), 0);
$this->assertTrue(is_array($bt->get_steps()));
$this->assertEqual(count($bt->get_steps()), 0);
}
/*
* test backup_task class
*/
function test_backup_task() {
// We need one (non interactive) controller for instatiating plan
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $this->userid);
// We need one plan
$bp = new backup_plan($bc);
// Instantiate task
$bt = new mock_backup_task('taskname', $bp);
$this->assertTrue($bt instanceof backup_task);
$this->assertEqual($bt->get_name(), 'taskname');
// Calculate checksum and check it
$checksum = $bt->calculate_checksum();
$this->assertTrue($bt->is_checksum_correct($checksum));
}
/**
* wrong base_task class tests
*/
function test_base_task_wrong() {
// Try to pass one wrong plan
try {
$bt = new mock_base_task('tasktest', new stdclass());
$this->assertTrue(false, 'base_task_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_task_exception);
$this->assertEqual($e->errorcode, 'wrong_base_plan_specified');
}
// Add wrong step to task
$bp = new mock_base_plan('planname'); // We need one plan
// Instantiate
$bt = new mock_base_task('taskname', $bp);
try {
$bt->add_step(new stdclass());
$this->assertTrue(false, 'base_task_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_task_exception);
$this->assertEqual($e->errorcode, 'wrong_base_step_specified');
}
}
/**
* wrong backup_task class tests
*/
function test_backup_task_wrong() {
// Try to pass one wrong plan
try {
$bt = new mock_backup_task('tasktest', new stdclass());
$this->assertTrue(false, 'backup_task_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_task_exception);
$this->assertEqual($e->errorcode, 'wrong_backup_plan_specified');
}
}
}
/**
* Instantiable class extending base_task in order to be able to perform tests
*/
class mock_base_task extends base_task {
public function build() {
}
public function define_settings() {
}
}
/**
* Instantiable class extending backup_task in order to be able to perform tests
*/
class mock_backup_task extends backup_task {
public function build() {
}
public function define_settings() {
}
}
@@ -1,468 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/interfaces/checksumable.class.php');
require_once($CFG->dirroot . '/backup/backup.class.php');
require_once($CFG->dirroot . '/backup/util/settings/base_setting.class.php');
require_once($CFG->dirroot . '/backup/util/settings/backup_setting.class.php');
require_once($CFG->dirroot . '/backup/util/settings/setting_dependency.class.php');
require_once($CFG->dirroot . '/backup/util/settings/root/root_backup_setting.class.php');
require_once($CFG->dirroot . '/backup/util/settings/activity/activity_backup_setting.class.php');
require_once($CFG->dirroot . '/backup/util/settings/section/section_backup_setting.class.php');
require_once($CFG->dirroot . '/backup/util/settings/course/course_backup_setting.class.php');
require_once($CFG->dirroot . '/backup/util/ui/backup_ui_setting.class.php');
/*
* setting tests (all)
*/
class setting_test extends UnitTestCase {
public static $includecoverage = array('backup/util/settings');
public static $excludecoverage = array('backup/util/settings/simpletest');
/*
* test base_setting class
*/
function test_base_setting() {
// Instantiate base_setting and check everything
$bs = new mock_base_setting('test', base_setting::IS_BOOLEAN);
$this->assertTrue($bs instanceof base_setting);
$this->assertEqual($bs->get_name(), 'test');
$this->assertEqual($bs->get_vtype(), base_setting::IS_BOOLEAN);
$this->assertTrue(is_null($bs->get_value()));
$this->assertEqual($bs->get_visibility(), base_setting::VISIBLE);
$this->assertEqual($bs->get_status(), base_setting::NOT_LOCKED);
// Instantiate base_setting with explicit nulls
$bs = new mock_base_setting('test', base_setting::IS_FILENAME, 'filename.txt', null, null);
$this->assertEqual($bs->get_value() , 'filename.txt');
$this->assertEqual($bs->get_visibility(), base_setting::VISIBLE);
$this->assertEqual($bs->get_status(), base_setting::NOT_LOCKED);
// Instantiate base_setting and set value, visibility and status
$bs = new mock_base_setting('test', base_setting::IS_BOOLEAN);
$bs->set_value(true);
$this->assertTrue($bs->get_value());
$bs->set_visibility(base_setting::HIDDEN);
$this->assertEqual($bs->get_visibility(), base_setting::HIDDEN);
$bs->set_status(base_setting::LOCKED_BY_HIERARCHY);
$this->assertEqual($bs->get_status(), base_setting::LOCKED_BY_HIERARCHY);
// Instantiate with wrong vtype
try {
$bs = new mock_base_setting('test', 'one_wrong_type');
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'setting_invalid_type');
}
// Instantiate with wrong integer value
try {
$bs = new mock_base_setting('test', base_setting::IS_INTEGER, 99.99);
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'setting_invalid_integer');
}
// Instantiate with wrong filename value
try {
$bs = new mock_base_setting('test', base_setting::IS_FILENAME, '../../filename.txt');
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'setting_invalid_filename');
}
// Instantiate with wrong visibility
try {
$bs = new mock_base_setting('test', base_setting::IS_BOOLEAN, null, 'one_wrong_visibility');
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'setting_invalid_visibility');
}
// Instantiate with wrong status
try {
$bs = new mock_base_setting('test', base_setting::IS_BOOLEAN, null, null, 'one_wrong_status');
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'setting_invalid_status');
}
// Instantiate base_setting and try to set wrong ui_type
// We need a custom error handler to catch the type hinting error
// that should return incorrect_object_passed
$bs = new mock_base_setting('test', base_setting::IS_BOOLEAN);
set_error_handler('backup_setting_error_handler', E_RECOVERABLE_ERROR);
try {
$bs->set_ui('one_wrong_ui_type', 'label', array(), array());
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'incorrect_object_passed');
}
restore_error_handler();
// Instantiate base_setting and try to set wrong ui_label
// We need a custom error handler to catch the type hinting error
// that should return incorrect_object_passed
$bs = new mock_base_setting('test', base_setting::IS_BOOLEAN);
set_error_handler('backup_setting_error_handler', E_RECOVERABLE_ERROR);
try {
$bs->set_ui(base_setting::UI_HTML_CHECKBOX, 'one/wrong/label', array(), array());
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'incorrect_object_passed');
}
restore_error_handler();
// Try to change value of locked setting by permission
$bs = new mock_base_setting('test', base_setting::IS_BOOLEAN, null, null, base_setting::LOCKED_BY_PERMISSION);
try {
$bs->set_value(true);
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'setting_locked_by_permission');
}
// Try to change value of locked setting by config
$bs = new mock_base_setting('test', base_setting::IS_BOOLEAN, null, null, base_setting::LOCKED_BY_CONFIG);
try {
$bs->set_value(true);
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'setting_locked_by_config');
}
// Try to add same setting twice
$bs1 = new mock_base_setting('test1', base_setting::IS_INTEGER, null);
$bs2 = new mock_base_setting('test2', base_setting::IS_INTEGER, null);
$bs1->add_dependency($bs2, null, array('value'=>0));
try {
$bs1->add_dependency($bs2);
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'setting_already_added');
}
// Try to create one circular reference
$bs1 = new mock_base_setting('test1', base_setting::IS_INTEGER, null);
try {
$bs1->add_dependency($bs1); // self
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'setting_circular_reference');
$this->assertTrue($e->a instanceof stdclass);
$this->assertEqual($e->a->main, 'test1');
$this->assertEqual($e->a->alreadydependent, 'test1');
}
$bs1 = new mock_base_setting('test1', base_setting::IS_INTEGER, null);
$bs2 = new mock_base_setting('test2', base_setting::IS_INTEGER, null);
$bs3 = new mock_base_setting('test3', base_setting::IS_INTEGER, null);
$bs4 = new mock_base_setting('test4', base_setting::IS_INTEGER, null);
$bs1->add_dependency($bs2, null, array('value'=>0));
$bs2->add_dependency($bs3, null, array('value'=>0));
$bs3->add_dependency($bs4, null, array('value'=>0));
try {
$bs4->add_dependency($bs1, null, array('value'=>0));
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'setting_circular_reference');
$this->assertTrue($e->a instanceof stdclass);
$this->assertEqual($e->a->main, 'test1');
$this->assertEqual($e->a->alreadydependent, 'test4');
}
$bs1 = new mock_base_setting('test1', base_setting::IS_INTEGER, null);
$bs2 = new mock_base_setting('test2', base_setting::IS_INTEGER, null);
$bs1->register_dependency(new setting_dependency_disabledif_empty($bs1, $bs2));
try {
// $bs1 is already dependent on $bs2 so this should fail.
$bs2->register_dependency(new setting_dependency_disabledif_empty($bs2, $bs1));
$this->assertTrue(false, 'base_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_setting_exception);
$this->assertEqual($e->errorcode, 'setting_circular_reference');
$this->assertTrue($e->a instanceof stdclass);
$this->assertEqual($e->a->main, 'test1');
$this->assertEqual($e->a->alreadydependent, 'test2');
}
// Create 3 settings and observe between them, last one must
// automatically inherit all the settings defined in the main one
$bs1 = new mock_base_setting('test1', base_setting::IS_INTEGER, null);
$bs2 = new mock_base_setting('test2', base_setting::IS_INTEGER, null);
$bs3 = new mock_base_setting('test3', base_setting::IS_INTEGER, null);
$bs1->add_dependency($bs2, setting_dependency::DISABLED_NOT_EMPTY);
$bs2->add_dependency($bs3, setting_dependency::DISABLED_NOT_EMPTY);
// Check values are spreaded ok
$bs1->set_value(123);
$this->assertEqual($bs1->get_value(), 123);
$this->assertEqual($bs2->get_value(), $bs1->get_value());
$this->assertEqual($bs3->get_value(), $bs1->get_value());
// Add one more setting and set value again
$bs4 = new mock_base_setting('test4', base_setting::IS_INTEGER, null);
$bs2->add_dependency($bs4, setting_dependency::DISABLED_NOT_EMPTY);
$bs2->set_value(321);
// The above change should change
$this->assertEqual($bs1->get_value(), 123);
$this->assertEqual($bs2->get_value(), 321);
$this->assertEqual($bs3->get_value(), 321);
$this->assertEqual($bs4->get_value(), 321);
// Check visibility is spreaded ok
$bs1->set_visibility(base_setting::HIDDEN);
$this->assertEqual($bs2->get_visibility(), $bs1->get_visibility());
$this->assertEqual($bs3->get_visibility(), $bs1->get_visibility());
// Check status is spreaded ok
$bs1->set_status(base_setting::LOCKED_BY_HIERARCHY);
$this->assertEqual($bs2->get_status(), $bs1->get_status());
$this->assertEqual($bs3->get_status(), $bs1->get_status());
// Create 3 settings and observe between them, put them in one array,
// force serialize/deserialize to check the observable pattern continues
// working after that
$bs1 = new mock_base_setting('test1', base_setting::IS_INTEGER, null);
$bs2 = new mock_base_setting('test2', base_setting::IS_INTEGER, null);
$bs3 = new mock_base_setting('test3', base_setting::IS_INTEGER, null);
$bs1->add_dependency($bs2, null, array('value'=>0));
$bs2->add_dependency($bs3, null, array('value'=>0));
// Serialize
$arr = array($bs1, $bs2, $bs3);
$ser = base64_encode(serialize($arr));
// Unserialize and copy to new objects
$newarr = unserialize(base64_decode($ser));
$ubs1 = $newarr[0];
$ubs2 = $newarr[1];
$ubs3 = $newarr[2];
// Must continue being base settings
$this->assertTrue($ubs1 instanceof base_setting);
$this->assertTrue($ubs2 instanceof base_setting);
$this->assertTrue($ubs3 instanceof base_setting);
// Set parent setting
$ubs1->set_value(1234);
$ubs1->set_visibility(base_setting::HIDDEN);
$ubs1->set_status(base_setting::LOCKED_BY_HIERARCHY);
// Check changes have been spreaded
$this->assertEqual($ubs2->get_visibility(), $ubs1->get_visibility());
$this->assertEqual($ubs3->get_visibility(), $ubs1->get_visibility());
$this->assertEqual($ubs2->get_status(), $ubs1->get_status());
$this->assertEqual($ubs3->get_status(), $ubs1->get_status());
}
/*
* test backup_setting class
*/
function test_backup_setting() {
// Instantiate backup_setting class and set level
$bs = new mock_backup_setting('test', base_setting::IS_INTEGER, null);
$bs->set_level(1);
$this->assertEqual($bs->get_level(), 1);
// Instantiate backup setting class and try to add one non backup_setting dependency
set_error_handler('backup_setting_error_handler', E_RECOVERABLE_ERROR);
$bs = new mock_backup_setting('test', base_setting::IS_INTEGER, null);
try {
$bs->add_dependency(new stdclass());
$this->assertTrue(false, 'backup_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_setting_exception);
$this->assertEqual($e->errorcode, 'incorrect_object_passed');
}
restore_error_handler();
// Try to assing upper level dependency
$bs1 = new mock_backup_setting('test1', base_setting::IS_INTEGER, null);
$bs1->set_level(1);
$bs2 = new mock_backup_setting('test2', base_setting::IS_INTEGER, null);
$bs2->set_level(2);
try {
$bs2->add_dependency($bs1);
$this->assertTrue(false, 'backup_setting_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_setting_exception);
$this->assertEqual($e->errorcode, 'cannot_add_upper_level_dependency');
}
// Check dependencies are working ok
$bs1 = new mock_backup_setting('test1', base_setting::IS_INTEGER, null);
$bs1->set_level(1);
$bs2 = new mock_backup_setting('test2', base_setting::IS_INTEGER, null);
$bs2->set_level(1); // Same level *must* work
$bs1->add_dependency($bs2, setting_dependency::DISABLED_NOT_EMPTY);
$bs1->set_value(123456);
$this->assertEqual($bs2->get_value(), $bs1->get_value());
}
/*
* test activity_backup_setting class
*/
function test_activity_backup_setting() {
$bs = new mock_activity_backup_setting('test', base_setting::IS_INTEGER, null);
$this->assertEqual($bs->get_level(), backup_setting::ACTIVITY_LEVEL);
// Check checksum implementation is working
$bs1 = new mock_activity_backup_setting('test', base_setting::IS_INTEGER, null);
$bs1->set_value(123);
$checksum = $bs1->calculate_checksum();
$this->assertTrue($checksum);
$this->assertTrue($bs1->is_checksum_correct($checksum));
}
/*
* test section_backup_setting class
*/
function test_section_backup_setting() {
$bs = new mock_section_backup_setting('test', base_setting::IS_INTEGER, null);
$this->assertEqual($bs->get_level(), backup_setting::SECTION_LEVEL);
// Check checksum implementation is working
$bs1 = new mock_section_backup_setting('test', base_setting::IS_INTEGER, null);
$bs1->set_value(123);
$checksum = $bs1->calculate_checksum();
$this->assertTrue($checksum);
$this->assertTrue($bs1->is_checksum_correct($checksum));
}
/*
* test course_backup_setting class
*/
function test_course_backup_setting() {
$bs = new mock_course_backup_setting('test', base_setting::IS_INTEGER, null);
$this->assertEqual($bs->get_level(), backup_setting::COURSE_LEVEL);
// Check checksum implementation is working
$bs1 = new mock_course_backup_setting('test', base_setting::IS_INTEGER, null);
$bs1->set_value(123);
$checksum = $bs1->calculate_checksum();
$this->assertTrue($checksum);
$this->assertTrue($bs1->is_checksum_correct($checksum));
}
}
/*
* helper extended base_setting class that makes some methods public for testing
*/
class mock_base_setting extends base_setting {
public function get_vtype() {
return $this->vtype;
}
public function process_change($setting, $ctype, $oldv) {
// Simply, inherit from the main object
$this->set_value($setting->get_value());
$this->set_visibility($setting->get_visibility());
$this->set_status($setting->get_status());
}
public function get_ui_info() {
// Return an array with all the ui info to be tested
return array($this->ui_type, $this->ui_label, $this->ui_values, $this->ui_options);
}
}
/*
* helper extended backup_setting class that makes some methods public for testing
*/
class mock_backup_setting extends backup_setting {
public function set_level($level) {
$this->level = $level;
}
public function process_change($setting, $ctype, $oldv) {
// Simply, inherit from the main object
$this->set_value($setting->get_value());
$this->set_visibility($setting->get_visibility());
$this->set_status($setting->get_status());
}
}
/*
* helper extended activity_backup_setting class that makes some methods public for testing
*/
class mock_activity_backup_setting extends activity_backup_setting {
public function process_change($setting, $ctype, $oldv) {
// Do nothing
}
}
/*
* helper extended section_backup_setting class that makes some methods public for testing
*/
class mock_section_backup_setting extends section_backup_setting {
public function process_change($setting, $ctype, $oldv) {
// Do nothing
}
}
/*
* helper extended course_backup_setting class that makes some methods public for testing
*/
class mock_course_backup_setting extends course_backup_setting {
public function process_change($setting, $ctype, $oldv) {
// Do nothing
}
}
/**
* This error handler is used to convert errors to excpetions so that simepltest can
* catch them.
*
* This is required in order to catch type hint mismatches that result in a error
* being thrown. It should only ever be used to catch E_RECOVERABLE_ERROR's.
*
* It throws a backup_setting_exception with 'incorrect_object_passed'
*
* @param int $errno E_RECOVERABLE_ERROR
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param array $errcontext
* @return null
*/
function backup_setting_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
if ($errno !== E_RECOVERABLE_ERROR) {
// Currently we only want to deal with type hinting errors
return false;
}
throw new backup_setting_exception('incorrect_object_passed');
}
@@ -1,123 +0,0 @@
<?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/>.
/**
* Mockup elements shared by various structure tests
*
* @package moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* helper extended base_attribute class that implements some methods for instantiating and testing
*/
class mock_base_attribute extends base_attribute {
// Nothing to do. Just allow instances to be created
}
/**
* helper extended final_element class that implements some methods for instantiating and testing
*/
class mock_base_final_element extends base_final_element {
/// Implementable API
protected function get_new_attribute($name) {
return new mock_base_attribute($name);
}
}
/**
* helper extended nested_element class that implements some methods for instantiating and testing
*/
class mock_base_nested_element extends base_nested_element {
/// Implementable API
protected function get_new_attribute($name) {
return new mock_base_attribute($name);
}
protected function get_new_final_element($name) {
return new mock_base_final_element($name);
}
}
/**
* helper extended optigroup class that implements some methods for instantiating and testing
*/
class mock_base_optigroup extends base_optigroup {
/// Implementable API
protected function get_new_attribute($name) {
return new mock_base_attribute($name);
}
protected function get_new_final_element($name) {
return new mock_base_final_element($name);
}
public function is_multiple() {
return parent::is_multiple();
}
}
/**
* helper class that extends backup_final_element in order to skip its value
*/
class mock_skip_final_element extends backup_final_element {
public function set_value($value) {
$this->clean_value();
}
}
/**
* helper class that extends backup_final_element in order to modify its value
*/
class mock_modify_final_element extends backup_final_element {
public function set_value($value) {
parent::set_value('original was ' . $value . ', now changed');
}
}
/**
* helper class that extends backup_final_element to delegate any calculation to another class
*/
class mock_final_element_interceptor extends backup_final_element {
public function set_value($value) {
// Get grandparent name
$gpname = $this->get_grandparent()->get_name();
// Get parent name
$pname = $this->get_parent()->get_name();
// Get my name
$myname = $this->get_name();
// Define class and function name
$classname = 'mock_' . $gpname . '_' . $pname . '_interceptor';
$methodname= 'intercept_' . $pname . '_' . $myname;
// Invoke the interception method
$result = call_user_func(array($classname, $methodname), $value);
// Finally set it
parent::set_value($result);
}
}
/**
* test interceptor class (its methods are called from interceptor)
*/
abstract class mock_forum_forum_interceptor {
static function intercept_forum_completionposts($element) {
return 'intercepted!';
}
}
@@ -1,673 +0,0 @@
<?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 base_final_element.class.php
*
* @package moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
require_once($CFG->dirroot . '/backup/util/xml/output/memory_xml_output.class.php');
/**
* Unit test case the all the backup structure classes. Note: Uses database
*/
class backup_structure_test extends UnitTestCaseUsingDatabase {
public static $includecoverage = array(
'backup/util/structure'
);
public static $excludecoverage = array(
'backup/util/structure/simpletest'
);
protected $testtables = array(
'lib' => array(
'files', 'rating'),
'mod/forum' => array(
'forum', 'forum_discussions', 'forum_posts',
'forum_read'));
protected $forumid; // To store the inserted forum->id
protected $contextid; // Official contextid for these tests
public function setUp() {
parent::setUp();
$this->switch_to_test_db(); // Switch to test DB for all the execution
foreach ($this->testtables as $dir => $tables) {
$this->create_test_tables($tables, $dir); // Create tables
}
$this->contextid = 666; // Let's assume this is the context for the forum
$this->fill_records(); // Add common stuff needed by various test methods
}
public function tearDown() {
parent::tearDown(); // In charge of droppng all the test tables
}
private function fill_records() {
global $DB;
// Create one forum
$forum_data = (object)array('course' => 1, 'name' => 'Test forum', 'intro' => 'Intro forum');
$this->forumid = $DB->insert_record('forum', $forum_data);
// With two related file
$f1_forum_data = (object)array(
'contenthash' => 'testf1', 'contextid' => $this->contextid,
'component'=>'mod_forum', 'filearea' => 'intro', 'filename' => 'tf1', 'itemid' => 0,
'filesize' => 123, 'timecreated' => 0, 'timemodified' => 0,
'pathnamehash' => 'testf1'
);
$DB->insert_record('files', $f1_forum_data);
$f2_forum_data = (object)array(
'contenthash' => 'tesft2', 'contextid' => $this->contextid,
'component'=>'mod_forum', 'filearea' => 'intro', 'filename' => 'tf2', 'itemid' => 0,
'filesize' => 123, 'timecreated' => 0, 'timemodified' => 0,
'pathnamehash' => 'testf2'
);
$DB->insert_record('files', $f2_forum_data);
// Create two discussions
$discussion1 = (object)array('course' => 1, 'forum' => $this->forumid, 'name' => 'd1', 'userid' => 100, 'groupid' => 200);
$d1id = $DB->insert_record('forum_discussions', $discussion1);
$discussion2 = (object)array('course' => 1, 'forum' => $this->forumid, 'name' => 'd2', 'userid' => 101, 'groupid' => 201);
$d2id = $DB->insert_record('forum_discussions', $discussion2);
// Create four posts
$post1 = (object)array('discussion' => $d1id, 'userid' => 100, 'subject' => 'p1', 'message' => 'm1');
$p1id = $DB->insert_record('forum_posts', $post1);
$post2 = (object)array('discussion' => $d1id, 'parent' => $p1id, 'userid' => 102, 'subject' => 'p2', 'message' => 'm2');
$p2id = $DB->insert_record('forum_posts', $post2);
$post3 = (object)array('discussion' => $d1id, 'parent' => $p2id, 'userid' => 103, 'subject' => 'p3', 'message' => 'm3');
$p3id = $DB->insert_record('forum_posts', $post3);
$post4 = (object)array('discussion' => $d2id, 'userid' => 101, 'subject' => 'p4', 'message' => 'm4');
$p4id = $DB->insert_record('forum_posts', $post4);
// With two related file
$f1_post1 = (object)array(
'contenthash' => 'testp1', 'contextid' => $this->contextid, 'component'=>'mod_forum',
'filearea' => 'post', 'filename' => 'tp1', 'itemid' => $p1id,
'filesize' => 123, 'timecreated' => 0, 'timemodified' => 0,
'pathnamehash' => 'testp1'
);
$DB->insert_record('files', $f1_post1);
$f1_post2 = (object)array(
'contenthash' => 'testp2', 'contextid' => $this->contextid, 'component'=>'mod_forum',
'filearea' => 'attachment', 'filename' => 'tp2', 'itemid' => $p2id,
'filesize' => 123, 'timecreated' => 0, 'timemodified' => 0,
'pathnamehash' => 'testp2'
);
$DB->insert_record('files', $f1_post2);
// Create two ratings
$rating1 = (object)array(
'contextid' => $this->contextid, 'userid' => 104, 'itemid' => $p1id, 'rating' => 2,
'scaleid' => -1, 'timecreated' => time(), 'timemodified' => time());
$r1id = $DB->insert_record('rating', $rating1);
$rating2 = (object)array(
'contextid' => $this->contextid, 'userid' => 105, 'itemid' => $p1id, 'rating' => 3,
'scaleid' => -1, 'timecreated' => time(), 'timemodified' => time());
$r2id = $DB->insert_record('rating', $rating2);
// Create 1 reads
$read1 = (object)array('userid' => 102, 'forumid' => $this->forumid, 'discussionid' => $d2id, 'postid' => $p4id);
$DB->insert_record('forum_read', $read1);
}
/**
* Backup structures tests (construction, definition and execution)
*/
function test_backup_structure_construct() {
global $DB;
$backupid = 'Testing Backup ID'; // Official backupid for these tests
// Create all the elements that will conform the tree
$forum = new backup_nested_element('forum',
array('id'),
array(
'type', 'name', 'intro', 'introformat',
'assessed', 'assesstimestart', 'assesstimefinish', 'scale',
'maxbytes', 'maxattachments', 'forcesubscribe', 'trackingtype',
'rsstype', 'rssarticles', 'timemodified', 'warnafter',
'blockafter',
new backup_final_element('blockperiod'),
new mock_skip_final_element('completiondiscussions'),
new mock_modify_final_element('completionreplies'),
new mock_final_element_interceptor('completionposts'))
);
$discussions = new backup_nested_element('discussions');
$discussion = new backup_nested_element('discussion',
array('id'),
array(
'forum', 'name', 'firstpost', 'userid',
'groupid', 'assessed', 'timemodified', 'usermodified',
'timestart', 'timeend')
);
$posts = new backup_nested_element('posts');
$post = new backup_nested_element('post',
array('id'),
array(
'discussion', 'parent', 'userid', 'created',
'modified', 'mailed', 'subject', 'message',
'messageformat', 'messagetrust', 'attachment', 'totalscore',
'mailnow')
);
$ratings = new backup_nested_element('ratings');
$rating = new backup_nested_element('rating',
array('id'),
array('userid', 'itemid', 'time', 'post_rating')
);
$reads = new backup_nested_element('readposts');
$read = new backup_nested_element('read',
array('id'),
array(
'userid', 'discussionid', 'postid',
'firstread', 'lastread')
);
$inventeds = new backup_nested_element('invented_elements',
array('reason', 'version')
);
$invented = new backup_nested_element('invented',
null,
array('one', 'two', 'three')
);
$one = $invented->get_final_element('one');
$one->add_attributes(array('attr1', 'attr2'));
// Build the tree
$forum->add_child($discussions);
$discussions->add_child($discussion);
$discussion->add_child($posts);
$posts->add_child($post);
$post->add_child($ratings);
$ratings->add_child($rating);
$forum->add_child($reads);
$reads->add_child($read);
$forum->add_child($inventeds);
$inventeds->add_child($invented);
// Let's add 1 optigroup with 4 elements
$alternative1 = new backup_optigroup_element('alternative1',
array('name', 'value'), '../../id', 1);
$alternative2 = new backup_optigroup_element('alternative2',
array('name', 'value'), backup::VAR_PARENTID, 2);
$alternative3 = new backup_optigroup_element('alternative3',
array('name', 'value'), '/forum/discussions/discussion/posts/post/id', 3);
$alternative4 = new backup_optigroup_element('alternative4',
array('forumtype', 'forumname')); // Alternative without conditions
// Create the optigroup, adding one element
$optigroup = new backup_optigroup('alternatives', $alternative1, false);
// Add second opti element
$optigroup->add_child($alternative2);
// Add optigroup to post element
$post->add_optigroup($optigroup);
// Add third opti element, on purpose after the add_optigroup() line above to check param evaluation works ok
$optigroup->add_child($alternative3);
// Add 4th opti element (the one without conditions, so will be present always)
$optigroup->add_child($alternative4);
/// Create some new nested elements, both named 'dupetest1', and add them to alternative1 and alternative2
/// (not problem as far as the optigroup in not unique)
$dupetest1 = new backup_nested_element('dupetest1', null, array('field1', 'field2'));
$dupetest2 = new backup_nested_element('dupetest2', null, array('field1', 'field2'));
$dupetest3 = new backup_nested_element('dupetest3', null, array('field1', 'field2'));
$dupetest4 = new backup_nested_element('dupetest1', null, array('field1', 'field2'));
$dupetest1->add_child($dupetest3);
$dupetest2->add_child($dupetest4);
$alternative1->add_child($dupetest1);
$alternative2->add_child($dupetest2);
// Define sources
$forum->set_source_table('forum', array('id' => backup::VAR_ACTIVITYID));
$discussion->set_source_sql('SELECT *
FROM {forum_discussions}
WHERE forum = ?',
array('/forum/id')
);
$post->set_source_table('forum_posts', array('discussion' => '/forum/discussions/discussion/id'));
$rating->set_source_sql('SELECT *
FROM {rating}
WHERE itemid = ?',
array(backup::VAR_PARENTID)
);
$read->set_source_table('forum_read', array('id' => '../../id'));
$inventeds->set_source_array(array((object)array('reason' => 'I love Moodle', 'version' => '1.0'),
(object)array('reason' => 'I love Moodle', 'version' => '2.0'))); // 2 object array
$invented->set_source_array(array((object)array('one' => 1, 'two' => 2, 'three' => 3),
(object)array('one' => 11, 'two' => 22, 'three' => 33))); // 2 object array
// Set optigroup_element sources
$alternative1->set_source_array(array((object)array('name' => 'alternative1', 'value' => 1))); // 1 object array
// Skip alternative2 source definition on purpose (will be tested)
// $alternative2->set_source_array(array((object)array('name' => 'alternative2', 'value' => 2))); // 1 object array
$alternative3->set_source_array(array((object)array('name' => 'alternative3', 'value' => 3))); // 1 object array
// Alternative 4 source is the forum type and name, so we'll get that in ALL posts (no conditions) that
// have not another alternative (post4 in our testing data in the only not matching any other alternative)
$alternative4->set_source_sql('SELECT type AS forumtype, name AS forumname
FROM {forum}
WHERE id = ?',
array('/forum/id')
);
// Set children of optigroup_element source
$dupetest1->set_source_array(array((object)array('field1' => '1', 'field2' => 1))); // 1 object array
$dupetest2->set_source_array(array((object)array('field1' => '2', 'field2' => 2))); // 1 object array
$dupetest3->set_source_array(array((object)array('field1' => '3', 'field2' => 3))); // 1 object array
$dupetest4->set_source_array(array((object)array('field1' => '4', 'field2' => 4))); // 1 object array
// Define some aliases
$rating->set_source_alias('rating', 'post_rating'); // Map the 'rating' value from DB to 'post_rating' final element
// Mark to detect files of type 'forum_intro' in forum (and not item id)
$forum->annotate_files('mod_forum', 'intro', null);
// Mark to detect file of type 'forum_post' and 'forum_attachment' in post (with itemid being post->id)
$post->annotate_files('mod_forum', 'post', 'id');
$post->annotate_files('mod_forum', 'attachment', 'id');
// Mark various elements to be annotated
$discussion->annotate_ids('user1', 'userid');
$post->annotate_ids('forum_post', 'id');
$rating->annotate_ids('user2', 'userid');
$rating->annotate_ids('forum_post', 'itemid');
// Create the backup_ids_temp table
backup_controller_dbops::create_backup_ids_temp_table($backupid);
// Instantiate in memory xml output
$xo = new memory_xml_output();
// Instantiate xml_writer and start it
$xw = new xml_writer($xo);
$xw->start();
// Instantiate the backup processor
$processor = new backup_structure_processor($xw);
// Set some variables
$processor->set_var(backup::VAR_ACTIVITYID, $this->forumid);
$processor->set_var(backup::VAR_BACKUPID, $backupid);
$processor->set_var(backup::VAR_CONTEXTID,$this->contextid);
// Process the backup structure with the backup processor
$forum->process($processor);
// Stop the xml_writer
$xw->stop();
// Check various counters
$this->assertEqual($forum->get_counter(), $DB->count_records('forum'));
$this->assertEqual($discussion->get_counter(), $DB->count_records('forum_discussions'));
$this->assertEqual($rating->get_counter(), $DB->count_records('rating'));
$this->assertEqual($read->get_counter(), $DB->count_records('forum_read'));
$this->assertEqual($inventeds->get_counter(), 2); // Array
// Perform some validations with the generated XML
$dom = new DomDocument();
$dom->loadXML($xo->get_allcontents());
$xpath = new DOMXPath($dom);
// Some more counters
$query = '/forum/discussions/discussion/posts/post';
$posts = $xpath->query($query);
$this->assertEqual($posts->length, $DB->count_records('forum_posts'));
$query = '/forum/invented_elements/invented';
$inventeds = $xpath->query($query);
$this->assertEqual($inventeds->length, 2*2);
// Check ratings information against DB
$ratings = $dom->getElementsByTagName('rating');
$this->assertEqual($ratings->length, $DB->count_records('rating'));
foreach ($ratings as $rating) {
$ratarr = array();
$ratarr['id'] = $rating->getAttribute('id');
foreach ($rating->childNodes as $node) {
if ($node->nodeType != XML_TEXT_NODE) {
$ratarr[$node->nodeName] = $node->nodeValue;
}
}
$this->assertEqual($ratarr['userid'], $DB->get_field('rating', 'userid', array('id' => $ratarr['id'])));
$this->assertEqual($ratarr['itemid'], $DB->get_field('rating', 'itemid', array('id' => $ratarr['id'])));
$this->assertEqual($ratarr['post_rating'], $DB->get_field('rating', 'rating', array('id' => $ratarr['id'])));
}
// Check forum has "blockeperiod" with value 0 (was declared by object instead of name)
$query = '/forum[blockperiod="0"]';
$result = $xpath->query($query);
$this->assertEqual($result->length, 1);
// Check forum is missing "completiondiscussions" (as we are using mock_skip_final_element)
$query = '/forum/completiondiscussions';
$result = $xpath->query($query);
$this->assertEqual($result->length, 0);
// Check forum has "completionreplies" with value "original was 0, now changed" (because of mock_modify_final_element)
$query = '/forum[completionreplies="original was 0, now changed"]';
$result = $xpath->query($query);
$this->assertEqual($result->length, 1);
// Check forum has "completionposts" with value "intercepted!" (because of mock_final_element_interceptor)
$query = '/forum[completionposts="intercepted!"]';
$result = $xpath->query($query);
$this->assertEqual($result->length, 1);
// Check there isn't any alternative2 tag, as far as it hasn't source defined
$query = '//alternative2';
$result = $xpath->query($query);
$this->assertEqual($result->length, 0);
// Check there are 4 "field1" elements
$query = '/forum/discussions/discussion/posts/post//field1';
$result = $xpath->query($query);
$this->assertEqual($result->length, 4);
// Check first post has one name element with value "alternative1"
$query = '/forum/discussions/discussion/posts/post[@id="1"][name="alternative1"]';
$result = $xpath->query($query);
$this->assertEqual($result->length, 1);
// Check there are two "dupetest1" elements
$query = '/forum/discussions/discussion/posts/post//dupetest1';
$result = $xpath->query($query);
$this->assertEqual($result->length, 2);
// Check second post has one name element with value "dupetest2"
$query = '/forum/discussions/discussion/posts/post[@id="2"]/dupetest2';
$result = $xpath->query($query);
$this->assertEqual($result->length, 1);
// Check element "dupetest2" of second post has one field1 element with value "2"
$query = '/forum/discussions/discussion/posts/post[@id="2"]/dupetest2[field1="2"]';
$result = $xpath->query($query);
$this->assertEqual($result->length, 1);
// Check forth post has no name element
$query = '/forum/discussions/discussion/posts/post[@id="4"]/name';
$result = $xpath->query($query);
$this->assertEqual($result->length, 0);
// Check 1st, 2nd and 3rd posts have no forumtype element
$query = '/forum/discussions/discussion/posts/post[@id="1"]/forumtype';
$result = $xpath->query($query);
$this->assertEqual($result->length, 0);
$query = '/forum/discussions/discussion/posts/post[@id="2"]/forumtype';
$result = $xpath->query($query);
$this->assertEqual($result->length, 0);
$query = '/forum/discussions/discussion/posts/post[@id="3"]/forumtype';
$result = $xpath->query($query);
$this->assertEqual($result->length, 0);
// Check 4th post has one forumtype element with value "general"
// (because it doesn't matches alternatives 1, 2, 3, then alternative 4,
// the one without conditions is being applied)
$query = '/forum/discussions/discussion/posts/post[@id="4"][forumtype="general"]';
$result = $xpath->query($query);
$this->assertEqual($result->length, 1);
// Check annotations information against DB
// Count records in original tables
$c_postsid = $DB->count_records_sql('SELECT COUNT(DISTINCT id) FROM {forum_posts}');
$c_dissuserid = $DB->count_records_sql('SELECT COUNT(DISTINCT userid) FROM {forum_discussions}');
$c_ratuserid = $DB->count_records_sql('SELECT COUNT(DISTINCT userid) FROM {rating}');
// Count records in backup_ids_table
$f_forumpost = $DB->count_records('backup_ids_temp', array('backupid' => $backupid, 'itemname' => 'forum_post'));
$f_user1 = $DB->count_records('backup_ids_temp', array('backupid' => $backupid, 'itemname' => 'user1'));
$f_user2 = $DB->count_records('backup_ids_temp', array('backupid' => $backupid, 'itemname' => 'user2'));
$c_notbackupid = $DB->count_records_select('backup_ids_temp', 'backupid != ?', array($backupid));
// Peform tests by comparing counts
$this->assertEqual($c_notbackupid, 0); // there isn't any record with incorrect backupid
$this->assertEqual($c_postsid, $f_forumpost); // All posts have been registered
$this->assertEqual($c_dissuserid, $f_user1); // All users coming from discussions have been registered
$this->assertEqual($c_ratuserid, $f_user2); // All users coming from ratings have been registered
// Check file annotations against DB
$fannotations = $DB->get_records('backup_ids_temp', array('backupid' => $backupid, 'itemname' => 'file'));
$ffiles = $DB->get_records('files', array('contextid' => $this->contextid));
$this->assertEqual(count($fannotations), count($ffiles)); // Same number of recs in both (all files have been annotated)
foreach ($fannotations as $annotation) { // Check ids annotated
$this->assertTrue($DB->record_exists('files', array('id' => $annotation->itemid)));
}
// Drop the backup_ids_temp table
backup_controller_dbops::drop_backup_ids_temp_table('testingid');
}
/**
* Backup structures wrong tests (trying to do things the wrong way)
*/
function test_backup_structure_wrong() {
// Instantiate the backup processor
$processor = new backup_structure_processor(new xml_writer(new memory_xml_output()));
$this->assertTrue($processor instanceof base_processor);
// Set one var twice
$processor->set_var('onenewvariable', 999);
try {
$processor->set_var('onenewvariable', 999);
$this->assertTrue(false, 'backup_processor_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_processor_exception);
$this->assertEqual($e->errorcode, 'processorvariablealreadyset');
$this->assertEqual($e->a, 'onenewvariable');
}
// Get non-existing var
try {
$var = $processor->get_var('nonexistingvar');
$this->assertTrue(false, 'backup_processor_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof backup_processor_exception);
$this->assertEqual($e->errorcode, 'processorvariablenotfound');
$this->assertEqual($e->a, 'nonexistingvar');
}
// Create nested element and try ro get its parent id (doesn't exisit => exception)
$ne = new backup_nested_element('test', 'one', 'two', 'three');
try {
$ne->set_source_table('forum', array('id' => backup::VAR_PARENTID));
$ne->process($processor);
$this->assertTrue(false, 'base_element_struct_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'cannotfindparentidforelement');
}
// Try to process one nested/final/attribute elements without processor
$ne = new backup_nested_element('test', 'one', 'two', 'three');
try {
$ne->process(new stdclass());
$this->assertTrue(false, 'base_element_struct_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'incorrect_processor');
}
$fe = new backup_final_element('test');
try {
$fe->process(new stdclass());
$this->assertTrue(false, 'base_element_struct_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'incorrect_processor');
}
$at = new backup_attribute('test');
try {
$at->process(new stdclass());
$this->assertTrue(false, 'base_element_struct_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'incorrect_processor');
}
// Try to put an incorrect alias
$ne = new backup_nested_element('test', 'one', 'two', 'three');
try {
$ne->set_source_alias('last', 'nonexisting');
$this->assertTrue(false, 'base_element_struct_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'incorrectaliasfinalnamenotfound');
$this->assertEqual($e->a, 'nonexisting');
}
// Try various incorrect paths specifying source
$ne = new backup_nested_element('test', 'one', 'two', 'three');
try {
$ne->set_source_table('forum', array('/test/subtest'));
$this->assertTrue(false, 'base_element_struct_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'baseelementincorrectfinalorattribute');
$this->assertEqual($e->a, 'subtest');
}
try {
$ne->set_source_table('forum', array('/wrongtest'));
$this->assertTrue(false, 'base_element_struct_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'baseelementincorrectgrandparent');
$this->assertEqual($e->a, 'wrongtest');
}
try {
$ne->set_source_table('forum', array('../nonexisting'));
$this->assertTrue(false, 'base_element_struct_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'baseelementincorrectparent');
$this->assertEqual($e->a, '..');
}
// Try various incorrect file annotations
$ne = new backup_nested_element('test', 'one', 'two', 'three');
$ne->annotate_files('test', 'filearea', null);
try {
$ne->annotate_files('test', 'filearea', null); // Try to add annotations twice
$this->assertTrue(false, 'base_element_struct_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'annotate_files_duplicate_annotation');
$this->assertEqual($e->a, 'test/filearea/');
}
$ne = new backup_nested_element('test', 'one', 'two', 'three');
try {
$ne->annotate_files('test', 'filearea', 'four'); // Incorrect element
$this->assertTrue(false, 'base_element_struct_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'baseelementincorrectfinalorattribute');
$this->assertEqual($e->a, 'four');
}
// Try to add incorrect element to backup_optigroup
$bog = new backup_optigroup('test');
try {
$bog->add_child(new backup_nested_element('test2'));
$this->assertTrue(false, 'base_optigroup_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_optigroup_exception);
$this->assertEqual($e->errorcode, 'optigroup_element_incorrect');
$this->assertEqual($e->a, 'backup_nested_element');
}
$bog = new backup_optigroup('test');
try {
$bog->add_child('test2');
$this->assertTrue(false, 'base_optigroup_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_optigroup_exception);
$this->assertEqual($e->errorcode, 'optigroup_element_incorrect');
$this->assertEqual($e->a, 'non object');
}
try {
$bog = new backup_optigroup('test', new stdclass());
$this->assertTrue(false, 'base_optigroup_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_optigroup_exception);
$this->assertEqual($e->errorcode, 'optigroup_elements_incorrect');
}
// Try a wrong processor with backup_optigroup
$bog = new backup_optigroup('test');
try {
$bog->process(new stdclass());
$this->assertTrue(false, 'base_element_struct_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'incorrect_processor');
}
// Try duplicating used elements with backup_optigroup
// Adding top->down
$bog = new backup_optigroup('test', null, true);
$boge1 = new backup_optigroup_element('boge1');
$boge2 = new backup_optigroup_element('boge2');
$ne1 = new backup_nested_element('ne1');
$ne2 = new backup_nested_element('ne1');
$bog->add_child($boge1);
$bog->add_child($boge2);
$boge1->add_child($ne1);
try {
$boge2->add_child($ne2);
$this->assertTrue(false, 'base_optigroup_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_optigroup_exception);
$this->assertEqual($e->errorcode, 'multiple_optigroup_duplicate_element');
$this->assertEqual($e->a, 'ne1');
}
// Adding down->top
$bog = new backup_optigroup('test', null, true);
$boge1 = new backup_optigroup_element('boge1');
$boge2 = new backup_optigroup_element('boge2');
$ne1 = new backup_nested_element('ne1');
$ne2 = new backup_nested_element('ne1');
$boge1->add_child($ne1);
$boge2->add_child($ne2);
$bog->add_child($boge1);
try {
$bog->add_child($boge2);
$this->assertTrue(false, 'base_element_struct_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'baseelementexisting');
$this->assertEqual($e->a, 'ne1');
}
}
}
@@ -1,136 +0,0 @@
<?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 base_atom.class.php
*
* @package moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
require_once($CFG->dirroot . '/backup/util/structure/base_atom.class.php');
/**
* Unit test case the base_atom class. Note: as it's abstract we are testing
* mock_base_atom instantiable class instead
*/
class base_atom_test extends UnitTestCase {
public static $includecoverage = array('/backup/util/structure/base_atom.class.php');
/**
* Correct base_atom_tests
*/
function test_base_atom() {
$name_with_all_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_';
$value_to_test = 'Some <value> to test';
// Create instance with correct names
$instance = new mock_base_atom($name_with_all_chars);
$this->assertIsA($instance, 'base_atom');
$this->assertEqual($instance->get_name(), $name_with_all_chars);
$this->assertFalse($instance->is_set());
$this->assertNull($instance->get_value());
// Set value
$instance->set_value($value_to_test);
$this->assertEqual($instance->get_value(), $value_to_test);
$this->assertTrue($instance->is_set());
// Clean value
$instance->clean_value();
$this->assertFalse($instance->is_set());
$this->assertNull($instance->get_value());
// Get to_string() results (with values)
$instance = new mock_base_atom($name_with_all_chars);
$instance->set_value($value_to_test);
$tostring = $instance->to_string(true);
$this->assertTrue(strpos($tostring, $name_with_all_chars) !== false);
$this->assertTrue(strpos($tostring, ' => ') !== false);
$this->assertTrue(strpos($tostring, $value_to_test) !== false);
// Get to_string() results (without values)
$tostring = $instance->to_string(false);
$this->assertTrue(strpos($tostring, $name_with_all_chars) !== false);
$this->assertFalse(strpos($tostring, ' => '));
$this->assertFalse(strpos($tostring, $value_to_test));
}
/**
* Throwing exception base_atom tests
*/
function test_base_atom_exceptions() {
// empty names
try {
$instance = new mock_base_atom('');
$this->fail("Expecting base_atom_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_struct_exception);
}
// whitespace names
try {
$instance = new mock_base_atom('TESTING ATOM');
$this->fail("Expecting base_atom_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_struct_exception);
}
// ascii names
try {
$instance = new mock_base_atom('TESTING-ATOM');
$this->fail("Expecting base_atom_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_struct_exception);
}
try {
$instance = new mock_base_atom('TESTING_ATOM_Á');
$this->fail("Expecting base_atom_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_struct_exception);
}
// setting already set value
$instance = new mock_base_atom('TEST');
$instance->set_value('test');
try {
$instance->set_value('test');
$this->fail("Expecting base_atom_content_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_content_exception);
}
}
}
/**
* Instantiable class extending base_atom in order to be able to perform tests
*/
class mock_base_atom extends base_atom {
// Nothing new in this class, just an instantiable base_atom class
// with the is_set() method public for testing purposes
public function is_set() {
return parent::is_set();
}
}
@@ -1,71 +0,0 @@
<?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 base_attribute.class.php
*
* @package moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
require_once($CFG->dirroot . '/backup/util/structure/base_atom.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_attribute.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_final_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_nested_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/simpletest/fixtures/structuremocks.php');
/**
* Unit test case the base_attribute class. Note: No really much to test here as attribute is 100%
* atom extension without new functionality (name/value)
*/
class base_attribute_test extends UnitTestCase {
public static $includecoverage = array('backup/util/structure/base_attribute.class.php');
/**
* Correct base_attribute tests
*/
function test_base_attribute() {
$name_with_all_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_';
$value_to_test = 'Some <value> to test';
// Create instance with correct names
$instance = new mock_base_attribute($name_with_all_chars);
$this->assertIsA($instance, 'base_attribute');
$this->assertEqual($instance->get_name(), $name_with_all_chars);
$this->assertNull($instance->get_value());
// Set value
$instance->set_value($value_to_test);
$this->assertEqual($instance->get_value(), $value_to_test);
// Get to_string() results (with values)
$instance = new mock_base_attribute($name_with_all_chars);
$instance->set_value($value_to_test);
$tostring = $instance->to_string(true);
$this->assertTrue(strpos($tostring, '@' . $name_with_all_chars) !== false);
$this->assertTrue(strpos($tostring, ' => ') !== false);
$this->assertTrue(strpos($tostring, $value_to_test) !== false);
}
}
@@ -1,176 +0,0 @@
<?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 base_final_element.class.php
*
* @package moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
require_once($CFG->dirroot . '/backup/util/structure/base_atom.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_attribute.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_final_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_nested_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/simpletest/fixtures/structuremocks.php');
/**
* Unit test case the base_final_element class. Note: highly imbricated with base_nested_element class
*/
class base_final_element_test extends UnitTestCase {
public static $includecoverage = array(
'backup/util/structure/base_final_element.class.php',
'backup/util/structure/base_nested_element.class.php'
);
/**
* Correct base_final_element tests
*/
function test_base_final_element() {
// Create instance with name
$instance = new mock_base_final_element('TEST');
$this->assertIsA($instance, 'base_final_element');
$this->assertEqual($instance->get_name(), 'TEST');
$this->assertNull($instance->get_value());
$this->assertEqual($instance->get_attributes(), array());
$this->assertNull($instance->get_parent());
$this->assertEqual($instance->get_level(), 1);
// Set value
$instance->set_value('value');
$this->assertEqual($instance->get_value(), 'value');
// Create instance with name and one object attribute
$instance = new mock_base_final_element('TEST', new mock_base_attribute('ATTR1'));
$attrs = $instance->get_attributes();
$this->assertTrue(is_array($attrs));
$this->assertEqual(count($attrs), 1);
$this->assertTrue($attrs['ATTR1'] instanceof base_attribute);
$this->assertEqual($attrs['ATTR1']->get_name(), 'ATTR1');
$this->assertNull($attrs['ATTR1']->get_value());
// Create instance with name and various object attributes
$attr1 = new mock_base_attribute('ATTR1');
$attr1->set_value('attr1_value');
$attr2 = new mock_base_attribute('ATTR2');
$instance = new mock_base_final_element('TEST', array($attr1, $attr2));
$attrs = $instance->get_attributes();
$this->assertTrue(is_array($attrs));
$this->assertEqual(count($attrs), 2);
$this->assertTrue($attrs['ATTR1'] instanceof base_attribute);
$this->assertEqual($attrs['ATTR1']->get_name(), 'ATTR1');
$this->assertEqual($attrs['ATTR1']->get_value(), 'attr1_value');
$this->assertTrue($attrs['ATTR2'] instanceof base_attribute);
$this->assertEqual($attrs['ATTR2']->get_name(), 'ATTR2');
$this->assertNull($attrs['ATTR2']->get_value());
// Create instance with name and one string attribute
$instance = new mock_base_final_element('TEST', 'ATTR1');
$attrs = $instance->get_attributes();
$this->assertTrue(is_array($attrs));
$this->assertEqual(count($attrs), 1);
$this->assertTrue($attrs['ATTR1'] instanceof base_attribute);
$this->assertEqual($attrs['ATTR1']->get_name(), 'ATTR1');
$this->assertNull($attrs['ATTR1']->get_value());
// Create instance with name and various object attributes
$instance = new mock_base_final_element('TEST', array('ATTR1', 'ATTR2'));
$attrs = $instance->get_attributes();
$attrs['ATTR1']->set_value('attr1_value');
$this->assertTrue(is_array($attrs));
$this->assertEqual(count($attrs), 2);
$this->assertTrue($attrs['ATTR1'] instanceof base_attribute);
$this->assertEqual($attrs['ATTR1']->get_name(), 'ATTR1');
$this->assertEqual($attrs['ATTR1']->get_value(), 'attr1_value');
$this->assertTrue($attrs['ATTR2'] instanceof base_attribute);
$this->assertEqual($attrs['ATTR2']->get_name(), 'ATTR2');
$this->assertNull($attrs['ATTR2']->get_value());
// Clean values
$instance = new mock_base_final_element('TEST', array('ATTR1', 'ATTR2'));
$instance->set_value('instance_value');
$attrs = $instance->get_attributes();
$attrs['ATTR1']->set_value('attr1_value');
$this->assertEqual($instance->get_value(), 'instance_value');
$this->assertEqual($attrs['ATTR1']->get_value(), 'attr1_value');
$instance->clean_values();
$this->assertNull($instance->get_value());
$this->assertNull($attrs['ATTR1']->get_value());
// Get to_string() results (with values)
$instance = new mock_base_final_element('TEST', array('ATTR1', 'ATTR2'));
$instance->set_value('final element value');
$attrs = $instance->get_attributes();
$attrs['ATTR1']->set_value('attr1 value');
$tostring = $instance->to_string(true);
$this->assertTrue(strpos($tostring, '#TEST (level: 1)') !== false);
$this->assertTrue(strpos($tostring, ' => ') !== false);
$this->assertTrue(strpos($tostring, 'final element value') !== false);
$this->assertTrue(strpos($tostring, 'attr1 value') !== false);
}
/**
* Exception base_final_element tests
*/
function test_base_final_element_exceptions() {
// Create instance with invalid name
try {
$instance = new mock_base_final_element('');
$this->fail("Expecting base_atom_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_struct_exception);
}
// Create instance with incorrect (object) attribute
try {
$obj = new stdClass;
$obj->name = 'test_attr';
$instance = new mock_base_final_element('TEST', $obj);
$this->fail("Expecting base_element_attribute_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_attribute_exception);
}
// Create instance with array containing incorrect (object) attribute
try {
$obj = new stdClass;
$obj->name = 'test_attr';
$instance = new mock_base_final_element('TEST', array($obj));
$this->fail("Expecting base_element_attribute_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_attribute_exception);
}
// Create instance with array containing duplicate attributes
try {
$instance = new mock_base_final_element('TEST', array('ATTR1', 'ATTR2', 'ATTR1'));
$this->fail("Expecting base_element_attribute_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_attribute_exception);
}
}
}
@@ -1,408 +0,0 @@
<?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 backup/backup_nested_element.class.php
*
* @package moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
require_once($CFG->dirroot . '/backup/util/structure/base_atom.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_attribute.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_final_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_nested_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/simpletest/fixtures/structuremocks.php');
/**
* Unit test case the base_nested_element class. Note: highly imbricated with base_final_element class
*/
class base_nested_element_test extends UnitTestCase {
public static $includecoverage = array(
'backup/util/structure/base_nested_element.class.php',
'backup/util/structure/base_final_element.class.php'
);
/**
* Correct creation tests (attributes and final elements)
*/
function test_creation() {
// Create instance with name, attributes and values and check all them
$instance = new mock_base_nested_element('NAME', array('ATTR1', 'ATTR2'), array('VAL1', 'VAL2', 'VAL3'));
$this->assertIsA($instance, 'base_nested_element');
$this->assertEqual($instance->get_name(), 'NAME');
$attrs = $instance->get_attributes();
$this->assertTrue(is_array($attrs));
$this->assertEqual(count($attrs), 2);
$this->assertIsA($attrs['ATTR1'], 'base_attribute');
$this->assertEqual($attrs['ATTR1']->get_name(), 'ATTR1');
$this->assertNull($attrs['ATTR1']->get_value());
$this->assertEqual($attrs['ATTR2']->get_name(), 'ATTR2');
$this->assertNull($attrs['ATTR2']->get_value());
$finals = $instance->get_final_elements();
$this->assertTrue(is_array($finals));
$this->assertEqual(count($finals), 3);
$this->assertIsA($finals['VAL1'], 'base_final_element');
$this->assertEqual($finals['VAL1']->get_name(), 'VAL1');
$this->assertNull($finals['VAL1']->get_value());
$this->assertEqual($finals['VAL1']->get_level(), 2);
$this->assertIsA($finals['VAL1']->get_parent(), 'base_nested_element');
$this->assertEqual($finals['VAL2']->get_name(), 'VAL2');
$this->assertNull($finals['VAL2']->get_value());
$this->assertEqual($finals['VAL2']->get_level(), 2);
$this->assertIsA($finals['VAL1']->get_parent(), 'base_nested_element');
$this->assertEqual($finals['VAL3']->get_name(), 'VAL3');
$this->assertNull($finals['VAL3']->get_value());
$this->assertEqual($finals['VAL3']->get_level(), 2);
$this->assertIsA($finals['VAL1']->get_parent(), 'base_nested_element');
$this->assertNull($instance->get_parent());
$this->assertEqual($instance->get_children(), array());
$this->assertEqual($instance->get_level(), 1);
// Create instance with name only
$instance = new mock_base_nested_element('NAME');
$this->assertIsA($instance, 'base_nested_element');
$this->assertEqual($instance->get_name(), 'NAME');
$this->assertEqual($instance->get_attributes(), array());
$this->assertEqual($instance->get_final_elements(), array());
$this->assertNull($instance->get_parent());
$this->assertEqual($instance->get_children(), array());
$this->assertEqual($instance->get_level(), 1);
// Add some attributes
$instance->add_attributes(array('ATTR1', 'ATTR2'));
$attrs = $instance->get_attributes();
$this->assertTrue(is_array($attrs));
$this->assertEqual(count($attrs), 2);
$this->assertEqual($attrs['ATTR1']->get_name(), 'ATTR1');
$this->assertNull($attrs['ATTR1']->get_value());
$this->assertEqual($attrs['ATTR2']->get_name(), 'ATTR2');
$this->assertNull($attrs['ATTR2']->get_value());
// And some more atributes
$instance->add_attributes(array('ATTR3', 'ATTR4'));
$attrs = $instance->get_attributes();
$this->assertTrue(is_array($attrs));
$this->assertEqual(count($attrs), 4);
$this->assertEqual($attrs['ATTR1']->get_name(), 'ATTR1');
$this->assertNull($attrs['ATTR1']->get_value());
$this->assertEqual($attrs['ATTR2']->get_name(), 'ATTR2');
$this->assertNull($attrs['ATTR2']->get_value());
$this->assertEqual($attrs['ATTR3']->get_name(), 'ATTR3');
$this->assertNull($attrs['ATTR3']->get_value());
$this->assertEqual($attrs['ATTR4']->get_name(), 'ATTR4');
$this->assertNull($attrs['ATTR4']->get_value());
// Add some final elements
$instance->add_final_elements(array('VAL1', 'VAL2', 'VAL3'));
$finals = $instance->get_final_elements();
$this->assertTrue(is_array($finals));
$this->assertEqual(count($finals), 3);
$this->assertEqual($finals['VAL1']->get_name(), 'VAL1');
$this->assertNull($finals['VAL1']->get_value());
$this->assertEqual($finals['VAL2']->get_name(), 'VAL2');
$this->assertNull($finals['VAL2']->get_value());
$this->assertEqual($finals['VAL3']->get_name(), 'VAL3');
$this->assertNull($finals['VAL3']->get_value());
// Add some more final elements
$instance->add_final_elements('VAL4');
$finals = $instance->get_final_elements();
$this->assertTrue(is_array($finals));
$this->assertEqual(count($finals), 4);
$this->assertEqual($finals['VAL1']->get_name(), 'VAL1');
$this->assertNull($finals['VAL1']->get_value());
$this->assertEqual($finals['VAL2']->get_name(), 'VAL2');
$this->assertNull($finals['VAL2']->get_value());
$this->assertEqual($finals['VAL3']->get_name(), 'VAL3');
$this->assertNull($finals['VAL3']->get_value());
$this->assertEqual($finals['VAL4']->get_name(), 'VAL4');
$this->assertNull($finals['VAL4']->get_value());
// Get to_string() results (with values)
$instance = new mock_base_nested_element('PARENT', array('ATTR1', 'ATTR2'), array('FINAL1', 'FINAL2', 'FINAL3'));
$child1 = new mock_base_nested_element('CHILD1', null, new mock_base_final_element('FINAL4'));
$child2 = new mock_base_nested_element('CHILD2', null, new mock_base_final_element('FINAL5'));
$instance->add_child($child1);
$instance->add_child($child2);
$children = $instance->get_children();
$final_elements = $children['CHILD1']->get_final_elements();
$final_elements['FINAL4']->set_value('final4value');
$final_elements['FINAL4']->add_attributes('ATTR4');
$grandchild = new mock_base_nested_element('GRANDCHILD', new mock_base_attribute('ATTR5'));
$child2->add_child($grandchild);
$attrs = $grandchild->get_attributes();
$attrs['ATTR5']->set_value('attr5value');
$tostring = $instance->to_string(true);
$this->assertTrue(strpos($tostring, 'PARENT (level: 1)') !== false);
$this->assertTrue(strpos($tostring, ' => ') !== false);
$this->assertTrue(strpos($tostring, '#FINAL4 (level: 3) => final4value') !== false);
$this->assertTrue(strpos($tostring, '@ATTR5 => attr5value') !== false);
$this->assertTrue(strpos($tostring, '#FINAL5 (level: 3) => not set') !== false);
// Clean values
$instance = new mock_base_nested_element('PARENT', array('ATTR1', 'ATTR2'), array('FINAL1', 'FINAL2', 'FINAL3'));
$child1 = new mock_base_nested_element('CHILD1', null, new mock_base_final_element('FINAL4'));
$child2 = new mock_base_nested_element('CHILD2', null, new mock_base_final_element('FINAL4'));
$instance->add_child($child1);
$instance->add_child($child2);
$children = $instance->get_children();
$final_elements = $children['CHILD1']->get_final_elements();
$final_elements['FINAL4']->set_value('final4value');
$final_elements['FINAL4']->add_attributes('ATTR4');
$grandchild = new mock_base_nested_element('GRANDCHILD', new mock_base_attribute('ATTR4'));
$child2->add_child($grandchild);
$attrs = $grandchild->get_attributes();
$attrs['ATTR4']->set_value('attr4value');
$this->assertEqual($final_elements['FINAL4']->get_value(), 'final4value');
$this->assertEqual($attrs['ATTR4']->get_value(), 'attr4value');
$instance->clean_values();
$this->assertNull($final_elements['FINAL4']->get_value());
$this->assertNull($attrs['ATTR4']->get_value());
}
/**
* Incorrect creation tests (attributes and final elements)
*/
function test_wrong_creation() {
// Create instance with invalid name
try {
$instance = new mock_base_nested_element('');
$this->fail("Expecting base_atom_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_struct_exception);
}
// Create instance with incorrect (object) final element
try {
$obj = new stdClass;
$obj->name = 'test_attr';
$instance = new mock_base_nested_element('TEST', null, $obj);
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Create instance with array containing incorrect (object) final element
try {
$obj = new stdClass;
$obj->name = 'test_attr';
$instance = new mock_base_nested_element('TEST', null, array($obj));
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Create instance with array containing duplicate final elements
try {
$instance = new mock_base_nested_element('TEST', null, array('VAL1', 'VAL2', 'VAL1'));
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Try to get value of base_nested_element
$instance = new mock_base_nested_element('TEST');
try {
$instance->get_value();
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Try to set value of base_nested_element
$instance = new mock_base_nested_element('TEST');
try {
$instance->set_value('some_value');
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Try to clean one value of base_nested_element
$instance = new mock_base_nested_element('TEST');
try {
$instance->clean_value('some_value');
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
}
/**
* Correct tree tests (children stuff)
*/
function test_tree() {
// Create parent and child instances, tree-ing them
$parent = new mock_base_nested_element('PARENT');
$child = new mock_base_nested_element('CHILD');
$parent->add_child($child);
$this->assertEqual($parent->get_children(), array('CHILD' => $child));
$this->assertEqual($child->get_parent(), $parent);
$check_children = $parent->get_children();
$check_child = $check_children['CHILD'];
$check_parent = $check_child->get_parent();
$this->assertEqual($check_child->get_name(), 'CHILD');
$this->assertEqual($check_parent->get_name(), 'PARENT');
$this->assertEqual($check_child->get_level(), 2);
$this->assertEqual($check_parent->get_level(), 1);
$this->assertEqual($check_parent->get_children(), array('CHILD' => $child));
$this->assertEqual($check_child->get_parent(), $parent);
// Add parent to grandparent
$grandparent = new mock_base_nested_element('GRANDPARENT');
$grandparent->add_child($parent);
$this->assertEqual($grandparent->get_children(), array('PARENT' => $parent));
$this->assertEqual($parent->get_parent(), $grandparent);
$this->assertEqual($parent->get_children(), array('CHILD' => $child));
$this->assertEqual($child->get_parent(), $parent);
$this->assertEqual($child->get_level(), 3);
$this->assertEqual($parent->get_level(), 2);
$this->assertEqual($grandparent->get_level(), 1);
// Add grandchild to child
$grandchild = new mock_base_nested_element('GRANDCHILD');
$child->add_child($grandchild);
$this->assertEqual($child->get_children(), array('GRANDCHILD' => $grandchild));
$this->assertEqual($grandchild->get_parent(), $child);
$this->assertEqual($grandchild->get_level(), 4);
$this->assertEqual($child->get_level(), 3);
$this->assertEqual($parent->get_level(), 2);
$this->assertEqual($grandparent->get_level(), 1);
// Add another child to parent
$child2 = new mock_base_nested_element('CHILD2');
$parent->add_child($child2);
$this->assertEqual($parent->get_children(), array('CHILD' => $child, 'CHILD2' => $child2));
$this->assertEqual($child2->get_parent(), $parent);
$this->assertEqual($grandchild->get_level(), 4);
$this->assertEqual($child->get_level(), 3);
$this->assertEqual($child2->get_level(), 3);
$this->assertEqual($parent->get_level(), 2);
$this->assertEqual($grandparent->get_level(), 1);
}
/**
* Incorrect tree tests (children stuff)
*/
function test_wrong_tree() {
// Add null object child
$parent = new mock_base_nested_element('PARENT');
$child = null;
try {
$parent->add_child($child);
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Add non base_element object child
$parent = new mock_base_nested_element('PARENT');
$child = new stdClass();
try {
$parent->add_child($child);
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Add existing element (being parent)
$parent = new mock_base_nested_element('PARENT');
$child = new mock_base_nested_element('PARENT');
try {
$parent->add_child($child);
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Add existing element (being grandparent)
$grandparent = new mock_base_nested_element('GRANDPARENT');
$parent = new mock_base_nested_element('PARENT');
$child = new mock_base_nested_element('GRANDPARENT');
$grandparent->add_child($parent);
try {
$parent->add_child($child);
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Add existing element (being grandchild)
$grandparent = new mock_base_nested_element('GRANDPARENT');
$parent = new mock_base_nested_element('PARENT');
$child = new mock_base_nested_element('GRANDPARENT');
$parent->add_child($child);
try {
$grandparent->add_child($parent);
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Add existing element (being cousin)
$grandparent = new mock_base_nested_element('GRANDPARENT');
$parent1 = new mock_base_nested_element('PARENT1');
$parent2 = new mock_base_nested_element('PARENT2');
$child1 = new mock_base_nested_element('CHILD1');
$child2 = new mock_base_nested_element('CHILD1');
$grandparent->add_child($parent1);
$parent1->add_child($child1);
$parent2->add_child($child2);
try {
$grandparent->add_child($parent2);
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Add element to two parents
$parent1 = new mock_base_nested_element('PARENT1');
$parent2 = new mock_base_nested_element('PARENT2');
$child = new mock_base_nested_element('CHILD');
$parent1->add_child($child);
try {
$parent2->add_child($child);
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_parent_exception);
}
// Add child element already used by own final elements
$nested = new mock_base_nested_element('PARENT1', null, array('FINAL1', 'FINAL2'));
$child = new mock_base_nested_element('FINAL2', null, array('FINAL3', 'FINAL4'));
try {
$nested->add_child($child);
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
$this->assertEqual($e->errorcode, 'baseelementchildnameconflict');
$this->assertEqual($e->a, 'FINAL2');
}
}
}
@@ -1,150 +0,0 @@
<?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 backup/backup_nested_element.class.php
*
* @package moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
require_once($CFG->dirroot . '/backup/util/structure/base_atom.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_attribute.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_final_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_nested_element.class.php');
require_once($CFG->dirroot . '/backup/util/structure/base_optigroup.class.php');
require_once($CFG->dirroot . '/backup/util/structure/simpletest/fixtures/structuremocks.php');
/**
* Unit test case the base_optigroup class. Note: highly imbricated with nested/final base elements
*/
class base_optigroup_test extends UnitTestCase {
public static $includecoverage = array(
'backup/util/structure/base_optigroup.class.php',
);
/**
* Correct creation tests (s)
*/
function test_creation() {
$instance = new mock_base_optigroup('optigroup', null, true);
$this->assertIsA($instance, 'base_optigroup');
$this->assertEqual($instance->get_name(), 'optigroup');
$this->assertNull($instance->get_parent());
$this->assertEqual($instance->get_children(), array());
$this->assertEqual($instance->get_level(), 1);
$this->assertTrue($instance->is_multiple());
// Get to_string() results (with values)
$child1 = new mock_base_nested_element('child1', null, new mock_base_final_element('four'));
$child2 = new mock_base_nested_element('child2', null, new mock_base_final_element('five'));
$instance->add_child($child1);
$instance->add_child($child2);
$children = $instance->get_children();
$final_elements = $children['child1']->get_final_elements();
$final_elements['four']->set_value('final4value');
$final_elements['four']->add_attributes('attr4');
$grandchild = new mock_base_nested_element('grandchild', new mock_base_attribute('attr5'));
$child2->add_child($grandchild);
$attrs = $grandchild->get_attributes();
$attrs['attr5']->set_value('attr5value');
$tostring = $instance->to_string(true);
$this->assertTrue(strpos($tostring, '!optigroup (level: 1)') !== false);
$this->assertTrue(strpos($tostring, '?child2 (level: 2) =>') !== false);
$this->assertTrue(strpos($tostring, ' => ') !== false);
$this->assertTrue(strpos($tostring, '#four (level: 3) => final4value') !== false);
$this->assertTrue(strpos($tostring, '@attr5 => attr5value') !== false);
$this->assertTrue(strpos($tostring, '#five (level: 3) => not set') !== false);
}
/**
* Incorrect creation tests (attributes and final elements)
*/
function itest_wrong_creation() {
// Create instance with invalid name
try {
$instance = new mock_base_nested_element('');
$this->fail("Expecting base_atom_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_struct_exception);
}
// Create instance with incorrect (object) final element
try {
$obj = new stdClass;
$obj->name = 'test_attr';
$instance = new mock_base_nested_element('TEST', null, $obj);
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Create instance with array containing incorrect (object) final element
try {
$obj = new stdClass;
$obj->name = 'test_attr';
$instance = new mock_base_nested_element('TEST', null, array($obj));
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Create instance with array containing duplicate final elements
try {
$instance = new mock_base_nested_element('TEST', null, array('VAL1', 'VAL2', 'VAL1'));
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Try to get value of base_nested_element
$instance = new mock_base_nested_element('TEST');
try {
$instance->get_value();
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Try to set value of base_nested_element
$instance = new mock_base_nested_element('TEST');
try {
$instance->set_value('some_value');
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
// Try to clean one value of base_nested_element
$instance = new mock_base_nested_element('TEST');
try {
$instance->clean_value('some_value');
$this->fail("Expecting base_element_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_element_struct_exception);
}
}
}
-46
View File
@@ -1,46 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
//require_once($CFG->dirroot . '/backup/util/checks/backup_check.class.php');
/*
* ui tests (all)
*/
class backup_ui_test extends UnitTestCase {
public static $includecoverage = array('backup/util/ui');
public static $excludecoverage = array('backup/util/ui/simpletest');
/*
* test backup_ui class
*/
function test_backup_ui() {
}
}
@@ -1,5 +1,4 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
@@ -16,18 +15,16 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package moodlecore
* @subpackage backup-tests
* @package core_backup
* @category phpunit
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
defined('MOODLE_INTERNAL') || die();
// Include all the needed stuff
global $CFG;
require_once($CFG->dirroot . '/backup/util/xml/output/xml_output.class.php');
require_once($CFG->dirroot . '/backup/util/xml/output/memory_xml_output.class.php');
require_once($CFG->dirroot . '/backup/util/xml/output/file_xml_output.class.php');
@@ -35,10 +32,7 @@ require_once($CFG->dirroot . '/backup/util/xml/output/file_xml_output.class.php'
/*
* xml_output tests (base, memory and file)
*/
class xml_output_test extends UnitTestCase {
public static $includecoverage = array('backup/util/xml/output');
public static $excludecoverage = array('backup/util/xml/output/simpletest');
class xml_output_test extends advanced_testcase {
/*
* test memory_xml_output
@@ -55,7 +49,7 @@ class xml_output_test extends UnitTestCase {
$this->assertTrue(false, 'xml_output_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_output_exception);
$this->assertEqual($e->errorcode, 'xml_output_not_started');
$this->assertEquals($e->errorcode, 'xml_output_not_started');
}
// Try to set buffer size if unsupported
@@ -65,7 +59,7 @@ class xml_output_test extends UnitTestCase {
$this->assertTrue(false, 'xml_output_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_output_exception);
$this->assertEqual($e->errorcode, 'xml_output_buffer_nosupport');
$this->assertEquals($e->errorcode, 'xml_output_buffer_nosupport');
}
// Try to set buffer after start
@@ -76,7 +70,7 @@ class xml_output_test extends UnitTestCase {
$this->assertTrue(false, 'xml_output_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_output_exception);
$this->assertEqual($e->errorcode, 'xml_output_already_started');
$this->assertEquals($e->errorcode, 'xml_output_already_started');
}
// Try to stop output before starting it
@@ -86,7 +80,7 @@ class xml_output_test extends UnitTestCase {
$this->assertTrue(false, 'xml_output_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_output_exception);
$this->assertEqual($e->errorcode, 'xml_output_not_started');
$this->assertEquals($e->errorcode, 'xml_output_not_started');
}
// Try to debug_info() before starting
@@ -96,7 +90,7 @@ class xml_output_test extends UnitTestCase {
$this->assertTrue(false, 'xml_output_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_output_exception);
$this->assertEqual($e->errorcode, 'xml_output_not_stopped');
$this->assertEquals($e->errorcode, 'xml_output_not_stopped');
}
// Start output twice
@@ -107,7 +101,7 @@ class xml_output_test extends UnitTestCase {
$this->assertTrue(false, 'xml_output_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_output_exception);
$this->assertEqual($e->errorcode, 'xml_output_already_started');
$this->assertEquals($e->errorcode, 'xml_output_already_started');
}
// Try to debug_info() before stoping
@@ -118,7 +112,7 @@ class xml_output_test extends UnitTestCase {
$this->assertTrue(false, 'xml_output_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_output_exception);
$this->assertEqual($e->errorcode, 'xml_output_not_stopped');
$this->assertEquals($e->errorcode, 'xml_output_not_stopped');
}
// Stop output twice
@@ -130,7 +124,7 @@ class xml_output_test extends UnitTestCase {
$this->assertTrue(false, 'xml_output_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_output_exception);
$this->assertEqual($e->errorcode, 'xml_output_not_started');
$this->assertEquals($e->errorcode, 'xml_output_not_started');
}
// Try to re-start after stop
@@ -142,7 +136,7 @@ class xml_output_test extends UnitTestCase {
$this->assertTrue(false, 'xml_output_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_output_exception);
$this->assertEqual($e->errorcode, 'xml_output_already_stopped');
$this->assertEquals($e->errorcode, 'xml_output_already_stopped');
}
// Try to get contents before stopping
@@ -153,7 +147,7 @@ class xml_output_test extends UnitTestCase {
$this->assertTrue(false, 'xml_output_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_output_exception);
$this->assertEqual($e->errorcode, 'xml_output_not_stopped');
$this->assertEquals($e->errorcode, 'xml_output_not_stopped');
}
// Write some contents and check them
@@ -161,7 +155,7 @@ class xml_output_test extends UnitTestCase {
$xo->start();
$xo->write('first test');
$xo->stop();
$this->assertEqual('first test', $xo->get_allcontents());
$this->assertEquals('first test', $xo->get_allcontents());
// Write 3 times and check them
$xo = new memory_xml_output();
@@ -170,7 +164,7 @@ class xml_output_test extends UnitTestCase {
$xo->write(', sencond test');
$xo->write(', third test');
$xo->stop();
$this->assertEqual('first test, sencond test, third test', $xo->get_allcontents());
$this->assertEquals('first test, sencond test, third test', $xo->get_allcontents());
// Write some line feeds, tabs and friends
$string = "\n\r\tcrazy test\n\r\t";
@@ -178,7 +172,7 @@ class xml_output_test extends UnitTestCase {
$xo->start();
$xo->write($string);
$xo->stop();
$this->assertEqual($string, $xo->get_allcontents());
$this->assertEquals($string, $xo->get_allcontents());
// Write some UTF-8 chars
$string = 'áéíóú';
@@ -186,7 +180,7 @@ class xml_output_test extends UnitTestCase {
$xo->start();
$xo->write($string);
$xo->stop();
$this->assertEqual($string, $xo->get_allcontents());
$this->assertEquals($string, $xo->get_allcontents());
// Write some empty content
$xo = new memory_xml_output();
@@ -198,7 +192,7 @@ class xml_output_test extends UnitTestCase {
$xo->write('World');
$xo->write(null);
$xo->stop();
$this->assertEqual('Hello World', $xo->get_allcontents());
$this->assertEquals('Hello World', $xo->get_allcontents());
// Get debug info
$xo = new memory_xml_output();
@@ -206,11 +200,11 @@ class xml_output_test extends UnitTestCase {
$xo->write('01234');
$xo->write('56789');
$xo->stop();
$this->assertEqual('0123456789', $xo->get_allcontents());
$this->assertEquals('0123456789', $xo->get_allcontents());
$debug = $xo->debug_info();
$this->assertTrue(is_array($debug));
$this->assertTrue(array_key_exists('sent', $debug));
$this->assertEqual($debug['sent'], 10);
$this->assertEquals($debug['sent'], 10);
}
/*
@@ -219,6 +213,8 @@ class xml_output_test extends UnitTestCase {
function test_file_xml_output() {
global $CFG;
$this->resetAfterTest();
$file = $CFG->tempdir . '/test/test_file_xml_output.txt';
// Remove the test dir and any content
@remove_dir(dirname($file));
@@ -239,7 +235,7 @@ class xml_output_test extends UnitTestCase {
$this->assertTrue(false, 'xml_output_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_output_exception);
$this->assertEqual($e->errorcode, 'directory_not_exists');
$this->assertEquals($e->errorcode, 'directory_not_exists');
}
// Try to init file already existing
@@ -251,7 +247,7 @@ class xml_output_test extends UnitTestCase {
$this->assertTrue(false, 'xml_output_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_output_exception);
$this->assertEqual($e->errorcode, 'file_already_exists');
$this->assertEquals($e->errorcode, 'file_already_exists');
}
unlink($file); // delete file
@@ -261,7 +257,7 @@ class xml_output_test extends UnitTestCase {
$xo->start();
$xo->write('first text');
$xo->stop();
$this->assertEqual('first text', file_get_contents($file));
$this->assertEquals('first text', file_get_contents($file));
unlink($file); // delete file
// With buffer of 4 bytes, send 3 contents of 3 bytes each
@@ -274,7 +270,7 @@ class xml_output_test extends UnitTestCase {
$xo->write('456');
$xo->write('789');
$xo->stop();
$this->assertEqual('123456789', file_get_contents($file));
$this->assertEquals('123456789', file_get_contents($file));
unlink($file); // delete file
// Write some line feeds, tabs and friends
@@ -284,7 +280,7 @@ class xml_output_test extends UnitTestCase {
$xo->start();
$xo->write($string);
$xo->stop();
$this->assertEqual($string, file_get_contents($file));
$this->assertEquals($string, file_get_contents($file));
unlink($file); // delete file
// Write some UTF-8 chars
@@ -294,7 +290,7 @@ class xml_output_test extends UnitTestCase {
$xo->start();
$xo->write($string);
$xo->stop();
$this->assertEqual($string, file_get_contents($file));
$this->assertEquals($string, file_get_contents($file));
unlink($file); // delete file
// Remove the test dir and any content
@@ -1,5 +1,4 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
@@ -16,18 +15,16 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package moodlecore
* @subpackage backup-tests
* @package core_backup
* @category phpunit
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
defined('MOODLE_INTERNAL') || die();
// Include all the needed stuff
global $CFG;
require_once($CFG->dirroot . '/backup/util/xml/parser/progressive_parser.class.php');
require_once($CFG->dirroot . '/backup/util/xml/parser/processors/progressive_parser_processor.class.php');
require_once($CFG->dirroot . '/backup/util/xml/parser/processors/simplified_parser_processor.class.php');
@@ -36,10 +33,7 @@ require_once($CFG->dirroot . '/backup/util/xml/parser/processors/grouped_parser_
/*
* progressive_parser and progressive_parser_processor tests
*/
class progressive_parser_test extends UnitTestCase {
public static $includecoverage = array('backup/util/xml/parser');
public static $excludecoverage = array('backup/util/xml/parser/simpletest');
class progressive_parser_test extends advanced_testcase {
/*
* test progressive_parser public methods
@@ -58,7 +52,7 @@ class progressive_parser_test extends UnitTestCase {
$this->assertTrue(false);
} catch (exception $e) {
$this->assertTrue($e instanceof progressive_parser_exception);
$this->assertEqual($e->errorcode, 'undefined_parser_processor');
$this->assertEquals($e->errorcode, 'undefined_parser_processor');
}
// Assign processor to parser
@@ -70,7 +64,7 @@ class progressive_parser_test extends UnitTestCase {
$this->assertTrue(false);
} catch (exception $e) {
$this->assertTrue($e instanceof progressive_parser_exception);
$this->assertEqual($e->errorcode, 'undefined_xml_to_parse');
$this->assertEquals($e->errorcode, 'undefined_xml_to_parse');
}
// Assign *invalid* processor to parser
@@ -79,30 +73,30 @@ class progressive_parser_test extends UnitTestCase {
$this->assertTrue(false);
} catch (exception $e) {
$this->assertTrue($e instanceof progressive_parser_exception);
$this->assertEqual($e->errorcode, 'invalid_parser_processor');
$this->assertEquals($e->errorcode, 'invalid_parser_processor');
}
// Set file from fixtures (test1.xml) and process it
$pp = new progressive_parser();
$pr = new mock_parser_processor();
$pp->set_processor($pr);
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/simpletest/fixtures/test1.xml');
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/tests/fixtures/test1.xml');
$pp->process();
$serfromfile = serialize($pr->get_chunks()); // Get serialized results (to compare later)
// Set *unexisting* file from fixtures
try {
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/simpletest/fixtures/test0.xml');
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/tests/fixtures/test0.xml');
$this->assertTrue(false);
} catch (exception $e) {
$this->assertTrue($e instanceof progressive_parser_exception);
$this->assertEqual($e->errorcode, 'invalid_file_to_parse');
$this->assertEquals($e->errorcode, 'invalid_file_to_parse');
}
// Set contents from fixtures (test1.xml) and process it
$pp = new progressive_parser();
$pr = new mock_parser_processor();
$pp->set_processor($pr);
$pp->set_contents(file_get_contents($CFG->dirroot . '/backup/util/xml/parser/simpletest/fixtures/test1.xml'));
$pp->set_contents(file_get_contents($CFG->dirroot . '/backup/util/xml/parser/tests/fixtures/test1.xml'));
$pp->process();
$serfrommemory = serialize($pr->get_chunks()); // Get serialized results (to compare later)
// Set *empty* contents
@@ -111,17 +105,17 @@ class progressive_parser_test extends UnitTestCase {
$this->assertTrue(false);
} catch (exception $e) {
$this->assertTrue($e instanceof progressive_parser_exception);
$this->assertEqual($e->errorcode, 'invalid_contents_to_parse');
$this->assertEquals($e->errorcode, 'invalid_contents_to_parse');
}
// Check that both results from file processing and content processing are equal
$this->assertEqual($serfromfile, $serfrommemory);
$this->assertEquals($serfromfile, $serfrommemory);
// Check case_folding is working ok
$pp = new progressive_parser(true);
$pr = new mock_parser_processor();
$pp->set_processor($pr);
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/simpletest/fixtures/test1.xml');
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/tests/fixtures/test1.xml');
$pp->process();
$chunks = $pr->get_chunks();
$this->assertTrue($chunks[0]['path'] === '/FIRSTTAG');
@@ -132,26 +126,26 @@ class progressive_parser_test extends UnitTestCase {
$pp = new progressive_parser(true);
$pr = new mock_parser_processor();
$pp->set_processor($pr);
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/simpletest/fixtures/test2.xml');
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/tests/fixtures/test2.xml');
try {
$pp->process();
} catch (exception $e) {
$this->assertTrue($e instanceof progressive_parser_exception);
$this->assertEqual($e->errorcode, 'xml_parsing_error');
$this->assertEquals($e->errorcode, 'xml_parsing_error');
}
// Check double process throws exception
$pp = new progressive_parser(true);
$pr = new mock_parser_processor();
$pp->set_processor($pr);
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/simpletest/fixtures/test1.xml');
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/tests/fixtures/test1.xml');
$pp->process();
try { // Second process, will throw exception
$pp->process();
$this->assertTrue(false);
} catch (exception $e) {
$this->assertTrue($e instanceof progressive_parser_exception);
$this->assertEqual($e->errorcode, 'progressive_parser_already_used');
$this->assertEquals($e->errorcode, 'progressive_parser_already_used');
}
}
@@ -169,7 +163,7 @@ class progressive_parser_test extends UnitTestCase {
// Assign processor to parser
$pp->set_processor($pr);
// Set file from fixtures
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/simpletest/fixtures/test3.xml');
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/tests/fixtures/test3.xml');
// Process the file, the autotest processor will perform a bunch of automatic tests
$pp->process();
// Get processor debug info
@@ -177,7 +171,7 @@ class progressive_parser_test extends UnitTestCase {
$this->assertTrue(is_array($debug));
$this->assertTrue(array_key_exists('chunks', $debug));
// Check the number of chunks is correct for the file
$this->assertEqual($debug['chunks'], 10);
$this->assertEquals($debug['chunks'], 10);
}
/*
@@ -202,7 +196,7 @@ class progressive_parser_test extends UnitTestCase {
// Assign processor to parser
$pp->set_processor($pr);
// Set file from fixtures
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/simpletest/fixtures/test4.xml');
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/tests/fixtures/test4.xml');
// Process the file
$pp->process();
// Get processor debug info
@@ -211,132 +205,132 @@ class progressive_parser_test extends UnitTestCase {
$this->assertTrue(array_key_exists('chunks', $debug));
// Check the number of chunks is correct for the file
$this->assertEqual($debug['chunks'], 12);
$this->assertEquals($debug['chunks'], 12);
// Get all the simplified chunks and perform various validations
$chunks = $pr->get_chunks();
// Check we have received the correct number of chunks
$this->assertEqual(count($chunks), 12);
$this->assertEquals(count($chunks), 12);
// chunk[0] (/activity) tests
$this->assertEqual(count($chunks[0]), 3);
$this->assertEqual($chunks[0]['path'], '/activity');
$this->assertEqual($chunks[0]['level'],'2');
$this->assertEquals(count($chunks[0]), 3);
$this->assertEquals($chunks[0]['path'], '/activity');
$this->assertEquals($chunks[0]['level'],'2');
$tags = $chunks[0]['tags'];
$this->assertEqual(count($tags), 4);
$this->assertEqual($tags['id'], 1);
$this->assertEqual($tags['moduleid'], 5);
$this->assertEqual($tags['modulename'], 'glossary');
$this->assertEqual($tags['contextid'], 26);
$this->assertEqual($chunks[0]['level'],'2');
$this->assertEquals(count($tags), 4);
$this->assertEquals($tags['id'], 1);
$this->assertEquals($tags['moduleid'], 5);
$this->assertEquals($tags['modulename'], 'glossary');
$this->assertEquals($tags['contextid'], 26);
$this->assertEquals($chunks[0]['level'],'2');
// chunk[1] (/activity/glossary) tests
$this->assertEqual(count($chunks[1]), 3);
$this->assertEqual($chunks[1]['path'], '/activity/glossary');
$this->assertEqual($chunks[1]['level'],'3');
$this->assertEquals(count($chunks[1]), 3);
$this->assertEquals($chunks[1]['path'], '/activity/glossary');
$this->assertEquals($chunks[1]['level'],'3');
$tags = $chunks[1]['tags'];
$this->assertEqual(count($tags), 24);
$this->assertEqual($tags['id'], 1);
$this->assertEqual($tags['intro'], '<p>One simple glossary to test backup &amp; restore. Here it\'s the standard image:</p>'.
$this->assertEquals(count($tags), 24);
$this->assertEquals($tags['id'], 1);
$this->assertEquals($tags['intro'], '<p>One simple glossary to test backup &amp; restore. Here it\'s the standard image:</p>'.
"\n".
'<p><img src="@@PLUGINFILE@@/88_31.png" alt="pwd by moodle" width="88" height="31" /></p>');
$this->assertEqual($tags['timemodified'], 1275639747);
$this->assertEquals($tags['timemodified'], 1275639747);
$this->assertTrue(!isset($tags['categories']));
// chunk[5] (second /activity/glossary/entries/entry) tests
$this->assertEqual(count($chunks[5]), 3);
$this->assertEqual($chunks[5]['path'], '/activity/glossary/entries/entry');
$this->assertEqual($chunks[5]['level'],'5');
$this->assertEquals(count($chunks[5]), 3);
$this->assertEquals($chunks[5]['path'], '/activity/glossary/entries/entry');
$this->assertEquals($chunks[5]['level'],'5');
$tags = $chunks[5]['tags'];
$this->assertEqual(count($tags), 15);
$this->assertEqual($tags['id'], 2);
$this->assertEqual($tags['concept'], 'cat');
$this->assertEquals(count($tags), 15);
$this->assertEquals($tags['id'], 2);
$this->assertEquals($tags['concept'], 'cat');
$this->assertTrue(!isset($tags['aliases']));
$this->assertTrue(!isset($tags['entries']));
// chunk[6] (second /activity/glossary/entries/entry/aliases/alias) tests
$this->assertEqual(count($chunks[6]), 3);
$this->assertEqual($chunks[6]['path'], '/activity/glossary/entries/entry/aliases/alias');
$this->assertEqual($chunks[6]['level'],'7');
$this->assertEquals(count($chunks[6]), 3);
$this->assertEquals($chunks[6]['path'], '/activity/glossary/entries/entry/aliases/alias');
$this->assertEquals($chunks[6]['level'],'7');
$tags = $chunks[6]['tags'];
$this->assertEqual(count($tags), 2);
$this->assertEqual($tags['id'], 2);
$this->assertEqual($tags['alias_text'], 'cats');
$this->assertEquals(count($tags), 2);
$this->assertEquals($tags['id'], 2);
$this->assertEquals($tags['alias_text'], 'cats');
// chunk[7] (second /activity/glossary/entries/entry/aliases/alias) tests
$this->assertEqual(count($chunks[7]), 3);
$this->assertEqual($chunks[7]['path'], '/activity/glossary/entries/entry/aliases/alias');
$this->assertEqual($chunks[7]['level'],'7');
$this->assertEquals(count($chunks[7]), 3);
$this->assertEquals($chunks[7]['path'], '/activity/glossary/entries/entry/aliases/alias');
$this->assertEquals($chunks[7]['level'],'7');
$tags = $chunks[7]['tags'];
$this->assertEqual(count($tags), 2);
$this->assertEqual($tags['id'], 3);
$this->assertEqual($tags['alias_text'], 'felines');
$this->assertEquals(count($tags), 2);
$this->assertEquals($tags['id'], 3);
$this->assertEquals($tags['alias_text'], 'felines');
// chunk[8] (second /activity/glossary/entries/entry/ratings/rating) tests
$this->assertEqual(count($chunks[8]), 3);
$this->assertEqual($chunks[8]['path'], '/activity/glossary/entries/entry/ratings/rating');
$this->assertEqual($chunks[8]['level'],'7');
$this->assertEquals(count($chunks[8]), 3);
$this->assertEquals($chunks[8]['path'], '/activity/glossary/entries/entry/ratings/rating');
$this->assertEquals($chunks[8]['level'],'7');
$tags = $chunks[8]['tags'];
$this->assertEqual(count($tags), 6);
$this->assertEqual($tags['id'], 1);
$this->assertEqual($tags['timemodified'], '1275639779');
$this->assertEquals(count($tags), 6);
$this->assertEquals($tags['id'], 1);
$this->assertEquals($tags['timemodified'], '1275639779');
// chunk[9] (first /activity/glossary/onetest) tests
$this->assertEqual(count($chunks[9]), 3);
$this->assertEqual($chunks[9]['path'], '/activity/glossary/onetest');
$this->assertEqual($chunks[9]['level'],'4');
$this->assertEquals(count($chunks[9]), 3);
$this->assertEquals($chunks[9]['path'], '/activity/glossary/onetest');
$this->assertEquals($chunks[9]['level'],'4');
$tags = $chunks[9]['tags'];
$this->assertEqual(count($tags), 2);
$this->assertEqual($tags['name'], 1);
$this->assertEqual($tags['value'], 1);
$this->assertEquals(count($tags), 2);
$this->assertEquals($tags['name'], 1);
$this->assertEquals($tags['value'], 1);
// chunk[10] (second /activity/glossary/onetest) tests
$this->assertEqual(count($chunks[10]), 3);
$this->assertEqual($chunks[10]['path'], '/activity/glossary/onetest');
$this->assertEqual($chunks[10]['level'],'4');
$this->assertEquals(count($chunks[10]), 3);
$this->assertEquals($chunks[10]['path'], '/activity/glossary/onetest');
$this->assertEquals($chunks[10]['level'],'4');
$tags = $chunks[10]['tags'];
$this->assertEqual(count($tags), 2);
$this->assertEqual($tags['name'], 2);
$this->assertEqual($tags['value'], 2);
$this->assertEquals(count($tags), 2);
$this->assertEquals($tags['name'], 2);
$this->assertEquals($tags['value'], 2);
// chunk[11] (first /activity/glossary/othertest) tests
// note we don't allow repeated "final" element, so we only return the last one
$this->assertEqual(count($chunks[11]), 3);
$this->assertEqual($chunks[11]['path'], '/activity/glossary/othertest');
$this->assertEqual($chunks[11]['level'],'4');
$this->assertEquals(count($chunks[11]), 3);
$this->assertEquals($chunks[11]['path'], '/activity/glossary/othertest');
$this->assertEquals($chunks[11]['level'],'4');
$tags = $chunks[11]['tags'];
$this->assertEqual(count($tags), 2);
$this->assertEqual($tags['name'], 4);
$this->assertEqual($tags['value'], 5);
$this->assertEquals(count($tags), 2);
$this->assertEquals($tags['name'], 4);
$this->assertEquals($tags['value'], 5);
// Now check start notifications
$snotifs = $pr->get_start_notifications();
// Check we have received the correct number of notifications
$this->assertEqual(count($snotifs), 12);
$this->assertEquals(count($snotifs), 12);
// Check first, sixth and last notifications
$this->assertEqual($snotifs[0], '/activity');
$this->assertEqual($snotifs[5], '/activity/glossary/entries/entry');
$this->assertEqual($snotifs[11], '/activity/glossary/othertest');
$this->assertEquals($snotifs[0], '/activity');
$this->assertEquals($snotifs[5], '/activity/glossary/entries/entry');
$this->assertEquals($snotifs[11], '/activity/glossary/othertest');
// Now check end notifications
$enotifs = $pr->get_end_notifications();
// Check we have received the correct number of notifications
$this->assertEqual(count($snotifs), 12);
$this->assertEquals(count($snotifs), 12);
// Check first, sixth and last notifications
$this->assertEqual($enotifs[0], '/activity/glossary/entries/entry/aliases/alias');
$this->assertEqual($enotifs[5], '/activity/glossary/entries/entry/ratings/rating');
$this->assertEqual($enotifs[11], '/activity');
$this->assertEquals($enotifs[0], '/activity/glossary/entries/entry/aliases/alias');
$this->assertEquals($enotifs[5], '/activity/glossary/entries/entry/ratings/rating');
$this->assertEquals($enotifs[11], '/activity');
// Check start and end notifications are balanced
sort($snotifs);
sort($enotifs);
$this->assertEqual($snotifs, $enotifs);
$this->assertEquals($snotifs, $enotifs);
// Now verify that the start/process/end order is correct
$allnotifs = $pr->get_all_notifications();
$this->assertEqual(count($allnotifs), count($snotifs) + count($enotifs) + count($chunks)); // The count
$this->assertEquals(count($allnotifs), count($snotifs) + count($enotifs) + count($chunks)); // The count
// Check integrity of the notifications
$errcount = $this->helper_check_notifications_order_integrity($allnotifs);
$this->assertEqual($errcount, 0); // No errors found, plz
$this->assertEquals($errcount, 0); // No errors found, plz
}
/**
@@ -359,51 +353,51 @@ class progressive_parser_test extends UnitTestCase {
// Assign processor to parser
$pp->set_processor($pr);
// Set file from fixtures
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/simpletest/fixtures/test5.xml');
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/tests/fixtures/test5.xml');
// Process the file
$pp->process();
// Get all the simplified chunks and perform various validations
$chunks = $pr->get_chunks();
$this->assertEqual(count($chunks), 3); // Only 3, because 7 (COURSE, ROLES_OVERRIDES and 5 MOD) are empty, aka no chunk
$this->assertEquals(count($chunks), 3); // Only 3, because 7 (COURSE, ROLES_OVERRIDES and 5 MOD) are empty, aka no chunk
// Now check start notifications
$snotifs = $pr->get_start_notifications();
// Check we have received the correct number of notifications
$this->assertEqual(count($snotifs), 10); // Start tags are dispatched for empties (ROLES_OVERRIDES)
$this->assertEquals(count($snotifs), 10); // Start tags are dispatched for empties (ROLES_OVERRIDES)
// Check first and last notifications
$this->assertEqual($snotifs[0], '/MOODLE_BACKUP/COURSE');
$this->assertEqual($snotifs[1], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION');
$this->assertEqual($snotifs[2], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEqual($snotifs[3], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD/ROLES_OVERRIDES');
$this->assertEqual($snotifs[7], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEqual($snotifs[8], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEqual($snotifs[9], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEquals($snotifs[0], '/MOODLE_BACKUP/COURSE');
$this->assertEquals($snotifs[1], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION');
$this->assertEquals($snotifs[2], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEquals($snotifs[3], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD/ROLES_OVERRIDES');
$this->assertEquals($snotifs[7], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEquals($snotifs[8], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEquals($snotifs[9], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
// Now check end notifications
$enotifs = $pr->get_end_notifications();
// Check we have received the correct number of notifications
$this->assertEqual(count($snotifs), 10); // End tags are dispatched for empties (ROLES_OVERRIDES)
$this->assertEquals(count($snotifs), 10); // End tags are dispatched for empties (ROLES_OVERRIDES)
// Check first, and last notifications
$this->assertEqual($enotifs[0], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD/ROLES_OVERRIDES');
$this->assertEqual($enotifs[1], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEqual($enotifs[2], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEqual($enotifs[3], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEqual($enotifs[7], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEqual($enotifs[8], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION');
$this->assertEqual($enotifs[9], '/MOODLE_BACKUP/COURSE');
$this->assertEquals($enotifs[0], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD/ROLES_OVERRIDES');
$this->assertEquals($enotifs[1], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEquals($enotifs[2], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEquals($enotifs[3], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEquals($enotifs[7], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION/MODS/MOD');
$this->assertEquals($enotifs[8], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION');
$this->assertEquals($enotifs[9], '/MOODLE_BACKUP/COURSE');
// Check start and end notifications are balanced
sort($snotifs);
sort($enotifs);
$this->assertEqual($snotifs, $enotifs);
$this->assertEquals($snotifs, $enotifs);
// Now verify that the start/process/end order is correct
$allnotifs = $pr->get_all_notifications();
$this->assertEqual(count($allnotifs), count($snotifs) + count($enotifs) + count($chunks)); // The count
$this->assertEquals(count($allnotifs), count($snotifs) + count($enotifs) + count($chunks)); // The count
// Check integrity of the notifications
$errcount = $this->helper_check_notifications_order_integrity($allnotifs);
$this->assertEqual($errcount, 0); // No errors found, plz
$this->assertEquals($errcount, 0); // No errors found, plz
}
/*
@@ -429,7 +423,7 @@ class progressive_parser_test extends UnitTestCase {
// Assign processor to parser
$pp->set_processor($pr);
// Set file from fixtures
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/simpletest/fixtures/test4.xml');
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/tests/fixtures/test4.xml');
// Process the file
$pp->process();
// Get processor debug info
@@ -438,35 +432,35 @@ class progressive_parser_test extends UnitTestCase {
$this->assertTrue(array_key_exists('chunks', $debug));
// Check the number of chunks is correct for the file
$this->assertEqual($debug['chunks'], 2);
$this->assertEquals($debug['chunks'], 2);
// Get all the simplified chunks and perform various validations
$chunks = $pr->get_chunks();
// Check we have received the correct number of chunks
$this->assertEqual(count($chunks), 2);
$this->assertEquals(count($chunks), 2);
// chunk[0] (/activity) tests
$this->assertEqual(count($chunks[0]), 3);
$this->assertEqual($chunks[0]['path'], '/activity');
$this->assertEqual($chunks[0]['level'],'2');
$this->assertEquals(count($chunks[0]), 3);
$this->assertEquals($chunks[0]['path'], '/activity');
$this->assertEquals($chunks[0]['level'],'2');
$tags = $chunks[0]['tags'];
$this->assertEqual(count($tags), 4);
$this->assertEqual($tags['id'], 1);
$this->assertEqual($tags['moduleid'], 5);
$this->assertEqual($tags['modulename'], 'glossary');
$this->assertEqual($tags['contextid'], 26);
$this->assertEqual($chunks[0]['level'],'2');
$this->assertEquals(count($tags), 4);
$this->assertEquals($tags['id'], 1);
$this->assertEquals($tags['moduleid'], 5);
$this->assertEquals($tags['modulename'], 'glossary');
$this->assertEquals($tags['contextid'], 26);
$this->assertEquals($chunks[0]['level'],'2');
// chunk[1] (grouped /activity/glossary tests)
$this->assertEqual(count($chunks[1]), 3);
$this->assertEqual($chunks[1]['path'], '/activity/glossary');
$this->assertEqual($chunks[1]['level'],'3');
$this->assertEquals(count($chunks[1]), 3);
$this->assertEquals($chunks[1]['path'], '/activity/glossary');
$this->assertEquals($chunks[1]['level'],'3');
$tags = $chunks[1]['tags'];
$this->assertEqual(count($tags), 27);
$this->assertEqual($tags['id'], 1);
$this->assertEqual($tags['intro'], '<p>One simple glossary to test backup &amp; restore. Here it\'s the standard image:</p>'.
$this->assertEquals(count($tags), 27);
$this->assertEquals($tags['id'], 1);
$this->assertEquals($tags['intro'], '<p>One simple glossary to test backup &amp; restore. Here it\'s the standard image:</p>'.
"\n".
'<p><img src="@@PLUGINFILE@@/88_31.png" alt="pwd by moodle" width="88" height="31" /></p>');
$this->assertEqual($tags['timemodified'], 1275639747);
$this->assertEquals($tags['timemodified'], 1275639747);
$this->assertTrue(!isset($tags['categories']));
$this->assertTrue(isset($tags['entries']));
$this->assertTrue(isset($tags['onetest']));
@@ -474,111 +468,111 @@ class progressive_parser_test extends UnitTestCase {
// Various tests under the entries
$entries = $chunks[1]['tags']['entries']['entry'];
$this->assertEqual(count($entries), 2);
$this->assertEquals(count($entries), 2);
// First entry
$entry1 = $entries[0];
$this->assertEqual(count($entry1), 17);
$this->assertEqual($entry1['id'], 1);
$this->assertEqual($entry1['userid'], 2);
$this->assertEqual($entry1['concept'], 'dog');
$this->assertEqual($entry1['definition'], '<p>Traditional enemies of cats</p>');
$this->assertEquals(count($entry1), 17);
$this->assertEquals($entry1['id'], 1);
$this->assertEquals($entry1['userid'], 2);
$this->assertEquals($entry1['concept'], 'dog');
$this->assertEquals($entry1['definition'], '<p>Traditional enemies of cats</p>');
$this->assertTrue(isset($entry1['aliases']));
$this->assertTrue(isset($entry1['ratings']));
// aliases of first entry
$aliases = $entry1['aliases']['alias'];
$this->assertEqual(count($aliases), 1);
$this->assertEquals(count($aliases), 1);
// first alias
$alias1 = $aliases[0];
$this->assertEqual(count($alias1), 2);
$this->assertEqual($alias1['id'], 1);
$this->assertEqual($alias1['alias_text'], 'dogs');
$this->assertEquals(count($alias1), 2);
$this->assertEquals($alias1['id'], 1);
$this->assertEquals($alias1['alias_text'], 'dogs');
// ratings of first entry
$ratings = $entry1['ratings']['rating'];
$this->assertEqual(count($ratings), 1);
$this->assertEquals(count($ratings), 1);
// first rating
$rating1 = $ratings[0];
$this->assertEqual(count($rating1), 6);
$this->assertEqual($rating1['id'], 2);
$this->assertEqual($rating1['value'], 6);
$this->assertEqual($rating1['timemodified'], '1275639797');
$this->assertEquals(count($rating1), 6);
$this->assertEquals($rating1['id'], 2);
$this->assertEquals($rating1['value'], 6);
$this->assertEquals($rating1['timemodified'], '1275639797');
// Second entry
$entry2 = $entries[1];
$this->assertEqual(count($entry2), 17);
$this->assertEqual($entry2['id'], 2);
$this->assertEqual($entry2['userid'], 2);
$this->assertEqual($entry2['concept'], 'cat');
$this->assertEqual($entry2['definition'], '<p>traditional enemies of dogs</p>');
$this->assertEquals(count($entry2), 17);
$this->assertEquals($entry2['id'], 2);
$this->assertEquals($entry2['userid'], 2);
$this->assertEquals($entry2['concept'], 'cat');
$this->assertEquals($entry2['definition'], '<p>traditional enemies of dogs</p>');
$this->assertTrue(isset($entry2['aliases']));
$this->assertTrue(isset($entry2['ratings']));
// aliases of first entry
$aliases = $entry2['aliases']['alias'];
$this->assertEqual(count($aliases), 2);
$this->assertEquals(count($aliases), 2);
// first alias
$alias1 = $aliases[0];
$this->assertEqual(count($alias1), 2);
$this->assertEqual($alias1['id'], 2);
$this->assertEqual($alias1['alias_text'], 'cats');
$this->assertEquals(count($alias1), 2);
$this->assertEquals($alias1['id'], 2);
$this->assertEquals($alias1['alias_text'], 'cats');
// second alias
$alias2 = $aliases[1];
$this->assertEqual(count($alias2), 2);
$this->assertEqual($alias2['id'], 3);
$this->assertEqual($alias2['alias_text'], 'felines');
$this->assertEquals(count($alias2), 2);
$this->assertEquals($alias2['id'], 3);
$this->assertEquals($alias2['alias_text'], 'felines');
// ratings of first entry
$ratings = $entry2['ratings']['rating'];
$this->assertEqual(count($ratings), 1);
$this->assertEquals(count($ratings), 1);
// first rating
$rating1 = $ratings[0];
$this->assertEqual(count($rating1), 6);
$this->assertEqual($rating1['id'], 1);
$this->assertEqual($rating1['value'], 5);
$this->assertEqual($rating1['scaleid'], 10);
$this->assertEquals(count($rating1), 6);
$this->assertEquals($rating1['id'], 1);
$this->assertEquals($rating1['value'], 5);
$this->assertEquals($rating1['scaleid'], 10);
// Onetest test (only 1 level nested)
$onetest = $tags['onetest'];
$this->assertEqual(count($onetest), 2);
$this->assertEqual(count($onetest[0]), 2);
$this->assertEqual($onetest[0]['name'], 1);
$this->assertEqual($onetest[0]['value'], 1);
$this->assertEqual(count($onetest[1]), 2);
$this->assertEqual($onetest[1]['name'], 2);
$this->assertEqual($onetest[1]['value'], 2);
$this->assertEquals(count($onetest), 2);
$this->assertEquals(count($onetest[0]), 2);
$this->assertEquals($onetest[0]['name'], 1);
$this->assertEquals($onetest[0]['value'], 1);
$this->assertEquals(count($onetest[1]), 2);
$this->assertEquals($onetest[1]['name'], 2);
$this->assertEquals($onetest[1]['value'], 2);
// Other test (0 level nested, only last one is retrieved)
$othertest = $tags['othertest'];
$this->assertEqual(count($othertest), 1);
$this->assertEqual(count($othertest[0]), 2);
$this->assertEqual($othertest[0]['name'], 4);
$this->assertEqual($othertest[0]['value'], 5);
$this->assertEquals(count($othertest), 1);
$this->assertEquals(count($othertest[0]), 2);
$this->assertEquals($othertest[0]['name'], 4);
$this->assertEquals($othertest[0]['value'], 5);
// Now check start notifications
$snotifs = $pr->get_start_notifications();
// Check we have received the correct number of notifications
$this->assertEqual(count($snotifs), 2);
$this->assertEquals(count($snotifs), 2);
// Check first and last notifications
$this->assertEqual($snotifs[0], '/activity');
$this->assertEqual($snotifs[1], '/activity/glossary');
$this->assertEquals($snotifs[0], '/activity');
$this->assertEquals($snotifs[1], '/activity/glossary');
// Now check end notifications
$enotifs = $pr->get_end_notifications();
// Check we have received the correct number of notifications
$this->assertEqual(count($snotifs), 2);
$this->assertEquals(count($snotifs), 2);
// Check first, and last notifications
$this->assertEqual($enotifs[0], '/activity/glossary');
$this->assertEqual($enotifs[1], '/activity');
$this->assertEquals($enotifs[0], '/activity/glossary');
$this->assertEquals($enotifs[1], '/activity');
// Check start and end notifications are balanced
sort($snotifs);
sort($enotifs);
$this->assertEqual($snotifs, $enotifs);
$this->assertEquals($snotifs, $enotifs);
// Now verify that the start/process/end order is correct
$allnotifs = $pr->get_all_notifications();
$this->assertEqual(count($allnotifs), count($snotifs) + count($enotifs) + count($chunks)); // The count
$this->assertEquals(count($allnotifs), count($snotifs) + count($enotifs) + count($chunks)); // The count
// Check integrity of the notifications
$errcount = $this->helper_check_notifications_order_integrity($allnotifs);
$this->assertEqual($errcount, 0); // No errors found, plz
$this->assertEquals($errcount, 0); // No errors found, plz
}
/**
@@ -601,41 +595,41 @@ class progressive_parser_test extends UnitTestCase {
// Assign processor to parser
$pp->set_processor($pr);
// Set file from fixtures
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/simpletest/fixtures/test5.xml');
$pp->set_file($CFG->dirroot . '/backup/util/xml/parser/tests/fixtures/test5.xml');
// Process the file
$pp->process();
// Get all the simplified chunks and perform various validations
$chunks = $pr->get_chunks();
$this->assertEqual(count($chunks), 1); // Only 1, the SECTION one
$this->assertEquals(count($chunks), 1); // Only 1, the SECTION one
// Now check start notifications
$snotifs = $pr->get_start_notifications();
// Check we have received the correct number of notifications
$this->assertEqual(count($snotifs), 2);
$this->assertEquals(count($snotifs), 2);
// Check first and last notifications
$this->assertEqual($snotifs[0], '/MOODLE_BACKUP/COURSE');
$this->assertEqual($snotifs[1], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION');
$this->assertEquals($snotifs[0], '/MOODLE_BACKUP/COURSE');
$this->assertEquals($snotifs[1], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION');
// Now check end notifications
$enotifs = $pr->get_end_notifications();
// Check we have received the correct number of notifications
$this->assertEqual(count($snotifs), 2); // End tags are dispatched for empties (ROLES_OVERRIDES)
$this->assertEquals(count($snotifs), 2); // End tags are dispatched for empties (ROLES_OVERRIDES)
// Check first, and last notifications
$this->assertEqual($enotifs[0], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION');
$this->assertEqual($enotifs[1], '/MOODLE_BACKUP/COURSE');
$this->assertEquals($enotifs[0], '/MOODLE_BACKUP/COURSE/SECTIONS/SECTION');
$this->assertEquals($enotifs[1], '/MOODLE_BACKUP/COURSE');
// Check start and end notifications are balanced
sort($snotifs);
sort($enotifs);
$this->assertEqual($snotifs, $enotifs);
$this->assertEquals($snotifs, $enotifs);
// Now verify that the start/process/end order is correct
$allnotifs = $pr->get_all_notifications();
$this->assertEqual(count($allnotifs), count($snotifs) + count($enotifs) + count($chunks)); // The count
$this->assertEquals(count($allnotifs), count($snotifs) + count($enotifs) + count($chunks)); // The count
// Check integrity of the notifications
$errcount = $this->helper_check_notifications_order_integrity($allnotifs);
$this->assertEqual($errcount, 0); // No errors found, plz
$this->assertEquals($errcount, 0); // No errors found, plz
}
@@ -723,19 +717,19 @@ class mock_auto_parser_processor extends progressive_parser_processor {
if (isset($data['tags'])) {
foreach ($data['tags'] as $tag) {
if (isset($tag['attrs']['name'])) { // name tests
$this->utc->assertEqual($tag['name'], $tag['attrs']['name']);
$this->utc->assertEquals($tag['name'], $tag['attrs']['name']);
}
if (isset($tag['attrs']['level'])) { // level tests
$this->utc->assertEqual($data['level'], $tag['attrs']['level']);
$this->utc->assertEquals($data['level'], $tag['attrs']['level']);
}
if (isset($tag['attrs']['path'])) { // path tests
$this->utc->assertEqual(rtrim($data['path'], '/') . '/' . $tag['name'], $tag['attrs']['path']);
$this->utc->assertEquals(rtrim($data['path'], '/') . '/' . $tag['name'], $tag['attrs']['path']);
}
if (!empty($tag['cdata'])) { // cdata tests
if (isset($tag['attrs']['value'])) {
$this->utc->assertEqual($tag['cdata'], $tag['attrs']['value']);
$this->utc->assertEquals($tag['cdata'], $tag['attrs']['value']);
} else {
$this->utc->assertEqual($tag['cdata'], $tag['name']);
$this->utc->assertEquals($tag['cdata'], $tag['name']);
}
}
}
-329
View File
@@ -1,329 +0,0 @@
<?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 moodlecore
* @subpackage backup-tests
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this file
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
// Include all the needed stuff
require_once($CFG->dirroot . '/backup/util/xml/xml_writer.class.php');
require_once($CFG->dirroot . '/backup/util/xml/output/xml_output.class.php');
require_once($CFG->dirroot . '/backup/util/xml/output/memory_xml_output.class.php');
require_once($CFG->dirroot . '/backup/util/xml/contenttransformer/xml_contenttransformer.class.php');
/*
* xml_writer tests
*/
class xml_writer_test extends UnitTestCase {
public static $includecoverage = array('backup/util/xml/xml_writer.class.php');
public static $excludecoverage = array('backup/util/xml/simpletest');
/*
* test xml_writer public methods
*/
function test_xml_writer_public_api() {
global $CFG;
// Instantiate xml_output
$xo = new memory_xml_output();
$this->assertTrue($xo instanceof xml_output);
// Instantiate xml_writer with null xml_output
try {
$xw = new mock_xml_writer(null);
$this->assertTrue(false, 'xml_writer_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_writer_exception);
$this->assertEqual($e->errorcode, 'invalid_xml_output');
}
// Instantiate xml_writer with wrong xml_output object
try {
$xw = new mock_xml_writer(new stdclass());
$this->assertTrue(false, 'xml_writer_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_writer_exception);
$this->assertEqual($e->errorcode, 'invalid_xml_output');
}
// Instantiate xml_writer with wrong xml_contenttransformer object
try {
$xw = new mock_xml_writer($xo, new stdclass());
$this->assertTrue(false, 'xml_writer_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_writer_exception);
$this->assertEqual($e->errorcode, 'invalid_xml_contenttransformer');
}
// Instantiate xml_writer and start it twice
$xw = new mock_xml_writer($xo);
$xw->start();
try {
$xw->start();
$this->assertTrue(false, 'xml_writer_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_writer_exception);
$this->assertEqual($e->errorcode, 'xml_writer_already_started');
}
// Instantiate xml_writer and stop it twice
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->start();
$xw->stop();
try {
$xw->stop();
$this->assertTrue(false, 'xml_writer_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_writer_exception);
$this->assertEqual($e->errorcode, 'xml_writer_already_stopped');
}
// Stop writer without starting it
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
try {
$xw->stop();
$this->assertTrue(false, 'xml_writer_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_writer_exception);
$this->assertEqual($e->errorcode, 'xml_writer_not_started');
}
// Start writer after stopping it
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->start();
$xw->stop();
try {
$xw->start();
$this->assertTrue(false, 'xml_writer_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_writer_exception);
$this->assertEqual($e->errorcode, 'xml_writer_already_stopped');
}
// Try to set prologue/schema after start
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->start();
try {
$xw->set_nonamespace_schema('http://moodle.org');
$this->assertTrue(false, 'xml_writer_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_writer_exception);
$this->assertEqual($e->errorcode, 'xml_writer_already_started');
}
try {
$xw->set_prologue('sweet prologue');
$this->assertTrue(false, 'xml_writer_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_writer_exception);
$this->assertEqual($e->errorcode, 'xml_writer_already_started');
}
// Instantiate properly with memory_xml_output, start and stop.
// Must get default UTF-8 prologue
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->start();
$xw->stop();
$this->assertEqual($xo->get_allcontents(), $xw->get_default_prologue());
// Instantiate, set prologue and schema, put 1 full tag and get results
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->set_prologue('CLEARLY WRONG PROLOGUE');
$xw->set_nonamespace_schema('http://moodle.org/littleschema');
$xw->start();
$xw->full_tag('TEST', 'Hello World!', array('id' => 1));
$xw->stop();
$result = $xo->get_allcontents();
// Perform various checks
$this->assertEqual(strpos($result, 'WRONG'), 8);
$this->assertEqual(strpos($result, '<TEST id="1"'), 22);
$this->assertEqual(strpos($result, 'xmlns:xsi='), 39);
$this->assertEqual(strpos($result, 'http://moodle.org/littleschema'), 128);
$this->assertEqual(strpos($result, 'Hello World'), 160);
$this->assertFalse(strpos($result, $xw->get_default_prologue()));
// Try to close one tag in wrong order
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->start();
$xw->begin_tag('first');
$xw->begin_tag('second');
try {
$xw->end_tag('first');
$this->assertTrue(false, 'xml_writer_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_writer_exception);
$this->assertEqual($e->errorcode, 'xml_writer_end_tag_no_match');
}
// Try to close one tag before starting any tag
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->start();
try {
$xw->end_tag('first');
$this->assertTrue(false, 'xml_writer_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_writer_exception);
$this->assertEqual($e->errorcode, 'xml_writer_end_tag_no_match');
}
// Full tag without contents (null and empty string)
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->set_prologue(''); // empty prologue for easier matching
$xw->start();
$xw->full_tag('tagname', null, array('attrname' => 'attrvalue'));
$xw->full_tag('tagname2', '', array('attrname' => 'attrvalue'));
$xw->stop();
$result = $xo->get_allcontents();
$this->assertEqual($result, '<tagname attrname="attrvalue" /><tagname2 attrname="attrvalue"></tagname2>');
// Test case-folding is working
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo, null, true);
$xw->set_prologue(''); // empty prologue for easier matching
$xw->start();
$xw->full_tag('tagname', 'textcontent', array('attrname' => 'attrvalue'));
$xw->stop();
$result = $xo->get_allcontents();
$this->assertEqual($result, '<TAGNAME ATTRNAME="attrvalue">textcontent</TAGNAME>');
// Test UTF-8 chars in tag and attribute names, attr values and contents
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->set_prologue(''); // empty prologue for easier matching
$xw->start();
$xw->full_tag('áéíóú', 'ÁÉÍÓÚ', array('àèìòù' => 'ÀÈÌÒÙ'));
$xw->stop();
$result = $xo->get_allcontents();
$this->assertEqual($result, '<áéíóú àèìòù="ÀÈÌÒÙ">ÁÉÍÓÚ</áéíóú>');
// Try non-safe content in attributes
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->set_prologue(''); // empty prologue for easier matching
$xw->start();
$xw->full_tag('tagname', 'textcontent', array('attrname' => 'attr' . chr(27) . '\'"value'));
$xw->stop();
$result = $xo->get_allcontents();
$this->assertEqual($result, '<tagname attrname="attr\'&quot;value">textcontent</tagname>');
// Try non-safe content in text
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->set_prologue(''); // empty prologue for easier matching
$xw->start();
$xw->full_tag('tagname', "text\r\ncontent\rwith" . chr(27), array('attrname' => 'attrvalue'));
$xw->stop();
$result = $xo->get_allcontents();
$this->assertEqual($result, '<tagname attrname="attrvalue">text' . "\ncontent\n" . 'with</tagname>');
// Try to stop the writer without clossing all the open tags
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->start();
$xw->begin_tag('first');
try {
$xw->stop();
$this->assertTrue(false, 'xml_writer_exception expected');
} catch (exception $e) {
$this->assertTrue($e instanceof xml_writer_exception);
$this->assertEqual($e->errorcode, 'xml_writer_open_tags_remaining');
}
// Test simple transformer
$xo = new memory_xml_output();
$xt = new mock_xml_contenttransformer();
$xw = new mock_xml_writer($xo, $xt);
$xw->set_prologue(''); // empty prologue for easier matching
$xw->start();
$xw->full_tag('tagname', null, array('attrname' => 'attrvalue'));
$xw->full_tag('tagname2', 'somecontent', array('attrname' => 'attrvalue'));
$xw->stop();
$result = $xo->get_allcontents();
$this->assertEqual($result, '<tagname attrname="attrvalue" /><tagname2 attrname="attrvalue">testsomecontent</tagname2>');
// Build a complex XML file and test results against stored file in fixtures
$xo = new memory_xml_output();
$xw = new mock_xml_writer($xo);
$xw->start();
$xw->begin_tag('toptag', array('name' => 'toptag', 'level' => 1, 'path' => '/toptag'));
$xw->full_tag('secondtag', 'secondvalue', array('name' => 'secondtag', 'level' => 2, 'path' => '/toptag/secondtag', 'value' => 'secondvalue'));
$xw->begin_tag('thirdtag', array('name' => 'thirdtag', 'level' => 2, 'path' => '/toptag/thirdtag'));
$xw->full_tag('onevalue', 'onevalue', array('name' => 'onevalue', 'level' => 3, 'path' => '/toptag/thirdtag/onevalue'));
$xw->full_tag('onevalue', 'anothervalue', array('name' => 'onevalue', 'level' => 3, 'value' => 'anothervalue'));
$xw->full_tag('onevalue', 'yetanothervalue', array('name' => 'onevalue', 'level' => 3, 'value' => 'yetanothervalue'));
$xw->full_tag('twovalue', 'twovalue', array('name' => 'twovalue', 'level' => 3, 'path' => '/toptag/thirdtag/twovalue'));
$xw->begin_tag('forthtag', array('name' => 'forthtag', 'level' => 3, 'path' => '/toptag/thirdtag/forthtag'));
$xw->full_tag('innervalue', 'innervalue');
$xw->begin_tag('innertag');
$xw->begin_tag('superinnertag', array('name' => 'superinnertag', 'level' => 5));
$xw->full_tag('superinnervalue', 'superinnervalue', array('name' => 'superinnervalue', 'level' => 6));
$xw->end_tag('superinnertag');
$xw->end_tag('innertag');
$xw->end_tag('forthtag');
$xw->begin_tag('fifthtag', array('level' => 3));
$xw->begin_tag('sixthtag', array('level' => 4));
$xw->full_tag('seventh', 'seventh', array('level' => 5));
$xw->end_tag('sixthtag');
$xw->end_tag('fifthtag');
$xw->full_tag('finalvalue', 'finalvalue', array('name' => 'finalvalue', 'level' => 3, 'path' => '/toptag/thirdtag/finalvalue'));
$xw->full_tag('finalvalue');
$xw->end_tag('thirdtag');
$xw->end_tag('toptag');
$xw->stop();
$result = $xo->get_allcontents();
$fcontents = file_get_contents($CFG->dirroot . '/backup/util/xml/simpletest/fixtures/test1.xml');
// Normalise carriage return characters.
$fcontents = str_replace("\r\n", "\n", $fcontents);
$this->assertEqual(trim($result), trim($fcontents));
}
}
/*
* helper extended xml_writer class that makes some methods public for testing
*/
class mock_xml_writer extends xml_writer {
public function get_default_prologue() {
return parent::get_default_prologue();
}
}
/*
* helper extended xml_contenttransformer prepending "test" to all the notnull contents
*/
class mock_xml_contenttransformer extends xml_contenttransformer {
public function process($content) {
return is_null($content) ? null : 'test' . $content;
}
}
+1 -1
View File
@@ -296,7 +296,7 @@ class xml_writer_testcase extends basic_testcase {
$xw->end_tag('toptag');
$xw->stop();
$result = $xo->get_allcontents();
$fcontents = file_get_contents($CFG->dirroot . '/backup/util/xml/simpletest/fixtures/test1.xml');
$fcontents = file_get_contents($CFG->dirroot . '/backup/util/xml/tests/fixtures/test1.xml');
// Normalise carriage return characters.
$fcontents = str_replace("\r\n", "\n", $fcontents);