Converted to PSR-2

This commit is contained in:
helpfulrobot 2015-12-18 07:17:16 +13:00
parent 4015611673
commit e40a0d0f1a
5 changed files with 916 additions and 852 deletions

View File

@ -2,7 +2,8 @@
/** /**
* Requires PHP's mycrypt extension in order to set the database name as an encrypted cookie. * Requires PHP's mycrypt extension in order to set the database name as an encrypted cookie.
*/ */
class TestSessionController extends Controller { class TestSessionController extends Controller
{
private static $allowed_actions = array( private static $allowed_actions = array(
'index', 'index',
@ -27,13 +28,15 @@ class TestSessionController extends Controller {
*/ */
protected $environment; protected $environment;
public function __construct() { public function __construct()
{
parent::__construct(); parent::__construct();
$this->environment = Injector::inst()->get('TestSessionEnvironment'); $this->environment = Injector::inst()->get('TestSessionEnvironment');
} }
public function init() { public function init()
{
parent::init(); parent::init();
$this->extend('init'); $this->extend('init');
@ -42,17 +45,21 @@ class TestSessionController extends Controller {
!Director::isLive() !Director::isLive()
&& (Director::isDev() || Director::isTest() || Director::is_cli() || Permission::check("ADMIN")) && (Director::isDev() || Director::isTest() || Director::is_cli() || Permission::check("ADMIN"))
); );
if(!$canAccess) return Security::permissionFailure($this); if (!$canAccess) {
return Security::permissionFailure($this);
}
Requirements::javascript('framework/thirdparty/jquery/jquery.js'); Requirements::javascript('framework/thirdparty/jquery/jquery.js');
Requirements::javascript('testsession/javascript/testsession.js'); Requirements::javascript('testsession/javascript/testsession.js');
} }
public function Link($action = null) { public function Link($action = null)
{
return Controller::join_links(Director::baseUrl(), 'dev/testsession', $action); return Controller::join_links(Director::baseUrl(), 'dev/testsession', $action);
} }
public function index() { public function index()
{
if ($this->environment->isRunningTests()) { if ($this->environment->isRunningTests()) {
return $this->renderWith('TestSession_inprogress'); return $this->renderWith('TestSession_inprogress');
} else { } else {
@ -65,7 +72,8 @@ class TestSessionController extends Controller {
* then take a look at {@link TestSessionEnvironment::startTestSession()} and * then take a look at {@link TestSessionEnvironment::startTestSession()} and
* {@link TestSessionEnvironment::applyState()} to see the extension points. * {@link TestSessionEnvironment::applyState()} to see the extension points.
*/ */
public function start() { public function start()
{
$params = $this->request->requestVars(); $params = $this->request->requestVars();
if (!empty($params['globalTestSession'])) { if (!empty($params['globalTestSession'])) {
@ -130,7 +138,8 @@ class TestSessionController extends Controller {
/** /**
* Set $_SESSION state for the current browser session. * Set $_SESSION state for the current browser session.
*/ */
public function browsersessionstate($request) { public function browsersessionstate($request)
{
if (!$this->environment->isRunningTests()) { if (!$this->environment->isRunningTests()) {
throw new LogicException("No test session in progress."); throw new LogicException("No test session in progress.");
} }
@ -150,7 +159,8 @@ class TestSessionController extends Controller {
Session::set('_TestSessionController.BrowserSessionState', array_merge($sessionStates, $newSessionStates)); Session::set('_TestSessionController.BrowserSessionState', array_merge($sessionStates, $newSessionStates));
} }
public function StartForm() { public function StartForm()
{
$databaseTemplates = $this->getDatabaseTemplates(); $databaseTemplates = $this->getDatabaseTemplates();
$fields = new FieldList( $fields = new FieldList(
new CheckboxField('createDatabase', 'Create temporary database?', 1) new CheckboxField('createDatabase', 'Create temporary database?', 1)
@ -188,7 +198,8 @@ class TestSessionController extends Controller {
/** /**
* Shows state which is allowed to be modified while a test session is in progress. * Shows state which is allowed to be modified while a test session is in progress.
*/ */
public function ProgressForm() { public function ProgressForm()
{
$fields = $this->getBaseFields(); $fields = $this->getBaseFields();
$form = new Form( $form = new Form(
$this, $this,
@ -207,7 +218,8 @@ class TestSessionController extends Controller {
return $form; return $form;
} }
protected function getBaseFields() { protected function getBaseFields()
{
$testState = $this->environment->getState(); $testState = $this->environment->getState();
$fields = new FieldList( $fields = new FieldList(
@ -230,7 +242,8 @@ class TestSessionController extends Controller {
return $fields; return $fields;
} }
public function DatabaseName() { public function DatabaseName()
{
$db = DB::get_conn(); $db = DB::get_conn();
return $db->getSelectedDatabase(); return $db->getSelectedDatabase();
} }
@ -242,7 +255,8 @@ class TestSessionController extends Controller {
* @return HTMLText Rendered Template * @return HTMLText Rendered Template
* @throws LogicException * @throws LogicException
*/ */
public function set() { public function set()
{
if (!$this->environment->isRunningTests()) { if (!$this->environment->isRunningTests()) {
throw new LogicException("No test session in progress."); throw new LogicException("No test session in progress.");
} }
@ -269,7 +283,8 @@ class TestSessionController extends Controller {
return $this->renderWith('TestSession_inprogress'); return $this->renderWith('TestSession_inprogress');
} }
public function clear() { public function clear()
{
if (!$this->environment->isRunningTests()) { if (!$this->environment->isRunningTests()) {
throw new LogicException("No test session in progress."); throw new LogicException("No test session in progress.");
} }
@ -294,7 +309,8 @@ class TestSessionController extends Controller {
* {@link TestSessionEnvironent::endTestSession()} as the extension points have moved to there now that the logic * {@link TestSessionEnvironent::endTestSession()} as the extension points have moved to there now that the logic
* is there. * is there.
*/ */
public function end() { public function end()
{
if (!$this->environment->isRunningTests()) { if (!$this->environment->isRunningTests()) {
throw new LogicException("No test session in progress."); throw new LogicException("No test session in progress.");
} }
@ -317,11 +333,13 @@ class TestSessionController extends Controller {
/** /**
* @return boolean * @return boolean
*/ */
public function isTesting() { public function isTesting()
{
return SapphireTest::using_temp_db(); return SapphireTest::using_temp_db();
} }
public function setState($data) { public function setState($data)
{
Deprecation::notice('3.1', 'TestSessionController::setState() is no longer used, please use ' Deprecation::notice('3.1', 'TestSessionController::setState() is no longer used, please use '
. 'TestSessionEnvironment instead.'); . 'TestSessionEnvironment instead.');
} }
@ -329,7 +347,8 @@ class TestSessionController extends Controller {
/** /**
* @return ArrayList * @return ArrayList
*/ */
public function getState() { public function getState()
{
$stateObj = $this->environment->getState(); $stateObj = $this->environment->getState();
$state = array(); $state = array();
@ -351,7 +370,8 @@ class TestSessionController extends Controller {
* @param String $path Absolute folder path * @param String $path Absolute folder path
* @return array * @return array
*/ */
protected function getDatabaseTemplates($path = null) { protected function getDatabaseTemplates($path = null)
{
$templates = array(); $templates = array();
if (!$path) { if (!$path) {
@ -366,7 +386,9 @@ class TestSessionController extends Controller {
if ($path && file_exists($path)) { if ($path && file_exists($path)) {
$it = new FilesystemIterator($path); $it = new FilesystemIterator($path);
foreach ($it as $fileinfo) { foreach ($it as $fileinfo) {
if($fileinfo->getExtension() != 'sql') continue; if ($fileinfo->getExtension() != 'sql') {
continue;
}
$templates[$fileinfo->getRealPath()] = $fileinfo->getFilename(); $templates[$fileinfo->getRealPath()] = $fileinfo->getFilename();
} }
} }
@ -378,7 +400,8 @@ class TestSessionController extends Controller {
* @param $params array The form fields as passed through from ->start() or ->set() * @param $params array The form fields as passed through from ->start() or ->set()
* @return array The form fields, after fixing the datetime field if necessary * @return array The form fields, after fixing the datetime field if necessary
*/ */
private function fixDatetimeFormField($params) { private function fixDatetimeFormField($params)
{
if (isset($params['datetime']) && is_array($params['datetime']) && !empty($params['datetime']['date'])) { if (isset($params['datetime']) && is_array($params['datetime']) && !empty($params['datetime']['date'])) {
// Convert DatetimeField format from array into string // Convert DatetimeField format from array into string
$datetime = $params['datetime']['date']; $datetime = $params['datetime']['date'];
@ -391,5 +414,4 @@ class TestSessionController extends Controller {
return $params; return $params;
} }
} }

View File

@ -24,7 +24,8 @@
* *
* See {@link $state} for default information stored in the test session. * See {@link $state} for default information stored in the test session.
*/ */
class TestSessionEnvironment extends Object { class TestSessionEnvironment extends Object
{
/** /**
* @var int Optional identifier for the session. * @var int Optional identifier for the session.
@ -51,7 +52,8 @@ class TestSessionEnvironment extends Object {
*/ */
private static $test_state_id_file = 'TESTS_RUNNING-%s.json'; private static $test_state_id_file = 'TESTS_RUNNING-%s.json';
public function __construct($id = null) { public function __construct($id = null)
{
parent::__construct(); parent::__construct();
if ($id) { if ($id) {
@ -67,7 +69,8 @@ class TestSessionEnvironment extends Object {
/** /**
* @return String Absolute path to the file persisting our state. * @return String Absolute path to the file persisting our state.
*/ */
public function getFilePath() { public function getFilePath()
{
if ($this->id) { if ($this->id) {
$path = Director::getAbsFile(sprintf($this->config()->test_state_id_file, $this->id)); $path = Director::getAbsFile(sprintf($this->config()->test_state_id_file, $this->id));
} else { } else {
@ -80,21 +83,24 @@ class TestSessionEnvironment extends Object {
/** /**
* Tests for the existence of the file specified by $this->test_state_file * Tests for the existence of the file specified by $this->test_state_file
*/ */
public function isRunningTests() { public function isRunningTests()
{
return(file_exists($this->getFilePath())); return(file_exists($this->getFilePath()));
} }
/** /**
* @param String $id * @param String $id
*/ */
public function setId($id) { public function setId($id)
{
$this->id = $id; $this->id = $id;
} }
/** /**
* @return String * @return String
*/ */
public function getId() { public function getId()
{
return $this->id; return $this->id;
} }
@ -111,8 +117,11 @@ class TestSessionEnvironment extends Object {
* *
* @param array $state An array of test state options to write. * @param array $state An array of test state options to write.
*/ */
public function startTestSession($state = null, $id = null) { public function startTestSession($state = null, $id = null)
if(!$state) $state = array(); {
if (!$state) {
$state = array();
}
$this->removeStateFile(); $this->removeStateFile();
$this->id = $id; $this->id = $id;
@ -128,7 +137,8 @@ class TestSessionEnvironment extends Object {
$this->extend('onAfterStartTestSession'); $this->extend('onAfterStartTestSession');
} }
public function updateTestSession($state) { public function updateTestSession($state)
{
$this->extend('onBeforeUpdateTestSession', $state); $this->extend('onBeforeUpdateTestSession', $state);
// Convert to JSON and back so we can share the appleState() code between this and ->loadFromFile() // Convert to JSON and back so we can share the appleState() code between this and ->loadFromFile()
@ -152,7 +162,8 @@ class TestSessionEnvironment extends Object {
* @throws LogicException * @throws LogicException
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function applyState($state) { public function applyState($state)
{
$this->extend('onBeforeApplyState', $state); $this->extend('onBeforeApplyState', $state);
$database = (isset($state->database)) ? $state->database : null; $database = (isset($state->database)) ? $state->database : null;
@ -259,7 +270,8 @@ class TestSessionEnvironment extends Object {
* @param String $path Absolute path to a SQL dump (include DROP TABLE commands) * @param String $path Absolute path to a SQL dump (include DROP TABLE commands)
* @return void * @return void
*/ */
public function importDatabase($path, $requireDefaultRecords = false) { public function importDatabase($path, $requireDefaultRecords = false)
{
$sql = file_get_contents($path); $sql = file_get_contents($path);
// Split into individual query commands, removing comments // Split into individual query commands, removing comments
@ -283,7 +295,8 @@ class TestSessionEnvironment extends Object {
/** /**
* Build the database with default records, see {@link DataObject->requireDefaultRecords()}. * Build the database with default records, see {@link DataObject->requireDefaultRecords()}.
*/ */
public function requireDefaultRecords() { public function requireDefaultRecords()
{
$dbAdmin = new DatabaseAdmin(); $dbAdmin = new DatabaseAdmin();
Versioned::set_reading_mode(''); Versioned::set_reading_mode('');
$dbAdmin->doBuild(true, true); $dbAdmin->doBuild(true, true);
@ -293,7 +306,8 @@ class TestSessionEnvironment extends Object {
* Sliented as if the file already exists by another process, we don't want * Sliented as if the file already exists by another process, we don't want
* to modify. * to modify.
*/ */
public function saveState($state) { public function saveState($state)
{
if (defined('JSON_PRETTY_PRINT')) { if (defined('JSON_PRETTY_PRINT')) {
$content = json_encode($state, JSON_PRETTY_PRINT); $content = json_encode($state, JSON_PRETTY_PRINT);
} else { } else {
@ -304,7 +318,8 @@ class TestSessionEnvironment extends Object {
umask($old); umask($old);
} }
public function loadFromFile() { public function loadFromFile()
{
if ($this->isRunningTests()) { if ($this->isRunningTests()) {
try { try {
$contents = file_get_contents($this->getFilePath()); $contents = file_get_contents($this->getFilePath());
@ -319,7 +334,8 @@ class TestSessionEnvironment extends Object {
} }
} }
private function removeStateFile() { private function removeStateFile()
{
$file = $this->getFilePath(); $file = $this->getFilePath();
if (file_exists($file)) { if (file_exists($file)) {
@ -341,7 +357,8 @@ class TestSessionEnvironment extends Object {
* a queueing system (e.g. silverstripe-resque) is used, the behat module may call this first, and then the forked * a queueing system (e.g. silverstripe-resque) is used, the behat module may call this first, and then the forked
* worker will call it as well - but there is only one state file that is created. * worker will call it as well - but there is only one state file that is created.
*/ */
public function endTestSession() { public function endTestSession()
{
$this->extend('onBeforeEndTestSession'); $this->extend('onBeforeEndTestSession');
if (SapphireTest::using_temp_db()) { if (SapphireTest::using_temp_db()) {
@ -362,7 +379,8 @@ class TestSessionEnvironment extends Object {
* @return FixtureFactory The loaded fixture * @return FixtureFactory The loaded fixture
* @throws LogicException * @throws LogicException
*/ */
public function loadFixtureIntoDb($fixtureFile) { public function loadFixtureIntoDb($fixtureFile)
{
$realFile = realpath(BASE_PATH.'/'.$fixtureFile); $realFile = realpath(BASE_PATH.'/'.$fixtureFile);
$baseDir = realpath(Director::baseFolder()); $baseDir = realpath(Director::baseFolder());
if (!$realFile || !file_exists($realFile)) { if (!$realFile || !file_exists($realFile)) {
@ -389,7 +407,8 @@ class TestSessionEnvironment extends Object {
/** /**
* Reset the database connection to use the original database. Called by {@link self::endTestSession()}. * Reset the database connection to use the original database. Called by {@link self::endTestSession()}.
*/ */
public function resetDatabaseName() { public function resetDatabaseName()
{
if ($this->oldDatabaseName) { if ($this->oldDatabaseName) {
global $databaseConfig; global $databaseConfig;
@ -406,7 +425,8 @@ class TestSessionEnvironment extends Object {
/** /**
* @return stdClass Data as taken from the JSON object in {@link self::loadFromFile()} * @return stdClass Data as taken from the JSON object in {@link self::loadFromFile()}
*/ */
public function getState() { public function getState()
{
$path = Director::getAbsFile($this->getFilePath()); $path = Director::getAbsFile($this->getFilePath());
return (file_exists($path)) ? json_decode(file_get_contents($path)) : new stdClass; return (file_exists($path)) ? json_decode(file_get_contents($path)) : new stdClass;
} }

View File

@ -2,19 +2,24 @@
/** /**
* Sets state previously initialized through {@link TestSessionController}. * Sets state previously initialized through {@link TestSessionController}.
*/ */
class TestSessionRequestFilter implements RequestFilter { class TestSessionRequestFilter implements RequestFilter
{
/** /**
* @var TestSessionEnvironment * @var TestSessionEnvironment
*/ */
protected $testSessionEnvironment; protected $testSessionEnvironment;
public function __construct() { public function __construct()
{
$this->testSessionEnvironment = Injector::inst()->get('TestSessionEnvironment'); $this->testSessionEnvironment = Injector::inst()->get('TestSessionEnvironment');
} }
public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model) { public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model)
if(!$this->testSessionEnvironment->isRunningTests()) return; {
if (!$this->testSessionEnvironment->isRunningTests()) {
return;
}
$testState = $this->testSessionEnvironment->getState(); $testState = $this->testSessionEnvironment->getState();
@ -40,14 +45,19 @@ class TestSessionRequestFilter implements RequestFilter {
if (!Director::isLive() && $file && file_exists($file)) { if (!Director::isLive() && $file && file_exists($file)) {
// Connect to the database so the included code can interact with it // Connect to the database so the included code can interact with it
global $databaseConfig; global $databaseConfig;
if ($databaseConfig) DB::connect($databaseConfig); if ($databaseConfig) {
DB::connect($databaseConfig);
}
include_once($file); include_once($file);
} }
} }
} }
public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model) { public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
if(!$this->testSessionEnvironment->isRunningTests()) return; {
if (!$this->testSessionEnvironment->isRunningTests()) {
return;
}
// Store PHP session // Store PHP session
$state = $this->testSessionEnvironment->getState(); $state = $this->testSessionEnvironment->getState();

View File

@ -3,7 +3,8 @@
* Writes PHP to a file which can be included in SilverStripe runs on existence. * Writes PHP to a file which can be included in SilverStripe runs on existence.
* The generated file is included in page execution through {@link TestSessionRequestFilter}. * The generated file is included in page execution through {@link TestSessionRequestFilter}.
*/ */
class TestSessionStubCodeWriter { class TestSessionStubCodeWriter
{
/** /**
* @var boolean Add debug statements to the generated PHP about * @var boolean Add debug statements to the generated PHP about
@ -16,7 +17,8 @@ class TestSessionStubCodeWriter {
*/ */
protected $filePath; protected $filePath;
public function __construct($filePath = null) { public function __construct($filePath = null)
{
$this->filePath = $filePath ? $filePath : BASE_PATH . '/testSessionStubCode.php'; $this->filePath = $filePath ? $filePath : BASE_PATH . '/testSessionStubCode.php';
} }
@ -28,7 +30,8 @@ class TestSessionStubCodeWriter {
* @param String $php Block of PHP code (without preceding <?php) * @param String $php Block of PHP code (without preceding <?php)
* @param boolean $eval Sanity check on code. * @param boolean $eval Sanity check on code.
*/ */
public function write($php, $eval = true) { public function write($php, $eval = true)
{
$trace = $this->debug ? debug_backtrace() : null; $trace = $this->debug ? debug_backtrace() : null;
$path = $this->getFilePath(); $path = $this->getFilePath();
$header = ''; $header = '';
@ -50,24 +53,27 @@ class TestSessionStubCodeWriter {
file_put_contents($path, $header . $php . "\n", FILE_APPEND); file_put_contents($path, $header . $php . "\n", FILE_APPEND);
} }
public function reset() { public function reset()
{
if (file_exists($this->getFilePath())) { if (file_exists($this->getFilePath())) {
unlink($this->getFilePath()); unlink($this->getFilePath());
} }
} }
public function getFilePath() { public function getFilePath()
{
return $this->filePath; return $this->filePath;
} }
public function getDebug() { public function getDebug()
{
return $this->debug; return $this->debug;
} }
public function setDebug($debug) { public function setDebug($debug)
{
$this->debug = $debug; $this->debug = $debug;
return $this; return $this;
} }
} }

View File

@ -1,14 +1,19 @@
<?php <?php
class TestSessionStubCodeWriterTest extends SapphireTest { class TestSessionStubCodeWriterTest extends SapphireTest
{
public function tearDown() { public function tearDown()
{
parent::tearDown(); parent::tearDown();
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php'; $file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
if(file_exists($file)) unlink($file); if (file_exists($file)) {
unlink($file);
}
} }
public function testWritesHeaderOnNewFile() { public function testWritesHeaderOnNewFile()
{
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php'; $file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
$writer = new TestSessionStubCodeWriter($file); $writer = new TestSessionStubCodeWriter($file);
$writer->write('foo();', false); $writer->write('foo();', false);
@ -19,7 +24,8 @@ class TestSessionStubCodeWriterTest extends SapphireTest {
); );
} }
public function testWritesWithAppendOnExistingFile() { public function testWritesWithAppendOnExistingFile()
{
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php'; $file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
$writer = new TestSessionStubCodeWriter($file); $writer = new TestSessionStubCodeWriter($file);
$writer->write('foo();', false); $writer->write('foo();', false);
@ -31,7 +37,8 @@ class TestSessionStubCodeWriterTest extends SapphireTest {
); );
} }
public function testReset() { public function testReset()
{
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php'; $file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
$writer = new TestSessionStubCodeWriter($file); $writer = new TestSessionStubCodeWriter($file);
$writer->write('foo();', false); $writer->write('foo();', false);
@ -39,5 +46,4 @@ class TestSessionStubCodeWriterTest extends SapphireTest {
$writer->reset(); $writer->reset();
$this->assertFileNotExists($file); $this->assertFileNotExists($file);
} }
} }