first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
+271
View File
@@ -0,0 +1,271 @@
<?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/>.
namespace core_cache;
use cache_config_testing;
use cache_config_writer;
use cache_factory;
use cache_helper;
use cache_store;
defined('MOODLE_INTERNAL') || die();
// Include the necessary evils.
global $CFG;
require_once($CFG->dirroot.'/cache/locallib.php');
require_once($CFG->dirroot.'/cache/tests/fixtures/lib.php');
/**
* PHPunit tests for the cache API and in particular the core_cache\administration_helper
*
* @package core_cache
* @category test
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class administration_helper_test extends \advanced_testcase {
/**
* Set things back to the default before each test.
*/
public function setUp(): void {
parent::setUp();
cache_factory::reset();
cache_config_testing::create_default_configuration();
}
/**
* Final task is to reset the cache system
*/
public static function tearDownAfterClass(): void {
parent::tearDownAfterClass();
cache_factory::reset();
}
/**
* Test the numerous summaries the helper can produce.
*/
public function test_get_summaries(): void {
// First the preparation.
$config = cache_config_writer::instance();
$this->assertTrue($config->add_store_instance('summariesstore', 'file'));
$config->set_definition_mappings('core/eventinvalidation', array('summariesstore'));
$this->assertTrue($config->set_mode_mappings(array(
cache_store::MODE_APPLICATION => array('summariesstore'),
cache_store::MODE_SESSION => array('default_session'),
cache_store::MODE_REQUEST => array('default_request'),
)));
$storesummaries = administration_helper::get_store_instance_summaries();
$this->assertIsArray($storesummaries);
$this->assertArrayHasKey('summariesstore', $storesummaries);
$summary = $storesummaries['summariesstore'];
// Check the keys
$this->assertArrayHasKey('name', $summary);
$this->assertArrayHasKey('plugin', $summary);
$this->assertArrayHasKey('default', $summary);
$this->assertArrayHasKey('isready', $summary);
$this->assertArrayHasKey('requirementsmet', $summary);
$this->assertArrayHasKey('mappings', $summary);
$this->assertArrayHasKey('modes', $summary);
$this->assertArrayHasKey('supports', $summary);
// Check the important/known values
$this->assertEquals('summariesstore', $summary['name']);
$this->assertEquals('file', $summary['plugin']);
$this->assertEquals(0, $summary['default']);
$this->assertEquals(1, $summary['isready']);
$this->assertEquals(1, $summary['requirementsmet']);
// Find the number of mappings to sessionstore.
$mappingcount = count(array_filter($config->get_definitions(), function($element) {
return $element['mode'] === cache_store::MODE_APPLICATION;
}));
$this->assertEquals($mappingcount, $summary['mappings']);
$definitionsummaries = administration_helper::get_definition_summaries();
$this->assertIsArray($definitionsummaries);
$this->assertArrayHasKey('core/eventinvalidation', $definitionsummaries);
$summary = $definitionsummaries['core/eventinvalidation'];
// Check the keys
$this->assertArrayHasKey('id', $summary);
$this->assertArrayHasKey('name', $summary);
$this->assertArrayHasKey('mode', $summary);
$this->assertArrayHasKey('component', $summary);
$this->assertArrayHasKey('area', $summary);
$this->assertArrayHasKey('mappings', $summary);
// Check the important/known values
$this->assertEquals('core/eventinvalidation', $summary['id']);
$this->assertInstanceOf('lang_string', $summary['name']);
$this->assertEquals(cache_store::MODE_APPLICATION, $summary['mode']);
$this->assertEquals('core', $summary['component']);
$this->assertEquals('eventinvalidation', $summary['area']);
$this->assertIsArray($summary['mappings']);
$this->assertContains('summariesstore', $summary['mappings']);
$pluginsummaries = administration_helper::get_store_plugin_summaries();
$this->assertIsArray($pluginsummaries);
$this->assertArrayHasKey('file', $pluginsummaries);
$summary = $pluginsummaries['file'];
// Check the keys
$this->assertArrayHasKey('name', $summary);
$this->assertArrayHasKey('requirementsmet', $summary);
$this->assertArrayHasKey('instances', $summary);
$this->assertArrayHasKey('modes', $summary);
$this->assertArrayHasKey('supports', $summary);
$this->assertArrayHasKey('canaddinstance', $summary);
$locksummaries = administration_helper::get_lock_summaries();
$this->assertIsArray($locksummaries);
$this->assertTrue(count($locksummaries) > 0);
$mappings = administration_helper::get_default_mode_stores();
$this->assertIsArray($mappings);
$this->assertCount(3, $mappings);
$this->assertArrayHasKey(cache_store::MODE_APPLICATION, $mappings);
$this->assertIsArray($mappings[cache_store::MODE_APPLICATION]);
$this->assertContains('summariesstore', $mappings[cache_store::MODE_APPLICATION]);
$potentials = administration_helper::get_definition_store_options('core', 'eventinvalidation');
$this->assertIsArray($potentials); // Currently used, suitable, default
$this->assertCount(3, $potentials);
$this->assertArrayHasKey('summariesstore', $potentials[0]);
$this->assertArrayHasKey('summariesstore', $potentials[1]);
$this->assertArrayHasKey('default_application', $potentials[1]);
}
/**
* Test instantiating an add store form.
*/
public function test_get_add_store_form(): void {
$form = cache_factory::get_administration_display_helper()->get_add_store_form('file');
$this->assertInstanceOf('moodleform', $form);
try {
$form = cache_factory::get_administration_display_helper()->get_add_store_form('somethingstupid');
$this->fail('You should not be able to create an add form for a store plugin that does not exist.');
} catch (\moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e, 'Needs to be: ' .get_class($e)." ::: ".$e->getMessage());
}
}
/**
* Test instantiating a form to edit a store instance.
*/
public function test_get_edit_store_form(): void {
// Always instantiate a new core display helper here.
$administrationhelper = new local\administration_display_helper;
$config = cache_config_writer::instance();
$this->assertTrue($config->add_store_instance('test_get_edit_store_form', 'file'));
$form = $administrationhelper->get_edit_store_form('file', 'test_get_edit_store_form');
$this->assertInstanceOf('moodleform', $form);
try {
$form = $administrationhelper->get_edit_store_form('somethingstupid', 'moron');
$this->fail('You should not be able to create an edit form for a store plugin that does not exist.');
} catch (\moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$form = $administrationhelper->get_edit_store_form('file', 'blisters');
$this->fail('You should not be able to create an edit form for a store plugin that does not exist.');
} catch (\moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
}
/**
* Test the hash_key functionality.
*/
public function test_hash_key(): void {
$this->resetAfterTest();
set_debugging(DEBUG_ALL);
// First with simplekeys
$instance = cache_config_testing::instance(true);
$instance->phpunit_add_definition('phpunit/hashtest', array(
'mode' => cache_store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'hashtest',
'simplekeys' => true
));
$factory = cache_factory::instance();
$definition = $factory->create_definition('phpunit', 'hashtest');
$result = cache_helper::hash_key('test', $definition);
$this->assertEquals('test-'.$definition->generate_single_key_prefix(), $result);
try {
cache_helper::hash_key('test/test', $definition);
$this->fail('Invalid key was allowed, you should see this.');
} catch (\coding_exception $e) {
$this->assertEquals('test/test', $e->debuginfo);
}
// Second without simple keys
$instance->phpunit_add_definition('phpunit/hashtest2', array(
'mode' => cache_store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'hashtest2',
'simplekeys' => false
));
$definition = $factory->create_definition('phpunit', 'hashtest2');
$result = cache_helper::hash_key('test', $definition);
$this->assertEquals(sha1($definition->generate_single_key_prefix().'-test'), $result);
$result = cache_helper::hash_key('test/test', $definition);
$this->assertEquals(sha1($definition->generate_single_key_prefix().'-test/test'), $result);
}
/**
* Tests the get_usage function.
*/
public function test_get_usage(): void {
// Create a test cache definition and put items in it.
$instance = cache_config_testing::instance(true);
$instance->phpunit_add_definition('phpunit/test', [
'mode' => cache_store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'test',
'simplekeys' => true
]);
$cache = \cache::make('phpunit', 'test');
for ($i = 0; $i < 100; $i++) {
$cache->set('key' . $i, str_repeat('x', $i));
}
$factory = cache_factory::instance();
$adminhelper = $factory->get_administration_display_helper();
$usage = $adminhelper->get_usage(10)['phpunit/test'];
$this->assertEquals('phpunit/test', $usage->cacheid);
$this->assertCount(1, $usage->stores);
$store = $usage->stores[0];
$this->assertEquals('default_application', $store->name);
$this->assertEquals('cachestore_file', $store->class);
$this->assertEquals(true, $store->supported);
$this->assertEquals(100, $store->items);
// As file store checks all items, the values should be exact.
$this->assertEqualsWithDelta(57.4, $store->mean, 0.1);
$this->assertEqualsWithDelta(29.0, $store->sd, 0.1);
$this->assertEquals(0, $store->margin);
}
}
+99
View File
@@ -0,0 +1,99 @@
<?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/>.
namespace core_cache;
/**
* Unit tests for {@see allow_temporary_caches}.
*
* @package core_cache
* @category test
* @copyright 2022 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @covers \core_cache\allow_temporary_caches
*/
class allow_temporary_caches_test extends \advanced_testcase {
/**
* Tests whether temporary caches are allowed.
*/
public function test_is_allowed(): void {
// Not allowed by default.
$this->assertFalse(allow_temporary_caches::is_allowed());
// Allowed if we have an instance.
$frog = new allow_temporary_caches();
$this->assertTrue(allow_temporary_caches::is_allowed());
// Or two instances.
$toad = new allow_temporary_caches();
$this->assertTrue(allow_temporary_caches::is_allowed());
// Get rid of the instances.
unset($frog);
$this->assertTrue(allow_temporary_caches::is_allowed());
// Not allowed when we get back to no instances.
unset($toad);
$this->assertFalse(allow_temporary_caches::is_allowed());
// Check it works to automatically free up the instance when variable goes out of scope.
$this->inner_is_allowed();
$this->assertFalse(allow_temporary_caches::is_allowed());
}
/**
* Function call to demonstrate that you don't need to manually unset the variable.
*/
protected function inner_is_allowed(): void {
$gecko = new allow_temporary_caches();
$this->assertTrue(allow_temporary_caches::is_allowed());
}
/**
* Tests that the temporary caches actually work, including normal and versioned get and set.
*/
public function test_temporary_cache(): void {
$this->resetAfterTest();
// Disable the cache.
\cache_phpunit_factory::phpunit_disable();
try {
// Try using the cache now - it returns false/null for everything.
$cache = \cache::make('core', 'coursemodinfo');
$cache->set('frog', 'ribbit');
$this->assertFalse($cache->get('frog'));
$cache->set_versioned('toad', 2, 'croak');
$this->assertFalse($cache->get_versioned('toad', 2));
// But when we allow temporary caches, it should work as normal.
$allow = new allow_temporary_caches();
$cache = \cache::make('core', 'coursemodinfo');
$cache->set('frog', 'ribbit');
$this->assertEquals('ribbit', $cache->get('frog'));
$cache->set_versioned('toad', 2, 'croak');
$this->assertEquals('croak', $cache->get_versioned('toad', 2));
// Let's actually use modinfo, to check it works with locking too.
$course = $this->getDataGenerator()->create_course();
get_fast_modinfo($course);
} finally {
// You have to do this after phpunit_disable or it breaks later tests.
\cache_factory::reset();
\cache_factory::instance(true);
}
}
}
+21
View File
@@ -0,0 +1,21 @@
@core @core_cache
Feature: Display cache information in performance info
In order to investigate performance problems with caching
As an administrator
I need to be able to see cache information in perfinfo
Background:
Given the following config values are set as admin:
| perfdebug | 15 |
And the following "courses" exist:
| fullname | shortname |
| Course 1 | C1 |
Scenario: Cache performance info displays
When I am on the "C1" "Course" page logged in as "admin"
# Confirm that the first cache info table is visible by checking an arbitrary row.
Then I should see "default_application" in the "core/databasemeta" "table_row"
# Don't specify the exact size as it may vary.
And I should see "KB" in the "core/databasemeta" "table_row"
# Confirm that the second cache info table is visible.
And I should see "default_application" in the "cachestore_file" "table_row"
+27
View File
@@ -0,0 +1,27 @@
@core @core_cache @javascript
Feature: Verify the breadcrumbs in different cache site administration pages
Whenever I navigate to caching configuration page in site administration
As an admin
The breadcrumbs should be visible
Background:
Given I log in as "admin"
Scenario: Verify the breadcrumbs in caching configuration, add assistance, edit mappings and edit sharings page as an admin
Given I navigate to "Plugins > Caching > Configuration" in site administration
And "Configuration" "text" should exist in the ".breadcrumb" "css_element"
And "Caching" "link" should exist in the ".breadcrumb" "css_element"
When I click on "Add instance" "link"
Then "Add cache store" "text" should exist in the ".breadcrumb" "css_element"
And "Configuration" "link" should exist in the ".breadcrumb" "css_element"
And "Caching" "link" should exist in the ".breadcrumb" "css_element"
And I press "Cancel"
And I click on "Edit mappings" "link"
And "Edit definition mapping" "text" should exist in the ".breadcrumb" "css_element"
And "Configuration" "link" should exist in the ".breadcrumb" "css_element"
And "Caching" "link" should exist in the ".breadcrumb" "css_element"
And I press "Cancel"
And I click on "Edit sharing" "link"
And "Edit definition sharing" "text" should exist in the ".breadcrumb" "css_element"
And "Configuration" "link" should exist in the ".breadcrumb" "css_element"
And "Caching" "link" should exist in the ".breadcrumb" "css_element"
+35
View File
@@ -0,0 +1,35 @@
@core @core_cache
Feature: Display usage information for cache
In order to investigate performance problems with caching
As an administrator
I need to be able to monitor the size of items in the cache
Background:
Given the following "courses" exist:
| fullname | shortname |
| Course 1 | C1 |
Scenario: Cache performance info displays
When I am on the "C1" "Course" page logged in as "admin"
And I navigate to "Plugins > Caching > Cache usage" in site administration
# Check one row of the summary table. The actual total is currently 3.6MB so it's likely to
# continue to be in the MB range.
Then "default_application" row "Plugin" column of "usage_summary" table should contain "cachestore_file"
And "default_application" row "Estimated total" column of "usage_summary" table should contain "MB"
And "default_application" row "Actual usage (if known)" column of "usage_summary" table should contain "MB"
# And one row of the main table. The totals are fixed to use the MB unit.
And "core/config" row "Store name" column of "usage_main" table should contain "default_application"
And "core/config" row "Plugin" column of "usage_main" table should contain "cachestore_file"
And "core/config" row "Estimated total" column of "usage_main" table should contain "MB"
Scenario: Sample option works
When I am on the "C1" "Course" page logged in as "admin"
And I navigate to "Plugins > Caching > Cache usage" in site administration
And I set the field "samples" to "1000"
And I press "Update"
Then the field "samples" matches value "1000"
And "usage_summary" "table" should exist
And "usage_main" "table" should exist
+64
View File
@@ -0,0 +1,64 @@
<?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/>.
namespace core_cache;
/**
* PHPunit tests for the cache_helper class.
*
* @package core
* @category cache
* @copyright 2023 Andrew Lyons <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \cache_helper
*/
class cache_helper_test extends \advanced_testcase {
/**
* Test the result_found method.
*
* @param mixed $value
* @param bool $expected
* @dataProvider result_found_provider
* @covers ::result_found
*/
public function test_result_found($value, bool $expected): void {
$this->assertEquals($expected, \cache_helper::result_found($value));
}
/**
* Data provider for result_found tests.
*
* @return array
*/
public function result_found_provider(): array {
return [
// Only false values are considered as not found.
[false, false],
// The rest are considered valid values.
[null, true],
[0, true],
['', true],
[[], true],
[new \stdClass(), true],
[true, true],
[1, true],
['a', true],
[[1], true],
[new \stdClass(), true],
];
}
}
+3288
View File
File diff suppressed because it is too large Load Diff
+287
View File
@@ -0,0 +1,287 @@
<?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/>.
namespace core_cache;
use cache_config_testing;
use cache_config_writer;
use cache_factory;
use cache_store;
defined('MOODLE_INTERNAL') || die();
// Include the necessary evils.
global $CFG;
require_once($CFG->dirroot.'/cache/locallib.php');
require_once($CFG->dirroot.'/cache/tests/fixtures/lib.php');
/**
* PHPunit tests for the cache API and in particular the cache config writer.
*
* @package core_cache
* @category test
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class config_writer_test extends \advanced_testcase {
/**
* Set things back to the default before each test.
*/
public function setUp(): void {
parent::setUp();
cache_factory::reset();
cache_config_testing::create_default_configuration();
}
/**
* Final task is to reset the cache system
*/
public static function tearDownAfterClass(): void {
parent::tearDownAfterClass();
cache_factory::reset();
}
/**
* Test getting an instance. Pretty basic.
*/
public function test_instance(): void {
$config = cache_config_writer::instance();
$this->assertInstanceOf('cache_config_writer', $config);
}
/**
* Test the default configuration.
*/
public function test_default_configuration(): void {
$config = cache_config_writer::instance();
// First check stores.
$stores = $config->get_all_stores();
$hasapplication = false;
$hassession = false;
$hasrequest = false;
foreach ($stores as $store) {
// Check the required keys.
$this->assertArrayHasKey('name', $store);
$this->assertArrayHasKey('plugin', $store);
$this->assertArrayHasKey('modes', $store);
$this->assertArrayHasKey('default', $store);
// Check the mode, we need at least one default store of each mode.
if (!empty($store['default'])) {
if ($store['modes'] & cache_store::MODE_APPLICATION) {
$hasapplication = true;
}
if ($store['modes'] & cache_store::MODE_SESSION) {
$hassession = true;
}
if ($store['modes'] & cache_store::MODE_REQUEST) {
$hasrequest = true;
}
}
}
$this->assertTrue($hasapplication, 'There is no default application cache store.');
$this->assertTrue($hassession, 'There is no default session cache store.');
$this->assertTrue($hasrequest, 'There is no default request cache store.');
// Next check the definitions.
$definitions = $config->get_definitions();
$eventinvalidation = false;
foreach ($definitions as $definition) {
// Check the required keys.
$this->assertArrayHasKey('mode', $definition);
$this->assertArrayHasKey('component', $definition);
$this->assertArrayHasKey('area', $definition);
if ($definition['component'] === 'core' && $definition['area'] === 'eventinvalidation') {
$eventinvalidation = true;
}
}
$this->assertTrue($eventinvalidation, 'Missing the event invalidation definition.');
// Next mode mappings
$mappings = $config->get_mode_mappings();
$hasapplication = false;
$hassession = false;
$hasrequest = false;
foreach ($mappings as $mode) {
// Check the required keys.
$this->assertArrayHasKey('mode', $mode);
$this->assertArrayHasKey('store', $mode);
if ($mode['mode'] === cache_store::MODE_APPLICATION) {
$hasapplication = true;
}
if ($mode['mode'] === cache_store::MODE_SESSION) {
$hassession = true;
}
if ($mode['mode'] === cache_store::MODE_REQUEST) {
$hasrequest = true;
}
}
$this->assertTrue($hasapplication, 'There is no mapping for the application mode.');
$this->assertTrue($hassession, 'There is no mapping for the session mode.');
$this->assertTrue($hasrequest, 'There is no mapping for the request mode.');
// Finally check config locks
$locks = $config->get_locks();
foreach ($locks as $lock) {
$this->assertArrayHasKey('name', $lock);
$this->assertArrayHasKey('type', $lock);
$this->assertArrayHasKey('default', $lock);
}
// There has to be at least the default lock.
$this->assertTrue(count($locks) > 0);
}
/**
* Test updating the definitions.
*/
public function test_update_definitions(): void {
$config = cache_config_writer::instance();
// Remove the definition.
$config->phpunit_remove_definition('core/string');
$definitions = $config->get_definitions();
// Check it is gone.
$this->assertFalse(array_key_exists('core/string', $definitions));
// Update definitions. This should re-add it.
cache_config_writer::update_definitions();
$definitions = $config->get_definitions();
// Check it is back again.
$this->assertTrue(array_key_exists('core/string', $definitions));
}
/**
* Test adding/editing/deleting store instances.
*/
public function test_add_edit_delete_plugin_instance(): void {
$config = cache_config_writer::instance();
$this->assertArrayNotHasKey('addplugintest', $config->get_all_stores());
$this->assertArrayNotHasKey('addplugintestwlock', $config->get_all_stores());
// Add a default file instance.
$config->add_store_instance('addplugintest', 'file');
cache_factory::reset();
$config = cache_config_writer::instance();
$this->assertArrayHasKey('addplugintest', $config->get_all_stores());
// Add a store with a lock described.
$config->add_store_instance('addplugintestwlock', 'file', array('lock' => 'default_file_lock'));
$this->assertArrayHasKey('addplugintestwlock', $config->get_all_stores());
$config->delete_store_instance('addplugintest');
$this->assertArrayNotHasKey('addplugintest', $config->get_all_stores());
$this->assertArrayHasKey('addplugintestwlock', $config->get_all_stores());
$config->delete_store_instance('addplugintestwlock');
$this->assertArrayNotHasKey('addplugintest', $config->get_all_stores());
$this->assertArrayNotHasKey('addplugintestwlock', $config->get_all_stores());
// Add a default file instance.
$config->add_store_instance('storeconfigtest', 'file', array('test' => 'a', 'one' => 'two'));
$stores = $config->get_all_stores();
$this->assertArrayHasKey('storeconfigtest', $stores);
$this->assertArrayHasKey('configuration', $stores['storeconfigtest']);
$this->assertArrayHasKey('test', $stores['storeconfigtest']['configuration']);
$this->assertArrayHasKey('one', $stores['storeconfigtest']['configuration']);
$this->assertEquals('a', $stores['storeconfigtest']['configuration']['test']);
$this->assertEquals('two', $stores['storeconfigtest']['configuration']['one']);
$config->edit_store_instance('storeconfigtest', 'file', array('test' => 'b', 'one' => 'three'));
$stores = $config->get_all_stores();
$this->assertArrayHasKey('storeconfigtest', $stores);
$this->assertArrayHasKey('configuration', $stores['storeconfigtest']);
$this->assertArrayHasKey('test', $stores['storeconfigtest']['configuration']);
$this->assertArrayHasKey('one', $stores['storeconfigtest']['configuration']);
$this->assertEquals('b', $stores['storeconfigtest']['configuration']['test']);
$this->assertEquals('three', $stores['storeconfigtest']['configuration']['one']);
$config->delete_store_instance('storeconfigtest');
try {
$config->delete_store_instance('default_application');
$this->fail('Default store deleted. This should not be possible!');
} catch (\Exception $e) {
$this->assertInstanceOf('cache_exception', $e);
}
try {
$config->delete_store_instance('some_crazy_store');
$this->fail('You should not be able to delete a store that does not exist.');
} catch (\Exception $e) {
$this->assertInstanceOf('cache_exception', $e);
}
try {
// Try with a plugin that does not exist.
$config->add_store_instance('storeconfigtest', 'shallowfail', array('test' => 'a', 'one' => 'two'));
$this->fail('You should not be able to add an instance of a store that does not exist.');
} catch (\Exception $e) {
$this->assertInstanceOf('cache_exception', $e);
}
}
/**
* Test setting some mode mappings.
*/
public function test_set_mode_mappings(): void {
$config = cache_config_writer::instance();
$this->assertTrue($config->add_store_instance('setmodetest', 'file'));
$this->assertTrue($config->set_mode_mappings(array(
cache_store::MODE_APPLICATION => array('setmodetest', 'default_application'),
cache_store::MODE_SESSION => array('default_session'),
cache_store::MODE_REQUEST => array('default_request'),
)));
$mappings = $config->get_mode_mappings();
$setmodetestfound = false;
foreach ($mappings as $mapping) {
if ($mapping['store'] == 'setmodetest' && $mapping['mode'] == cache_store::MODE_APPLICATION) {
$setmodetestfound = true;
}
}
$this->assertTrue($setmodetestfound, 'Set mapping did not work as expected.');
}
/**
* Test setting some definition mappings.
*/
public function test_set_definition_mappings(): void {
$config = cache_config_testing::instance(true);
$config->phpunit_add_definition('phpunit/testdefinition', array(
'mode' => cache_store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'testdefinition'
));
$config = cache_config_writer::instance();
$this->assertTrue($config->add_store_instance('setdefinitiontest', 'file'));
$this->assertIsArray($config->get_definition_by_id('phpunit/testdefinition'));
$config->set_definition_mappings('phpunit/testdefinition', array('setdefinitiontest', 'default_application'));
try {
$config->set_definition_mappings('phpunit/testdefinition', array('something that does not exist'));
$this->fail('You should not be able to set a mapping for a store that does not exist.');
} catch (\Exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$config->set_definition_mappings('something/crazy', array('setdefinitiontest'));
$this->fail('You should not be able to set a mapping for a definition that does not exist.');
} catch (\Exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
}
}
@@ -0,0 +1,84 @@
<?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/>.
/**
* A dummy datasource which supports versioning.
*
* @package core_cache
* @copyright 2021 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_phpunit_dummy_datasource_versionable extends cache_phpunit_dummy_datasource
implements cache_data_source_versionable {
/** @var array Data in cache */
protected $data = [];
/** @var cache_phpunit_dummy_datasource_versionable Last created instance */
protected static $lastinstance;
/**
* Returns an instance of this object for use with the cache.
*
* @param cache_definition $definition
* @return cache_phpunit_dummy_datasource New object
*/
public static function get_instance_for_cache(cache_definition $definition):
cache_phpunit_dummy_datasource_versionable {
self::$lastinstance = new cache_phpunit_dummy_datasource_versionable();
return self::$lastinstance;
}
/**
* Gets the last instance that was created.
*
* @return cache_phpunit_dummy_datasource_versionable
*/
public static function get_last_instance(): cache_phpunit_dummy_datasource_versionable {
return self::$lastinstance;
}
/**
* Sets up the datasource so that it has a value for a particular key.
*
* @param string $key Key
* @param int $version Version for key
* @param mixed $data
*/
public function has_value(string $key, int $version, $data): void {
$this->data[$key] = new \core_cache\version_wrapper($data, $version);
}
/**
* Loads versioned data.
*
* @param int|string $key Key
* @param int $requiredversion Minimum version number
* @param mixed $actualversion Should be set to the actual version number retrieved
* @return mixed Data retrieved from cache or false if none
*/
public function load_for_cache_versioned($key, int $requiredversion, &$actualversion) {
if (!array_key_exists($key, $this->data)) {
return false;
}
$value = $this->data[$key];
if ($value->version < $requiredversion) {
return false;
}
$actualversion = $value->version;
return $value->data;
}
}
@@ -0,0 +1,37 @@
<?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/>.
/**
* A subclass of cachestore_file but which doesn't report that it has TTL support.
*
* This is so we can easily test behaviour involving the TTL wrapper objects.
*
* @package core_cache
* @copyright 2021 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cachestore_file_with_ttl_wrappers extends cachestore_file {
/**
* Reports the same supported features as the parent, but without SUPPORTS_NATIVE_TTL.
*
* @param array $configuration Configuration
* @return int Supported features
*/
public static function get_supported_features(array $configuration = array()) {
return parent::get_supported_features($configuration) - self::SUPPORTS_NATIVE_TTL;
}
}
+600
View File
@@ -0,0 +1,600 @@
<?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/>.
/**
* Support library for the cache PHPUnit tests.
*
* This file is part of Moodle's cache API, affectionately called MUC.
* It contains the components that are requried in order to use caching.
*
* @package core
* @category cache
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot.'/cache/locallib.php');
/**
* Override the default cache configuration for our own maniacal purposes.
*
* This class was originally named cache_config_phpunittest but was renamed in 2.9
* because it is used for both unit tests and acceptance tests.
*
* @since 2.9
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_config_testing extends cache_config_writer {
/**
* Creates the default configuration and saves it.
*
* This function calls config_save, however it is safe to continue using it afterwards as this function should only ever
* be called when there is no configuration file already.
*
* @param bool $forcesave If set to true then we will forcefully save the default configuration file.
* @return true|array Returns true if the default configuration was successfully created.
* Returns a configuration array if it could not be saved. This is a bad situation. Check your error logs.
*/
public static function create_default_configuration($forcesave = false) {
global $CFG;
// HACK ALERT.
// We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
// default store plugins are protected from deletion.
$writer = new self;
$writer->configstores = self::get_default_stores();
$writer->configdefinitions = self::locate_definitions();
$defaultapplication = 'default_application';
$appdefine = defined('TEST_CACHE_USING_APPLICATION_STORE') ? TEST_CACHE_USING_APPLICATION_STORE : false;
if ($appdefine !== false && preg_match('/^[a-zA-Z][a-zA-Z0-9_]+$/', $appdefine)) {
$expectedstore = $appdefine;
$file = $CFG->dirroot.'/cache/stores/'.$appdefine.'/lib.php';
$class = 'cachestore_'.$appdefine;
if (file_exists($file)) {
require_once($file);
}
if (class_exists($class) && $class::ready_to_be_used_for_testing()) {
/* @var cache_store $class */
$writer->configstores['test_application'] = array(
'name' => 'test_application',
'plugin' => $expectedstore,
'modes' => $class::get_supported_modes(),
'features' => $class::get_supported_features(),
'configuration' => $class::unit_test_configuration()
);
$defaultapplication = 'test_application';
}
}
$writer->configmodemappings = array(
array(
'mode' => cache_store::MODE_APPLICATION,
'store' => $defaultapplication,
'sort' => -1
),
array(
'mode' => cache_store::MODE_SESSION,
'store' => 'default_session',
'sort' => -1
),
array(
'mode' => cache_store::MODE_REQUEST,
'store' => 'default_request',
'sort' => -1
)
);
$writer->configlocks = array(
'default_file_lock' => array(
'name' => 'cachelock_file_default',
'type' => 'cachelock_file',
'dir' => 'filelocks',
'default' => true
)
);
$factory = cache_factory::instance();
// We expect the cache to be initialising presently. If its not then something has gone wrong and likely
// we are now in a loop.
if (!$forcesave && $factory->get_state() !== cache_factory::STATE_INITIALISING) {
return $writer->generate_configuration_array();
}
$factory->set_state(cache_factory::STATE_SAVING);
$writer->config_save();
return true;
}
/**
* Returns the expected path to the configuration file.
*
* We override this function to add handling for $CFG->altcacheconfigpath.
* We want to support it so that people can run unit tests against alternative cache setups.
* However we don't want to ever make changes to the file at $CFG->altcacheconfigpath so we
* always use dataroot and copy the alt file there as required.
*
* @throws cache_exception
* @return string The absolute path
*/
protected static function get_config_file_path() {
global $CFG;
// We always use this path.
$configpath = $CFG->dataroot.'/muc/config.php';
if (!empty($CFG->altcacheconfigpath)) {
// No need to check we are within a test here, this is the cache config class that gets used
// only when one of those is true.
if (!defined('TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH') || !TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH) {
// TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH has not being defined or is false, we want to use the default.
return $configpath;
}
$path = $CFG->altcacheconfigpath;
if (is_dir($path) && is_writable($path)) {
// Its a writable directory, thats fine. Convert it to a file.
$path = $CFG->altcacheconfigpath.'/cacheconfig.php';
}
if (is_readable($path)) {
$directory = dirname($configpath);
if ($directory !== $CFG->dataroot && !file_exists($directory)) {
$result = make_writable_directory($directory, false);
if (!$result) {
throw new cache_exception('ex_configcannotsave', 'cache', '', null, 'Cannot create config directory. Check the permissions on your moodledata directory.');
}
}
// We don't care that this fails but we should let the developer know.
if (!is_readable($configpath) && !@copy($path, $configpath)) {
debugging('Failed to copy alt cache config file to required location');
}
}
}
// We always use the dataroot location.
return $configpath;
}
/**
* Adds a definition to the stack
* @param string $area
* @param array $properties
* @param bool $addmapping By default this method adds a definition and a mapping for that definition. You can
* however set this to false if you only want it to add the definition and not the mapping.
*/
public function phpunit_add_definition($area, array $properties, $addmapping = true) {
if (!array_key_exists('overrideclass', $properties)) {
switch ($properties['mode']) {
case cache_store::MODE_APPLICATION:
$properties['overrideclass'] = 'cache_phpunit_application';
break;
case cache_store::MODE_SESSION:
$properties['overrideclass'] = 'cache_phpunit_session';
break;
case cache_store::MODE_REQUEST:
$properties['overrideclass'] = 'cache_phpunit_request';
break;
}
}
$this->configdefinitions[$area] = $properties;
if ($addmapping) {
switch ($properties['mode']) {
case cache_store::MODE_APPLICATION:
$this->phpunit_add_definition_mapping($area, 'default_application', 0);
break;
case cache_store::MODE_SESSION:
$this->phpunit_add_definition_mapping($area, 'default_session', 0);
break;
case cache_store::MODE_REQUEST:
$this->phpunit_add_definition_mapping($area, 'default_request', 0);
break;
}
}
}
/**
* Removes a definition.
* @param string $name
*/
public function phpunit_remove_definition($name) {
unset($this->configdefinitions[$name]);
}
/**
* Removes the configured stores so that there are none available.
*/
public function phpunit_remove_stores() {
$this->configstores = array();
}
/**
* Forcefully adds a file store.
*
* You can turn off native TTL support if you want a way to test TTL wrapper objects.
*
* @param string $name
* @param bool $nativettl If false, uses fixture that turns off native TTL support
*/
public function phpunit_add_file_store(string $name, bool $nativettl = true): void {
if (!$nativettl) {
require_once(__DIR__ . '/cachestore_file_with_ttl_wrappers.php');
}
$this->configstores[$name] = array(
'name' => $name,
'plugin' => 'file',
'configuration' => array(
'path' => ''
),
'features' => 6,
'modes' => 3,
'mappingsonly' => false,
'class' => $nativettl ? 'cachestore_file' : 'cachestore_file_with_ttl_wrappers',
'default' => false,
'lock' => 'cachelock_file_default'
);
}
/**
* Hacks the in-memory configuration for a store.
*
* @param string $store Name of store to edit e.g. 'default_application'
* @param array $configchanges List of config changes
*/
public function phpunit_edit_store_config(string $store, array $configchanges): void {
foreach ($configchanges as $name => $value) {
$this->configstores[$store]['configuration'][$name] = $value;
}
}
/**
* Forcefully adds a session store.
*
* @param string $name
*/
public function phpunit_add_session_store($name) {
$this->configstores[$name] = array(
'name' => $name,
'plugin' => 'session',
'configuration' => array(),
'features' => 14,
'modes' => 2,
'default' => true,
'class' => 'cachestore_session',
'lock' => 'cachelock_file_default',
);
}
/**
* Forcefully injects a definition => store mapping.
*
* This function does no validation, you should only be calling if it you know
* exactly what to expect.
*
* @param string $definition
* @param string $store
* @param int $sort
*/
public function phpunit_add_definition_mapping($definition, $store, $sort) {
$this->configdefinitionmappings[] = array(
'store' => $store,
'definition' => $definition,
'sort' => (int)$sort
);
}
/**
* Overrides the default site identifier used by the Cache API so that we can be sure of what it is.
*
* @return string
*/
public function get_site_identifier() {
global $CFG;
return $CFG->wwwroot.'phpunit';
}
/**
* Checks if the configuration file exists.
*
* @return bool True if it exists
*/
public static function config_file_exists() {
// Allow for late static binding by using static.
$configfilepath = static::get_config_file_path();
// Invalidate opcode php cache, so we get correct status of file.
core_component::invalidate_opcode_php_cache($configfilepath);
return file_exists($configfilepath);
}
}
/**
* Dummy object for testing cacheable object interface and interaction
*
* Wake from cache needs specific testing at times to ensure that during multiple
* cache get() requests it's possible to verify that it's getting woken each time.
*
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_phpunit_dummy_object extends stdClass implements cacheable_object {
/**
* Test property 1
* @var string
*/
public $property1;
/**
* Test property 1
* @var string
*/
public $property2;
/**
* Test property time for verifying wake is run at each get() call.
* @var float
*/
public $propertytime;
/**
* Constructor
* @param string $property1
* @param string $property2
*/
public function __construct($property1, $property2, $propertytime = null) {
$this->property1 = $property1;
$this->property2 = $property2;
$this->propertytime = $propertytime === null ? microtime(true) : $propertytime;
}
/**
* Prepares this object for caching
* @return array
*/
public function prepare_to_cache() {
return array($this->property1.'_ptc', $this->property2.'_ptc', $this->propertytime);
}
/**
* Returns this object from the cache
* @param array $data
* @return cache_phpunit_dummy_object
*/
public static function wake_from_cache($data) {
$time = null;
if (!is_null($data[2])) {
// Windows 32bit microtime() resolution is 15ms, we ensure the time has moved forward.
do {
$time = microtime(true);
} while ($time == $data[2]);
}
return new cache_phpunit_dummy_object(array_shift($data).'_wfc', array_shift($data).'_wfc', $time);
}
}
/**
* Dummy data source object for testing data source interface and implementation
*
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_phpunit_dummy_datasource implements cache_data_source {
/**
* Returns an instance of this object for use with the cache.
*
* @param cache_definition $definition
* @return cache_phpunit_dummy_datasource
*/
public static function get_instance_for_cache(cache_definition $definition) {
return new cache_phpunit_dummy_datasource();
}
/**
* Loads a key for the cache.
*
* @param string $key
* @return string
*/
public function load_for_cache($key) {
return $key.' has no value really.';
}
/**
* Loads many keys for the cache
*
* @param array $keys
* @return array
*/
public function load_many_for_cache(array $keys) {
$return = array();
foreach ($keys as $key) {
$return[$key] = $key.' has no value really.';
}
return $return;
}
}
/**
* PHPUnit application cache loader.
*
* Used to expose things we could not otherwise see within an application cache.
*
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_phpunit_application extends cache_application {
/**
* Returns the class of the store immediately associated with this cache.
* @return string
*/
public function phpunit_get_store_class() {
return get_class($this->get_store());
}
/**
* Returns all the interfaces the cache store implements.
* @return array
*/
public function phpunit_get_store_implements() {
return class_implements($this->get_store());
}
/**
* Returns the given key directly from the static acceleration array.
*
* @param string $key
* @return false|mixed
*/
public function phpunit_static_acceleration_get($key) {
return $this->static_acceleration_get($key);
}
/**
* Purges only the static acceleration while leaving the rest of the store in tack.
*
* Used for behaving like you have loaded 2 pages, and reset static while the backing store
* still contains all the same data.
*
*/
public function phpunit_static_acceleration_purge() {
$this->static_acceleration_purge();
}
}
/**
* PHPUnit session cache loader.
*
* Used to expose things we could not otherwise see within an session cache.
*
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_phpunit_session extends cache_session {
/** @var Static member used for emulating the behaviour of session_id() during the tests. */
protected static $sessionidmockup = 'phpunitmockupsessionid';
/**
* Returns the class of the store immediately associated with this cache.
* @return string
*/
public function phpunit_get_store_class() {
return get_class($this->get_store());
}
/**
* Returns all the interfaces the cache store implements.
* @return array
*/
public function phpunit_get_store_implements() {
return class_implements($this->get_store());
}
/**
* Provide access to the {@link cache_session::get_key_prefix()} method.
*
* @return string
*/
public function phpunit_get_key_prefix() {
return $this->get_key_prefix();
}
/**
* Allows to inject the session identifier.
*
* @param string $sessionid
*/
public static function phpunit_mockup_session_id($sessionid) {
static::$sessionidmockup = $sessionid;
}
/**
* Override the parent behaviour so that it does not need the actual session_id() call.
*/
protected function set_session_id() {
$this->sessionid = static::$sessionidmockup;
}
}
/**
* PHPUnit request cache loader.
*
* Used to expose things we could not otherwise see within an request cache.
*
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_phpunit_request extends cache_request {
/**
* Returns the class of the store immediately associated with this cache.
* @return string
*/
public function phpunit_get_store_class() {
return get_class($this->get_store());
}
/**
* Returns all the interfaces the cache store implements.
* @return array
*/
public function phpunit_get_store_implements() {
return class_implements($this->get_store());
}
}
/**
* Dummy overridden cache loader class that we can use to test overriding loader functionality.
*
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_phpunit_dummy_overrideclass extends cache_application {
// Satisfying the code pre-checker is just part of my day job.
}
/**
* Cache PHPUnit specific factory.
*
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_phpunit_factory extends cache_factory {
/**
* Exposes the cache_factory's disable method.
*
* Perhaps one day that method will be made public, for the time being it is protected.
*/
public static function phpunit_disable() {
parent::disable();
}
}
/**
* Cache PHPUnit specific Cache helper.
*
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_phpunit_cache extends cache {
/**
* Make the changes which simulate a new request within the cache.
* This essentially resets currently held static values in the class, and increments the current timestamp.
*/
public static function simulate_new_request() {
self::$now += 0.1;
self::$purgetoken = null;
}
}
+193
View File
@@ -0,0 +1,193 @@
<?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/>.
/**
* Cache store test fixtures.
*
* @package core
* @category cache
* @copyright 2013 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* An abstract class to make writing unit tests for cache stores very easy.
*
* @package core
* @category cache
* @copyright 2013 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class cachestore_tests extends advanced_testcase {
/**
* Returns the class name for the store.
*
* @return string
*/
abstract protected function get_class_name();
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp(): void {
$class = $this->get_class_name();
if (!class_exists($class) || !$class::are_requirements_met()) {
$this->markTestSkipped('Could not test '.$class.'. Requirements are not met.');
}
parent::setUp();
}
/**
* Run the unit tests for the store.
*/
public function test_test_instance() {
$class = $this->get_class_name();
$modes = $class::get_supported_modes();
if ($modes & cache_store::MODE_APPLICATION) {
$definition = cache_definition::load_adhoc(cache_store::MODE_APPLICATION, $class, 'phpunit_test');
$instance = new $class($class.'_test', $class::unit_test_configuration());
if (!$instance->is_ready()) {
$this->markTestSkipped('Could not test '.$class.'. No test instance configured for application caches.');
} else {
$instance->initialise($definition);
$this->run_tests($instance);
}
}
if ($modes & cache_store::MODE_SESSION) {
$definition = cache_definition::load_adhoc(cache_store::MODE_SESSION, $class, 'phpunit_test');
$instance = new $class($class.'_test', $class::unit_test_configuration());
if (!$instance->is_ready()) {
$this->markTestSkipped('Could not test '.$class.'. No test instance configured for session caches.');
} else {
$instance->initialise($definition);
$this->run_tests($instance);
}
}
if ($modes & cache_store::MODE_REQUEST) {
$definition = cache_definition::load_adhoc(cache_store::MODE_REQUEST, $class, 'phpunit_test');
$instance = new $class($class.'_test', $class::unit_test_configuration());
if (!$instance->is_ready()) {
$this->markTestSkipped('Could not test '.$class.'. No test instance configured for request caches.');
} else {
$instance->initialise($definition);
$this->run_tests($instance);
}
}
}
/**
* Test the store for basic functionality.
*/
public function run_tests(cache_store $instance) {
$object = new stdClass;
$object->data = 1;
// Test set with a string.
$this->assertTrue($instance->set('test1', 'test1'));
$this->assertTrue($instance->set('test2', 'test2'));
$this->assertTrue($instance->set('test3', '3'));
$this->assertTrue($instance->set('other3', '3'));
// Test get with a string.
$this->assertSame('test1', $instance->get('test1'));
$this->assertSame('test2', $instance->get('test2'));
$this->assertSame('3', $instance->get('test3'));
// Test find and find with prefix if this class implements the searchable interface.
if ($instance->is_searchable()) {
// Extra settings here ignore the return order of the array.
$this->assertEqualsCanonicalizing(['test3', 'test1', 'test2', 'other3'], $instance->find_all());
// Extra settings here ignore the return order of the array.
$this->assertEqualsCanonicalizing(['test2', 'test1', 'test3'], $instance->find_by_prefix('test'));
$this->assertEquals(['test2'], $instance->find_by_prefix('test2'));
$this->assertEquals(['other3'], $instance->find_by_prefix('other'));
$this->assertEquals([], $instance->find_by_prefix('nothere'));
}
// Test set with an int.
$this->assertTrue($instance->set('test1', 1));
$this->assertTrue($instance->set('test2', 2));
// Test get with an int.
$this->assertSame(1, $instance->get('test1'));
$this->assertIsInt($instance->get('test1'));
$this->assertSame(2, $instance->get('test2'));
$this->assertIsInt($instance->get('test2'));
// Test set with a bool.
$this->assertTrue($instance->set('test1', true));
// Test get with an bool.
$this->assertSame(true, $instance->get('test1'));
$this->assertIsBool($instance->get('test1'));
// Test with an object.
$this->assertTrue($instance->set('obj', $object));
if ($instance::get_supported_features() & cache_store::DEREFERENCES_OBJECTS) {
$this->assertNotSame($object, $instance->get('obj'), 'Objects must be dereferenced when returned.');
}
$this->assertEquals($object, $instance->get('obj'));
// Test delete.
$this->assertTrue($instance->delete('test1'));
$this->assertTrue($instance->delete('test3'));
$this->assertFalse($instance->delete('test3'));
$this->assertFalse($instance->get('test1'));
$this->assertSame(2, $instance->get('test2'));
$this->assertTrue($instance->set('test1', 'test1'));
// Test purge.
$this->assertTrue($instance->purge());
$this->assertFalse($instance->get('test1'));
$this->assertFalse($instance->get('test2'));
// Test set_many.
$outcome = $instance->set_many(array(
array('key' => 'many1', 'value' => 'many1'),
array('key' => 'many2', 'value' => 'many2'),
array('key' => 'many3', 'value' => 'many3'),
array('key' => 'many4', 'value' => 'many4'),
array('key' => 'many5', 'value' => 'many5')
));
$this->assertSame(5, $outcome);
$this->assertSame('many1', $instance->get('many1'));
$this->assertSame('many5', $instance->get('many5'));
$this->assertFalse($instance->get('many6'));
// Test get_many.
$result = $instance->get_many(array('many1', 'many3', 'many5', 'many6'));
$this->assertIsArray($result);
$this->assertCount(4, $result);
$this->assertSame(array(
'many1' => 'many1',
'many3' => 'many3',
'many5' => 'many5',
'many6' => false,
), $result);
// Test delete_many.
$this->assertSame(3, $instance->delete_many(array('many2', 'many3', 'many4')));
$this->assertSame(2, $instance->delete_many(array('many1', 'many5', 'many6')));
}
}
+79
View File
@@ -0,0 +1,79 @@
<?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/>.
namespace core_cache;
/**
* Unit tests for cache_store functionality.
*
* @package core_cache
* @copyright 2021 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class store_test extends \advanced_testcase {
/**
* Tests the default implementation of cache_size_details, which does some
* complicated statistics.
*/
public function test_cache_size_details(): void {
// Fill a store with 100 entries of varying size.
$store = self::create_static_store();
for ($i = 0; $i < 100; $i++) {
$store->set('key' . $i, str_repeat('x', $i));
}
// Do the statistics for 10 random picks.
$details = $store->cache_size_details(10);
$this->assertTrue($details->supported);
$this->assertEquals(100, $details->items);
// Min/max possible means if it picks the smallest/largest 10.
$this->assertGreaterThan(22, $details->mean);
$this->assertLessThan(115, $details->mean);
// Min/max possible SD.
$this->assertLessThan(49, $details->sd);
$this->assertGreaterThan(2.8, $details->sd);
// Lowest possible confidence margin is about 1.74.
$this->assertGreaterThan(1.7, $details->margin);
// Repeat the statistics for a pick of all 100 entries (exact).
$details = $store->cache_size_details(100);
$this->assertTrue($details->supported);
$this->assertEquals(100, $details->items);
$this->assertEqualsWithDelta(69.3, $details->mean, 0.1);
$this->assertEqualsWithDelta(29.2, $details->sd, 0.1);
$this->assertEquals(0, $details->margin);
}
/**
* Creates a static store for testing.
*
* @return \cachestore_static Store
*/
protected static function create_static_store(): \cachestore_static {
require_once(__DIR__ . '/../stores/static/lib.php');
$store = new \cachestore_static('frog');
$definition = \cache_definition::load('zombie', [
'mode' => \cache_store::MODE_REQUEST,
'component' => 'phpunit',
'area' => 'store_test',
'simplekeys' => true
]);
$store->initialise($definition);
return $store;
}
}