2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Support library for the cache PHPUnit tests.
20 * This file is part of Moodle's cache API, affectionately called MUC.
21 * It contains the components that are requried in order to use caching.
25 * @copyright 2012 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->dirroot.'/cache/locallib.php');
34 * Override the default cache configuration for our own maniacal purposes.
36 * This class was originally named cache_config_phpunittest but was renamed in 2.9
37 * because it is used for both unit tests and acceptance tests.
40 * @copyright 2012 Sam Hemelryk
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 class cache_config_testing extends cache_config_writer {
46 * Creates the default configuration and saves it.
48 * This function calls config_save, however it is safe to continue using it afterwards as this function should only ever
49 * be called when there is no configuration file already.
51 * @param bool $forcesave If set to true then we will forcefully save the default configuration file.
52 * @return true|array Returns true if the default configuration was successfully created.
53 * Returns a configuration array if it could not be saved. This is a bad situation. Check your error logs.
55 public static function create_default_configuration($forcesave = false) {
58 // We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
59 // default store plugins are protected from deletion.
61 $writer->configstores = self::get_default_stores();
62 $writer->configdefinitions = self::locate_definitions();
63 $defaultapplication = 'default_application';
65 $appdefine = defined('TEST_CACHE_USING_APPLICATION_STORE') ? TEST_CACHE_USING_APPLICATION_STORE : false;
66 if ($appdefine !== false && preg_match('/^[a-zA-Z][a-zA-Z0-9_]+$/', $appdefine)) {
67 $expectedstore = $appdefine;
68 $file = $CFG->dirroot.'/cache/stores/'.$appdefine.'/lib.php';
69 $class = 'cachestore_'.$appdefine;
70 if (file_exists($file)) {
73 if (class_exists($class) && $class::ready_to_be_used_for_testing()) {
74 /* @var cache_store $class */
75 $writer->configstores['test_application'] = array(
76 'name' => 'test_application',
77 'plugin' => $expectedstore,
78 'modes' => $class::get_supported_modes(),
79 'features' => $class::get_supported_features(),
80 'configuration' => $class::unit_test_configuration()
83 $defaultapplication = 'test_application';
87 $writer->configmodemappings = array(
89 'mode' => cache_store::MODE_APPLICATION,
90 'store' => $defaultapplication,
94 'mode' => cache_store::MODE_SESSION,
95 'store' => 'default_session',
99 'mode' => cache_store::MODE_REQUEST,
100 'store' => 'default_request',
104 $writer->configlocks = array(
105 'default_file_lock' => array(
106 'name' => 'cachelock_file_default',
107 'type' => 'cachelock_file',
108 'dir' => 'filelocks',
113 $factory = cache_factory::instance();
114 // We expect the cache to be initialising presently. If its not then something has gone wrong and likely
115 // we are now in a loop.
116 if (!$forcesave && $factory->get_state() !== cache_factory::STATE_INITIALISING) {
117 return $writer->generate_configuration_array();
119 $factory->set_state(cache_factory::STATE_SAVING);
120 $writer->config_save();
125 * Returns the expected path to the configuration file.
127 * We override this function to add handling for $CFG->altcacheconfigpath.
128 * We want to support it so that people can run unit tests against alternative cache setups.
129 * However we don't want to ever make changes to the file at $CFG->altcacheconfigpath so we
130 * always use dataroot and copy the alt file there as required.
132 * @throws cache_exception
133 * @return string The absolute path
135 protected static function get_config_file_path() {
137 // We always use this path.
138 $configpath = $CFG->dataroot.'/muc/config.php';
140 if (!empty($CFG->altcacheconfigpath)) {
142 // No need to check we are within a test here, this is the cache config class that gets used
143 // only when one of those is true.
144 if (!defined('TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH') || !TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH) {
145 // TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH has not being defined or is false, we want to use the default.
149 $path = $CFG->altcacheconfigpath;
150 if (is_dir($path) && is_writable($path)) {
151 // Its a writable directory, thats fine. Convert it to a file.
152 $path = $CFG->altcacheconfigpath.'/cacheconfig.php';
154 if (is_readable($path)) {
155 $directory = dirname($configpath);
156 if ($directory !== $CFG->dataroot && !file_exists($directory)) {
157 $result = make_writable_directory($directory, false);
159 throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Cannot create config directory. Check the permissions on your moodledata directory.');
162 // We don't care that this fails but we should let the developer know.
163 if (!is_readable($configpath) && !@copy($path, $configpath)) {
164 debugging('Failed to copy alt cache config file to required location');
169 // We always use the dataroot location.
174 * Adds a definition to the stack
175 * @param string $area
176 * @param array $properties
177 * @param bool $addmapping By default this method adds a definition and a mapping for that definition. You can
178 * however set this to false if you only want it to add the definition and not the mapping.
180 public function phpunit_add_definition($area, array $properties, $addmapping = true) {
181 if (!array_key_exists('overrideclass', $properties)) {
182 switch ($properties['mode']) {
183 case cache_store::MODE_APPLICATION:
184 $properties['overrideclass'] = 'cache_phpunit_application';
186 case cache_store::MODE_SESSION:
187 $properties['overrideclass'] = 'cache_phpunit_session';
189 case cache_store::MODE_REQUEST:
190 $properties['overrideclass'] = 'cache_phpunit_request';
194 $this->configdefinitions[$area] = $properties;
196 switch ($properties['mode']) {
197 case cache_store::MODE_APPLICATION:
198 $this->phpunit_add_definition_mapping($area, 'default_application', 0);
200 case cache_store::MODE_SESSION:
201 $this->phpunit_add_definition_mapping($area, 'default_session', 0);
203 case cache_store::MODE_REQUEST:
204 $this->phpunit_add_definition_mapping($area, 'default_request', 0);
211 * Removes a definition.
212 * @param string $name
214 public function phpunit_remove_definition($name) {
215 unset($this->configdefinitions[$name]);
219 * Removes the configured stores so that there are none available.
221 public function phpunit_remove_stores() {
222 $this->configstores = array();
226 * Forcefully adds a file store.
228 * @param string $name
230 public function phpunit_add_file_store($name) {
231 $this->configstores[$name] = array(
234 'configuration' => array(
239 'mappingsonly' => false,
240 'class' => 'cachestore_file',
242 'lock' => 'cachelock_file_default'
247 * Forcefully adds a session store.
249 * @param string $name
251 public function phpunit_add_session_store($name) {
252 $this->configstores[$name] = array(
254 'plugin' => 'session',
255 'configuration' => array(),
259 'class' => 'cachestore_session',
260 'lock' => 'cachelock_file_default',
265 * Forcefully injects a definition => store mapping.
267 * This function does no validation, you should only be calling if it you know
268 * exactly what to expect.
270 * @param string $definition
271 * @param string $store
274 public function phpunit_add_definition_mapping($definition, $store, $sort) {
275 $this->configdefinitionmappings[] = array(
277 'definition' => $definition,
283 * Overrides the default site identifier used by the Cache API so that we can be sure of what it is.
287 public function get_site_identifier() {
289 return $CFG->wwwroot.'phpunit';
293 * Checks if the configuration file exists.
295 * @return bool True if it exists
297 public static function config_file_exists() {
298 // Allow for late static binding by using static.
299 $configfilepath = static::get_config_file_path();
301 // Invalidate opcode php cache, so we get correct status of file.
302 core_component::invalidate_opcode_php_cache($configfilepath);
303 return file_exists($configfilepath);
309 * Dummy object for testing cacheable object interface and interaction
311 * Wake from cache needs specific testing at times to ensure that during multiple
312 * cache get() requests it's possible to verify that it's getting woken each time.
314 * @copyright 2012 Sam Hemelryk
315 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
317 class cache_phpunit_dummy_object extends stdClass implements cacheable_object {
329 * Test property time for verifying wake is run at each get() call.
332 public $propertytime;
335 * @param string $property1
336 * @param string $property2
338 public function __construct($property1, $property2, $propertytime = null) {
339 $this->property1 = $property1;
340 $this->property2 = $property2;
341 $this->propertytime = $propertytime === null ? microtime(true) : $propertytime;
344 * Prepares this object for caching
347 public function prepare_to_cache() {
348 return array($this->property1.'_ptc', $this->property2.'_ptc', $this->propertytime);
351 * Returns this object from the cache
353 * @return cache_phpunit_dummy_object
355 public static function wake_from_cache($data) {
357 if (!is_null($data[2])) {
358 // Windows 32bit microtime() resolution is 15ms, we ensure the time has moved forward.
360 $time = microtime(true);
361 } while ($time == $data[2]);
364 return new cache_phpunit_dummy_object(array_shift($data).'_wfc', array_shift($data).'_wfc', $time);
369 * Dummy data source object for testing data source interface and implementation
371 * @copyright 2012 Sam Hemelryk
372 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
374 class cache_phpunit_dummy_datasource implements cache_data_source {
376 * Returns an instance of this object for use with the cache.
378 * @param cache_definition $definition
379 * @return cache_phpunit_dummy_datasource
381 public static function get_instance_for_cache(cache_definition $definition) {
382 return new cache_phpunit_dummy_datasource();
386 * Loads a key for the cache.
391 public function load_for_cache($key) {
392 return $key.' has no value really.';
396 * Loads many keys for the cache
401 public function load_many_for_cache(array $keys) {
403 foreach ($keys as $key) {
404 $return[$key] = $key.' has no value really.';
411 * PHPUnit application cache loader.
413 * Used to expose things we could not otherwise see within an application cache.
415 * @copyright 2012 Sam Hemelryk
416 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
418 class cache_phpunit_application extends cache_application {
421 * Returns the class of the store immediately associated with this cache.
424 public function phpunit_get_store_class() {
425 return get_class($this->get_store());
429 * Returns all the interfaces the cache store implements.
432 public function phpunit_get_store_implements() {
433 return class_implements($this->get_store());
437 * Returns the given key directly from the static acceleration array.
440 * @return false|mixed
442 public function phpunit_static_acceleration_get($key) {
443 return $this->static_acceleration_get($key);
447 * Purges only the static acceleration while leaving the rest of the store in tack.
449 * Used for behaving like you have loaded 2 pages, and reset static while the backing store
450 * still contains all the same data.
453 public function phpunit_static_acceleration_purge() {
454 $this->static_acceleration_purge();
459 * PHPUnit session cache loader.
461 * Used to expose things we could not otherwise see within an session cache.
463 * @copyright 2012 Sam Hemelryk
464 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
466 class cache_phpunit_session extends cache_session {
469 * Returns the class of the store immediately associated with this cache.
472 public function phpunit_get_store_class() {
473 return get_class($this->get_store());
477 * Returns all the interfaces the cache store implements.
480 public function phpunit_get_store_implements() {
481 return class_implements($this->get_store());
486 * PHPUnit request cache loader.
488 * Used to expose things we could not otherwise see within an request cache.
490 * @copyright 2012 Sam Hemelryk
491 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
493 class cache_phpunit_request extends cache_request {
496 * Returns the class of the store immediately associated with this cache.
499 public function phpunit_get_store_class() {
500 return get_class($this->get_store());
504 * Returns all the interfaces the cache store implements.
507 public function phpunit_get_store_implements() {
508 return class_implements($this->get_store());
513 * Dummy overridden cache loader class that we can use to test overriding loader functionality.
515 * @copyright 2012 Sam Hemelryk
516 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
518 class cache_phpunit_dummy_overrideclass extends cache_application {
519 // Satisfying the code pre-checker is just part of my day job.
523 * Cache PHPUnit specific factory.
525 * @copyright 2012 Sam Hemelryk
526 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
528 class cache_phpunit_factory extends cache_factory {
530 * Exposes the cache_factory's disable method.
532 * Perhaps one day that method will be made public, for the time being it is protected.
534 public static function phpunit_disable() {