Merge pull request #8408 from dhensby/pulls/4/test-cleanup

Test cleanup
This commit is contained in:
Robbie Averill 2018-10-03 13:28:59 +02:00 committed by GitHub
commit d1f30a20c2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 188 additions and 200 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
/assets/
.sass-cache .sass-cache
.DS_Store .DS_Store
npm-debug.log npm-debug.log

View File

@ -2,7 +2,6 @@
namespace SilverStripe\Control\Tests; namespace SilverStripe\Control\Tests;
use InvalidArgumentException;
use SilverStripe\Control\Controller; use SilverStripe\Control\Controller;
use SilverStripe\Control\Director; use SilverStripe\Control\Director;
use SilverStripe\Control\Tests\ControllerTest\AccessBaseController; use SilverStripe\Control\Tests\ControllerTest\AccessBaseController;
@ -15,10 +14,8 @@ use SilverStripe\Control\Tests\ControllerTest\IndexSecuredController;
use SilverStripe\Control\Tests\ControllerTest\SubController; use SilverStripe\Control\Tests\ControllerTest\SubController;
use SilverStripe\Control\Tests\ControllerTest\TestController; use SilverStripe\Control\Tests\ControllerTest\TestController;
use SilverStripe\Control\Tests\ControllerTest\UnsecuredController; use SilverStripe\Control\Tests\ControllerTest\UnsecuredController;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Dev\FunctionalTest; use SilverStripe\Dev\FunctionalTest;
use SilverStripe\Security\Member; use SilverStripe\Security\Member;
use SilverStripe\Security\Security;
use SilverStripe\View\SSViewer; use SilverStripe\View\SSViewer;
class ControllerTest extends FunctionalTest class ControllerTest extends FunctionalTest
@ -47,28 +44,21 @@ class ControllerTest extends FunctionalTest
{ {
parent::setUp(); parent::setUp();
Director::config()->update('alternate_base_url', '/'); Director::config()->update('alternate_base_url', '/');
$this->depSettings = Deprecation::dump_settings();
// Add test theme // Add test theme
$themeDir = substr(__DIR__, strlen(FRAMEWORK_DIR)) . '/ControllerTest/'; $themeDir = substr(__DIR__, strlen(FRAMEWORK_DIR)) . '/ControllerTest/';
$themes = [ $themes = [
"silverstripe/framework:{$themeDir}", "silverstripe/framework:{$themeDir}",
SSViewer::DEFAULT_THEME SSViewer::DEFAULT_THEME,
]; ];
SSViewer::set_themes($themes); SSViewer::set_themes($themes);
} }
protected function tearDown()
{
Deprecation::restore_settings($this->depSettings);
parent::tearDown();
}
public function testDefaultAction() public function testDefaultAction()
{ {
/* For a controller with a template, the default action will simple run that template. */ /* For a controller with a template, the default action will simple run that template. */
$response = $this->get("TestController/"); $response = $this->get("TestController/");
$this->assertRegExp("/This is the main template. Content is 'default content'/", $response->getBody()); $this->assertContains("This is the main template. Content is 'default content'", $response->getBody());
} }
public function testMethodActions() public function testMethodActions()
@ -76,19 +66,19 @@ class ControllerTest extends FunctionalTest
/* The Action can refer to a method that is called on the object. If a method returns an array, then it /* The Action can refer to a method that is called on the object. If a method returns an array, then it
* will be used to customise the template data */ * will be used to customise the template data */
$response = $this->get("TestController/methodaction"); $response = $this->get("TestController/methodaction");
$this->assertRegExp("/This is the main template. Content is 'methodaction content'./", $response->getBody()); $this->assertContains("This is the main template. Content is 'methodaction content'.", $response->getBody());
/* If the method just returns a string, then that will be used as the response */ /* If the method just returns a string, then that will be used as the response */
$response = $this->get("TestController/stringaction"); $response = $this->get("TestController/stringaction");
$this->assertRegExp("/stringaction was called./", $response->getBody()); $this->assertContains("stringaction was called.", $response->getBody());
} }
public function testTemplateActions() public function testTemplateActions()
{ {
/* If there is no method, it can be used to point to an alternative template. */ /* If there is no method, it can be used to point to an alternative template. */
$response = $this->get("TestController/templateaction"); $response = $this->get("TestController/templateaction");
$this->assertRegExp( $this->assertContains(
"/This is the template for templateaction. Content is 'default content'./", "This is the template for templateaction. Content is 'default content'.",
$response->getBody() $response->getBody()
); );
} }
@ -188,15 +178,15 @@ class ControllerTest extends FunctionalTest
'Access denied on action with $allowed_actions on defining controller, ' . 'if action is not a method but rather a template discovered by naming convention' 'Access denied on action with $allowed_actions on defining controller, ' . 'if action is not a method but rather a template discovered by naming convention'
); );
Security::setCurrentUser($adminUser); Member::actAs($adminUser, function () {
$response = $this->get("AccessSecuredController/templateaction"); $response = $this->get("AccessSecuredController/templateaction");
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
'Access granted for logged in admin on action with $allowed_actions on defining controller, ' . 'if action is not a method but rather a template discovered by naming convention' 'Access granted for logged in admin on action with $allowed_actions on defining controller, ' . 'if action is not a method but rather a template discovered by naming convention'
); );
});
Security::setCurrentUser(null);
$response = $this->get("AccessSecuredController/adminonly"); $response = $this->get("AccessSecuredController/adminonly");
$this->assertEquals( $this->assertEquals(
403, 403,
@ -218,15 +208,15 @@ class ControllerTest extends FunctionalTest
"Access denied to protected method even if its listed in allowed_actions" "Access denied to protected method even if its listed in allowed_actions"
); );
Security::setCurrentUser($adminUser); Member::actAs($adminUser, function () {
$response = $this->get("AccessSecuredController/adminonly"); $response = $this->get("AccessSecuredController/adminonly");
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
"Permission codes are respected when set in \$allowed_actions" "Permission codes are respected when set in \$allowed_actions"
); );
});
Security::setCurrentUser(null);
$response = $this->get('AccessBaseController/extensionmethod1'); $response = $this->get('AccessBaseController/extensionmethod1');
$this->assertEquals( $this->assertEquals(
200, 200,
@ -262,14 +252,14 @@ class ControllerTest extends FunctionalTest
"Access denied when index action is limited through allowed_actions, " . "and doesn't satisfy checks" "Access denied when index action is limited through allowed_actions, " . "and doesn't satisfy checks"
); );
Security::setCurrentUser($adminUser); Member::actAs($adminUser, function () {
$response = $this->get('IndexSecuredController/'); $response = $this->get('IndexSecuredController/');
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
"Access granted when index action is limited through allowed_actions, " . "and does satisfy checks" "Access granted when index action is limited through allowed_actions, " . "and does satisfy checks"
); );
Security::setCurrentUser(null); });
} }
/** /**
@ -417,14 +407,6 @@ 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::modify()->merge('Director', 'alternate_base_url', '/baseurl/');
$this->assertEquals(Controller::BaseURL(), Director::BaseURL());
}
*/
public function testRedirectBackByReferer() public function testRedirectBackByReferer()
{ {
$internalRelativeUrl = Controller::join_links(Director::baseURL(), '/some-url'); $internalRelativeUrl = Controller::join_links(Director::baseURL(), '/some-url');

View File

@ -66,7 +66,7 @@ class CookieJarTest extends SapphireTest
//PHP will replace an incoming COOKIE called 'var.with.dots' to 'var_with_dots' //PHP will replace an incoming COOKIE called 'var.with.dots' to 'var_with_dots'
$cookieJar = new CookieJar( $cookieJar = new CookieJar(
array( array(
'var_with_dots' => 'value', 'var_with_dots' => 'value',
) )
); );
@ -87,7 +87,7 @@ class CookieJarTest extends SapphireTest
//load with a cookie //load with a cookie
$cookieJar = new CookieJar( $cookieJar = new CookieJar(
array( array(
'cookieExisting' => 'i woz here', 'cookieExisting' => 'i woz here',
) )
); );
@ -110,8 +110,8 @@ class CookieJarTest extends SapphireTest
//check we can get all cookies //check we can get all cookies
$this->assertEquals( $this->assertEquals(
array( array(
'cookieExisting' => 'i woz changed', 'cookieExisting' => 'i woz changed',
'cookieNew' => 'i am new', 'cookieNew' => 'i am new',
), ),
$cookieJar->getAll() $cookieJar->getAll()
); );
@ -119,7 +119,7 @@ class CookieJarTest extends SapphireTest
//check we can get all original cookies //check we can get all original cookies
$this->assertEquals( $this->assertEquals(
array( array(
'cookieExisting' => 'i woz here', 'cookieExisting' => 'i woz here',
), ),
$cookieJar->getAll(false) $cookieJar->getAll(false)
); );
@ -133,7 +133,7 @@ class CookieJarTest extends SapphireTest
//load an existing cookie //load an existing cookie
$cookieJar = new CookieJar( $cookieJar = new CookieJar(
array( array(
'cookieExisting' => 'i woz here', 'cookieExisting' => 'i woz here',
) )
); );

View File

@ -10,22 +10,12 @@ use SilverStripe\Control\Cookie;
class CookieTest extends SapphireTest class CookieTest extends SapphireTest
{ {
private $cookieInst;
protected function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
Injector::nest();
Injector::inst()->registerService(new CookieJar($_COOKIE), 'SilverStripe\\Control\\Cookie_Backend'); Injector::inst()->registerService(new CookieJar($_COOKIE), 'SilverStripe\\Control\\Cookie_Backend');
} }
protected function tearDown()
{
//restore the cookie_backend
Injector::unnest();
parent::tearDown();
}
/** /**
* Check a new cookie inst will be loaded with the superglobal by default * Check a new cookie inst will be loaded with the superglobal by default
*/ */
@ -132,7 +122,7 @@ class CookieTest extends SapphireTest
//load with a cookie //load with a cookie
$cookieJar = new CookieJar( $cookieJar = new CookieJar(
array( array(
'cookieExisting' => 'i woz here', 'cookieExisting' => 'i woz here',
) )
); );
Injector::inst()->registerService($cookieJar, 'SilverStripe\\Control\\Cookie_Backend'); Injector::inst()->registerService($cookieJar, 'SilverStripe\\Control\\Cookie_Backend');
@ -156,8 +146,8 @@ class CookieTest extends SapphireTest
//check we can get all cookies //check we can get all cookies
$this->assertEquals( $this->assertEquals(
array( array(
'cookieExisting' => 'i woz changed', 'cookieExisting' => 'i woz changed',
'cookieNew' => 'i am new', 'cookieNew' => 'i am new',
), ),
Cookie::get_all() Cookie::get_all()
); );
@ -165,7 +155,7 @@ class CookieTest extends SapphireTest
//check we can get all original cookies //check we can get all original cookies
$this->assertEquals( $this->assertEquals(
array( array(
'cookieExisting' => 'i woz here', 'cookieExisting' => 'i woz here',
), ),
Cookie::get_all(false) Cookie::get_all(false)
); );
@ -179,7 +169,7 @@ class CookieTest extends SapphireTest
//load an existing cookie //load an existing cookie
$cookieJar = new CookieJar( $cookieJar = new CookieJar(
array( array(
'cookieExisting' => 'i woz here', 'cookieExisting' => 'i woz here',
) )
); );
Injector::inst()->registerService($cookieJar, 'SilverStripe\\Control\\Cookie_Backend'); Injector::inst()->registerService($cookieJar, 'SilverStripe\\Control\\Cookie_Backend');

View File

@ -1,4 +1,5 @@
<?php <?php
namespace SilverStripe\Control\Tests; namespace SilverStripe\Control\Tests;
use SilverStripe\Control\Cookie_Backend; use SilverStripe\Control\Cookie_Backend;
@ -193,24 +194,26 @@ class DirectorTest extends SapphireTest
/** /**
* Tests that {@link Director::is_absolute()} works under different environment types * Tests that {@link Director::is_absolute()} works under different environment types
* @dataProvider provideAbsolutePaths
*/ */
public function testIsAbsolute() public function testIsAbsolute($path, $result)
{ {
$expected = array ( $this->assertEquals($result, Director::is_absolute($path));
'C:/something' => true, }
'd:\\' => true,
'e/' => false,
's:/directory' => true,
'/var/www' => true,
'\\Something' => true,
'something/c:' => false,
'folder' => false,
'a/c:/' => false
);
foreach ($expected as $path => $result) { public function provideAbsolutePaths()
$this->assertEquals(Director::is_absolute($path), $result, "Test result for $path"); {
} return [
['C:/something', true],
['d:\\', true],
['e/', false],
['s:/directory', true],
['/var/www', true],
['\\Something', true],
['something/c:', false],
['folder', false],
['a/c:/', false],
];
} }
public function testIsAbsoluteUrl() public function testIsAbsoluteUrl()
@ -486,7 +489,7 @@ class DirectorTest extends SapphireTest
public function providerTestTestRequestCarriesGlobals() public function providerTestTestRequestCarriesGlobals()
{ {
$tests = []; $tests = [];
$fixture = [ 'somekey' => 'sometestvalue' ]; $fixture = ['somekey' => 'sometestvalue'];
foreach (array('get', 'post') as $method) { foreach (array('get', 'post') as $method) {
foreach (array('return%sValue', 'returnRequestValue', 'returnCookieValue') as $testfunction) { foreach (array('return%sValue', 'returnRequestValue', 'returnCookieValue') as $testfunction) {
$url = 'TestController/' . sprintf($testfunction, ucfirst($method)) $url = 'TestController/' . sprintf($testfunction, ucfirst($method))
@ -761,7 +764,7 @@ class DirectorTest extends SapphireTest
null, null,
null, null,
null, null,
[ 'X-Forwarded-Protocol' => 'https' ] ['X-Forwarded-Protocol' => 'https']
)->getBody() )->getBody()
); );
@ -773,7 +776,7 @@ class DirectorTest extends SapphireTest
null, null,
null, null,
null, null,
[ 'X-Forwarded-Protocol' => 'http' ] ['X-Forwarded-Protocol' => 'http']
)->getBody() )->getBody()
); );
@ -785,7 +788,7 @@ class DirectorTest extends SapphireTest
null, null,
null, null,
null, null,
[ 'X-Forwarded-Protocol' => 'ftp' ] ['X-Forwarded-Protocol' => 'ftp']
)->getBody() )->getBody()
); );
@ -925,7 +928,7 @@ class DirectorTest extends SapphireTest
// Global middleware // Global middleware
$middleware = new DirectorTest\TestMiddleware; $middleware = new DirectorTest\TestMiddleware;
Director::singleton()->setMiddlewares([ $middleware ]); Director::singleton()->setMiddlewares([$middleware]);
// URL rules, one of which has a specific middleware // URL rules, one of which has a specific middleware
Config::modify()->set( Config::modify()->set(

View File

@ -58,18 +58,34 @@ class EmailTest extends SapphireTest
$this->assertEquals('foo.txt', $child->getFilename()); $this->assertEquals('foo.txt', $child->getFilename());
} }
public function testValidEmailAddress() /**
* @dataProvider provideValidEmailAddresses
*/
public function testValidEmailAddress($email)
{ {
$validEmails = array('test@example.com', 'test-123@example.sub.com'); $this->assertTrue(Email::is_valid_address($email));
$invalidEmails = array('foo.bar@', '@example.com', 'foo@'); }
foreach ($validEmails as $email) { /**
$this->assertTrue(Email::is_valid_address($email)); * @dataProvider provideInvalidEmailAddresses
} */
public function testInvalidEmailAddress($email)
{
$this->assertFalse(Email::is_valid_address($email));
}
foreach ($invalidEmails as $email) { public function provideValidEmailAddresses()
$this->assertFalse(Email::is_valid_address($email)); {
} return [
['test@example.com', 'test-123@sub.example.com'],
];
}
public function provideInvalidEmailAddresses()
{
return [
['foo.bar@', '@example.com', 'foo@'],
];
} }
public function testObfuscate() public function testObfuscate()

View File

@ -28,9 +28,9 @@ class SwiftMailerTest extends SapphireTest
$transport $transport
->expects($this->once()) ->expects($this->once())
->method('registerPlugin') ->method('registerPlugin')
->willReturnCallback(function ($plugin) { ->with(
$this->assertInstanceOf(Swift_Plugins_AntiFloodPlugin::class, $plugin); $this->isInstanceOf(Swift_Plugins_AntiFloodPlugin::class)
}); );
/** @var Swift_Mailer $swift */ /** @var Swift_Mailer $swift */
$swift = $this->getMockBuilder(Swift_Mailer::class)->disableOriginalConstructor()->getMock(); $swift = $this->getMockBuilder(Swift_Mailer::class)->disableOriginalConstructor()->getMock();
@ -54,9 +54,9 @@ class SwiftMailerTest extends SapphireTest
$mailer = $this->getMockBuilder(SwiftMailer::class) $mailer = $this->getMockBuilder(SwiftMailer::class)
->setMethods(array('sendSwift')) ->setMethods(array('sendSwift'))
->getMock(); ->getMock();
$mailer->expects($this->once())->method('sendSwift')->willReturnCallback(function ($message) { $mailer->expects($this->once())->method('sendSwift')->with(
$this->assertInstanceOf(Swift_Message::class, $message); $this->isInstanceOf(Swift_Message::class)
}); );
$mailer->send($email); $mailer->send($email);
} }

