PageRenderTime 45ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/cache/tests/fixtures/lib.php

http://github.com/moodle/moodle
PHP | 582 lines | 257 code | 47 blank | 278 comment | 26 complexity | 4fd2506207b6626f3a9a98941bb0fae8 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  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.
  8. //
  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.
  13. //
  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/>.
  16. /**
  17. * Support library for the cache PHPUnit tests.
  18. *
  19. * This file is part of Moodle's cache API, affectionately called MUC.
  20. * It contains the components that are requried in order to use caching.
  21. *
  22. * @package core
  23. * @category cache
  24. * @copyright 2012 Sam Hemelryk
  25. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26. */
  27. defined('MOODLE_INTERNAL') || die();
  28. require_once($CFG->dirroot.'/cache/locallib.php');
  29. /**
  30. * Override the default cache configuration for our own maniacal purposes.
  31. *
  32. * This class was originally named cache_config_phpunittest but was renamed in 2.9
  33. * because it is used for both unit tests and acceptance tests.
  34. *
  35. * @since 2.9
  36. * @copyright 2012 Sam Hemelryk
  37. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  38. */
  39. class cache_config_testing extends cache_config_writer {
  40. /**
  41. * Creates the default configuration and saves it.
  42. *
  43. * This function calls config_save, however it is safe to continue using it afterwards as this function should only ever
  44. * be called when there is no configuration file already.
  45. *
  46. * @param bool $forcesave If set to true then we will forcefully save the default configuration file.
  47. * @return true|array Returns true if the default configuration was successfully created.
  48. * Returns a configuration array if it could not be saved. This is a bad situation. Check your error logs.
  49. */
  50. public static function create_default_configuration($forcesave = false) {
  51. global $CFG;
  52. // HACK ALERT.
  53. // We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
  54. // default store plugins are protected from deletion.
  55. $writer = new self;
  56. $writer->configstores = self::get_default_stores();
  57. $writer->configdefinitions = self::locate_definitions();
  58. $defaultapplication = 'default_application';
  59. $appdefine = defined('TEST_CACHE_USING_APPLICATION_STORE') ? TEST_CACHE_USING_APPLICATION_STORE : false;
  60. if ($appdefine !== false && preg_match('/^[a-zA-Z][a-zA-Z0-9_]+$/', $appdefine)) {
  61. $expectedstore = $appdefine;
  62. $file = $CFG->dirroot.'/cache/stores/'.$appdefine.'/lib.php';
  63. $class = 'cachestore_'.$appdefine;
  64. if (file_exists($file)) {
  65. require_once($file);
  66. }
  67. if (class_exists($class) && $class::ready_to_be_used_for_testing()) {
  68. /* @var cache_store $class */
  69. $writer->configstores['test_application'] = array(
  70. 'name' => 'test_application',
  71. 'plugin' => $expectedstore,
  72. 'modes' => $class::get_supported_modes(),
  73. 'features' => $class::get_supported_features(),
  74. 'configuration' => $class::unit_test_configuration()
  75. );
  76. $defaultapplication = 'test_application';
  77. }
  78. }
  79. $writer->configmodemappings = array(
  80. array(
  81. 'mode' => cache_store::MODE_APPLICATION,
  82. 'store' => $defaultapplication,
  83. 'sort' => -1
  84. ),
  85. array(
  86. 'mode' => cache_store::MODE_SESSION,
  87. 'store' => 'default_session',
  88. 'sort' => -1
  89. ),
  90. array(
  91. 'mode' => cache_store::MODE_REQUEST,
  92. 'store' => 'default_request',
  93. 'sort' => -1
  94. )
  95. );
  96. $writer->configlocks = array(
  97. 'default_file_lock' => array(
  98. 'name' => 'cachelock_file_default',
  99. 'type' => 'cachelock_file',
  100. 'dir' => 'filelocks',
  101. 'default' => true
  102. )
  103. );
  104. $factory = cache_factory::instance();
  105. // We expect the cache to be initialising presently. If its not then something has gone wrong and likely
  106. // we are now in a loop.
  107. if (!$forcesave && $factory->get_state() !== cache_factory::STATE_INITIALISING) {
  108. return $writer->generate_configuration_array();
  109. }
  110. $factory->set_state(cache_factory::STATE_SAVING);
  111. $writer->config_save();
  112. return true;
  113. }
  114. /**
  115. * Returns the expected path to the configuration file.
  116. *
  117. * We override this function to add handling for $CFG->altcacheconfigpath.
  118. * We want to support it so that people can run unit tests against alternative cache setups.
  119. * However we don't want to ever make changes to the file at $CFG->altcacheconfigpath so we
  120. * always use dataroot and copy the alt file there as required.
  121. *
  122. * @throws cache_exception
  123. * @return string The absolute path
  124. */
  125. protected static function get_config_file_path() {
  126. global $CFG;
  127. // We always use this path.
  128. $configpath = $CFG->dataroot.'/muc/config.php';
  129. if (!empty($CFG->altcacheconfigpath)) {
  130. // No need to check we are within a test here, this is the cache config class that gets used
  131. // only when one of those is true.
  132. if (!defined('TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH') || !TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH) {
  133. // TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH has not being defined or is false, we want to use the default.
  134. return $configpath;
  135. }
  136. $path = $CFG->altcacheconfigpath;
  137. if (is_dir($path) && is_writable($path)) {
  138. // Its a writable directory, thats fine. Convert it to a file.
  139. $path = $CFG->altcacheconfigpath.'/cacheconfig.php';
  140. }
  141. if (is_readable($path)) {
  142. $directory = dirname($configpath);
  143. if ($directory !== $CFG->dataroot && !file_exists($directory)) {
  144. $result = make_writable_directory($directory, false);
  145. if (!$result) {
  146. throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Cannot create config directory. Check the permissions on your moodledata directory.');
  147. }
  148. }
  149. // We don't care that this fails but we should let the developer know.
  150. if (!is_readable($configpath) && !@copy($path, $configpath)) {
  151. debugging('Failed to copy alt cache config file to required location');
  152. }
  153. }
  154. }
  155. // We always use the dataroot location.
  156. return $configpath;
  157. }
  158. /**
  159. * Adds a definition to the stack
  160. * @param string $area
  161. * @param array $properties
  162. * @param bool $addmapping By default this method adds a definition and a mapping for that definition. You can
  163. * however set this to false if you only want it to add the definition and not the mapping.
  164. */
  165. public function phpunit_add_definition($area, array $properties, $addmapping = true) {
  166. if (!array_key_exists('overrideclass', $properties)) {
  167. switch ($properties['mode']) {
  168. case cache_store::MODE_APPLICATION:
  169. $properties['overrideclass'] = 'cache_phpunit_application';
  170. break;
  171. case cache_store::MODE_SESSION:
  172. $properties['overrideclass'] = 'cache_phpunit_session';
  173. break;
  174. case cache_store::MODE_REQUEST:
  175. $properties['overrideclass'] = 'cache_phpunit_request';
  176. break;
  177. }
  178. }
  179. $this->configdefinitions[$area] = $properties;
  180. if ($addmapping) {
  181. switch ($properties['mode']) {
  182. case cache_store::MODE_APPLICATION:
  183. $this->phpunit_add_definition_mapping($area, 'default_application', 0);
  184. break;
  185. case cache_store::MODE_SESSION:
  186. $this->phpunit_add_definition_mapping($area, 'default_session', 0);
  187. break;
  188. case cache_store::MODE_REQUEST:
  189. $this->phpunit_add_definition_mapping($area, 'default_request', 0);
  190. break;
  191. }
  192. }
  193. }
  194. /**
  195. * Removes a definition.
  196. * @param string $name
  197. */
  198. public function phpunit_remove_definition($name) {
  199. unset($this->configdefinitions[$name]);
  200. }
  201. /**
  202. * Removes the configured stores so that there are none available.
  203. */
  204. public function phpunit_remove_stores() {
  205. $this->configstores = array();
  206. }
  207. /**
  208. * Forcefully adds a file store.
  209. *
  210. * @param string $name
  211. */
  212. public function phpunit_add_file_store($name) {
  213. $this->configstores[$name] = array(
  214. 'name' => $name,
  215. 'plugin' => 'file',
  216. 'configuration' => array(
  217. 'path' => ''
  218. ),
  219. 'features' => 6,
  220. 'modes' => 3,
  221. 'mappingsonly' => false,
  222. 'class' => 'cachestore_file',
  223. 'default' => false,
  224. 'lock' => 'cachelock_file_default'
  225. );
  226. }
  227. /**
  228. * Forcefully adds a session store.
  229. *
  230. * @param string $name
  231. */
  232. public function phpunit_add_session_store($name) {
  233. $this->configstores[$name] = array(
  234. 'name' => $name,
  235. 'plugin' => 'session',
  236. 'configuration' => array(),
  237. 'features' => 14,
  238. 'modes' => 2,
  239. 'default' => true,
  240. 'class' => 'cachestore_session',
  241. 'lock' => 'cachelock_file_default',
  242. );
  243. }
  244. /**
  245. * Forcefully injects a definition => store mapping.
  246. *
  247. * This function does no validation, you should only be calling if it you know
  248. * exactly what to expect.
  249. *
  250. * @param string $definition
  251. * @param string $store
  252. * @param int $sort
  253. */
  254. public function phpunit_add_definition_mapping($definition, $store, $sort) {
  255. $this->configdefinitionmappings[] = array(
  256. 'store' => $store,
  257. 'definition' => $definition,
  258. 'sort' => (int)$sort
  259. );
  260. }
  261. /**
  262. * Overrides the default site identifier used by the Cache API so that we can be sure of what it is.
  263. *
  264. * @return string
  265. */
  266. public function get_site_identifier() {
  267. global $CFG;
  268. return $CFG->wwwroot.'phpunit';
  269. }
  270. /**
  271. * Checks if the configuration file exists.
  272. *
  273. * @return bool True if it exists
  274. */
  275. public static function config_file_exists() {
  276. // Allow for late static binding by using static.
  277. $configfilepath = static::get_config_file_path();
  278. // Invalidate opcode php cache, so we get correct status of file.
  279. core_component::invalidate_opcode_php_cache($configfilepath);
  280. return file_exists($configfilepath);
  281. }
  282. }
  283. /**
  284. * Dummy object for testing cacheable object interface and interaction
  285. *
  286. * Wake from cache needs specific testing at times to ensure that during multiple
  287. * cache get() requests it's possible to verify that it's getting woken each time.
  288. *
  289. * @copyright 2012 Sam Hemelryk
  290. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  291. */
  292. class cache_phpunit_dummy_object extends stdClass implements cacheable_object {
  293. /**
  294. * Test property 1
  295. * @var string
  296. */
  297. public $property1;
  298. /**
  299. * Test property 1
  300. * @var string
  301. */
  302. public $property2;
  303. /**
  304. * Test property time for verifying wake is run at each get() call.
  305. * @var float
  306. */
  307. public $propertytime;
  308. /**
  309. * Constructor
  310. * @param string $property1
  311. * @param string $property2
  312. */
  313. public function __construct($property1, $property2, $propertytime = null) {
  314. $this->property1 = $property1;
  315. $this->property2 = $property2;
  316. $this->propertytime = $propertytime === null ? microtime(true) : $propertytime;
  317. }
  318. /**
  319. * Prepares this object for caching
  320. * @return array
  321. */
  322. public function prepare_to_cache() {
  323. return array($this->property1.'_ptc', $this->property2.'_ptc', $this->propertytime);
  324. }
  325. /**
  326. * Returns this object from the cache
  327. * @param array $data
  328. * @return cache_phpunit_dummy_object
  329. */
  330. public static function wake_from_cache($data) {
  331. $time = null;
  332. if (!is_null($data[2])) {
  333. // Windows 32bit microtime() resolution is 15ms, we ensure the time has moved forward.
  334. do {
  335. $time = microtime(true);
  336. } while ($time == $data[2]);
  337. }
  338. return new cache_phpunit_dummy_object(array_shift($data).'_wfc', array_shift($data).'_wfc', $time);
  339. }
  340. }
  341. /**
  342. * Dummy data source object for testing data source interface and implementation
  343. *
  344. * @copyright 2012 Sam Hemelryk
  345. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  346. */
  347. class cache_phpunit_dummy_datasource implements cache_data_source {
  348. /**
  349. * Returns an instance of this object for use with the cache.
  350. *
  351. * @param cache_definition $definition
  352. * @return cache_phpunit_dummy_datasource
  353. */
  354. public static function get_instance_for_cache(cache_definition $definition) {
  355. return new cache_phpunit_dummy_datasource();
  356. }
  357. /**
  358. * Loads a key for the cache.
  359. *
  360. * @param string $key
  361. * @return string
  362. */
  363. public function load_for_cache($key) {
  364. return $key.' has no value really.';
  365. }
  366. /**
  367. * Loads many keys for the cache
  368. *
  369. * @param array $keys
  370. * @return array
  371. */
  372. public function load_many_for_cache(array $keys) {
  373. $return = array();
  374. foreach ($keys as $key) {
  375. $return[$key] = $key.' has no value really.';
  376. }
  377. return $return;
  378. }
  379. }
  380. /**
  381. * PHPUnit application cache loader.
  382. *
  383. * Used to expose things we could not otherwise see within an application cache.
  384. *
  385. * @copyright 2012 Sam Hemelryk
  386. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  387. */
  388. class cache_phpunit_application extends cache_application {
  389. /**
  390. * Returns the class of the store immediately associated with this cache.
  391. * @return string
  392. */
  393. public function phpunit_get_store_class() {
  394. return get_class($this->get_store());
  395. }
  396. /**
  397. * Returns all the interfaces the cache store implements.
  398. * @return array
  399. */
  400. public function phpunit_get_store_implements() {
  401. return class_implements($this->get_store());
  402. }
  403. /**
  404. * Returns the given key directly from the static acceleration array.
  405. *
  406. * @param string $key
  407. * @return false|mixed
  408. */
  409. public function phpunit_static_acceleration_get($key) {
  410. return $this->static_acceleration_get($key);
  411. }
  412. /**
  413. * Purges only the static acceleration while leaving the rest of the store in tack.
  414. *
  415. * Used for behaving like you have loaded 2 pages, and reset static while the backing store
  416. * still contains all the same data.
  417. *
  418. */
  419. public function phpunit_static_acceleration_purge() {
  420. $this->static_acceleration_purge();
  421. }
  422. }
  423. /**
  424. * PHPUnit session cache loader.
  425. *
  426. * Used to expose things we could not otherwise see within an session cache.
  427. *
  428. * @copyright 2012 Sam Hemelryk
  429. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  430. */
  431. class cache_phpunit_session extends cache_session {
  432. /** @var Static member used for emulating the behaviour of session_id() during the tests. */
  433. protected static $sessionidmockup = 'phpunitmockupsessionid';
  434. /**
  435. * Returns the class of the store immediately associated with this cache.
  436. * @return string
  437. */
  438. public function phpunit_get_store_class() {
  439. return get_class($this->get_store());
  440. }
  441. /**
  442. * Returns all the interfaces the cache store implements.
  443. * @return array
  444. */
  445. public function phpunit_get_store_implements() {
  446. return class_implements($this->get_store());
  447. }
  448. /**
  449. * Provide access to the {@link cache_session::get_key_prefix()} method.
  450. *
  451. * @return string
  452. */
  453. public function phpunit_get_key_prefix() {
  454. return $this->get_key_prefix();
  455. }
  456. /**
  457. * Allows to inject the session identifier.
  458. *
  459. * @param string $sessionid
  460. */
  461. public static function phpunit_mockup_session_id($sessionid) {
  462. static::$sessionidmockup = $sessionid;
  463. }
  464. /**
  465. * Override the parent behaviour so that it does not need the actual session_id() call.
  466. */
  467. protected function set_session_id() {
  468. $this->sessionid = static::$sessionidmockup;
  469. }
  470. }
  471. /**
  472. * PHPUnit request cache loader.
  473. *
  474. * Used to expose things we could not otherwise see within an request cache.
  475. *
  476. * @copyright 2012 Sam Hemelryk
  477. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  478. */
  479. class cache_phpunit_request extends cache_request {
  480. /**
  481. * Returns the class of the store immediately associated with this cache.
  482. * @return string
  483. */
  484. public function phpunit_get_store_class() {
  485. return get_class($this->get_store());
  486. }
  487. /**
  488. * Returns all the interfaces the cache store implements.
  489. * @return array
  490. */
  491. public function phpunit_get_store_implements() {
  492. return class_implements($this->get_store());
  493. }
  494. }
  495. /**
  496. * Dummy overridden cache loader class that we can use to test overriding loader functionality.
  497. *
  498. * @copyright 2012 Sam Hemelryk
  499. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  500. */
  501. class cache_phpunit_dummy_overrideclass extends cache_application {
  502. // Satisfying the code pre-checker is just part of my day job.
  503. }
  504. /**
  505. * Cache PHPUnit specific factory.
  506. *
  507. * @copyright 2012 Sam Hemelryk
  508. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  509. */
  510. class cache_phpunit_factory extends cache_factory {
  511. /**
  512. * Exposes the cache_factory's disable method.
  513. *
  514. * Perhaps one day that method will be made public, for the time being it is protected.
  515. */
  516. public static function phpunit_disable() {
  517. parent::disable();
  518. }
  519. }
  520. /**
  521. * Cache PHPUnit specific Cache helper.
  522. *
  523. * @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
  524. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  525. */
  526. class cache_phpunit_cache extends cache {
  527. /**
  528. * Make the changes which simulate a new request within the cache.
  529. * This essentially resets currently held static values in the class, and increments the current timestamp.
  530. */
  531. public static function simulate_new_request() {
  532. self::$now += 0.1;
  533. self::$purgetoken = null;
  534. }
  535. }