MDL-32569 drop migrated core simpletests

This commit is contained in:
Petr Skoda
2012-04-21 16:36:37 +02:00
parent 05d531a5fb
commit 7a636d6e7f
32 changed files with 0 additions and 10802 deletions
-347
View File
@@ -1,347 +0,0 @@
<?php
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.org //
// //
// Copyright (C) 1999 onwards Martin Dougiamas http://moodle.com //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
require_once($CFG->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 = '[email protected]';
$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&amp;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&amp;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));
}
}
-44
View File
@@ -1,44 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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,
)
);
-878
View File
@@ -1,878 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package moodlecore
* @copyright [email protected]
* @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
*/
}
-57
View File
@@ -1,57 +0,0 @@
<?php
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.org //
// //
// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
/**
* An array of possible user_agent strings.
*
* @TODO Complete that list using http://www.pgts.com.au/pgtsj/pgtsj0208c.html
* OR make this test function dynamic by pulling out strings from a server somewhere,
* then testing each of them against the check_browser_version function.
*/
$user_agents = array(
'MSIE' => 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)')
)
);
File diff suppressed because it is too large Load Diff
-46
View File
@@ -1,46 +0,0 @@
<?php
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.org //
// //
// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
/**
* Unit tests for (some of) ../../backup/backuplib.php.
*
* @author [email protected]
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package moodlecore
*/
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
require_once($CFG->dirroot . '/backup/backuplib.php');
class backuplib_test extends UnitTestCase {
public static $includecoverage = array('backup/backuplib.php');
}
@@ -1,399 +0,0 @@
<?php
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.org //
// //
// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
/**
* Tests for the block_manager class in ../blocklib.php.
*
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package moodlecore
*/
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
require_once($CFG->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);
}
}
-50
View File
@@ -1,50 +0,0 @@
<?php
/**
* Code quality unit tests that are fast enough to run each time.
*
* @copyright &copy; 2006 The Open University
* @author [email protected]
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package SimpleTestEx
*/
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
class code_test extends UnitTestCase {
var $allok = array();
var $badstrings;
var $extensions_to_ignore = array('exe', 'gif', 'ico', 'jpg', 'png', 'ttf', 'log');
var $ignore_folders = array();
function test_dnc() {
global $CFG;
$regexp = '/\.(' . implode('|', $this->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;
}
}
}
}
-698
View File
@@ -1,698 +0,0 @@
<?php
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
require_once($CFG->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));
}
}
-181
View File
@@ -1,181 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for /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 <[email protected]>
* @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 '';
}
}
}
-385
View File
@@ -1,385 +0,0 @@
<?php
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.');
}
require_once($CFG->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);
}
}
-721
View File
@@ -1,721 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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 = <<<CSS
.test .one {
margin:5px;
border:0;
}
.test .one {
margin: 10px;
color: red;
}
.test.one {
margin: 15px;
}
#test .one {margin: 20px;}
#test #one {margin: 25px;}.test #one {margin: 30px;}
.test .one { background-color: #123; }
.test.one{border:1px solid blue}.test.one{border-color:green;}
@media print {
#test .one {margin: 35px;}
}
@media print {
#test .one {margin: 40px;color: #123456;}
#test #one {margin: 45px;}
}
@media print,screen {
#test .one {color: #654321;}
}
#test .one,
#new.style {color:#000;}
CSS;
$cssout = <<<CSS
.test .one{color:#F00;margin:10px;border-width:0;background:#123;}
.test.one{margin:15px;border:1px solid #008000;}
#test .one{color:#000;margin:20px;}
#test #one{margin:25px;}
.test #one{margin:30px;}
#new.style{color:#000;}
@media print {
#test .one{color:#123456;margin:40px;}
#test #one{margin:45px;}
}
@media print,screen {
#test .one{color:#654321;}
}
CSS;
$CFG->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));
}
}
-34
View File
@@ -1,34 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for ../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 {
}
-225
View File
@@ -1,225 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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');
}
}
-80
View File
@@ -1,80 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for /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');
}
}
-91
View File
@@ -1,91 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for /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));
}
}
-830
View File
@@ -1,830 +0,0 @@
<?php
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.org //
// //
// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
/**
* Tests for the parts of ../filterlib.php that involve loading the configuration
* from, and saving the configuration to, the database.
*
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package moodlecore
*/
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
require_once($CFG->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);
}
}
-223
View File
@@ -1,223 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for /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('<p></p>'));
$this->assertTrue($rule->validate('<p> </p>'));
$this->assertTrue($rule->validate('<p>x</p>'));
$this->assertTrue($rule->validate('<img src="smile.jpg" alt="smile" />'));
$this->assertTrue($rule->validate('<img src="smile.jpg" alt="smile"/>'));
$this->assertTrue($rule->validate('<img src="smile.jpg" alt="smile"></img>'));
$this->assertTrue($rule->validate('<hr />'));
$this->assertTrue($rule->validate('<hr/>'));
$this->assertTrue($rule->validate('<hr>'));
$this->assertTrue($rule->validate('<hr></hr>'));
$this->assertTrue($rule->validate('<br />'));
$this->assertTrue($rule->validate('<br/>'));
$this->assertTrue($rule->validate('<br>'));
$this->assertTrue($rule->validate('&nbsp;'));
// 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('<p>x</p>'));
$this->assertTrue($rule->validate('<img src="smile.jpg" alt="smile" />'));
$this->assertTrue($rule->validate('<img src="smile.jpg" alt="smile"/>'));
$this->assertTrue($rule->validate('<img src="smile.jpg" alt="smile"></img>'));
$this->assertTrue($rule->validate('<hr />'));
$this->assertTrue($rule->validate('<hr/>'));
$this->assertTrue($rule->validate('<hr>'));
$this->assertTrue($rule->validate('<hr></hr>'));
// 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('<p></p>'));
$this->assertFalse($rule->validate('<p> </p>'));
$this->assertFalse($rule->validate('<br />'));
$this->assertFalse($rule->validate('<br/>'));
$this->assertFalse($rule->validate('<br>'));
$this->assertFalse($rule->validate('&nbsp;'));
$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');
}
}
-46
View File
@@ -1,46 +0,0 @@
<?php
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.org //
// //
// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
/**
* Unit tests for (some of) ../gradelib.php.
*
* @author [email protected]
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package moodlecore
*/
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
require_once($CFG->libdir.'/simpletest/fixtures/gradetest.php');
class gradelib_test extends grade_test {
function test_grade_get_grades() {
//TODO
}
}
-147
View File
@@ -1,147 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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('<img src="edit.png" alt="edit" />'));
$text = 'xx<img src="gif.gif" alt="some gif" />xx';
$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('<img src="edit.png" alt="\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 = '<strong>Žluťoučký koníček</strong>';
$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('<p><i>Hello</i> <b>world</b>!</p>'));
$this->assertEqual("All the WORLDS a stage.\n\n-- William Shakespeare", html_to_text('<p>All the <strong>worlds</strong> a stage.</p><p>-- William Shakespeare</p>'));
$this->assertEqual("HELLO WORLD!\n\n", html_to_text('<h1>Hello world!</h1>'));
$this->assertEqual("Hello\nworld!", html_to_text('Hello<br />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:<br /><pre><span style="color: rgb(153, 51, 102);">void FillMeUp(char* in_string) {'.
'<br /> int i = 0;<br /> while (in_string[i] != \'\0\') {<br /> in_string[i] = \'X\';<br /> i++;<br /> }<br />'.
'}</span></pre>What would happen if a non-terminated string were input to this function?<br /><br />';
$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));
}
}
-255
View File
@@ -1,255 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* 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 = '<a href="http://moodle.org" target="_blank">Some link</a>';
$result = format_text($text, FORMAT_HTML);
$this->assertIdentical($text, $result);
$result = format_text('<a href="http://moodle.org" target="some">Some link</a>', FORMAT_HTML);
$this->assertIdentical('<a href="http://moodle.org">Some link</a>', $result);
}
/**
* Verify our nolink tag accepted
* @return void
*/
public function test_nolink() {
// we can not use format text because nolink changes result
$text = '<nolink><div>no filters</div></nolink>';
$result = purify_html($text, array());
$this->assertIdentical($text, $result);
$text = '<nolink>xxx<em>xx</em><div>xxx</div></nolink>';
$result = purify_html($text, array());
$this->assertIdentical($text, $result);
}
/**
* Verify our tex tag accepted
* @return void
*/
public function test_tex() {
$text = '<tex>a+b=c</tex>';
$result = purify_html($text, array());
$this->assertIdentical($text, $result);
}
/**
* Verify our algebra tag accepted
* @return void
*/
public function test_algebra() {
$text = '<algebra>a+b=c</algebra>';
$result = purify_html($text, array());
$this->assertIdentical($text, $result);
}
/**
* Verify our hacky multilang works
* @return void
*/
public function test_multilang() {
$text = '<lang lang="en">hmmm</lang><lang lang="anything">hm</lang>';
$result = purify_html($text, array());
$this->assertIdentical($text, $result);
$text = '<span lang="en" class="multilang">hmmm</span><span lang="anything" class="multilang">hm</span>';
$result = purify_html($text, array());
$this->assertIdentical($text, $result);
$text = '<span lang="en">hmmm</span>';
$result = purify_html($text, array());
$this->assertNotIdentical($text, $result);
// keep standard lang tags
$text = '<span lang="de_DU" class="multilang">asas</span>';
$result = purify_html($text, array());
$this->assertIdentical($text, $result);
$text = '<lang lang="de_DU">xxxxxx</lang>';
$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('<div id="example">Frog</div>', FORMAT_HTML, $options);
$this->assertIdentical('<div>Frog</div>', $result);
// Now allow ids
$options['allowid'] = true;
$result = format_text('<div id="example">Frog</div>', FORMAT_HTML, $options);
$this->assertIdentical('<div id="example">Frog</div>', $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 = "<p>xx";
$this->assertIdentical('<p>xx</p>', purify_html($text));
$text = "<P>xx</P>";
$this->assertIdentical('<p>xx</p>', purify_html($text));
$text = "xx<br>";
$this->assertIdentical('xx<br />', purify_html($text));
}
/**
* Test nesting - this used to cause problems in earlier versions
*/
function test_nested_lists() {
$text = "<ul><li>One<ul><li>Two</li></ul></li><li>Three</li></ul>";
$this->assertIdentical($text, purify_html($text));
}
/**
* Test that XSS protection works, complete smoke tests are in htmlpurifier itself.
*/
function test_cleaning_nastiness() {
$text = "x<SCRIPT>alert('XSS')</SCRIPT>x";
$this->assertIdentical('xx', purify_html($text));
$text = '<DIV STYLE="background-image:url(javascript:alert(\'XSS\'))">xx</DIV>';
$this->assertIdentical('<div>xx</div>', purify_html($text));
$text = '<DIV STYLE="width:expression(alert(\'XSS\'));">xx</DIV>';
$this->assertIdentical('<div>xx</div>', purify_html($text));
$text = 'x<IFRAME SRC="javascript:alert(\'XSS\');"></IFRAME>x';
$this->assertIdentical('xx', purify_html($text));
$text = 'x<OBJECT TYPE="text/x-scriptlet" DATA="http://ha.ckers.org/scriptlet.html"></OBJECT>x';
$this->assertIdentical('xx', purify_html($text));
$text = 'x<EMBED SRC="http://ha.ckers.org/xss.swf" AllowScriptAccess="always"></EMBED>x';
$this->assertIdentical('xx', purify_html($text));
$text = 'x<form></form>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<p>def</p>efg<p>hij</p>";
$this->assertFalse(is_purify_html_necessary($text));
$this->assertidentical($text, purify_html($text));
$text = "<br />abc\n<p>def<em>efg</em><strong>hi<br />j</strong></p>";
$this->assertFalse(is_purify_html_necessary($text));
$this->assertidentical($text, purify_html($text));
// now failures
$text = "&nbsp;";
$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 = "<div>abc</div>";
$this->assertTrue(is_purify_html_necessary($text));
$text = "<span>abc</span>";
$this->assertTrue(is_purify_html_necessary($text));
$text = "<br>abc";
$this->assertTrue(is_purify_html_necessary($text));
$text = "<p class='xxx'>abc</p>";
$this->assertTrue(is_purify_html_necessary($text));
$text = "<p>abc<em></p></em>";
$this->assertTrue(is_purify_html_necessary($text));
$text = "<p>abc";
$this->assertTrue(is_purify_html_necessary($text));
}
}
-97
View File
@@ -1,97 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for the 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('<div>', html_writer::start_tag('div'));
}
public function test_start_tag_with_attr() {
$this->assertEqual('<div class="frog">',
html_writer::start_tag('div', array('class' => 'frog')));
}
public function test_start_tag_with_attrs() {
$this->assertEqual('<div class="frog" id="mydiv">',
html_writer::start_tag('div', array('class' => 'frog', 'id' => 'mydiv')));
}
public function test_end_tag() {
$this->assertEqual('</div>', html_writer::end_tag('div'));
}
public function test_empty_tag() {
$this->assertEqual('<br />', html_writer::empty_tag('br'));
}
public function test_empty_tag_with_attrs() {
$this->assertEqual('<input type="submit" value="frog" />',
html_writer::empty_tag('input', array('type' => 'submit', 'value' => 'frog')));
}
public function test_nonempty_tag_with_content() {
$this->assertEqual('<div>Hello world!</div>',
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('<div class="score">0</div>',
html_writer::nonempty_tag('div', 0, array('class' => 'score')));
}
public function test_nonempty_tag_zero_string() {
$this->assertEqual('<div class="score">0</div>',
html_writer::nonempty_tag('div', '0', array('class' => 'score')));
}
}
-221
View File
@@ -1,221 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
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);
}
}
File diff suppressed because it is too large Load Diff
-513
View File
@@ -1,513 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for lib/navigationlib.php
*
* @package moodlecore
* @copyright 2009 Sam Hemelryk
* @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
}
global $CFG;
require_once($CFG->libdir . '/navigationlib.php');
class navigation_node_test extends UnitTestCase {
protected $tree;
public static $includecoverage = array('./lib/navigationlib.php');
public static $excludecoverage = array();
protected $fakeproperties = array(
'text' => 'text',
'shorttext' => 'A very silly extra long short text string, more than 25 characters',
'key' => 'key',
'type' => 'navigation_node::TYPE_COURSE',
'action' => 'http://www.moodle.org/');
protected $activeurl = null;
protected $inactivenode = null;
/**
* @var navigation_node
*/
public $node;
public function setUp() {
global $CFG, $PAGE;
parent::setUp();
$this->activeurl = $PAGE->url;
navigation_node::override_active_url($this->activeurl);
$this->inactiveurl = new moodle_url('http://www.moodle.com/');
$this->fakeproperties['action'] = $this->inactiveurl;
$this->node = new navigation_node('Test Node');
$this->node->type = navigation_node::TYPE_SYSTEM;
$demo1 = $this->node->add('demo1', $this->inactiveurl, navigation_node::TYPE_COURSE, null, 'demo1', new pix_icon('i/course', ''));
$demo2 = $this->node->add('demo2', $this->inactiveurl, navigation_node::TYPE_COURSE, null, 'demo2', new pix_icon('i/course', ''));
$demo3 = $this->node->add('demo3', $this->inactiveurl, navigation_node::TYPE_CATEGORY, null, 'demo3',new pix_icon('i/course', ''));
$demo4 = $demo3->add('demo4', $this->inactiveurl,navigation_node::TYPE_COURSE, null, 'demo4', new pix_icon('i/course', ''));
$demo5 = $demo3->add('demo5', $this->activeurl, navigation_node::TYPE_COURSE, null, 'demo5',new pix_icon('i/course', ''));
$demo5->add('activity1', null, navigation_node::TYPE_ACTIVITY, null, 'activity1')->make_active();
$hiddendemo1 = $this->node->add('hiddendemo1', $this->inactiveurl, navigation_node::TYPE_CATEGORY, null, 'hiddendemo1', new pix_icon('i/course', ''));
$hiddendemo1->hidden = true;
$hiddendemo1->add('hiddendemo2', $this->inactiveurl, navigation_node::TYPE_COURSE, null, 'hiddendemo2', new pix_icon('i/course', ''))->helpbutton = 'Here is a help button';;
$hiddendemo1->add('hiddendemo3', $this->inactiveurl, navigation_node::TYPE_COURSE,null, 'hiddendemo3', new pix_icon('i/course', ''))->display = false;
}
public function test___construct() {
global $CFG;
$node = new navigation_node($this->fakeproperties);
$this->assertEqual($node->text, $this->fakeproperties['text']);
$this->assertEqual($node->title, $this->fakeproperties['text']);
$this->assertTrue(strpos($this->fakeproperties['shorttext'], substr($node->shorttext,0, -3))===0);
$this->assertEqual($node->key, $this->fakeproperties['key']);
$this->assertEqual($node->type, $this->fakeproperties['type']);
$this->assertEqual($node->action, $this->fakeproperties['action']);
}
public function test_add() {
global $CFG;
// Add a node with all args set
$node1 = $this->node->add('test_add_1','http://www.moodle.org/',navigation_node::TYPE_COURSE,'testadd1','key',new pix_icon('i/course', ''));
// Add a node with the minimum args required
$node2 = $this->node->add('test_add_2',null, navigation_node::TYPE_CUSTOM,'testadd2');
$node3 = $this->node->add(str_repeat('moodle ', 15),str_repeat('moodle', 15));
$this->assertIsA($node1, 'navigation_node');
$this->assertIsA($node2, 'navigation_node');
$this->assertIsA($node3, 'navigation_node');
$ref = $this->node->get('key');
$this->assertReference($node1, $ref);
$ref = $this->node->get($node2->key);
$this->assertReference($node2, $ref);
$ref = $this->node->get($node2->key, $node2->type);
$this->assertReference($node2, $ref);
$ref = $this->node->get($node3->key, $node3->type);
$this->assertReference($node3, $ref);
}
public function test_add_before() {
global $CFG;
// Create 3 nodes
$node1 = navigation_node::create('test_add_1', null, navigation_node::TYPE_CUSTOM,
'test 1', 'testadd1');
$node2 = navigation_node::create('test_add_2', null, navigation_node::TYPE_CUSTOM,
'test 2', 'testadd2');
$node3 = navigation_node::create('test_add_3', null, navigation_node::TYPE_CUSTOM,
'test 3', 'testadd3');
// Add node 2, then node 1 before 2, then node 3 at end
$this->node->add_node($node2);
$this->node->add_node($node1, 'testadd2');
$this->node->add_node($node3);
// Check the last 3 nodes are in 1, 2, 3 order and have those indexes
foreach($this->node->children as $child) {
$keys[] = $child->key;
}
$this->assertEqual('testadd1', $keys[count($keys)-3]);
$this->assertEqual('testadd2', $keys[count($keys)-2]);
$this->assertEqual('testadd3', $keys[count($keys)-1]);
}
public function test_add_class() {
$node = $this->node->get('demo1');
$this->assertIsA($node, 'navigation_node');
if ($node !== false) {
$node->add_class('myclass');
$classes = $node->classes;
$this->assertTrue(in_array('myclass', $classes));
}
}
public function test_check_if_active() {
// First test the string urls
// demo1 -> action is http://www.moodle.org/, thus should be true
$demo5 = $this->node->find('demo5', navigation_node::TYPE_COURSE);
if ($this->assertIsA($demo5, 'navigation_node')) {
$this->assertTrue($demo5->check_if_active());
}
// demo2 -> action is http://www.moodle.com/, thus should be false
$demo2 = $this->node->get('demo2');
if ($this->assertIsA($demo2, 'navigation_node')) {
$this->assertFalse($demo2->check_if_active());
}
}
public function test_contains_active_node() {
// demo5, and activity1 were set to active during setup
// Should be true as it contains all nodes
$this->assertTrue($this->node->contains_active_node());
// Should be true as demo5 is a child of demo3
$this->assertTrue($this->node->get('demo3')->contains_active_node());
// Obviously duff
$this->assertFalse($this->node->get('demo1')->contains_active_node());
// Should be true as demo5 contains activity1
$this->assertTrue($this->node->get('demo3')->get('demo5')->contains_active_node());
// Should be true activity1 is the active node
$this->assertTrue($this->node->get('demo3')->get('demo5')->get('activity1')->contains_active_node());
// Obviously duff
$this->assertFalse($this->node->get('demo3')->get('demo4')->contains_active_node());
}
public function test_find_active_node() {
$activenode1 = $this->node->find_active_node();
$activenode2 = $this->node->get('demo1')->find_active_node();
if ($this->assertIsA($activenode1, 'navigation_node')) {
$ref = $this->node->get('demo3')->get('demo5')->get('activity1');
$this->assertReference($activenode1, $ref);
}
$this->assertNotA($activenode2, 'navigation_node');
}
public function test_find() {
$node1 = $this->node->find('demo1', navigation_node::TYPE_COURSE);
$node2 = $this->node->find('demo5', navigation_node::TYPE_COURSE);
$node3 = $this->node->find('demo5', navigation_node::TYPE_CATEGORY);
$node4 = $this->node->find('demo0', navigation_node::TYPE_COURSE);
$this->assertIsA($node1, 'navigation_node');
$this->assertIsA($node2, 'navigation_node');
$this->assertNotA($node3, 'navigation_node');
$this->assertNotA($node4, 'navigation_node');
}
public function test_find_expandable() {
$expandable = array();
$this->node->find_expandable($expandable);
$this->assertEqual(count($expandable), 4);
if (count($expandable) === 4) {
$name = $expandable[0]['key'];
$name .= $expandable[1]['key'];
$name .= $expandable[2]['key'];
$name .= $expandable[3]['key'];
$this->assertEqual($name, 'demo1demo2demo4hiddendemo2');
}
}
public function test_get() {
$node1 = $this->node->get('demo1'); // Exists
$node2 = $this->node->get('demo4'); // Doesn't exist for this node
$node3 = $this->node->get('demo0'); // Doesn't exist at all
$node4 = $this->node->get(false); // Sometimes occurs in nature code
$this->assertIsA($node1, 'navigation_node');
$this->assertFalse($node2);
$this->assertFalse($node3);
$this->assertFalse($node4);
}
public function test_get_css_type() {
$csstype1 = $this->node->get('demo3')->get_css_type();
$csstype2 = $this->node->get('demo3')->get('demo5')->get_css_type();
$this->node->get('demo3')->get('demo5')->type = 1000;
$csstype3 = $this->node->get('demo3')->get('demo5')->get_css_type();
$this->assertEqual($csstype1, 'type_category');
$this->assertEqual($csstype2, 'type_course');
$this->assertEqual($csstype3, 'type_unknown');
}
public function test_make_active() {
global $CFG;
$node1 = $this->node->add('active node 1', null, navigation_node::TYPE_CUSTOM, null, 'anode1');
$node2 = $this->node->add('active node 2', new moodle_url($CFG->wwwroot), navigation_node::TYPE_COURSE, null, 'anode2');
$node1->make_active();
$this->node->get('anode2')->make_active();
$this->assertTrue($node1->isactive);
$this->assertTrue($this->node->get('anode2')->isactive);
}
public function test_remove() {
$remove1 = $this->node->add('child to remove 1', null, navigation_node::TYPE_CUSTOM, null, 'remove1');
$remove2 = $this->node->add('child to remove 2', null, navigation_node::TYPE_CUSTOM, null, 'remove2');
$remove3 = $remove2->add('child to remove 3', null, navigation_node::TYPE_CUSTOM, null, 'remove3');
$this->assertIsA($remove1, 'navigation_node');
$this->assertIsA($remove2, 'navigation_node');
$this->assertIsA($remove3, 'navigation_node');
$this->assertIsA($this->node->get('remove1'), 'navigation_node');
$this->assertIsA($this->node->get('remove2'), 'navigation_node');
$this->assertIsA($remove2->get('remove3'), 'navigation_node');
$this->assertTrue($remove1->remove());
$this->assertTrue($this->node->get('remove2')->remove());
$this->assertTrue($remove2->get('remove3')->remove());
$this->assertFalse($this->node->get('remove1'));
$this->assertFalse($this->node->get('remove2'));
}
public function test_remove_class() {
$this->node->add_class('testclass');
$this->assertTrue($this->node->remove_class('testclass'));
$this->assertFalse(in_array('testclass', $this->node->classes));
}
}
/**
* This is a dummy object that allows us to call protected methods within the
* global navigation class by prefixing the methods with `exposed_`
*/
class exposed_global_navigation extends global_navigation {
protected $exposedkey = 'exposed_';
public function __construct(moodle_page $page=null) {
global $PAGE;
if ($page === null) {
$page = $PAGE;
}
parent::__construct($page);
$this->cache = new navigation_cache('simpletest_nav');
}
public function __call($method, $arguments) {
if (strpos($method,$this->exposedkey) !== false) {
$method = substr($method, strlen($this->exposedkey));
}
if (method_exists($this, $method)) {
return call_user_func_array(array($this, $method), $arguments);
}
throw new coding_exception('You have attempted to access a method that does not exist for the given object '.$method, DEBUG_DEVELOPER);
}
public function set_initialised() {
$this->initialised = true;
}
}
class mock_initialise_global_navigation extends global_navigation {
static $count = 1;
public function load_for_category() {
$this->add('load_for_category', null, null, null, 'initcall'.self::$count);
self::$count++;
return 0;
}
public function load_for_course() {
$this->add('load_for_course', null, null, null, 'initcall'.self::$count);
self::$count++;
return 0;
}
public function load_for_activity() {
$this->add('load_for_activity', null, null, null, 'initcall'.self::$count);
self::$count++;
return 0;
}
public function load_for_user($user=null, $forceforcontext=false) {
$this->add('load_for_user', null, null, null, 'initcall'.self::$count);
self::$count++;
return 0;
}
}
class global_navigation_test extends UnitTestCase {
/**
* @var global_navigation
*/
public $node;
public static $includecoverage = array('./lib/navigationlib.php');
public static $excludecoverage = array();
public function setUp() {
$this->node = new exposed_global_navigation();
// Create an initial tree structure to work with
$cat1 = $this->node->add('category 1', null, navigation_node::TYPE_CATEGORY, null, 'cat1');
$cat2 = $this->node->add('category 2', null, navigation_node::TYPE_CATEGORY, null, 'cat2');
$cat3 = $this->node->add('category 3', null, navigation_node::TYPE_CATEGORY, null, 'cat3');
$sub1 = $cat2->add('sub category 1', null, navigation_node::TYPE_CATEGORY, null, 'sub1');
$sub2 = $cat2->add('sub category 2', null, navigation_node::TYPE_CATEGORY, null, 'sub2');
$sub3 = $cat2->add('sub category 3', null, navigation_node::TYPE_CATEGORY, null, 'sub3');
$course1 = $sub2->add('course 1', null, navigation_node::TYPE_COURSE, null, 'course1');
$course2 = $sub2->add('course 2', null, navigation_node::TYPE_COURSE, null, 'course2');
$course3 = $sub2->add('course 3', null, navigation_node::TYPE_COURSE, null, 'course3');
$section1 = $course2->add('section 1', null, navigation_node::TYPE_SECTION, null, 'sec1');
$section2 = $course2->add('section 2', null, navigation_node::TYPE_SECTION, null, 'sec2');
$section3 = $course2->add('section 3', null, navigation_node::TYPE_SECTION, null, 'sec3');
$act1 = $section2->add('activity 1', null, navigation_node::TYPE_ACTIVITY, null, 'act1');
$act2 = $section2->add('activity 2', null, navigation_node::TYPE_ACTIVITY, null, 'act2');
$act3 = $section2->add('activity 3', null, navigation_node::TYPE_ACTIVITY, null, 'act3');
$res1 = $section2->add('resource 1', null, navigation_node::TYPE_RESOURCE, null, 'res1');
$res2 = $section2->add('resource 2', null, navigation_node::TYPE_RESOURCE, null, 'res2');
$res3 = $section2->add('resource 3', null, navigation_node::TYPE_RESOURCE, null, 'res3');
}
public function test_format_display_course_content() {
$this->assertTrue($this->node->exposed_format_display_course_content('topic'));
$this->assertFalse($this->node->exposed_format_display_course_content('scorm'));
$this->assertTrue($this->node->exposed_format_display_course_content('dummy'));
}
public function test_module_extends_navigation() {
$this->assertTrue($this->node->exposed_module_extends_navigation('data'));
$this->assertFalse($this->node->exposed_module_extends_navigation('test1'));
}
}
/**
* This is a dummy object that allows us to call protected methods within the
* global navigation class by prefixing the methods with `exposed_`
*/
class exposed_navbar extends navbar {
protected $exposedkey = 'exposed_';
public function __construct(moodle_page $page) {
parent::__construct($page);
$this->cache = new navigation_cache('simpletest_nav');
}
function __call($method, $arguments) {
if (strpos($method,$this->exposedkey) !== false) {
$method = substr($method, strlen($this->exposedkey));
}
if (method_exists($this, $method)) {
return call_user_func_array(array($this, $method), $arguments);
}
throw new coding_exception('You have attempted to access a method that does not exist for the given object '.$method, DEBUG_DEVELOPER);
}
}
class navigation_exposed_moodle_page extends moodle_page {
public function set_navigation(navigation_node $node) {
$this->_navigation = $node;
}
}
class navbar_test extends UnitTestCase {
protected $node;
protected $oldnav;
public static $includecoverage = array('./lib/navigationlib.php');
public static $excludecoverage = array();
public function setUp() {
global $PAGE;
$temptree = new global_navigation_test();
$temptree->setUp();
$temptree->node->find('course2', navigation_node::TYPE_COURSE)->make_active();
$page = new navigation_exposed_moodle_page();
$page->set_url($PAGE->url);
$page->set_context($PAGE->context);
$navigation = new exposed_global_navigation($page);
$navigation->children = $temptree->node->children;
$navigation->set_initialised();
$page->set_navigation($navigation);
$this->cache = new navigation_cache('simpletest_nav');
$this->node = new exposed_navbar($page);
}
public function test_add() {
// Add a node with all args set
$this->node->add('test_add_1','http://www.moodle.org/',navigation_node::TYPE_COURSE,'testadd1','testadd1',new pix_icon('i/course', ''));
// Add a node with the minimum args required
$this->node->add('test_add_2','http://www.moodle.org/',navigation_node::TYPE_COURSE,'testadd2','testadd2',new pix_icon('i/course', ''));
$this->assertIsA($this->node->get('testadd1'), 'navigation_node');
$this->assertIsA($this->node->get('testadd2'), 'navigation_node');
}
public function test_has_items() {
$this->assertTrue($this->node->has_items());
}
}
class navigation_cache_test extends UnitTestCase {
protected $cache;
public static $includecoverage = array('./lib/navigationlib.php');
public static $excludecoverage = array();
public function setUp() {
$this->cache = new navigation_cache('simpletest_nav');
$this->cache->anysetvariable = true;
}
public function test___get() {
$this->assertTrue($this->cache->anysetvariable);
$this->assertEqual($this->cache->notasetvariable, null);
}
public function test___set() {
$this->cache->myname = 'Sam Hemelryk';
$this->assertTrue($this->cache->cached('myname'));
$this->assertEqual($this->cache->myname, 'Sam Hemelryk');
}
public function test_cached() {
$this->assertTrue($this->cache->cached('anysetvariable'));
$this->assertFalse($this->cache->cached('notasetvariable'));
}
public function test_clear() {
$cache = clone($this->cache);
$this->assertTrue($cache->cached('anysetvariable'));
$cache->clear();
$this->assertFalse($cache->cached('anysetvariable'));
}
public function test_set() {
$this->cache->set('software', 'Moodle');
$this->assertTrue($this->cache->cached('software'));
$this->assertEqual($this->cache->software, 'Moodle');
}
}
/**
* This is a dummy object that allows us to call protected methods within the
* global navigation class by prefixing the methods with `exposed_`
*/
class exposed_settings_navigation extends settings_navigation {
protected $exposedkey = 'exposed_';
function __construct() {
global $PAGE;
parent::__construct($PAGE);
$this->cache = new navigation_cache('simpletest_nav');
}
function __call($method, $arguments) {
if (strpos($method,$this->exposedkey) !== false) {
$method = substr($method, strlen($this->exposedkey));
}
if (method_exists($this, $method)) {
return call_user_func_array(array($this, $method), $arguments);
}
throw new coding_exception('You have attempted to access a method that does not exist for the given object '.$method, DEBUG_DEVELOPER);
}
}
class settings_navigation_test extends UnitTestCase {
protected $node;
protected $cache;
public static $includecoverage = array('./lib/navigationlib.php');
public static $excludecoverage = array();
public function setUp() {
global $PAGE;
$this->cache = new navigation_cache('simpletest_nav');
$this->node = new exposed_settings_navigation();
}
public function test___construct() {
$this->node = new exposed_settings_navigation();
}
public function test___initialise() {
$this->node->initialise();
$this->assertEqual($this->node->id, 'settingsnav');
}
public function test_in_alternative_role() {
$this->assertFalse($this->node->exposed_in_alternative_role());
}
}
-234
View File
@@ -1,234 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for lib/outputcomponents.php.
*
* @package core
* @copyright 2011 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/outputcomponents.php');
/**
* Unit tests for the user_picture class
*/
class user_picture_test extends UnitTestCase {
public static $includecoverage = array('lib/outputcomponents.php');
public function test_user_picture_fields_aliasing() {
$fields = user_picture::fields();
$fields = array_map('trim', explode(',', $fields));
$this->assertTrue(in_array('id', $fields));
$aliased = array();
foreach ($fields as $field) {
if ($field === 'id') {
$aliased['id'] = 'aliasedid';
} else {
$aliased[$field] = 'prefix'.$field;
}
}
$returned = user_picture::fields('', array('custom1', 'id'), 'aliasedid', 'prefix');
$returned = array_map('trim', explode(',', $returned));
$this->assertEqual(count($returned), count($fields) + 1); // only one extra field added
foreach ($fields as $field) {
if ($field === 'id') {
$expected = "id AS aliasedid";
} else {
$expected = "$field AS prefix$field";
}
$this->assertTrue(in_array($expected, $returned), "Expected pattern '$expected' not returned");
}
$this->assertTrue(in_array("custom1 AS prefixcustom1", $returned), "Expected pattern 'custom1 AS prefixcustom1' not returned");
}
public function test_user_picture_fields_unaliasing() {
$fields = user_picture::fields();
$fields = array_map('trim', explode(',', $fields));
$fakerecord = new stdClass();
$fakerecord->aliasedid = 42;
foreach ($fields as $field) {
if ($field !== 'id') {
$fakerecord->{'prefix'.$field} = "Value of $field";
}
}
$fakerecord->prefixcustom1 = 'Value of custom1';
$returned = user_picture::unalias($fakerecord, array('custom1'), 'aliasedid', 'prefix');
$this->assertEqual($returned->id, 42);
foreach ($fields as $field) {
if ($field !== 'id') {
$this->assertEqual($returned->{$field}, "Value of $field");
}
}
$this->assertEqual($returned->custom1, 'Value of custom1');
}
public function test_user_picture_fields_unaliasing_null() {
$fields = user_picture::fields();
$fields = array_map('trim', explode(',', $fields));
$fakerecord = new stdClass();
$fakerecord->aliasedid = 42;
foreach ($fields as $field) {
if ($field !== 'id') {
$fakerecord->{'prefix'.$field} = "Value of $field";
}
}
$fakerecord->prefixcustom1 = 'Value of custom1';
$fakerecord->prefiximagealt = null;
$returned = user_picture::unalias($fakerecord, array('custom1'), 'aliasedid', 'prefix');
$this->assertEqual($returned->id, 42);
$this->assertEqual($returned->imagealt, null);
foreach ($fields as $field) {
if ($field !== 'id' and $field !== 'imagealt') {
$this->assertEqual($returned->{$field}, "Value of $field");
}
}
$this->assertEqual($returned->custom1, 'Value of custom1');
}
}
/**
* Unit tests for the custom_menu class
*/
class custom_menu_test extends UnitTestCase {
public function test_empty_menu() {
$emptymenu = new custom_menu();
$this->assertTrue($emptymenu instanceof custom_menu);
$this->assertFalse($emptymenu->has_children());
}
public function test_basic_syntax() {
$definition = <<<EOF
Moodle community|http://moodle.org
-Moodle free support|http://moodle.org/support
-Moodle development|http://moodle.org/development
--Moodle Tracker|http://tracker.moodle.org
--Moodle Docs|http://docs.moodle.org
-Moodle News|http://moodle.org/news
Moodle company
-Hosting|http://moodle.com/hosting|Commercial hosting
-Support|http://moodle.com/support|Commercial support
EOF;
$menu = new custom_menu($definition);
$this->assertTrue($menu instanceof custom_menu);
$this->assertTrue($menu->has_children());
$firstlevel = $menu->get_children();
$this->assertTrue(is_array($firstlevel));
$this->assertEqual(2, count($firstlevel));
$item = array_shift($firstlevel);
$this->assertTrue($item instanceof custom_menu_item);
$this->assertTrue($item->has_children());
$this->assertEqual(3, count($item->get_children()));
$this->assertEqual('Moodle community', $item->get_text());
$itemurl = $item->get_url();
$this->assertTrue($itemurl instanceof moodle_url);
$this->assertEqual('http://moodle.org', $itemurl->out());
$this->assertEqual($item->get_text(), $item->get_title()); // implicit title
$item = array_shift($firstlevel);
$this->assertTrue($item->has_children());
$this->assertEqual(2, count($item->get_children()));
$this->assertEqual('Moodle company', $item->get_text());
$this->assertTrue(is_null($item->get_url()));
$children = $item->get_children();
$subitem = array_shift($children);
$this->assertFalse($subitem->has_children());
$this->assertEqual('Hosting', $subitem->get_text());
$this->assertEqual('Commercial hosting', $subitem->get_title());
}
public function test_multilang_support() {
$definition = <<<EOF
Start|http://school.info
Info
-English|http://school.info/en|Information in English|en
-Deutsch|http://school.info/de|Informationen in deutscher Sprache|de,de_du,de_kids
EOF;
// the menu without multilang support
$menu = new custom_menu($definition);
$this->assertTrue($menu->has_children());
$this->assertEqual(2, count($menu->get_children()));
$children = $menu->get_children();
$infomenu = array_pop($children);
$this->assertTrue($infomenu->has_children());
$children = $infomenu->get_children();
$this->assertEqual(2, count($children));
$children = $infomenu->get_children();
$langspecinfo = array_shift($children);
$this->assertEqual('Information in English', $langspecinfo->get_title());
// same menu for English language selected
$menu = new custom_menu($definition, 'en');
$this->assertTrue($menu->has_children());
$this->assertEqual(2, count($menu->get_children()));
$children = $menu->get_children();
$infomenu = array_pop($children);
$this->assertTrue($infomenu->has_children());
$this->assertEqual(1, count($infomenu->get_children()));
$children = $infomenu->get_children();
$langspecinfo = array_shift($children);
$this->assertEqual('Information in English', $langspecinfo->get_title());
// same menu for German (de_du) language selected
$menu = new custom_menu($definition, 'de_du');
$this->assertTrue($menu->has_children());
$this->assertEqual(2, count($menu->get_children()));
$children = $menu->get_children();
$infomenu = array_pop($children);
$this->assertTrue($infomenu->has_children());
$this->assertEqual(1, count($infomenu->get_children()));
$children = $infomenu->get_children();
$langspecinfo = array_shift($children);
$this->assertEqual('Informationen in deutscher Sprache', $langspecinfo->get_title());
// same menu for Czech language selected
$menu = new custom_menu($definition, 'cs');
$this->assertTrue($menu->has_children());
$this->assertEqual(2, count($menu->get_children()));
$children = $infomenu->get_children();
$infomenu = array_pop( $children);
$this->assertFalse($infomenu->has_children());
}
}
-179
View File
@@ -1,179 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for (some of) ../outputlib.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 . '/outputlib.php');
/**
* Unit tests for the xhtml_container_stack class.
*
* These tests assume that developer debug mode is on, which, at the time of
* writing, is true. admin/tool/unittest/index.php forces it on.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class xhtml_container_stack_test extends UnitTestCase {
protected $olddebug;
public static $includecoverage = array('lib/outputlib.php');
protected function start_capture() {
ob_start();
}
protected function end_capture() {
$result = ob_get_contents();
ob_end_clean();
return $result;
}
function setUp() {
global $CFG;
parent::setUp();
$this->olddebug = $CFG->debug;
$CFG->debug = DEBUG_DEVELOPER;
}
function tearDown() {
global $CFG;
$CFG->debug = $this->olddebug;
parent::tearDown();
}
public function test_push_then_pop() {
// Set up.
$stack = new xhtml_container_stack();
// Exercise SUT.
$this->start_capture();
$stack->push('testtype', '</div>');
$html = $stack->pop('testtype');
$errors = $this->end_capture();
// Verify outcome
$this->assertEqual('</div>', $html);
$this->assertEqual('', $errors);
}
public function test_mismatched_pop_prints_warning() {
// Set up.
$stack = new xhtml_container_stack();
$stack->push('testtype', '</div>');
// Exercise SUT.
$this->start_capture();
$html = $stack->pop('mismatch');
$errors = $this->end_capture();
// Verify outcome
$this->assertEqual('</div>', $html);
$this->assertNotEqual('', $errors);
}
public function test_pop_when_empty_prints_warning() {
// Set up.
$stack = new xhtml_container_stack();
// Exercise SUT.
$this->start_capture();
$html = $stack->pop('testtype');
$errors = $this->end_capture();
// Verify outcome
$this->assertEqual('', $html);
$this->assertNotEqual('', $errors);
}
public function test_correct_nesting() {
// Set up.
$stack = new xhtml_container_stack();
// Exercise SUT.
$this->start_capture();
$stack->push('testdiv', '</div>');
$stack->push('testp', '</p>');
$html2 = $stack->pop('testp');
$html1 = $stack->pop('testdiv');
$errors = $this->end_capture();
// Verify outcome
$this->assertEqual('</p>', $html2);
$this->assertEqual('</div>', $html1);
$this->assertEqual('', $errors);
}
public function test_pop_all_but_last() {
// Set up.
$stack = new xhtml_container_stack();
$stack->push('test1', '</h1>');
$stack->push('test2', '</h2>');
$stack->push('test3', '</h3>');
// Exercise SUT.
$this->start_capture();
$html = $stack->pop_all_but_last();
$errors = $this->end_capture();
// Verify outcome
$this->assertEqual('</h3></h2>', $html);
$this->assertEqual('', $errors);
// Tear down.
$stack->discard();
}
public function test_pop_all_but_last_only_one() {
// Set up.
$stack = new xhtml_container_stack();
$stack->push('test1', '</h1>');
// Exercise SUT.
$this->start_capture();
$html = $stack->pop_all_but_last();
$errors = $this->end_capture();
// Verify outcome
$this->assertEqual('', $html);
$this->assertEqual('', $errors);
// Tear down.
$stack->discard();
}
public function test_pop_all_but_last_empty() {
// Set up.
$stack = new xhtml_container_stack();
// Exercise SUT.
$this->start_capture();
$html = $stack->pop_all_but_last();
$errors = $this->end_capture();
// Verify outcome
$this->assertEqual('', $html);
$this->assertEqual('', $errors);
}
public function test_discard() {
// Set up.
$stack = new xhtml_container_stack();
$stack->push('test1', '</somethingdistinctive>');
$stack->discard();
// Exercise SUT.
$this->start_capture();
$stack = null;
$errors = $this->end_capture();
// Verify outcome
$this->assertEqual('', $errors);
}
}
-62
View File
@@ -1,62 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for (some of) ../questionlib.php.
*
* @package moodlecore
* @subpackage questionbank
* @copyright 2006 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/questionlib.php');
/**
* Unit tests for (some of) ../questionlib.php.
*
* @copyright 2006 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class questionlib_test extends UnitTestCase {
public static $includecoverage = array('lib/questionlib.php');
public function test_question_reorder_qtypes() {
$this->assertEqual(question_reorder_qtypes(
array('t1' => '', 't2' => '', 't3' => ''), 't1', +1),
array(0 => 't2', 1 => 't1', 2 => 't3'));
$this->assertEqual(question_reorder_qtypes(
array('t1' => '', 't2' => '', 't3' => ''), 't1', -1),
array(0 => 't1', 1 => 't2', 2 => 't3'));
$this->assertEqual(question_reorder_qtypes(
array('t1' => '', 't2' => '', 't3' => ''), 't2', -1),
array(0 => 't2', 1 => 't1', 2 => 't3'));
$this->assertEqual(question_reorder_qtypes(
array('t1' => '', 't2' => '', 't3' => ''), 't3', +1),
array(0 => 't1', 1 => 't2', 2 => 't3'));
$this->assertEqual(question_reorder_qtypes(
array('t1' => '', 't2' => '', 't3' => ''), 'missing', +1),
array(0 => 't1', 1 => 't2', 2 => 't3'));
}
}
-68
View File
@@ -1,68 +0,0 @@
<?php
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.org //
// //
// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
/**
* Unit tests for ../repositorylib.php.
*
* @author [email protected]
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package moodlecore
*/
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
require_once("$CFG->dirroot/repository/lib.php");
// Generate a mock class for each plugin subclass present
$repository_plugins = get_list_of_plugins('repository');
foreach ($repository_plugins as $plugin) {
require_once($CFG->dirroot . "/repository/$plugin/lib.php");
Mock::generatePartial("repository_$plugin", "partialmock_$plugin", array('send_package'));
}
class repositorylib_test extends UnitTestCaseUsingDatabase {
public static $includecoverage = array('repository/lib.php');
function setup() {
parent::setup();
}
public function test_plugins() {
$plugins = get_list_of_plugins('repository');
foreach ($plugins as $plugin) {
// Instantiate a fake plugin instance
$plugin_class = "partialmock_$plugin";
$plugin = new $plugin_class($this);
// add common plugin tests here
}
}
}
-130
View File
@@ -1,130 +0,0 @@
<?php
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
/*
* These tests rely on the rsstest.xml file on download.moodle.org,
* from eloys listing:
* rsstest.xml: One valid rss feed.
* md5: 8fd047914863bf9b3a4b1514ec51c32c
* size: 32188
*
* If networking/proxy configuration is wrong these tests will fail..
*/
global $CFG;
require_once($CFG->libdir.'/simplepie/moodle_simplepie.php');
class moodlesimplepie_test extends UnitTestCase {
public static $includecoverage = array('lib/simplepie/moodle_simplepie.php');
# A url we know exists and is valid
const VALIDURL = 'http://download.moodle.org/unittest/rsstest.xml';
# A url which we know doesn't exist
const INVALIDURL = 'http://download.moodle.org/unittest/rsstest-which-doesnt-exist.xml';
# This tinyurl redirects to th rsstest.xml file
const REDIRECTURL = 'http://tinyurl.com/lvyslv';
function setUp() {
moodle_simplepie::reset_cache();
}
function test_getfeed() {
$feed = new moodle_simplepie(moodlesimplepie_test::VALIDURL);
$this->assertIsA($feed, 'moodle_simplepie');
$this->assertFalse($feed->error(), "Failed to load the sample RSS file. Please check your proxy settings in Moodle. %s");
if ($feed->error()) {
return;
}
$this->assertEqual($feed->get_title(), 'Moodle News');
$this->assertEqual($feed->get_link(), 'http://moodle.org/mod/forum/view.php?f=1');
$this->assertEqual($feed->get_description(), "General news about Moodle.\n\nMoodle is a leading open-source course management system (CMS) - a software package designed to help educators create quality online courses. Such e-learning systems are sometimes also called Learning Management Systems (LMS) or Virtual Learning Environments (VLE). One of the main advantages of Moodle over other systems is a strong grounding in social constructionist pedagogy.");
$this->assertEqual($feed->get_copyright(), '&amp;#169; 2007 moodle');
$this->assertEqual($feed->get_image_url(), 'http://moodle.org/pix/i/rsssitelogo.gif');
$this->assertEqual($feed->get_image_title(), 'moodle');
$this->assertEqual($feed->get_image_link(), 'http://moodle.org');
$this->assertEqual($feed->get_image_width(), '140');
$this->assertEqual($feed->get_image_height(), '35');
$this->assertTrue($items = $feed->get_items());
$this->assertEqual(count($items), 15);
$this->assertTrue($itemone = $feed->get_item(0));
if (!$itemone) {
return;
}
$this->assertEqual($itemone->get_title(), 'Google HOP contest encourages pre-University students to work on Moodle');
$this->assertEqual($itemone->get_link(), 'http://moodle.org/mod/forum/discuss.php?d=85629');
$this->assertEqual($itemone->get_id(), 'http://moodle.org/mod/forum/discuss.php?d=85629');
$description = <<<EOD
by Martin Dougiamas. &nbsp;<p><p><img src="http://code.google.com/opensource/ghop/2007-8/images/ghoplogosm.jpg" align="right" style="margin:10px" />After their very successful <a href="http://code.google.com/soc/2007/">Summer of Code</a> program for University students, Google just announced their new <a href="http://code.google.com/opensource/ghop/2007-8/">Highly Open Participation contest</a>, designed to encourage pre-University students to get involved with open source projects via much smaller and diverse contributions.<br />
<br />
I'm very proud that Moodle has been selected as one of only <a href="http://code.google.com/opensource/ghop/2007-8/projects.html">ten open source projects</a> to take part in the inaugural year of this new contest.<br />
<br />
We have a <a href="http://code.google.com/p/google-highly-open-participation-moodle/issues/list">long list of small tasks</a> prepared already for students, but we would definitely like to see the Moodle community come up with more - so if you have any ideas for things you want to see done, please <a href="http://code.google.com/p/google-highly-open-participation-moodle/">send them to us</a>! Just remember they can't take more than five days.<br />
<br />
Google will pay students US$100 for every three tasks they successfully complete, plus send a cool T-shirt. There are also grand prizes including an all-expenses-paid trip to Google HQ in Mountain View, California. If you are (or know) a young student with an interest in Moodle then give it a go! <br />
<br />
You can find out all the details on the <a href="http://code.google.com/p/google-highly-open-participation-moodle/">Moodle/GHOP contest site</a>.</p></p>
EOD;
$this->assertEqual($itemone->get_description(), $description);
// TODO fix this so it uses $CFG by default
$this->assertEqual($itemone->get_date('U'), 1196412453);
// last item
$this->assertTrue($feed->get_item(14));
// Past last item
$this->assertFalse($feed->get_item(15));
}
/*
* Test retrieving a url which doesn't exist
*/
function test_failurl() {
$feed = @new moodle_simplepie(moodlesimplepie_test::INVALIDURL); // we do not want this in php error log
$this->assertTrue($feed->error());
}
/*
* Test retrieving a url with broken proxy configuration
*/
function test_failproxy() {
global $CFG;
$oldproxy = $CFG->proxyhost;
$CFG->proxyhost = 'xxxxxxxxxxxxxxx.moodle.org';
$feed = new moodle_simplepie(moodlesimplepie_test::VALIDURL);
$this->assertTrue($feed->error());
$this->assertFalse($feed->get_title());
$CFG->proxyhost = $oldproxy;
}
/*
* Test retrieving a url which sends a redirect to another valid feed
*/
function test_redirect() {
global $CFG;
$feed = new moodle_simplepie(moodlesimplepie_test::REDIRECTURL);
$this->assertFalse($feed->error());
$this->assertEqual($feed->get_title(), 'Moodle News');
$this->assertEqual($feed->get_link(), 'http://moodle.org/mod/forum/view.php?f=1');
}
}
-422
View File
@@ -1,422 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Functions to support installation process
*
* @package core
* @subpackage lib
* @copyright 2010 Petr Skoda (http://skodak.org)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Unit tests for our utf-8 aware text processing
*
* @package core
* @subpackage lib
* @copyright 2010 Petr Skoda (http://skodak.org)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class textlib_test extends UnitTestCase {
public static $includecoverage = array('lib/textlib.class.php');
public function test_parse_charset() {
$this->assertIdentical(textlib::parse_charset('Cp1250'), 'windows-1250');
// does typo3 work? some encoding moodle does not use
$this->assertIdentical(textlib::parse_charset('ms-ansi'), 'windows-1252');
}
public function test_convert() {
$utf8 = "Žluťoučký koníček";
$iso2 = pack("H*", "ae6c75bb6f75e86bfd206b6f6eede8656b");
$win = pack("H*", "8e6c759d6f75e86bfd206b6f6eede8656b");
$this->assertIdentical(textlib::convert($utf8, 'utf-8', 'iso-8859-2'), $iso2);
$this->assertIdentical(textlib::convert($iso2, 'iso-8859-2', 'utf-8'), $utf8);
$this->assertIdentical(textlib::convert($utf8, 'utf-8', 'win-1250'), $win);
$this->assertIdentical(textlib::convert($win, 'win-1250', 'utf-8'), $utf8);
$this->assertIdentical(textlib::convert($win, 'win-1250', 'iso-8859-2'), $iso2);
$this->assertIdentical(textlib::convert($iso2, 'iso-8859-2', 'win-1250'), $win);
$this->assertIdentical(textlib::convert($iso2, 'iso-8859-2', 'iso-8859-2'), $iso2);
$this->assertIdentical(textlib::convert($win, 'win-1250', 'cp1250'), $win);
$utf8 = '言語設定';
$str = pack("H*", "b8c0b8ecc0dfc4ea"); //EUC-JP
$this->assertIdentical(textlib::convert($utf8, 'utf-8', 'EUC-JP'), $str);
$this->assertIdentical(textlib::convert($str, 'EUC-JP', 'utf-8'), $utf8);
$str = pack("H*", "1b24423840386c405f446a1b2842"); //ISO-2022-JP
$this->assertIdentical(textlib::convert($utf8, 'utf-8', 'ISO-2022-JP'), $str);
$this->assertIdentical(textlib::convert($str, 'ISO-2022-JP', 'utf-8'), $utf8);
$str = pack("H*", "8cbe8cea90dd92e8"); //SHIFT-JIS
$this->assertIdentical(textlib::convert($utf8, 'utf-8', 'SHIFT-JIS'), $str);
$this->assertIdentical(textlib::convert($str, 'SHIFT-JIS', 'utf-8'), $utf8);
$utf8 = '简体中文';
$str = pack("H*", "bcf2cce5d6d0cec4"); //GB2312
$this->assertIdentical(textlib::convert($utf8, 'utf-8', 'GB2312'), $str);
$this->assertIdentical(textlib::convert($str, 'GB2312', 'utf-8'), $utf8);
$str = pack("H*", "bcf2cce5d6d0cec4"); //GB18030
$this->assertIdentical(textlib::convert($utf8, 'utf-8', 'GB18030'), $str);
$this->assertIdentical(textlib::convert($str, 'GB18030', 'utf-8'), $utf8);
}
public function test_substr() {
$str = "Žluťoučký koníček";
$this->assertIdentical(textlib::substr($str, 0), $str);
$this->assertIdentical(textlib::substr($str, 1), 'luťoučký koníček');
$this->assertIdentical(textlib::substr($str, 1, 3), 'luť');
$this->assertIdentical(textlib::substr($str, 0, 100), $str);
$this->assertIdentical(textlib::substr($str, -3, 2), 'če');
$iso2 = pack("H*", "ae6c75bb6f75e86bfd206b6f6eede8656b");
$this->assertIdentical(textlib::substr($iso2, 1, 3, 'iso-8859-2'), textlib::convert('luť', 'utf-8', 'iso-8859-2'));
$this->assertIdentical(textlib::substr($iso2, 0, 100, 'iso-8859-2'), textlib::convert($str, 'utf-8', 'iso-8859-2'));
$this->assertIdentical(textlib::substr($iso2, -3, 2, 'iso-8859-2'), textlib::convert('če', 'utf-8', 'iso-8859-2'));
$win = pack("H*", "8e6c759d6f75e86bfd206b6f6eede8656b");
$this->assertIdentical(textlib::substr($win, 1, 3, 'cp1250'), textlib::convert('luť', 'utf-8', 'cp1250'));
$this->assertIdentical(textlib::substr($win, 0, 100, 'cp1250'), textlib::convert($str, 'utf-8', 'cp1250'));
$this->assertIdentical(textlib::substr($win, -3, 2, 'cp1250'), textlib::convert('če', 'utf-8', 'cp1250'));
$str = pack("H*", "b8c0b8ecc0dfc4ea"); //EUC-JP
$s = pack("H*", "b8ec"); //EUC-JP
$this->assertIdentical(textlib::substr($str, 1, 1, 'EUC-JP'), $s);
$str = pack("H*", "1b24423840386c405f446a1b2842"); //ISO-2022-JP
$s = pack("H*", "1b2442386c1b2842"); //ISO-2022-JP
$this->assertIdentical(textlib::substr($str, 1, 1, 'ISO-2022-JP'), $s);
$str = pack("H*", "8cbe8cea90dd92e8"); //SHIFT-JIS
$s = pack("H*", "8cea"); //SHIFT-JIS
$this->assertIdentical(textlib::substr($str, 1, 1, 'SHIFT-JIS'), $s);
$str = pack("H*", "bcf2cce5d6d0cec4"); //GB2312
$s = pack("H*", "cce5"); //GB2312
$this->assertIdentical(textlib::substr($str, 1, 1, 'GB2312'), $s);
$str = pack("H*", "bcf2cce5d6d0cec4"); //GB18030
$s = pack("H*", "cce5"); //GB18030
$this->assertIdentical(textlib::substr($str, 1, 1, 'GB18030'), $s);
}
public function test_strlen() {
$str = "Žluťoučký koníček";
$this->assertIdentical(textlib::strlen($str), 17);
$iso2 = pack("H*", "ae6c75bb6f75e86bfd206b6f6eede8656b");
$this->assertIdentical(textlib::strlen($iso2, 'iso-8859-2'), 17);
$win = pack("H*", "8e6c759d6f75e86bfd206b6f6eede8656b");
$this->assertIdentical(textlib::strlen($win, 'cp1250'), 17);
$str = pack("H*", "b8ec"); //EUC-JP
$this->assertIdentical(textlib::strlen($str, 'EUC-JP'), 1);
$str = pack("H*", "b8c0b8ecc0dfc4ea"); //EUC-JP
$this->assertIdentical(textlib::strlen($str, 'EUC-JP'), 4);
$str = pack("H*", "1b2442386c1b2842"); //ISO-2022-JP
$this->assertIdentical(textlib::strlen($str, 'ISO-2022-JP'), 1);
$str = pack("H*", "1b24423840386c405f446a1b2842"); //ISO-2022-JP
$this->assertIdentical(textlib::strlen($str, 'ISO-2022-JP'), 4);
$str = pack("H*", "8cea"); //SHIFT-JIS
$this->assertIdentical(textlib::strlen($str, 'SHIFT-JIS'), 1);
$str = pack("H*", "8cbe8cea90dd92e8"); //SHIFT-JIS
$this->assertIdentical(textlib::strlen($str, 'SHIFT-JIS'), 4);
$str = pack("H*", "cce5"); //GB2312
$this->assertIdentical(textlib::strlen($str, 'GB2312'), 1);
$str = pack("H*", "bcf2cce5d6d0cec4"); //GB2312
$this->assertIdentical(textlib::strlen($str, 'GB2312'), 4);
$str = pack("H*", "cce5"); //GB18030
$this->assertIdentical(textlib::strlen($str, 'GB18030'), 1);
$str = pack("H*", "bcf2cce5d6d0cec4"); //GB18030
$this->assertIdentical(textlib::strlen($str, 'GB18030'), 4);
}
public function test_strtolower() {
$str = "Žluťoučký koníček";
$low = 'žluťoučký koníček';
$this->assertIdentical(textlib::strtolower($str), $low);
$iso2 = pack("H*", "ae6c75bb6f75e86bfd206b6f6eede8656b");
$this->assertIdentical(textlib::strtolower($iso2, 'iso-8859-2'), textlib::convert($low, 'utf-8', 'iso-8859-2'));
$win = pack("H*", "8e6c759d6f75e86bfd206b6f6eede8656b");
$this->assertIdentical(textlib::strtolower($win, 'cp1250'), textlib::convert($low, 'utf-8', 'cp1250'));
$str = '言語設定';
$this->assertIdentical(textlib::strtolower($str), $str);
$str = '简体中文';
$this->assertIdentical(textlib::strtolower($str), $str);
$str = pack("H*", "1b24423840386c405f446a1b2842"); //ISO-2022-JP
$this->assertIdentical(textlib::strtolower($str, 'ISO-2022-JP'), $str);
$str = pack("H*", "8cbe8cea90dd92e8"); //SHIFT-JIS
$this->assertIdentical(textlib::strtolower($str, 'SHIFT-JIS'), $str);
$str = pack("H*", "bcf2cce5d6d0cec4"); //GB2312
$this->assertIdentical(textlib::strtolower($str, 'GB2312'), $str);
$str = pack("H*", "bcf2cce5d6d0cec4"); //GB18030
$this->assertIdentical(textlib::strtolower($str, 'GB18030'), $str);
}
public function test_strtoupper() {
$str = "Žluťoučký koníček";
$up = 'ŽLUŤOUČKÝ KONÍČEK';
$this->assertIdentical(textlib::strtoupper($str), $up);
$iso2 = pack("H*", "ae6c75bb6f75e86bfd206b6f6eede8656b");
$this->assertIdentical(textlib::strtoupper($iso2, 'iso-8859-2'), textlib::convert($up, 'utf-8', 'iso-8859-2'));
$win = pack("H*", "8e6c759d6f75e86bfd206b6f6eede8656b");
$this->assertIdentical(textlib::strtoupper($win, 'cp1250'), textlib::convert($up, 'utf-8', 'cp1250'));
$str = '言語設定';
$this->assertIdentical(textlib::strtoupper($str), $str);
$str = '简体中文';
$this->assertIdentical(textlib::strtoupper($str), $str);
$str = pack("H*", "1b24423840386c405f446a1b2842"); //ISO-2022-JP
$this->assertIdentical(textlib::strtoupper($str, 'ISO-2022-JP'), $str);
$str = pack("H*", "8cbe8cea90dd92e8"); //SHIFT-JIS
$this->assertIdentical(textlib::strtoupper($str, 'SHIFT-JIS'), $str);
$str = pack("H*", "bcf2cce5d6d0cec4"); //GB2312
$this->assertIdentical(textlib::strtoupper($str, 'GB2312'), $str);
$str = pack("H*", "bcf2cce5d6d0cec4"); //GB18030
$this->assertIdentical(textlib::strtoupper($str, 'GB18030'), $str);
}
public function test_strpos() {
$str = "Žluťoučký koníček";
$this->assertIdentical(textlib::strpos($str, 'koníč'), 10);
}
public function test_strrpos() {
$str = "Žluťoučký koníček";
$this->assertIdentical(textlib::strrpos($str, 'o'), 11);
}
public function test_specialtoascii() {
$str = "Žluťoučký koníček";
$this->assertIdentical(textlib::specialtoascii($str), 'Zlutoucky konicek');
}
public function test_encode_mimeheader() {
$str = "Žluťoučký koníček";
$this->assertIdentical(textlib::encode_mimeheader($str), '=?utf-8?B?xb1sdcWlb3XEjWvDvSBrb27DrcSNZWs=?=');
}
public function test_entities_to_utf8() {
$str = "&#x17d;lu&#x165;ou&#x10d;k&#xfd; kon&#237;&#269;ek";
$this->assertIdentical(textlib::entities_to_utf8($str), "Žluťoučký koníček");
}
public function test_utf8_to_entities() {
$str = "Žluťoučký koníček";
$this->assertIdentical(textlib::utf8_to_entities($str), "&#x17d;lu&#x165;ou&#x10d;k&#xfd; kon&#xed;&#x10d;ek");
$this->assertIdentical(textlib::utf8_to_entities($str, true), "&#381;lu&#357;ou&#269;k&#253; kon&#237;&#269;ek");
}
public function test_trim_utf8_bom() {
$bom = "\xef\xbb\xbf";
$str = "Žluťoučký koníček";
$this->assertIdentical(textlib::trim_utf8_bom($bom.$str.$bom), $str.$bom);
}
public function test_get_encodings() {
$encodings = textlib::get_encodings();
$this->assertTrue(is_array($encodings));
$this->assertTrue(count($encodings) > 1);
$this->assertTrue(isset($encodings['UTF-8']));
}
public function test_code2utf8() {
$this->assertIdentical(textlib::code2utf8(381), 'Ž');
}
public function test_strtotitle() {
$str = "žluťoučký koníček";
$this->assertIdentical(textlib::strtotitle($str), "Žluťoučký Koníček");
}
public function test_deprecated_textlib_get_instance() {
global $CFG;
$debugging = $CFG->debug;
$CFG->debug = DEBUG_NORMAL;
$textlib = textlib_get_instance();
$this->assertIdentical($textlib->substr('abc', 1, 1), 'b');
$this->assertIdentical($textlib->strlen('abc'), 3);
$this->assertIdentical($textlib->strtoupper('Abc'), 'ABC');
$this->assertIdentical($textlib->strtolower('Abc'), 'abc');
$this->assertIdentical($textlib->strpos('abc', 'a'), 0);
$this->assertIdentical($textlib->strpos('abc', 'd'), false);
$this->assertIdentical($textlib->strrpos('abcabc', 'a'), 3);
$this->assertIdentical($textlib->specialtoascii('ábc'), 'abc');
$this->assertIdentical($textlib->strtotitle('abc ABC'), 'Abc Abc');
$CFG->debug = $debugging;
}
}
/**
* Unit tests for our utf-8 aware collator.
*
* Used for sorting.
*
* @package core
* @subpackage lib
* @copyright 2011 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class collatorlib_test extends UnitTestCase {
protected $initiallang = null;
protected $error = null;
public function setUp() {
global $SESSION;
if (isset($SESSION->lang)) {
$this->initiallang = $SESSION->lang;
}
$SESSION->lang = 'en'; // make sure we test en language to get consistent results, hopefully all systems have this locale
if (extension_loaded('intl')) {
$this->error = 'Collation aware sorting not supported';
} else {
$this->error = 'Collation aware sorting not supported, PHP extension "intl" is not available.';
}
parent::setUp();
}
public function tearDown() {
global $SESSION;
parent::tearDown();
if ($this->initiallang !== null) {
$SESSION->lang = $this->initiallang;
$this->initiallang = null;
} else {
unset($SESSION->lang);
}
}
function test_asort() {
$arr = array('b' => 'ab', 1 => 'aa', 0 => 'cc');
collatorlib::asort($arr);
$this->assertIdentical(array_keys($arr), array(1, 'b', 0));
$this->assertIdentical(array_values($arr), array('aa', 'ab', 'cc'));
$arr = array('a' => 'áb', 'b' => 'ab', 1 => 'aa', 0=>'cc');
collatorlib::asort($arr);
$this->assertIdentical(array_keys($arr), array(1, 'b', 'a', 0), $this->error);
$this->assertIdentical(array_values($arr), array('aa', 'ab', 'áb', 'cc'), $this->error);
}
function test_asort_objects_by_method() {
$objects = array(
'b' => new string_test_class('ab'),
1 => new string_test_class('aa'),
0 => new string_test_class('cc')
);
collatorlib::asort_objects_by_method($objects, 'get_protected_name');
$this->assertIdentical(array_keys($objects), array(1, 'b', 0));
$this->assertIdentical($this->get_ordered_names($objects, 'get_protected_name'), array('aa', 'ab', 'cc'));
$objects = array(
'a' => new string_test_class('áb'),
'b' => new string_test_class('ab'),
1 => new string_test_class('aa'),
0 => new string_test_class('cc')
);
collatorlib::asort_objects_by_method($objects, 'get_private_name');
$this->assertIdentical(array_keys($objects), array(1, 'b', 'a', 0), $this->error);
$this->assertIdentical($this->get_ordered_names($objects, 'get_private_name'), array('aa', 'ab', 'áb', 'cc'), $this->error);
}
function test_asort_objects_by_property() {
$objects = array(
'b' => new string_test_class('ab'),
1 => new string_test_class('aa'),
0 => new string_test_class('cc')
);
collatorlib::asort_objects_by_property($objects, 'publicname');
$this->assertIdentical(array_keys($objects), array(1, 'b', 0));
$this->assertIdentical($this->get_ordered_names($objects, 'publicname'), array('aa', 'ab', 'cc'));
$objects = array(
'a' => new string_test_class('áb'),
'b' => new string_test_class('ab'),
1 => new string_test_class('aa'),
0 => new string_test_class('cc')
);
collatorlib::asort_objects_by_property($objects, 'publicname');
$this->assertIdentical(array_keys($objects), array(1, 'b', 'a', 0), $this->error);
$this->assertIdentical($this->get_ordered_names($objects, 'publicname'), array('aa', 'ab', 'áb', 'cc'), $this->error);
}
protected function get_ordered_names($objects, $methodproperty = 'get_protected_name') {
$return = array();
foreach ($objects as $object) {
if ($methodproperty == 'publicname') {
$return[] = $object->publicname;
} else {
$return[] = $object->$methodproperty();
}
}
return $return;
}
}
/**
* Simple class used to work with the unit test.
*
* @package core
* @subpackage lib
* @copyright 2011 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class string_test_class extends stdClass {
public $publicname;
protected $protectedname;
private $privatename;
public function __construct($name) {
$this->publicname = $name;
$this->protectedname = $name;
$this->privatename = $name;
}
public function get_protected_name() {
return $this->protectedname;
}
public function get_private_name() {
return $this->publicname;
}
}
-169
View File
@@ -1,169 +0,0 @@
<?php
/**
* Unit tests for (some of) ../weblib.php.
*
* @copyright &copy; 2006 The Open University
* @author [email protected]
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package moodlecore
*/
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
class web_test extends UnitTestCase {
public static $includecoverage = array('lib/weblib.php');
function setUp() {
}
function tearDown() {
}
function test_format_string() {
global $CFG;
// Ampersands
$this->assertEqual(format_string("& &&&&& &&"), "&amp; &amp;&amp;&amp;&amp;&amp; &amp;&amp;");
$this->assertEqual(format_string("ANother & &&&&& Category"), "ANother &amp; &amp;&amp;&amp;&amp;&amp; Category");
$this->assertEqual(format_string("ANother & &&&&& Category", true), "ANother &amp; &amp;&amp;&amp;&amp;&amp; Category");
$this->assertEqual(format_string("Nick's Test Site & Other things", true), "Nick's Test Site &amp; Other things");
// String entities
$this->assertEqual(format_string("&quot;"), "&quot;");
// Digital entities
$this->assertEqual(format_string("&11234;"), "&11234;");
// Unicode entities
$this->assertEqual(format_string("&#4475;"), "&#4475;");
// < and > signs
$originalformatstringstriptags = $CFG->formatstringstriptags;
$CFG->formatstringstriptags = false;
$this->assertEqual(format_string('x < 1'), 'x &lt; 1');
$this->assertEqual(format_string('x > 1'), 'x &gt; 1');
$this->assertEqual(format_string('x < 1 and x > 0'), 'x &lt; 1 and x &gt; 0');
$CFG->formatstringstriptags = true;
$this->assertEqual(format_string('x < 1'), 'x &lt; 1');
$this->assertEqual(format_string('x > 1'), 'x &gt; 1');
$this->assertEqual(format_string('x < 1 and x > 0'), 'x &lt; 1 and x &gt; 0');
$CFG->formatstringstriptags = $originalformatstringstriptags;
}
function test_s() {
$this->assertEqual(s("This Breaks \" Strict"), "This Breaks &quot; Strict");
$this->assertEqual(s("This Breaks <a>\" Strict</a>"), "This Breaks &lt;a&gt;&quot; Strict&lt;/a&gt;");
}
function test_format_text_email() {
$this->assertEqual("This is a TEST",
format_text_email('<p>This is a <strong>test</strong></p>',FORMAT_HTML));
$this->assertEqual("This is a TEST",
format_text_email('<p class="frogs">This is a <strong class=\'fishes\'>test</strong></p>',FORMAT_HTML));
$this->assertEqual('& so is this',
format_text_email('&amp; so is this',FORMAT_HTML));
$this->assertEqual('Two bullets: '.textlib::code2utf8(8226).' *',
format_text_email('Two bullets: &#x2022; &#8226;',FORMAT_HTML));
$this->assertEqual(textlib::code2utf8(0x7fd2).textlib::code2utf8(0x7fd2),
format_text_email('&#x7fd2;&#x7FD2;',FORMAT_HTML));
}
function test_highlight() {
$this->assertEqual(highlight('good', 'This is good'), 'This is <span class="highlight">good</span>');
$this->assertEqual(highlight('SpaN', 'span'), '<span class="highlight">span</span>');
$this->assertEqual(highlight('span', 'SpaN'), '<span class="highlight">SpaN</span>');
$this->assertEqual(highlight('span', '<span>span</span>'), '<span><span class="highlight">span</span></span>');
$this->assertEqual(highlight('good is', 'He is good'), 'He <span class="highlight">is</span> <span class="highlight">good</span>');
$this->assertEqual(highlight('+good', 'This is good'), 'This is <span class="highlight">good</span>');
$this->assertEqual(highlight('-good', 'This is good'), 'This is good');
$this->assertEqual(highlight('+good', 'This is goodness'), 'This is goodness');
$this->assertEqual(highlight('good', 'This is goodness'), 'This is <span class="highlight">good</span>ness');
}
function test_replace_ampersands() {
$this->assertEqual(replace_ampersands_not_followed_by_entity("This & that &nbsp;"), "This &amp; that &nbsp;");
$this->assertEqual(replace_ampersands_not_followed_by_entity("This &nbsp that &nbsp;"), "This &amp;nbsp that &nbsp;");
}
function test_strip_links() {
$this->assertEqual(strip_links('this is a <a href="http://someaddress.com/query">link</a>'), 'this is a link');
}
function test_wikify_links() {
$this->assertEqual(wikify_links('this is a <a href="http://someaddress.com/query">link</a>'), 'this is a link [ http://someaddress.com/query ]');
}
function test_moodle_url_round_trip() {
$strurl = 'http://moodle.org/course/view.php?id=5';
$url = new moodle_url($strurl);
$this->assertEqual($strurl, $url->out(false));
$strurl = 'http://moodle.org/user/index.php?contextid=53&sifirst=M&silast=D';
$url = new moodle_url($strurl);
$this->assertEqual($strurl, $url->out(false));
}
function test_moodle_url_round_trip_array_params() {
$strurl = 'http://example.com/?a%5B1%5D=1&a%5B2%5D=2';
$url = new moodle_url($strurl);
$this->assertEqual($strurl, $url->out(false));
$url = new moodle_url('http://example.com/?a[1]=1&a[2]=2');
$this->assertEqual($strurl, $url->out(false));
// For un-keyed array params, we expect 0..n keys to be returned
$strurl = 'http://example.com/?a%5B0%5D=0&a%5B1%5D=1';
$url = new moodle_url('http://example.com/?a[]=0&a[]=1');
$this->assertEqual($strurl, $url->out(false));
}
function test_compare_url() {
$url1 = new moodle_url('index.php', array('var1' => 1, 'var2' => 2));
$url2 = new moodle_url('index2.php', array('var1' => 1, 'var2' => 2, 'var3' => 3));
$this->assertFalse($url1->compare($url2, URL_MATCH_BASE));
$this->assertFalse($url1->compare($url2, URL_MATCH_PARAMS));
$this->assertFalse($url1->compare($url2, URL_MATCH_EXACT));
$url2 = new moodle_url('index.php', array('var1' => 1, 'var3' => 3));
$this->assertTrue($url1->compare($url2, URL_MATCH_BASE));
$this->assertFalse($url1->compare($url2, URL_MATCH_PARAMS));
$this->assertFalse($url1->compare($url2, URL_MATCH_EXACT));
$url2 = new moodle_url('index.php', array('var1' => 1, 'var2' => 2, 'var3' => 3));
$this->assertTrue($url1->compare($url2, URL_MATCH_BASE));
$this->assertTrue($url1->compare($url2, URL_MATCH_PARAMS));
$this->assertFalse($url1->compare($url2, URL_MATCH_EXACT));
$url2 = new moodle_url('index.php', array('var2' => 2, 'var1' => 1));
$this->assertTrue($url1->compare($url2, URL_MATCH_BASE));
$this->assertTrue($url1->compare($url2, URL_MATCH_PARAMS));
$this->assertTrue($url1->compare($url2, URL_MATCH_EXACT));
}
function test_out_as_local_url() {
$url1 = new moodle_url('/lib/simpletest/testweblib.php');
$this->assertEqual('/lib/simpletest/testweblib.php', $url1->out_as_local_url());
$url2 = new moodle_url('http://www.google.com/lib/simpletest/testweblib.php');
$this->expectException('coding_exception');
$url2->out_as_local_url();
}
public function test_clean_text() {
$text = "lala <applet>xx</applet>";
$this->assertEqual($text, clean_text($text, FORMAT_PLAIN));
$this->assertEqual('lala xx', clean_text($text, FORMAT_MARKDOWN));
$this->assertEqual('lala xx', clean_text($text, FORMAT_MOODLE));
$this->assertEqual('lala xx', clean_text($text, FORMAT_HTML));
}
}