View File

@ -23,29 +23,17 @@ class HTTPResponseTest extends SapphireTest
$response = new HTTPResponse("Test", 200, 'OK'); $response = new HTTPResponse("Test", 200, 'OK');
// Confirm that the exception's statusCode and statusDescription take precedence // Confirm that the exception's statusCode and statusDescription take precedence
try { $e = new HTTPResponse_Exception($response, 404, 'not even found');
throw new HTTPResponse_Exception($response, 404, 'not even found'); $this->assertEquals(404, $e->getResponse()->getStatusCode());
} catch (HTTPResponse_Exception $e) { $this->assertEquals('not even found', $e->getResponse()->getStatusDescription());
$this->assertEquals(404, $e->getResponse()->getStatusCode());
$this->assertEquals('not even found', $e->getResponse()->getStatusDescription());
return;
}
// Fail if we get to here
$this->assertFalse(true, 'Something went wrong with our test exception');
} }
public function testExceptionContentPlainByDefault() public function testExceptionContentPlainByDefault()
{ {
// Confirm that the exception's statusCode and statusDescription take precedence // Confirm that the exception's statusCode and statusDescription take precedence
try { $e = new HTTPResponse_Exception("Some content that may be from a hacker", 404, 'not even found');
throw new HTTPResponse_Exception("Some content that may be from a hacker", 404, 'not even found'); $this->assertEquals("text/plain", $e->getResponse()->getHeader("Content-Type"));
} catch (HTTPResponse_Exception $e) {
$this->assertEquals("text/plain", $e->getResponse()->getHeader("Content-Type"));
return;
}
// Fail if we get to here
$this->assertFalse(true, 'Something went wrong with our test exception');
} }
public function testRemoveHeader() public function testRemoveHeader()

