API Upgrade tests to use new Config API

This commit is contained in:
Damian Mooyman 2017-02-22 16:15:08 +13:00
parent 3362e15a29
commit 8444a21cbf
36 changed files with 355 additions and 927 deletions

View File

@ -19,12 +19,5 @@ $_SERVER['REQUEST_URI'] = BASE_URL;
// Fake a session
$_SESSION = null;
// Prepare manifest autoloader
$controller = new FakeController();
SapphireTest::use_test_manifest();
SapphireTest::set_is_running_test(true);
// Remove the error handler so that PHPUnit can add its own
restore_error_handler();

View File

@ -124,15 +124,15 @@ class GDTest extends SapphireTest
case 0:
$this->assertColourEquals(0, $samples[2]['alpha'], $tolerance);
$this->assertColourEquals(0, $samples[12]['alpha'], $tolerance);
break;
break;
case 1:
$this->assertColourEquals(0, $samples[2]['alpha'], $tolerance);
$this->assertColourEquals(127, $samples[12]['alpha'], $tolerance);
break;
break;
default:
$this->assertColourEquals(63, $samples[2]['alpha'], $tolerance);
$this->assertColourEquals(127, $samples[12]['alpha'], $tolerance);
break;
break;
}
}

View File

@ -13,14 +13,14 @@ use SilverStripe\Dev\SapphireTest;
class AssetStoreTest extends SapphireTest
{
/**
* @skipUpgrade
*/
public function setUp()
{
parent::setUp();
// Set backend and base url
/**
* @skipUpgrade
*/
TestAssetStore::activate('AssetStoreTest');
}
@ -332,7 +332,7 @@ class AssetStoreTest extends SapphireTest
*/
public function testLegacyFilenames()
{
Config::inst()->update(get_class(new FlysystemAssetStore()), 'legacy_filenames', true);
Config::modify()->set(FlysystemAssetStore::class, 'legacy_filenames', true);
$backend = $this->getBackend();
@ -442,12 +442,12 @@ class AssetStoreTest extends SapphireTest
$store = $this->getBackend();
// Disable legacy filenames
Config::inst()->update(get_class(new FlysystemAssetStore()), 'legacy_filenames', false);
Config::modify()->set(FlysystemAssetStore::class, 'legacy_filenames', false);
$this->assertEquals(AssetStore::CONFLICT_OVERWRITE, $store->getDefaultConflictResolution(null));
$this->assertEquals(AssetStore::CONFLICT_OVERWRITE, $store->getDefaultConflictResolution('somevariant'));
// Enable legacy filenames
Config::inst()->update(get_class(new FlysystemAssetStore()), 'legacy_filenames', true);
Config::modify()->set(FlysystemAssetStore::class, 'legacy_filenames', true);
$this->assertEquals(AssetStore::CONFLICT_RENAME, $store->getDefaultConflictResolution(null));
$this->assertEquals(AssetStore::CONFLICT_OVERWRITE, $store->getDefaultConflictResolution('somevariant'));
}

View File

@ -14,7 +14,7 @@ use SilverStripe\Assets\Flysystem\GeneratedAssetHandler;
use SilverStripe\Assets\Storage\DBFile;
use SilverStripe\Assets\File;
use SilverStripe\Assets\Folder;
use SilverStripe\Core\Config\Config;
use SilverStripe\Control\Director;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\View\Requirements;
@ -23,7 +23,6 @@ use SilverStripe\View\Requirements;
*/
class TestAssetStore extends FlysystemAssetStore
{
/**
* Enable disclosure of secure assets
*
@ -81,10 +80,10 @@ class TestAssetStore extends FlysystemAssetStore
Requirements::backend()->setAssetHandler($generated);
// Disable legacy and set defaults
Config::inst()->remove(get_class(new FlysystemAssetStore()), 'legacy_filenames');
Config::inst()->update('SilverStripe\\Control\\Director', 'alternate_base_url', '/');
DBFile::config()->force_resample = false;
File::config()->force_resample = false;
FlysystemAssetStore::config()->set('legacy_filenames', false);
Director::config()->set('alternate_base_url', '/');
DBFile::config()->set('force_resample', false);
File::config()->set('force_resample', false);
self::reset();
self::$basedir = $basedir;
@ -136,18 +135,14 @@ class TestAssetStore extends FlysystemAssetStore
$asset = $asset->File;
}
// Extract filesystem used to store this object
/**
* @var TestAssetStore $assetStore
*/
/** @var TestAssetStore $assetStore */
$assetStore = Injector::inst()->get('AssetStore');
$fileID = $assetStore->getFileID($asset->Filename, $asset->Hash, $asset->Variant);
$filesystem = $assetStore->getProtectedFilesystem();
if (!$filesystem->has($fileID)) {
$filesystem = $assetStore->getPublicFilesystem();
}
/**
* @var Local $adapter
*/
/** @var Local $adapter */
$adapter = $filesystem->getAdapter();
return $adapter->applyPathPrefix($fileID);
}

View File

@ -2,7 +2,9 @@
namespace SilverStripe\Control\Tests;
use InvalidArgumentException;
use PHPUnit_Framework_Error;
use SilverStripe\Control\RequestHandler;
use SilverStripe\Control\Tests\ControllerTest\AccessBaseController;
use SilverStripe\Control\Tests\ControllerTest\AccessSecuredController;
use SilverStripe\Control\Tests\ControllerTest\AccessWildcardSecuredController;
@ -20,6 +22,7 @@ use SilverStripe\Control\HTTPRequest;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Dev\FunctionalTest;
use SilverStripe\ORM\DataModel;
use SilverStripe\Security\Member;
use SilverStripe\View\SSViewer;
class ControllerTest extends FunctionalTest
@ -103,7 +106,7 @@ class ControllerTest extends FunctionalTest
public function testAllowedActions()
{
$adminUser = $this->objFromFixture('SilverStripe\\Security\\Member', 'admin');
$adminUser = $this->objFromFixture(Member::class, 'admin');
$response = $this->get("UnsecuredController/");
$this->assertEquals(
@ -121,7 +124,7 @@ class ControllerTest extends FunctionalTest
'when called with an action in the URL'
);
Config::inst()->update('SilverStripe\\Control\\RequestHandler', 'require_allowed_actions', false);
Config::modify()->merge(RequestHandler::class, 'require_allowed_actions', false);
$response = $this->get("UnsecuredController/index");
$this->assertEquals(
200,
@ -129,7 +132,7 @@ class ControllerTest extends FunctionalTest
'Access granted on index action without $allowed_actions on defining controller, ' .
'when called with an action in the URL, and explicitly allowed through config'
);
Config::inst()->update('SilverStripe\\Control\\RequestHandler', 'require_allowed_actions', true);
Config::modify()->merge(RequestHandler::class, 'require_allowed_actions', true);
$response = $this->get("UnsecuredController/method1");
$this->assertEquals(
@ -139,7 +142,7 @@ class ControllerTest extends FunctionalTest
'when called without an action in the URL'
);
Config::inst()->update('SilverStripe\\Control\\RequestHandler', 'require_allowed_actions', false);
Config::modify()->merge(RequestHandler::class, 'require_allowed_actions', false);
$response = $this->get("UnsecuredController/method1");
$this->assertEquals(
200,
@ -147,7 +150,7 @@ class ControllerTest extends FunctionalTest
'Access granted on action without $allowed_actions on defining controller, ' .
'when called without an action in the URL, and explicitly allowed through config'
);
Config::inst()->update('SilverStripe\\Control\\RequestHandler', 'require_allowed_actions', true);
Config::modify()->merge(RequestHandler::class, 'require_allowed_actions', true);
$response = $this->get("AccessBaseController/");
$this->assertEquals(
@ -313,13 +316,9 @@ class ControllerTest extends FunctionalTest
$this->session()->inst_set('loggedInAs', null);
}
/**
* @expectedException PHPUnit_Framework_Error
* @expectedExceptionMessage Wildcards (*) are no longer valid
*/
public function testWildcardAllowedActions()
{
Deprecation::set_enabled(true);
$this->setExpectedException(InvalidArgumentException::class, "Invalid allowed_action '*'");
$this->get('AccessWildcardSecuredController');
}
@ -399,7 +398,7 @@ class ControllerTest extends FunctionalTest
}
/**
* @covers SilverStripe\Control\Controller::hasAction
* @covers \SilverStripe\Control\Controller::hasAction
*/
public function testHasAction()
{
@ -463,7 +462,7 @@ class ControllerTest extends FunctionalTest
/* Controller::BaseURL no longer exists, but was just a direct call to Director::BaseURL, so not sure what this
* code was supposed to test
public function testBaseURL() {
Config::inst()->update('Director', 'alternate_base_url', '/baseurl/');
Config::modify()->merge('Director', 'alternate_base_url', '/baseurl/');
$this->assertEquals(Controller::BaseURL(), Director::BaseURL());
}
*/

View File

@ -31,7 +31,6 @@ class DirectorTest extends SapphireTest
{
parent::setUp();
// Hold the original request URI once so it doesn't get overwritten
if (!self::$originalRequestURI) {
self::$originalRequestURI = $_SERVER['REQUEST_URI'];
@ -42,18 +41,6 @@ class DirectorTest extends SapphireTest
$this->originalSession = $_SESSION;
$_SESSION = array();
Config::inst()->update(
'SilverStripe\\Control\\Director',
'rules',
array(
'DirectorTestRule/$Action/$ID/$OtherID' => TestController::class,
'en-nz/$Action/$ID/$OtherID' => array(
'Controller' => TestController::class,
'Locale' => 'en_NZ'
)
)
);
$headers = array(
'HTTP_X_FORWARDED_PROTOCOL', 'HTTPS', 'SSL'
);
@ -64,13 +51,29 @@ class DirectorTest extends SapphireTest
}
}
Config::inst()->update('SilverStripe\\Control\\Director', 'alternate_base_url', '/');
Config::modify()->set(Director::class, 'alternate_base_url', '/');
}
protected function getExtraRoutes()
{
$rules = parent::getExtraRoutes();
$rules['DirectorTestRule/$Action/$ID/$OtherID'] = TestController::class;
$rules['en-nz/$Action/$ID/$OtherID'] = [
'Controller' => TestController::class,
'Locale' => 'en_NZ',
];
return $rules;
}
protected function setUpRoutes()
{
// Don't merge with any existing rules
Director::config()->set('rules', $this->getExtraRoutes());
}
public function tearDown()
{
// TODO Remove director rule, currently API doesnt allow this
$_GET = $this->originalGet;
$_SESSION = $this->originalSession;
@ -492,6 +495,7 @@ class DirectorTest extends SapphireTest
public function testUnmatchedRequestReturns404()
{
// Remove non-tested rules
$this->assertEquals(404, Director::test('no-route')->getStatusCode());
}

View File

@ -27,13 +27,13 @@ class HTTPTest extends FunctionalTest
$this->assertNotEmpty($response->getHeader('Cache-Control'));
// Ensure max-age is zero for development.
Director::config()->update('environment_type', 'dev');
Director::set_environment_type('dev');
$response = new HTTPResponse($body, 200);
HTTP::add_cache_headers($response);
$this->assertContains('max-age=0', $response->getHeader('Cache-Control'));
// Ensure max-age setting is respected in production.
Director::config()->update('environment_type', 'live');
Director::set_environment_type('live');
$response = new HTTPResponse($body, 200);
HTTP::add_cache_headers($response);
$this->assertContains('max-age=30', explode(', ', $response->getHeader('Cache-Control')));
@ -59,7 +59,7 @@ class HTTPTest extends FunctionalTest
{
$body = "<html><head></head><body><h1>Mysite</h1></body></html>";
$response = new HTTPResponse($body, 200);
Director::config()->update('environment_type', 'live');
Director::set_environment_type('live');
HTTP::set_cache_age(30);
HTTP::add_cache_headers($response);

View File

@ -45,50 +45,36 @@ class RequestHandlingTest extends FunctionalTest
FormActionController::class
];
public function setUp()
public function getExtraRoutes()
{
parent::setUp();
$routes = parent::getExtraRoutes();
return array_merge(
$routes,
[
// If we don't request any variables, then the whole URL will get shifted off.
// This is fine, but it means that the controller will have to parse the Action from the URL itself.
'testGoodBase1' => TestController::class,
Director::config()->update(
'rules',
array(
// If we don't request any variables, then the whole URL will get shifted off.
// This is fine, but it means that the controller will have to parse the Action from the URL itself.
'testGoodBase1' => TestController::class,
// The double-slash indicates how much of the URL should be shifted off the stack.
// This is important for dealing with nested request handlers appropriately.
'testGoodBase2//$Action/$ID/$OtherID' => TestController::class,
// The double-slash indicates how much of the URL should be shifted off the stack.
// This is important for dealing with nested request handlers appropriately.
'testGoodBase2//$Action/$ID/$OtherID' => TestController::class,
// By default, the entire URL will be shifted off. This creates a bit of
// backward-incompatability, but makes the URL rules much more explicit.
'testBadBase/$Action/$ID/$OtherID' => TestController::class,
// By default, the entire URL will be shifted off. This creates a bit of
// backward-incompatability, but makes the URL rules much more explicit.
'testBadBase/$Action/$ID/$OtherID' => TestController::class,
// Rules with an extension always default to the index() action
'testBaseWithExtension/virtualfile.xml' => TestController::class,
// Rules with an extension always default to the index() action
'testBaseWithExtension/virtualfile.xml' => TestController::class,
// Without the extension, the methodname should be matched
'testBaseWithExtension//$Action/$ID/$OtherID' => TestController::class,
// Without the extension, the methodname should be matched
'testBaseWithExtension//$Action/$ID/$OtherID' => TestController::class,
// Test nested base
'testParentBase/testChildBase//$Action/$ID/$OtherID' => TestController::class,
)
// Test nested base
'testParentBase/testChildBase//$Action/$ID/$OtherID' => TestController::class,
]
);
}
// public function testRequestHandlerChainingLatestParams() {
// $c = new RequestHandlingTest_Controller();
// $c->init();
// $response = $c->handleRequest(new HTTPRequest('GET', 'testGoodBase1/TestForm/fields/MyField'));
// $this->assertEquals(
// $c->getRequest()->latestParams(),
// array(
// 'Action' => 'fields',
// 'ID' => 'MyField'
// )
// );
// }
public function testConstructedWithNullRequest()
{
$r = new RequestHandler();

View File

@ -2,32 +2,16 @@
namespace SilverStripe\Core\Tests\Config;
use SilverStripe\Config\MergeStrategy\Priority;
use SilverStripe\Core\Object;
use SilverStripe\Core\Config\Config;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Dev\SapphireTest;
class ConfigTest extends SapphireTest
{
protected $depSettings = null;
public function setUp()
{
parent::setUp();
$this->depSettings = Deprecation::dump_settings();
Deprecation::set_enabled(false);
}
public function tearDown()
{
Deprecation::restore_settings($this->depSettings);
parent::tearDown();
}
public function testNest()
{
// Check basic config
$this->assertEquals(3, Config::inst()->get(ConfigTest\TestNest::class, 'foo'));
$this->assertEquals(5, Config::inst()->get(ConfigTest\TestNest::class, 'bar'));
@ -38,7 +22,7 @@ class ConfigTest extends SapphireTest
$this->assertEquals(5, Config::inst()->get(ConfigTest\TestNest::class, 'bar'));
// Test nested data can be updated
Config::inst()->update(ConfigTest\TestNest::class, 'foo', 4);
Config::modify()->merge(ConfigTest\TestNest::class, 'foo', 4);
$this->assertEquals(4, Config::inst()->get(ConfigTest\TestNest::class, 'foo'));
$this->assertEquals(5, Config::inst()->get(ConfigTest\TestNest::class, 'bar'));
@ -51,45 +35,85 @@ class ConfigTest extends SapphireTest
public function testUpdateStatic()
{
$this->assertEquals(
Config::inst()->get(ConfigTest\First::class, 'first', Config::FIRST_SET),
array('test_1')
['test_1'],
Config::inst()->get(ConfigTest\First::class, 'first')
);
$this->assertEquals(
Config::inst()->get(ConfigTest\Second::class, 'first', Config::FIRST_SET),
array('test_2')
[
'test_1',
'test_2'
],
Config::inst()->get(ConfigTest\Second::class, 'first')
);
$this->assertEquals(
Config::inst()->get(ConfigTest\Third::class, 'first', Config::FIRST_SET),
array('test_3')
[ 'test_2' ],
Config::inst()->get(ConfigTest\Second::class, 'first', true)
);
$this->assertEquals(
[
'test_1',
'test_2',
'test_3'
],
Config::inst()->get(ConfigTest\Third::class, 'first')
);
$this->assertEquals(
[ 'test_3' ],
Config::inst()->get(ConfigTest\Third::class, 'first', true)
);
Config::inst()->update(ConfigTest\First::class, 'first', array('test_1_2'));
Config::inst()->update(ConfigTest\Third::class, 'first', array('test_3_2'));
Config::inst()->update(ConfigTest\Fourth::class, 'first', array('test_4'));
Config::modify()->merge(ConfigTest\First::class, 'first', array('test_1_2'));
Config::modify()->merge(ConfigTest\Third::class, 'first', array('test_3_2'));
Config::modify()->merge(ConfigTest\Fourth::class, 'first', array('test_4'));
$this->assertEquals(
Config::inst()->get(ConfigTest\First::class, 'first', Config::FIRST_SET),
array('test_1_2', 'test_1')
);
Config::inst()->update(ConfigTest\Fourth::class, 'second', array('test_4'));
Config::inst()->update(ConfigTest\Third::class, 'second', array('test_3_2'));
$this->assertEquals(
Config::inst()->get(ConfigTest\Fourth::class, 'second', Config::FIRST_SET),
array('test_4')
['test_1', 'test_1_2'],
Config::inst()->get(ConfigTest\First::class, 'first')
);
$this->assertEquals(
Config::inst()->get(ConfigTest\Third::class, 'second', Config::FIRST_SET),
array('test_3_2', 'test_3')
['test_1', 'test_1_2'],
Config::inst()->get(ConfigTest\First::class, 'first', true)
);
Config::inst()->remove(ConfigTest\Third::class, 'second');
$this->assertEquals(array(), Config::inst()->get(ConfigTest\Third::class, 'second'));
Config::inst()->update(ConfigTest\Third::class, 'second', array('test_3_2'));
Config::modify()->merge(ConfigTest\Fourth::class, 'second', array('test_4'));
Config::modify()->merge(ConfigTest\Third::class, 'second', array('test_3_2'));
$this->assertEquals(
Config::inst()->get(ConfigTest\Third::class, 'second', Config::FIRST_SET),
array('test_3_2')
['test_1', 'test_3', 'test_3_2', 'test_4'],
Config::inst()->get(ConfigTest\Fourth::class, 'second')
);
$this->assertEquals(
['test_4'],
Config::inst()->get(ConfigTest\Fourth::class, 'second', true)
);
$this->assertEquals(
['test_1', 'test_3', 'test_3_2'],
Config::inst()->get(ConfigTest\Third::class, 'second')
);
$this->assertEquals(
['test_3', 'test_3_2'],
Config::inst()->get(ConfigTest\Third::class, 'second', true)
);
Config::modify()->remove(ConfigTest\Third::class, 'second');
$this->assertEquals(
['test_1'],
Config::inst()->get(ConfigTest\Third::class, 'second')
);
$this->assertTrue(
Config::inst()->exists(ConfigTest\Third::class, 'second')
);
$this->assertEquals(
null,
Config::inst()->get(ConfigTest\Third::class, 'second', true)
);
$this->assertFalse(
Config::inst()->exists(ConfigTest\Third::class, 'second', true)
);
Config::modify()->merge(ConfigTest\Third::class, 'second', ['test_3_2']);
$this->assertEquals(
['test_1', 'test_3_2'],
Config::inst()->get(ConfigTest\Third::class, 'second')
);
}
@ -97,30 +121,30 @@ class ConfigTest extends SapphireTest
{
// Booleans
$this->assertTrue(Config::inst()->get(ConfigTest\First::class, 'bool'));
Config::inst()->update(ConfigTest\First::class, 'bool', false);
Config::modify()->merge(ConfigTest\First::class, 'bool', false);
$this->assertFalse(Config::inst()->get(ConfigTest\First::class, 'bool'));
Config::inst()->update(ConfigTest\First::class, 'bool', true);
Config::modify()->merge(ConfigTest\First::class, 'bool', true);
$this->assertTrue(Config::inst()->get(ConfigTest\First::class, 'bool'));
// Integers
$this->assertEquals(42, Config::inst()->get(ConfigTest\First::class, 'int'));
Config::inst()->update(ConfigTest\First::class, 'int', 0);
Config::modify()->merge(ConfigTest\First::class, 'int', 0);
$this->assertEquals(0, Config::inst()->get(ConfigTest\First::class, 'int'));
Config::inst()->update(ConfigTest\First::class, 'int', 42);
Config::modify()->merge(ConfigTest\First::class, 'int', 42);
$this->assertEquals(42, Config::inst()->get(ConfigTest\First::class, 'int'));
// Strings
$this->assertEquals('value', Config::inst()->get(ConfigTest\First::class, 'string'));
Config::inst()->update(ConfigTest\First::class, 'string', '');
Config::modify()->merge(ConfigTest\First::class, 'string', '');
$this->assertEquals('', Config::inst()->get(ConfigTest\First::class, 'string'));
Config::inst()->update(ConfigTest\First::class, 'string', 'value');
Config::modify()->merge(ConfigTest\First::class, 'string', 'value');
$this->assertEquals('value', Config::inst()->get(ConfigTest\First::class, 'string'));
// Nulls
$this->assertEquals('value', Config::inst()->get(ConfigTest\First::class, 'nullable'));
Config::inst()->update(ConfigTest\First::class, 'nullable', null);
Config::modify()->merge(ConfigTest\First::class, 'nullable', null);
$this->assertNull(Config::inst()->get(ConfigTest\First::class, 'nullable'));
Config::inst()->update(ConfigTest\First::class, 'nullable', 'value');
Config::modify()->merge(ConfigTest\First::class, 'nullable', 'value');
$this->assertEquals('value', Config::inst()->get(ConfigTest\First::class, 'nullable'));
}
@ -138,8 +162,8 @@ class ConfigTest extends SapphireTest
$this->assertEquals(Config::inst()->get(ConfigTest\First::class, 'third', Config::UNINHERITED), 'test_1');
$this->assertEquals(Config::inst()->get(ConfigTest\Fourth::class, 'third', Config::UNINHERITED), null);
Config::inst()->update(ConfigTest\First::class, 'first', array('test_1b'));
Config::inst()->update(ConfigTest\Second::class, 'first', array('test_2b'));
Config::modify()->merge(ConfigTest\First::class, 'first', array('test_1b'));
Config::modify()->merge(ConfigTest\Second::class, 'first', array('test_2b'));
// Check that it can be applied to parent and subclasses, and queried directly
$this->assertContains(
@ -161,54 +185,78 @@ class ConfigTest extends SapphireTest
// Subclasses that don't have the static explicitly defined should allow definition, also
// This also checks that set can be called after the first uninherited get()
// call (which can be buggy due to caching)
Config::inst()->update(ConfigTest\Fourth::class, 'first', array('test_4b'));
Config::modify()->merge(ConfigTest\Fourth::class, 'first', array('test_4b'));
$this->assertContains('test_4b', Config::inst()->get(ConfigTest\Fourth::class, 'first', Config::UNINHERITED));
}
public function testCombinedStatic()
{
$this->assertEquals(
Config::inst()->get(ConfigTest\Combined3::class, 'first'),
array('test_3', 'test_2', 'test_1')
['test_1', 'test_2', 'test_3'],
ConfigTest\Combined3::config()->get('first')
);
// test that null values are ignored, but values on either side are still merged
// Test that unset values are ignored
$this->assertEquals(
Config::inst()->get(ConfigTest\Combined3::class, 'second'),
array('test_3', 'test_1')
['test_1', 'test_3'],
ConfigTest\Combined3::config()->get('second')
);
}
public function testMerges()
{
$result = array('A' => 1, 'B' => 2, 'C' => 3);
Config::merge_array_low_into_high($result, array('C' => 4, 'D' => 5));
$this->assertEquals($result, array('A' => 1, 'B' => 2, 'C' => 3, 'D' => 5));
$result = array('A' => 1, 'B' => 2, 'C' => 3);
Config::merge_array_high_into_low($result, array('C' => 4, 'D' => 5));
$this->assertEquals($result, array('A' => 1, 'B' => 2, 'C' => 4, 'D' => 5));
$result = array('A' => 1, 'B' => 2, 'C' => array(1, 2, 3));
Config::merge_array_low_into_high($result, array('C' => array(4, 5, 6), 'D' => 5));
$this->assertEquals($result, array('A' => 1, 'B' => 2, 'C' => array(1, 2, 3, 4, 5, 6), 'D' => 5));
$result = array('A' => 1, 'B' => 2, 'C' => array(1, 2, 3));
Config::merge_array_high_into_low($result, array('C' => array(4, 5, 6), 'D' => 5));
$this->assertEquals($result, array('A' => 1, 'B' => 2, 'C' => array(4, 5, 6, 1, 2, 3), 'D' => 5));
$result = array('A' => 1, 'B' => 2, 'C' => array('Foo' => 1, 'Bar' => 2), 'D' => 3);
Config::merge_array_low_into_high($result, array('C' => array('Bar' => 3, 'Baz' => 4)));
$result = Priority::mergeArray(
['A' => 1, 'B' => 2, 'C' => 3],
['C' => 4, 'D' => 5]
);
$this->assertEquals(
$result,
array('A' => 1, 'B' => 2, 'C' => array('Foo' => 1, 'Bar' => 2, 'Baz' => 4), 'D' => 3)
['A' => 1, 'B' => 2, 'C' => 3, 'D' => 5],
$result
);
$result = array('A' => 1, 'B' => 2, 'C' => array('Foo' => 1, 'Bar' => 2), 'D' => 3);
Config::merge_array_high_into_low($result, array('C' => array('Bar' => 3, 'Baz' => 4)));
$result = Priority::mergeArray(
['C' => 4, 'D' => 5],
['A' => 1, 'B' => 2, 'C' => 3]
);
$this->assertEquals(
$result,
array('A' => 1, 'B' => 2, 'C' => array('Foo' => 1, 'Bar' => 3, 'Baz' => 4), 'D' => 3)
['A' => 1, 'B' => 2, 'C' => 4, 'D' => 5],
$result
);
$result = Priority::mergeArray(
[ 'C' => [4, 5, 6], 'D' => 5 ],
[ 'A' => 1, 'B' => 2, 'C' => [1, 2, 3] ]
);
$this->assertEquals(
['A' => 1, 'B' => 2, 'C' => [1, 2, 3, 4, 5, 6], 'D' => 5],
$result
);
$result = Priority::mergeArray(
['A' => 1, 'B' => 2, 'C' => [1, 2, 3]],
['C' => [4, 5, 6], 'D' => 5]
);
$this->assertEquals(
['A' => 1, 'B' => 2, 'C' => [4, 5, 6, 1, 2, 3], 'D' => 5],
$result
);
$result = Priority::mergeArray(
['A' => 1, 'B' => 2, 'C' => ['Foo' => 1, 'Bar' => 2], 'D' => 3],
['C' => ['Bar' => 3, 'Baz' => 4]]
);
$this->assertEquals(
['A' => 1, 'B' => 2, 'C' => ['Foo' => 1, 'Bar' => 2, 'Baz' => 4], 'D' => 3],
$result
);
$result = Priority::mergeArray(
['C' => ['Bar' => 3, 'Baz' => 4]],
['A' => 1, 'B' => 2, 'C' => ['Foo' => 1, 'Bar' => 2], 'D' => 3]
);
$this->assertEquals(
['A' => 1, 'B' => 2, 'C' => ['Foo' => 1, 'Bar' => 3, 'Baz' => 4], 'D' => 3],
$result
);
}
@ -240,41 +288,4 @@ class ConfigTest extends SapphireTest
$this->assertTrue(empty($config->bar));
$this->assertNull($config->bar);
}
public function testFragmentOrder()
{
$this->markTestIncomplete();
}
public function testCacheCleaning()
{
$cache = new ConfigTest\ConfigTestMemCache();
for ($i = 0; $i < 1000;
$i++) {
$cache->set($i, $i);
}
$this->assertEquals(1000, count($cache->cache));
$cache->clean();
$this->assertEquals(0, count($cache->cache), 'Clean clears all items');
$this->assertFalse($cache->get(1), 'Clean clears all items');
$cache->set(1, 1, array('Foo'));
$this->assertEquals(1, count($cache->cache));
$this->assertEquals(1, count($cache->tags));
$cache->clean('Foo');
$this->assertEquals(0, count($cache->tags), 'Clean items with matching tag');
$this->assertFalse($cache->get(1), 'Clean items with matching tag');
$cache->set(1, 1, array('Foo', 'Bar'));
$this->assertEquals(2, count($cache->tags));
$this->assertEquals(1, count($cache->cache));
$cache->clean('Bar');
$this->assertEquals(1, count($cache->tags));
$this->assertEquals(0, count($cache->cache), 'Clean items with any single matching tag');
$this->assertFalse($cache->get(1), 'Clean items with any single matching tag');
}
}

View File

@ -2,17 +2,20 @@
namespace SilverStripe\Core\Tests\Config\ConfigTest;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Dev\TestOnly;
class Combined1 extends Config implements TestOnly
class Combined1 implements TestOnly
{
use Configurable;
/**
* @config
*/
private static $first = array('test_1');
private static $first = ['test_1'];
/**
* @config
*/
private static $second = array('test_1');
private static $second = ['test_1'];
}

View File

@ -4,6 +4,5 @@ namespace SilverStripe\Core\Tests\Config\ConfigTest;
class Combined2 extends Combined1
{
private static $first = array('test_2');
private static $second = null;
private static $first = ['test_2'];
}

View File

@ -4,6 +4,6 @@ namespace SilverStripe\Core\Tests\Config\ConfigTest;
class Combined3 extends Combined2
{
private static $first = array('test_3');
private static $second = array('test_3');
private static $first = ['test_3'];
private static $second = ['test_3'];
}

View File

@ -1,12 +0,0 @@
<?php
namespace SilverStripe\Core\Tests\Config\ConfigTest;
use SilverStripe\Core\Config\Config_MemCache;
use SilverStripe\Dev\TestOnly;
class ConfigTestMemCache extends Config_MemCache implements TestOnly
{
public $cache;
public $tags;
}

View File

@ -13,7 +13,7 @@ class InjectorTestConfigLocator extends SilverStripeServiceConfigurationLocator
switch ($name) {
case TestObject::class:
return $this->configs[$name] = array(
return $this->configs[$name] = array(
'class' => ConstructableObject::class,
'constructor' => array(
'%$'.OtherTestObject::class
@ -21,7 +21,7 @@ class InjectorTestConfigLocator extends SilverStripeServiceConfigurationLocator
);
case 'ConfigConstructor':
return $this->configs[$name] = array(
return $this->configs[$name] = array(
'class' => ConstructableObject::class,
'constructor' => array('value')
);

View File

@ -50,8 +50,8 @@ class ClassManifestTest extends SapphireTest
'classc' => "{$this->base}/module/classes/ClassC.php",
'classd' => "{$this->base}/module/classes/ClassD.php",
'classe' => "{$this->base}/module/classes/ClassE.php",
'sstemplateparser' => FRAMEWORK_PATH."/View/SSTemplateParser.php",
'sstemplateparseexception' => FRAMEWORK_PATH."/View/SSTemplateParseException.php"
'sstemplateparser' => FRAMEWORK_PATH."/src/View/SSTemplateParser.php",
'sstemplateparseexception' => FRAMEWORK_PATH."/src/View/SSTemplateParseException.php"
);
$this->assertEquals($expect, $this->manifest->getClasses());
}

View File

@ -2,12 +2,11 @@
namespace SilverStripe\Core\Tests\Manifest;
use Dotenv\Loader;
use SilverStripe\Config\Collections\MemoryConfigCollection;
use SilverStripe\Control\Director;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Manifest\ConfigManifest;
use SilverStripe\Core\Config\CoreConfigCreator;
use SilverStripe\Dev\SapphireTest;
use ReflectionProperty;
use Symfony\Component\Cache\Simple\ArrayCache;
class ConfigManifestTest extends SapphireTest
{
@ -19,378 +18,33 @@ class ConfigManifestTest extends SapphireTest
*/
protected function getConfigFixtureValue($name)
{
$manifest = new ConfigManifest(dirname(__FILE__).'/fixtures/configmanifest', true, true);
return $manifest->get(__CLASS__, $name);
return $this->getTestConfig()->get(__CLASS__, $name);
}
/**
* Build a new config based on YMl manifest
*
* @return MemoryConfigCollection
*/
public function getTestConfig()
{
$config = new MemoryConfigCollection();
$transformer = CoreConfigCreator::inst()->buildYamlTransformerForPath(dirname(__FILE__) . '/fixtures/configmanifest');
$config->transform([$transformer]);
return $config;
}
/**
* This is a helper method for displaying a relevant message about a parsing failure
*
* @param string $path
* @return string
*/
protected function getParsedAsMessage($path)
{
return sprintf('Reference path "%s" failed to parse correctly', $path);
}
/**
* A helper method to return a mock of the cache in order to test expectations and reduce dependency
*
* @return \PHPUnit_Framework_MockObject_MockObject
*/
protected function getCacheMock()
{
return $this->getMock(
ArrayCache::class,
array('set', 'get'),
array(),
'',
false
);
}
/**
* A helper method to return a mock of the manifest in order to test expectations and reduce dependency
*
* @param $methods
* @return \PHPUnit_Framework_MockObject_MockObject
*/
protected function getManifestMock($methods)
{
return $this->getMock(
ConfigManifest::class,
$methods,
array(), // no constructor arguments
'', // default
false // don't call the constructor
);
}
/**
* Test the caching functionality when we are forcing regeneration
*
* 1. Test that regenerate is called in the default case and that cache->load isn't
* 2. Test that save is called correctly after the regeneration
*/
public function testCachingForceRegeneration()
{
// Test that regenerate is called correctly.
$manifest = $this->getManifestMock(array('getCache', 'regenerate', 'buildYamlConfigVariant'));
$manifest->expects($this->once()) // regenerate should be called once
->method('regenerate')
->with($this->equalTo(true)); // includeTests = true
// Set up a cache where we expect load to never be called
$cache = $this->getCacheMock();
$cache->expects($this->never())
->method('get');
$manifest->expects($this->any())
->method('getCache')
->will($this->returnValue($cache));
$manifest->__construct(dirname(__FILE__).'/fixtures/configmanifest', true, true);
// Test that save is called correctly
$manifest = $this->getManifestMock(array('getCache'));
$cache = $this->getCacheMock();
$cache->expects($this->atLeastOnce())
->method('set');
$manifest->expects($this->any())
->method('getCache')
->will($this->returnValue($cache));
$manifest->__construct(dirname(__FILE__).'/fixtures/configmanifest', true, true);
}
/**
* Test the caching functionality when we are not forcing regeneration
*
* 1. Test that load is called
* 2. Test the regenerate is called when the cache is unprimed
* 3. Test that when there is a value in the cache regenerate isn't called
*/
public function testCachingNotForceRegeneration()
{
// Test that load is called
$manifest = $this->getManifestMock(array('getCache', 'regenerate', 'buildYamlConfigVariant'));
// Load should be called twice
$cache = $this->getCacheMock();
$cache->expects($this->exactly(2))
->method('get');
$manifest->expects($this->any())
->method('getCache')
->will($this->returnValue($cache));
$manifest->__construct(dirname(__FILE__).'/fixtures/configmanifest', true, false);
// Now test that regenerate is called because the cache is unprimed
$manifest = $this->getManifestMock(array('getCache', 'regenerate', 'buildYamlConfigVariant'));
$cache = $this->getCacheMock();
$cache->expects($this->exactly(2))
->method('get')
->will($this->onConsecutiveCalls(false, false));
$manifest->expects($this->any())
->method('getCache')
->will($this->returnValue($cache));
$manifest->expects($this->once())
->method('regenerate')
->with($this->equalTo(false)); //includeTests = false
$manifest->__construct(dirname(__FILE__).'/fixtures/configmanifest', false, false);
// Now test that when there is a value in the cache that regenerate isn't called
$manifest = $this->getManifestMock(array('getCache', 'regenerate', 'buildYamlConfigVariant'));
$cache = $this->getCacheMock();
$cache->expects($this->exactly(2))
->method('get')
->will($this->onConsecutiveCalls(array(), array()));
$manifest->expects($this->any())
->method('getCache')
->will($this->returnValue($cache));
$manifest->expects($this->never())
->method('regenerate');
$manifest->__construct(dirname(__FILE__).'/fixtures/configmanifest', false, false);
}
/**
* Test cache regeneration if all or some of the cache files are missing
*
* 1. Test regeneration if all cache files are missing
* 2. Test regeneration if 'variant_key_spec' cache file is missing
* 3. Test regeneration if 'php_config_sources' cache file is missing
*/
public function testAutomaticCacheRegeneration()
{
$base = dirname(__FILE__) . '/fixtures/configmanifest';
// Test regeneration if all cache files are missing
$manifest = $this->getManifestMock(array('getCache', 'regenerate', 'buildYamlConfigVariant'));
$manifest->expects($this->once())// regenerate should be called once
->method('regenerate')
->with($this->equalTo(false)); // includeTests = false
// Set up a cache where we expect load to never be called
$cache = $this->getCacheMock();
$cache->expects($this->exactly(2))
->will($this->returnValue(false))
->method('get');
$manifest->expects($this->any())
->method('getCache')
->will($this->returnValue($cache));
$manifest->__construct($base);
// Test regeneration if 'variant_key_spec' cache file is missing
$manifest = $this->getManifestMock(array('getCache', 'regenerate', 'buildYamlConfigVariant'));
$manifest->expects($this->once())// regenerate should be called once
->method('regenerate')
->with($this->equalTo(false)); // includeTests = false
$cache = $this->getCacheMock();
$cache->expects($this->exactly(2))
->method('get')
->will($this->returnCallback(function ($parameter) {
if (strpos($parameter, 'variant_key_spec') !== false) {
return false;
}
return array();
}));
$manifest->expects($this->any())
->method('getCache')
->will($this->returnValue($cache));
$manifest->__construct($base);
// Test regeneration if 'php_config_sources' cache file is missing
$manifest = $this->getManifestMock(array('getCache', 'regenerate', 'buildYamlConfigVariant'));
$manifest->expects($this->once())// regenerate should be called once
->method('regenerate')
->with($this->equalTo(false)); // includeTests = false
$cache = $this->getCacheMock();
$cache->expects($this->exactly(2))
->method('get')
->will($this->returnCallback(function ($parameter) {
if (strpos($parameter, 'php_config_sources') !== false) {
return false;
}
return array();
}));
$manifest->expects($this->any())
->method('getCache')
->will($this->returnValue($cache));
$manifest->__construct($base);
}
/**
* This test checks the processing of before and after reference paths (module-name/filename#fragment)
* This method uses fixture/configmanifest/mysite/_config/addyamlconfigfile.yml as a fixture
*/
public function testAddYAMLConfigFileReferencePathParsing()
{
// Use a mock to avoid testing unrelated functionality
$manifest = $this->getManifestMock(array('addModule'));
// This tests that the addModule method is called with the correct value
$manifest->expects($this->once())
->method('addModule')
->with($this->equalTo(dirname(__FILE__).'/fixtures/configmanifest/mysite'));
// Call the method to be tested
$manifest->addYAMLConfigFile(
'addyamlconfigfile.yml',
dirname(__FILE__).'/fixtures/configmanifest/mysite/_config/addyamlconfigfile.yml',
false
);
// There is no getter for yamlConfigFragments
$property = new ReflectionProperty('SilverStripe\\Core\\Manifest\\ConfigManifest', 'yamlConfigFragments');
$property->setAccessible(true);
// Get the result back from the parsing
$result = $property->getValue($manifest);
$this->assertEquals(
array(
array(
'module' => 'mysite',
'file' => 'testfile',
'name' => 'fragment',
),
),
@$result[0]['after'],
$this->getParsedAsMessage('mysite/testfile#fragment')
);
$this->assertEquals(
array(
array(
'module' => 'test-module',
'file' => 'testfile',
'name' => 'fragment',
),
),
@$result[1]['after'],
$this->getParsedAsMessage('test-module/testfile#fragment')
);
$this->assertEquals(
array(
array(
'module' => '*',
'file' => '*',
'name' => '*',
),
),
@$result[2]['after'],
$this->getParsedAsMessage('*')
);
$this->assertEquals(
array(
array(
'module' => '*',
'file' => 'testfile',
'name' => '*'
),
),
@$result[3]['after'],
$this->getParsedAsMessage('*/testfile')
);
$this->assertEquals(
array(
array(
'module' => '*',
'file' => '*',
'name' => 'fragment'
),
),
@$result[4]['after'],
$this->getParsedAsMessage('*/*#fragment')
);
$this->assertEquals(
array(
array(
'module' => '*',
'file' => '*',
'name' => 'fragment'
),
),
@$result[5]['after'],
$this->getParsedAsMessage('#fragment')
);
$this->assertEquals(
array(
array(
'module' => 'test-module',
'file' => '*',
'name' => 'fragment'
),
),
@$result[6]['after'],
$this->getParsedAsMessage('test-module#fragment')
);
$this->assertEquals(
array(
array(
'module' => 'test-module',
'file' => '*',
'name' => '*'
),
),
@$result[7]['after'],
$this->getParsedAsMessage('test-module')
);
$this->assertEquals(
array(
array(
'module' => 'test-module',
'file' => '*',
'name' => '*'
),
),
@$result[8]['after'],
$this->getParsedAsMessage('test-module/*')
);
$this->assertEquals(
array(
array(
'module' => 'test-module',
'file' => '*',
'name' => '*'
),
),
@$result[9]['after'],
$this->getParsedAsMessage('test-module/*/#*')
);
}
public function testClassRules()
{
$config = $this->getConfigFixtureValue('Class');
@ -427,8 +81,7 @@ class ConfigManifestTest extends SapphireTest
public function testEnvVarSetRules()
{
$loader = new \Dotenv\Loader(null);
$loader = new Loader(null);
$loader->setEnvironmentVariable('ENVVARSET_FOO', 1);
$config = $this->getConfigFixtureValue('EnvVarSet');
@ -465,10 +118,10 @@ class ConfigManifestTest extends SapphireTest
public function testEnvOrConstantMatchesValueRules()
{
$loader = new \Dotenv\Loader(null);
$loader = new Loader(null);
$loader->setEnvironmentVariable('ENVORCONSTANTMATCHESVALUE_FOO', 'Foo');
define('ENVORCONSTANTMATCHESVALUE_BAR', 'Bar');
$loader->setEnvironmentVariable('CONSTANTMATCHESVALUE_FOO', 'Foo');
define('CONSTANTMATCHESVALUE_BAR', 'Bar');
$config = $this->getConfigFixtureValue('EnvOrConstantMatchesValue');
$this->assertEquals(
@ -505,43 +158,22 @@ class ConfigManifestTest extends SapphireTest
public function testEnvironmentRules()
{
foreach (array('dev', 'test', 'live') as $env) {
Config::nest();
Config::inst()->update('SilverStripe\\Control\\Director', 'environment_type', $env);
Director::set_environment_type($env);
$config = $this->getConfigFixtureValue('Environment');
foreach (array('dev', 'test', 'live') as $check) {
$this->assertEquals(
$env == $check ? $check : 'not'.$check,
@$config[ucfirst($check).'Environment'],
'Only & except rules correctly detect environment'
'Only & except rules correctly detect environment in env ' . $env
);
}
Config::unnest();
}
}
public function testDynamicEnvironmentRules()
{
// First, make sure environment_type is live
Director::config()->update('environment_type', 'live');
$this->assertEquals('live', Director::config()->get('environment_type'));
// Then, load in a new manifest, which includes a _config.php that sets environment_type to dev
$manifest = new ConfigManifest(dirname(__FILE__).'/fixtures/configmanifest_dynamicenv', true, true);
Config::inst()->pushConfigYamlManifest($manifest);
// Make sure that stuck
$this->assertEquals('dev', Director::config()->get('environment_type'));
// And that the dynamic rule was calculated correctly
$this->assertEquals('dev', Config::inst()->get(__CLASS__, 'DynamicEnvironment'));
}
public function testMultipleRules()
{
$loader = new \Dotenv\Loader(null);
$loader = new Loader(null);
$loader->setEnvironmentVariable('MULTIPLERULES_ENVVARIABLESET', 1);
define('MULTIPLERULES_DEFINEDCONSTANT', 'defined');
@ -577,121 +209,4 @@ class ConfigManifestTest extends SapphireTest
'Fragment is included if both blocks succeed.'
);
}
public function testRelativeOrder()
{
$accessor = new ConfigManifestTest\ConfigManifestAccess(BASE_PATH, true, false);
// A fragment with a fully wildcard before rule
$beforeWildcarded = array(
'module' => 'foo', 'file' => 'alpha', 'name' => '1',
'before' => array(array('module' => '*', 'file' => '*', 'name' => '*'))
);
// A fragment with a fully wildcard before rule and a fully explicit after rule
$beforeWildcardedAfterExplicit = array_merge(
$beforeWildcarded,
array(
'after' => array(array('module' => 'bar', 'file' => 'beta', 'name' => '2'))
)
);
// A fragment with a fully wildcard before rule and two fully explicit after rules
$beforeWildcardedAfterTwoExplicitRules = array_merge(
$beforeWildcarded,
array(
'after' => array(
array('module' => 'bar', 'file' => 'beta', 'name' => '2'),
array('module' => 'baz', 'file' => 'gamma', 'name' => '3')
)
)
);
// A fragment with a fully wildcard before rule and a partially explicit after rule
$beforeWildcardedAfterPartialWildcarded = array_merge(
$beforeWildcarded,
array(
'after' => array(array('module' => 'bar', 'file' => 'beta', 'name' => '*'))
)
);
// Wildcard should match any module
$this->assertEquals(
$accessor->relativeOrder(
$beforeWildcarded,
array('module' => 'qux', 'file' => 'delta', 'name' => '4')
),
'before'
);
// Wildcard should match any module even if there is an opposing rule, if opposing rule doesn't match
$this->assertEquals(
$accessor->relativeOrder(
$beforeWildcardedAfterExplicit,
array('module' => 'qux', 'file' => 'delta', 'name' => '4')
),
'before'
);
// Wildcard should match any module even if there is an opposing rule, if opposing rule doesn't match, no
// matter how many opposing rules
$this->assertEquals(
$accessor->relativeOrder(
$beforeWildcardedAfterExplicit,
array('module' => 'qux', 'file' => 'delta', 'name' => '4')
),
'before'
);
// Wildcard should match any module even if there is an opposing rule, if opposing rule doesn't match
// (even if some portions do)
$this->assertEquals(
$accessor->relativeOrder(
$beforeWildcardedAfterExplicit,
array('module' => 'bar', 'file' => 'beta', 'name' => 'nomatchy')
),
'before'
);
// When opposing rule matches, wildcard should be ignored
$this->assertEquals(
$accessor->relativeOrder(
$beforeWildcardedAfterExplicit,
array('module' => 'bar', 'file' => 'beta', 'name' => '2')
),
'after'
);
// When any one of mutiple opposing rule exists, wildcard should be ignored
$this->assertEquals(
$accessor->relativeOrder(
$beforeWildcardedAfterTwoExplicitRules,
array('module' => 'bar', 'file' => 'beta', 'name' => '2')
),
'after'
);
$this->assertEquals(
$accessor->relativeOrder(
$beforeWildcardedAfterTwoExplicitRules,
array('module' => 'baz', 'file' => 'gamma', 'name' => '3')
),
'after'
);
// When two opposed wildcard rules, and more specific one doesn't match, other should win
$this->assertEquals(
$accessor->relativeOrder(
$beforeWildcardedAfterPartialWildcarded,
array('module' => 'qux', 'file' => 'delta', 'name' => '4')
),
'before'
);
// When two opposed wildcard rules, and more specific one does match, more specific one should win
$this->assertEquals(
$accessor->relativeOrder(
$beforeWildcardedAfterPartialWildcarded,
array('module' => 'bar', 'file' => 'beta', 'name' => 'wildcardmatchy')
),
'after'
);
}
}

View File

@ -1,13 +0,0 @@
<?php
namespace SilverStripe\Core\Tests\Manifest\ConfigManifestTest;
use SilverStripe\Core\Manifest\ConfigManifest;
class ConfigManifestAccess extends ConfigManifest
{
public function relativeOrder($a, $b)
{
return parent::relativeOrder($a, $b);
}
}

View File

@ -1,38 +0,0 @@
<?php
namespace SilverStripe\Core\Tests\Manifest;
use SilverStripe\Core\Manifest\ConfigStaticManifest;
use SilverStripe\Dev\SapphireTest;
class ConfigStaticManifestTest extends SapphireTest
{
private static $testString = 'string';
private static $testArray = array('foo' => 'bar');
protected static $ignored = true;
public function testGet()
{
$manifest = new ConfigStaticManifest();
// Test madeup value
$this->assertNull($manifest->get(__CLASS__, 'madeup', null));
// Test string value
$this->assertEquals('string', $manifest->get(__CLASS__, 'testString'));
// Test array value
$this->assertEquals(array('foo' => 'bar'), $manifest->get(__CLASS__, 'testArray'));
// Test to ensure we're only picking up private statics
$this->assertNull($manifest->get(__CLASS__, 'ignored', null));
// Test madeup class
if (!class_exists('aonsffgrgx')) {
$this->assertNull($manifest->get('aonsffgrgx', 'madeup', null));
}
}
}

View File

@ -263,8 +263,8 @@ class NamespacedClassManifestTest extends SapphireTest
'silverstripe\test\classf' => "{$this->base}/module/classes/ClassF.php",
'silverstripe\test\classg' => "{$this->base}/module/classes/ClassG.php",
'silverstripe\test\classh' => "{$this->base}/module/classes/ClassH.php",
'sstemplateparser' => FRAMEWORK_PATH."/View/SSTemplateParser.php",
'sstemplateparseexception' => FRAMEWORK_PATH."/View/SSTemplateParseException.php",
'sstemplateparser' => FRAMEWORK_PATH."/src/View/SSTemplateParser.php",
'sstemplateparseexception' => FRAMEWORK_PATH."/src/View/SSTemplateParseException.php",
'silverstripe\framework\tests\classi' => "{$this->base}/module/classes/ClassI.php",
);

View File

@ -1,69 +1,79 @@
---
Only:
ENVORCONSTANTMATCHESVALUE_FOO: Foo
envorconstant:
CONSTANTMATCHESVALUE_FOO: Foo
---
SilverStripe\Core\Tests\Manifest\ConfigManifestTest:
EnvOrConstantMatchesValue:
FooIsFoo: Yes
---
Only:
ENVORCONSTANTMATCHESVALUE_FOO: Qux
envorconstant:
CONSTANTMATCHESVALUE_FOO: 'Qux'
---
SilverStripe\Core\Tests\Manifest\ConfigManifestTest:
EnvOrConstantMatchesValue:
FooIsQux: Yes
---
Only:
ENVORCONSTANTMATCHESVALUE_BAR: Bar
envorconstant:
CONSTANTMATCHESVALUE_BAR: Bar
---
SilverStripe\Core\Tests\Manifest\ConfigManifestTest:
EnvOrConstantMatchesValue:
BarIsBar: Yes
---
Only:
ENVORCONSTANTMATCHESVALUE_BAR: Qux
envorconstant:
CONSTANTMATCHESVALUE_BAR: Qux
---
SilverStripe\Core\Tests\Manifest\ConfigManifestTest:
EnvOrConstantMatchesValue:
BarIsQux: Yes
---
Only:
ENVORCONSTANTMATCHESVALUE_Baz: Baz
envorconstant:
CONSTANTMATCHESVALUE_Baz: Baz
---
SilverStripe\Core\Tests\Manifest\ConfigManifestTest:
EnvOrConstantMatchesValue:
BazIsBaz: Yes
---
Except:
ENVORCONSTANTMATCHESVALUE_FOO: Foo
envorconstant:
CONSTANTMATCHESVALUE_FOO: Foo
---
SilverStripe\Core\Tests\Manifest\ConfigManifestTest:
EnvOrConstantMatchesValue:
FooIsFoo: No
---
Except:
ENVORCONSTANTMATCHESVALUE_FOO: Qux
envorconstant:
CONSTANTMATCHESVALUE_FOO: Qux
---
SilverStripe\Core\Tests\Manifest\ConfigManifestTest:
EnvOrConstantMatchesValue:
FooIsQux: No
---
Except:
ENVORCONSTANTMATCHESVALUE_BAR: Bar
envorconstant:
CONSTANTMATCHESVALUE_BAR: Bar
---
SilverStripe\Core\Tests\Manifest\ConfigManifestTest:
EnvOrConstantMatchesValue:
BarIsBar: No
---
Except:
ENVORCONSTANTMATCHESVALUE_BAR: Qux
envorconstant:
CONSTANTMATCHESVALUE_BAR: Qux
---
SilverStripe\Core\Tests\Manifest\ConfigManifestTest:
EnvOrConstantMatchesValue:
BarIsQux: No
---
Except:
ENVORCONSTANTMATCHESVALUE_Baz: Baz
envorconstant:
CONSTANTMATCHESVALUE_Baz: Baz
---
SilverStripe\Core\Tests\Manifest\ConfigManifestTest:
EnvOrConstantMatchesValue:

View File

@ -1,6 +1,6 @@
<?php
use SilverStripe\Core\Config\Config;
use SilverStripe\Control\Director;
// Dynamically change environment
Config::inst()->update('SilverStripe\\Control\\Director', 'environment_type', 'dev');
Director::set_environment_type('dev');

View File

@ -49,22 +49,25 @@ class MemoryLimitTest extends SapphireTest
return;
}
set_time_limit(6000);
// Can't change time limit
if (!set_time_limit(6000)) {
return;
}
// It can go up
increase_time_limit_to(7000);
$this->assertTrue(increase_time_limit_to(7000));
$this->assertEquals(7000, ini_get('max_execution_time'));
// But not down
increase_time_limit_to(5000);
$this->assertTrue(increase_time_limit_to(5000));
$this->assertEquals(7000, ini_get('max_execution_time'));
// 0/nothing means infinity
increase_time_limit_to();
$this->assertTrue(increase_time_limit_to());
$this->assertEquals(0, ini_get('max_execution_time'));
// Can't go down from there
increase_time_limit_to(10000);
$this->assertTrue(increase_time_limit_to(10000));
$this->assertEquals(0, ini_get('max_execution_time'));
}
@ -82,6 +85,7 @@ class MemoryLimitTest extends SapphireTest
set_increase_memory_limit_max(-1);
set_increase_time_limit_max(-1);
}
public function tearDown()
{
ini_set('memory_limit', $this->origMemLimit);

View File

@ -209,13 +209,13 @@ class AssetFieldTest extends FunctionalTest
switch ($name) {
case 'File[Filename]':
$tuple['Filename'] = $value;
break;
break;
case 'File[Hash]':
$tuple['Hash'] = $value;
break;
break;
case 'File[Variant]':
$tuple['Variant'] = $value;
break;
break;
}
}

View File

@ -2,6 +2,7 @@
namespace SilverStripe\Forms\Tests\GridField;
use SilverStripe\Dev\Debug;
use SilverStripe\Forms\Tests\GridField\GridFieldAddExistingAutocompleterTest\TestController;
use SilverStripe\Forms\Tests\GridField\GridFieldTest\Cheerleader;
use SilverStripe\Forms\Tests\GridField\GridFieldTest\Permissions;
@ -29,22 +30,20 @@ class GridFieldAddExistingAutocompleterTest extends FunctionalTest
TestController::class
];
function testScaffoldSearchFields()
public function testScaffoldSearchFields()
{
$autoCompleter = new GridFieldAddExistingAutocompleter($targetFragment = 'before', array('Test'));
$this->assertEquals(
$autoCompleter->scaffoldSearchFields(Team::class),
array(
'Name:PartialMatch',
'City:StartsWith',
'Cheerleaders.Name:StartsWith'
)
),
$autoCompleter->scaffoldSearchFields(Team::class)
);
$this->assertEquals(
$autoCompleter->scaffoldSearchFields(Cheerleader::class),
array(
'Name:StartsWith'
)
[ 'Name:StartsWith' ],
$autoCompleter->scaffoldSearchFields(Cheerleader::class)
);
}

View File

@ -28,23 +28,19 @@ class HTMLEditorFieldToolbarTest extends SapphireTest
{
parent::setUp();
HTMLEditorField_Toolbar::config()->update('fileurl_scheme_whitelist', array('http'));
HTMLEditorField_Toolbar::config()->update('fileurl_domain_whitelist', array('example.com'));
HTMLEditorField_Toolbar::config()->set('fileurl_scheme_whitelist', array('http'));
HTMLEditorField_Toolbar::config()->set('fileurl_domain_whitelist', array('example.com'));
// Filesystem mock
TestAssetStore::activate(__CLASS__);
// Load up files
/**
* @var File $file1
*/
/** @var File $file1 */
$file1 = $this->objFromFixture(File::class, 'example_file');
$file1->setFromString(str_repeat('x', 1000), $file1->Name);
$file1->write();
/**
* @var Image $image1
*/
/** @var Image $image1 */
$image1 = $this->objFromFixture(Image::class, 'example_image');
$image1->setFromLocalFile(
__DIR__ . '/HTMLEditorFieldTest/images/example.jpg',
@ -55,48 +51,42 @@ class HTMLEditorFieldToolbarTest extends SapphireTest
public function testValidLocalReference()
{
/**
* @var File $exampleFile
*/
/** @var File $exampleFile */
$exampleFile = $this->objFromFixture(File::class, 'example_file');
$expectedUrl = $exampleFile->AbsoluteLink();
HTMLEditorField_Toolbar::config()->update(
HTMLEditorField_Toolbar::config()->set(
'fileurl_domain_whitelist',
array(
'example.com',
strtolower(parse_url($expectedUrl, PHP_URL_HOST))
)
[
'example.com',
strtolower(parse_url($expectedUrl, PHP_URL_HOST))
]
);
list($file, $url) = $this->getToolbar()->viewfile_getRemoteFileByURL($exampleFile->AbsoluteLink());
list(, $url) = $this->getToolbar()->viewfile_getRemoteFileByURL($exampleFile->AbsoluteLink());
$this->assertEquals($expectedUrl, $url);
}
public function testValidScheme()
{
list($file, $url) = $this->getToolbar()->viewfile_getRemoteFileByURL('http://example.com/test.pdf');
list(, $url) = $this->getToolbar()->viewfile_getRemoteFileByURL('http://example.com/test.pdf');
$this->assertEquals($url, 'http://example.com/test.pdf');
}
/**
* @expectedException SilverStripe\Control\HTTPResponse_Exception
*/
public function testInvalidScheme()
{
list($file, $url) = $this->getToolbar()->viewfile_getRemoteFileByURL('nosuchscheme://example.com/test.pdf');
$this->setExpectedException(HTTPResponse_Exception::class);
$this->getToolbar()->viewfile_getRemoteFileByURL('nosuchscheme://example.com/test.pdf');
}
public function testValidDomain()
{
list($file, $url) = $this->getToolbar()->viewfile_getRemoteFileByURL('http://example.com/test.pdf');
list(, $url) = $this->getToolbar()->viewfile_getRemoteFileByURL('http://example.com/test.pdf');
$this->assertEquals($url, 'http://example.com/test.pdf');
}
/**
* @expectedException SilverStripe\Control\HTTPResponse_Exception
*/
public function testInvalidDomain()
{
list($file, $url) = $this->getToolbar()->viewfile_getRemoteFileByURL('http://evil.com/test.pdf');
$this->setExpectedException(HTTPResponse_Exception::class);
$this->getToolbar()->viewfile_getRemoteFileByURL('http://evil.com/test.pdf');
}
}

View File

@ -14,16 +14,16 @@ class DBTest extends SapphireTest
$prefix = getenv('SS_DATABASE_PREFIX') ?: 'ss_';
Director::config()->update('environment_type', 'dev');
Director::set_environment_type('dev');
$this->assertTrue(DB::valid_alternative_database_name($prefix.'tmpdb1234567'));
$this->assertFalse(DB::valid_alternative_database_name($prefix.'tmpdb12345678'));
$this->assertFalse(DB::valid_alternative_database_name('tmpdb1234567'));
$this->assertFalse(DB::valid_alternative_database_name('random'));
$this->assertFalse(DB::valid_alternative_database_name(''));
Director::config()->update('environment_type', 'live');
Director::set_environment_type('live');
$this->assertFalse(DB::valid_alternative_database_name($prefix.'tmpdb1234567'));
Director::config()->update('environment_type', 'dev');
Director::set_environment_type('dev');
}
}

View File

@ -2,10 +2,13 @@
namespace SilverStripe\ORM\Tests;
use SilverStripe\Assets\Tests\FileMigrationHelperTest\Extension;
use SilverStripe\Core\Config\Middleware\ExtensionMiddleware;
use SilverStripe\Dev\Debug;
use SilverStripe\ORM\DataObject;
use SilverStripe\Core\Config\Config;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\Tests\DataExtensionTest\TestMember;
use SilverStripe\ORM\DB;
use SilverStripe\Security\Member;
class DataExtensionTest extends SapphireTest
@ -127,13 +130,11 @@ class DataExtensionTest extends SapphireTest
// Pull the record out of the DB and examine the extended fields
$player = DataObject::get_one(
DataExtensionTest\Player::class,
array(
'"DataExtensionTest_Player"."Name"' => 'Joe'
)
[ '"DataExtensionTest_Player"."Name"' => 'Joe' ]
);
$this->assertEquals($player->DateBirth, '1990-05-10');
$this->assertEquals($player->Address, '123 somewhere street');
$this->assertEquals($player->Status, 'Goalie');
$this->assertEquals('1990-05-10', $player->DateBirth);
$this->assertEquals('123 somewhere street', $player->Address);
$this->assertEquals('Goalie', $player->Status);
}
/**
@ -141,7 +142,10 @@ class DataExtensionTest extends SapphireTest
*/
public function testApiAccessCanBeExtended()
{
$this->assertTrue(Config::inst()->get(DataExtensionTest\TestMember::class, 'api_access', Config::FIRST_SET));
$this->assertTrue(Config::inst()->get(
DataExtensionTest\TestMember::class,
'api_access'
));
}
public function testPermissionExtension()

View File

@ -4,12 +4,9 @@ namespace SilverStripe\ORM\Tests\DataExtensionTest;
use SilverStripe\Dev\TestOnly;
use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\Tests\DataExtensionTest\RelatedObject;
class ContactRole extends DataExtension implements TestOnly
{
private static $table_name = 'DataExtensionTest_ContactRole';
private static $db = array(
'Website' => 'Varchar',
'Phone' => 'Varchar(255)',

View File

@ -4,7 +4,6 @@ namespace SilverStripe\ORM\Tests\DataExtensionTest;
use SilverStripe\Dev\TestOnly;
use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\Tests\DataExtensionTest\Player;
class PlayerExtension extends DataExtension implements TestOnly
{
@ -15,7 +14,7 @@ class PlayerExtension extends DataExtension implements TestOnly
// Only add these extensions if the $class is set to DataExtensionTest_Player, to
// test that the argument works.
if ($class == Player::class) {
if (strcasecmp($class, Player::class) === 0) {
$config['db'] = array(
'Address' => 'Text',
'DateBirth' => 'Date',

View File

@ -147,9 +147,7 @@ class DataObjectSchemaGenerationTest extends SapphireTest
// Test with alternate index format, although these indexes are the same
$config = TestIndexObject::config();
$config
->remove('indexes')
->update('indexes', $config->get('indexes_alt'));
$config->set('indexes', $config->get('indexes_alt'));
// Verify that it still doesn't need to be recreated
$schema->schemaUpdate(

View File

@ -1377,21 +1377,21 @@ class DataObjectTest extends SapphireTest
public function testValidateModelDefinitionsFailsWithArray()
{
Config::inst()->update(DataObjectTest\Team::class, 'has_one', array('NotValid' => array('NoArraysAllowed')));
Config::modify()->merge(DataObjectTest\Team::class, 'has_one', array('NotValid' => array('NoArraysAllowed')));
$this->setExpectedException(InvalidArgumentException::class);
DataObject::getSchema()->hasOneComponent(DataObjectTest\Team::class, 'NotValid');
}
public function testValidateModelDefinitionsFailsWithIntKey()
{
Config::inst()->update(DataObjectTest\Team::class, 'has_many', array(12 => DataObjectTest\Player::class));
Config::modify()->set(DataObjectTest\Team::class, 'has_many', array(0 => DataObjectTest\Player::class));
$this->setExpectedException(InvalidArgumentException::class);
DataObject::getSchema()->hasManyComponent(DataObjectTest\Team::class, 12);
DataObject::getSchema()->hasManyComponent(DataObjectTest\Team::class, 0);
}
public function testValidateModelDefinitionsFailsWithIntValue()
{
Config::inst()->update(DataObjectTest\Team::class, 'many_many', array('Players' => 12));
Config::modify()->merge(DataObjectTest\Team::class, 'many_many', array('Players' => 12));
$this->setExpectedException(InvalidArgumentException::class);
DataObject::getSchema()->manyManyComponent(DataObjectTest\Team::class, 'Players');
}
@ -1460,7 +1460,7 @@ class DataObjectTest extends SapphireTest
// Check everything works when no relation is present
$teamWithoutSponsor = $this->objFromFixture(DataObjectTest\Team::class, 'team3');
$this->assertInstanceOf('SilverStripe\\ORM\\ManyManyList', $teamWithoutSponsor->Sponsors());
$this->assertInstanceOf(ManyManyList::class, $teamWithoutSponsor->Sponsors());
$this->assertEquals(0, $teamWithoutSponsor->Sponsors()->count());
// Test that belongs_many_many can be infered from with getNonReciprocalComponent

View File

@ -4,7 +4,23 @@ namespace SilverStripe\ORM\Tests\DataObjectTest;
use SilverStripe\Dev\TestOnly;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\HasManyList;
use SilverStripe\ORM\ManyManyList;
/**
* @property string Title
* @property string DatabaseField
* @method Player Captain()
* @method Player Founder()
* @method Player HasOneRelationship()
* @method HasManyList SubTeams()
* @method HasManyList Comments()
* @method HasManyList Fans()
* @method HasManyList PlayerFans()
* @method ManyManyList Players()
* @method ManyManyList Sponsors()
* @method ManyManyList EquipmentSuppliers()
*/
class Team extends DataObject implements TestOnly
{
private static $table_name = 'DataObjectTest_Team';

View File

@ -26,7 +26,6 @@ class MemberTest extends FunctionalTest
protected static $fixture_file = 'MemberTest.yml';
protected $orig = array();
protected $local = null;
protected $illegalExtensions = array(
Member::class => array(
@ -44,13 +43,7 @@ class MemberTest extends FunctionalTest
//Setting the locale has to happen in the constructor (using the setUp and tearDown methods doesn't work)
//This is because the test relies on the yaml file being interpreted according to a particular date format
//and this setup occurs before the setUp method is run
$this->local = i18n::config()->get('default_locale');
i18n::config()->update('default_locale', 'en_US');
}
public function __destruct()
{
i18n::config()->update('default_locale', $this->local);
i18n::config()->set('default_locale', 'en_US');
}
/**

View File

@ -12,29 +12,15 @@ use SilverStripe\Security\Tests\PasswordEncryptorTest\TestEncryptor;
class PasswordEncryptorTest extends SapphireTest
{
/**
*
* @var Config
*/
private $config = null;
public function setUp()
{
parent::setUp();
$this->config = clone(Config::inst());
}
public function tearDown()
{
parent::tearDown();
Config::set_instance($this->config);
PasswordEncryptor_Blowfish::set_cost(10);
}
public function testCreateForCode()
{
Config::inst()->update(
Config::modify()->merge(
PasswordEncryptor::class,
'encryptors',
['test' => [TestEncryptor::class => null]]
@ -53,7 +39,7 @@ class PasswordEncryptorTest extends SapphireTest
public function testRegister()
{
Config::inst()->update(
Config::modify()->merge(
PasswordEncryptor::class,
'encryptors',
array('test' => array(TestEncryptor::class => null))
@ -64,31 +50,21 @@ class PasswordEncryptorTest extends SapphireTest
$this->assertContains(TestEncryptor::class, key($encryptor));
}
public function testUnregister()
{
Config::inst()->update(
PasswordEncryptor::class,
'encryptors',
array('test' => array(TestEncryptor::class => null))
);
Config::inst()->remove(PasswordEncryptor::class, 'encryptors', 'test');
$this->assertNotContains('test', array_keys(PasswordEncryptor::get_encryptors()));
}
public function testEncryptorPHPHashWithArguments()
{
Config::inst()->update(
Config::modify()->merge(
PasswordEncryptor::class,
'encryptors',
['test_md5' => [PasswordEncryptor_PHPHash::class=>'md5']]
);
/** @var PasswordEncryptor_PHPHash $e */
$e = PasswordEncryptor::create_for_algorithm('test_md5');
$this->assertEquals('md5', $e->getAlgorithm());
}
public function testEncryptorPHPHash()
{
Config::inst()->update(
Config::modify()->merge(
PasswordEncryptor::class,
'encryptors',
['test_sha1' => [PasswordEncryptor_PHPHash::class => 'sha1']]
@ -104,11 +80,12 @@ class PasswordEncryptorTest extends SapphireTest
public function testEncryptorBlowfish()
{
Config::inst()->update(
Config::modify()->merge(
PasswordEncryptor::class,
'encryptors',
['test_blowfish' => [PasswordEncryptor_Blowfish::class => '']]
);
/** @var PasswordEncryptor_Blowfish $e */
$e = PasswordEncryptor::create_for_algorithm('test_blowfish');
$password = 'mypassword';
@ -156,7 +133,7 @@ class PasswordEncryptorTest extends SapphireTest
public function testEncryptorPHPHashCheck()
{
Config::inst()->update(
Config::modify()->merge(
PasswordEncryptor::class,
'encryptors',
['test_sha1' => [PasswordEncryptor_PHPHash::class => 'sha1']]
@ -174,7 +151,7 @@ class PasswordEncryptorTest extends SapphireTest
*/
public function testEncryptorLegacyPHPHashCheck()
{
Config::inst()->update(
Config::modify()->merge(
PasswordEncryptor::class,
'encryptors',
['test_sha1legacy' => [PasswordEncryptor_LegacyPHPHash::class => 'sha1']]

View File

@ -1087,11 +1087,11 @@ EOS
$type = strtolower($type);
switch (strtolower($type)) {
case 'css':
return $backend->getCSS();
return $backend->getCSS();
case 'js':
case 'javascript':
case 'script':
return $backend->getJavascript();
return $backend->getJavascript();
}
return array();
}

View File

@ -68,11 +68,10 @@ class SSViewerTest extends SapphireTest
*/
public function testCurrentTheme()
{
//TODO: SiteConfig moved to CMS
SSViewer::config()->update('theme', 'mytheme');
$this->assertEquals(
'mytheme',
SSViewer::config()->get('theme'),
SSViewer::config()->uninherited('theme'),
'Current theme is the default - user has not defined one'
);
}
@ -1730,7 +1729,7 @@ EOC;
public function testRenderWithSourceFileComments()
{
Director::config()->update('environment_type', 'dev');
Director::set_environment_type('dev');
SSViewer::config()->update('source_file_comments', true);
$i = __DIR__ . '/SSViewerTest/templates/Includes';
$f = __DIR__ . '/SSViewerTest/templates/SSViewerTestComments';