Merge pull request #29 from helpfulrobot/convert-to-psr-2

Converted to PSR-2
This commit is contained in:
Damian Mooyman 2015-12-18 10:05:50 +13:00
commit 5167be8d96
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,18 +45,22 @@ 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 {
return $this->renderWith('TestSession_start'); return $this->renderWith('TestSession_start');
@ -65,10 +72,11 @@ 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'])) {
$id = null; $id = null;
} else { } else {
$generator = Injector::inst()->get('RandomGenerator'); $generator = Injector::inst()->get('RandomGenerator');
@ -94,17 +102,17 @@ class TestSessionController extends Controller {
$this->environment->startTestSession($params, $id); $this->environment->startTestSession($params, $id);
// Optionally import database // Optionally import database
if(!empty($params['importDatabasePath']) || !empty($params['importDatabaseFilename'])) { if (!empty($params['importDatabasePath']) || !empty($params['importDatabaseFilename'])) {
$absPath = ''; $absPath = '';
// by path // by path
if(!empty($params['importDatabasePath'])) { if (!empty($params['importDatabasePath'])) {
$absPath = $params['importDatabasePath']; $absPath = $params['importDatabasePath'];
// by filename // by filename
}else if(!empty($params['importDatabaseFilename'])) { } elseif (!empty($params['importDatabaseFilename'])) {
foreach($this->getDatabaseTemplates() as $tAbsPath => $tFilename){ foreach ($this->getDatabaseTemplates() as $tAbsPath => $tFilename) {
if($tFilename === $params['importDatabaseFilename']){ if ($tFilename === $params['importDatabaseFilename']) {
$absPath = $tAbsPath; $absPath = $tAbsPath;
break; break;
} }
@ -114,13 +122,13 @@ class TestSessionController extends Controller {
$absPath, $absPath,
!empty($params['requireDefaultRecords']) ? $params['requireDefaultRecords'] : false !empty($params['requireDefaultRecords']) ? $params['requireDefaultRecords'] : false
); );
} else if(!empty($params['requireDefaultRecords']) && $params['requireDefaultRecords']) { } elseif (!empty($params['requireDefaultRecords']) && $params['requireDefaultRecords']) {
$this->environment->requireDefaultRecords(); $this->environment->requireDefaultRecords();
} }
// Fixtures // Fixtures
$fixtureFile = (!empty($params['fixture'])) ? $params['fixture'] : null; $fixtureFile = (!empty($params['fixture'])) ? $params['fixture'] : null;
if($fixtureFile) { if ($fixtureFile) {
$this->environment->loadFixtureIntoDb($fixtureFile); $this->environment->loadFixtureIntoDb($fixtureFile);
} }
@ -130,19 +138,20 @@ 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.");
} }
$newSessionStates = array_diff_key($request->getVars(), array('url' => true)); $newSessionStates = array_diff_key($request->getVars(), array('url' => true));
if(!$newSessionStates) { if (!$newSessionStates) {
throw new LogicException('No query parameters detected'); throw new LogicException('No query parameters detected');
} }
$sessionStates = (array)Session::get('_TestSessionController.BrowserSessionState'); $sessionStates = (array)Session::get('_TestSessionController.BrowserSessionState');
foreach($newSessionStates as $k => $v) { foreach ($newSessionStates as $k => $v) {
Session::set($k, $v); Session::set($k, $v);
} }
@ -150,12 +159,13 @@ 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)
); );
if($databaseTemplates) { if ($databaseTemplates) {
$fields->push( $fields->push(
$dropdown = new DropdownField('importDatabasePath', false) $dropdown = new DropdownField('importDatabasePath', false)
); );
@ -164,7 +174,7 @@ class TestSessionController extends Controller {
->setEmptyString('Empty database'); ->setEmptyString('Empty database');
} }
$fields->push(new CheckboxField('requireDefaultRecords', 'Create default data?')); $fields->push(new CheckboxField('requireDefaultRecords', 'Create default data?'));
if(Director::isDev()) { if (Director::isDev()) {
$fields->push( $fields->push(
CheckboxField::create('globalTestSession', 'Use global test session?') CheckboxField::create('globalTestSession', 'Use global test session?')
->setDescription('Caution: Will apply to all users across browsers') ->setDescription('Caution: Will apply to all users across browsers')
@ -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,8 +255,9 @@ 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,18 +283,19 @@ 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.");
} }
$this->extend('onBeforeClear'); $this->extend('onBeforeClear');
if(SapphireTest::using_temp_db()) { if (SapphireTest::using_temp_db()) {
SapphireTest::empty_temp_db(); SapphireTest::empty_temp_db();
} }
if(isset($_SESSION['_testsession_codeblocks'])) { if (isset($_SESSION['_testsession_codeblocks'])) {
unset($_SESSION['_testsession_codeblocks']); unset($_SESSION['_testsession_codeblocks']);
} }
@ -294,8 +309,9 @@ 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.");
} }
@ -303,8 +319,8 @@ class TestSessionController extends Controller {
Session::clear('TestSessionId'); Session::clear('TestSessionId');
// Clear out all PHP session states which have been set previously // Clear out all PHP session states which have been set previously
if($sessionStates = Session::get('_TestSessionController.BrowserSessionState')) { if ($sessionStates = Session::get('_TestSessionController.BrowserSessionState')) {
foreach($sessionStates as $k => $v) { foreach ($sessionStates as $k => $v) {
Session::clear($k); Session::clear($k);
} }
Session::clear('_TestSessionController'); Session::clear('_TestSessionController');
@ -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,12 +347,13 @@ 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();
// Convert the stdObject of state into ArrayData // Convert the stdObject of state into ArrayData
foreach($stateObj as $k => $v) { foreach ($stateObj as $k => $v) {
$state[] = new ArrayData(array( $state[] = new ArrayData(array(
'Name' => $k, 'Name' => $k,
'Value' => var_export($v, true) 'Value' => var_export($v, true)
@ -351,22 +370,25 @@ 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) {
$path = $this->config()->database_templates_path; $path = $this->config()->database_templates_path;
} }
// TODO Remove once we can set BASE_PATH through the config layer // TODO Remove once we can set BASE_PATH through the config layer
if($path && !Director::is_absolute($path)) { if ($path && !Director::is_absolute($path)) {
$path = BASE_PATH . '/' . $path; $path = BASE_PATH . '/' . $path;
} }
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,18 +400,18 @@ 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'];
$datetime .= ' '; $datetime .= ' ';
$datetime .= (@$params['datetime']['time']) ? $params['datetime']['time'] : '00:00:00'; $datetime .= (@$params['datetime']['time']) ? $params['datetime']['time'] : '00:00:00';
$params['datetime'] = $datetime; $params['datetime'] = $datetime;
} else if(isset($params['datetime']) && empty($params['datetime']['date'])) { } elseif (isset($params['datetime']) && empty($params['datetime']['date'])) {
unset($params['datetime']); // No datetime, so remove the param entirely unset($params['datetime']); // No datetime, so remove the param entirely
} }
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,10 +52,11 @@ 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) {
$this->id = $id; $this->id = $id;
} else { } else {
Session::start(); Session::start();
@ -67,8 +69,9 @@ 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 {
$path = Director::getAbsFile($this->config()->test_state_file); $path = Director::getAbsFile($this->config()->test_state_file);
@ -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;
@ -164,19 +175,19 @@ class TestSessionEnvironment extends Object {
// Load existing state from $this->state into $state, if there is any // Load existing state from $this->state into $state, if there is any
$oldState = $this->getState(); $oldState = $this->getState();
if($oldState) { if ($oldState) {
foreach($oldState as $k => $v) { foreach ($oldState as $k => $v) {
if(!isset($state->$k)) { if (!isset($state->$k)) {
$state->$k = $v; // Don't overwrite stuff in $state, as that's the new state $state->$k = $v; // Don't overwrite stuff in $state, as that's the new state
} }
} }
} }
// ensure we have a connection to the database // ensure we have a connection to the database
if(isset($state->database) && $state->database) { if (isset($state->database) && $state->database) {
if(!DB::get_conn()) { if (!DB::get_conn()) {
// No connection, so try and connect to tmpdb if it exists // No connection, so try and connect to tmpdb if it exists
if(isset($state->database)) { if (isset($state->database)) {
$this->oldDatabaseName = $databaseConfig['database']; $this->oldDatabaseName = $databaseConfig['database'];
$databaseConfig['database'] = $state->database; $databaseConfig['database'] = $state->database;
} }
@ -186,7 +197,7 @@ class TestSessionEnvironment extends Object {
} else { } else {
// We've already connected to the database, do a fast check to see what database we're currently using // We've already connected to the database, do a fast check to see what database we're currently using
$db = DB::get_conn()->getSelectedDatabase(); $db = DB::get_conn()->getSelectedDatabase();
if(isset($state->database) && $db != $state->database) { if (isset($state->database) && $db != $state->database) {
$this->oldDatabaseName = $databaseConfig['database']; $this->oldDatabaseName = $databaseConfig['database'];
$databaseConfig['database'] = $state->database; $databaseConfig['database'] = $state->database;
DB::connect($databaseConfig); DB::connect($databaseConfig);
@ -195,16 +206,16 @@ class TestSessionEnvironment extends Object {
} }
// Database // Database
if(!$this->isRunningTests()) { if (!$this->isRunningTests()) {
$dbName = (isset($state->database)) ? $state->database : null; $dbName = (isset($state->database)) ? $state->database : null;
if($dbName) { if ($dbName) {
$dbExists = DB::get_conn()->databaseExists($dbName); $dbExists = DB::get_conn()->databaseExists($dbName);
} else { } else {
$dbExists = false; $dbExists = false;
} }
if(!$dbExists) { if (!$dbExists) {
// Create a new one with a randomized name // Create a new one with a randomized name
$dbName = SapphireTest::create_temp_db(); $dbName = SapphireTest::create_temp_db();
@ -213,7 +224,7 @@ class TestSessionEnvironment extends Object {
// Set existing one, assumes it already has been created // Set existing one, assumes it already has been created
$prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_'; $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
$pattern = strtolower(sprintf('#^%stmpdb\d{7}#', $prefix)); $pattern = strtolower(sprintf('#^%stmpdb\d{7}#', $prefix));
if(!preg_match($pattern, $dbName)) { if (!preg_match($pattern, $dbName)) {
throw new InvalidArgumentException("Invalid database name format"); throw new InvalidArgumentException("Invalid database name format");
} }
@ -228,8 +239,8 @@ class TestSessionEnvironment extends Object {
// Mailer // Mailer
$mailer = (isset($state->mailer)) ? $state->mailer : null; $mailer = (isset($state->mailer)) ? $state->mailer : null;
if($mailer) { if ($mailer) {
if(!class_exists($mailer) || !is_subclass_of($mailer, 'Mailer')) { if (!class_exists($mailer) || !is_subclass_of($mailer, 'Mailer')) {
throw new InvalidArgumentException(sprintf( throw new InvalidArgumentException(sprintf(
'Class "%s" is not a valid class, or subclass of Mailer', 'Class "%s" is not a valid class, or subclass of Mailer',
$mailer $mailer
@ -238,10 +249,10 @@ class TestSessionEnvironment extends Object {
} }
// Date and time // Date and time
if(isset($state->datetime)) { if (isset($state->datetime)) {
require_once 'Zend/Date.php'; require_once 'Zend/Date.php';
// Convert DatetimeField format // Convert DatetimeField format
if(!Zend_Date::isDate($state->datetime, 'yyyy-MM-dd HH:mm:ss')) { if (!Zend_Date::isDate($state->datetime, 'yyyy-MM-dd HH:mm:ss')) {
throw new LogicException(sprintf( throw new LogicException(sprintf(
'Invalid date format "%s", use yyyy-MM-dd HH:mm:ss', 'Invalid date format "%s", use yyyy-MM-dd HH:mm:ss',
$state->datetime $state->datetime
@ -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
@ -270,7 +282,7 @@ class TestSessionEnvironment extends Object {
); );
// Execute each query // Execute each query
foreach($sqlCmds as $sqlCmd) { foreach ($sqlCmds as $sqlCmd) {
DB::query($sqlCmd); DB::query($sqlCmd);
} }
@ -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,14 +318,15 @@ 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());
$json = json_decode($contents); $json = json_decode($contents);
$this->applyState($json); $this->applyState($json);
} catch(Exception $e) { } catch (Exception $e) {
throw new \Exception("A test session appears to be in progress, but we can't retrieve the details. " throw new \Exception("A test session appears to be in progress, but we can't retrieve the details. "
. "Try removing the " . $this->getFilePath() . " file. Inner " . "Try removing the " . $this->getFilePath() . " file. Inner "
. "error: " . $e->getMessage()); . "error: " . $e->getMessage());
@ -319,11 +334,12 @@ class TestSessionEnvironment extends Object {
} }
} }
private function removeStateFile() { private function removeStateFile()
{
$file = $this->getFilePath(); $file = $this->getFilePath();
if(file_exists($file)) { if (file_exists($file)) {
if(!unlink($file)) { if (!unlink($file)) {
throw new \Exception('Unable to remove the testsession state file, please remove it manually. File ' throw new \Exception('Unable to remove the testsession state file, please remove it manually. File '
. 'path: ' . $file); . 'path: ' . $file);
} }
@ -341,10 +357,11 @@ 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()) {
$this->resetDatabaseName(); $this->resetDatabaseName();
SapphireTest::set_is_running_test(false); SapphireTest::set_is_running_test(false);
@ -362,16 +379,17 @@ 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)) {
throw new LogicException("Fixture file doesn't exist"); throw new LogicException("Fixture file doesn't exist");
} else if(substr($realFile,0,strlen($baseDir)) != $baseDir) { } elseif (substr($realFile, 0, strlen($baseDir)) != $baseDir) {
throw new LogicException("Fixture file must be inside $baseDir"); throw new LogicException("Fixture file must be inside $baseDir");
} else if(substr($realFile,-4) != '.yml') { } elseif (substr($realFile, -4) != '.yml') {
throw new LogicException("Fixture file must be a .yml file"); throw new LogicException("Fixture file must be a .yml file");
} else if(!preg_match('/^([^\/.][^\/]+)\/tests\//', $fixtureFile)) { } elseif (!preg_match('/^([^\/.][^\/]+)\/tests\//', $fixtureFile)) {
throw new LogicException("Fixture file must be inside the tests subfolder of one of your modules."); throw new LogicException("Fixture file must be inside the tests subfolder of one of your modules.");
} }
@ -389,15 +407,16 @@ 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;
$databaseConfig['database'] = $this->oldDatabaseName; $databaseConfig['database'] = $this->oldDatabaseName;
$conn = DB::get_conn(); $conn = DB::get_conn();
if($conn) { if ($conn) {
$conn->selectDatabase($this->oldDatabaseName, false, false); $conn->selectDatabase($this->oldDatabaseName, false, false);
} }
} }
@ -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,32 +2,37 @@
/** /**
* 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();
// Date and time // Date and time
if(isset($testState->datetime)) { if (isset($testState->datetime)) {
SS_Datetime::set_mock_now($testState->datetime); SS_Datetime::set_mock_now($testState->datetime);
} }
// Register mailer // Register mailer
if(isset($testState->mailer)) { if (isset($testState->mailer)) {
$mailer = $testState->mailer; $mailer = $testState->mailer;
Email::set_mailer(new $mailer()); Email::set_mailer(new $mailer());
Config::inst()->update("Email","send_all_emails_to", null); Config::inst()->update("Email", "send_all_emails_to", null);
} }
// Allows inclusion of a PHP file, usually with procedural commands // Allows inclusion of a PHP file, usually with procedural commands
@ -35,19 +40,24 @@ class TestSessionRequestFilter implements RequestFilter {
// through {@link TestSessionStubCodeWriter}, and the session state // through {@link TestSessionStubCodeWriter}, and the session state
// set through {@link TestSessionController->set()} and the // set through {@link TestSessionController->set()} and the
// 'testsession.stubfile' state parameter. // 'testsession.stubfile' state parameter.
if(isset($testState->stubfile)) { if (isset($testState->stubfile)) {
$file = $testState->stubfile; $file = $testState->stubfile;
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,15 +30,16 @@ 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 = '';
// Create file incl. header if it doesn't exist // Create file incl. header if it doesn't exist
if(!file_exists($this->getFilePath())) { if (!file_exists($this->getFilePath())) {
touch($this->getFilePath()); touch($this->getFilePath());
if($this->debug) { if ($this->debug) {
$header .= "<?php\n// Generated by " . $trace[1]['class'] . " on " . date('Y-m-d H:i:s') . "\n\n"; $header .= "<?php\n// Generated by " . $trace[1]['class'] . " on " . date('Y-m-d H:i:s') . "\n\n";
} else { } else {
$header .= "<?php\n"; $header .= "<?php\n";
@ -44,30 +47,33 @@ class TestSessionStubCodeWriter {
} }
// Add content // Add content
if($this->debug) { if ($this->debug) {
$header .= "// Added by " . $trace[1]['class'] . '::' . $trace[1]['function'] . "\n"; $header .= "// Added by " . $trace[1]['class'] . '::' . $trace[1]['function'] . "\n";
} }
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);
} }
} }