View File

@ -219,7 +219,7 @@ class HTTPTest extends FunctionalTest
sort($result); sort($result);
sort($expected); sort($expected);
$this->assertTrue(is_array($result)); $this->assertInternalType('array', $result);
$this->assertEquals($expected, $result, 'Test that all links within the content are found.'); $this->assertEquals($expected, $result, 'Test that all links within the content are found.');
} }
@ -459,7 +459,7 @@ class HTTPTest extends FunctionalTest
{ {
$this->withBaseURL( $this->withBaseURL(
'http://www.silverstripe.org/', 'http://www.silverstripe.org/',
function ($test) { function () {
$frameworkTests = ltrim(FRAMEWORK_DIR . '/tests', '/'); $frameworkTests = ltrim(FRAMEWORK_DIR . '/tests', '/');
$this->assertEquals( $this->assertEquals(
"http://www.silverstripe.org/$frameworkTests/php/Control/HTTPTest.php", "http://www.silverstripe.org/$frameworkTests/php/Control/HTTPTest.php",
@ -483,7 +483,7 @@ class HTTPTest extends FunctionalTest
// Run middleware // Run middleware
HTTPCacheControlMiddleware::singleton() HTTPCacheControlMiddleware::singleton()
->process($request, function (HTTPRequest $request) use ($response) { ->process($request, function () use ($response) {
return $response; return $response;
}); });
} }

View File

@ -13,11 +13,11 @@ class PjaxResponseNegotiatorTest extends SapphireTest
public function testDefaultCallbacks() public function testDefaultCallbacks()
{ {
$negotiator = new PjaxResponseNegotiator( $negotiator = new PjaxResponseNegotiator(
array( [
'default' => function () { 'default' => function () {
return 'default response'; return 'default response';
}, },
) ]
); );
$request = new HTTPRequest('GET', '/'); // not setting pjax header $request = new HTTPRequest('GET', '/'); // not setting pjax header
$request->setSession(new Session([])); $request->setSession(new Session([]));
@ -28,14 +28,14 @@ class PjaxResponseNegotiatorTest extends SapphireTest
public function testSelectsFragmentByHeader() public function testSelectsFragmentByHeader()
{ {
$negotiator = new PjaxResponseNegotiator( $negotiator = new PjaxResponseNegotiator(
array( [
'default' => function () { 'default' => function () {
return 'default response'; return 'default response';
}, },
'myfragment' => function () { 'myfragment' => function () {
return 'myfragment response'; return 'myfragment response';
}, },
) ]
); );
$request = new HTTPRequest('GET', '/'); $request = new HTTPRequest('GET', '/');
$request->setSession(new Session([])); $request->setSession(new Session([]));
@ -47,17 +47,17 @@ class PjaxResponseNegotiatorTest extends SapphireTest
public function testMultipleFragments() public function testMultipleFragments()
{ {
$negotiator = new PjaxResponseNegotiator( $negotiator = new PjaxResponseNegotiator(
array( [
'default' => function () { 'default' => function () {
return 'default response'; return 'default response';
}, },
'myfragment' => function () { 'myfragment' => function () {
return 'myfragment response'; return 'myfragment response';
}, },
'otherfragment' => function () { 'otherfragment' => function () {
return 'otherfragment response'; return 'otherfragment response';
}, },
) ]
); );
$request = new HTTPRequest('GET', '/'); $request = new HTTPRequest('GET', '/');
$request->setSession(new Session([])); $request->setSession(new Session([]));
@ -74,14 +74,14 @@ class PjaxResponseNegotiatorTest extends SapphireTest
public function testFragmentsOverride() public function testFragmentsOverride()
{ {
$negotiator = new PjaxResponseNegotiator( $negotiator = new PjaxResponseNegotiator(
array( [
'alpha' => function () { 'alpha' => function () {
return 'alpha response'; return 'alpha response';
}, },
'beta' => function () { 'beta' => function () {
return 'beta response'; return 'beta response';
} },
) ]
); );
$request = new HTTPRequest('GET', '/'); $request = new HTTPRequest('GET', '/');
@ -89,7 +89,7 @@ class PjaxResponseNegotiatorTest extends SapphireTest
$request->addHeader('X-Pjax', 'alpha'); $request->addHeader('X-Pjax', 'alpha');
$request->addHeader('Accept', 'application/json'); $request->addHeader('Accept', 'application/json');
$response = $negotiator->setFragmentOverride(array('beta'))->respond($request); $response = $negotiator->setFragmentOverride(['beta'])->respond($request);
$json = json_decode($response->getBody()); $json = json_decode($response->getBody());
$this->assertFalse(isset($json->alpha)); $this->assertFalse(isset($json->alpha));
$this->assertObjectHasAttribute('beta', $json); $this->assertObjectHasAttribute('beta', $json);

View File

@ -3,16 +3,16 @@
namespace SilverStripe\Control\Tests; namespace SilverStripe\Control\Tests;
use SilverStripe\Admin\LeftAndMain; use SilverStripe\Admin\LeftAndMain;
use SilverStripe\ErrorPage\ErrorPageControllerExtension;
use SilverStripe\Control\Controller; use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Control\RequestHandler;
use SilverStripe\Control\Tests\RequestHandlingTest\AllowedController; use SilverStripe\Control\Tests\RequestHandlingTest\AllowedController;
use SilverStripe\Control\Tests\RequestHandlingTest\ControllerFormWithAllowedActions; use SilverStripe\Control\Tests\RequestHandlingTest\ControllerFormWithAllowedActions;
use SilverStripe\Control\Tests\RequestHandlingTest\FieldController; use SilverStripe\Control\Tests\RequestHandlingTest\FieldController;
use SilverStripe\Control\Tests\RequestHandlingTest\FormActionController; use SilverStripe\Control\Tests\RequestHandlingTest\FormActionController;
use SilverStripe\Control\Tests\RequestHandlingTest\TestController; use SilverStripe\Control\Tests\RequestHandlingTest\TestController;
use SilverStripe\Dev\FunctionalTest; use SilverStripe\Dev\FunctionalTest;
use SilverStripe\Control\RequestHandler; use SilverStripe\ErrorPage\ErrorPageControllerExtension;
use SilverStripe\Control\Director;
use SilverStripe\Forms\Form; use SilverStripe\Forms\Form;
use SilverStripe\Security\SecurityToken; use SilverStripe\Security\SecurityToken;
@ -24,25 +24,25 @@ class RequestHandlingTest extends FunctionalTest
{ {
protected static $fixture_file = null; protected static $fixture_file = null;
protected static $illegal_extensions = array( protected static $illegal_extensions = [
// Suppress CMS error page handling // Suppress CMS error page handling
Controller::class => array( Controller::class => [
ErrorPageControllerExtension::class, ErrorPageControllerExtension::class,
), ],
Form::class => array( Form::class => [
ErrorPageControllerExtension::class, ErrorPageControllerExtension::class,
), ],
LeftAndMain::class => array( LeftAndMain::class => [
ErrorPageControllerExtension::class, ErrorPageControllerExtension::class,
), ],
); ];
protected static $extra_controllers = [ protected static $extra_controllers = [
TestController::class, TestController::class,
AllowedController::class, AllowedController::class,
ControllerFormWithAllowedActions::class, ControllerFormWithAllowedActions::class,
FieldController::class, FieldController::class,
FormActionController::class FormActionController::class,
]; ];
public function getExtraRoutes() public function getExtraRoutes()
@ -99,13 +99,16 @@ class RequestHandlingTest extends FunctionalTest
/* In addition, these values are availalbe in $controller->urlParams. This is mainly for backward /* In addition, these values are availalbe in $controller->urlParams. This is mainly for backward
* compatability. */ * compatability. */
$response = Director::test("testGoodBase1/legacymethod/3/4"); $response = Director::test("testGoodBase1/legacymethod/3/4");
$this->assertEquals("\$this->urlParams can be used, for backward compatibility: 3, 4", $response->getBody()); $this->assertEquals(
"\$this->urlParams can be used, for backward compatibility: 3, 4",
$response->getBody()
);
} }
public function testPostRequests() public function testPostRequests()
{ {
/* The HTTP Request handler can trigger special behaviour for GET and POST. */ /* The HTTP Request handler can trigger special behaviour for GET and POST. */
$response = Director::test("testGoodBase1/TestForm", array("MyField" => 3), null, "POST"); $response = Director::test("testGoodBase1/TestForm", ["MyField" => 3], null, "POST");
$this->assertEquals("Form posted", $response->getBody()); $this->assertEquals("Form posted", $response->getBody());
$response = Director::test("testGoodBase1/TestForm"); $response = Director::test("testGoodBase1/TestForm");
@ -120,7 +123,7 @@ class RequestHandlingTest extends FunctionalTest
$this->assertEquals("MyField requested", $response->getBody()); $this->assertEquals("MyField requested", $response->getBody());
/* We can also make a POST request on a form field, which could be used for in-place editing, for example. */ /* We can also make a POST request on a form field, which could be used for in-place editing, for example. */
$response = Director::test("testGoodBase1/TestForm/fields/MyField", array("MyField" => 5)); $response = Director::test("testGoodBase1/TestForm/fields/MyField", ["MyField" => 5]);
$this->assertEquals("MyField posted, update to 5", $response->getBody()); $this->assertEquals("MyField posted, update to 5", $response->getBody());
} }
@ -128,7 +131,7 @@ class RequestHandlingTest extends FunctionalTest
{ {
$this->withBaseFolder( $this->withBaseFolder(
'/silverstripe', '/silverstripe',
function ($test) { function () {
$this->assertEquals( $this->assertEquals(
'MyField requested', 'MyField requested',
Director::test('/silverstripe/testGoodBase1/TestForm/fields/MyField')->getBody() Director::test('/silverstripe/testGoodBase1/TestForm/fields/MyField')->getBody()
@ -136,7 +139,10 @@ class RequestHandlingTest extends FunctionalTest
$this->assertEquals( $this->assertEquals(
'MyField posted, update to 5', 'MyField posted, update to 5',
Director::test('/silverstripe/testGoodBase1/TestForm/fields/MyField', array('MyField' => 5))->getBody() Director::test(
'/silverstripe/testGoodBase1/TestForm/fields/MyField',
['MyField' => 5]
)->getBody()
); );
} }
); );
@ -148,7 +154,7 @@ class RequestHandlingTest extends FunctionalTest
$response = Director::test("testBadBase/method/1/2"); $response = Director::test("testBadBase/method/1/2");
$this->assertNotEquals("This is a method on the controller: 1, 2", $response->getBody()); $this->assertNotEquals("This is a method on the controller: 1, 2", $response->getBody());
$response = Director::test("testBadBase/TestForm", array("MyField" => 3), null, "POST"); $response = Director::test("testBadBase/TestForm", ["MyField" => 3], null, "POST");
$this->assertNotEquals("Form posted", $response->getBody()); $this->assertNotEquals("Form posted", $response->getBody());
$response = Director::test("testBadBase/TestForm/fields/MyField"); $response = Director::test("testBadBase/TestForm/fields/MyField");
@ -254,7 +260,7 @@ class RequestHandlingTest extends FunctionalTest
$tokenEls = $this->cssParser()->getBySelector('#Form_Form_SecurityID'); $tokenEls = $this->cssParser()->getBySelector('#Form_Form_SecurityID');
$securityId = (string)$tokenEls[0]['value']; $securityId = (string)$tokenEls[0]['value'];
$data = array('action_formaction' => 1); $data = ['action_formaction' => 1];
$response = $this->post('FormActionController/Form', $data); $response = $this->post('FormActionController/Form', $data);
$this->assertEquals( $this->assertEquals(
400, 400,
@ -262,7 +268,7 @@ class RequestHandlingTest extends FunctionalTest
'Should fail: Invocation through POST form handler, not contained in $allowed_actions, without CSRF token' 'Should fail: Invocation through POST form handler, not contained in $allowed_actions, without CSRF token'
); );
$data = array('action_disallowedcontrollermethod' => 1, 'SecurityID' => $securityId); $data = ['action_disallowedcontrollermethod' => 1, 'SecurityID' => $securityId];
$response = $this->post('FormActionController/Form', $data); $response = $this->post('FormActionController/Form', $data);
$this->assertEquals( $this->assertEquals(
403, 403,
@ -271,7 +277,7 @@ class RequestHandlingTest extends FunctionalTest
. ' not contained in $allowed_actions, with CSRF token' . ' not contained in $allowed_actions, with CSRF token'
); );
$data = array('action_formaction' => 1, 'SecurityID' => $securityId); $data = ['action_formaction' => 1, 'SecurityID' => $securityId];
$response = $this->post('FormActionController/Form', $data); $response = $this->post('FormActionController/Form', $data);
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
$this->assertEquals( $this->assertEquals(
@ -280,16 +286,16 @@ class RequestHandlingTest extends FunctionalTest
'Should pass: Invocation through POST form handler, not contained in $allowed_actions, with CSRF token' 'Should pass: Invocation through POST form handler, not contained in $allowed_actions, with CSRF token'
); );
$data = array('action_controlleraction' => 1, 'SecurityID' => $securityId); $data = ['action_controlleraction' => 1, 'SecurityID' => $securityId];
$response = $this->post('FormActionController/Form', $data); $response = $this->post('FormActionController/Form', $data);
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
'Should pass: Invocation through POST form handler, controller action instead of form action, contained in' 'Should pass: Invocation through POST form handler, controller action instead of form action, contained in'
. ' $allowed_actions, with CSRF token' . ' $allowed_actions, with CSRF token'
); );
$data = array('action_formactionInAllowedActions' => 1); $data = ['action_formactionInAllowedActions' => 1];
$response = $this->post('FormActionController/Form', $data); $response = $this->post('FormActionController/Form', $data);
$this->assertEquals( $this->assertEquals(
400, 400,
@ -297,7 +303,7 @@ class RequestHandlingTest extends FunctionalTest
'Should fail: Invocation through POST form handler, contained in $allowed_actions, without CSRF token' 'Should fail: Invocation through POST form handler, contained in $allowed_actions, without CSRF token'
); );
$data = array('action_formactionInAllowedActions' => 1, 'SecurityID' => $securityId); $data = ['action_formactionInAllowedActions' => 1, 'SecurityID' => $securityId];
$response = $this->post('FormActionController/Form', $data); $response = $this->post('FormActionController/Form', $data);
$this->assertEquals( $this->assertEquals(
200, 200,
@ -305,7 +311,7 @@ class RequestHandlingTest extends FunctionalTest
'Should pass: Invocation through POST form handler, contained in $allowed_actions, with CSRF token' 'Should pass: Invocation through POST form handler, contained in $allowed_actions, with CSRF token'
); );
$data = array(); $data = [];
$response = $this->post('FormActionController/formaction', $data); $response = $this->post('FormActionController/formaction', $data);
$this->assertEquals( $this->assertEquals(
404, 404,
@ -313,7 +319,7 @@ class RequestHandlingTest extends FunctionalTest
'Should fail: Invocation through POST URL, not contained in $allowed_actions, without CSRF token' 'Should fail: Invocation through POST URL, not contained in $allowed_actions, without CSRF token'
); );
$data = array(); $data = [];
$response = $this->post('FormActionController/formactionInAllowedActions', $data); $response = $this->post('FormActionController/formactionInAllowedActions', $data);
$this->assertEquals( $this->assertEquals(
200, 200,
@ -321,7 +327,7 @@ class RequestHandlingTest extends FunctionalTest
'Should pass: Invocation of form action through POST URL, contained in $allowed_actions, without CSRF token' 'Should pass: Invocation of form action through POST URL, contained in $allowed_actions, without CSRF token'
); );
$data = array('SecurityID' => $securityId); $data = ['SecurityID' => $securityId];
$response = $this->post('FormActionController/formactionInAllowedActions', $data); $response = $this->post('FormActionController/formactionInAllowedActions', $data);
$this->assertEquals( $this->assertEquals(
200, 200,
@ -329,7 +335,7 @@ class RequestHandlingTest extends FunctionalTest
'Should pass: Invocation of form action through POST URL, contained in $allowed_actions, with CSRF token' 'Should pass: Invocation of form action through POST URL, contained in $allowed_actions, with CSRF token'
); );
$data = array(); // CSRF protection doesnt kick in for direct requests $data = []; // CSRF protection doesnt kick in for direct requests
$response = $this->post('FormActionController/formactionInAllowedActions', $data); $response = $this->post('FormActionController/formactionInAllowedActions', $data);
$this->assertEquals( $this->assertEquals(
200, 200,
@ -342,12 +348,12 @@ class RequestHandlingTest extends FunctionalTest
public function testAllowedActionsEnforcedOnForm() public function testAllowedActionsEnforcedOnForm()
{ {
$data = array('action_allowedformaction' => 1); $data = ['action_allowedformaction' => 1];
$response = $this->post('ControllerFormWithAllowedActions/Form', $data); $response = $this->post('ControllerFormWithAllowedActions/Form', $data);
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('allowedformaction', $response->getBody()); $this->assertEquals('allowedformaction', $response->getBody());
$data = array('action_disallowedformaction' => 1); $data = ['action_disallowedformaction' => 1];
$response = $this->post('ControllerFormWithAllowedActions/Form', $data); $response = $this->post('ControllerFormWithAllowedActions/Form', $data);
$this->assertEquals(403, $response->getStatusCode()); $this->assertEquals(403, $response->getStatusCode());
// Note: Looks for a specific 403 thrown by Form->httpSubmission(), not RequestHandler->handleRequest() // Note: Looks for a specific 403 thrown by Form->httpSubmission(), not RequestHandler->handleRequest()
@ -356,12 +362,12 @@ class RequestHandlingTest extends FunctionalTest
public function testActionHandlingOnField() public function testActionHandlingOnField()
{ {
$data = array('action_actionOnField' => 1); $data = ['action_actionOnField' => 1];
$response = $this->post('FieldController/TestForm', $data); $response = $this->post('FieldController/TestForm', $data);
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Test method on MyField', $response->getBody()); $this->assertEquals('Test method on MyField', $response->getBody());
$data = array('action_actionNotAllowedOnField' => 1); $data = ['action_actionNotAllowedOnField' => 1];
$response = $this->post('FieldController/TestForm', $data); $response = $this->post('FieldController/TestForm', $data);
$this->assertEquals(404, $response->getStatusCode()); $this->assertEquals(404, $response->getStatusCode());
} }

View File

@ -137,7 +137,7 @@ class SessionTest extends SapphireTest
[ [
// 'existing' => true, // 'existing' => true,
'new' => true, 'new' => true,
'merge' => 2 'merge' => 2,
], ],
$session->getAll() $session->getAll()
); );
@ -183,17 +183,17 @@ class SessionTest extends SapphireTest
$session = $this->session->getAll(); $session = $this->session->getAll();
unset($session['HTTP_USER_AGENT']); unset($session['HTTP_USER_AGENT']);
$this->assertEquals($session, array('Test' => 'Test', 'Test-2' => 'Test-2')); $this->assertEquals($session, ['Test' => 'Test', 'Test-2' => 'Test-2']);
} }
public function testSettingExistingDoesntClear() public function testSettingExistingDoesntClear()
{ {
$s = new Session(array('something' => array('does' => 'exist'))); $s = new Session(['something' => ['does' => 'exist']]);
$s->set('something.does', 'exist'); $s->set('something.does', 'exist');
$result = $s->changedData(); $result = $s->changedData();
unset($result['HTTP_USER_AGENT']); unset($result['HTTP_USER_AGENT']);
$this->assertEquals(array(), $result); $this->assertEmpty($result);
} }
/** /**
@ -206,7 +206,7 @@ class SessionTest extends SapphireTest
// Clear without existing data // Clear without existing data
$data = $s->get('something.doesnt.exist'); $data = $s->get('something.doesnt.exist');
$this->assertEquals(array(), $s->changedData()); $this->assertEmpty($s->changedData());
$this->assertNull($data); $this->assertNull($data);
// Clear with existing change // Clear with existing change
@ -273,7 +273,7 @@ class SessionTest extends SapphireTest
$req1->addHeader('User-Agent', 'Test Agent'); $req1->addHeader('User-Agent', 'Test Agent');
// Generate our session // Generate our session
$s = new Session(array()); $s = new Session([]);
$s->init($req1); $s->init($req1);
$s->set('val', 123); $s->set('val', 123);
$s->finalize($req1); $s->finalize($req1);
@ -312,13 +312,13 @@ class SessionTest extends SapphireTest
'something' => [ 'something' => [
'another' => 'newanother', 'another' => 'newanother',
'newkey' => 'new value', 'newkey' => 'new value',
] ],
], ],
$_SESSION $_SESSION
); );
// Test cleared keys are restorable // Test cleared keys are restorable
$s = new Session($_SESSION = ['bookmarks' => [ 1 => 1, 2 => 2]]); $s = new Session($_SESSION = ['bookmarks' => [1 => 1, 2 => 2]]);
$s->clear('bookmarks'); $s->clear('bookmarks');
$s->set('bookmarks', [ $s->set('bookmarks', [
1 => 1, 1 => 1,
@ -330,7 +330,7 @@ class SessionTest extends SapphireTest
'bookmarks' => [ 'bookmarks' => [
1 => 1, 1 => 1,
3 => 3, 3 => 3,
] ],
], ],
$_SESSION $_SESSION
); );

View File

@ -32,7 +32,9 @@ class SimpleResourceURLGeneratorTest extends SapphireTest
{ {
/** @var SimpleResourceURLGenerator $generator */ /** @var SimpleResourceURLGenerator $generator */
$generator = Injector::inst()->get(ResourceURLGenerator::class); $generator = Injector::inst()->get(ResourceURLGenerator::class);
$mtime = filemtime(__DIR__ . '/SimpleResourceURLGeneratorTest/_fakewebroot/basemodule/client/file.js'); $mtime = filemtime(
__DIR__ . '/SimpleResourceURLGeneratorTest/_fakewebroot/basemodule/client/file.js'
);
$this->assertEquals( $this->assertEquals(
'/resources/basemodule/client/file.js?m=' . $mtime, '/resources/basemodule/client/file.js?m=' . $mtime,
$generator->urlForResource('basemodule/client/file.js') $generator->urlForResource('basemodule/client/file.js')