From 7a636d6e7f17bb17bd0d71791bd41ea0bc739610 Mon Sep 17 00:00:00 2001 From: Petr Skoda Date: Sat, 21 Apr 2012 16:36:37 +0200 Subject: [PATCH] MDL-32569 drop migrated core simpletests --- lib/simpletest/broken_testfilelib.php | 347 ---- lib/simpletest/fixtures/events.php | 44 - lib/simpletest/fixtures/gradetest.php | 878 --------- lib/simpletest/fixtures/user_agents.php | 57 - lib/simpletest/fulltestaccesslib.php | 1172 ------------ lib/simpletest/testbackuplib.php | 46 - lib/simpletest/testblocklib_blockmanager.php | 399 ---- lib/simpletest/testcode.php | 50 - lib/simpletest/testcompletionlib.php | 698 ------- lib/simpletest/testcomponentlib.php | 181 -- lib/simpletest/testconditionlib.php | 385 ---- lib/simpletest/testcsslib.php | 721 ------- lib/simpletest/testdeprecatedlib.php | 34 - lib/simpletest/testeventslib.php | 225 --- lib/simpletest/testexternallib.php | 80 - lib/simpletest/testfilelib.php | 91 - lib/simpletest/testfilterconfig.php | 830 -------- lib/simpletest/testformslib.php | 223 --- lib/simpletest/testgradelib.php | 46 - lib/simpletest/testhtml2text.php | 147 -- lib/simpletest/testhtmlpurifier.php | 255 --- lib/simpletest/testhtmlwriter.php | 97 - lib/simpletest/testmathslib.php | 221 --- lib/simpletest/testmoodlelib.php | 1798 ------------------ lib/simpletest/testnavigationlib.php | 513 ----- lib/simpletest/testoutputcomponents.php | 234 --- lib/simpletest/testoutputlib.php | 179 -- lib/simpletest/testquestionlib.php | 62 - lib/simpletest/testrepositorylib.php | 68 - lib/simpletest/testrss.php | 130 -- lib/simpletest/testtextlib.php | 422 ---- lib/simpletest/testweblib.php | 169 -- 32 files changed, 10802 deletions(-) delete mode 100644 lib/simpletest/broken_testfilelib.php delete mode 100644 lib/simpletest/fixtures/events.php delete mode 100644 lib/simpletest/fixtures/gradetest.php delete mode 100644 lib/simpletest/fixtures/user_agents.php delete mode 100644 lib/simpletest/fulltestaccesslib.php delete mode 100644 lib/simpletest/testbackuplib.php delete mode 100644 lib/simpletest/testblocklib_blockmanager.php delete mode 100644 lib/simpletest/testcode.php delete mode 100644 lib/simpletest/testcompletionlib.php delete mode 100644 lib/simpletest/testcomponentlib.php delete mode 100644 lib/simpletest/testconditionlib.php delete mode 100644 lib/simpletest/testcsslib.php delete mode 100644 lib/simpletest/testdeprecatedlib.php delete mode 100644 lib/simpletest/testeventslib.php delete mode 100644 lib/simpletest/testexternallib.php delete mode 100644 lib/simpletest/testfilelib.php delete mode 100644 lib/simpletest/testfilterconfig.php delete mode 100644 lib/simpletest/testformslib.php delete mode 100644 lib/simpletest/testgradelib.php delete mode 100644 lib/simpletest/testhtml2text.php delete mode 100644 lib/simpletest/testhtmlpurifier.php delete mode 100644 lib/simpletest/testhtmlwriter.php delete mode 100644 lib/simpletest/testmathslib.php delete mode 100644 lib/simpletest/testmoodlelib.php delete mode 100644 lib/simpletest/testnavigationlib.php delete mode 100644 lib/simpletest/testoutputcomponents.php delete mode 100644 lib/simpletest/testoutputlib.php delete mode 100644 lib/simpletest/testquestionlib.php delete mode 100644 lib/simpletest/testrepositorylib.php delete mode 100644 lib/simpletest/testrss.php delete mode 100644 lib/simpletest/testtextlib.php delete mode 100644 lib/simpletest/testweblib.php diff --git a/lib/simpletest/broken_testfilelib.php b/lib/simpletest/broken_testfilelib.php deleted file mode 100644 index 43910027dd4..00000000000 --- a/lib/simpletest/broken_testfilelib.php +++ /dev/null @@ -1,347 +0,0 @@ -libdir.'/filelib.php'); - -require_once($CFG->dirroot.'/user/lib.php'); -require_once($CFG->dirroot.'/mod/forum/lib.php'); - -/** - * Parent class used only for setup() and teardown() methods, to create and cleanup test data - */ -class filelib_test extends UnitTestCaseUsingDatabase { - protected $course; - protected $section; - protected $coursecat; - protected $user; - protected $module; - public static $includecoverage = array('lib/filelib.php'); - - /** - * Setup the DB fixture data - */ - public function setup() { - parent::setUp(); - $tables = array('block_instances', 'cache_flags', 'capabilities', 'context', 'context_temp', - 'course', 'course_modules', 'course_categories', 'course_sections','files', - 'grade_items', 'grade_categories', 'groups', 'groups_members', - 'modules', 'role', 'role_names', 'role_context_levels', 'role_assignments', - 'role_capabilities', 'user'); - $this->create_test_tables($tables, 'lib'); - $this->create_test_table('forum', 'mod/forum'); - $this->switch_to_test_db(); - - global $DB, $CFG; - // Insert needed capabilities - $DB->insert_record('capabilities', - array('id' => 45, 'name' => 'moodle/course:update', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 4)); - $DB->insert_record('capabilities', - array('id' => 14, 'name' => 'moodle/backup:backupcourse', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 28)); - $DB->insert_record('capabilities', - array('id' => 17, 'name' => 'moodle/restore:restorecourse', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 28)); - $DB->insert_record('capabilities', - array('id' => 52, 'name' => 'moodle/course:managefiles', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 4)); - $DB->insert_record('capabilities', - array('id' => 73, 'name' => 'moodle/user:editownprofile', 'cattype' => 'write', 'contextlevel' => 10, 'component' => 'moodle', 'riskbitmask' => 16)); - - // Insert system context - $DB->insert_record('context', array('id' => 1, 'contextlevel' => 10, 'instanceid' => 0, 'path' => '/1', 'depth' => 1)); - $DB->insert_record('context', array('id' => 2, 'contextlevel' => 50, 'instanceid' => 1, 'path' => '/1/2', 'depth' => 2)); - - // Insert site course - $DB->insert_record('course', array('category' => 0, 'sortorder' => 1, 'fullname' => 'Test site', 'shortname' => 'test', 'format' => 'site', 'modinfo' => 'a:0:{}')); - - // User and capability stuff (stolen from testaccesslib.php) - $syscontext = get_system_context(false); - - /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles - update_capabilities('moodle'); - update_capabilities('mod_forum'); - - $contexts = $this->load_test_data('context', - array('contextlevel', 'instanceid', 'path', 'depth'), array( - 1 => array(40, 666, '', 2))); - $contexts[0] = $syscontext; - $contexts[1]->path = $contexts[0]->path . '/' . $contexts[1]->id; - $this->testdb->set_field('context', 'path', $contexts[1]->path, array('id' => $contexts[1]->id)); - $users = $this->load_test_data('user', - array('username', 'confirmed', 'deleted'), array( - 'a' => array('a', 1, 0))); - $admin = $this->testdb->get_record('role', array('shortname' => 'admin')); - $ras = $this->load_test_data('role_assignments', array('userid', 'roleid', 'contextid'), array( 'a' => array($users['a']->id, $admin->id, $contexts[0]->id))); - - $this->switch_global_user_id(1); - accesslib_clear_all_caches_for_unit_testing(); - - // Create a coursecat - $newcategory = new stdClass(); - $newcategory->name = 'test category'; - $newcategory->sortorder = 999; - $newcategory->id = $DB->insert_record('course_categories', $newcategory); - - $newcategory->context = get_context_instance(CONTEXT_COURSECAT, $newcategory->id); - mark_context_dirty($newcategory->context->path); - fix_course_sortorder(); // Required to build course_categories.depth and .path. - $this->coursecat = $DB->get_record('course_categories', array('id' => $newcategory->id)); - - // Create a course - $coursedata = new stdClass(); - $coursedata->category = $newcategory->id; - $coursedata->shortname = 'testcourse'; - $coursedata->fullname = 'Test Course'; - - try { - $this->course = create_course($coursedata); - } catch (moodle_exception $e) { - // Most likely the result of an aborted unit test: the test course was not correctly deleted - $this->course = $DB->get_record('course', array('shortname' => $coursedata->shortname)); - } - - // Create a user - $this->user = new stdClass(); - $this->user->username = 'testuser09987654321'; - $this->user->password = 'password'; - $this->user->firstname = 'TestUser'; - $this->user->lastname = 'TestUser'; - $this->user->email = 'fakeemail@fake.org'; - $this->user->id = create_user($this->user); - - // Assign user to course - // role_assign(5, $this->user->id, get_context_instance(CONTEXT_COURSE, $this->course->id)->id); - - // Create a module - $module = new stdClass(); - $module->intro = 'Forum used for testing filelib API'; - $module->type = 'general'; - $module->forcesubscribe = 1; - $module->format = 1; - $module->name = 'Test Forum'; - $module->module = $DB->get_field('modules', 'id', array('name' => 'forum')); - $module->modulename = 'forum'; - $module->add = 'forum'; - $module->cmidnumber = ''; - $module->course = $this->course->id; - - $module->instance = forum_add_instance($module, ''); - - $this->section = get_course_section(1, $this->course->id); - $module->section = $this->section->id; - $module->coursemodule = add_course_module($module); - - add_mod_to_section($module); - - $module->cmidnumber = set_coursemodule_idnumber($module->coursemodule, ''); - - rebuild_course_cache($this->course->id); - $this->module= $DB->get_record('forum', array('id' => $module->instance)); - $this->module->instance = $module->instance; - - // Update local copy of course - $this->course = $DB->get_record('course', array('id' => $this->course->id)); - } - - public function teardown() { - parent::tearDown(); - } - - public function createFiles() { - - } -} - -/** - * Tests for file_browser class - */ - -class file_browser_test extends filelib_test { - - public function test_encodepath() { - global $CFG; - $fb = new file_browser(); - - $CFG->slasharguments = true; - $this->assertEqual('http://test.url.com/path/to/page.php', file_encode_url('http://test.url.com', '/path/to/page.php')); - $this->assertEqual('http://test.url.com/path/to/page.php?forcedownload=1', file_encode_url('http://test.url.com', '/path/to/page.php', true)); - $this->assertEqual('https://test.url.com/path/to/page.php?forcedownload=1', file_encode_url('http://test.url.com', '/path/to/page.php', true, true)); - - // TODO add error checking for malformed path (does method support get variables?) - $this->assertEqual('http://test.url.com/path/to/page.php?var1=value1&var2=value2', file_encode_url('http://test.url.com', '/path/to/page.php?var1=value1&var2=value2')); - $this->assertEqual('http://test.url.com/path/to/page.php?var1=value1&var2=value2&forcedownload=1', file_encode_url('http://test.url.com', '/path/to/page.php?var1=value1&var2=value2', true)); - - $CFG->slasharguments = false; - $this->assertEqual('http://test.url.com?file=%2Fpath%2Fto%2Fpage.php', file_encode_url('http://test.url.com', '/path/to/page.php')); - $this->assertEqual('http://test.url.com?file=%2Fpath%2Fto%2Fpage.php&forcedownload=1', file_encode_url('http://test.url.com', '/path/to/page.php', true)); - $this->assertEqual('https://test.url.com?file=%2Fpath%2Fto%2Fpage.php&forcedownload=1', file_encode_url('http://test.url.com', '/path/to/page.php', true, true)); - } -} - -class test_file_info_context_system extends filelib_test { - public function test_get_children() { - $context = get_context_instance(CONTEXT_SYSTEM); - - $fis = new file_info_context_system(new file_browser(), $context); - $children = $fis->get_children(); - - $found_coursecat = false; - $context_coursecat = get_context_instance(CONTEXT_COURSECAT, $this->coursecat->id); - $file_info_context_coursecat = new file_info_context_coursecat(new file_browser(), $context_coursecat, $this->coursecat); - - foreach ($children as $child) { - if ($child == $file_info_context_coursecat) { - $found_coursecat = true; - } - } - $this->assertTrue($found_coursecat); - } -} - -class test_file_info_context_coursecat extends filelib_test { - private $fileinfo; - - public function setup() { - parent::setup(); - $context = get_context_instance(CONTEXT_COURSECAT, $this->coursecat->id); - $this->fileinfo = new file_info_context_coursecat(new file_browser(), $context, $this->coursecat); - } - - public function test_get_children() { - $children = $this->fileinfo->get_children(); - $this->assertEqual(2, count($children)); - - // Not sure but I think there should be two children: a file_info_stored object and a file_info_course object. - $this->assertEqual('Category introduction', $children[0]->get_visible_name()); - $this->assertEqual('', $children[0]->get_url()); - $this->assertEqual('file_info_stored', get_class($children[0])); - - $context_course = get_context_instance(CONTEXT_COURSE, $this->course->id); - $fic = new file_info_context_course(new file_browser(), $context_course, $this->course); - $this->assertEqual($fic, $children[1]); - } - - public function test_get_parent() { - $context = get_context_instance(CONTEXT_SYSTEM); - $fis = new file_info_context_system(new file_browser(), $context); - $parent = $this->fileinfo->get_parent(); - $this->assertEqual($parent, $fis); - } -} - -class test_file_info_context_course extends filelib_test { - private $fileinfo; - - public function setup() { - parent::setup(); - $context = get_context_instance(CONTEXT_COURSE, $this->course->id); - $this->fileinfo = new file_info_context_course(new file_browser(), $context, $this->course); - } - - public function test_get_children() { - global $DB; - - $children = $this->fileinfo->get_children(); - $this->assertEqual(4, count($children)); - - $this->assertEqual('Course introduction', $children[0]->get_visible_name()); - $this->assertEqual('', $children[0]->get_url()); - $this->assertEqual('file_info_stored', get_class($children[0])); - - $context_course = get_context_instance(CONTEXT_COURSE, $this->course->id); - $fics = new file_info_area_course_section(new file_browser(), $context_course, $this->course); - $this->assertEqual($fics, $children[1]); - - $this->assertEqual('Backups', $children[2]->get_visible_name()); - $this->assertEqual('', $children[2]->get_url()); - $this->assertEqual('file_info_stored', get_class($children[2])); - - $this->assertEqual('Course files', $children[3]->get_visible_name()); - $this->assertEqual('', $children[3]->get_url()); - $this->assertEqual('file_info_area_course_legacy', get_class($children[3])); - - } - - public function test_get_parent() { - $context = get_context_instance(CONTEXT_COURSECAT, $this->coursecat->id); - $fic = new file_info_context_coursecat(new file_browser(), $context, $this->coursecat); - $parent = $this->fileinfo->get_parent(); - $this->assertEqual($parent, $fic); - } -} - -class test_file_info_context_user extends filelib_test { - private $fileinfo; - - public function setup() { - parent::setup(); - $context = get_context_instance(CONTEXT_USER, $this->user->id); - $this->fileinfo = new file_info_context_user(new file_browser(), $context, $this->user); - } - - public function test_get_parent() { - $context = get_context_instance(CONTEXT_SYSTEM); - $fic = new file_info_context_system(new file_browser(), $context); - $parent = $this->fileinfo->get_parent(); - $this->assertEqual($parent, $fic); - } - - public function test_get_children() { - $children = $this->fileinfo->get_children(); - $this->assertEqual(2, count($children)); - - $this->assertEqual('Personal', $children[0]->get_visible_name()); - $this->assertEqual('', $children[0]->get_url()); - $this->assertEqual('file_info_stored', get_class($children[0])); - - $this->assertEqual('Profile', $children[1]->get_visible_name()); - $this->assertEqual('', $children[1]->get_url()); - $this->assertEqual('file_info_stored', get_class($children[1])); - } -} - -class test_file_info_context_module extends filelib_test { - private $fileinfo; - - public function setup() { - global $DB; - parent::setup(); - $context = get_context_instance(CONTEXT_MODULE, $DB->get_field('course_modules', 'id', array('instance' => $this->module->instance))); - $this->fileinfo = new file_info_context_module(new file_browser(), $this->course, $this->module->instance, $context, array()); - } - - public function test_get_parent() { - $context = get_context_instance(CONTEXT_COURSE, $this->course->id); - $fic = new file_info_context_course(new file_browser(), $context, $this->course); - $parent = $this->fileinfo->get_parent(); - $this->assertEqual($parent, $fic); - } - - public function test_get_children() { - $children = $this->fileinfo->get_children(); - $this->assertEqual(0, count($children)); - } -} diff --git a/lib/simpletest/fixtures/events.php b/lib/simpletest/fixtures/events.php deleted file mode 100644 index b305451e673..00000000000 --- a/lib/simpletest/fixtures/events.php +++ /dev/null @@ -1,44 +0,0 @@ -. - -/** - * Test event handler definition used only from unit tests. - * - * @package core - * @subpackage event - * @copyright 2007 onwards Martin Dougiamas (http://dougiamas.com) - * @author Petr Skoda {@link http://skodak.org} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -$handlers = array ( - 'test_instant' => array ( - 'handlerfile' => '/lib/simpletest/testeventslib.php', - 'handlerfunction' => 'sample_function_handler', - 'schedule' => 'instant', - 'internal' => 1, - ), - - 'test_cron' => array ( - 'handlerfile' => '/lib/simpletest/testeventslib.php', - 'handlerfunction' => array('sample_handler_class', 'static_method'), - 'schedule' => 'cron', - 'internal' => 1, - ) -); - - diff --git a/lib/simpletest/fixtures/gradetest.php b/lib/simpletest/fixtures/gradetest.php deleted file mode 100644 index 2bea87e8808..00000000000 --- a/lib/simpletest/fixtures/gradetest.php +++ /dev/null @@ -1,878 +0,0 @@ -. - -/** - * @package moodlecore - * @copyright nicolas@moodle.com - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -if (!defined('MOODLE_INTERNAL')) { - die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page -} - -require_once($CFG->libdir . '/adminlib.php'); -require_once($CFG->libdir . '/gradelib.php'); - -/** - * Shared code for all grade related tests. - * - * Here is a brief explanation of the test data set up in these unit tests. - * category1 => array(category2 => array(grade_item1, grade_item2), category3 => array(grade_item3)) - * 3 users for 3 grade_items - */ -class grade_test extends UnitTestCaseUsingDatabase { - - public $grade_tables = array('lib' => array( - 'grade_categories', 'grade_categories_history', - 'scale', 'scale_history', - 'grade_items', 'grade_items_history', - 'grade_grades', 'grade_grades_history', - 'grade_outcomes', 'grade_outcomes_history','grade_outcomes_courses', - 'files', - 'modules', - 'course_modules'), - 'mod/quiz' => array('quiz') - ); - - public $grade_items = array(); - public $grade_categories = array(); - public $grade_grades = array(); - public $grade_outcomes = array(); - public $scale = array(); - - public $activities = array(); - public $courseid = 1; - public $userid = 1; - - /** - * Create temporary test tables and entries in the database for these tests. - * These tests have to work on a brand new site. - */ - function setUp() { - global $CFG; - - parent::setup(); - $CFG->grade_droplow = -1; - $CFG->grade_keephigh = -1; - $CFG->grade_aggregation = -1; - $CFG->grade_aggregateonlygraded = -1; - $CFG->grade_aggregateoutcomes = -1; - $CFG->grade_aggregatesubcats = -1; - - $this->switch_to_test_db(); // All operations until end of test method will happen in test DB - - foreach ($this->grade_tables as $dir => $tables) { - $this->create_test_tables($tables, $dir); // Create tables - foreach ($tables as $table) { // Fill them if load_xxx method is available - $function = "load_$table"; - if (method_exists($this, $function)) { - $this->$function(); - } - } - } - - } - - function tearDown() { - parent::tearDown(); // All the test tables created in setUp will be dropped by this - } - - /** - * Load scale data into the database, and adds the corresponding objects to this class' variable. - */ - function load_scale() { - global $DB; - $scale = new stdClass(); - - $scale->name = 'unittestscale1'; - $scale->courseid = $this->courseid; - $scale->userid = $this->userid; - $scale->scale = 'Way off topic, Not very helpful, Fairly neutral, Fairly helpful, Supportive, Some good information, Perfect answer!'; - $scale->description = 'This scale defines some of qualities that make posts helpful within the Moodle help forums.\n Your feedback will help others see how their posts are being received.'; - $scale->timemodified = time(); - - $scale->id = $DB->insert_record('scale', $scale); - $this->scale[0] = $scale; - $temp = explode(',', $scale->scale); - $this->scalemax[0] = count($temp) -1; - - $scale = new stdClass(); - - $scale->name = 'unittestscale2'; - $scale->courseid = $this->courseid; - $scale->userid = $this->userid; - $scale->scale = 'Distinction, Very Good, Good, Pass, Fail'; - $scale->description = 'This scale is used to mark standard assignments.'; - $scale->timemodified = time(); - - $scale->id = $DB->insert_record('scale', $scale); - $this->scale[1] = $scale; - $temp = explode(',', $scale->scale); - $this->scalemax[1] = count($temp) -1; - - $scale = new stdClass(); - - $scale->name = 'unittestscale3'; - $scale->courseid = $this->courseid; - $scale->userid = $this->userid; - $scale->scale = 'Loner, Contentious, Disinterested, Participative, Follower, Leader'; - $scale->description = 'Describes the level of teamwork of a student.'; - $scale->timemodified = time(); - $temp = explode(',', $scale->scale); - $scale->max = count($temp) -1; - - $scale->id = $DB->insert_record('scale', $scale); - $this->scale[2] = $scale; - $temp = explode(',', $scale->scale); - $this->scalemax[2] = count($temp) -1; - - $scale->name = 'unittestscale4'; - $scale->courseid = $this->courseid; - $scale->userid = $this->userid; - $scale->scale = 'Does not understand theory, Understands theory but fails practice, Manages through, Excels'; - $scale->description = 'Level of expertise at a technical task, with a theoretical framework.'; - $scale->timemodified = time(); - $temp = explode(',', $scale->scale); - $scale->max = count($temp) -1; - - $scale->id = $DB->insert_record('scale', $scale); - $this->scale[3] = $scale; - $temp = explode(',', $scale->scale); - $this->scalemax[3] = count($temp) -1; - - $scale->name = 'unittestscale5'; - $scale->courseid = $this->courseid; - $scale->userid = $this->userid; - $scale->scale = 'Insufficient, Acceptable, Excellent.'; - $scale->description = 'Description of skills.'; - $scale->timemodified = time(); - $temp = explode(',', $scale->scale); - $scale->max = count($temp) -1; - - $scale->id = $DB->insert_record('scale', $scale); - $this->scale[4] = $scale; - $temp = explode(',', $scale->scale); - $this->scalemax[4] = count($temp) -1; - } - - /** - * Load grade_category data into the database, and adds the corresponding objects to this class' variable. - * category structure: - course category - | - +--------+-------------+ - | | - unittestcategory1 level1category - | - +--------+-------------+ - | | - unittestcategory2 unittestcategory3 - */ - function load_grade_categories() { - global $DB; - - $course_category = grade_category::fetch_course_category($this->courseid); - - $grade_category = new stdClass(); - - $grade_category->fullname = 'unittestcategory1'; - $grade_category->courseid = $this->courseid; - $grade_category->aggregation = GRADE_AGGREGATE_MEAN; - $grade_category->aggregateonlygraded = 1; - $grade_category->keephigh = 0; - $grade_category->droplow = 0; - $grade_category->parent = $course_category->id; - $grade_category->timecreated = time(); - $grade_category->timemodified = time(); - $grade_category->depth = 2; - - $grade_category->id = $DB->insert_record('grade_categories', $grade_category); - $grade_category->path = '/'.$course_category->id.'/'.$grade_category->id.'/'; - $DB->update_record('grade_categories', $grade_category); - $this->grade_categories[0] = $grade_category; - - $grade_category = new stdClass(); - - $grade_category->fullname = 'unittestcategory2'; - $grade_category->courseid = $this->courseid; - $grade_category->aggregation = GRADE_AGGREGATE_MEAN; - $grade_category->aggregateonlygraded = 1; - $grade_category->keephigh = 0; - $grade_category->droplow = 0; - $grade_category->parent = $this->grade_categories[0]->id; - $grade_category->timecreated = time(); - $grade_category->timemodified = time(); - $grade_category->depth = 3; - - $grade_category->id = $DB->insert_record('grade_categories', $grade_category); - $grade_category->path = $this->grade_categories[0]->path.$grade_category->id.'/'; - $DB->update_record('grade_categories', $grade_category); - $this->grade_categories[1] = $grade_category; - - $grade_category = new stdClass(); - - $grade_category->fullname = 'unittestcategory3'; - $grade_category->courseid = $this->courseid; - $grade_category->aggregation = GRADE_AGGREGATE_MEAN; - $grade_category->aggregateonlygraded = 1; - $grade_category->keephigh = 0; - $grade_category->droplow = 0; - $grade_category->parent = $this->grade_categories[0]->id; - $grade_category->timecreated = time(); - $grade_category->timemodified = time(); - $grade_category->depth = 3; - - $grade_category->id = $DB->insert_record('grade_categories', $grade_category); - $grade_category->path = $this->grade_categories[0]->path.$grade_category->id.'/'; - $DB->update_record('grade_categories', $grade_category); - $this->grade_categories[2] = $grade_category; - - // A category with no parent, but grade_items as children - - $grade_category = new stdClass(); - - $grade_category->fullname = 'level1category'; - $grade_category->courseid = $this->courseid; - $grade_category->aggregation = GRADE_AGGREGATE_MEAN; - $grade_category->aggregateonlygraded = 1; - $grade_category->keephigh = 0; - $grade_category->droplow = 0; - $grade_category->parent = $course_category->id; - $grade_category->timecreated = time(); - $grade_category->timemodified = time(); - $grade_category->depth = 2; - - $grade_category->id = $DB->insert_record('grade_categories', $grade_category); - $grade_category->path = '/'.$course_category->id.'/'.$grade_category->id.'/'; - $DB->update_record('grade_categories', $grade_category); - $this->grade_categories[3] = $grade_category; - } - - /** - * Load module entries in modules table - */ - function load_modules() { - global $DB; - $module = new stdClass(); - $module->name = 'assignment'; - $module->id = $DB->insert_record('modules', $module); - $this->modules[0] = $module; - - $module = new stdClass(); - $module->name = 'quiz'; - $module->id = $DB->insert_record('modules', $module); - $this->modules[1] = $module; - - $module = new stdClass(); - $module->name = 'forum'; - $module->id = $DB->insert_record('modules', $module); - $this->modules[2] = $module; - } - - /** - * Load module instance entries in course_modules table - */ - function load_course_modules() { - global $DB; - $course_module = new stdClass(); - $course_module->course = $this->courseid; - $quiz = new stdClass(); - $quiz->module = 1; - $quiz->instance = 2; - $course_module->id = $DB->insert_record('course_modules', $course_module); - $this->course_module[0] = $course_module; - - $course_module = new stdClass(); - $course_module->course = $this->courseid; - $quiz->module = 2; - $quiz->instance = 1; - $course_module->id = $DB->insert_record('course_modules', $course_module); - $this->course_module[0] = $course_module; - - $course_module = new stdClass(); - $course_module->course = $this->courseid; - $quiz->module = 2; - $quiz->instance = 5; - $course_module->id = $DB->insert_record('course_modules', $course_module); - $this->course_module[0] = $course_module; - - $course_module = new stdClass(); - $course_module->course = $this->courseid; - $quiz->module = 3; - $quiz->instance = 3; - $course_module->id = $DB->insert_record('course_modules', $course_module); - $this->course_module[0] = $course_module; - - $course_module = new stdClass(); - $course_module->course = $this->courseid; - $quiz->module = 3; - $quiz->instance = 7; - $course_module->id = $DB->insert_record('course_modules', $course_module); - $this->course_module[0] = $course_module; - - $course_module = new stdClass(); - $course_module->course = $this->courseid; - $quiz->module = 3; - $quiz->instance = 9; - $course_module->id = $DB->insert_record('course_modules', $course_module); - $this->course_module[0] = $course_module; - } - - /** - * Load test quiz data into the database - */ - function load_quiz_activities() { - global $DB; - $quiz = new stdClass(); - $quiz->course = $this->courseid; - $quiz->name = 'test quiz'; - $quiz->intro = 'let us quiz you!'; - $quiz->questions = '1,2'; - $quiz->id = $DB->insert_record('quiz', $quiz); - $this->activities[0] = $quiz; - - $quiz = new stdClass(); - $quiz->course = $this->courseid; - $quiz->name = 'test quiz 2'; - $quiz->intro = 'let us quiz you again!'; - $quiz->questions = '1,3'; - $quiz->id = $DB->insert_record('quiz', $quiz); - $this->activities[1] = $quiz; - } - - /** - * Load grade_item data into the database, and adds the corresponding objects to this class' variable. - */ - function load_grade_items() { - global $DB; - - $course_category = grade_category::fetch_course_category($this->courseid); - - // id = 0 - $grade_item = new stdClass(); - - $grade_item->courseid = $this->courseid; - $grade_item->categoryid = $this->grade_categories[1]->id; - $grade_item->itemname = 'unittestgradeitem1'; - $grade_item->itemtype = 'mod'; - $grade_item->itemmodule = 'quiz'; - $grade_item->iteminstance = 1; - $grade_item->gradetype = GRADE_TYPE_VALUE; - $grade_item->grademin = 30; - $grade_item->grademax = 110; - $grade_item->itemnumber = 1; - $grade_item->idnumber = 'item id 0'; - $grade_item->iteminfo = 'Grade item 0 used for unit testing'; - $grade_item->timecreated = time(); - $grade_item->timemodified = time(); - $grade_item->sortorder = 3; - - $grade_item->id = $DB->insert_record('grade_items', $grade_item); - $this->grade_items[0] = $grade_item; - - // id = 1 - $grade_item = new stdClass(); - - $grade_item->courseid = $this->courseid; - $grade_item->categoryid = $this->grade_categories[1]->id; - $grade_item->itemname = 'unittestgradeitem2'; - $grade_item->itemtype = 'import'; - $grade_item->itemmodule = 'assignment'; - $grade_item->calculation = '= ##gi'.$this->grade_items[0]->id.'## + 30 + [[item id 0]] - [[item id 0]]'; - $grade_item->gradetype = GRADE_TYPE_VALUE; - $grade_item->iteminstance = 2; - $grade_item->itemnumber = null; - $grade_item->grademin = 0; - $grade_item->grademax = 100; - $grade_item->iteminfo = 'Grade item 1 used for unit testing'; - $grade_item->timecreated = time(); - $grade_item->timemodified = time(); - $grade_item->sortorder = 4; - - $grade_item->id = $DB->insert_record('grade_items', $grade_item); - $this->grade_items[1] = $grade_item; - - // id = 2 - $grade_item = new stdClass(); - - $grade_item->courseid = $this->courseid; - $grade_item->categoryid = $this->grade_categories[2]->id; - $grade_item->itemname = 'unittestgradeitem3'; - $grade_item->itemtype = 'mod'; - $grade_item->itemmodule = 'forum'; - $grade_item->iteminstance = 3; - $grade_item->gradetype = GRADE_TYPE_SCALE; - $grade_item->scaleid = $this->scale[0]->id; - $grade_item->grademin = 0; - $grade_item->grademax = $this->scalemax[0]; - $grade_item->iteminfo = 'Grade item 2 used for unit testing'; - $grade_item->timecreated = time(); - $grade_item->timemodified = time(); - $grade_item->sortorder = 6; - - $grade_item->id = $DB->insert_record('grade_items', $grade_item); - $this->grade_items[2] = $grade_item; - - // Load grade_items associated with the 3 categories - // id = 3 - $grade_item = new stdClass(); - - $grade_item->courseid = $this->courseid; - $grade_item->iteminstance = $this->grade_categories[0]->id; - $grade_item->itemname = 'unittestgradeitemcategory1'; - $grade_item->needsupdate = 0; - $grade_item->itemtype = 'category'; - $grade_item->gradetype = GRADE_TYPE_VALUE; - $grade_item->grademin = 0; - $grade_item->grademax = 100; - $grade_item->iteminfo = 'Grade item 3 used for unit testing'; - $grade_item->timecreated = time(); - $grade_item->timemodified = time(); - $grade_item->sortorder = 1; - - $grade_item->id = $DB->insert_record('grade_items', $grade_item); - $this->grade_items[3] = $grade_item; - - // id = 4 - $grade_item = new stdClass(); - - $grade_item->courseid = $this->courseid; - $grade_item->iteminstance = $this->grade_categories[1]->id; - $grade_item->itemname = 'unittestgradeitemcategory2'; - $grade_item->itemtype = 'category'; - $grade_item->gradetype = GRADE_TYPE_VALUE; - $grade_item->needsupdate = 0; - $grade_item->grademin = 0; - $grade_item->grademax = 100; - $grade_item->iteminfo = 'Grade item 4 used for unit testing'; - $grade_item->timecreated = time(); - $grade_item->timemodified = time(); - $grade_item->sortorder = 2; - - $grade_item->id = $DB->insert_record('grade_items', $grade_item); - $this->grade_items[4] = $grade_item; - - // id = 5 - $grade_item = new stdClass(); - - $grade_item->courseid = $this->courseid; - $grade_item->iteminstance = $this->grade_categories[2]->id; - $grade_item->itemname = 'unittestgradeitemcategory3'; - $grade_item->itemtype = 'category'; - $grade_item->gradetype = GRADE_TYPE_VALUE; - $grade_item->needsupdate = true; - $grade_item->grademin = 0; - $grade_item->grademax = 100; - $grade_item->iteminfo = 'Grade item 5 used for unit testing'; - $grade_item->timecreated = time(); - $grade_item->timemodified = time(); - $grade_item->sortorder = 5; - - $grade_item->id = $DB->insert_record('grade_items', $grade_item); - $this->grade_items[5] = $grade_item; - - // Orphan grade_item - // id = 6 - $grade_item = new stdClass(); - - $grade_item->courseid = $this->courseid; - $grade_item->categoryid = $course_category->id; - $grade_item->itemname = 'unittestorphangradeitem1'; - $grade_item->itemtype = 'mod'; - $grade_item->itemmodule = 'quiz'; - $grade_item->iteminstance = 5; - $grade_item->itemnumber = 0; - $grade_item->gradetype = GRADE_TYPE_VALUE; - $grade_item->grademin = 10; - $grade_item->grademax = 120; - $grade_item->locked = time(); - $grade_item->iteminfo = 'Orphan Grade 6 item used for unit testing'; - $grade_item->timecreated = time(); - $grade_item->timemodified = time(); - $grade_item->sortorder = 7; - - $grade_item->id = $DB->insert_record('grade_items', $grade_item); - $this->grade_items[6] = $grade_item; - - // 2 grade items under level1category - // id = 7 - $grade_item = new stdClass(); - - $grade_item->courseid = $this->courseid; - $grade_item->categoryid = $this->grade_categories[3]->id; - $grade_item->itemname = 'singleparentitem1'; - $grade_item->itemtype = 'mod'; - $grade_item->itemmodule = 'forum'; - $grade_item->iteminstance = 7; - $grade_item->gradetype = GRADE_TYPE_SCALE; - $grade_item->scaleid = $this->scale[0]->id; - $grade_item->grademin = 0; - $grade_item->grademax = $this->scalemax[0]; - $grade_item->iteminfo = 'Grade item 7 used for unit testing'; - $grade_item->timecreated = time(); - $grade_item->timemodified = time(); - $grade_item->sortorder = 9; - - $grade_item->id = $DB->insert_record('grade_items', $grade_item); - $this->grade_items[7] = $grade_item; - - // id = 8 - $grade_item = new stdClass(); - - $grade_item->courseid = $this->courseid; - $grade_item->categoryid = $this->grade_categories[3]->id; - $grade_item->itemname = 'singleparentitem2'; - $grade_item->itemtype = 'mod'; - $grade_item->itemmodule = 'forum'; - $grade_item->iteminstance = 9; - $grade_item->gradetype = GRADE_TYPE_VALUE; - $grade_item->grademin = 0; - $grade_item->grademax = 100; - $grade_item->iteminfo = 'Grade item 8 used for unit testing'; - $grade_item->timecreated = time(); - $grade_item->timemodified = time(); - $grade_item->sortorder = 10; - - $grade_item->id = $DB->insert_record('grade_items', $grade_item); - $this->grade_items[8] = $grade_item; - - // Grade_item for level1category - // id = 9 - $grade_item = new stdClass(); - - $grade_item->courseid = $this->courseid; - $grade_item->itemname = 'grade_item for level1 category'; - $grade_item->itemtype = 'category'; - $grade_item->itemmodule = 'quiz'; - $grade_item->iteminstance = $this->grade_categories[3]->id; - $grade_item->needsupdate = true; - $grade_item->gradetype = GRADE_TYPE_VALUE; - $grade_item->grademin = 0; - $grade_item->grademax = 100; - $grade_item->iteminfo = 'Orphan Grade item 9 used for unit testing'; - $grade_item->timecreated = time(); - $grade_item->timemodified = time(); - $grade_item->sortorder = 8; - - $grade_item->id = $DB->insert_record('grade_items', $grade_item); - $this->grade_items[9] = $grade_item; - - // Manual grade_item - // id = 10 - $grade_item = new stdClass(); - - $grade_item->courseid = $this->courseid; - $grade_item->categoryid = $course_category->id; - $grade_item->itemname = 'manual grade_item'; - $grade_item->itemtype = 'manual'; - $grade_item->itemnumber = 0; - $grade_item->needsupdate = false; - $grade_item->gradetype = GRADE_TYPE_VALUE; - $grade_item->grademin = 0; - $grade_item->grademax = 100; - $grade_item->iteminfo = 'Manual grade item 10 used for unit testing'; - $grade_item->timecreated = time(); - $grade_item->timemodified = time(); - - $grade_item->id = $DB->insert_record('grade_items', $grade_item); - $this->grade_items[10] = $grade_item; - } - - /** - * Load grade_grades data into the database, and adds the corresponding objects to this class' variable. - */ - function load_grade_grades() { - global $DB; - - //this method is called once for each test method. Avoid adding things to $this->grade_grades multiple times - $this->grade_grades = array(); - - // Grades for grade_item 1 - $grade = new stdClass(); - $grade->itemid = $this->grade_items[0]->id; - $grade->userid = 1; - $grade->rawgrade = 15; // too small - $grade->finalgrade = 30; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '1 of 17 grade_grades'; - $grade->informationformat = FORMAT_PLAIN; - $grade->feedback = 'Good, but not good enough..'; - $grade->feedbackformat = FORMAT_PLAIN; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[0] = $grade; - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[0]->id; - $grade->userid = 2; - $grade->rawgrade = 40; - $grade->finalgrade = 40; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '2 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[1] = $grade; - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[0]->id; - $grade->userid = 3; - $grade->rawgrade = 170; // too big - $grade->finalgrade = 110; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '3 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[2] = $grade; - - - // No raw grades for grade_item 2 - it is calculated - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[1]->id; - $grade->userid = 1; - $grade->finalgrade = 72; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '4 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[3] = $grade; - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[1]->id; - $grade->userid = 2; - $grade->finalgrade = 92; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '5 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[4] = $grade; - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[1]->id; - $grade->userid = 3; - $grade->finalgrade = 100; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '6 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[5] = $grade; - - - // Grades for grade_item 3 - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[2]->id; - $grade->userid = 1; - $grade->rawgrade = 2; - $grade->finalgrade = 6; - $grade->scaleid = $this->scale[3]->id; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '7 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[6] = $grade; - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[2]->id; - $grade->userid = 2; - $grade->rawgrade = 3; - $grade->finalgrade = 2; - $grade->scaleid = $this->scale[3]->id; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '8 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[] = $grade; - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[2]->id; - $grade->userid = 3; - $grade->rawgrade = 1; - $grade->finalgrade = 3; - $grade->scaleid = $this->scale[3]->id; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '9 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[] = $grade; - - // Grades for grade_item 7 - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[6]->id; - $grade->userid = 1; - $grade->rawgrade = 97; - $grade->finalgrade = 69; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '10 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[] = $grade; - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[6]->id; - $grade->userid = 2; - $grade->rawgrade = 49; - $grade->finalgrade = 87; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '11 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[] = $grade; - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[6]->id; - $grade->userid = 3; - $grade->rawgrade = 67; - $grade->finalgrade = 94; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '12 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[] = $grade; - - // Grades for grade_item 8 - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[7]->id; - $grade->userid = 2; - $grade->rawgrade = 3; - $grade->finalgrade = 3; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '13 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[] = $grade; - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[7]->id; - $grade->userid = 3; - $grade->rawgrade = 6; - $grade->finalgrade = 6; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '14 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[] = $grade; - - // Grades for grade_item 9 - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[8]->id; - $grade->userid = 1; - $grade->rawgrade = 20; - $grade->finalgrade = 20; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '15 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[] = $grade; - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[8]->id; - $grade->userid = 2; - $grade->rawgrade = 50; - $grade->finalgrade = 50; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '16 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[] = $grade; - - $grade = new stdClass(); - $grade->itemid = $this->grade_items[8]->id; - $grade->userid = 3; - $grade->rawgrade = 100; - $grade->finalgrade = 100; - $grade->timecreated = time(); - $grade->timemodified = time(); - $grade->information = '17 of 17 grade_grades'; - - $grade->id = $DB->insert_record('grade_grades', $grade); - $this->grade_grades[] = $grade; - } - - /** - * Load grade_outcome data into the database, and adds the corresponding objects to this class' variable. - */ - function load_grade_outcomes() { - global $DB; - - //this method is called once for each test method. Avoid adding things to $this->grade_outcomes multiple times - $this->grade_outcomes = array(); - - // Calculation for grade_item 1 - $grade_outcome = new stdClass(); - $grade_outcome->fullname = 'Team work'; - $grade_outcome->shortname = 'Team work'; - $grade_outcome->fullname = 'Team work outcome'; - $grade_outcome->timecreated = time(); - $grade_outcome->timemodified = time(); - $grade_outcome->scaleid = $this->scale[2]->id; - - $grade_outcome->id = $DB->insert_record('grade_outcomes', $grade_outcome); - $this->grade_outcomes[] = $grade_outcome; - - // Calculation for grade_item 2 - $grade_outcome = new stdClass(); - $grade_outcome->fullname = 'Complete circuit board'; - $grade_outcome->shortname = 'Complete circuit board'; - $grade_outcome->fullname = 'Complete circuit board'; - $grade_outcome->timecreated = time(); - $grade_outcome->timemodified = time(); - $grade_outcome->scaleid = $this->scale[3]->id; - - $grade_outcome->id = $DB->insert_record('grade_outcomes', $grade_outcome); - $this->grade_outcomes[] = $grade_outcome; - - // Calculation for grade_item 3 - $grade_outcome = new stdClass(); - $grade_outcome->fullname = 'Debug Java program'; - $grade_outcome->shortname = 'Debug Java program'; - $grade_outcome->fullname = 'Debug Java program'; - $grade_outcome->timecreated = time(); - $grade_outcome->timemodified = time(); - $grade_outcome->scaleid = $this->scale[4]->id; - - $grade_outcome->id = $DB->insert_record('grade_outcomes', $grade_outcome); - $this->grade_outcomes[] = $grade_outcome; - } - -/** - * No unit tests here - */ - -} - - diff --git a/lib/simpletest/fixtures/user_agents.php b/lib/simpletest/fixtures/user_agents.php deleted file mode 100644 index 6a4b49c2c96..00000000000 --- a/lib/simpletest/fixtures/user_agents.php +++ /dev/null @@ -1,57 +0,0 @@ - array( - '5.5' => array('Windows 2000' => 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)'), - '6.0' => array('Windows XP SP2' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'), - '7.0' => array('Windows XP SP2' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; YPC 3.0.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)') - ), - 'Firefox' => array( - '1.0.6' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6'), - '1.5' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; nl; rv:1.8) Gecko/20051107 Firefox/1.5'), - '1.5.0.1' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.0.1) Gecko/20060111 Firefox/1.5.0.1'), - '2.0' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1', - 'Ubuntu Linux AMD64' => 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1) Gecko/20060601 Firefox/2.0 (Ubuntu-edgy)') - ), - 'Safari' => array( - '312' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312'), - '2.0' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/412 (KHTML, like Gecko) Safari/412') - ), - 'Opera' => array( - '8.51' => array('Windows XP' => 'Opera/8.51 (Windows NT 5.1; U; en)'), - '9.0' => array('Windows XP' => 'Opera/9.0 (Windows NT 5.1; U; en)', - 'Debian Linux' => 'Opera/9.01 (X11; Linux i686; U; en)') - ) -); - diff --git a/lib/simpletest/fulltestaccesslib.php b/lib/simpletest/fulltestaccesslib.php deleted file mode 100644 index a60788c2152..00000000000 --- a/lib/simpletest/fulltestaccesslib.php +++ /dev/null @@ -1,1172 +0,0 @@ -. - -/** - * Full functional accesslib test - * - * It is implemented as one test case because it would take hours - * to prepare the fake test site for each test, at the same time - * we have to work around multiple problems in UnitTestCaseUsingDatabase. - * - * @package core - * @copyright 2011 Petr Skoda (http://skodak.org) - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -defined('MOODLE_INTERNAL') || die(); - - -/** - * Context caching fixture - */ -class context_inspection extends context_helper { - public static function test_context_cache_size() { - return self::$cache_count; - } -} - - -/** - * Functional test for accesslib.php - * - * Note: execution may take many minutes especially on slower servers. - */ -class accesslib_test extends UnitTestCaseUsingDatabase { - // NOTE: The UnitTestCaseUsingDatabase is problematic and VERY dangerous especially for production servers! - // - // 1. We could create full install without plugins and use the test DB since the very beginning in lib/setup.php. - // 2. We should not execute the tests from the web UI because the static caches all over the place collide, instead - // we could use CLI - // 3. SimpleTest appears to be dead - unfortunately nobody else thinks we should switch to PHPUnit asap - // 4. switching of USER->id alone is not acceptable at all, we must switch the complete USER record - // and probably deal with _SESSION['USER'] too - // 5. we must close session before messing with anything in $USER or $SESSION - // 6. $SITE is not switched - // 7. tons of other static caches are not reset - // 8. etc. - // - // -- - // skodak - - //TODO: add more tests for the remaining accesslib parts that were not touched by the refactoring in 2.2dev - - public static $includecoverage = array('lib/accesslib.php'); - - protected $accesslibprevuser = null; - protected $accesslibprevsite = null; - - /** - * A small functional test of accesslib functions and classes. - */ - public function test_everything_in_accesslib() { - global $USER, $SITE, $CFG, $DB, $ACCESSLIB_PRIVATE; - - // First of all finalize the session, we must not carry over any of this mess to the next page via SESSION!!! - session_get_instance()->write_close(); - - // hack - this is going to take very long time - set_time_limit(3600); - - // Get rid of current user that would not work anyway, - // do NOT even think about using $this->switch_global_user_id()! - if (!isset($this->accesslibprevuser)) { - $this->accesslibprevuser = clone($USER); - $USER = new stdClass(); - $USER->id = 0; - } - - // Backup $SITE global - if (!isset($this->accesslibprevsite)) { - $this->accesslibprevsite = $SITE; - } - - // Switch DB, if it somehow fails or you specified wrong unittest prefix it will nuke real data, you have been warned! - $this->switch_to_test_db(); - - // Let's switch the CFG - $prevcfg = clone($CFG); - $this->switch_to_test_cfg(); - $CFG->config_php_settings = $prevcfg->config_php_settings; - $CFG->noemailever = true; - $CFG->admin = $prevcfg->admin; - $CFG->lang = 'en'; - $CFG->tempdir = $prevcfg->tempdir; - $CFG->cachedir = $prevcfg->cachedir; - $CFG->directorypermissions = $prevcfg->directorypermissions; - $CFG->filepermissions = $prevcfg->filepermissions; - - // Reset all caches - accesslib_clear_all_caches_for_unit_testing(); - - // Add some core tables - this is known to break constantly because we keep adding dependencies... - $tablenames = array('config', 'config_plugins', 'modules', 'course', 'course_modules', 'course_sections', 'course_categories', 'mnet_host', 'mnet_application', - 'capabilities', 'context', 'context_temp', 'role', 'role_capabilities', 'role_allow_switch', 'license', 'my_pages', 'block', 'block_instances', 'block_positions', - 'role_allow_assign', 'role_allow_override', 'role_assignments', 'role_context_levels' ,'enrol', 'user_enrolments', 'filter_active', 'filter_config', 'comments', - 'user', 'groups_members', 'cache_flags', 'events_handlers', 'user_lastaccess', 'rating', 'files', 'role_names', 'user_preferences', 'grading_areas'); - $this->create_test_tables($tablenames, 'lib'); - - // Create all core default records and default settings - require_once("$CFG->libdir/db/install.php"); - xmldb_main_install(); // installs the capabilities too - - // Fake mod_page install - $tablenames = array('page'); - $this->create_test_tables($tablenames, 'mod/page'); - $module = new stdClass(); - require($CFG->dirroot .'/mod/page/version.php'); - $module->name = 'page'; - $pagemoduleid = $DB->insert_record('modules', $module); - update_capabilities('mod_page'); - - // Fake block_online_users install - $plugin = new stdClass(); - $plugin->version = NULL; - $plugin->cron = 0; - include($CFG->dirroot.'/blocks/online_users/version.php'); - $plugin->name = 'online_users'; - $onlineusersblockid = $DB->insert_record('block', $plugin); - update_capabilities('block_online_users'); - - // Finish roles setup - set_config('defaultfrontpageroleid', $DB->get_field('role', 'id', array('archetype'=>'frontpage'))); - set_config('defaultuserroleid', $DB->get_field('role', 'id', array('archetype'=>'user'))); - set_config('notloggedinroleid', $DB->get_field('role', 'id', array('archetype'=>'guest'))); - set_config('rolesactive', 1); - - // Init manual enrol - set_config('status', ENROL_INSTANCE_ENABLED, 'enrol_manual'); - set_config('defaultperiod', 0, 'enrol_manual'); - $manualenrol = enrol_get_plugin('manual'); - - // Fill the site with some real data - $testcategories = array(); - $testcourses = array(); - $testpages = array(); - $testblocks = array(); - $allroles = $DB->get_records_menu('role', array(), 'id', 'archetype, id'); - - $systemcontext = context_system::instance(); - $frontpagecontext = context_course::instance(SITEID); - - // Add block to system context - $bi = new stdClass(); - $bi->blockname = 'online_users'; - $bi->parentcontextid = $systemcontext->id; - $bi->showinsubcontexts = 1; - $bi->pagetypepattern = ''; - $bi->subpagepattern = ''; - $bi->defaultregion = ''; - $bi->defaultweight = 0; - $bi->configdata = ''; - $biid = $DB->insert_record('block_instances', $bi); - context_block::instance($biid); - $testblocks[] = $biid; - - // Some users - $testusers = array(); - for($i=0; $i<20; $i++) { - $user = new stdClass(); - $user->auth = 'manual'; - $user->firstname = 'user'.$i; - $user->lastname = 'user'.$i; - $user->username = 'user'.$i; - $user->password = 'doesnotexist'; - $user->email = "user$i@example.com"; - $user->confirmed = 1; - $user->mnethostid = $CFG->mnet_localhost_id; - $user->lang = $CFG->lang; - $user->maildisplay = 1; - $user->timemodified = time(); - $user->deleted = 0; - $user->lastip = '0.0.0.0'; - $userid = $DB->insert_record('user', $user); - $testusers[$i] = $userid; - $usercontext = context_user::instance($userid); - - // Add block to user profile - $bi->parentcontextid = $usercontext->id; - $biid = $DB->insert_record('block_instances', $bi); - context_block::instance($biid); - $testblocks[] = $biid; - } - // Deleted user - should be ignored everywhere, can not have context - $user = new stdClass(); - $user->auth = 'manual'; - $user->firstname = ''; - $user->lastname = ''; - $user->username = 'user@example.com121132132'; - $user->password = ''; - $user->email = ''; - $user->confirmed = 1; - $user->mnethostid = $CFG->mnet_localhost_id; - $user->lang = $CFG->lang; - $user->maildisplay = 1; - $user->timemodified = time(); - $user->deleted = 1; - $user->lastip = '0.0.0.0'; - $DB->insert_record('user', $user); - unset($user); - - // Add block to frontpage - $bi->parentcontextid = $frontpagecontext->id; - $biid = $DB->insert_record('block_instances', $bi); - $frontpageblockcontext = context_block::instance($biid); - $testblocks[] = $biid; - - // Add a resource to frontpage - $page = new stdClass(); - $page->course = $SITE->id; - $page->intro = '...'; - $page->introformat = FORMAT_HTML; - $page->content = '...'; - $page->contentformat = FORMAT_HTML; - $pageid = $DB->insert_record('page', $page); - $testpages[] = $pageid; - $cm = new stdClass(); - $cm->course = $SITE->id; - $cm->module = $pagemoduleid; - $cm->section = 1; - $cm->instance = $pageid; - $cmid = $DB->insert_record('course_modules', $cm); - $frontpagepagecontext = context_module::instance($cmid); - - // Add block to frontpage resource - $bi->parentcontextid = $frontpagepagecontext->id; - $biid = $DB->insert_record('block_instances', $bi); - $frontpagepageblockcontext = context_block::instance($biid); - $testblocks[] = $biid; - - // Some nested course categories with courses - require_once("$CFG->dirroot/course/lib.php"); - $path = ''; - $parentcat = 0; - for($i=0; $i<5; $i++) { - $cat = new stdClass(); - $cat->name = 'category'.$i; - $cat->parent = $parentcat; - $cat->depth = $i+1; - $cat->sortorder = MAX_COURSES_IN_CATEGORY * ($i+2); - $cat->timemodified = time(); - $catid = $DB->insert_record('course_categories', $cat); - $path = $path . '/' . $catid; - $DB->set_field('course_categories', 'path', $path, array('id'=>$catid)); - $parentcat = $catid; - $testcategories[] = $catid; - $catcontext = context_coursecat::instance($catid); - - if ($i >=4) { - continue; - } - - // Add resource to each category - $bi->parentcontextid = $catcontext->id; - $biid = $DB->insert_record('block_instances', $bi); - context_block::instance($biid); - - // Add a few courses to each category - for($j=0; $j<6; $j++) { - $course = new stdClass(); - $course->fullname = 'course'.$j; - $course->shortname = 'c'.$j; - $course->summary = 'bah bah bah'; - $course->newsitems = 0; - $course->numsections = 1; - $course->category = $catid; - $course->format = 'topics'; - $course->timecreated = time(); - $course->visible = 1; - $course->timemodified = $course->timecreated; - $courseid = $DB->insert_record('course', $course); - $section = new stdClass(); - $section->course = $courseid; - $section->section = 0; - $section->summaryformat = FORMAT_HTML; - $DB->insert_record('course_sections', $section); - $section->section = 1; - $DB->insert_record('course_sections', $section); - $testcourses[] = $courseid; - $coursecontext = context_course::instance($courseid); - - if ($j >= 5) { - continue; - } - // Add manual enrol instance - $manualenrol->add_default_instance($DB->get_record('course', array('id'=>$courseid))); - - // Add block to each course - $bi->parentcontextid = $coursecontext->id; - $biid = $DB->insert_record('block_instances', $bi); - context_block::instance($biid); - $testblocks[] = $biid; - - // Add a resource to each course - $page->course = $courseid; - $pageid = $DB->insert_record('page', $page); - $testpages[] = $pageid; - $cm->course = $courseid; - $cm->instance = $pageid; - $cm->id = $DB->insert_record('course_modules', $cm); - $modcontext = context_module::instance($cm->id); - - // Add block to each module - $bi->parentcontextid = $modcontext->id; - $biid = $DB->insert_record('block_instances', $bi); - context_block::instance($biid); - $testblocks[] = $biid; - } - } - - // Make sure all contexts were created properly - $count = 1; //system - $count += $DB->count_records('user', array('deleted'=>0)); - $count += $DB->count_records('course_categories'); - $count += $DB->count_records('course'); - $count += $DB->count_records('course_modules'); - $count += $DB->count_records('block_instances'); - $this->assertEqual($DB->count_records('context'), $count); - $this->assertEqual($DB->count_records('context', array('depth'=>0)), 0); - $this->assertEqual($DB->count_records('context', array('path'=>NULL)), 0); - - - // ====== context_helper::get_level_name() ================================ - - $levels = context_helper::get_all_levels(); - foreach ($levels as $level=>$classname) { - $name = context_helper::get_level_name($level); - $this->assertFalse(empty($name)); - } - - - // ======= context::instance_by_id(), context_xxx::instance(); - - $context = context::instance_by_id($frontpagecontext->id); - $this->assertidentical($context->contextlevel, CONTEXT_COURSE); - $this->assertFalse(context::instance_by_id(-1, IGNORE_MISSING)); - try { - context::instance_by_id(-1); - $this->fail('exception expected'); - } catch (Exception $e) { - $this->assertTrue(true); - } - $this->assertTrue(context_system::instance() instanceof context_system); - $this->assertTrue(context_coursecat::instance($testcategories[0]) instanceof context_coursecat); - $this->assertTrue(context_course::instance($testcourses[0]) instanceof context_course); - $this->assertTrue(context_module::instance($testpages[0]) instanceof context_module); - $this->assertTrue(context_block::instance($testblocks[0]) instanceof context_block); - - $this->assertFalse(context_coursecat::instance(-1, IGNORE_MISSING)); - $this->assertFalse(context_course::instance(-1, IGNORE_MISSING)); - $this->assertFalse(context_module::instance(-1, IGNORE_MISSING)); - $this->assertFalse(context_block::instance(-1, IGNORE_MISSING)); - try { - context_coursecat::instance(-1); - $this->fail('exception expected'); - } catch (Exception $e) { - $this->assertTrue(true); - } - try { - context_course::instance(-1); - $this->fail('exception expected'); - } catch (Exception $e) { - $this->assertTrue(true); - } - try { - context_module::instance(-1); - $this->fail('exception expected'); - } catch (Exception $e) { - $this->assertTrue(true); - } - try { - context_block::instance(-1); - $this->fail('exception expected'); - } catch (Exception $e) { - $this->assertTrue(true); - } - - - // ======= $context->get_url(), $context->get_context_name(), $context->get_capabilities() ========= - - $testcontexts = array(); - $testcontexts[CONTEXT_SYSTEM] = context_system::instance(); - $testcontexts[CONTEXT_COURSECAT] = context_coursecat::instance($testcategories[0]); - $testcontexts[CONTEXT_COURSE] = context_course::instance($testcourses[0]); - $testcontexts[CONTEXT_MODULE] = context_module::instance($testpages[0]); - $testcontexts[CONTEXT_BLOCK] = context_block::instance($testblocks[0]); - - foreach ($testcontexts as $context) { - $name = $context->get_context_name(true, true); - $this->assertFalse(empty($name)); - - $this->assertTrue($context->get_url() instanceof moodle_url); - - $caps = $context->get_capabilities(); - $this->assertTrue(is_array($caps)); - foreach ($caps as $cap) { - $cap = (array)$cap; - $this->assertIdentical(array_keys($cap), array('id', 'name', 'captype', 'contextlevel', 'component', 'riskbitmask')); - } - } - unset($testcontexts); - - // ===== $context->get_course_context() ========================================= - - $this->assertFalse($systemcontext->get_course_context(false)); - try { - $systemcontext->get_course_context(); - $this->fail('exception expected'); - } catch (Exception $e) { - $this->assertTrue(true); - } - $context = context_coursecat::instance($testcategories[0]); - $this->assertFalse($context->get_course_context(false)); - try { - $context->get_course_context(); - $this->fail('exception expected'); - } catch (Exception $e) { - $this->assertTrue(true); - } - $this->assertIdentical($frontpagecontext->get_course_context(true), $frontpagecontext); - $this->assertIdentical($frontpagepagecontext->get_course_context(true), $frontpagecontext); - $this->assertIdentical($frontpagepageblockcontext->get_course_context(true), $frontpagecontext); - - - // ======= $context->get_parent_context(), $context->get_parent_contexts(), $context->get_parent_context_ids() ======= - - $userid = reset($testusers); - $usercontext = context_user::instance($userid); - $this->assertIdentical($usercontext->get_parent_context(), $systemcontext); - $this->assertIdentical($usercontext->get_parent_contexts(), array($systemcontext->id=>$systemcontext)); - $this->assertIdentical($usercontext->get_parent_contexts(true), array($usercontext->id=>$usercontext, $systemcontext->id=>$systemcontext)); - - $this->assertIdentical($systemcontext->get_parent_contexts(), array()); - $this->assertIdentical($systemcontext->get_parent_contexts(true), array($systemcontext->id=>$systemcontext)); - $this->assertIdentical($systemcontext->get_parent_context_ids(), array()); - $this->assertIdentical($systemcontext->get_parent_context_ids(true), array($systemcontext->id)); - - $this->assertIdentical($frontpagecontext->get_parent_context(), $systemcontext); - $this->assertIdentical($frontpagecontext->get_parent_contexts(), array($systemcontext->id=>$systemcontext)); - $this->assertIdentical($frontpagecontext->get_parent_contexts(true), array($frontpagecontext->id=>$frontpagecontext, $systemcontext->id=>$systemcontext)); - $this->assertIdentical($frontpagecontext->get_parent_context_ids(), array($systemcontext->id)); - $this->assertEqual($frontpagecontext->get_parent_context_ids(true), array($frontpagecontext->id, $systemcontext->id)); - - $this->assertIdentical($systemcontext->get_parent_context(), false); - $frontpagecontext = context_course::instance($SITE->id); - $parent = $systemcontext; - foreach ($testcategories as $catid) { - $catcontext = context_coursecat::instance($catid); - $this->assertIdentical($catcontext->get_parent_context(), $parent); - $parent = $catcontext; - } - $this->assertIdentical($frontpagepagecontext->get_parent_context(), $frontpagecontext); - $this->assertIdentical($frontpageblockcontext->get_parent_context(), $frontpagecontext); - $this->assertIdentical($frontpagepageblockcontext->get_parent_context(), $frontpagepagecontext); - - - // ====== $context->get_child_contexts() ================================ - - $children = $systemcontext->get_child_contexts(); - $this->assertEqual(count($children)+1, $DB->count_records('context')); - - $context = context_coursecat::instance($testcategories[3]); - $children = $context->get_child_contexts(); - $countcats = 0; - $countcourses = 0; - $countblocks = 0; - foreach ($children as $child) { - if ($child->contextlevel == CONTEXT_COURSECAT) { - $countcats++; - } - if ($child->contextlevel == CONTEXT_COURSE) { - $countcourses++; - } - if ($child->contextlevel == CONTEXT_BLOCK) { - $countblocks++; - } - } - $this->assertEqual(count($children), 8); - $this->assertEqual($countcats, 1); - $this->assertEqual($countcourses, 6); - $this->assertEqual($countblocks, 1); - - $context = context_course::instance($testcourses[2]); - $children = $context->get_child_contexts(); - $this->assertEqual(count($children), 3); - - $context = context_module::instance($testpages[3]); - $children = $context->get_child_contexts(); - $this->assertEqual(count($children), 1); - - $context = context_block::instance($testblocks[1]); - $children = $context->get_child_contexts(); - $this->assertEqual(count($children), 0); - - unset($children); - unset($countcats); - unset($countcourses); - unset($countblocks); - - - // ======= context_helper::reset_caches() ============================ - - context_helper::reset_caches(); - $this->assertEqual(context_inspection::test_context_cache_size(), 0); - context_course::instance($SITE->id); - $this->assertEqual(context_inspection::test_context_cache_size(), 1); - - - // ======= context preloading ======================================== - - context_helper::reset_caches(); - $sql = "SELECT ".context_helper::get_preload_record_columns_sql('c')." - FROM {context} c - WHERE c.contextlevel <> ".CONTEXT_SYSTEM; - $records = $DB->get_records_sql($sql); - $firstrecord = reset($records); - $columns = context_helper::get_preload_record_columns('c'); - $firstrecord = (array)$firstrecord; - $this->assertIdentical(array_keys($firstrecord), array_values($columns)); - context_helper::reset_caches(); - foreach ($records as $record) { - context_helper::preload_from_record($record); - $this->assertIdentical($record, new stdClass()); - } - $this->assertEqual(context_inspection::test_context_cache_size(), count($records)); - unset($records); - unset($columns); - - context_helper::reset_caches(); - context_helper::preload_course($SITE->id); - $this->assertEqual(context_inspection::test_context_cache_size(), 4); - - // ====== assign_capability(), unassign_capability() ==================== - - $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups')); - $this->assertFalse($rc); - assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $allroles['teacher'], $frontpagecontext->id); - $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups')); - $this->assertEqual($rc->permission, CAP_ALLOW); - assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $allroles['teacher'], $frontpagecontext->id); - $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups')); - $this->assertEqual($rc->permission, CAP_ALLOW); - assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $allroles['teacher'], $frontpagecontext, true); - $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups')); - $this->assertEqual($rc->permission, CAP_PREVENT); - - assign_capability('moodle/site:accessallgroups', CAP_INHERIT, $allroles['teacher'], $frontpagecontext); - $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups')); - $this->assertFalse($rc); - assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $allroles['teacher'], $frontpagecontext); - unassign_capability('moodle/site:accessallgroups', $allroles['teacher'], $frontpagecontext, true); - $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups')); - $this->assertFalse($rc); - unassign_capability('moodle/site:accessallgroups', $allroles['teacher'], $frontpagecontext->id, true); - unset($rc); - - accesslib_clear_all_caches(false); // must be done after assign_capability() - - - // ======= role_assign(), role_unassign(), role_unassign_all() ============== - - $context = context_course::instance($testcourses[1]); - $this->assertEqual($DB->count_records('role_assignments', array('contextid'=>$context->id)), 0); - role_assign($allroles['teacher'], $testusers[1], $context->id); - role_assign($allroles['teacher'], $testusers[2], $context->id); - role_assign($allroles['manager'], $testusers[1], $context->id); - $this->assertEqual($DB->count_records('role_assignments', array('contextid'=>$context->id)), 3); - role_unassign($allroles['teacher'], $testusers[1], $context->id); - $this->assertEqual($DB->count_records('role_assignments', array('contextid'=>$context->id)), 2); - role_unassign_all(array('contextid'=>$context->id)); - $this->assertEqual($DB->count_records('role_assignments', array('contextid'=>$context->id)), 0); - unset($context); - - accesslib_clear_all_caches(false); // just in case - - - // ====== has_capability(), get_users_by_capability(), role_switch(), reload_all_capabilities() and friends ======================== - - $adminid = get_admin()->id; - $guestid = $CFG->siteguest; - - // Enrol some users into some courses - $course1 = $DB->get_record('course', array('id'=>$testcourses[22]), '*', MUST_EXIST); - $course2 = $DB->get_record('course', array('id'=>$testcourses[7]), '*', MUST_EXIST); - $cms = $DB->get_records('course_modules', array('course'=>$course1->id), 'id'); - $cm1 = reset($cms); - $blocks = $DB->get_records('block_instances', array('parentcontextid'=>context_module::instance($cm1->id)->id), 'id'); - $block1 = reset($blocks); - $instance1 = $DB->get_record('enrol', array('enrol'=>'manual', 'courseid'=>$course1->id)); - $instance2 = $DB->get_record('enrol', array('enrol'=>'manual', 'courseid'=>$course2->id)); - for($i=0; $i<9; $i++) { - $manualenrol->enrol_user($instance1, $testusers[$i], $allroles['student']); - } - $manualenrol->enrol_user($instance1, $testusers[8], $allroles['teacher']); - $manualenrol->enrol_user($instance1, $testusers[9], $allroles['editingteacher']); - - for($i=10; $i<15; $i++) { - $manualenrol->enrol_user($instance2, $testusers[$i], $allroles['student']); - } - $manualenrol->enrol_user($instance2, $testusers[15], $allroles['editingteacher']); - - // Add tons of role assignments - the more the better - role_assign($allroles['coursecreator'], $testusers[11], context_coursecat::instance($testcategories[2])); - role_assign($allroles['manager'], $testusers[12], context_coursecat::instance($testcategories[1])); - role_assign($allroles['student'], $testusers[9], context_module::instance($cm1->id)); - role_assign($allroles['teacher'], $testusers[8], context_module::instance($cm1->id)); - role_assign($allroles['guest'], $testusers[13], context_course::instance($course1->id)); - role_assign($allroles['teacher'], $testusers[7], context_block::instance($block1->id)); - role_assign($allroles['manager'], $testusers[9], context_block::instance($block1->id)); - role_assign($allroles['editingteacher'], $testusers[9], context_course::instance($course1->id)); - - role_assign($allroles['teacher'], $adminid, context_course::instance($course1->id)); - role_assign($allroles['editingteacher'], $adminid, context_block::instance($block1->id)); - - // Add tons of overrides - the more the better - assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultuserroleid, $frontpageblockcontext, true); - assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpageblockcontext, true); - assign_capability('moodle/block:view', CAP_PROHIBIT, $allroles['guest'], $frontpageblockcontext, true); - assign_capability('block/online_users:viewlist', CAP_PREVENT, $allroles['user'], $frontpageblockcontext, true); - assign_capability('block/online_users:viewlist', CAP_PREVENT, $allroles['student'], $frontpageblockcontext, true); - - assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $CFG->defaultuserroleid, $frontpagepagecontext, true); - assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpagepagecontext, true); - assign_capability('mod/page:view', CAP_PREVENT, $allroles['guest'], $frontpagepagecontext, true); - assign_capability('mod/page:view', CAP_ALLOW, $allroles['user'], $frontpagepagecontext, true); - assign_capability('moodle/page:view', CAP_ALLOW, $allroles['student'], $frontpagepagecontext, true); - - assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultuserroleid, $frontpagecontext, true); - assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpagecontext, true); - assign_capability('mod/page:view', CAP_ALLOW, $allroles['guest'], $frontpagecontext, true); - assign_capability('mod/page:view', CAP_PROHIBIT, $allroles['user'], $frontpagecontext, true); - - assign_capability('mod/page:view', CAP_PREVENT, $allroles['guest'], $systemcontext, true); - - accesslib_clear_all_caches(false); // must be done after assign_capability() - - // Extra tests for guests and not-logged-in users because they can not be verified by cross checking - // with get_users_by_capability() where they are ignored - $this->assertFalse(has_capability('moodle/block:view', $frontpageblockcontext, $guestid)); - $this->assertFalse(has_capability('mod/page:view', $frontpagepagecontext, $guestid)); - $this->assertTrue(has_capability('mod/page:view', $frontpagecontext, $guestid)); - $this->assertFalse(has_capability('mod/page:view', $systemcontext, $guestid)); - - $this->assertFalse(has_capability('moodle/block:view', $frontpageblockcontext, 0)); - $this->assertFalse(has_capability('mod/page:view', $frontpagepagecontext, 0)); - $this->assertTrue(has_capability('mod/page:view', $frontpagecontext, 0)); - $this->assertFalse(has_capability('mod/page:view', $systemcontext, 0)); - - $this->assertFalse(has_capability('moodle/course:create', $systemcontext, $testusers[11])); - $this->assertTrue(has_capability('moodle/course:create', context_coursecat::instance($testcategories[2]), $testusers[11])); - $this->assertFalse(has_capability('moodle/course:create', context_course::instance($testcourses[1]), $testusers[11])); - $this->assertTrue(has_capability('moodle/course:create', context_course::instance($testcourses[19]), $testusers[11])); - - $this->assertFalse(has_capability('moodle/course:update', context_course::instance($testcourses[1]), $testusers[9])); - $this->assertFalse(has_capability('moodle/course:update', context_course::instance($testcourses[19]), $testusers[9])); - $this->assertFalse(has_capability('moodle/course:update', $systemcontext, $testusers[9])); - - // Test the list of enrolled users - $coursecontext = context_course::instance($course1->id); - $enrolled = get_enrolled_users($coursecontext); - $this->assertEqual(count($enrolled), 10); - for($i=0; $i<10; $i++) { - $this->assertTrue(isset($enrolled[$testusers[$i]])); - } - $enrolled = get_enrolled_users($coursecontext, 'moodle/course:update'); - $this->assertEqual(count($enrolled), 1); - $this->assertTrue(isset($enrolled[$testusers[9]])); - unset($enrolled); - - // role switching - $userid = $testusers[9]; - $USER = $DB->get_record('user', array('id'=>$userid)); - load_all_capabilities(); - $coursecontext = context_course::instance($course1->id); - $this->assertTrue(has_capability('moodle/course:update', $coursecontext)); - $this->assertFalse(is_role_switched($course1->id)); - role_switch($allroles['student'], $coursecontext); - $this->assertTrue(is_role_switched($course1->id)); - $this->assertEqual($USER->access['rsw'][$coursecontext->path], $allroles['student']); - $this->assertFalse(has_capability('moodle/course:update', $coursecontext)); - reload_all_capabilities(); - $this->assertFalse(has_capability('moodle/course:update', $coursecontext)); - role_switch(0, $coursecontext); - $this->assertTrue(has_capability('moodle/course:update', $coursecontext)); - $userid = $adminid; - $USER = $DB->get_record('user', array('id'=>$userid)); - load_all_capabilities(); - $coursecontext = context_course::instance($course1->id); - $blockcontext = context_block::instance($block1->id); - $this->assertTrue(has_capability('moodle/course:update', $blockcontext)); - role_switch($allroles['student'], $coursecontext); - $this->assertEqual($USER->access['rsw'][$coursecontext->path], $allroles['student']); - $this->assertFalse(has_capability('moodle/course:update', $blockcontext)); - reload_all_capabilities(); - $this->assertFalse(has_capability('moodle/course:update', $blockcontext)); - load_all_capabilities(); - $this->assertTrue(has_capability('moodle/course:update', $blockcontext)); - - // temp course role for enrol - $DB->delete_records('cache_flags', array()); // this prevents problem with dirty contexts immediately resetting the temp role - this is a known problem... - $userid = $testusers[5]; - $roleid = $allroles['editingteacher']; - $USER = $DB->get_record('user', array('id'=>$userid)); - load_all_capabilities(); - $coursecontext = context_course::instance($course1->id); - $this->assertFalse(has_capability('moodle/course:update', $coursecontext)); - $this->assertFalse(isset($USER->access['ra'][$coursecontext->path][$roleid])); - load_temp_course_role($coursecontext, $roleid); - $this->assertEqual($USER->access['ra'][$coursecontext->path][$roleid], $roleid); - $this->assertTrue(has_capability('moodle/course:update', $coursecontext)); - remove_temp_course_roles($coursecontext); - $this->assertFalse(has_capability('moodle/course:update', $coursecontext, $userid)); - load_temp_course_role($coursecontext, $roleid); - reload_all_capabilities(); - $this->assertFalse(has_capability('moodle/course:update', $coursecontext, $userid)); - $USER = new stdClass(); - $USER->id = 0; - - // Now cross check has_capability() with get_users_by_capability(), each using different code paths, - // they have to be kept in sync, usually only one of them breaks, so we know when something is wrong, - // at the same time validate extra restrictions (guest read only no risks, admin exception, non existent and deleted users) - $contexts = $DB->get_records('context', array(), 'id'); - $contexts = array_values($contexts); - $capabilities = $DB->get_records('capabilities', array(), 'id'); - $capabilities = array_values($capabilities); - $roles = array($allroles['guest'], $allroles['user'], $allroles['teacher'], $allroles['editingteacher'], $allroles['coursecreator'], $allroles['manager']); - - // Random time! - srand(666); - foreach($testusers as $userid) { // no guest or deleted - // each user gets 0-20 random roles - $rcount = rand(0, 10); - for($j=0; $j<$rcount; $j++) { - $roleid = $roles[rand(0, count($roles)-1)]; - $contextid = $contexts[rand(0, count($contexts)-1)]->id; - role_assign($roleid, $userid, $contextid); - } - } - $permissions = array(CAP_ALLOW, CAP_PREVENT, CAP_INHERIT, CAP_PREVENT); - for($j=0; $j<10000; $j++) { - $roleid = $roles[rand(0, count($roles)-1)]; - $contextid = $contexts[rand(0, count($contexts)-1)]->id; - $permission = $permissions[rand(0,count($permissions)-1)]; - $capname = $capabilities[rand(0, count($capabilities)-1)]->name; - assign_capability($capname, $permission, $roleid, $contextid, true); - } - unset($permissions); - unset($roles); - unset($contexts); - unset($users); - unset($capabilities); - - accesslib_clear_all_caches(false); // must be done after assign_capability() - - // Test time - let's set up some real user, just in case the logic for USER affects the others... - $USER = $DB->get_record('user', array('id'=>$testusers[3])); - load_all_capabilities(); - - $contexts = $DB->get_records('context', array(), 'id'); - $users = $DB->get_records('user', array(), 'id', 'id'); - $capabilities = $DB->get_records('capabilities', array(), 'id'); - $users[0] = null; // not-logged-in user - $users[-1] = null; // non-existent user - - foreach ($contexts as $crecord) { - $context = context::instance_by_id($crecord->id); - if ($coursecontext = $context->get_course_context(false)) { - $enrolled = get_enrolled_users($context); - } else { - $enrolled = array(); - } - foreach ($capabilities as $cap) { - $allowed = get_users_by_capability($context, $cap->name, 'u.id, u.username'); - if ($enrolled) { - $enrolledwithcap = get_enrolled_users($context, $cap->name); - } else { - $enrolledwithcap = array(); - } - foreach ($users as $userid=>$unused) { - if ($userid == 0 or isguestuser($userid)) { - if ($userid == 0) { - $CFG->forcelogin = true; - $this->assertFalse(has_capability($cap->name, $context, $userid)); - unset($CFG->forcelogin); - } - if (($cap->captype === 'write') or ($cap->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) { - $this->assertFalse(has_capability($cap->name, $context, $userid)); - } - $this->assertFalse(isset($allowed[$userid])); - } else { - if (is_siteadmin($userid)) { - $this->assertTrue(has_capability($cap->name, $context, $userid, true)); - } - $hascap = has_capability($cap->name, $context, $userid, false); - $this->assertIdentical($hascap, isset($allowed[$userid]), "Capability result mismatch user:$userid, context:$context->id, $cap->name, hascap: ".(int)$hascap." "); - if (isset($enrolled[$userid])) { - $this->assertIdentical(isset($allowed[$userid]), isset($enrolledwithcap[$userid]), "Enrolment with capability result mismatch user:$userid, context:$context->id, $cap->name, hascap: ".(int)$hascap." "); - } - } - } - } - } - // Back to nobody - $USER = new stdClass(); - $USER->id = 0; - unset($contexts); - unset($users); - unset($capabilities); - - // Now let's do all the remaining tests that break our carefully prepared fake site - - - - // ======= $context->mark_dirty() ======================================= - - $DB->delete_records('cache_flags', array()); - accesslib_clear_all_caches(false); - $systemcontext->mark_dirty(); - $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2); - $this->assertTrue(isset($dirty[$systemcontext->path])); - $this->assertTrue(isset($ACCESSLIB_PRIVATE->dirtycontexts[$systemcontext->path])); - - - // ======= $context->reload_if_dirty(); ================================= - - $DB->delete_records('cache_flags', array()); - accesslib_clear_all_caches(false); - load_all_capabilities(); - $context = context_course::instance($testcourses[2]); - $page = $DB->get_record('page', array('course'=>$testcourses[2])); - $pagecontext = context_module::instance($page->id); - - $context->mark_dirty(); - $this->assertTrue(isset($ACCESSLIB_PRIVATE->dirtycontexts[$context->path])); - $USER->access['test'] = true; - $context->reload_if_dirty(); - $this->assertFalse(isset($USER->access['test'])); - - $context->mark_dirty(); - $this->assertTrue(isset($ACCESSLIB_PRIVATE->dirtycontexts[$context->path])); - $USER->access['test'] = true; - $pagecontext->reload_if_dirty(); - $this->assertFalse(isset($USER->access['test'])); - - - // ======= context_helper::build_all_paths() ============================ - - $oldcontexts = $DB->get_records('context', array(), 'id'); - $DB->set_field_select('context', 'path', NULL, "contextlevel <> ".CONTEXT_SYSTEM); - $DB->set_field_select('context', 'depth', 0, "contextlevel <> ".CONTEXT_SYSTEM); - context_helper::build_all_paths(); - $newcontexts = $DB->get_records('context', array(), 'id'); - $this->assertIdentical($oldcontexts, $newcontexts); - unset($oldcontexts); - unset($newcontexts); - - - // ======= $context->reset_paths() ====================================== - - $context = context_course::instance($testcourses[2]); - $children = $context->get_child_contexts(); - $context->reset_paths(false); - $this->assertIdentical($DB->get_field('context', 'path', array('id'=>$context->id)), NULL); - $this->assertEqual($DB->get_field('context', 'depth', array('id'=>$context->id)), 0); - foreach ($children as $child) { - $this->assertIdentical($DB->get_field('context', 'path', array('id'=>$child->id)), NULL); - $this->assertEqual($DB->get_field('context', 'depth', array('id'=>$child->id)), 0); - } - $this->assertEqual(count($children)+1, $DB->count_records('context', array('depth'=>0))); - $this->assertEqual(count($children)+1, $DB->count_records('context', array('path'=>NULL))); - - $context = context_course::instance($testcourses[2]); - $context->reset_paths(true); - $context = context_course::instance($testcourses[2]); - $this->assertEqual($DB->get_field('context', 'path', array('id'=>$context->id)), $context->path); - $this->assertEqual($DB->get_field('context', 'depth', array('id'=>$context->id)), $context->depth); - $this->assertEqual(0, $DB->count_records('context', array('depth'=>0))); - $this->assertEqual(0, $DB->count_records('context', array('path'=>NULL))); - - - // ====== $context->update_moved(); ====================================== - - accesslib_clear_all_caches(false); - $DB->delete_records('cache_flags', array()); - $course = $DB->get_record('course', array('id'=>$testcourses[0])); - $context = context_course::instance($course->id); - $oldpath = $context->path; - $miscid = $DB->get_field_sql("SELECT MIN(id) FROM {course_categories}"); - $categorycontext = context_coursecat::instance($miscid); - $course->category = $miscid; - $DB->update_record('course', $course); - $context->update_moved($categorycontext); - - $context = context_course::instance($course->id); - $this->assertIdentical($context->get_parent_context(), $categorycontext); - $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2); - $this->assertTrue(isset($dirty[$oldpath])); - $this->assertTrue(isset($dirty[$context->path])); - - - // ====== $context->delete_content() ===================================== - - context_helper::reset_caches(); - $context = context_module::instance($testpages[3]); - $this->assertTrue($DB->record_exists('context', array('id'=>$context->id))); - $this->assertEqual(1, $DB->count_records('block_instances', array('parentcontextid'=>$context->id))); - $context->delete_content(); - $this->assertTrue($DB->record_exists('context', array('id'=>$context->id))); - $this->assertEqual(0, $DB->count_records('block_instances', array('parentcontextid'=>$context->id))); - - - // ====== $context->delete() ============================= - - context_helper::reset_caches(); - $context = context_module::instance($testpages[4]); - $this->assertTrue($DB->record_exists('context', array('id'=>$context->id))); - $this->assertEqual(1, $DB->count_records('block_instances', array('parentcontextid'=>$context->id))); - $bi = $DB->get_record('block_instances', array('parentcontextid'=>$context->id)); - $bicontext = context_block::instance($bi->id); - $DB->delete_records('cache_flags', array()); - $context->delete(); // should delete also linked blocks - $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2); - $this->assertTrue(isset($dirty[$context->path])); - $this->assertFalse($DB->record_exists('context', array('id'=>$context->id))); - $this->assertFalse($DB->record_exists('context', array('id'=>$bicontext->id))); - $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$testpages[4]))); - $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$bi->id))); - $this->assertEqual(0, $DB->count_records('block_instances', array('parentcontextid'=>$context->id))); - context_module::instance($testpages[4]); - - - // ====== context_helper::delete_instance() ============================= - - context_helper::reset_caches(); - $lastcourse = array_pop($testcourses); - $this->assertTrue($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$lastcourse))); - $coursecontext = context_course::instance($lastcourse); - $this->assertEqual(context_inspection::test_context_cache_size(), 1); - $this->assertFalse($coursecontext->instanceid == CONTEXT_COURSE); - $DB->delete_records('cache_flags', array()); - context_helper::delete_instance(CONTEXT_COURSE, $lastcourse); - $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2); - $this->assertTrue(isset($dirty[$coursecontext->path])); - $this->assertEqual(context_inspection::test_context_cache_size(), 0); - $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$lastcourse))); - context_course::instance($lastcourse); - - - // ======= context_helper::create_instances() ========================== - - $prevcount = $DB->count_records('context'); - $DB->delete_records('context', array('contextlevel'=>CONTEXT_BLOCK)); - context_helper::create_instances(null, true); - $this->assertIdentical($DB->count_records('context'), $prevcount); - $this->assertEqual($DB->count_records('context', array('depth'=>0)), 0); - $this->assertEqual($DB->count_records('context', array('path'=>NULL)), 0); - - $DB->delete_records('context', array('contextlevel'=>CONTEXT_BLOCK)); - $DB->delete_records('block_instances', array()); - $prevcount = $DB->count_records('context'); - $DB->delete_records_select('context', 'contextlevel <> '.CONTEXT_SYSTEM); - context_helper::create_instances(null, true); - $this->assertIdentical($DB->count_records('context'), $prevcount); - $this->assertEqual($DB->count_records('context', array('depth'=>0)), 0); - $this->assertEqual($DB->count_records('context', array('path'=>NULL)), 0); - - - // ======= context_helper::cleanup_instances() ========================== - - $lastcourse = $DB->get_field_sql("SELECT MAX(id) FROM {course}"); - $DB->delete_records('course', array('id'=>$lastcourse)); - $lastcategory = $DB->get_field_sql("SELECT MAX(id) FROM {course_categories}"); - $DB->delete_records('course_categories', array('id'=>$lastcategory)); - $lastuser = $DB->get_field_sql("SELECT MAX(id) FROM {user} WHERE deleted=0"); - $DB->delete_records('user', array('id'=>$lastuser)); - $DB->delete_records('block_instances', array('parentcontextid'=>$frontpagepagecontext->id)); - $DB->delete_records('course_modules', array('id'=>$frontpagepagecontext->instanceid)); - context_helper::cleanup_instances(); - $count = 1; //system - $count += $DB->count_records('user', array('deleted'=>0)); - $count += $DB->count_records('course_categories'); - $count += $DB->count_records('course'); - $count += $DB->count_records('course_modules'); - $count += $DB->count_records('block_instances'); - $this->assertEqual($DB->count_records('context'), $count); - - - // ======= context cache size restrictions ============================== - - $testusers= array(); - for ($i=0; $iauth = 'manual'; - $user->firstname = 'xuser'.$i; - $user->lastname = 'xuser'.$i; - $user->username = 'xuser'.$i; - $user->password = 'doesnotexist'; - $user->email = "xuser$i@example.com"; - $user->confirmed = 1; - $user->mnethostid = $CFG->mnet_localhost_id; - $user->lang = $CFG->lang; - $user->maildisplay = 1; - $user->timemodified = time(); - $user->lastip = '0.0.0.0'; - $userid = $DB->insert_record('user', $user); - $testusers[$i] = $userid; - } - context_helper::create_instances(null, true); - context_helper::reset_caches(); - for ($i=0; $iassertEqual(context_inspection::test_context_cache_size(), CONTEXT_CACHE_MAX_SIZE); - } else if ($i == CONTEXT_CACHE_MAX_SIZE) { - // once the limit is reached roughly 1/3 of records should be removed from cache - $this->assertEqual(context_inspection::test_context_cache_size(), (int)(CONTEXT_CACHE_MAX_SIZE * (2/3) +102)); - } - } - // We keep the first 100 cached - $prevsize = context_inspection::test_context_cache_size(); - for ($i=0; $i<100; $i++) { - context_user::instance($testusers[$i]); - $this->assertEqual(context_inspection::test_context_cache_size(), $prevsize); - } - context_user::instance($testusers[102]); - $this->assertEqual(context_inspection::test_context_cache_size(), $prevsize+1); - unset($testusers); - - - - // ================================================================= - // ======= basic test of legacy functions ========================== - // ================================================================= - // note: watch out, the fake site might be pretty borked already - - $this->assertIdentical(get_system_context(), context_system::instance()); - - foreach ($DB->get_records('context') as $contextid=>$record) { - $context = context::instance_by_id($contextid); - $this->assertIdentical(get_context_instance_by_id($contextid), $context); - $this->assertIdentical(get_context_instance($record->contextlevel, $record->instanceid), $context); - $this->assertIdentical(get_parent_contexts($context), $context->get_parent_context_ids()); - if ($context->id == SYSCONTEXTID) { - $this->assertIdentical(get_parent_contextid($context), false); - } else { - $this->assertIdentical(get_parent_contextid($context), $context->get_parent_context()->id); - } - } - - $children = get_child_contexts($systemcontext); - $this->assertEqual(count($children), $DB->count_records('context')-1); - unset($children); - - $DB->delete_records('context', array('contextlevel'=>CONTEXT_BLOCK)); - create_contexts(); - $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_BLOCK))); - - $DB->set_field('context', 'depth', 0, array('contextlevel'=>CONTEXT_BLOCK)); - build_context_path(); - $this->assertFalse($DB->record_exists('context', array('depth'=>0))); - - $lastcourse = $DB->get_field_sql("SELECT MAX(id) FROM {course}"); - $DB->delete_records('course', array('id'=>$lastcourse)); - $lastcategory = $DB->get_field_sql("SELECT MAX(id) FROM {course_categories}"); - $DB->delete_records('course_categories', array('id'=>$lastcategory)); - $lastuser = $DB->get_field_sql("SELECT MAX(id) FROM {user} WHERE deleted=0"); - $DB->delete_records('user', array('id'=>$lastuser)); - $DB->delete_records('block_instances', array('parentcontextid'=>$frontpagepagecontext->id)); - $DB->delete_records('course_modules', array('id'=>$frontpagepagecontext->instanceid)); - cleanup_contexts(); - $count = 1; //system - $count += $DB->count_records('user', array('deleted'=>0)); - $count += $DB->count_records('course_categories'); - $count += $DB->count_records('course'); - $count += $DB->count_records('course_modules'); - $count += $DB->count_records('block_instances'); - $this->assertEqual($DB->count_records('context'), $count); - - context_helper::reset_caches(); - preload_course_contexts($SITE->id); - $this->assertEqual(context_inspection::test_context_cache_size(), 1); - - context_helper::reset_caches(); - list($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSECAT, 'ctx'); - $sql = "SELECT c.id $select FROM {course_categories} c $join"; - $records = $DB->get_records_sql($sql); - foreach ($records as $record) { - context_instance_preload($record); - $record = (array)$record; - $this->assertEqual(1, count($record)); // only id left - } - $this->assertEqual(count($records), context_inspection::test_context_cache_size()); - - accesslib_clear_all_caches(true); - $DB->delete_records('cache_flags', array()); - mark_context_dirty($systemcontext->path); - $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2); - $this->assertTrue(isset($dirty[$systemcontext->path])); - - accesslib_clear_all_caches(false); - $DB->delete_records('cache_flags', array()); - $course = $DB->get_record('course', array('id'=>$testcourses[2])); - $context = get_context_instance(CONTEXT_COURSE, $course->id); - $oldpath = $context->path; - $miscid = $DB->get_field_sql("SELECT MIN(id) FROM {course_categories}"); - $categorycontext = context_coursecat::instance($miscid); - $course->category = $miscid; - $DB->update_record('course', $course); - context_moved($context, $categorycontext); - $context = get_context_instance(CONTEXT_COURSE, $course->id); - $this->assertIdentical($context->get_parent_context(), $categorycontext); - - $this->assertTrue($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$testcourses[2]))); - delete_context(CONTEXT_COURSE, $testcourses[2]); - $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$testcourses[2]))); - - $name = get_contextlevel_name(CONTEXT_COURSE); - $this->assertFalse(empty($name)); - - $context = get_context_instance(CONTEXT_COURSE, $testcourses[2]); - $name = print_context_name($context); - $this->assertFalse(empty($name)); - - $url = get_context_url($coursecontext); - $this->assertFalse($url instanceof modole_url); - - $page = $DB->get_record('page', array('id'=>$testpages[7])); - $context = get_context_instance(CONTEXT_MODULE, $page->id); - $coursecontext = get_course_context($context); - $this->assertEqual($coursecontext->contextlevel, CONTEXT_COURSE); - $this->assertEqual(get_courseid_from_context($context), $page->course); - - $caps = fetch_context_capabilities($systemcontext); - $this->assertTrue(is_array($caps)); - unset($caps); - } - - public function tearDown() { - global $USER, $SITE; - if (isset($this->accesslibprevuser)) { - $USER = $this->accesslibprevuser; - } - if (isset($this->accesslibprevsite)) { - $SITE = $this->accesslibprevsite; - } - - - parent::tearDown(); - } -} - diff --git a/lib/simpletest/testbackuplib.php b/lib/simpletest/testbackuplib.php deleted file mode 100644 index 2d74c3e42e3..00000000000 --- a/lib/simpletest/testbackuplib.php +++ /dev/null @@ -1,46 +0,0 @@ -dirroot . '/backup/backuplib.php'); - -class backuplib_test extends UnitTestCase { - - public static $includecoverage = array('backup/backuplib.php'); - -} - - diff --git a/lib/simpletest/testblocklib_blockmanager.php b/lib/simpletest/testblocklib_blockmanager.php deleted file mode 100644 index 818f3d14a12..00000000000 --- a/lib/simpletest/testblocklib_blockmanager.php +++ /dev/null @@ -1,399 +0,0 @@ -libdir . '/pagelib.php'); -require_once($CFG->libdir . '/blocklib.php'); - -/** Test-specific subclass to make some protected things public. */ -class testable_block_manager extends block_manager { - - public function mark_loaded() { - $this->birecordsbyregion = array(); - } - public function get_loaded_blocks() { - return $this->birecordsbyregion; - } -} -class block_ablocktype extends block_base { - public function init() { - } -} - -/** - * Test functions that don't need to touch the database. - */ -class moodle_block_manager_test extends UnitTestCase { - public static $includecoverage = array('lib/pagelib.php', 'lib/blocklib.php'); - protected $testpage; - protected $blockmanager; - - public function setUp() { - $this->testpage = new moodle_page(); - $this->testpage->set_context(get_context_instance(CONTEXT_SYSTEM)); - $this->blockmanager = new testable_block_manager($this->testpage); - } - - public function tearDown() { - $this->testpage = NULL; - $this->blockmanager = NULL; - } - - public function test_no_regions_initially() { - // Exercise SUT & Validate - $this->assertEqual(array(), $this->blockmanager->get_regions()); - } - - public function test_add_region() { - // Exercise SUT. - $this->blockmanager->add_region('a-region-name'); - // Validate - $this->assertEqual(array('a-region-name'), $this->blockmanager->get_regions()); - } - - public function test_add_regions() { - // Set up fixture. - $regions = array('a-region', 'another-region'); - // Exercise SUT. - $this->blockmanager->add_regions($regions); - // Validate - $this->assert(new ArraysHaveSameValuesExpectation($regions), $this->blockmanager->get_regions()); - } - - public function test_add_region_twice() { - // Exercise SUT. - $this->blockmanager->add_region('a-region-name'); - $this->blockmanager->add_region('another-region'); - // Validate - $this->assert(new ArraysHaveSameValuesExpectation(array('a-region-name', 'another-region')), - $this->blockmanager->get_regions()); - } - - public function test_cannot_add_region_after_loaded() { - // Set up fixture. - $this->blockmanager->mark_loaded(); - // Set expectation - $this->expectException(); - // Exercise SUT. - $this->blockmanager->add_region('too-late'); - } - - public function test_set_default_region() { - // Set up fixture. - $this->blockmanager->add_region('a-region-name'); - // Exercise SUT. - $this->blockmanager->set_default_region('a-region-name'); - // Validate - $this->assertEqual('a-region-name', $this->blockmanager->get_default_region()); - } - - public function test_cannot_set_unknown_region_as_default() { - // Set expectation - $this->expectException(); - // Exercise SUT. - $this->blockmanager->set_default_region('a-region-name'); - } - - public function test_cannot_change_default_region_after_loaded() { - // Set up fixture. - $this->blockmanager->mark_loaded(); - // Set expectation - $this->expectException(); - // Exercise SUT. - $this->blockmanager->set_default_region('too-late'); - } - - public function test_matching_page_type_patterns() { - $this->assert(new ArraysHaveSameValuesExpectation( - array('site-index', 'site-index-*', 'site-*', '*')), - matching_page_type_patterns('site-index')); - - $this->assert(new ArraysHaveSameValuesExpectation( - array('mod-quiz-report-overview', 'mod-quiz-report-overview-*', 'mod-quiz-report-*', 'mod-quiz-*', 'mod-*', '*')), - matching_page_type_patterns('mod-quiz-report-overview')); - - $this->assert(new ArraysHaveSameValuesExpectation( - array('mod-forum-view', 'mod-*-view', 'mod-forum-view-*', 'mod-forum-*', 'mod-*', '*')), - matching_page_type_patterns('mod-forum-view')); - - $this->assert(new ArraysHaveSameValuesExpectation( - array('mod-forum-index', 'mod-*-index', 'mod-forum-index-*', 'mod-forum-*', 'mod-*', '*')), - matching_page_type_patterns('mod-forum-index')); - } -} - -/** - * Test methods that load and save data from block_instances and block_positions. - */ -class moodle_block_manager_test_saving_loading extends UnitTestCaseUsingDatabase { - - protected $isediting = null; - - public function setUp() { - global $USER; - if (!empty($USER->editing)) { - // We want to avoid the capability checks associated with - // checking the user is editing. - $this->isediting = $USER->editing; - unset($USER->editing); - } - parent::setUp(); - $this->create_test_tables(array('block', 'block_instances', 'block_positions', 'context', 'course_categories', 'course'), 'lib'); - $this->switch_to_test_db(); - // Nasty hack, recreate the system context record (the accesslib API does not allow to create it easily) - $this->create_system_context_record(); - // Reset all caches - accesslib_clear_all_caches_for_unit_testing(); - } - - public function tearDown() { - global $USER; - if (!empty($this->isediting)) { - // Replace $USER->editing as it was there at setup. - $USER->editing = $this->isediting; - $this->isediting = null; - } - parent::tearDown(); - } - - protected function get_a_page_and_block_manager($regions, $context, $pagetype, $subpage = '') { - $page = new moodle_page; - $page->set_context($context); - $page->set_pagetype($pagetype); - $page->set_subpage($subpage); - - $blockmanager = new testable_block_manager($page); - $blockmanager->add_regions($regions); - $blockmanager->set_default_region($regions[0]); - - return array($page, $blockmanager); - } - - protected function get_a_known_block_type() { - global $DB; - $block = new stdClass; - $block->name = 'ablocktype'; - $this->testdb->insert_record('block', $block); - return $block->name; - } - - protected function assertContainsBlocksOfType($typearray, $blockarray) { - if (!$this->assertEqual(count($typearray), count($blockarray), "Blocks array contains the wrong number of elements %s.")) { - return; - } - $types = array_values($typearray); - $i = 0; - foreach ($blockarray as $block) { - $blocktype = $types[$i]; - $this->assertEqual($blocktype, $block->name(), "Block types do not match at postition $i %s."); - $i++; - } - } - - public function test_empty_initially() { - // Set up fixture. - list($page, $blockmanager) = $this->get_a_page_and_block_manager(array('a-region'), - get_context_instance(CONTEXT_SYSTEM), 'page-type'); - // Exercise SUT. - $blockmanager->load_blocks(); - // Validate. - $blocks = $blockmanager->get_loaded_blocks(); - $this->assertEqual(array('a-region' => array()), $blocks); - } - - public function test_adding_and_retrieving_one_block() { - // Set up fixture. - $regionname = 'a-region'; - $blockname = $this->get_a_known_block_type(); - $context = get_context_instance(CONTEXT_SYSTEM); - - list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), - $context, 'page-type'); - - // Exercise SUT. - $blockmanager->add_block($blockname, $regionname, 0, false); - $blockmanager->load_blocks(); - // Validate. - $blocks = $blockmanager->get_blocks_for_region($regionname); - $this->assertContainsBlocksOfType(array($blockname), $blocks); - } - - public function test_adding_and_retrieving_two_blocks() { - // Set up fixture. - $regionname = 'a-region'; - $blockname = $this->get_a_known_block_type(); - $context = get_context_instance(CONTEXT_SYSTEM); - - list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), - $context, 'page-type'); - - // Exercise SUT. - $blockmanager->add_block($blockname, $regionname, 0, false); - $blockmanager->add_block($blockname, $regionname, 1, false); - $blockmanager->load_blocks(); - // Validate. - $blocks = $blockmanager->get_blocks_for_region($regionname); - $this->assertContainsBlocksOfType(array($blockname, $blockname), $blocks); - } - - public function test_block_not_included_in_different_context() { - global $DB; - // Set up fixture. - $syscontext = get_context_instance(CONTEXT_SYSTEM); - $cat = new stdClass(); - $cat->name = 'testcategory'; - $cat->parent = 0; - $cat->depth = 1; - $cat->sortorder = 100; - $cat->timemodified = time(); - $catid = $DB->insert_record('course_categories', $cat); - $DB->set_field('course_categories', 'path', '/' . $catid, array('id' => $catid)); - $fakecontext = context_coursecat::instance($catid); - $regionname = 'a-region'; - $blockname = $this->get_a_known_block_type(); - - list($addpage, $addbm) = $this->get_a_page_and_block_manager(array($regionname), $fakecontext, 'page-type'); - list($viewpage, $viewbm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'page-type'); - - $addbm->add_block($blockname, $regionname, 0, false); - - // Exercise SUT. - $viewbm->load_blocks(); - // Validate. - $blocks = $viewbm->get_blocks_for_region($regionname); - $this->assertContainsBlocksOfType(array(), $blocks); - } - - public function test_block_included_in_sub_context() { - global $DB; - // Set up fixture. - $syscontext = get_context_instance(CONTEXT_SYSTEM); - $cat = new stdClass(); - $cat->name = 'testcategory'; - $cat->parent = 0; - $cat->depth = 1; - $cat->sortorder = 100; - $cat->timemodified = time(); - $catid = $DB->insert_record('course_categories', $cat); - $DB->set_field('course_categories', 'path', '/' . $catid, array('id' => $catid)); - $childcontext = context_coursecat::instance($catid); - $regionname = 'a-region'; - $blockname = $this->get_a_known_block_type(); - - list($addpage, $addbm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'page-type'); - list($viewpage, $viewbm) = $this->get_a_page_and_block_manager(array($regionname), $childcontext, 'page-type'); - - $addbm->add_block($blockname, $regionname, 0, true); - - // Exercise SUT. - $viewbm->load_blocks(); - // Validate. - $blocks = $viewbm->get_blocks_for_region($regionname); - $this->assertContainsBlocksOfType(array($blockname), $blocks); - } - - public function test_block_not_included_on_different_page_type() { - // Set up fixture. - $syscontext = get_context_instance(CONTEXT_SYSTEM); - $regionname = 'a-region'; - $blockname = $this->get_a_known_block_type(); - - list($addpage, $addbm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'page-type'); - list($viewpage, $viewbm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'other-page-type'); - - $addbm->add_block($blockname, $regionname, 0, true); - - // Exercise SUT. - $viewbm->load_blocks(); - // Validate. - $blocks = $viewbm->get_blocks_for_region($regionname); - $this->assertContainsBlocksOfType(array(), $blocks); - } - - public function test_block_not_included_on_different_sub_page() { - // Set up fixture. - $regionname = 'a-region'; - $blockname = $this->get_a_known_block_type(); - $syscontext = get_context_instance(CONTEXT_SYSTEM); - - list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), - $syscontext, 'page-type', 'sub-page'); - - $blockmanager->add_block($blockname, $regionname, 0, true, $page->pagetype, 'other-sub-page'); - - // Exercise SUT. - $blockmanager->load_blocks(); - // Validate. - $blocks = $blockmanager->get_blocks_for_region($regionname); - $this->assertContainsBlocksOfType(array(), $blocks); - } - - public function test_block_included_with_explicit_sub_page() { - // Set up fixture. - $regionname = 'a-region'; - $blockname = $this->get_a_known_block_type(); - $syscontext = get_context_instance(CONTEXT_SYSTEM); - - list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), - $syscontext, 'page-type', 'sub-page'); - - $blockmanager->add_block($blockname, $regionname, 0, true, $page->pagetype, $page->subpage); - - // Exercise SUT. - $blockmanager->load_blocks(); - // Validate. - $blocks = $blockmanager->get_blocks_for_region($regionname); - $this->assertContainsBlocksOfType(array($blockname), $blocks); - } - - public function test_block_included_with_page_type_pattern() { - // Set up fixture. - $regionname = 'a-region'; - $blockname = $this->get_a_known_block_type(); - $syscontext = get_context_instance(CONTEXT_SYSTEM); - - list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), - $syscontext, 'page-type', 'sub-page'); - - $blockmanager->add_block($blockname, $regionname, 0, true, 'page-*', $page->subpage); - - // Exercise SUT. - $blockmanager->load_blocks(); - // Validate. - $blocks = $blockmanager->get_blocks_for_region($regionname); - $this->assertContainsBlocksOfType(array($blockname), $blocks); - } -} - diff --git a/lib/simpletest/testcode.php b/lib/simpletest/testcode.php deleted file mode 100644 index 492ec4bd902..00000000000 --- a/lib/simpletest/testcode.php +++ /dev/null @@ -1,50 +0,0 @@ -extensions_to_ignore) . ')$/'; - $this->badstrings = array(); - $this->badstrings['DONOT' . 'COMMIT'] = 'DONOT' . 'COMMIT'; // If we put the literal string here, it fails the test! - $this->badstrings['trailing whitespace'] = "[\t ][\r\n]"; - foreach ($this->badstrings as $description => $ignored) { - $this->allok[$description] = true; - } - recurseFolders($CFG->dirroot, array($this, 'search_file_for_dnc'), $regexp, true); - foreach ($this->badstrings as $description => $ignored) { - if ($this->allok[$description]) { - $this->pass("No files contain $description."); - } - } - } - - function search_file_for_dnc($filepath) { - $content = file_get_contents($filepath); - foreach ($this->badstrings as $description => $badstring) { - $pass = (stripos($content, $badstring) === false); - if (!$pass) { - $this->fail("File $filepath contains $description."); - $this->allok[$description] = false; - } - } - } -} - diff --git a/lib/simpletest/testcompletionlib.php b/lib/simpletest/testcompletionlib.php deleted file mode 100644 index 179f26bc808..00000000000 --- a/lib/simpletest/testcompletionlib.php +++ /dev/null @@ -1,698 +0,0 @@ -libdir.'/completionlib.php'); - -global $DB; -Mock::generate(get_class($DB), 'mock_database'); -Mock::generate('moodle_transaction', 'mock_transaction'); - -Mock::generatePartial('completion_info','completion_cutdown', - array('delete_all_state','get_tracked_users','update_state', - 'internal_get_grade_state','is_enabled','get_data','internal_get_state','internal_set_data')); -Mock::generatePartial('completion_info','completion_cutdown2', - array('is_enabled','get_data','internal_get_state','internal_set_data')); -Mock::generatePartial('completion_info','completion_cutdown3', - array('internal_get_grade_state')); - -class fake_recordset implements Iterator { - var $closed; - var $values,$index; - - function fake_recordset($values) { - $this->values=$values; - $this->index=0; - } - - function current() { - return $this->values[$this->index]; - } - - function key() { - return $this->values[$this->index]; - } - - function next() { - $this->index++; - } - - function rewind() { - $this->index=0; - } - - function valid() { - return count($this->values) > $this->index; - } - - function close() { - $this->closed=true; - } - - function was_closed() { - return $this->closed; - } -} - -/** - * Expectation that checks an object for given values (normal equality test) - * plus a 'timemodified' field that is current (last second or two). - */ -class TimeModifiedExpectation extends SimpleExpectation { - private $otherfields; - - /** - * @param array $otherfields Array key=>value of required object fields - */ - function TimeModifiedExpectation($otherfields) { - $this->otherfields=$otherfields; - } - - function test($thing) { - $thingfields=(array)$thing; - foreach($this->otherfields as $key=>$value) { - if(!array_key_exists($key,$thingfields)) { - return false; - } - if($thingfields[$key]!=$value) { - return false; - } - } - - $timedifference=time()-$thing->timemodified; - return ($timedifference < 2 && $timedifference>=0); - } - - function testMessage($thing) { - return "Object does not match fields/time requirement"; - } -} - -class completionlib_test extends UnitTestCaseUsingDatabase { - - public static $includecoverage = array('lib/completionlib.php'); - var $realdb,$realcfg,$realsession,$realuser; - - function setUp() { - global $DB,$CFG,$SESSION,$USER; - $this->realdb=$DB; - $this->realcfg=$CFG; - $this->realsession=$SESSION; - $this->prevuser=$USER; - $DB=new mock_database(); - $CFG=clone($this->realcfg); - $CFG->prefix='test_'; - $CFG->enablecompletion=COMPLETION_ENABLED; - $SESSION=new stdClass(); - $USER=(object)array('id'=>314159); - } - - function tearDown() { - global $DB,$CFG,$SESSION,$USER; - $DB=$this->realdb; - $CFG=$this->realcfg; - $SESSION=$this->realsession; - $USER=$this->prevuser; - } - - function test_is_enabled() { - global $CFG; - - // Config alone - $CFG->enablecompletion=COMPLETION_DISABLED; - $this->assertEqual(COMPLETION_DISABLED,completion_info::is_enabled_for_site()); - $CFG->enablecompletion=COMPLETION_ENABLED; - $this->assertEqual(COMPLETION_ENABLED,completion_info::is_enabled_for_site()); - - // Course - //$course=new stdClass; - $course=(object)array('id'=>13); - $c=new completion_info($course); - $course->enablecompletion=COMPLETION_DISABLED; - $this->assertEqual(COMPLETION_DISABLED,$c->is_enabled()); - $course->enablecompletion=COMPLETION_ENABLED; - $this->assertEqual(COMPLETION_ENABLED,$c->is_enabled()); - $CFG->enablecompletion=COMPLETION_DISABLED; - $this->assertEqual(COMPLETION_DISABLED,$c->is_enabled()); - - // Course and CM - $cm=new stdClass; - $cm->completion=COMPLETION_TRACKING_MANUAL; - $this->assertEqual(COMPLETION_DISABLED,$c->is_enabled($cm)); - $CFG->enablecompletion=COMPLETION_ENABLED; - $course->enablecompletion=COMPLETION_DISABLED; - $this->assertEqual(COMPLETION_DISABLED,$c->is_enabled($cm)); - $course->enablecompletion=COMPLETION_ENABLED; - $this->assertEqual(COMPLETION_TRACKING_MANUAL,$c->is_enabled($cm)); - $cm->completion=COMPLETION_TRACKING_NONE; - $this->assertEqual(COMPLETION_TRACKING_NONE,$c->is_enabled($cm)); - $cm->completion=COMPLETION_TRACKING_AUTOMATIC; - $this->assertEqual(COMPLETION_TRACKING_AUTOMATIC,$c->is_enabled($cm)); - } - - function test_update_state() { - $c=new completion_cutdown2(); - $c->__construct((object)array('id'=>42)); - $cm=(object)array('id'=>13,'course'=>42); - - // Not enabled, should do nothing - $c->expectAt(0,'is_enabled',array($cm)); - $c->setReturnValueAt(0,'is_enabled',false); - $c->update_state($cm); - - // Enabled, but current state is same as possible result, do nothing - $current=(object)array('completionstate'=>COMPLETION_COMPLETE); - $c->expectAt(1,'is_enabled',array($cm)); - $c->setReturnValueAt(1,'is_enabled',true); - - $c->expectAt(0,'get_data',array($cm,false,0)); - $c->setReturnValueAt(0,'get_data',$current); - $c->update_state($cm,COMPLETION_COMPLETE); - - // Enabled, but current state is a specific one and new state is just - // omplete, so do nothing - $current->completionstate=COMPLETION_COMPLETE_PASS; - $c->expectAt(2,'is_enabled',array($cm)); - $c->setReturnValueAt(2,'is_enabled',true); - $c->expectAt(1,'get_data',array($cm,false,0)); - $c->setReturnValueAt(1,'get_data',$current); - $c->update_state($cm,COMPLETION_COMPLETE); - - // Manual, change state (no change) - $cm->completion=COMPLETION_TRACKING_MANUAL; - $current->completionstate=COMPLETION_COMPLETE; - $c->expectAt(3,'is_enabled',array($cm)); - $c->setReturnValueAt(3,'is_enabled',true); - $c->expectAt(2,'get_data',array($cm,false,0)); - $c->setReturnValueAt(2,'get_data',$current); - $c->update_state($cm,COMPLETION_COMPLETE); - - // Manual, change state (change) - $c->expectAt(4,'is_enabled',array($cm)); - $c->setReturnValueAt(4,'is_enabled',true); - $c->expectAt(3,'get_data',array($cm,false,0)); - $c->setReturnValueAt(3,'get_data',$current); - $c->expectAt(0,'internal_set_data',array($cm, - new TimeModifiedExpectation(array('completionstate'=>COMPLETION_INCOMPLETE)))); - $c->update_state($cm,COMPLETION_INCOMPLETE); - - // Auto, change state - $cm->completion=COMPLETION_TRACKING_AUTOMATIC; - $c->expectAt(5,'is_enabled',array($cm)); - $c->setReturnValueAt(5,'is_enabled',true); - $c->expectAt(4,'get_data',array($cm,false,0)); - $c->setReturnValueAt(4,'get_data',$current); - $c->expectAt(0,'internal_get_state',array($cm,0,$current)); - $c->setReturnValueAt(0,'internal_get_state',COMPLETION_COMPLETE_PASS); - $c->expectAt(1,'internal_set_data',array($cm, - new TimeModifiedExpectation(array('completionstate'=>COMPLETION_COMPLETE_PASS)))); - $c->update_state($cm,COMPLETION_COMPLETE_PASS); - - //$c->tally(); - } - - function test_internal_get_state() { - global $DB; - - $c=new completion_cutdown3(); - $c->__construct((object)array('id'=>42)); - $cm=(object)array('id'=>13,'course'=>42,'completiongradeitemnumber'=>null); - - // If view is required, but they haven't viewed it yet - $cm->completionview=COMPLETION_VIEW_REQUIRED; - $current=(object)array('viewed'=>COMPLETION_NOT_VIEWED); - $this->assertEqual(COMPLETION_INCOMPLETE,$c->internal_get_state($cm,123,$current)); - - // OK set view not required - $cm->completionview=COMPLETION_VIEW_NOT_REQUIRED; - - // Test not getting module name - $cm->modname='label'; - $this->assertEqual(COMPLETION_COMPLETE,$c->internal_get_state($cm,123,$current)); - - // Test getting module name - $cm->module=13; - unset($cm->modname); - $DB->expectOnce('get_field',array('modules','name',array('id'=>13))); - $DB->setReturnValue('get_field','label'); - $this->assertEqual(COMPLETION_COMPLETE,$c->internal_get_state($cm,123,$current)); - - // Note: This function is not fully tested (including kind of the main - // part) because: - // * the grade_item/grade_grade calls are static and can't be mocked - // * the plugin_supports call is static and can't be mocked - - //$DB->tally(); - //$c->tally(); - } - - function test_set_module_viewed() { - $c=new completion_cutdown(); - $c->__construct((object)array('id'=>42)); - $cm=(object)array('id'=>13,'course'=>42); - - // Not tracking completion, should do nothing - $cm->completionview=COMPLETION_VIEW_NOT_REQUIRED; - $c->set_module_viewed($cm); - - // Tracking completion but completion is disabled, should do nothing - $cm->completionview=COMPLETION_VIEW_REQUIRED; - $c->expectAt(0,'is_enabled',array($cm)); - $c->setReturnValueAt(0,'is_enabled',false); - $c->set_module_viewed($cm); - - // Now it's enabled, we expect it to get data. If data already has - // viewed, still do nothing - $c->expectAt(1,'is_enabled',array($cm)); - $c->setReturnValueAt(1,'is_enabled',true); - $c->expectAt(0,'get_data',array($cm,0)); - $hasviewed=(object)array('viewed'=>COMPLETION_VIEWED); - $c->setReturnValueAt(0,'get_data',$hasviewed); - $c->set_module_viewed($cm); - - // OK finally one that hasn't been viewed, now it should set it viewed - // and update state - $c->expectAt(2,'is_enabled',array($cm)); - $c->setReturnValueAt(2,'is_enabled',true); - $notviewed=(object)array('viewed'=>COMPLETION_NOT_VIEWED); - $c->expectAt(1,'get_data',array($cm,1337)); - $c->setReturnValueAt(1,'get_data',$notviewed); - $c->expectOnce('internal_set_data',array($cm,$hasviewed)); - $c->expectOnce('update_state',array($cm,COMPLETION_COMPLETE,1337)); - $c->set_module_viewed($cm,1337); - - //$c->tally(); - } - - function test_count_user_data() { - global $DB; - $course=(object)array('id'=>13); - $cm=(object)array('id'=>42); - $DB->setReturnValue('get_field_sql',666); - $DB->expectOnce('get_field_sql',array(new IgnoreWhitespaceExpectation("SELECT - COUNT(1) -FROM - {course_modules_completion} -WHERE - coursemoduleid=? AND completionstate<>0"),array(42))); - $c=new completion_info($course); - $this->assertEqual(666,$c->count_user_data($cm)); - - //$DB->tally(); - } - - function test_delete_all_state() { - global $DB,$SESSION; - $course=(object)array('id'=>13); - $cm=(object)array('id'=>42,'course'=>13); - $c=new completion_info($course); - // Check it works ok without data in session - $DB->expectAt(0,'delete_records', - array('course_modules_completion',array('coursemoduleid'=>42))); - $c->delete_all_state($cm); - - // Build up a session to check it deletes the right bits from it - // (and not other bits) - $SESSION->completioncache=array(); - $SESSION->completioncache[13]=array(); - $SESSION->completioncache[13][42]='foo'; - $SESSION->completioncache[13][43]='foo'; - $SESSION->completioncache[14]=array(); - $SESSION->completioncache[14][42]='foo'; - $DB->expectAt(1,'delete_records', - array('course_modules_completion',array('coursemoduleid'=>42))); - $c->delete_all_state($cm); - $this->assertEqual(array(13=>array(43=>'foo'),14=>array(42=>'foo')), - $SESSION->completioncache); - - //$DB->tally(); - } - - function test_reset_all_state() { - global $DB; - $c=new completion_cutdown(); - $c->__construct((object)array('id'=>42)); - - $cm=(object)array('id'=>13,'course'=>42, - 'completion'=>COMPLETION_TRACKING_AUTOMATIC); - - $DB->setReturnValue('get_recordset',new fake_recordset(array( - (object)array('id'=>1,'userid'=>100), - (object)array('id'=>2,'userid'=>101), - ))); - $DB->expectOnce('get_recordset',array('course_modules_completion', - array('coursemoduleid'=>13),'','userid')); - $c->expectOnce('delete_all_state',array($cm)); - $c->expectOnce('get_tracked_users',array()); - $c->setReturnValue('get_tracked_users',array( - (object)array('id'=>100,'firstname'=>'Woot','lastname'=>'Plugh'), - (object)array('id'=>201,'firstname'=>'Vroom','lastname'=>'Xyzzy'), - )); - - $c->expectAt(0,'update_state',array($cm,COMPLETION_UNKNOWN,100)); - $c->expectAt(1,'update_state',array($cm,COMPLETION_UNKNOWN,101)); - $c->expectAt(2,'update_state',array($cm,COMPLETION_UNKNOWN,201)); - - $c->reset_all_state($cm); - - //$DB->tally(); - //$c->tally(); - } - - function test_get_data() { - global $DB,$SESSION; - - $c=new completion_info((object)array('id'=>42)); - $cm=(object)array('id'=>13,'course'=>42); - - // 1. Not current user, record exists - $sillyrecord=(object)array('frog'=>'kermit'); - $DB->expectAt(0,'get_record',array('course_modules_completion', - array('coursemoduleid'=>13,'userid'=>123))); - $DB->setReturnValueAt(0,'get_record',$sillyrecord); - $result=$c->get_data($cm,false,123); - $this->assertEqual($sillyrecord,$result); - $this->assertTrue(empty($SESSION->completioncache)); - - // 2. Not current user, default record, wholecourse (ignored) - $DB->expectAt(1,'get_record',array('course_modules_completion', - array('coursemoduleid'=>13,'userid'=>123))); - $DB->setReturnValueAt(1,'get_record',false); - $result=$c->get_data($cm,true,123); - $this->assertEqual((object)array( - 'id'=>'0','coursemoduleid'=>13,'userid'=>123,'completionstate'=>0, - 'viewed'=>0,'timemodified'=>0),$result); - $this->assertTrue(empty($SESSION->completioncache)); - - // 3. Current user, single record, not from cache - $DB->expectAt(2,'get_record',array('course_modules_completion', - array('coursemoduleid'=>13,'userid'=>314159))); - $DB->setReturnValueAt(2,'get_record',$sillyrecord); - $result=$c->get_data($cm); - $this->assertEqual($sillyrecord,$result); - $this->assertEqual($sillyrecord,$SESSION->completioncache[42][13]); - // When checking time(), allow for second overlaps - $this->assertTrue(time()-$SESSION->completioncache[42]['updated']<2); - - // 4. Current user, 'whole course', but from cache - $result=$c->get_data($cm,true); - $this->assertEqual($sillyrecord,$result); - - // 5. Current user, single record, cache expired - $SESSION->completioncache[42]['updated']=37; // Quite a long time ago - $now=time(); - $SESSION->completioncache[17]['updated']=$now; - $SESSION->completioncache[39]['updated']=72; // Also a long time ago - $DB->expectAt(3,'get_record',array('course_modules_completion', - array('coursemoduleid'=>13,'userid'=>314159))); - $DB->setReturnValueAt(3,'get_record',$sillyrecord); - $result=$c->get_data($cm,false); - $this->assertEqual($sillyrecord,$result); - // Check that updated value is right, then fudge it to make next compare - // work - $this->assertTrue(time()-$SESSION->completioncache[42]['updated']<2); - $SESSION->completioncache[42]['updated']=$now; - // Check things got expired from cache - $this->assertEqual(array(42=>array(13=>$sillyrecord,'updated'=>$now), - 17=>array('updated'=>$now)),$SESSION->completioncache); - - // 6. Current user, 'whole course' and record not in cache - unset($SESSION->completioncache); - - // Scenario: Completion data exists for one CMid - $basicrecord=(object)array('coursemoduleid'=>13); - $DB->setReturnValueAt(0,'get_records_sql',array( - 1=>$basicrecord - )); - $DB->expectAt(0,'get_records_sql',array(new IgnoreWhitespaceExpectation(" -SELECT - cmc.* -FROM - {course_modules} cm - INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id -WHERE - cm.course=? AND cmc.userid=?"),array(42,314159))); - - // There are two CMids in total, the one we had data for and another one - $modinfo = new stdClass(); - $modinfo->cms=array((object)array('id'=>13),(object)array('id'=>14)); - $result=$c->get_data($cm,true,0,$modinfo); - - // Check result - $this->assertEqual($basicrecord,$result); - - // Check the cache contents - $this->assertTrue(time()-$SESSION->completioncache[42]['updated']<2); - $SESSION->completioncache[42]['updated']=$now; - $this->assertEqual(array(42=>array(13=>$basicrecord,14=>(object)array( - 'id'=>'0','coursemoduleid'=>14,'userid'=>314159,'completionstate'=>0, - 'viewed'=>0,'timemodified'=>0),'updated'=>$now)),$SESSION->completioncache); - - //$DB->tally(); - } - - function test_internal_set_data() { - global $DB,$SESSION; - - $cm = (object)array('course' => 42,'id' => 13); - $c = new completion_info((object)array('id' => 42)); - - // 1) Test with new data - $data = (object)array('id'=>0, 'userid' => 314159, 'coursemoduleid' => 99); - $DB->setReturnValueAt(0, 'start_delegated_transaction', new mock_transaction()); - $DB->setReturnValueAt(0, 'insert_record', 4); - $DB->expectAt(0, 'get_field', array('course_modules_completion', 'id', - array('coursemoduleid' => 99, 'userid' => 314159))); - $DB->expectAt(0, 'insert_record', array('course_modules_completion', $data)); - $c->internal_set_data($cm, $data); - $this->assertEqual(4, $data->id); - $this->assertEqual(array(42 => array(13 => $data)), $SESSION->completioncache); - - // 2) Test with existing data and for different user (not cached) - unset($SESSION->completioncache); - $d2 = (object)array('id' => 7, 'userid' => 17, 'coursemoduleid' => 66); - $DB->setReturnValueAt(1, 'start_delegated_transaction', new mock_transaction()); - $DB->expectAt(0,'update_record', array('course_modules_completion', $d2)); - $c->internal_set_data($cm, $d2); - $this->assertFalse(isset($SESSION->completioncache)); - - // 3) Test where it THINKS the data is new (from cache) but actually - // in the database it has been set since - // 1) Test with new data - $data = (object)array('id'=>0, 'userid' => 314159, 'coursemoduleid' => 99); - $DB->setReturnValueAt(2, 'start_delegated_transaction', new mock_transaction()); - $DB->setReturnValueAt(1, 'get_field', 13); - $DB->expectAt(1, 'get_field', array('course_modules_completion', 'id', - array('coursemoduleid' => 99, 'userid' => 314159))); - $d3 = (object)array('id' => 13, 'userid' => 314159, 'coursemoduleid' => 99); - $DB->expectAt(1,'update_record', array('course_modules_completion', $d3)); - $c->internal_set_data($cm, $data); - - //$DB->tally(); - } - - function test_get_activities() { - global $DB; - - $c=new completion_info((object)array('id'=>42)); - - // Try with no activities - $DB->expectAt(0,'get_records_select',array('course_modules', - 'course=42 AND completion<>'.COMPLETION_TRACKING_NONE)); - $DB->setReturnValueAt(0,'get_records_select',array()); - $result=$c->get_activities(); - $this->assertEqual(array(),$result); - - // Try with an activity (need to fake up modinfo for it as well) - $DB->expectAt(1,'get_records_select',array('course_modules', - 'course=42 AND completion<>'.COMPLETION_TRACKING_NONE)); - $DB->setReturnValueAt(1,'get_records_select',array( - 13=>(object)array('id'=>13) - )); - $modinfo=new stdClass; - $modinfo->sections=array(array(1,2,3),array(12,13,14)); - $modinfo->cms[13]=(object)array('modname'=>'frog','name'=>'kermit'); - $result=$c->get_activities($modinfo); - $this->assertEqual(array(13=>(object)array('id'=>13,'modname'=>'frog','name'=>'kermit')),$result); - - //$DB->tally(); - } - - // get_tracked_users() cannot easily be tested because it uses - // get_role_users, so skipping that - - function test_get_progress_all() { - global $DB; - - $c=new completion_cutdown(); - $c->__construct((object)array('id'=>42)); - - // 1) Basic usage - $c->expectAt(0,'get_tracked_users',array(false, array(), 0, '', '', '', null)); - $c->setReturnValueAt(0,'get_tracked_users',array( - (object)array('id'=>100,'firstname'=>'Woot','lastname'=>'Plugh'), - (object)array('id'=>201,'firstname'=>'Vroom','lastname'=>'Xyzzy'), - )); - $DB->expectAt(0,'get_in_or_equal',array(array(100,201))); - $DB->setReturnValueAt(0,'get_in_or_equal',array(' IN (100,201)',array())); - $DB->expectAt(0,'get_recordset_sql',array(new IgnoreWhitespaceExpectation(" -SELECT - cmc.* -FROM - {course_modules} cm - INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid -WHERE - cm.course=? AND cmc.userid IN (100,201)"),array(42))); - $progress1=(object)array('userid'=>100,'coursemoduleid'=>13); - $progress2=(object)array('userid'=>201,'coursemoduleid'=>14); - $DB->setReturnValueAt(0,'get_recordset_sql',new fake_recordset(array( - $progress1,$progress2 - ))); - $this->assertEqual(array( - - 100 => (object)array('id'=>100,'firstname'=>'Woot','lastname'=>'Plugh', - 'progress'=>array(13=>$progress1)), - 201 => (object)array('id'=>201,'firstname'=>'Vroom','lastname'=>'Xyzzy', - 'progress'=>array(14=>$progress2)), - ),$c->get_progress_all(false)); - - // 2) With more than 1,000 results - $c->expectAt(1,'get_tracked_users',array(true, 3, 0, '', '', '', null)); - - $tracked=array(); - $ids=array(); - $progress=array(); - for($i=100;$i<2000;$i++) { - $tracked[]=(object)array('id'=>$i,'firstname'=>'frog','lastname'=>$i); - $ids[]=$i; - $progress[]=(object)array('userid'=>$i,'coursemoduleid'=>13); - $progress[]=(object)array('userid'=>$i,'coursemoduleid'=>14); - } - $c->setReturnValueAt(1,'get_tracked_users',$tracked); - - $DB->expectAt(1,'get_in_or_equal',array(array_slice($ids,0,1000))); - $DB->setReturnValueAt(1,'get_in_or_equal',array(' IN whatever',array())); - $DB->expectAt(1,'get_recordset_sql',array(new IgnoreWhitespaceExpectation(" -SELECT - cmc.* -FROM - {course_modules} cm - INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid -WHERE - cm.course=? AND cmc.userid IN whatever"),array(42))); - $DB->setReturnValueAt(1,'get_recordset_sql',new fake_recordset(array_slice($progress,0,1000))); - $DB->expectAt(2,'get_in_or_equal',array(array_slice($ids,1000))); - $DB->setReturnValueAt(2,'get_in_or_equal',array(' IN whatever2',array())); - $DB->expectAt(2,'get_recordset_sql',array(new IgnoreWhitespaceExpectation(" -SELECT - cmc.* -FROM - {course_modules} cm - INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid -WHERE - cm.course=? AND cmc.userid IN whatever2"),array(42))); - $DB->setReturnValueAt(2,'get_recordset_sql',new fake_recordset(array_slice($progress,1000))); - $result=$c->get_progress_all(true,3); - $resultok=true; - $resultok = $resultok && ($ids==array_keys($result)); - - foreach($result as $userid => $data) { - $resultok = $resultok && $data->firstname=='frog'; - $resultok = $resultok && $data->lastname==$userid; - $resultok = $resultok && $data->id==$userid; - $cms=$data->progress; - $resultok= $resultok && (array(13,14)==array_keys($cms)); - $resultok= $resultok && ((object)array('userid'=>$userid,'coursemoduleid'=>13)==$cms[13]); - $resultok= $resultok && ((object)array('userid'=>$userid,'coursemoduleid'=>14)==$cms[14]); - } - $this->assertTrue($resultok); - - //$DB->tally(); - //$c->tally(); - } - - function test_inform_grade_changed() { - $c=new completion_cutdown(); - $c->__construct((object)array('id'=>42)); - - $cm=(object)array('course'=>42,'id'=>13,'completion'=>0,'completiongradeitemnumber'=>null); - $item=(object)array('itemnumber'=>3, 'gradepass'=>1, 'hidden'=>0); - $grade=(object)array('userid'=>31337, 'finalgrade'=>0, 'rawgrade'=>0); - - // Not enabled (should do nothing) - $c->setReturnValueAt(0,'is_enabled',false); - $c->expectAt(0,'is_enabled',array($cm)); - $c->inform_grade_changed($cm,$item,$grade,false); - - // Enabled but still no grade completion required, should still do nothing - $c->setReturnValueAt(1,'is_enabled',true); - $c->expectAt(1,'is_enabled',array($cm)); - $c->inform_grade_changed($cm,$item,$grade,false); - - // Enabled and completion required but item number is wrong, does nothing - $cm->completiongradeitemnumber=7; - $c->setReturnValueAt(2,'is_enabled',true); - $c->expectAt(2,'is_enabled',array($cm)); - $c->inform_grade_changed($cm,$item,$grade,false); - - // Enabled and completion required and item number right. It is supposed - // to call update_state with the new potential state being obtained from - // internal_get_grade_state. - $cm->completiongradeitemnumber=3; - $c->setReturnValueAt(3,'is_enabled',true); - $c->expectAt(3,'is_enabled',array($cm)); - $c->expectAt(0,'update_state',array($cm,COMPLETION_COMPLETE_PASS,31337)); - $grade->finalgrade = 1; - $c->inform_grade_changed($cm,$item,$grade,false); - - // Same as above but marked deleted. It is supposed to call update_state - // with new potential state being COMPLETION_INCOMPLETE - $c->setReturnValueAt(4,'is_enabled',false); - $c->expectAt(4,'is_enabled',array($cm)); - $c->expectAt(1,'update_state',array($cm,COMPLETION_INCOMPLETE,31337)); - $c->inform_grade_changed($cm,$item,$grade,false); - - //$c->tally(); - } - - function test_internal_get_grade_state() { - $item=new stdClass; - $grade=new stdClass; - - $item->gradepass=4; - $item->hidden=0; - $grade->rawgrade=4.0; - $grade->finalgrade=null; - - // Grade has pass mark and is not hidden, user passes - $this->assertEqual( - COMPLETION_COMPLETE_PASS, - completion_info::internal_get_grade_state($item,$grade)); - - // Same but user fails - $grade->rawgrade=3.9; - $this->assertEqual( - COMPLETION_COMPLETE_FAIL, - completion_info::internal_get_grade_state($item,$grade)); - - // User fails on raw grade but passes on final - $grade->finalgrade=4.0; - $this->assertEqual( - COMPLETION_COMPLETE_PASS, - completion_info::internal_get_grade_state($item,$grade)); - - // Item is hidden - $item->hidden=1; - $this->assertEqual( - COMPLETION_COMPLETE, - completion_info::internal_get_grade_state($item,$grade)); - - // Item isn't hidden but has no pass mark - $item->hidden=0; - $item->gradepass=0; - $this->assertEqual( - COMPLETION_COMPLETE, - completion_info::internal_get_grade_state($item,$grade)); - } -} - diff --git a/lib/simpletest/testcomponentlib.php b/lib/simpletest/testcomponentlib.php deleted file mode 100644 index 44a0fe2ced0..00000000000 --- a/lib/simpletest/testcomponentlib.php +++ /dev/null @@ -1,181 +0,0 @@ -. - - -/** - * Unit tests for /lib/componentlib.class.php. - * - * @package moodlecore - * @copyright 2011 Tomasz Muras - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -if (!defined('MOODLE_INTERNAL')) { - die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page -} - -global $CFG; - -require_once($CFG->libdir.'/componentlib.class.php'); - -class componentlib_test extends UnitTestCase { - - public function test_component_installer() { - global $CFG; - - $ci = new component_installer('http://download.moodle.org', 'unittest', 'downloadtests.zip'); - $this->assertTrue($ci->check_requisites()); - - $destpath = $CFG->dataroot.'/downloadtests'; - - //carefully remove component files to enforce fresh installation - @unlink($destpath.'/'.'downloadtests.md5'); - @unlink($destpath.'/'.'test.html'); - @unlink($destpath.'/'.'test.jpg'); - @rmdir($destpath); - - $this->assertEqual(COMPONENT_NEEDUPDATE, $ci->need_upgrade()); - - $status = $ci->install(); - $this->assertEqual(COMPONENT_INSTALLED, $status); - $this->assertEqual('9e94f74b3efb1ff6cf075dc6b2abf15c', $ci->get_component_md5()); - - //it's already installed, so Moodle should detect it's up to date - $this->assertEqual(COMPONENT_UPTODATE, $ci->need_upgrade()); - $status = $ci->install(); - $this->assertEqual(COMPONENT_UPTODATE, $status); - - //check if correct files were downloaded - $this->assertEqual('2af180e813dc3f446a9bb7b6af87ce24', md5_file($destpath.'/'.'test.jpg')); - $this->assertEqual('47250a973d1b88d9445f94db4ef2c97a', md5_file($destpath.'/'.'test.html')); - } - - /** - * Test the public API of the {@link lang_installer} class - */ - public function test_lang_installer() { - - // test the manipulation with the download queue - $installer = new testable_lang_installer(); - $this->assertFalse($installer->protected_is_queued()); - $installer->protected_add_to_queue('cs'); - $installer->protected_add_to_queue(array('cs', 'sk')); - $this->assertTrue($installer->protected_is_queued()); - $this->assertTrue($installer->protected_is_queued('cs')); - $this->assertTrue($installer->protected_is_queued('sk')); - $this->assertFalse($installer->protected_is_queued('de_kids')); - $installer->set_queue('de_kids'); - $this->assertFalse($installer->protected_is_queued('cs')); - $this->assertFalse($installer->protected_is_queued('sk')); - $this->assertFalse($installer->protected_is_queued('de')); - $this->assertFalse($installer->protected_is_queued('de_du')); - $this->assertTrue($installer->protected_is_queued('de_kids')); - $installer->set_queue(array('cs', 'de_kids')); - $this->assertTrue($installer->protected_is_queued('cs')); - $this->assertFalse($installer->protected_is_queued('sk')); - $this->assertFalse($installer->protected_is_queued('de')); - $this->assertFalse($installer->protected_is_queued('de_du')); - $this->assertTrue($installer->protected_is_queued('de_kids')); - $installer->set_queue(array()); - $this->assertFalse($installer->protected_is_queued()); - unset($installer); - - // install a set of lang packs - $installer = new testable_lang_installer(array('cs', 'de_kids', 'xx')); - $result = $installer->run(); - $this->assertEqual($result['cs'], lang_installer::RESULT_UPTODATE); - $this->assertEqual($result['de_kids'], lang_installer::RESULT_INSTALLED); - $this->assertEqual($result['xx'], lang_installer::RESULT_DOWNLOADERROR); - // the following two were automatically added to the queue - $this->assertEqual($result['de_du'], lang_installer::RESULT_INSTALLED); - $this->assertEqual($result['de'], lang_installer::RESULT_UPTODATE); - - // exception throwing - $installer = new testable_lang_installer(array('yy')); - $this->expectException('lang_installer_exception'); - $installer->run(); - } -} - -/** - * Testable lang_installer subclass that does not actually install anything - * and provides access to the protected methods of the parent class - * - * @copyright 2011 David Mudrak - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class testable_lang_installer extends lang_installer { - - /** - * @see parent::is_queued() - */ - public function protected_is_queued($langcode = '') { - return $this->is_queued($langcode); - } - - /** - * @see parent::add_to_queue() - */ - public function protected_add_to_queue($langcodes) { - return $this->add_to_queue($langcodes); - } - - /** - * Simulate lang pack installation via component_installer - * - * Language packages 'de_du' and 'de_kids' reported as installed - * Language packages 'cs' and 'de' reported as up-to-date - * Language package 'xx' returns download error - * All other language packages will throw an unknown exception - * - * @see parent::install_language_pack() - */ - protected function install_language_pack($langcode) { - - switch ($langcode) { - case 'de_du': - case 'de_kids': - return self::RESULT_INSTALLED; - - case 'cs': - case 'de': - return self::RESULT_UPTODATE; - - case 'xx': - return self::RESULT_DOWNLOADERROR; - - default: - throw new lang_installer_exception('testing-unknown-exception', $langcode); - } - } - - /** - * Simulate detection of parent languge - * - * @see parent::get_parent_language() - */ - protected function get_parent_language($langcode) { - - switch ($langcode) { - case 'de_kids': - return 'de_du'; - case 'de_du': - return 'de'; - default: - return ''; - } - } -} diff --git a/lib/simpletest/testconditionlib.php b/lib/simpletest/testconditionlib.php deleted file mode 100644 index 7b7eba81ccc..00000000000 --- a/lib/simpletest/testconditionlib.php +++ /dev/null @@ -1,385 +0,0 @@ -dirroot . '/lib/conditionlib.php'); - -class conditionlib_test extends UnitTestCaseUsingDatabase { - public static $includecoverage = array('lib/conditionlib.php'); - - public $conditionlib_tables = array( - 'lib' => array( - 'files','context', 'capabilities', 'role', - 'role_capabilities', 'role_assignments', - 'course_categories', 'course', - 'modules', - 'course_sections', 'course_modules', - 'course_modules_availability', - 'course_modules_completion', - 'grade_items', 'grade_grades'), - 'mod/resource' => array( - 'resource')); - public $oldcfg; - - public function setUp() { - global $CFG; - parent::setUp(); - $this->oldcfg=clone $CFG; - $CFG->enableavailability=true; - $CFG->enablecompletion=true; - - $this->switch_to_test_db(); // All operations until end of test method will happen in test DB - - foreach ($this->conditionlib_tables as $dir => $tables) { - $this->create_test_tables($tables, $dir); // Create tables - } - $this->fill_records(); // Add common stuff needed by various test methods - } - - /** - * Method called after each test method. Doesn't do anything extraordinary except restore the global $DB to the real one. - */ - public function tearDown() { - global $CFG; - $CFG->enableavailability=$this->oldcfg->enableavailability; - $CFG->enablecompletion=$this->oldcfg->enablecompletion; - parent::tearDown(); // All the test tables created in setUp will be dropped by this - } - - private function fill_records() { - global $DB; - - // We need the resource modules record available - $DB->insert_record('modules', (object)array('name' => 'resource')); - - // We (get_fast_modinfo) need some capabilities present - $DB->insert_record('capabilities', (object)array('name' => 'moodle/course:viewhiddenactivities', - 'contextlevel' => CONTEXT_COURSE)); - } - - function test_constructor() { - global $DB,$CFG; - $cm=new stdClass; - - // Test records - $id=$DB->insert_record('course_modules',(object)array( - 'showavailability'=>1,'availablefrom'=>17,'availableuntil'=>398,'course'=>64)); - - // no ID - try { - $test=new condition_info($cm); - $this->fail(); - } catch(coding_exception $e) { - } - - // no other data - $cm->id=$id; - $test=new condition_info($cm,CONDITION_MISSING_EVERYTHING); - $this->assertEqual( - (object)array('id'=>$id,'showavailability'=>1, - 'availablefrom'=>17,'availableuntil'=>398,'course'=>64, - 'conditionsgrade'=>array(), 'conditionscompletion'=>array()), - $test->get_full_course_module()); - - // just the course_modules stuff; check it doesn't request that from db - $cm->showavailability=0; - $cm->availablefrom=2; - $cm->availableuntil=74; - $cm->course=38; - $test=new condition_info($cm,CONDITION_MISSING_EXTRATABLE); - $this->assertEqual( - (object)array('id'=>$id,'showavailability'=>0, - 'availablefrom'=>2,'availableuntil'=>74,'course'=>38, - 'conditionsgrade'=>array(), 'conditionscompletion'=>array()), - $test->get_full_course_module()); - - // Now let's add some actual grade/completion conditions - $DB->insert_record('course_modules_availability',(object)array( - 'coursemoduleid'=>$id, - 'sourcecmid'=>42, - 'requiredcompletion'=>2 - )); - $DB->insert_record('course_modules_availability',(object)array( - 'coursemoduleid'=>$id, - 'sourcecmid'=>666, - 'requiredcompletion'=>1 - )); - $DB->insert_record('course_modules_availability',(object)array( - 'coursemoduleid'=>$id, - 'gradeitemid'=>37, - 'grademin'=>5.5 - )); - - $cm=(object)array('id'=>$id); - $test=new condition_info($cm,CONDITION_MISSING_EVERYTHING); - $fullcm=$test->get_full_course_module(); - $this->assertEqual(array(42=>2,666=>1),$fullcm->conditionscompletion); - $this->assertEqual(array(37=>(object)array('min'=>5.5,'max'=>null,'name'=>'!missing')), - $fullcm->conditionsgrade); - } - - private function make_course() { - global $DB; - $categoryid=$DB->insert_record('course_categories',(object)array('name'=>'conditionlibtest')); - return $DB->insert_record('course',(object)array( - 'fullname'=>'Condition test','shortname'=>'CT1', - 'category'=>$categoryid,'enablecompletion'=>1)); - } - - private function make_course_module($courseid,$params=array()) { - global $DB; - static $moduleid=0; - if(!$moduleid) { - $moduleid=$DB->get_field('modules','id',array('name'=>'resource')); - } - - $rid=$DB->insert_record('resource',(object)array('course'=>$courseid, - 'name'=>'xxx','alltext'=>'','popup'=>'')); - $settings=(object)array( - 'course'=>$courseid,'module'=>$moduleid,'instance'=>$rid); - foreach($params as $name=>$value) { - $settings->{$name}=$value; - } - return $DB->insert_record('course_modules',$settings); - } - - private function make_section($courseid,$cmids,$sectionnum=0) { - global $DB; - $DB->insert_record('course_sections',(object)array( - 'course'=>$courseid,'sequence'=>implode(',',$cmids),'section'=>$sectionnum)); - } - - function test_modinfo() { - global $DB; - - // Let's make a course - $courseid=$this->make_course(); - - // Now let's make a couple modules on that course - $cmid1=$this->make_course_module($courseid,array( - 'showavailability'=>1,'availablefrom'=>17,'availableuntil'=>398, - 'completion'=>COMPLETION_TRACKING_MANUAL)); - $cmid2=$this->make_course_module($courseid,array( - 'showavailability'=>0,'availablefrom'=>0,'availableuntil'=>0)); - $this->make_section($courseid,array($cmid1,$cmid2)); - - // Add a fake grade item - $gradeitemid=$DB->insert_record('grade_items',(object)array( - 'courseid'=>$courseid,'itemname'=>'frog')); - - // One of the modules has grade and completion conditions, other doesn't - $DB->insert_record('course_modules_availability',(object)array( - 'coursemoduleid'=>$cmid2, - 'sourcecmid'=>$cmid1, - 'requiredcompletion'=>1 - )); - $DB->insert_record('course_modules_availability',(object)array( - 'coursemoduleid'=>$cmid2, - 'gradeitemid'=>$gradeitemid, - 'grademin'=>5.5 - )); - - // Okay sweet, now get modinfo - $course = $DB->get_record('course',array('id'=>$courseid)); - $modinfo=get_fast_modinfo($course); - - // Test basic data - $this->assertEqual(1,$modinfo->cms[$cmid1]->showavailability); - $this->assertEqual(17,$modinfo->cms[$cmid1]->availablefrom); - $this->assertEqual(398,$modinfo->cms[$cmid1]->availableuntil); - $this->assertEqual(0,$modinfo->cms[$cmid2]->showavailability); - $this->assertEqual(0,$modinfo->cms[$cmid2]->availablefrom); - $this->assertEqual(0,$modinfo->cms[$cmid2]->availableuntil); - - // Test condition arrays - $this->assertEqual(array(),$modinfo->cms[$cmid1]->conditionscompletion); - $this->assertEqual(array(),$modinfo->cms[$cmid1]->conditionsgrade); - $this->assertEqual(array($cmid1=>1), - $modinfo->cms[$cmid2]->conditionscompletion); - $this->assertEqual(array($gradeitemid=>(object)array('min'=>5.5,'max'=>null,'name'=>'frog')), - $modinfo->cms[$cmid2]->conditionsgrade); - } - - function test_add_and_remove() { - global $DB; - // Make course and module - $courseid=$this->make_course(); - $cmid=$this->make_course_module($courseid,array( - 'showavailability'=>0,'availablefrom'=>0,'availableuntil'=>0)); - $this->make_section($courseid,array($cmid)); - - // Check it has no conditions - $test1=new condition_info((object)array('id'=>$cmid), - CONDITION_MISSING_EVERYTHING); - $cm=$test1->get_full_course_module(); - $this->assertEqual(array(),$cm->conditionscompletion); - $this->assertEqual(array(),$cm->conditionsgrade); - - // Add conditions of each type - $test1->add_completion_condition(13,3); - $this->assertEqual(array(13=>3),$cm->conditionscompletion); - $test1->add_grade_condition(666,0.4,null,true); - $this->assertEqual(array(666=>(object)array('min'=>0.4,'max'=>null,'name'=>'!missing')), - $cm->conditionsgrade); - - // Check they were really added in db - $test2=new condition_info((object)array('id'=>$cmid), - CONDITION_MISSING_EVERYTHING); - $cm=$test2->get_full_course_module(); - $this->assertEqual(array(13=>3),$cm->conditionscompletion); - $this->assertEqual(array(666=>(object)array('min'=>0.4,'max'=>null,'name'=>'!missing')), - $cm->conditionsgrade); - - // Wipe conditions - $test2->wipe_conditions(); - $this->assertEqual(array(),$cm->conditionscompletion); - $this->assertEqual(array(),$cm->conditionsgrade); - - // Check they were really wiped - $test3=new condition_info((object)array('id'=>$cmid), - CONDITION_MISSING_EVERYTHING); - $cm=$test3->get_full_course_module(); - $this->assertEqual(array(),$cm->conditionscompletion); - $this->assertEqual(array(),$cm->conditionsgrade); - } - - function test_is_available() { - global $DB,$USER; - $courseid=$this->make_course(); - - // No conditions - $cmid=$this->make_course_module($courseid); - $ci=new condition_info((object)array('id'=>$cmid), - CONDITION_MISSING_EVERYTHING); - $this->assertTrue($ci->is_available($text,false,0)); - $this->assertEqual('',$text); - - // Time (from) - $time=time()+100; - $cmid=$this->make_course_module($courseid,array('availablefrom'=>$time)); - $ci=new condition_info((object)array('id'=>$cmid), - CONDITION_MISSING_EVERYTHING); - $this->assertFalse($ci->is_available($text)); - $this->assert(new PatternExpectation( - '/'.preg_quote(userdate($time,get_string('strftimedate','langconfig'))).'/'),$text); - - $time=time()-100; - $cmid=$this->make_course_module($courseid,array('availablefrom'=>$time)); - $ci=new condition_info((object)array('id'=>$cmid), - CONDITION_MISSING_EVERYTHING); - $this->assertTrue($ci->is_available($text)); - $this->assertEqual('',$text); - $this->assert(new PatternExpectation( - '/'.preg_quote(userdate($time,get_string('strftimedate','langconfig'))).'/'),$ci->get_full_information()); - - // Time (until) - $cmid=$this->make_course_module($courseid,array('availableuntil'=>time()-100)); - $ci=new condition_info((object)array('id'=>$cmid), - CONDITION_MISSING_EVERYTHING); - $this->assertFalse($ci->is_available($text)); - $this->assertEqual('',$text); - - // Completion - $oldid=$cmid; - $cmid=$this->make_course_module($courseid); - $this->make_section($courseid,array($oldid,$cmid)); - $oldcm=$DB->get_record('course_modules',array('id'=>$oldid)); - $oldcm->completion=COMPLETION_TRACKING_MANUAL; - $DB->update_record('course_modules',$oldcm); - - // Need to reset modinfo after changing the options - rebuild_course_cache($courseid); - $reset = 'reset'; - get_fast_modinfo($reset); - - $ci=new condition_info((object)array('id'=>$cmid),CONDITION_MISSING_EVERYTHING); - $ci->add_completion_condition($oldid,COMPLETION_COMPLETE); - condition_info::wipe_session_cache(); - - $this->assertFalse($ci->is_available($text,false)); - $this->assertEqual(get_string('requires_completion_1','condition','xxx'),$text); - completion_info::wipe_session_cache(); - $completion=new completion_info($DB->get_record('course',array('id'=>$courseid))); - $completion->update_state($oldcm,COMPLETION_COMPLETE); - completion_info::wipe_session_cache(); - condition_info::wipe_session_cache(); - - $this->assertTrue($ci->is_available($text)); - $this->assertFalse($ci->is_available($text,false,$USER->id+1)); - completion_info::wipe_session_cache(); - condition_info::wipe_session_cache(); - $completion=new completion_info($DB->get_record('course',array('id'=>$courseid))); - $completion->update_state($oldcm,COMPLETION_INCOMPLETE); - $this->assertFalse($ci->is_available($text)); - - $ci->wipe_conditions(); - $ci->add_completion_condition($oldid,COMPLETION_INCOMPLETE); - condition_info::wipe_session_cache(); - $this->assertTrue($ci->is_available($text)); - $this->assertTrue($ci->is_available($text,false,$USER->id+1)); - - condition_info::wipe_session_cache(); - $this->assertTrue($ci->is_available($text,true)); - - // Grade - $ci->wipe_conditions(); - // Add a fake grade item - $gradeitemid=$DB->insert_record('grade_items',(object)array( - 'courseid'=>$courseid,'itemname'=>'frog')); - // Add a condition on a value existing... - $ci->add_grade_condition($gradeitemid,null,null,true); - $this->assertFalse($ci->is_available($text)); - $this->assertEqual(get_string('requires_grade_any','condition','frog'),$text); - - // Fake it existing - $DB->insert_record('grade_grades',(object)array( - 'itemid'=>$gradeitemid,'userid'=>$USER->id,'finalgrade'=>3.78)); - condition_info::wipe_session_cache(); - $this->assertTrue($ci->is_available($text)); - - condition_info::wipe_session_cache(); - $this->assertTrue($ci->is_available($text,true)); - - // Now require that user gets more than 3.78001 - $ci->wipe_conditions(); - $ci->add_grade_condition($gradeitemid,3.78001,null,true); - condition_info::wipe_session_cache(); - $this->assertFalse($ci->is_available($text)); - $this->assertEqual(get_string('requires_grade_min','condition','frog'),$text); - - // ...just on 3.78... - $ci->wipe_conditions(); - $ci->add_grade_condition($gradeitemid,3.78,null,true); - condition_info::wipe_session_cache(); - $this->assertTrue($ci->is_available($text)); - - // ...less than 3.78 - $ci->wipe_conditions(); - $ci->add_grade_condition($gradeitemid,null,3.78,true); - condition_info::wipe_session_cache(); - $this->assertFalse($ci->is_available($text)); - $this->assertEqual(get_string('requires_grade_max','condition','frog'),$text); - - // ...less than 3.78001 - $ci->wipe_conditions(); - $ci->add_grade_condition($gradeitemid,null,3.78001,true); - condition_info::wipe_session_cache(); - $this->assertTrue($ci->is_available($text)); - - // ...in a range that includes it - $ci->wipe_conditions(); - $ci->add_grade_condition($gradeitemid,3,4,true); - condition_info::wipe_session_cache(); - $this->assertTrue($ci->is_available($text)); - - // ...in a range that doesn't include it - $ci->wipe_conditions(); - $ci->add_grade_condition($gradeitemid,4,5,true); - condition_info::wipe_session_cache(); - $this->assertFalse($ci->is_available($text)); - $this->assertEqual(get_string('requires_grade_range','condition','frog'),$text); - } - -} - diff --git a/lib/simpletest/testcsslib.php b/lib/simpletest/testcsslib.php deleted file mode 100644 index cea549a57fb..00000000000 --- a/lib/simpletest/testcsslib.php +++ /dev/null @@ -1,721 +0,0 @@ -. - -/** - * This file contains the unittests for the css optimiser in csslib.php - * - * @package core_css - * @category css - * @copyright 2012 Sam Hemelryk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -if (!defined('MOODLE_INTERNAL')) { - die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page -} - -global $CFG; - -require_once($CFG->libdir . '/csslib.php'); - - -/** - * CSS optimiser test class - * - * @package core_css - * @category css - * @copyright 2012 Sam Hemelryk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class css_optimiser_test extends UnitTestCase { - - /** - * Sets up the test class - */ - public function setUp() { - global $CFG; - parent::setUp(); - // We need to disable these if they are enabled to that we can predict - // the output. - $CFG->cssoptimiserstats = false; - $CFG->cssoptimiserpretty = false; - } - - /** - * Test the process method - */ - public function test_process() { - $optimiser = new css_optimiser; - - $this->check_background($optimiser); - $this->check_borders($optimiser); - $this->check_colors($optimiser); - $this->check_margins($optimiser); - $this->check_padding($optimiser); - $this->check_widths($optimiser); - - $this->try_broken_css_found_in_moodle($optimiser); - $this->try_invalid_css_handling($optimiser); - $this->try_bulk_processing($optimiser); - $this->try_break_things($optimiser); - } - - /** - * Background colour tests - * @param css_optimiser $optimiser - */ - protected function check_background(css_optimiser $optimiser) { - - $cssin = '.test {background-color: #123456;}'; - $cssout = '.test{background:#123456;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {background-image: url(\'test.png\');}'; - $cssout = '.test{background-image:url(\'test.png\');}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {background: #123456 url(\'test.png\') no-repeat top left;}'; - $cssout = '.test{background:#123456 url(\'test.png\') no-repeat top left;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {background: url(\'test.png\') no-repeat top left;}.test{background-position: bottom right}.test {background-color:#123456;}'; - $cssout = '.test{background:#123456 url(\'test.png\') no-repeat bottom right;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {background: url( \'test.png\' )}.test{background: bottom right}.test {background:#123456;}'; - $cssout = '.test{background-image:url(\'test.png\');background-position:bottom right;background-color:#123456;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {background-color: #123456;background-repeat: repeat-x; background-position: 100% 0%;}'; - $cssout = '.test{background-color:#123456;background-repeat:repeat-x;background-position:100% 0%;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.tree_item.branch {background-image: url([[pix:t/expanded]]);background-position: 0 10%;background-repeat: no-repeat;} - .tree_item.branch.navigation_node {background-image:none;padding-left:0;}'; - $cssout = '.tree_item.branch{background:url([[pix:t/expanded]]) no-repeat 0 10%;} .tree_item.branch.navigation_node{background-image:none;padding-left:0;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.block_tree .tree_item.emptybranch {background-image: url([[pix:t/collapsed_empty]]);background-position: 0% 5%;background-repeat: no-repeat;} - .block_tree .collapsed .tree_item.branch {background-image: url([[pix:t/collapsed]]);}'; - $cssout = '.block_tree .tree_item.emptybranch{background:url([[pix:t/collapsed_empty]]) no-repeat 0% 5%;} .block_tree .collapsed .tree_item.branch{background-image:url([[pix:t/collapsed]]);}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '#nextLink{background:url(data:image/gif;base64,AAAA);}'; - $cssout = '#nextLink{background-image:url(data:image/gif;base64,AAAA);}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '#nextLink{background-image:url(data:image/gif;base64,AAAA);}'; - $cssout = '#nextLink{background-image:url(data:image/gif;base64,AAAA);}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {background: #123456 url(data:image/gif;base64,AAAA) no-repeat top left;}'; - $cssout = '.test{background:#123456 url(data:image/gif;base64,AAAA) no-repeat top left;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - } - - /** - * Border tests - * @param css_optimiser $optimiser - */ - protected function check_borders(css_optimiser $optimiser) { - $cssin = '.test {border: 1px solid #654321} .test {border-bottom-color: #123456}'; - $cssout = '.test{border:1px solid;border-color:#654321 #654321 #123456;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {border:1px solid red;}'; - $cssout = '.one{border:1px solid #FF0000;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {border:1px solid;} .one {border:2px dotted #DDD;}'; - $cssout = '.one{border:2px dotted #DDDDDD;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {border:2px dotted #DDD;}.one {border:1px solid;} '; - $cssout = '.one{border:1px solid #DDDDDD;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one, .two {border:1px solid red;}'; - $cssout = ".one, .two{border:1px solid #FF0000;}"; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one, .two {border:0px;}'; - $cssout = ".one, .two{border-width:0;}"; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one, .two {border-top: 5px solid white;}'; - $cssout = ".one, .two{border-top:5px solid #FFFFFF;}"; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {border:1px solid red;} .two {border:1px solid red;}'; - $cssout = ".one, .two{border:1px solid #FF0000;}"; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {border:1px solid red;width:20px;} .two {border:1px solid red;height:20px;}'; - $cssout = ".one{width:20px;border:1px solid #FF0000;} .two{height:20px;border:1px solid #FF0000;}"; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {border: 1px solid #123456;} .test {border-color: #654321}'; - $cssout = '.test{border:1px solid #654321;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {border-width: 1px; border-style: solid; border-color: #123456;}'; - $cssout = '.test{border:1px solid #123456;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {border:1px solid #123456;border-top:2px dotted #654321;}'; - $cssout = '.test{border:1px solid #123456;border-top:2px dotted #654321;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {border:1px solid #123456;border-left:2px dotted #654321;}'; - $cssout = '.test{border:1px solid #123456;border-left:2px dotted #654321;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {border-left:2px dotted #654321;border:1px solid #123456;}'; - $cssout = '.test{border:1px solid #123456;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {border:1px solid;border-top-color:#123456;}'; - $cssout = '.test{border:1px solid;border-top-color:#123456;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {border:1px solid;border-top-color:#111; border-bottom-color: #222;border-left-color: #333;}'; - $cssout = '.test{border:1px solid;border-top-color:#111;border-bottom-color:#222;border-left-color:#333;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.test {border:1px solid;border-top-color:#111; border-bottom-color: #222;border-left-color: #333;border-right-color:#444;}'; - $cssout = '.test{border:1px solid;border-color:#111 #444 #222 #333;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.generaltable .cell {border-color:#EEEEEE;} .generaltable .cell {border-width: 1px;border-style: solid;}'; - $cssout = '.generaltable .cell{border:1px solid #EEEEEE;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '#page-admin-roles-override .rolecap {border:none;border-bottom:1px solid #CECECE;}'; - $cssout = '#page-admin-roles-override .rolecap{border-top:0;border-right:0;border-bottom:1px solid #CECECE;border-left:0;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - } - - /** - * Test colour styles - * @param css_optimiser $optimiser - */ - protected function check_colors(css_optimiser $optimiser) { - $css = '.css{}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = '.css{color:#123456;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = '#some{color:#123456;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = 'div{color:#123456;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = 'div.css{color:#123456;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = 'div#some{color:#123456;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = 'div[type=blah]{color:#123456;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = 'div.css[type=blah]{color:#123456;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = 'div#some[type=blah]{color:#123456;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = '#some.css[type=blah]{color:#123456;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = '#some .css[type=blah]{color:#123456;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $cssin = '.one {color:red;} .two {color:#F00;}'; - $cssout = ".one, .two{color:#F00;}"; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {color:#123;color:#321;}'; - $cssout = '.one{color:#321;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {color:#123; color : #321 ;}'; - $cssout = '.one{color:#321;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {color:#123;} .one {color:#321;}'; - $cssout = '.one{color:#321;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {color:#123 !important;color:#321;}'; - $cssout = '.one{color:#123 !important;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {color:#123 !important;} .one {color:#321;}'; - $cssout = '.one{color:#123 !important;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {color:rgb(255, 128, 1)}'; - $cssout = '.one{color:rgb(255, 128, 1);}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {color:rgba(255, 128, 1, 0.5)}'; - $cssout = '.one{color:rgba(255, 128, 1, 0.5);}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {color:hsl(120, 65%, 75%)}'; - $cssout = '.one{color:hsl(120, 65%, 75%);}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {color:hsla(120,65%,75%,0.5)}'; - $cssout = '.one{color:hsla(120,65%,75%,0.5);}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Try some invalid colours to make sure we don't mangle them. - $css = 'div#some{color:#1;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = 'div#some{color:#12;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = 'div#some{color:#1234;}'; - $this->assertEqual($css, $optimiser->process($css)); - - $css = 'div#some{color:#12345;}'; - $this->assertEqual($css, $optimiser->process($css)); - } - - protected function check_widths(css_optimiser $optimiser) { - $cssin = '.css {width:0}'; - $cssout = '.css{width:0;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.css {width:0px}'; - $cssout = '.css{width:0;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.css {width:0em}'; - $cssout = '.css{width:0;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.css {width:0pt}'; - $cssout = '.css{width:0;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.css {width:0mm}'; - $cssout = '.css{width:0;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.css {width:100px}'; - $cssout = '.css{width:100px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - } - - /** - * Test margin styles - * @param css_optimiser $optimiser - */ - protected function check_margins(css_optimiser $optimiser) { - $cssin = '.one {margin: 1px 2px 3px 4px}'; - $cssout = '.one{margin:1px 2px 3px 4px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {margin-top:1px; margin-left:4px; margin-right:2px; margin-bottom: 3px;}'; - $cssout = '.one{margin:1px 2px 3px 4px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {margin-top:1px; margin-left:4px;}'; - $cssout = '.one{margin-top:1px;margin-left:4px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {margin:1px; margin-left:4px;}'; - $cssout = '.one{margin:1px 1px 1px 4px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {margin:1px; margin-bottom:4px;}'; - $cssout = '.one{margin:1px 1px 4px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one, .two, .one.two, .one .two {margin:0;} .one.two {margin:0 7px;}'; - $cssout = '.one, .two, .one .two{margin:0;} .one.two{margin:0 7px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - } - - /** - * Test padding styles - * - * @param css_optimiser $optimiser - */ - protected function check_padding(css_optimiser $optimiser) { - $cssin = '.one {margin: 1px 2px 3px 4px}'; - $cssout = '.one{margin:1px 2px 3px 4px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {margin-top:1px; margin-left:4px; margin-right:2px; margin-bottom: 3px;}'; - $cssout = '.one{margin:1px 2px 3px 4px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {margin-top:1px; margin-left:4px;}'; - $cssout = '.one{margin-top:1px;margin-left:4px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {margin:1px; margin-left:4px;}'; - $cssout = '.one{margin:1px 1px 1px 4px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {margin:1px; margin-bottom:4px;}'; - $cssout = '.one{margin:1px 1px 4px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {margin:0 !important;}'; - $cssout = '.one{margin:0 !important;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {padding:0 !important;}'; - $cssout = '.one{padding:0 !important;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one, .two, .one.two, .one .two {margin:0;} .one.two {margin:0 7px;}'; - $cssout = '.one, .two, .one .two{margin:0;} .one.two{margin:0 7px;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - } - - /** - * Test some totally invalid CSS optimisation - * - * @param css_optimiser $optimiser - */ - protected function try_invalid_css_handling(css_optimiser $optimiser) { - - $cssin = array( - '.one{}', - '.one {:}', - '.one {;}', - '.one {;;;;;}', - '.one {:;}', - '.one {:;:;:;:::;;;}', - '.one {!important}', - '.one {:!important}', - '.one {:!important;}', - '.one {;!important}' - ); - $cssout = '.one{}'; - foreach ($cssin as $css) { - $this->assertEqual($cssout, $optimiser->process($css)); - } - - $cssin = array( - '.one{background-color:red;}', - '.one {background-color:red;} .one {background-color:}', - '.one {background-color:red;} .one {background-color;}', - '.one {background-color:red;} .one {background-color}', - '.one {background-color:red;} .one {background-color:;}', - '.one {background-color:red;} .one {:blue;}', - '.one {background-color:red;} .one {:#00F}', - ); - $cssout = '.one{background:#F00;}'; - foreach ($cssin as $css) { - $this->assertEqual($cssout, $optimiser->process($css)); - } - - $cssin = '..one {background-color:color:red}'; - $cssout = '..one{background-color:color:red;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '#.one {background-color:color:red}'; - $cssout = '#.one{background-color:color:red;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '##one {background-color:color:red}'; - $cssout = '##one{background-color:color:red;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {background-color:color:red}'; - $cssout = '.one{background-color:color:red;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {background-color:red;color;border-color:blue}'; - $cssout = '.one{background:#F00;border-color:#00F;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '{background-color:#123456;color:red;}{color:green;}'; - $cssout = "{color:#008000;background:#123456;}"; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - $cssin = '.one {color:red;} {color:green;} .one {background-color:blue;}'; - $cssout = ".one{color:#F00;background:#00F;} {color:#008000;}"; - $this->assertEqual($cssout, $optimiser->process($cssin)); - } - - /** - * Try to break some things - * @param css_optimiser $optimiser - */ - protected function try_break_things(css_optimiser $optimiser) { - // Wildcard test - $cssin = '* {color: black;}'; - $cssout = '*{color:#000;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Wildcard test - $cssin = '.one * {color: black;}'; - $cssout = '.one *{color:#000;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Wildcard test - $cssin = '* .one * {color: black;}'; - $cssout = '* .one *{color:#000;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Wildcard test - $cssin = '*,* {color: black;}'; - $cssout = '*{color:#000;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Wildcard test - $cssin = '*, * .one {color: black;}'; - $cssout = "*,\n* .one{color:#000;}"; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Wildcard test - $cssin = '*, *.one {color: black;}'; - $cssout = "*,\n*.one{color:#000;}"; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Psedo test - $cssin = '.one:before {color: black;}'; - $cssout = '.one:before{color:#000;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Psedo test - $cssin = '.one:after {color: black;}'; - $cssout = '.one:after{color:#000;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Psedo test - $cssin = '.one:onclick {color: black;}'; - $cssout = '.one:onclick{color:#000;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Test complex CSS rules that don't really exist but mimic other CSS rules - $cssin = '.one {master-of-destruction: explode(\' \', "What madness");}'; - $cssout = '.one{master-of-destruction:explode(\' \', "What madness");}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Test some complex IE css... I couldn't even think of a more complext solution - // than the CSS they came up with. - $cssin = 'a { opacity: 0.5; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; filter: alpha(opacity=50); }'; - $cssout = 'a{opacity:0.5;-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";filter:alpha(opacity=50);}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - } - - /** - * A bulk processing test - * @param css_optimiser $optimiser - */ - protected function try_bulk_processing(css_optimiser $optimiser) { - global $CFG; - $cssin = <<cssoptimiserpretty = 1; - $this->assertEqual($optimiser->process($cssin), $cssout); - } - - /** - * Test CSS colour matching - */ - public function test_css_is_colour() { - // First lets test hex colours - $this->assertTrue(css_is_colour('#123456')); - $this->assertTrue(css_is_colour('#123')); - $this->assertTrue(css_is_colour('#ABCDEF')); - $this->assertTrue(css_is_colour('#ABC')); - $this->assertTrue(css_is_colour('#abcdef')); - $this->assertTrue(css_is_colour('#abc')); - $this->assertTrue(css_is_colour('#aBcDeF')); - $this->assertTrue(css_is_colour('#aBc')); - $this->assertTrue(css_is_colour('#1a2Bc3')); - $this->assertTrue(css_is_colour('#1Ac')); - - // Note the following two colour's arn't really colours but browsers process - // them still. - $this->assertTrue(css_is_colour('#A')); - $this->assertTrue(css_is_colour('#12')); - // Having four or five characters however are not valid colours and - // browsers don't parse them. They need to fail so that broken CSS - // stays broken after optimisation. - $this->assertFalse(css_is_colour('#1234')); - $this->assertFalse(css_is_colour('#12345')); - - $this->assertFalse(css_is_colour('#BCDEFG')); - $this->assertFalse(css_is_colour('#')); - $this->assertFalse(css_is_colour('#0000000')); - $this->assertFalse(css_is_colour('#132-245')); - $this->assertFalse(css_is_colour('#13 23 43')); - $this->assertFalse(css_is_colour('123456')); - - // Next lets test real browser mapped colours - $this->assertTrue(css_is_colour('black')); - $this->assertTrue(css_is_colour('blue')); - $this->assertTrue(css_is_colour('BLACK')); - $this->assertTrue(css_is_colour('Black')); - $this->assertTrue(css_is_colour('bLACK')); - $this->assertTrue(css_is_colour('mediumaquamarine')); - $this->assertTrue(css_is_colour('mediumAquamarine')); - $this->assertFalse(css_is_colour('monkey')); - $this->assertFalse(css_is_colour('')); - $this->assertFalse(css_is_colour('not a colour')); - - // Next lets test rgb(a) colours - $this->assertTrue(css_is_colour('rgb(255,255,255)')); - $this->assertTrue(css_is_colour('rgb(0, 0, 0)')); - $this->assertTrue(css_is_colour('RGB (255, 255 , 255)')); - $this->assertTrue(css_is_colour('rgba(0,0,0,0)')); - $this->assertTrue(css_is_colour('RGBA(255,255,255,1)')); - $this->assertTrue(css_is_colour('rgbA(255,255,255,0.5)')); - $this->assertFalse(css_is_colour('rgb(-255,-255,-255)')); - $this->assertFalse(css_is_colour('rgb(256,-256,256)')); - - // Now lets test HSL colours - $this->assertTrue(css_is_colour('hsl(0,0%,100%)')); - $this->assertTrue(css_is_colour('hsl(180, 0%, 10%)')); - $this->assertTrue(css_is_colour('hsl (360, 100% , 95%)')); - - // Finally test the special values - $this->assertTrue(css_is_colour('inherit')); - } - - /** - * Test the css_is_width function - */ - public function test_css_is_width() { - - $this->assertTrue(css_is_width('0')); - $this->assertTrue(css_is_width('0px')); - $this->assertTrue(css_is_width('0em')); - $this->assertTrue(css_is_width('199px')); - $this->assertTrue(css_is_width('199em')); - $this->assertTrue(css_is_width('199%')); - $this->assertTrue(css_is_width('-1')); - $this->assertTrue(css_is_width('-1px')); - $this->assertTrue(css_is_width('auto')); - $this->assertTrue(css_is_width('inherit')); - - $this->assertFalse(css_is_width('-')); - $this->assertFalse(css_is_width('bananas')); - $this->assertFalse(css_is_width('')); - $this->assertFalse(css_is_width('top')); - } - - /** - * This function tests some of the broken crazy CSS we have in Moodle. - * For each of these things the value needs to be corrected if we can be 100% - * certain what is going wrong, Or it needs to be left as is. - * - * @param css_optimiser $optimiser - */ - public function try_broken_css_found_in_moodle(css_optimiser $optimiser) { - // Notice how things are out of order here but that they get corrected - $cssin = '.test {background:url([[pix:theme|pageheaderbgred]]) top center no-repeat}'; - $cssout = '.test{background:url([[pix:theme|pageheaderbgred]]) no-repeat top center;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Cursor hand isn't valid - $cssin = '.test {cursor: hand;}'; - $cssout = '.test{cursor:hand;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Zoom property isn't valid - $cssin = '.test {zoom: 1;}'; - $cssout = '.test{zoom:1;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Left isn't a valid position property - $cssin = '.test {position: left;}'; - $cssout = '.test{position:left;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // The dark red color isn't a valid HTML color but has a standardised - // translation of #8B0000 - $cssin = '.test {color: darkred;}'; - $cssout = '.test{color:#8B0000;}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // You can't use argb colours as border colors - $cssin = '.test {border-bottom: 1px solid rgba(0,0,0,0.25);}'; - $cssout = '.test{border-bottom:1px solid rgba(0,0,0,0.25);}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - - // Opacity with annoying IE equivilants.... - $cssin = '.test {opacity: 0.5; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; filter: alpha(opacity=50);}'; - $cssout = '.test{opacity:0.5;-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";filter:alpha(opacity=50);}'; - $this->assertEqual($cssout, $optimiser->process($cssin)); - } -} \ No newline at end of file diff --git a/lib/simpletest/testdeprecatedlib.php b/lib/simpletest/testdeprecatedlib.php deleted file mode 100644 index 6c216df8d8a..00000000000 --- a/lib/simpletest/testdeprecatedlib.php +++ /dev/null @@ -1,34 +0,0 @@ -. - - -/** - * Unit tests for ../deprecatedlib.php. - * - * @package moodlecore - * @copyright 2009 Tim Hunt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later (5) - */ - -if (!defined('MOODLE_INTERNAL')) { - die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page -} -require_once($CFG->libdir . '/deprecatedlib.php'); - -class outputlib_methods_test extends UnitTestCase { - -} diff --git a/lib/simpletest/testeventslib.php b/lib/simpletest/testeventslib.php deleted file mode 100644 index 4d5fd7a6d9a..00000000000 --- a/lib/simpletest/testeventslib.php +++ /dev/null @@ -1,225 +0,0 @@ -. - -/** - * Tests events subsystems - * - * @package core - * @subpackage event - * @copyright 2007 onwards Martin Dougiamas (http://dougiamas.com) - * @author Petr Skoda {@link http://skodak.org} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - - -defined('MOODLE_INTERNAL') || die(); - -// test handler function -function sample_function_handler($eventdata) { - static $called = 0; - static $ignorefail = false; - - if ($eventdata == 'status') { - return $called; - - } else if ($eventdata == 'reset') { - $called = 0; - $ignorefail = false; - return; - - } else if ($eventdata == 'fail') { - if ($ignorefail) { - $called++; - return true; - } else { - return false; - } - - } else if ($eventdata == 'ignorefail') { - $ignorefail = true; - return; - - } else if ($eventdata == 'ok') { - $called++; - return true; - } - - print_error('invalideventdata', '', '', $eventdata); -} - -// test handler class with static method -class sample_handler_class { - static function static_method($eventdata) { - static $called = 0; - static $ignorefail = false; - - if ($eventdata == 'status') { - return $called; - - } else if ($eventdata == 'reset') { - $called = 0; - $ignorefail = false; - return; - - } else if ($eventdata == 'fail') { - if ($ignorefail) { - $called++; - return true; - } else { - return false; - } - - } else if ($eventdata == 'ignorefail') { - $ignorefail = true; - return; - - } else if ($eventdata == 'ok') { - $called++; - return true; - } - - print_error('invalideventdata', '', '', $eventdata); - } -} - -class eventslib_test extends UnitTestCase { - - public static $includecoverage = array('lib/eventslib.php'); - - /** - * Create temporary entries in the database for these tests. - * These tests have to work no matter the data currently in the database - * (meaning they should run on a brand new site). This means several items of - * data have to be artificially inseminated (:-) in the DB. - */ - function setUp() { - // Set global category settings to -1 (not force) - - events_uninstall('unittest'); - sample_function_handler('reset'); - sample_handler_class::static_method('reset'); - events_update_definition('unittest'); - } - - /** - * Delete temporary entries from the database - */ - function tearDown() { - events_uninstall('unittest'); - } - - /** - * Tests the installation of event handlers from file - */ - function test__events_update_definition__install() { - global $CFG, $DB; - - $dbcount = $DB->count_records('events_handlers', array('component'=>'unittest')); - $handlers = array(); - require($CFG->libdir.'/simpletest/fixtures/events.php'); - $filecount = count($handlers); - $this->assertEqual($dbcount, $filecount, 'Equal number of handlers in file and db: %s'); - } - - /** - * Tests the uninstallation of event handlers from file - */ - function test__events_update_definition__uninstall() { - global $DB; - - events_uninstall('unittest'); - $this->assertEqual(0, $DB->count_records('events_handlers', array('component'=>'unittest')), 'All handlers should be uninstalled: %s'); - } - - /** - * Tests the update of event handlers from file - */ - function test__events_update_definition__update() { - global $DB; - // first modify directly existing handler - $handler = $DB->get_record('events_handlers', array('component'=>'unittest', 'eventname'=>'test_instant')); - - $original = $handler->handlerfunction; - - // change handler in db - $DB->set_field('events_handlers', 'handlerfunction', serialize('some_other_function_handler'), array('id'=>$handler->id)); - - // update the definition, it should revert the handler back - events_update_definition('unittest'); - $handler = $DB->get_record('events_handlers', array('component'=>'unittest', 'eventname'=>'test_instant')); - $this->assertEqual($handler->handlerfunction, $original, 'update should sync db with file definition: %s'); - } - - /** - * tests events_trigger_is_registered funtion() - */ - function test__events_is_registered() { - $this->assertTrue(events_is_registered('test_instant', 'unittest')); - } - - /** - * tests events_trigger funtion() - */ - function test__events_trigger__instant() { - $this->assertEqual(0, events_trigger('test_instant', 'ok')); - $this->assertEqual(0, events_trigger('test_instant', 'ok')); - $this->assertEqual(2, sample_function_handler('status')); - } - - /** - * tests events_trigger funtion() - */ - function test__events_trigger__cron() { - $this->assertEqual(0, events_trigger('test_cron', 'ok')); - $this->assertEqual(0, sample_handler_class::static_method('status')); - events_cron('test_cron'); - $this->assertEqual(1, sample_handler_class::static_method('status')); - } - - /** - * tests events_pending_count() - */ - function test__events_pending_count() { - events_trigger('test_cron', 'ok'); - events_trigger('test_cron', 'ok'); - events_cron('test_cron'); - $this->assertEqual(0, events_pending_count('test_cron'), 'all messages should be already dequeued: %s'); - } - - /** - * tests events_trigger funtion() when instant handler fails - */ - function test__events_trigger__failed_instant() { - $this->assertEqual(1, events_trigger('test_instant', 'fail'), 'fail first event: %s'); - $this->assertEqual(1, events_trigger('test_instant', 'ok'), 'this one should fail too: %s'); - $this->assertEqual(0, events_cron('test_instant'), 'all events should stay in queue: %s'); - $this->assertEqual(2, events_pending_count('test_instant'), 'two events should in queue: %s'); - $this->assertEqual(0, sample_function_handler('status'), 'verify no event dispatched yet: %s'); - sample_function_handler('ignorefail'); //ignore "fail" eventdata from now on - $this->assertEqual(1, events_trigger('test_instant', 'ok'), 'this one should go to queue directly: %s'); - $this->assertEqual(3, events_pending_count('test_instant'), 'three events should in queue: %s'); - $this->assertEqual(0, sample_function_handler('status'), 'verify previous event was not dispatched: %s'); - $this->assertEqual(3, events_cron('test_instant'), 'all events should be dispatched: %s'); - $this->assertEqual(3, sample_function_handler('status'), 'verify three events were dispatched: %s'); - $this->assertEqual(0, events_pending_count('test_instant'), 'no events should in queue: %s'); - $this->assertEqual(0, events_trigger('test_instant', 'ok'), 'this event should be dispatched immediately: %s'); - $this->assertEqual(4, sample_function_handler('status'), 'verify event was dispatched: %s'); - $this->assertEqual(0, events_pending_count('test_instant'), 'no events should in queue: %s'); - } -} - - diff --git a/lib/simpletest/testexternallib.php b/lib/simpletest/testexternallib.php deleted file mode 100644 index 31f1581fe0a..00000000000 --- a/lib/simpletest/testexternallib.php +++ /dev/null @@ -1,80 +0,0 @@ -. - - -/** - * Unit tests for /lib/externallib.php. - * - * @package webservices - * @copyright 2009 Petr Skoda - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -if (!defined('MOODLE_INTERNAL')) { - die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page -} - -global $CFG; - -require_once($CFG->libdir . '/externallib.php'); - -class externallib_test extends UnitTestCase { - public function test_validate_params() { - $params = array('text'=>'aaa', 'someid'=>'6',); - $description = new external_function_parameters(array('someid' => new external_value(PARAM_INT, 'Some int value'), - 'text' => new external_value(PARAM_ALPHA, 'Some text value'))); - $result = external_api::validate_parameters($description, $params); - $this->assertEqual(count($result), 2); - reset($result); - $this->assertTrue(key($result) === 'someid'); - $this->assertTrue($result['someid'] === 6); - $this->assertTrue($result['text'] === 'aaa'); - - - $params = array('someids'=>array('1', 2, 'a'=>'3'), 'scalar'=>666); - $description = new external_function_parameters(array('someids' => new external_multiple_structure(new external_value(PARAM_INT, 'Some ID')), - 'scalar' => new external_value(PARAM_ALPHANUM, 'Some text value'))); - $result = external_api::validate_parameters($description, $params); - $this->assertEqual(count($result), 2); - reset($result); - $this->assertTrue(key($result) === 'someids'); - $this->assertTrue($result['someids'] == array(0=>1, 1=>2, 2=>3)); - $this->assertTrue($result['scalar'] === '666'); - - - $params = array('text'=>'aaa'); - $description = new external_function_parameters(array('someid' => new external_value(PARAM_INT, 'Some int value', false), - 'text' => new external_value(PARAM_ALPHA, 'Some text value'))); - $result = external_api::validate_parameters($description, $params); - $this->assertEqual(count($result), 2); - reset($result); - $this->assertTrue(key($result) === 'someid'); - $this->assertTrue($result['someid'] === null); - $this->assertTrue($result['text'] === 'aaa'); - - - $params = array('text'=>'aaa'); - $description = new external_function_parameters(array('someid' => new external_value(PARAM_INT, 'Some int value', false, 6), - 'text' => new external_value(PARAM_ALPHA, 'Some text value'))); - $result = external_api::validate_parameters($description, $params); - $this->assertEqual(count($result), 2); - reset($result); - $this->assertTrue(key($result) === 'someid'); - $this->assertTrue($result['someid'] === 6); - $this->assertTrue($result['text'] === 'aaa'); - } -} diff --git a/lib/simpletest/testfilelib.php b/lib/simpletest/testfilelib.php deleted file mode 100644 index 0e63fc8a439..00000000000 --- a/lib/simpletest/testfilelib.php +++ /dev/null @@ -1,91 +0,0 @@ -. - - -/** - * Unit tests for /lib/filelib.php. - * - * @package file - * @copyright 2009 Jerome Mouneyrac - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -if (!defined('MOODLE_INTERNAL')) { - die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page -} - -global $CFG; - -require_once($CFG->libdir . '/filelib.php'); - -class filelib_test extends UnitTestCase { - public function test_format_postdata_for_curlcall() { - - //POST params with just simple types - $postdatatoconvert =array( 'userid' => 1, 'roleid' => 22, 'name' => 'john'); - $expectedresult = "userid=1&roleid=22&name=john"; - $postdata = format_postdata_for_curlcall($postdatatoconvert); - $this->assertEqual($postdata, $expectedresult); - - //POST params with a string containing & character - $postdatatoconvert =array( 'name' => 'john&emilie', 'roleid' => 22); - $expectedresult = "name=john%26emilie&roleid=22"; //urlencode: '%26' => '&' - $postdata = format_postdata_for_curlcall($postdatatoconvert); - $this->assertEqual($postdata, $expectedresult); - - //POST params with an empty value - $postdatatoconvert =array( 'name' => null, 'roleid' => 22); - $expectedresult = "name=&roleid=22"; - $postdata = format_postdata_for_curlcall($postdatatoconvert); - $this->assertEqual($postdata, $expectedresult); - - //POST params with complex types - $postdatatoconvert =array( 'users' => array( - array( - 'id' => 2, - 'customfields' => array( - array - ( - 'type' => 'Color', - 'value' => 'violet' - ) - ) - ) - ) - ); - $expectedresult = "users[0][id]=2&users[0][customfields][0][type]=Color&users[0][customfields][0][value]=violet"; - $postdata = format_postdata_for_curlcall($postdatatoconvert); - $this->assertEqual($postdata, $expectedresult); - - //POST params with other complex types - $postdatatoconvert = array ('members' => - array( - array('groupid' => 1, 'userid' => 1) - , array('groupid' => 1, 'userid' => 2) - ) - ); - $expectedresult = "members[0][groupid]=1&members[0][userid]=1&members[1][groupid]=1&members[1][userid]=2"; - $postdata = format_postdata_for_curlcall($postdatatoconvert); - $this->assertEqual($postdata, $expectedresult); - } - - public function test_download_file_content() { - $testhtml = "http://download.moodle.org/unittest/test.html"; - $contents = download_file_content($testhtml); - $this->assertEqual('47250a973d1b88d9445f94db4ef2c97a', md5($contents)); - } -} diff --git a/lib/simpletest/testfilterconfig.php b/lib/simpletest/testfilterconfig.php deleted file mode 100644 index fcb4e3b6028..00000000000 --- a/lib/simpletest/testfilterconfig.php +++ /dev/null @@ -1,830 +0,0 @@ -libdir . '/filterlib.php'); - -/** - * Test functions that affect filter_active table with contextid = $syscontextid. - */ -class filter_active_global_test extends UnitTestCaseUsingDatabase { - private $syscontextid; - public static $includecoverage = array('lib/filterlib.php'); - - public function setUp() { - parent::setUp(); - - // Make sure accesslib has cached a sensible system context object - // before we switch to the test DB. - $this->syscontextid = get_context_instance(CONTEXT_SYSTEM)->id; - - // Create the table we need and switch to test DB. - $this->create_test_table('filter_active', 'lib'); - $this->switch_to_test_db(); - } - - private function assert_only_one_filter_globally($filter, $state) { - $recs = $this->testdb->get_records('filter_active'); - $this->assertEqual(1, count($recs), 'More than one record returned %s.'); - $rec = reset($recs); - $expectedrec = new stdClass; - $expectedrec->filter = $filter; - $expectedrec->contextid = $this->syscontextid; - $expectedrec->active = $state; - $expectedrec->sortorder = 1; - $this->assert(new CheckSpecifiedFieldsExpectation($expectedrec), $rec); - } - - private function assert_global_sort_order($filters) { - $sortedfilters = $this->testdb->get_records_menu('filter_active', - array('contextid' => $this->syscontextid), 'sortorder', 'sortorder,filter'); - $testarray = array(); - $index = 1; - foreach($filters as $filter) { - $testarray[$index++] = $filter; - } - $this->assertEqual($testarray, $sortedfilters); - } - - public function test_set_filter_globally_on() { - // Setup fixture. - // Exercise SUT. - filter_set_global_state('filter/name', TEXTFILTER_ON, 1); - // Validate. - $this->assert_only_one_filter_globally('filter/name', TEXTFILTER_ON); - } - - public function test_set_filter_globally_off() { - // Setup fixture. - // Exercise SUT. - filter_set_global_state('filter/name', TEXTFILTER_OFF, 1); - // Validate. - $this->assert_only_one_filter_globally('filter/name', TEXTFILTER_OFF); - } - - public function test_set_filter_globally_disabled() { - // Setup fixture. - // Exercise SUT. - filter_set_global_state('filter/name', TEXTFILTER_DISABLED, 1); - // Validate. - $this->assert_only_one_filter_globally('filter/name', TEXTFILTER_DISABLED); - } - - public function test_global_config_exception_on_invalid_state() { - // Setup fixture. - // Set expectation. - $this->expectException(); - // Exercise SUT. - filter_set_global_state('filter/name', 0, 1); - } - - public function test_set_no_sortorder_clash() { - // Setup fixture. - // Exercise SUT. - filter_set_global_state('filter/one', TEXTFILTER_DISABLED, 1); - filter_set_global_state('filter/two', TEXTFILTER_DISABLED, 1); - // Validate - should have pushed other filters down. - $this->assert_global_sort_order(array('filter/two', 'filter/one')); - } - - public function test_auto_sort_order_disabled() { - // Setup fixture. - // Exercise SUT. - filter_set_global_state('filter/one', TEXTFILTER_DISABLED); - filter_set_global_state('filter/two', TEXTFILTER_DISABLED); - // Validate. - $this->assert_global_sort_order(array('filter/one', 'filter/two')); - } - - public function test_auto_sort_order_enabled() { - // Setup fixture. - // Exercise SUT. - filter_set_global_state('filter/one', TEXTFILTER_ON); - filter_set_global_state('filter/two', TEXTFILTER_OFF); - // Validate. - $this->assert_global_sort_order(array('filter/one', 'filter/two')); - } - - public function test_auto_sort_order_mixed() { - // Setup fixture. - // Exercise SUT. - filter_set_global_state('filter/0', TEXTFILTER_DISABLED); - filter_set_global_state('filter/1', TEXTFILTER_ON); - filter_set_global_state('filter/2', TEXTFILTER_DISABLED); - filter_set_global_state('filter/3', TEXTFILTER_OFF); - // Validate. - $this->assert_global_sort_order(array('filter/1', 'filter/3', 'filter/0', 'filter/2')); - } - - public function test_update_existing_dont_duplicate() { - // Setup fixture. - // Exercise SUT. - filter_set_global_state('filter/name', TEXTFILTER_ON); - filter_set_global_state('filter/name', TEXTFILTER_OFF); - // Validate. - $this->assert_only_one_filter_globally('filter/name', TEXTFILTER_OFF); - } - - public function test_sort_order_not_too_low() { - // Setup fixture. - filter_set_global_state('filter/1', TEXTFILTER_ON); - // Set expectation. - $this->expectException(); - // Exercise SUT. - filter_set_global_state('filter/2', TEXTFILTER_ON, 0); - } - - public function test_sort_order_not_too_high() { - // Setup fixture. - filter_set_global_state('filter/1', TEXTFILTER_ON); - // Set expectation. - $this->expectException(); - // Exercise SUT. - filter_set_global_state('filter/2', TEXTFILTER_ON, 3); - } - - public function test_update_reorder_down() { - // Setup fixture. - filter_set_global_state('filter/1', TEXTFILTER_ON); - filter_set_global_state('filter/2', TEXTFILTER_ON); - filter_set_global_state('filter/3', TEXTFILTER_ON); - // Exercise SUT. - filter_set_global_state('filter/2', TEXTFILTER_ON, 1); - // Validate. - $this->assert_global_sort_order(array('filter/2', 'filter/1', 'filter/3')); - } - - public function test_update_reorder_up() { - // Setup fixture. - filter_set_global_state('filter/1', TEXTFILTER_ON); - filter_set_global_state('filter/2', TEXTFILTER_ON); - filter_set_global_state('filter/3', TEXTFILTER_ON); - filter_set_global_state('filter/4', TEXTFILTER_ON); - // Exercise SUT. - filter_set_global_state('filter/2', TEXTFILTER_ON, 3); - // Validate. - $this->assert_global_sort_order(array('filter/1', 'filter/3', 'filter/2', 'filter/4')); - } - - public function test_auto_sort_order_change_to_enabled() { - // Setup fixture. - filter_set_global_state('filter/1', TEXTFILTER_ON); - filter_set_global_state('filter/2', TEXTFILTER_DISABLED); - filter_set_global_state('filter/3', TEXTFILTER_DISABLED); - // Exercise SUT. - filter_set_global_state('filter/3', TEXTFILTER_ON); - // Validate. - $this->assert_global_sort_order(array('filter/1', 'filter/3', 'filter/2')); - } - - public function test_auto_sort_order_change_to_disabled() { - // Setup fixture. - filter_set_global_state('filter/1', TEXTFILTER_ON); - filter_set_global_state('filter/2', TEXTFILTER_ON); - filter_set_global_state('filter/3', TEXTFILTER_DISABLED); - // Exercise SUT. - filter_set_global_state('filter/1', TEXTFILTER_DISABLED); - // Validate. - $this->assert_global_sort_order(array('filter/2', 'filter/1', 'filter/3')); - } - - public function test_filter_get_global_states() { - // Setup fixture. - filter_set_global_state('filter/1', TEXTFILTER_ON); - filter_set_global_state('filter/2', TEXTFILTER_OFF); - filter_set_global_state('filter/3', TEXTFILTER_DISABLED); - // Exercise SUT. - $filters = filter_get_global_states(); - // Validate. - $this->assertEqual(array( - 'filter/1' => (object) array('filter' => 'filter/1', 'active' => TEXTFILTER_ON, 'sortorder' => 1), - 'filter/2' => (object) array('filter' => 'filter/2', 'active' => TEXTFILTER_OFF, 'sortorder' => 2), - 'filter/3' => (object) array('filter' => 'filter/3', 'active' => TEXTFILTER_DISABLED, 'sortorder' => 3) - ), $filters); - } -} - -/** - * Test functions that affect filter_active table with contextid = $syscontextid. - */ -class filter_active_local_test extends UnitTestCaseUsingDatabase { - public function setUp() { - parent::setUp(); - - // Create the table we need and switch to test DB. - $this->create_test_table('filter_active', 'lib'); - $this->switch_to_test_db(); - } - - private function assert_only_one_local_setting($filter, $contextid, $state) { - $recs = $this->testdb->get_records('filter_active'); - $this->assertEqual(1, count($recs), 'More than one record returned %s.'); - $rec = reset($recs); - $expectedrec = new stdClass; - $expectedrec->filter = $filter; - $expectedrec->contextid = $contextid; - $expectedrec->active = $state; - $this->assert(new CheckSpecifiedFieldsExpectation($expectedrec), $rec); - } - - private function assert_no_local_setting() { - $this->assertEqual(0, $this->testdb->count_records('filter_active')); - } - - public function test_local_on() { - // Exercise SUT. - filter_set_local_state('filter/name', 123, TEXTFILTER_ON); - // Validate. - $this->assert_only_one_local_setting('filter/name', 123, TEXTFILTER_ON); - } - - public function test_local_off() { - // Exercise SUT. - filter_set_local_state('filter/name', 123, TEXTFILTER_OFF); - // Validate. - $this->assert_only_one_local_setting('filter/name', 123, TEXTFILTER_OFF); - } - - public function test_local_inherit() { - global $DB; - // Exercise SUT. - filter_set_local_state('filter/name', 123, TEXTFILTER_INHERIT); - // Validate. - $this->assert_no_local_setting(); - } - - public function test_local_invalid_state_throws_exception() { - // Set expectation. - $this->expectException(); - // Exercise SUT. - filter_set_local_state('filter/name', 123, -9999); - } - - public function test_throws_exception_when_setting_global() { - // Set expectation. - $this->expectException(); - // Exercise SUT. - filter_set_local_state('filter/name', get_context_instance(CONTEXT_SYSTEM)->id, TEXTFILTER_INHERIT); - } - - public function test_local_inherit_deletes_existing() { - global $DB; - // Setup fixture. - filter_set_local_state('filter/name', 123, TEXTFILTER_INHERIT); - // Exercise SUT. - filter_set_local_state('filter/name', 123, TEXTFILTER_INHERIT); - // Validate. - $this->assert_no_local_setting(); - } -} - -/** - * Test functions that use just the filter_config table. - */ -class filter_config_test extends UnitTestCaseUsingDatabase { - public function setUp() { - parent::setUp(); - - // Create the table we need and switch to test DB. - $this->create_test_table('filter_config', 'lib'); - $this->switch_to_test_db(); - } - - private function assert_only_one_config($filter, $context, $name, $value) { - $recs = $this->testdb->get_records('filter_config'); - $this->assertEqual(1, count($recs), 'More than one record returned %s.'); - $rec = reset($recs); - $expectedrec = new stdClass; - $expectedrec->filter = $filter; - $expectedrec->contextid = $context; - $expectedrec->name = $name; - $expectedrec->value = $value; - $this->assert(new CheckSpecifiedFieldsExpectation($expectedrec), $rec); - } - - public function test_set_new_config() { - // Exercise SUT. - filter_set_local_config('filter/name', 123, 'settingname', 'An arbitrary value'); - // Validate. - $this->assert_only_one_config('filter/name', 123, 'settingname', 'An arbitrary value'); - } - - public function test_update_existing_config() { - // Setup fixture. - filter_set_local_config('filter/name', 123, 'settingname', 'An arbitrary value'); - // Exercise SUT. - filter_set_local_config('filter/name', 123, 'settingname', 'A changed value'); - // Validate. - $this->assert_only_one_config('filter/name', 123, 'settingname', 'A changed value'); - } - - public function test_filter_get_local_config() { - // Setup fixture. - filter_set_local_config('filter/name', 123, 'setting1', 'An arbitrary value'); - filter_set_local_config('filter/name', 123, 'setting2', 'Another arbitrary value'); - filter_set_local_config('filter/name', 122, 'settingname', 'Value from another context'); - filter_set_local_config('filter/other', 123, 'settingname', 'Someone else\'s value'); - // Exercise SUT. - $config = filter_get_local_config('filter/name', 123); - // Validate. - $this->assertEqual(array('setting1' => 'An arbitrary value', 'setting2' => 'Another arbitrary value'), $config); - } -} - -class filter_get_active_available_in_context_test extends UnitTestCaseUsingDatabase { - private $syscontext; - private $childcontext; - private $childcontext2; - - public function setUp() { - parent::setUp(); - - // Create the table we need and switch to test DB. - $this->create_test_tables(array('filter_active', 'filter_config', 'context', 'course_categories', 'course'), 'lib'); - $this->switch_to_test_db(); - // Nasty hack, recreate the system context record (the accesslib API does not allow to create it easily) - $this->create_system_context_record(); - // Reset all caches - accesslib_clear_all_caches_for_unit_testing(); - - $this->syscontext = get_context_instance(CONTEXT_SYSTEM); - - // Set up a child context. - $cat = new stdClass(); - $cat->name = 'testcategory'; - $cat->parent = 0; - $cat->depth = 1; - $cat->sortorder = 100; - $cat->timemodified = time(); - $catid = $this->testdb->insert_record('course_categories', $cat); - $this->testdb->set_field('course_categories', 'path', '/' . $catid, array('id' => $catid)); - $this->childcontext = context_coursecat::instance($catid); - - // Set up a grandchild context. - $course = new stdClass(); - $course->fullname = 'testcourse'; - $course->shortname = 'tc'; - $course->summary = 'testcourse summary'; - $course->newsitems = 0; - $course->numsections = 1; - $course->category = $catid; - $course->format = 'topics'; - $course->timecreated = time(); - $course->visible = 1; - $course->timemodified = $course->timecreated; - $courseid = $this->testdb->insert_record('course', $course); - $this->childcontext2 = context_course::instance($courseid); - } - - private function assert_filter_list($expectedfilters, $filters) { - $this->assert(new ArraysHaveSameValuesExpectation($expectedfilters), array_keys($filters)); - } - - public function test_globally_on_is_returned() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_ON); - // Exercise SUT. - $filters = filter_get_active_in_context($this->syscontext); - // Validate. - $this->assert_filter_list(array('filter/name'), $filters); - // Check no config returned correctly. - $this->assertEqual(array(), $filters['filter/name']); - } - - public function test_globally_off_not_returned() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_OFF); - // Exercise SUT. - $filters = filter_get_active_in_context($this->childcontext2); - // Validate. - $this->assert_filter_list(array(), $filters); - } - - public function test_globally_off_overridden() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_OFF); - filter_set_local_state('filter/name', $this->childcontext->id, TEXTFILTER_ON); - // Exercise SUT. - $filters = filter_get_active_in_context($this->childcontext2); - // Validate. - $this->assert_filter_list(array('filter/name'), $filters); - } - - public function test_globally_on_overridden() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_ON); - filter_set_local_state('filter/name', $this->childcontext->id, TEXTFILTER_OFF); - // Exercise SUT. - $filters = filter_get_active_in_context($this->childcontext2); - // Validate. - $this->assert_filter_list(array(), $filters); - } - - public function test_globally_disabled_not_overridden() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_DISABLED); - filter_set_local_state('filter/name', $this->childcontext->id, TEXTFILTER_ON); - // Exercise SUT. - $filters = filter_get_active_in_context($this->syscontext); - // Validate. - $this->assert_filter_list(array(), $filters); - } - - public function test_single_config_returned() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_ON); - filter_set_local_config('filter/name', $this->childcontext->id, 'settingname', 'A value'); - // Exercise SUT. - $filters = filter_get_active_in_context($this->childcontext); - // Validate. - $this->assertEqual(array('settingname' => 'A value'), $filters['filter/name']); - } - - public function test_multi_config_returned() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_ON); - filter_set_local_config('filter/name', $this->childcontext->id, 'settingname', 'A value'); - filter_set_local_config('filter/name', $this->childcontext->id, 'anothersettingname', 'Another value'); - // Exercise SUT. - $filters = filter_get_active_in_context($this->childcontext); - // Validate. - $this->assertEqual(array('settingname' => 'A value', 'anothersettingname' => 'Another value'), $filters['filter/name']); - } - - public function test_config_from_other_context_not_returned() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_ON); - filter_set_local_config('filter/name', $this->childcontext->id, 'settingname', 'A value'); - filter_set_local_config('filter/name', $this->childcontext2->id, 'anothersettingname', 'Another value'); - // Exercise SUT. - $filters = filter_get_active_in_context($this->childcontext2); - // Validate. - $this->assertEqual(array('anothersettingname' => 'Another value'), $filters['filter/name']); - } - - public function test_config_from_other_filter_not_returned() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_ON); - filter_set_local_config('filter/name', $this->childcontext->id, 'settingname', 'A value'); - filter_set_local_config('filter/other', $this->childcontext->id, 'anothersettingname', 'Another value'); - // Exercise SUT. - $filters = filter_get_active_in_context($this->childcontext); - // Validate. - $this->assertEqual(array('settingname' => 'A value'), $filters['filter/name']); - } - - protected function assert_one_available_filter($filter, $localstate, $inheritedstate, $filters) { - $this->assertEqual(1, count($filters), 'More than one record returned %s.'); - $rec = $filters[$filter]; - $expectedrec = new stdClass; - $expectedrec->filter = $filter; - $expectedrec->localstate = $localstate; - $expectedrec->inheritedstate = $inheritedstate; - $this->assert(new CheckSpecifiedFieldsExpectation($expectedrec), $rec); - } - - public function test_available_in_context_localoverride() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_ON); - filter_set_local_state('filter/name', $this->childcontext->id, TEXTFILTER_OFF); - // Exercise SUT. - $filters = filter_get_available_in_context($this->childcontext); - // Validate. - $this->assert_one_available_filter('filter/name', TEXTFILTER_OFF, TEXTFILTER_ON, $filters); - } - - public function test_available_in_context_nolocaloverride() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_ON); - filter_set_local_state('filter/name', $this->childcontext->id, TEXTFILTER_OFF); - // Exercise SUT. - $filters = filter_get_available_in_context($this->childcontext2); - // Validate. - $this->assert_one_available_filter('filter/name', TEXTFILTER_INHERIT, TEXTFILTER_OFF, $filters); - } - - public function test_available_in_context_disabled_not_returned() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_DISABLED); - filter_set_local_state('filter/name', $this->childcontext->id, TEXTFILTER_ON); - // Exercise SUT. - $filters = filter_get_available_in_context($this->childcontext); - // Validate. - $this->assertEqual(array(), $filters); - } - - public function test_available_in_context_exception_with_syscontext() { - // Set expectation. - $this->expectException(); - // Exercise SUT. - filter_get_available_in_context($this->syscontext); - } -} - -class filter_preload_activities_test extends UnitTestCaseUsingDatabase { - private $syscontext, $catcontext, $coursecontext, $activity1context, $activity2context; - - public function setUp() { - parent::setUp(); - - // Make sure accesslib has cached a sensible system context object - // before we switch to the test DB. - $this->syscontext = get_context_instance(CONTEXT_SYSTEM); - - // Create the table we need and switch to test DB. - $this->create_test_tables(array('filter_active', 'filter_config', 'context', - 'course', 'course_categories', 'course_modules', 'modules', 'course_sections', - 'course_modules_availability', 'grade_items', 'cache_text'), 'lib'); - $this->create_test_tables(array('label'), 'mod/label'); - $this->switch_to_test_db(); - // Nasty hack, recreate the system context record (the accesslib API does not allow to create it easily) - $this->create_system_context_record(); - // Reset all caches - accesslib_clear_all_caches_for_unit_testing(); - - $this->syscontext = get_context_instance(CONTEXT_SYSTEM); - - // Make the category - $cat = new stdClass(); - $cat->name = 'testcategory'; - $cat->parent = 0; - $cat->depth = 1; - $cat->sortorder = 100; - $cat->timemodified = time(); - $catid = $this->testdb->insert_record('course_categories', $cat); - $this->testdb->set_field('course_categories', 'path', '/' . $catid, array('id' => $catid)); - $this->catcontext = context_coursecat::instance($catid); - - // Make the course - $course = (object)array( - 'shortname' => 'TEST101'); - $courseid = $this->testdb->insert_record('course', $course); - $this->coursecontext = context_course::instance($courseid); - - // Set up section - $section = (object)array( - 'course' => $courseid); - $section->id = $this->testdb->insert_record('course_sections', $section); - - // Make course-modules - $mod = (object)array( - 'name' => 'label', - 'visible' => 1); - $mod->id = $this->testdb->insert_record('modules', $mod); - $label1 = (object)array( - 'course' => $courseid, - 'intro' => 'Intro 1', - 'name' => 'Label 1'); - $label1->id = $this->testdb->insert_record('label', $label1); - $cm1 = (object)array( - 'course' => $courseid, - 'section' => $section->id, - 'module' => $mod->id, - 'instance' => $label1->id); - $cm1->id = $this->testdb->insert_record('course_modules', $cm1); - $this->activity1context = context_module::instance($cm1->id); - - $label2 = (object)array( - 'course' => $courseid, - 'intro' => 'Intro 2', - 'name' => 'Label 2'); - $label2->id = $this->testdb->insert_record('label', $label2); - $cm2 = (object)array( - 'course' => $courseid, - 'section' => $section->id, - 'module' => $mod->id, - 'instance' => $label2->id); - $cm2->id = $this->testdb->insert_record('course_modules', $cm2); - $this->testdb->set_field('course_sections', 'sequence', - "$cm1->id,$cm2->id", array('id' => $section->id)); - $this->activity2context = context_module::instance($cm2->id); - } - - private function assert_matches($modinfo) { - global $FILTERLIB_PRIVATE; - - // Use preload cache... - $FILTERLIB_PRIVATE = new stdClass; - filter_preload_activities($modinfo); - - // Get data and check no queries are made - $before = $this->testdb->perf_get_reads(); - $plfilters1 = filter_get_active_in_context($this->activity1context); - $plfilters2 = filter_get_active_in_context($this->activity2context); - $after = $this->testdb->perf_get_reads(); - $this->assertEqual($before, $after); - - // Repeat without cache and check it makes queries now - $FILTERLIB_PRIVATE = new stdClass; - $before = $this->testdb->perf_get_reads(); - $filters1 = filter_get_active_in_context($this->activity1context); - $filters2 = filter_get_active_in_context($this->activity2context); - $after = $this->testdb->perf_get_reads(); - $this->assertTrue($after > $before); - - // Check they match - $this->assertEqual($plfilters1, $filters1); - $this->assertEqual($plfilters2, $filters2); - } - - public function test_preload() { - global $FILTERLIB_PRIVATE; - - // Get course and modinfo - $course = $this->testdb->get_record('course', array('id'=>1)); - $modinfo = new course_modinfo($course, 1); - - // Note: All the tests in this function check that the result from the - // preloaded cache is the same as the result from calling the standard - // function without preloading. - - // Initially, check with no filters enabled - $this->assert_matches($modinfo); - - // Enable filter globally, check - filter_set_global_state('filter/name', TEXTFILTER_ON); - $this->assert_matches($modinfo); - - // Disable for activity 2 - filter_set_local_state('filter/name', $this->activity2context->id, TEXTFILTER_OFF); - $this->assert_matches($modinfo); - - // Disable at category - filter_set_local_state('filter/name', $this->catcontext->id, TEXTFILTER_OFF); - $this->assert_matches($modinfo); - - // Enable for activity 1 - filter_set_local_state('filter/name', $this->activity1context->id, TEXTFILTER_ON); - $this->assert_matches($modinfo); - - // Disable globally - filter_set_global_state('filter/name', TEXTFILTER_DISABLED); - $this->assert_matches($modinfo); - - // Add another 2 filters - filter_set_global_state('filter/frog', TEXTFILTER_ON); - filter_set_global_state('filter/zombie', TEXTFILTER_ON); - $this->assert_matches($modinfo); - - // Disable random one of these in each context - filter_set_local_state('filter/zombie', $this->activity1context->id, TEXTFILTER_OFF); - filter_set_local_state('filter/frog', $this->activity2context->id, TEXTFILTER_OFF); - $this->assert_matches($modinfo); - - // Now do some filter options - filter_set_local_config('filter/name', $this->activity1context->id, 'a', 'x'); - filter_set_local_config('filter/zombie', $this->activity1context->id, 'a', 'y'); - filter_set_local_config('filter/frog', $this->activity1context->id, 'a', 'z'); - // These last two don't do anything as they are not at final level but I - // thought it would be good to have that verified in test - filter_set_local_config('filter/frog', $this->coursecontext->id, 'q', 'x'); - filter_set_local_config('filter/frog', $this->catcontext->id, 'q', 'z'); - $this->assert_matches($modinfo); - } -} - -class filter_delete_config_test extends UnitTestCaseUsingDatabase { - protected $syscontext; - - public function setUp() { - parent::setUp(); - - $this->syscontext = get_context_instance(CONTEXT_SYSTEM); - - // Create the table we need and switch to test DB. - $this->create_test_tables(array('filter_active', 'filter_config', 'config', 'config_plugins'), 'lib'); - $this->switch_to_test_db(); - } - - public function test_filter_delete_all_for_filter() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_ON); - filter_set_global_state('filter/other', TEXTFILTER_ON); - filter_set_local_config('filter/name', $this->syscontext->id, 'settingname', 'A value'); - filter_set_local_config('filter/other', $this->syscontext->id, 'settingname', 'Other value'); - set_config('configname', 'A config value', 'filter_name'); - set_config('configname', 'Other config value', 'filter_other'); - // Exercise SUT. - filter_delete_all_for_filter('filter/name'); - // Validate. - $this->assertEqual(1, $this->testdb->count_records('filter_active')); - $this->assertTrue($this->testdb->record_exists('filter_active', array('filter' => 'filter/other'))); - $this->assertEqual(1, $this->testdb->count_records('filter_config')); - $this->assertTrue($this->testdb->record_exists('filter_config', array('filter' => 'filter/other'))); - $expectedconfig = new stdClass; - $expectedconfig->configname = 'Other config value'; - $this->assertEqual($expectedconfig, get_config('filter_other')); - $this->assertIdentical(get_config('filter_name'), new stdClass()); - } - - public function test_filter_delete_all_for_context() { - // Setup fixture. - filter_set_global_state('filter/name', TEXTFILTER_ON); - filter_set_local_state('filter/name', 123, TEXTFILTER_OFF); - filter_set_local_config('filter/name', 123, 'settingname', 'A value'); - filter_set_local_config('filter/other', 123, 'settingname', 'Other value'); - filter_set_local_config('filter/other', 122, 'settingname', 'Other value'); - // Exercise SUT. - filter_delete_all_for_context(123); - // Validate. - $this->assertEqual(1, $this->testdb->count_records('filter_active')); - $this->assertTrue($this->testdb->record_exists('filter_active', array('contextid' => $this->syscontext->id))); - $this->assertEqual(1, $this->testdb->count_records('filter_config')); - $this->assertTrue($this->testdb->record_exists('filter_config', array('filter' => 'filter/other'))); - } -} - -class filter_filter_set_applies_to_strings extends UnitTestCaseUsingDatabase { - protected $origcfgstringfilters; - protected $origcfgfilterall; - - public function setUp() { - global $CFG; - parent::setUp(); - - // Create the table we need and switch to test DB. - $this->create_test_table('config', 'lib'); - $this->switch_to_test_db(); - - // Store original $CFG; - $this->origcfgstringfilters = $CFG->stringfilters; - $this->origcfgfilterall = $CFG->filterall; - } - - public function tearDown() { - global $CFG; - $CFG->stringfilters = $this->origcfgstringfilters; - $CFG->filterall = $this->origcfgfilterall; - - parent::tearDown(); - } - - public function test_set() { - global $CFG; - // Setup fixture. - $CFG->filterall = 0; - $CFG->stringfilters = ''; - // Exercise SUT. - filter_set_applies_to_strings('filter/name', true); - // Validate. - $this->assertEqual('filter/name', $CFG->stringfilters); - $this->assertTrue($CFG->filterall); - } - - public function test_unset_to_empty() { - global $CFG; - // Setup fixture. - $CFG->filterall = 1; - $CFG->stringfilters = 'filter/name'; - // Exercise SUT. - filter_set_applies_to_strings('filter/name', false); - // Validate. - $this->assertEqual('', $CFG->stringfilters); - $this->assertFalse($CFG->filterall); - } - - public function test_unset_multi() { - global $CFG; - // Setup fixture. - $CFG->filterall = 1; - $CFG->stringfilters = 'filter/name,filter/other'; - // Exercise SUT. - filter_set_applies_to_strings('filter/name', false); - // Validate. - $this->assertEqual('filter/other', $CFG->stringfilters); - $this->assertTrue($CFG->filterall); - } -} diff --git a/lib/simpletest/testformslib.php b/lib/simpletest/testformslib.php deleted file mode 100644 index 7b41c302eb0..00000000000 --- a/lib/simpletest/testformslib.php +++ /dev/null @@ -1,223 +0,0 @@ -. - - -/** - * Unit tests for /lib/formslib.php. - * - * @package file - * @copyright 2011 Sam Hemelryk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -if (!defined('MOODLE_INTERNAL')) { - die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page -} - -require_once($CFG->libdir . '/formslib.php'); -require_once($CFG->libdir . '/form/radio.php'); -require_once($CFG->libdir . '/form/select.php'); -require_once($CFG->libdir . '/form/text.php'); - -class formslib_test extends UnitTestCase { - - public function test_require_rule() { - global $CFG; - - $strictformsrequired = false; - if (!empty($CFG->strictformsrequired)) { - $strictformsrequired = $CFG->strictformsrequired; - } - - $rule = new MoodleQuickForm_Rule_Required(); - - // First run the tests with strictformsrequired off - $CFG->strictformsrequired = false; - // Passes - $this->assertTrue($rule->validate('Something')); - $this->assertTrue($rule->validate("Something\nmore")); - $this->assertTrue($rule->validate("\nmore")); - $this->assertTrue($rule->validate(" more ")); - $this->assertTrue($rule->validate("0")); - $this->assertTrue($rule->validate(0)); - $this->assertTrue($rule->validate(true)); - $this->assertTrue($rule->validate(' ')); - $this->assertTrue($rule->validate(' ')); - $this->assertTrue($rule->validate("\t")); - $this->assertTrue($rule->validate("\n")); - $this->assertTrue($rule->validate("\r")); - $this->assertTrue($rule->validate("\r\n")); - $this->assertTrue($rule->validate(" \t \n \r ")); - $this->assertTrue($rule->validate('

')); - $this->assertTrue($rule->validate('

')); - $this->assertTrue($rule->validate('

x

')); - $this->assertTrue($rule->validate('smile')); - $this->assertTrue($rule->validate('smile')); - $this->assertTrue($rule->validate('smile')); - $this->assertTrue($rule->validate('
')); - $this->assertTrue($rule->validate('
')); - $this->assertTrue($rule->validate('
')); - $this->assertTrue($rule->validate('
')); - $this->assertTrue($rule->validate('
')); - $this->assertTrue($rule->validate('
')); - $this->assertTrue($rule->validate('
')); - $this->assertTrue($rule->validate(' ')); - // Fails - $this->assertFalse($rule->validate('')); - $this->assertFalse($rule->validate(false)); - $this->assertFalse($rule->validate(null)); - - // Now run the same tests with it on to make sure things work as expected - $CFG->strictformsrequired = true; - // Passes - $this->assertTrue($rule->validate('Something')); - $this->assertTrue($rule->validate("Something\nmore")); - $this->assertTrue($rule->validate("\nmore")); - $this->assertTrue($rule->validate(" more ")); - $this->assertTrue($rule->validate("0")); - $this->assertTrue($rule->validate(0)); - $this->assertTrue($rule->validate(true)); - $this->assertTrue($rule->validate('

x

')); - $this->assertTrue($rule->validate('smile')); - $this->assertTrue($rule->validate('smile')); - $this->assertTrue($rule->validate('smile')); - $this->assertTrue($rule->validate('
')); - $this->assertTrue($rule->validate('
')); - $this->assertTrue($rule->validate('
')); - $this->assertTrue($rule->validate('
')); - // Fails - $this->assertFalse($rule->validate(' ')); - $this->assertFalse($rule->validate(' ')); - $this->assertFalse($rule->validate("\t")); - $this->assertFalse($rule->validate("\n")); - $this->assertFalse($rule->validate("\r")); - $this->assertFalse($rule->validate("\r\n")); - $this->assertFalse($rule->validate(" \t \n \r ")); - $this->assertFalse($rule->validate('

')); - $this->assertFalse($rule->validate('

')); - $this->assertFalse($rule->validate('
')); - $this->assertFalse($rule->validate('
')); - $this->assertFalse($rule->validate('
')); - $this->assertFalse($rule->validate(' ')); - $this->assertFalse($rule->validate('')); - $this->assertFalse($rule->validate(false)); - $this->assertFalse($rule->validate(null)); - - $CFG->strictformsrequired = $strictformsrequired; - } - - public function test_generate_id_select() { - $el = new MoodleQuickForm_select('choose_one', 'Choose one', - array(1 => 'One', '2' => 'Two')); - $el->_generateId(); - $this->assertEqual('id_choose_one', $el->getAttribute('id')); - } - - public function test_generate_id_like_repeat() { - $el = new MoodleQuickForm_text('text[7]', 'Type something'); - $el->_generateId(); - $this->assertEqual('id_text_7', $el->getAttribute('id')); - } - - public function test_can_manually_set_id() { - $el = new MoodleQuickForm_text('elementname', 'Type something', - array('id' => 'customelementid')); - $el->_generateId(); - $this->assertEqual('customelementid', $el->getAttribute('id')); - } - - public function test_generate_id_radio() { - $el = new MoodleQuickForm_radio('radio', 'Label', 'Choice label', 'choice_value'); - $el->_generateId(); - $this->assertEqual('id_radio_choice_value', $el->getAttribute('id')); - } - - public function test_radio_can_manually_set_id() { - $el = new MoodleQuickForm_radio('radio2', 'Label', 'Choice label', 'choice_value', - array('id' => 'customelementid2')); - $el->_generateId(); - $this->assertEqual('customelementid2', $el->getAttribute('id')); - } - - public function test_generate_id_radio_like_repeat() { - $el = new MoodleQuickForm_radio('repeatradio[2]', 'Label', 'Choice label', 'val'); - $el->_generateId(); - $this->assertEqual('id_repeatradio_2_val', $el->getAttribute('id')); - } - - public function test_rendering() { - $form = new formslib_test_form(); - ob_start(); - $form->display(); - $html = ob_get_clean(); - - $this->assert(new ContainsTagWithAttributes('select', array( - 'id' => 'id_choose_one', 'name' => 'choose_one')), $html); - - $this->assert(new ContainsTagWithAttributes('input', array( - 'type' => 'text', 'id' => 'id_text_0', 'name' => 'text[0]')), $html); - - $this->assert(new ContainsTagWithAttributes('input', array( - 'type' => 'text', 'id' => 'id_text_1', 'name' => 'text[1]')), $html); - - $this->assert(new ContainsTagWithAttributes('input', array( - 'type' => 'radio', 'id' => 'id_radio_choice_value', - 'name' => 'radio', 'value' => 'choice_value')), $html); - - $this->assert(new ContainsTagWithAttributes('input', array( - 'type' => 'radio', 'id' => 'customelementid2', 'name' => 'radio2')), $html); - - $this->assert(new ContainsTagWithAttributes('input', array( - 'type' => 'radio', 'id' => 'id_repeatradio_0_2', - 'name' => 'repeatradio[0]', 'value' => '2')), $html); - - $this->assert(new ContainsTagWithAttributes('input', array( - 'type' => 'radio', 'id' => 'id_repeatradio_2_1', - 'name' => 'repeatradio[2]', 'value' => '1')), $html); - - $this->assert(new ContainsTagWithAttributes('input', array( - 'type' => 'radio', 'id' => 'id_repeatradio_2_2', - 'name' => 'repeatradio[2]', 'value' => '2')), $html); - } -} - - -/** - * Test form to be used by {@link formslib_test::test_rendering()}. - */ -class formslib_test_form extends moodleform { - public function definition() { - $this->_form->addElement('select', 'choose_one', 'Choose one', - array(1 => 'One', '2' => 'Two')); - - $repeatels = array( - $this->_form->createElement('text', 'text', 'Type something') - ); - $this->repeat_elements($repeatels, 2, array(), 'numtexts', 'addtexts'); - - $this->_form->addElement('radio', 'radio', 'Label', 'Choice label', 'choice_value'); - - $this->_form->addElement('radio', 'radio2', 'Label', 'Choice label', 'choice_value', - array('id' => 'customelementid2')); - - $repeatels = array( - $this->_form->createElement('radio', 'repeatradio', 'Choose {no}', 'One', 1), - $this->_form->createElement('radio', 'repeatradio', 'Choose {no}', 'Two', 2), - ); - $this->repeat_elements($repeatels, 3, array(), 'numradios', 'addradios'); - } -} \ No newline at end of file diff --git a/lib/simpletest/testgradelib.php b/lib/simpletest/testgradelib.php deleted file mode 100644 index 60c5a8ebee5..00000000000 --- a/lib/simpletest/testgradelib.php +++ /dev/null @@ -1,46 +0,0 @@ -libdir.'/simpletest/fixtures/gradetest.php'); - -class gradelib_test extends grade_test { - function test_grade_get_grades() { - //TODO - } -} - - diff --git a/lib/simpletest/testhtml2text.php b/lib/simpletest/testhtml2text.php deleted file mode 100644 index 5ac56edc097..00000000000 --- a/lib/simpletest/testhtml2text.php +++ /dev/null @@ -1,147 +0,0 @@ -. - -/** - * Tests our html2text hacks - * - * Note: includes original tests from testweblib.php - * - * @package core - * @subpackage lib - * @copyright 2012 Petr Skoda {@link http://skodak.org} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - - -defined('MOODLE_INTERNAL') || die(); - -class html2text_test extends UnitTestCase { - - public static $includecoverage = array('lib/html2text.php'); - - /** - * ALT as image replacements - */ - public function test_images() { - $this->assertEqual('[edit]', html_to_text('edit')); - - $text = 'xxsome gifxx'; - $result = html_to_text($text, null, false, false); - $this->assertIdentical($result, 'xx[some gif]xx'); - } - - /** - * No magic quotes messing - */ - public function test_no_strip_slashes() { - $this->assertEqual('[\edit]', html_to_text('\edit')); - - $text = '\\magic\\quotes\\are\\\\horrible'; - $result = html_to_text($text, null, false, false); - $this->assertIdentical($result, $text); - } - - /** - * Textlib integration - */ - public function test_textlib() { - $text = 'Žluťoučký koníček'; - $result = html_to_text($text, null, false, false); - $this->assertIdentical($result, 'ŽLUŤOUČKÝ KONÍČEK'); - } - - /** - * Protect 0 - */ - public function test_zero() { - $text = '0'; - $result = html_to_text($text, null, false, false); - $this->assertIdentical($result, $text); - - $this->assertIdentical('0', html_to_text('0')); - } - - // ======= Standard html2text conversion features ======= - - /** - * Various invalid HTML typed by users that ignore html strict - **/ - public function test_invalid_html() { - $text = 'Gin & Tonic'; - $result = html_to_text($text, null, false, false); - $this->assertIdentical($result, $text); - - $text = 'Gin > Tonic'; - $result = html_to_text($text, null, false, false); - $this->assertIdentical($result, $text); - - $text = 'Gin < Tonic'; - $result = html_to_text($text, null, false, false); - $this->assertIdentical($result, $text); - } - - /** - * Basic text formatting. - */ - public function test_simple() { - $this->assertEqual("_Hello_ WORLD!", html_to_text('

Hello world!

')); - $this->assertEqual("All the WORLD’S a stage.\n\n-- William Shakespeare", html_to_text('

All the world’s a stage.

-- William Shakespeare

')); - $this->assertEqual("HELLO WORLD!\n\n", html_to_text('

Hello world!

')); - $this->assertEqual("Hello\nworld!", html_to_text('Hello
world!')); - } - - /** - * Test line wrapping - */ - public function test_text_nowrap() { - $long = "Here is a long string, more than 75 characters long, since by default html_to_text wraps text at 75 chars."; - $wrapped = "Here is a long string, more than 75 characters long, since by default\nhtml_to_text wraps text at 75 chars."; - $this->assertEqual($long, html_to_text($long, 0)); - $this->assertEqual($wrapped, html_to_text($long)); - } - - /** - * Whitespace removal - */ - public function test_trailing_whitespace() { - $this->assertEqual('With trailing whitespace and some more text', html_to_text("With trailing whitespace \nand some more text", 0)); - } - - /** - * PRE parsing - */ - public function test_html_to_text_pre_parsing_problem() { - $strorig = 'Consider the following function:
void FillMeUp(char* in_string) {'.
-            '
int i = 0;
while (in_string[i] != \'\0\') {
in_string[i] = \'X\';
i++;
}
'. - '}
What would happen if a non-terminated string were input to this function?

'; - - $strconv = 'Consider the following function: - -void FillMeUp(char* in_string) { - int i = 0; - while (in_string[i] != \'\0\') { - in_string[i] = \'X\'; - i++; - } -} -What would happen if a non-terminated string were input to this function? - -'; - - $this->assertIdentical($strconv, html_to_text($strorig)); - } -} - diff --git a/lib/simpletest/testhtmlpurifier.php b/lib/simpletest/testhtmlpurifier.php deleted file mode 100644 index 65725cbce29..00000000000 --- a/lib/simpletest/testhtmlpurifier.php +++ /dev/null @@ -1,255 +0,0 @@ -. - -/** - * Tests our HTMLPurifier hacks - * - * @package core - * @subpackage lib - * @copyright 2010 Petr Skoda {@link http://skodak.org} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - - -defined('MOODLE_INTERNAL') || die(); - -class htmlpurifier_test extends UnitTestCase { - - - public static $includecoverage = array('lib/htmlpurifier/HTMLPurifier.php'); - - private $cachetext = null; - - function setUp() { - global $CFG; - $this->cachetext = $CFG->cachetext; - $CFG->cachetext = 0; - } - - function tearDown() { - global $CFG; - $CFG->cachetext = $this->cachetext; - } - - /** - * Verify _blank target is allowed - * @return void - */ - public function test_allow_blank_target() { - $text = 'Some link'; - $result = format_text($text, FORMAT_HTML); - $this->assertIdentical($text, $result); - - $result = format_text('Some link', FORMAT_HTML); - $this->assertIdentical('Some link', $result); - } - - /** - * Verify our nolink tag accepted - * @return void - */ - public function test_nolink() { - // we can not use format text because nolink changes result - $text = '
no filters
'; - $result = purify_html($text, array()); - $this->assertIdentical($text, $result); - - $text = 'xxxxx
xxx
'; - $result = purify_html($text, array()); - $this->assertIdentical($text, $result); - } - - /** - * Verify our tex tag accepted - * @return void - */ - public function test_tex() { - $text = 'a+b=c'; - $result = purify_html($text, array()); - $this->assertIdentical($text, $result); - } - - /** - * Verify our algebra tag accepted - * @return void - */ - public function test_algebra() { - $text = 'a+b=c'; - $result = purify_html($text, array()); - $this->assertIdentical($text, $result); - } - - /** - * Verify our hacky multilang works - * @return void - */ - public function test_multilang() { - $text = 'hmmmhm'; - $result = purify_html($text, array()); - $this->assertIdentical($text, $result); - - $text = 'hmmmhm'; - $result = purify_html($text, array()); - $this->assertIdentical($text, $result); - - $text = 'hmmm'; - $result = purify_html($text, array()); - $this->assertNotIdentical($text, $result); - - // keep standard lang tags - - $text = 'asas'; - $result = purify_html($text, array()); - $this->assertIdentical($text, $result); - - $text = 'xxxxxx'; - $result = purify_html($text, array()); - $this->assertIdentical($text, $result); - } - - /** - * Tests the 'allowid' option for format_text. - */ - public function test_format_text_allowid() { - // Start off by not allowing ids (default) - $options = array( - 'nocache' => true - ); - $result = format_text('
Frog
', FORMAT_HTML, $options); - $this->assertIdentical('
Frog
', $result); - - // Now allow ids - $options['allowid'] = true; - $result = format_text('
Frog
', FORMAT_HTML, $options); - $this->assertIdentical('
Frog
', $result); - } - - /** - * Test if linebreaks kept unchanged. - */ - function test_line_breaking() { - $text = "\n\raa\rsss\nsss\r"; - $this->assertIdentical($text, purify_html($text)); - } - - /** - * Test fixing of strict problems. - */ - function test_tidy() { - $text = "

xx"; - $this->assertIdentical('

xx

', purify_html($text)); - - $text = "

xx

"; - $this->assertIdentical('

xx

', purify_html($text)); - - $text = "xx
"; - $this->assertIdentical('xx
', purify_html($text)); - } - - /** - * Test nesting - this used to cause problems in earlier versions - */ - function test_nested_lists() { - $text = "
  • One
    • Two
  • Three
"; - $this->assertIdentical($text, purify_html($text)); - } - - /** - * Test that XSS protection works, complete smoke tests are in htmlpurifier itself. - */ - function test_cleaning_nastiness() { - $text = "xx"; - $this->assertIdentical('xx', purify_html($text)); - - $text = '
xx
'; - $this->assertIdentical('
xx
', purify_html($text)); - - $text = '
xx
'; - $this->assertIdentical('
xx
', purify_html($text)); - - $text = 'xx'; - $this->assertIdentical('xx', purify_html($text)); - - $text = 'xx'; - $this->assertIdentical('xx', purify_html($text)); - - $text = 'xx'; - $this->assertIdentical('xx', purify_html($text)); - - $text = 'x
x'; - $this->assertIdentical('xx', purify_html($text)); - } - - /** - * Test internal function used for clean_text() speedup. - */ - function test_is_purify_html_necessary() { - // first our shortcuts - $text = ""; - $this->assertFalse(is_purify_html_necessary($text)); - $this->assertidentical($text, purify_html($text)); - - $text = "666"; - $this->assertFalse(is_purify_html_necessary($text)); - $this->assertidentical($text, purify_html($text)); - - $text = "abc\ndef \" ' "; - $this->assertFalse(is_purify_html_necessary($text)); - $this->assertidentical($text, purify_html($text)); - - $text = "abc\n

def

efg

hij

"; - $this->assertFalse(is_purify_html_necessary($text)); - $this->assertidentical($text, purify_html($text)); - - $text = "
abc\n

defefghi
j

"; - $this->assertFalse(is_purify_html_necessary($text)); - $this->assertidentical($text, purify_html($text)); - - // now failures - $text = " "; - $this->assertTrue(is_purify_html_necessary($text)); - - $text = "Gin & Tonic"; - $this->assertTrue(is_purify_html_necessary($text)); - - $text = "Gin > Tonic"; - $this->assertTrue(is_purify_html_necessary($text)); - - $text = "Gin < Tonic"; - $this->assertTrue(is_purify_html_necessary($text)); - - $text = "
abc
"; - $this->assertTrue(is_purify_html_necessary($text)); - - $text = "abc"; - $this->assertTrue(is_purify_html_necessary($text)); - - $text = "
abc"; - $this->assertTrue(is_purify_html_necessary($text)); - - $text = "

abc

"; - $this->assertTrue(is_purify_html_necessary($text)); - - $text = "

abc

"; - $this->assertTrue(is_purify_html_necessary($text)); - - $text = "

abc"; - $this->assertTrue(is_purify_html_necessary($text)); - - } -} - diff --git a/lib/simpletest/testhtmlwriter.php b/lib/simpletest/testhtmlwriter.php deleted file mode 100644 index b22c92c2307..00000000000 --- a/lib/simpletest/testhtmlwriter.php +++ /dev/null @@ -1,97 +0,0 @@ -. - - -/** - * Unit tests for the html_writer class. - * - * @package moodlecore - * @copyright 2010 Tim Hunt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -if (!defined('MOODLE_INTERNAL')) { - die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page -} - -global $CFG; - -require_once($CFG->libdir . '/outputcomponents.php'); - - -/** - * Unit tests for the html_writer class. - * - * @copyright 2010 Tim Hunt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class html_writer_test extends UnitTestCase { - - public static $includecoverage = array('lib/outputcomponents.php'); - - public function test_start_tag() { - $this->assertEqual('

', html_writer::start_tag('div')); - } - - public function test_start_tag_with_attr() { - $this->assertEqual('
', - html_writer::start_tag('div', array('class' => 'frog'))); - } - - public function test_start_tag_with_attrs() { - $this->assertEqual('
', - html_writer::start_tag('div', array('class' => 'frog', 'id' => 'mydiv'))); - } - - public function test_end_tag() { - $this->assertEqual('
', html_writer::end_tag('div')); - } - - public function test_empty_tag() { - $this->assertEqual('
', html_writer::empty_tag('br')); - } - - public function test_empty_tag_with_attrs() { - $this->assertEqual('', - html_writer::empty_tag('input', array('type' => 'submit', 'value' => 'frog'))); - } - - public function test_nonempty_tag_with_content() { - $this->assertEqual('
Hello world!
', - html_writer::nonempty_tag('div', 'Hello world!')); - } - - public function test_nonempty_tag_empty() { - $this->assertEqual('', - html_writer::nonempty_tag('div', '')); - } - - public function test_nonempty_tag_null() { - $this->assertEqual('', - html_writer::nonempty_tag('div', null)); - } - - public function test_nonempty_tag_zero() { - $this->assertEqual('
0
', - html_writer::nonempty_tag('div', 0, array('class' => 'score'))); - } - - public function test_nonempty_tag_zero_string() { - $this->assertEqual('
0
', - html_writer::nonempty_tag('div', '0', array('class' => 'score'))); - } -} diff --git a/lib/simpletest/testmathslib.php b/lib/simpletest/testmathslib.php deleted file mode 100644 index cac7bd077f7..00000000000 --- a/lib/simpletest/testmathslib.php +++ /dev/null @@ -1,221 +0,0 @@ -. -if (!defined('MOODLE_INTERNAL')) { - die('Direct access to this script is forbidden.');/// It must be included from a Moodle page -} - -require_once($CFG->libdir . '/mathslib.php'); - -/** - * Unit tests of mathslib wrapper and underlying EvalMath library. - * - * @author Petr Skoda (skodak) - * @version $Id$ - */ -class mathsslib_test extends UnitTestCase { - - public static $includecoverage = array('lib/mathslib.php'); - - /** - * Tests the basic formula evaluation - */ - public function test__basic() { - $formula = new calc_formula('=1+2'); - $res = $formula->evaluate(); - $this->assertEqual($res, 3, '3+1 is: %s'); - } - - /** - * Tests the formula params - */ - public function test__params() { - $formula = new calc_formula('=a+b+c', array('a'=>10, 'b'=>20, 'c'=>30)); - $res = $formula->evaluate(); - $this->assertEqual($res, 60, '10+20+30 is: %s'); - } - - /** - * Tests the changed params - */ - public function test__changing_params() { - $formula = new calc_formula('=a+b+c', array('a'=>10, 'b'=>20, 'c'=>30)); - $res = $formula->evaluate(); - $this->assertEqual($res, 60, '10+20+30 is: %s'); - $formula->set_params(array('a'=>1, 'b'=>2, 'c'=>3)); - $res = $formula->evaluate(); - $this->assertEqual($res, 6, 'changed params 1+2+3 is: %s'); - } - - /** - * Tests the spreadsheet emulation function in formula - */ - public function test__calc_function() { - $formula = new calc_formula('=sum(a, b, c)', array('a'=>10, 'b'=>20, 'c'=>30)); - $res = $formula->evaluate(); - $this->assertEqual($res, 60, 'sum(a, b, c) is: %s'); - } - - public function test_other_functions() { - $formula = new calc_formula('=average(1,2,3)'); - $this->assertEqual($formula->evaluate(), 2); - - $formula = new calc_formula('=mod(10,3)'); - $this->assertEqual($formula->evaluate(), 1); - - $formula = new calc_formula('=power(2,3)'); - $this->assertEqual($formula->evaluate(), 8); - } - - /** - * Tests the min and max functions - */ - public function test__minmax_function() { - $formula = new calc_formula('=min(a, b, c)', array('a'=>10, 'b'=>20, 'c'=>30)); - $res = $formula->evaluate(); - $this->assertEqual($res, 10, 'minimum is: %s'); - $formula = new calc_formula('=max(a, b, c)', array('a'=>10, 'b'=>20, 'c'=>30)); - $res = $formula->evaluate(); - $this->assertEqual($res, 30, 'maximum is: %s'); - } - - /** - * Tests special chars - */ - public function test__specialchars() { - $formula = new calc_formula('=gi1 + gi2 + gi11', array('gi1'=>10, 'gi2'=>20, 'gi11'=>30)); - $res = $formula->evaluate(); - $this->assertEqual($res, 60, 'sum is: %s'); - } - - /** - * Tests some slightly more complex expressions - */ - public function test__more_complex_expressions() { - $formula = new calc_formula('=pi() + a', array('a'=>10)); - $res = $formula->evaluate(); - $this->assertEqual($res, pi()+10); - $formula = new calc_formula('=pi()^a', array('a'=>10)); - $res = $formula->evaluate(); - $this->assertEqual($res, pow(pi(), 10)); - $formula = new calc_formula('=-8*(5/2)^2*(1-sqrt(4))-8'); - $res = $formula->evaluate(); - $this->assertEqual($res, -8*pow((5/2), 2)*(1-sqrt(4))-8); - } - - /** - * Tests some slightly more complex expressions - */ - public function test__error_handling() { - $formula = new calc_formula('=pi( + a', array('a'=>10)); - $res = $formula->evaluate(); - $this->assertEqual($res, false); - $this->assertEqual($formula->get_error(), - get_string('unexpectedoperator', 'mathslib', '+')); - - $formula = new calc_formula('=pi('); - $res = $formula->evaluate(); - $this->assertEqual($res, false); - $this->assertEqual($formula->get_error(), - get_string('expectingaclosingbracket', 'mathslib')); - - $formula = new calc_formula('=pi()^'); - $res = $formula->evaluate(); - $this->assertEqual($res, false); - $this->assertEqual($formula->get_error(), - get_string('operatorlacksoperand', 'mathslib', '^')); - - } - - public function test_rounding_function() { - $formula = new calc_formula('=round(2.5)'); - $this->assertEqual($formula->evaluate(), 3); - - $formula = new calc_formula('=round(1.5)'); - $this->assertEqual($formula->evaluate(), 2); - - $formula = new calc_formula('=round(-1.49)'); - $this->assertEqual($formula->evaluate(), -1); - - $formula = new calc_formula('=round(-2.49)'); - $this->assertEqual($formula->evaluate(), -2); - - $formula = new calc_formula('=round(-1.5)'); - $this->assertEqual($formula->evaluate(), -2); - - $formula = new calc_formula('=round(-2.5)'); - $this->assertEqual($formula->evaluate(), -3); - - $formula = new calc_formula('=ceil(2.5)'); - $this->assertEqual($formula->evaluate(), 3); - - $formula = new calc_formula('=ceil(1.5)'); - $this->assertEqual($formula->evaluate(), 2); - - $formula = new calc_formula('=ceil(-1.49)'); - $this->assertEqual($formula->evaluate(), -1); - - $formula = new calc_formula('=ceil(-2.49)'); - $this->assertEqual($formula->evaluate(), -2); - - $formula = new calc_formula('=ceil(-1.5)'); - $this->assertEqual($formula->evaluate(), -1); - - $formula = new calc_formula('=ceil(-2.5)'); - $this->assertEqual($formula->evaluate(), -2); - - $formula = new calc_formula('=floor(2.5)'); - $this->assertEqual($formula->evaluate(), 2); - - $formula = new calc_formula('=floor(1.5)'); - $this->assertEqual($formula->evaluate(), 1); - - $formula = new calc_formula('=floor(-1.49)'); - $this->assertEqual($formula->evaluate(), -2); - - $formula = new calc_formula('=floor(-2.49)'); - $this->assertEqual($formula->evaluate(), -3); - - $formula = new calc_formula('=floor(-1.5)'); - $this->assertEqual($formula->evaluate(), -2); - - $formula = new calc_formula('=floor(-2.5)'); - $this->assertEqual($formula->evaluate(), -3); - - } - - public function test_scientific_notation() { - $formula = new calc_formula('=10e10'); - $this->assertWithinMargin($formula->evaluate(), 1e11, 1e11*1e-15); - - $formula = new calc_formula('=10e-10'); - $this->assertWithinMargin($formula->evaluate(), 1e-9, 1e11*1e-15); - - $formula = new calc_formula('=10e+10'); - $this->assertWithinMargin($formula->evaluate(), 1e11, 1e11*1e-15); - - $formula = new calc_formula('=10e10*5'); - $this->assertWithinMargin($formula->evaluate(), 5e11, 1e11*1e-15); - - $formula = new calc_formula('=10e10^2'); - $this->assertWithinMargin($formula->evaluate(), 1e22, 1e22*1e-15); - - } - - - -} - - diff --git a/lib/simpletest/testmoodlelib.php b/lib/simpletest/testmoodlelib.php deleted file mode 100644 index 3cc7e598e8e..00000000000 --- a/lib/simpletest/testmoodlelib.php +++ /dev/null @@ -1,1798 +0,0 @@ -libdir . '/moodlelib.php'); - -class moodlelib_test extends UnitTestCase { - - public static $includecoverage = array('lib/moodlelib.php'); - - var $user_agents = array( - 'MSIE' => array( - '5.0' => array('Windows 98' => 'Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)'), - '5.5' => array('Windows 2000' => 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)'), - '6.0' => array('Windows XP SP2' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'), - '7.0' => array('Windows XP SP2' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; YPC 3.0.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)'), - '8.0' => array('Windows Vista' => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)'), - '9.0' => array('Windows 7' => 'Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))'), - - ), - 'Firefox' => array( - '1.0.6' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6'), - '1.5' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; nl; rv:1.8) Gecko/20051107 Firefox/1.5'), - '1.5.0.1' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.0.1) Gecko/20060111 Firefox/1.5.0.1'), - '2.0' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1', - 'Ubuntu Linux AMD64' => 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1) Gecko/20060601 Firefox/2.0 (Ubuntu-edgy)'), - '3.0.6' => array('SUSE' => 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.6) Gecko/2009012700 SUSE/3.0.6-1.4 Firefox/3.0.6'), - ), - 'Safari' => array( - '312' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312'), - '412' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/412 (KHTML, like Gecko) Safari/412') - ), - 'Safari iOS' => array( - '528' => array('iPhone' => 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_1_2 like Mac OS X; cs-cz) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7D11 Safari/528.16'), - '533' => array('iPad' => 'Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5'), - ), - 'WebKit Android' => array( - '525' => array('G1 Phone' => 'Mozilla/5.0 (Linux; U; Android 1.1; en-gb; dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2 – G1 Phone'), - '530' => array('Nexus' => 'Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17 –Nexus'), - ), - 'Chrome' => array( - '8' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.215 Safari/534.10'), - ), - 'Opera' => array( - '8.51' => array('Windows XP' => 'Opera/8.51 (Windows NT 5.1; U; en)'), - '9.0' => array('Windows XP' => 'Opera/9.0 (Windows NT 5.1; U; en)', - 'Debian Linux' => 'Opera/9.01 (X11; Linux i686; U; en)') - ) - ); - - function test_cleanremoteaddr() { - //IPv4 - $this->assertEqual(cleanremoteaddr('1023.121.234.1'), null); - $this->assertEqual(cleanremoteaddr('123.121.234.01 '), '123.121.234.1'); - - //IPv6 - $this->assertEqual(cleanremoteaddr('0:0:0:0:0:0:0:0:0'), null); - $this->assertEqual(cleanremoteaddr('0:0:0:0:0:0:0:abh'), null); - $this->assertEqual(cleanremoteaddr('0:0:0:::0:0:1'), null); - $this->assertEqual(cleanremoteaddr('0:0:0:0:0:0:0:0', true), '::'); - $this->assertEqual(cleanremoteaddr('0:0:0:0:0:0:1:1', true), '::1:1'); - $this->assertEqual(cleanremoteaddr('abcd:00ef:0:0:0:0:0:0', true), 'abcd:ef::'); - $this->assertEqual(cleanremoteaddr('1:0:0:0:0:0:0:1', true), '1::1'); - $this->assertEqual(cleanremoteaddr('::10:1', false), '0:0:0:0:0:0:10:1'); - $this->assertEqual(cleanremoteaddr('01:1::', false), '1:1:0:0:0:0:0:0'); - $this->assertEqual(cleanremoteaddr('10::10', false), '10:0:0:0:0:0:0:10'); - $this->assertEqual(cleanremoteaddr('::ffff:192.168.1.1', true), '::ffff:c0a8:11'); - } - - function test_address_in_subnet() { - /// 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask) - $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.1/32')); - $this->assertFalse(address_in_subnet('123.121.23.1', '123.121.23.0/32')); - $this->assertTrue(address_in_subnet('10.10.10.100', '123.121.23.45/0')); - $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/24')); - $this->assertFalse(address_in_subnet('123.121.34.1', '123.121.234.0/24')); - $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/30')); - $this->assertFalse(address_in_subnet('123.121.23.8', '123.121.23.0/30')); - $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128')); - $this->assertFalse(address_in_subnet('bab:baba::baba', 'bab:baba::cece/128')); - $this->assertTrue(address_in_subnet('baba:baba::baba', 'cece:cece::cece/0')); - $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128')); - $this->assertTrue(address_in_subnet('baba:baba::00ba', 'baba:baba::/120')); - $this->assertFalse(address_in_subnet('baba:baba::aba', 'baba:baba::/120')); - $this->assertTrue(address_in_subnet('baba::baba:00ba', 'baba::baba:0/112')); - $this->assertFalse(address_in_subnet('baba::aba:00ba', 'baba::baba:0/112')); - $this->assertFalse(address_in_subnet('aba::baba:0000', 'baba::baba:0/112')); - - // fixed input - $this->assertTrue(address_in_subnet('123.121.23.1 ', ' 123.121.23.0 / 24')); - $this->assertTrue(address_in_subnet('::ffff:10.1.1.1', ' 0:0:0:000:0:ffff:a1:10 / 126')); - - // incorrect input - $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/-2')); - $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/64')); - $this->assertFalse(address_in_subnet('123.121.234.x', '123.121.234.1/24')); - $this->assertFalse(address_in_subnet('123.121.234.0', '123.121.234.xx/24')); - $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/xx0')); - $this->assertFalse(address_in_subnet('::1', '::aa:0/xx0')); - $this->assertFalse(address_in_subnet('::1', '::aa:0/-5')); - $this->assertFalse(address_in_subnet('::1', '::aa:0/130')); - $this->assertFalse(address_in_subnet('x:1', '::aa:0/130')); - $this->assertFalse(address_in_subnet('::1', '::ax:0/130')); - - - /// 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group) - $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12-14')); - $this->assertTrue(address_in_subnet('123.121.234.13', '123.121.234.12-14')); - $this->assertTrue(address_in_subnet('123.121.234.14', '123.121.234.12-14')); - $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.12-14')); - $this->assertFalse(address_in_subnet('123.121.234.20', '123.121.234.12-14')); - $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.234.12-14')); - $this->assertFalse(address_in_subnet('123.12.234.12', '123.121.234.12-14')); - $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba-babe')); - $this->assertTrue(address_in_subnet('baba:baba::babc', 'baba:baba::baba-babe')); - $this->assertTrue(address_in_subnet('baba:baba::babe', 'baba:baba::baba-babe')); - $this->assertFalse(address_in_subnet('bab:baba::bab0', 'bab:baba::baba-babe')); - $this->assertFalse(address_in_subnet('bab:baba::babf', 'bab:baba::baba-babe')); - $this->assertFalse(address_in_subnet('bab:baba::bfbe', 'bab:baba::baba-babe')); - $this->assertFalse(address_in_subnet('bfb:baba::babe', 'bab:baba::baba-babe')); - - // fixed input - $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12 - 14 ')); - $this->assertTrue(address_in_subnet('bab:baba::babe', 'bab:baba::baba - babe ')); - - // incorrect input - $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-234.14')); - $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-256')); - $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12--256')); - - - /// 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-) - $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12')); - $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.23.13')); - $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.')); - $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234')); - $this->assertTrue(address_in_subnet('123.121.234.12', '123.121')); - $this->assertTrue(address_in_subnet('123.121.234.12', '123')); - $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234.')); - $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234')); - $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba::bab')); - $this->assertFalse(address_in_subnet('baba:baba::ba', 'baba:baba::bc')); - $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba')); - $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:')); - $this->assertFalse(address_in_subnet('bab:baba::bab', 'baba:')); - - - /// multiple subnets - $this->assertTrue(address_in_subnet('123.121.234.12', '::1/64, 124., 123.121.234.10-30')); - $this->assertTrue(address_in_subnet('124.121.234.12', '::1/64, 124., 123.121.234.10-30')); - $this->assertTrue(address_in_subnet('::2', '::1/64, 124., 123.121.234.10-30')); - $this->assertFalse(address_in_subnet('12.121.234.12', '::1/64, 124., 123.121.234.10-30')); - - - /// other incorrect input - $this->assertFalse(address_in_subnet('123.123.123.123', '')); - } - - /** - * Modifies $_SERVER['HTTP_USER_AGENT'] manually to check if check_browser_version - * works as expected. - */ - function test_check_browser_version() - { - global $CFG; - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari']['412']['Mac OS X']; - $this->assertTrue(check_browser_version('Safari')); - $this->assertTrue(check_browser_version('WebKit')); - $this->assertTrue(check_browser_version('Safari', '312')); - $this->assertFalse(check_browser_version('Safari', '500')); - $this->assertFalse(check_browser_version('Chrome')); - $this->assertFalse(check_browser_version('Safari iOS')); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari iOS']['528']['iPhone']; - $this->assertTrue(check_browser_version('Safari iOS')); - $this->assertTrue(check_browser_version('WebKit')); - $this->assertTrue(check_browser_version('Safari iOS', '527')); - $this->assertFalse(check_browser_version('Safari iOS', 590)); - $this->assertFalse(check_browser_version('Safari', '312')); - $this->assertFalse(check_browser_version('Safari', '500')); - $this->assertFalse(check_browser_version('Chrome')); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['WebKit Android']['530']['Nexus']; - $this->assertTrue(check_browser_version('WebKit')); - $this->assertTrue(check_browser_version('WebKit Android', '527')); - $this->assertFalse(check_browser_version('WebKit Android', 590)); - $this->assertFalse(check_browser_version('Safari')); - $this->assertFalse(check_browser_version('Chrome')); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Chrome']['8']['Mac OS X']; - $this->assertTrue(check_browser_version('Chrome')); - $this->assertTrue(check_browser_version('WebKit')); - $this->assertTrue(check_browser_version('Chrome', 8)); - $this->assertFalse(check_browser_version('Chrome', 10)); - $this->assertFalse(check_browser_version('Safari', '1')); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Opera']['9.0']['Windows XP']; - $this->assertTrue(check_browser_version('Opera')); - $this->assertTrue(check_browser_version('Opera', '8.0')); - $this->assertFalse(check_browser_version('Opera', '10.0')); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['6.0']['Windows XP SP2']; - $this->assertTrue(check_browser_version('MSIE')); - $this->assertTrue(check_browser_version('MSIE', '5.0')); - $this->assertFalse(check_browser_version('MSIE', '7.0')); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['5.0']['Windows 98']; - $this->assertFalse(check_browser_version('MSIE')); - $this->assertTrue(check_browser_version('MSIE', 0)); - $this->assertTrue(check_browser_version('MSIE', '5.0')); - $this->assertFalse(check_browser_version('MSIE', '7.0')); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['9.0']['Windows 7']; - $this->assertTrue(check_browser_version('MSIE')); - $this->assertTrue(check_browser_version('MSIE', 0)); - $this->assertTrue(check_browser_version('MSIE', '5.0')); - $this->assertTrue(check_browser_version('MSIE', '9.0')); - $this->assertFalse(check_browser_version('MSIE', '10')); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['2.0']['Windows XP']; - $this->assertTrue(check_browser_version('Firefox')); - $this->assertTrue(check_browser_version('Firefox', '1.5')); - $this->assertFalse(check_browser_version('Firefox', '3.0')); - } - - function test_get_browser_version_classes() { - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari']['412']['Mac OS X']; - $this->assertEqual(array('safari'), get_browser_version_classes()); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Chrome']['8']['Mac OS X']; - $this->assertEqual(array('safari'), get_browser_version_classes()); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari iOS']['528']['iPhone']; - $this->assertEqual(array('safari', 'ios'), get_browser_version_classes()); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['WebKit Android']['530']['Nexus']; - $this->assertEqual(array('safari', 'android'), get_browser_version_classes()); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Chrome']['8']['Mac OS X']; - $this->assertEqual(array('safari'), get_browser_version_classes()); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Opera']['9.0']['Windows XP']; - $this->assertEqual(array('opera'), get_browser_version_classes()); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['6.0']['Windows XP SP2']; - $this->assertEqual(array('ie', 'ie6'), get_browser_version_classes()); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['7.0']['Windows XP SP2']; - $this->assertEqual(array('ie', 'ie7'), get_browser_version_classes()); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['8.0']['Windows Vista']; - $this->assertEqual(array('ie', 'ie8'), get_browser_version_classes()); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['2.0']['Windows XP']; - $this->assertEqual(array('gecko', 'gecko18'), get_browser_version_classes()); - - $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['3.0.6']['SUSE']; - $this->assertEqual(array('gecko', 'gecko19'), get_browser_version_classes()); - } - - function test_get_device_type() { - // IE8 (common pattern ~1.5% of IE7/8 users have embedded IE6 agent)) - $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; BT Openworld BB; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; Hotbar 10.2.197.0; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727)'; - $this->assertEqual('default', get_device_type()); - // Genuine IE6 - $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/4.0 (compatible; MSIE 6.0; AOL 9.0; Windows NT 5.1; SV1; FunWebProducts; .NET CLR 1.0.3705; Media Center PC 2.8)'; - $this->assertEqual('legacy', get_device_type()); - } - - function test_fix_utf8() { - // make sure valid data including other types is not changed - $this->assertidentical(null, fix_utf8(null)); - $this->assertidentical(1, fix_utf8(1)); - $this->assertidentical(1.1, fix_utf8(1.1)); - $this->assertidentical(true, fix_utf8(true)); - $this->assertidentical('', fix_utf8('')); - $array = array('do', 're', 'mi'); - $this->assertidentical($array, fix_utf8($array)); - $object = new stdClass(); - $object->a = 'aa'; - $object->b = 'bb'; - $this->assertidentical($object, fix_utf8($object)); - - // valid utf8 string - $this->assertidentical("žlutý koníček přeskočil potůček \n\t\r\0", fix_utf8("žlutý koníček přeskočil potůček \n\t\r\0")); - - // invalid utf8 string - $this->assertidentical('aaabbb', fix_utf8('aaa'.chr(130).'bbb')); - } - - function test_optional_param() { - global $CFG; - - $_POST['username'] = 'post_user'; - $_GET['username'] = 'get_user'; - $this->assertIdentical(optional_param('username', 'default_user', PARAM_RAW), $_POST['username']); - - unset($_POST['username']); - $this->assertIdentical(optional_param('username', 'default_user', PARAM_RAW), $_GET['username']); - - unset($_GET['username']); - $this->assertIdentical(optional_param('username', 'default_user', PARAM_RAW), 'default_user'); - - // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2 - $_POST['username'] = 'post_user'; - try { - optional_param('username', 'default_user', null); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - try { - @optional_param('username', 'default_user'); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - try { - @optional_param('username'); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - try { - optional_param('', 'default_user', PARAM_RAW); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - - // make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3 - $debugging = isset($CFG->debug) ? $CFG->debug : null; - $debugdisplay = isset($CFG->debugdisplay) ? $CFG->debugdisplay : null; - $CFG->debug = DEBUG_DEVELOPER; - $CFG->debugdisplay = true; - - ob_start(); - $this->assertIdentical(optional_param('username', 'default_user', PARAM_RAW), $_POST['username']); - $d = ob_end_clean(); - $this->assertTrue($d !== ''); - - if ($debugging !== null) { - $CFG->debug = $debugging; - } else { - unset($CFG->debug); - } - if ($debugdisplay !== null) { - $CFG->debugdisplay = $debugdisplay; - } else { - unset($CFG->debugdisplay); - } - } - - function test_optional_param_array() { - global $CFG; - - $_POST['username'] = array('a'=>'post_user'); - $_GET['username'] = array('a'=>'get_user'); - $this->assertIdentical(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), $_POST['username']); - - unset($_POST['username']); - $this->assertIdentical(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), $_GET['username']); - - unset($_GET['username']); - $this->assertIdentical(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), array('a'=>'default_user')); - - // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2 - $_POST['username'] = array('a'=>'post_user'); - try { - optional_param_array('username', array('a'=>'default_user'), null); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - try { - @optional_param_array('username', array('a'=>'default_user')); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - try { - @optional_param_array('username'); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - try { - optional_param_array('', array('a'=>'default_user'), PARAM_RAW); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - - // do not allow nested arrays - try { - $_POST['username'] = array('a'=>array('b'=>'post_user')); - optional_param_array('username', array('a'=>'default_user'), PARAM_RAW); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - - // do not allow non-arrays - $debugging = isset($CFG->debug) ? $CFG->debug : null; - $debugdisplay = isset($CFG->debugdisplay) ? $CFG->debugdisplay : null; - $CFG->debug = DEBUG_DEVELOPER; - $CFG->debugdisplay = true; - - ob_start(); - $_POST['username'] = 'post_user'; - $this->assertIdentical(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), array('a'=>'default_user')); - $d = ob_end_clean(); - $this->assertTrue($d !== ''); - - // make sure array keys are sanitised - ob_start(); - $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user'); - $this->assertIdentical(optional_param_array('username', array(), PARAM_RAW), array('a1_-'=>'post_user')); - $d = ob_end_clean(); - $this->assertTrue($d !== ''); - - if ($debugging !== null) { - $CFG->debug = $debugging; - } else { - unset($CFG->debug); - } - if ($debugdisplay !== null) { - $CFG->debugdisplay = $debugdisplay; - } else { - unset($CFG->debugdisplay); - } - } - - function test_required_param() { - global $CFG; - - $_POST['username'] = 'post_user'; - $_GET['username'] = 'get_user'; - $this->assertIdentical(required_param('username', PARAM_RAW), 'post_user'); - - unset($_POST['username']); - $this->assertIdentical(required_param('username', PARAM_RAW), 'get_user'); - - unset($_GET['username']); - try { - $this->assertIdentical(required_param('username', PARAM_RAW), 'default_user'); - $this->fail('moodle_exception expected'); - } catch (moodle_exception $ex) { - $this->assertTrue(true); - } - - // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2 - $_POST['username'] = 'post_user'; - try { - @required_param('username'); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - try { - required_param('username', ''); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - try { - required_param('', PARAM_RAW); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - - // make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3 - $debugging = isset($CFG->debug) ? $CFG->debug : null; - $debugdisplay = isset($CFG->debugdisplay) ? $CFG->debugdisplay : null; - $CFG->debug = DEBUG_DEVELOPER; - $CFG->debugdisplay = true; - - ob_start(); - $this->assertIdentical(required_param('username', PARAM_RAW), $_POST['username']); - $d = ob_end_clean(); - $this->assertTrue($d !== ''); - - if ($debugging !== null) { - $CFG->debug = $debugging; - } else { - unset($CFG->debug); - } - if ($debugdisplay !== null) { - $CFG->debugdisplay = $debugdisplay; - } else { - unset($CFG->debugdisplay); - } - } - - function test_required_param_array() { - global $CFG; - - $_POST['username'] = array('a'=>'post_user'); - $_GET['username'] = array('a'=>'get_user'); - $this->assertIdentical(required_param_array('username', PARAM_RAW), $_POST['username']); - - unset($_POST['username']); - $this->assertIdentical(required_param_array('username', PARAM_RAW), $_GET['username']); - - // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2 - $_POST['username'] = array('a'=>'post_user'); - try { - required_param_array('username', null); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - try { - @required_param_array('username'); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - try { - required_param_array('', PARAM_RAW); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - - // do not allow nested arrays - try { - $_POST['username'] = array('a'=>array('b'=>'post_user')); - required_param_array('username', PARAM_RAW); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - - // do not allow non-arrays - try { - $_POST['username'] = 'post_user'; - required_param_array('username', PARAM_RAW); - $this->fail('moodle_exception expected'); - } catch (moodle_exception $ex) { - $this->assertTrue(true); - } - - // do not allow non-arrays - $debugging = isset($CFG->debug) ? $CFG->debug : null; - $debugdisplay = isset($CFG->debugdisplay) ? $CFG->debugdisplay : null; - $CFG->debug = DEBUG_DEVELOPER; - $CFG->debugdisplay = true; - - // make sure array keys are sanitised - ob_start(); - $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user'); - $this->assertIdentical(required_param_array('username', PARAM_RAW), array('a1_-'=>'post_user')); - $d = ob_end_clean(); - $this->assertTrue($d !== ''); - - if ($debugging !== null) { - $CFG->debug = $debugging; - } else { - unset($CFG->debug); - } - if ($debugdisplay !== null) { - $CFG->debugdisplay = $debugdisplay; - } else { - unset($CFG->debugdisplay); - } - } - - function test_clean_param() { - // forbid objects and arrays - try { - clean_param(array('x', 'y'), PARAM_RAW); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - try { - $param = new stdClass(); - $param->id = 1; - clean_param($param, PARAM_RAW); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - - // require correct type - try { - clean_param('x', 'xxxxxx'); - $this->fail('moodle_exception expected'); - } catch (moodle_exception $ex) { - $this->assertTrue(true); - } - try { - @clean_param('x'); - $this->fail('moodle_exception expected'); - } catch (moodle_exception $ex) { - $this->assertTrue(true); - } - - } - - function test_clean_param_array() { - $this->assertIdentical(clean_param_array(null, PARAM_RAW), array()); - $this->assertIdentical(clean_param_array(array('a', 'b'), PARAM_RAW), array('a', 'b')); - $this->assertIdentical(clean_param_array(array('a', array('b')), PARAM_RAW, true), array('a', array('b'))); - - // require correct type - try { - clean_param_array(array('x'), 'xxxxxx'); - $this->fail('moodle_exception expected'); - } catch (moodle_exception $ex) { - $this->assertTrue(true); - } - try { - @clean_param_array(array('x')); - $this->fail('moodle_exception expected'); - } catch (moodle_exception $ex) { - $this->assertTrue(true); - } - - try { - clean_param_array(array('x', array('y')), PARAM_RAW); - $this->fail('coding_exception expected'); - } catch (coding_exception $ex) { - $this->assertTrue(true); - } - - // test recursive - } - - function test_clean_param_raw() { - $this->assertEqual(clean_param('#()*#,9789\'".,<42897>assertEqual(clean_param(" Frog toad \r\n ", PARAM_RAW_TRIMMED), 'Frog toad'); - } - - function test_clean_param_clean() { - // PARAM_CLEAN is an ugly hack, do not use in new code (skodak) - // instead use more specific type, or submit sothing that can be verified properly - $this->assertEqual(clean_param('xx