mirror of
https://github.com/silverstripe/silverstripe-testsession
synced 2024-10-22 14:06:00 +02:00
Converted to PSR-2
This commit is contained in:
parent
4015611673
commit
e40a0d0f1a
@ -2,7 +2,8 @@
|
||||
/**
|
||||
* 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(
|
||||
'index',
|
||||
@ -27,13 +28,15 @@ class TestSessionController extends Controller {
|
||||
*/
|
||||
protected $environment;
|
||||
|
||||
public function __construct() {
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->environment = Injector::inst()->get('TestSessionEnvironment');
|
||||
}
|
||||
|
||||
public function init() {
|
||||
public function init()
|
||||
{
|
||||
parent::init();
|
||||
|
||||
$this->extend('init');
|
||||
@ -42,18 +45,22 @@ class TestSessionController extends Controller {
|
||||
!Director::isLive()
|
||||
&& (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('testsession/javascript/testsession.js');
|
||||
}
|
||||
|
||||
public function Link($action = null) {
|
||||
public function Link($action = null)
|
||||
{
|
||||
return Controller::join_links(Director::baseUrl(), 'dev/testsession', $action);
|
||||
}
|
||||
|
||||
public function index() {
|
||||
if($this->environment->isRunningTests()) {
|
||||
public function index()
|
||||
{
|
||||
if ($this->environment->isRunningTests()) {
|
||||
return $this->renderWith('TestSession_inprogress');
|
||||
} else {
|
||||
return $this->renderWith('TestSession_start');
|
||||
@ -65,10 +72,11 @@ class TestSessionController extends Controller {
|
||||
* then take a look at {@link TestSessionEnvironment::startTestSession()} and
|
||||
* {@link TestSessionEnvironment::applyState()} to see the extension points.
|
||||
*/
|
||||
public function start() {
|
||||
public function start()
|
||||
{
|
||||
$params = $this->request->requestVars();
|
||||
|
||||
if(!empty($params['globalTestSession'])) {
|
||||
if (!empty($params['globalTestSession'])) {
|
||||
$id = null;
|
||||
} else {
|
||||
$generator = Injector::inst()->get('RandomGenerator');
|
||||
@ -94,17 +102,17 @@ class TestSessionController extends Controller {
|
||||
$this->environment->startTestSession($params, $id);
|
||||
|
||||
// Optionally import database
|
||||
if(!empty($params['importDatabasePath']) || !empty($params['importDatabaseFilename'])) {
|
||||
if (!empty($params['importDatabasePath']) || !empty($params['importDatabaseFilename'])) {
|
||||
$absPath = '';
|
||||
|
||||
// by path
|
||||
if(!empty($params['importDatabasePath'])) {
|
||||
if (!empty($params['importDatabasePath'])) {
|
||||
$absPath = $params['importDatabasePath'];
|
||||
|
||||
// by filename
|
||||
}else if(!empty($params['importDatabaseFilename'])) {
|
||||
foreach($this->getDatabaseTemplates() as $tAbsPath => $tFilename){
|
||||
if($tFilename === $params['importDatabaseFilename']){
|
||||
} elseif (!empty($params['importDatabaseFilename'])) {
|
||||
foreach ($this->getDatabaseTemplates() as $tAbsPath => $tFilename) {
|
||||
if ($tFilename === $params['importDatabaseFilename']) {
|
||||
$absPath = $tAbsPath;
|
||||
break;
|
||||
}
|
||||
@ -114,13 +122,13 @@ class TestSessionController extends Controller {
|
||||
$absPath,
|
||||
!empty($params['requireDefaultRecords']) ? $params['requireDefaultRecords'] : false
|
||||
);
|
||||
} else if(!empty($params['requireDefaultRecords']) && $params['requireDefaultRecords']) {
|
||||
} elseif (!empty($params['requireDefaultRecords']) && $params['requireDefaultRecords']) {
|
||||
$this->environment->requireDefaultRecords();
|
||||
}
|
||||
|
||||
// Fixtures
|
||||
$fixtureFile = (!empty($params['fixture'])) ? $params['fixture'] : null;
|
||||
if($fixtureFile) {
|
||||
if ($fixtureFile) {
|
||||
$this->environment->loadFixtureIntoDb($fixtureFile);
|
||||
}
|
||||
|
||||
@ -130,19 +138,20 @@ class TestSessionController extends Controller {
|
||||
/**
|
||||
* Set $_SESSION state for the current browser session.
|
||||
*/
|
||||
public function browsersessionstate($request) {
|
||||
if(!$this->environment->isRunningTests()) {
|
||||
public function browsersessionstate($request)
|
||||
{
|
||||
if (!$this->environment->isRunningTests()) {
|
||||
throw new LogicException("No test session in progress.");
|
||||
}
|
||||
|
||||
$newSessionStates = array_diff_key($request->getVars(), array('url' => true));
|
||||
if(!$newSessionStates) {
|
||||
if (!$newSessionStates) {
|
||||
throw new LogicException('No query parameters detected');
|
||||
}
|
||||
|
||||
$sessionStates = (array)Session::get('_TestSessionController.BrowserSessionState');
|
||||
|
||||
foreach($newSessionStates as $k => $v) {
|
||||
foreach ($newSessionStates as $k => $v) {
|
||||
Session::set($k, $v);
|
||||
}
|
||||
|
||||
@ -150,12 +159,13 @@ class TestSessionController extends Controller {
|
||||
Session::set('_TestSessionController.BrowserSessionState', array_merge($sessionStates, $newSessionStates));
|
||||
}
|
||||
|
||||
public function StartForm() {
|
||||
public function StartForm()
|
||||
{
|
||||
$databaseTemplates = $this->getDatabaseTemplates();
|
||||
$fields = new FieldList(
|
||||
new CheckboxField('createDatabase', 'Create temporary database?', 1)
|
||||
);
|
||||
if($databaseTemplates) {
|
||||
if ($databaseTemplates) {
|
||||
$fields->push(
|
||||
$dropdown = new DropdownField('importDatabasePath', false)
|
||||
);
|
||||
@ -164,7 +174,7 @@ class TestSessionController extends Controller {
|
||||
->setEmptyString('Empty database');
|
||||
}
|
||||
$fields->push(new CheckboxField('requireDefaultRecords', 'Create default data?'));
|
||||
if(Director::isDev()) {
|
||||
if (Director::isDev()) {
|
||||
$fields->push(
|
||||
CheckboxField::create('globalTestSession', 'Use global test session?')
|
||||
->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.
|
||||
*/
|
||||
public function ProgressForm() {
|
||||
public function ProgressForm()
|
||||
{
|
||||
$fields = $this->getBaseFields();
|
||||
$form = new Form(
|
||||
$this,
|
||||
@ -207,7 +218,8 @@ class TestSessionController extends Controller {
|
||||
return $form;
|
||||
}
|
||||
|
||||
protected function getBaseFields() {
|
||||
protected function getBaseFields()
|
||||
{
|
||||
$testState = $this->environment->getState();
|
||||
|
||||
$fields = new FieldList(
|
||||
@ -230,7 +242,8 @@ class TestSessionController extends Controller {
|
||||
return $fields;
|
||||
}
|
||||
|
||||
public function DatabaseName() {
|
||||
public function DatabaseName()
|
||||
{
|
||||
$db = DB::get_conn();
|
||||
return $db->getSelectedDatabase();
|
||||
}
|
||||
@ -242,8 +255,9 @@ class TestSessionController extends Controller {
|
||||
* @return HTMLText Rendered Template
|
||||
* @throws LogicException
|
||||
*/
|
||||
public function set() {
|
||||
if(!$this->environment->isRunningTests()) {
|
||||
public function set()
|
||||
{
|
||||
if (!$this->environment->isRunningTests()) {
|
||||
throw new LogicException("No test session in progress.");
|
||||
}
|
||||
|
||||
@ -269,18 +283,19 @@ class TestSessionController extends Controller {
|
||||
return $this->renderWith('TestSession_inprogress');
|
||||
}
|
||||
|
||||
public function clear() {
|
||||
if(!$this->environment->isRunningTests()) {
|
||||
public function clear()
|
||||
{
|
||||
if (!$this->environment->isRunningTests()) {
|
||||
throw new LogicException("No test session in progress.");
|
||||
}
|
||||
|
||||
$this->extend('onBeforeClear');
|
||||
|
||||
if(SapphireTest::using_temp_db()) {
|
||||
if (SapphireTest::using_temp_db()) {
|
||||
SapphireTest::empty_temp_db();
|
||||
}
|
||||
|
||||
if(isset($_SESSION['_testsession_codeblocks'])) {
|
||||
if (isset($_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
|
||||
* is there.
|
||||
*/
|
||||
public function end() {
|
||||
if(!$this->environment->isRunningTests()) {
|
||||
public function end()
|
||||
{
|
||||
if (!$this->environment->isRunningTests()) {
|
||||
throw new LogicException("No test session in progress.");
|
||||
}
|
||||
|
||||
@ -303,8 +319,8 @@ class TestSessionController extends Controller {
|
||||
Session::clear('TestSessionId');
|
||||
|
||||
// Clear out all PHP session states which have been set previously
|
||||
if($sessionStates = Session::get('_TestSessionController.BrowserSessionState')) {
|
||||
foreach($sessionStates as $k => $v) {
|
||||
if ($sessionStates = Session::get('_TestSessionController.BrowserSessionState')) {
|
||||
foreach ($sessionStates as $k => $v) {
|
||||
Session::clear($k);
|
||||
}
|
||||
Session::clear('_TestSessionController');
|
||||
@ -317,11 +333,13 @@ class TestSessionController extends Controller {
|
||||
/**
|
||||
* @return boolean
|
||||
*/
|
||||
public function isTesting() {
|
||||
public function isTesting()
|
||||
{
|
||||
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 '
|
||||
. 'TestSessionEnvironment instead.');
|
||||
}
|
||||
@ -329,12 +347,13 @@ class TestSessionController extends Controller {
|
||||
/**
|
||||
* @return ArrayList
|
||||
*/
|
||||
public function getState() {
|
||||
public function getState()
|
||||
{
|
||||
$stateObj = $this->environment->getState();
|
||||
$state = array();
|
||||
|
||||
// Convert the stdObject of state into ArrayData
|
||||
foreach($stateObj as $k => $v) {
|
||||
foreach ($stateObj as $k => $v) {
|
||||
$state[] = new ArrayData(array(
|
||||
'Name' => $k,
|
||||
'Value' => var_export($v, true)
|
||||
@ -351,22 +370,25 @@ class TestSessionController extends Controller {
|
||||
* @param String $path Absolute folder path
|
||||
* @return array
|
||||
*/
|
||||
protected function getDatabaseTemplates($path = null) {
|
||||
protected function getDatabaseTemplates($path = null)
|
||||
{
|
||||
$templates = array();
|
||||
|
||||
if(!$path) {
|
||||
if (!$path) {
|
||||
$path = $this->config()->database_templates_path;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
if($path && file_exists($path)) {
|
||||
if ($path && file_exists($path)) {
|
||||
$it = new FilesystemIterator($path);
|
||||
foreach($it as $fileinfo) {
|
||||
if($fileinfo->getExtension() != 'sql') continue;
|
||||
foreach ($it as $fileinfo) {
|
||||
if ($fileinfo->getExtension() != 'sql') {
|
||||
continue;
|
||||
}
|
||||
$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()
|
||||
* @return array The form fields, after fixing the datetime field if necessary
|
||||
*/
|
||||
private function fixDatetimeFormField($params) {
|
||||
if(isset($params['datetime']) && is_array($params['datetime']) && !empty($params['datetime']['date'])) {
|
||||
private function fixDatetimeFormField($params)
|
||||
{
|
||||
if (isset($params['datetime']) && is_array($params['datetime']) && !empty($params['datetime']['date'])) {
|
||||
// Convert DatetimeField format from array into string
|
||||
$datetime = $params['datetime']['date'];
|
||||
$datetime .= ' ';
|
||||
$datetime .= (@$params['datetime']['time']) ? $params['datetime']['time'] : '00:00:00';
|
||||
$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
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -24,7 +24,8 @@
|
||||
*
|
||||
* 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.
|
||||
@ -51,10 +52,11 @@ class TestSessionEnvironment extends Object {
|
||||
*/
|
||||
private static $test_state_id_file = 'TESTS_RUNNING-%s.json';
|
||||
|
||||
public function __construct($id = null) {
|
||||
public function __construct($id = null)
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
if($id) {
|
||||
if ($id) {
|
||||
$this->id = $id;
|
||||
} else {
|
||||
Session::start();
|
||||
@ -67,8 +69,9 @@ class TestSessionEnvironment extends Object {
|
||||
/**
|
||||
* @return String Absolute path to the file persisting our state.
|
||||
*/
|
||||
public function getFilePath() {
|
||||
if($this->id) {
|
||||
public function getFilePath()
|
||||
{
|
||||
if ($this->id) {
|
||||
$path = Director::getAbsFile(sprintf($this->config()->test_state_id_file, $this->id));
|
||||
} else {
|
||||
$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
|
||||
*/
|
||||
public function isRunningTests() {
|
||||
public function isRunningTests()
|
||||
{
|
||||
return(file_exists($this->getFilePath()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param String $id
|
||||
*/
|
||||
public function setId($id) {
|
||||
public function setId($id)
|
||||
{
|
||||
$this->id = $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return String
|
||||
*/
|
||||
public function getId() {
|
||||
public function getId()
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
@ -111,8 +117,11 @@ class TestSessionEnvironment extends Object {
|
||||
*
|
||||
* @param array $state An array of test state options to write.
|
||||
*/
|
||||
public function startTestSession($state = null, $id = null) {
|
||||
if(!$state) $state = array();
|
||||
public function startTestSession($state = null, $id = null)
|
||||
{
|
||||
if (!$state) {
|
||||
$state = array();
|
||||
}
|
||||
$this->removeStateFile();
|
||||
$this->id = $id;
|
||||
|
||||
@ -128,7 +137,8 @@ class TestSessionEnvironment extends Object {
|
||||
$this->extend('onAfterStartTestSession');
|
||||
}
|
||||
|
||||
public function updateTestSession($state) {
|
||||
public function updateTestSession($state)
|
||||
{
|
||||
$this->extend('onBeforeUpdateTestSession', $state);
|
||||
|
||||
// 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 InvalidArgumentException
|
||||
*/
|
||||
public function applyState($state) {
|
||||
public function applyState($state)
|
||||
{
|
||||
$this->extend('onBeforeApplyState', $state);
|
||||
|
||||
$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
|
||||
$oldState = $this->getState();
|
||||
|
||||
if($oldState) {
|
||||
foreach($oldState as $k => $v) {
|
||||
if(!isset($state->$k)) {
|
||||
if ($oldState) {
|
||||
foreach ($oldState as $k => $v) {
|
||||
if (!isset($state->$k)) {
|
||||
$state->$k = $v; // Don't overwrite stuff in $state, as that's the new state
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ensure we have a connection to the database
|
||||
if(isset($state->database) && $state->database) {
|
||||
if(!DB::get_conn()) {
|
||||
if (isset($state->database) && $state->database) {
|
||||
if (!DB::get_conn()) {
|
||||
// No connection, so try and connect to tmpdb if it exists
|
||||
if(isset($state->database)) {
|
||||
if (isset($state->database)) {
|
||||
$this->oldDatabaseName = $databaseConfig['database'];
|
||||
$databaseConfig['database'] = $state->database;
|
||||
}
|
||||
@ -186,7 +197,7 @@ class TestSessionEnvironment extends Object {
|
||||
} else {
|
||||
// We've already connected to the database, do a fast check to see what database we're currently using
|
||||
$db = DB::get_conn()->getSelectedDatabase();
|
||||
if(isset($state->database) && $db != $state->database) {
|
||||
if (isset($state->database) && $db != $state->database) {
|
||||
$this->oldDatabaseName = $databaseConfig['database'];
|
||||
$databaseConfig['database'] = $state->database;
|
||||
DB::connect($databaseConfig);
|
||||
@ -195,16 +206,16 @@ class TestSessionEnvironment extends Object {
|
||||
}
|
||||
|
||||
// Database
|
||||
if(!$this->isRunningTests()) {
|
||||
if (!$this->isRunningTests()) {
|
||||
$dbName = (isset($state->database)) ? $state->database : null;
|
||||
|
||||
if($dbName) {
|
||||
if ($dbName) {
|
||||
$dbExists = DB::get_conn()->databaseExists($dbName);
|
||||
} else {
|
||||
$dbExists = false;
|
||||
}
|
||||
|
||||
if(!$dbExists) {
|
||||
if (!$dbExists) {
|
||||
// Create a new one with a randomized name
|
||||
$dbName = SapphireTest::create_temp_db();
|
||||
|
||||
@ -213,7 +224,7 @@ class TestSessionEnvironment extends Object {
|
||||
// Set existing one, assumes it already has been created
|
||||
$prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
|
||||
$pattern = strtolower(sprintf('#^%stmpdb\d{7}#', $prefix));
|
||||
if(!preg_match($pattern, $dbName)) {
|
||||
if (!preg_match($pattern, $dbName)) {
|
||||
throw new InvalidArgumentException("Invalid database name format");
|
||||
}
|
||||
|
||||
@ -228,8 +239,8 @@ class TestSessionEnvironment extends Object {
|
||||
// Mailer
|
||||
$mailer = (isset($state->mailer)) ? $state->mailer : null;
|
||||
|
||||
if($mailer) {
|
||||
if(!class_exists($mailer) || !is_subclass_of($mailer, 'Mailer')) {
|
||||
if ($mailer) {
|
||||
if (!class_exists($mailer) || !is_subclass_of($mailer, 'Mailer')) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'Class "%s" is not a valid class, or subclass of Mailer',
|
||||
$mailer
|
||||
@ -238,10 +249,10 @@ class TestSessionEnvironment extends Object {
|
||||
}
|
||||
|
||||
// Date and time
|
||||
if(isset($state->datetime)) {
|
||||
if (isset($state->datetime)) {
|
||||
require_once 'Zend/Date.php';
|
||||
// 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(
|
||||
'Invalid date format "%s", use yyyy-MM-dd HH:mm:ss',
|
||||
$state->datetime
|
||||
@ -259,7 +270,8 @@ class TestSessionEnvironment extends Object {
|
||||
* @param String $path Absolute path to a SQL dump (include DROP TABLE commands)
|
||||
* @return void
|
||||
*/
|
||||
public function importDatabase($path, $requireDefaultRecords = false) {
|
||||
public function importDatabase($path, $requireDefaultRecords = false)
|
||||
{
|
||||
$sql = file_get_contents($path);
|
||||
|
||||
// Split into individual query commands, removing comments
|
||||
@ -270,7 +282,7 @@ class TestSessionEnvironment extends Object {
|
||||
);
|
||||
|
||||
// Execute each query
|
||||
foreach($sqlCmds as $sqlCmd) {
|
||||
foreach ($sqlCmds as $sqlCmd) {
|
||||
DB::query($sqlCmd);
|
||||
}
|
||||
|
||||
@ -283,7 +295,8 @@ class TestSessionEnvironment extends Object {
|
||||
/**
|
||||
* Build the database with default records, see {@link DataObject->requireDefaultRecords()}.
|
||||
*/
|
||||
public function requireDefaultRecords() {
|
||||
public function requireDefaultRecords()
|
||||
{
|
||||
$dbAdmin = new DatabaseAdmin();
|
||||
Versioned::set_reading_mode('');
|
||||
$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
|
||||
* to modify.
|
||||
*/
|
||||
public function saveState($state) {
|
||||
public function saveState($state)
|
||||
{
|
||||
if (defined('JSON_PRETTY_PRINT')) {
|
||||
$content = json_encode($state, JSON_PRETTY_PRINT);
|
||||
} else {
|
||||
@ -304,14 +318,15 @@ class TestSessionEnvironment extends Object {
|
||||
umask($old);
|
||||
}
|
||||
|
||||
public function loadFromFile() {
|
||||
if($this->isRunningTests()) {
|
||||
public function loadFromFile()
|
||||
{
|
||||
if ($this->isRunningTests()) {
|
||||
try {
|
||||
$contents = file_get_contents($this->getFilePath());
|
||||
$json = json_decode($contents);
|
||||
|
||||
$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. "
|
||||
. "Try removing the " . $this->getFilePath() . " file. Inner "
|
||||
. "error: " . $e->getMessage());
|
||||
@ -319,11 +334,12 @@ class TestSessionEnvironment extends Object {
|
||||
}
|
||||
}
|
||||
|
||||
private function removeStateFile() {
|
||||
private function removeStateFile()
|
||||
{
|
||||
$file = $this->getFilePath();
|
||||
|
||||
if(file_exists($file)) {
|
||||
if(!unlink($file)) {
|
||||
if (file_exists($file)) {
|
||||
if (!unlink($file)) {
|
||||
throw new \Exception('Unable to remove the testsession state file, please remove it manually. 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
|
||||
* 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');
|
||||
|
||||
if(SapphireTest::using_temp_db()) {
|
||||
if (SapphireTest::using_temp_db()) {
|
||||
$this->resetDatabaseName();
|
||||
|
||||
SapphireTest::set_is_running_test(false);
|
||||
@ -362,16 +379,17 @@ class TestSessionEnvironment extends Object {
|
||||
* @return FixtureFactory The loaded fixture
|
||||
* @throws LogicException
|
||||
*/
|
||||
public function loadFixtureIntoDb($fixtureFile) {
|
||||
public function loadFixtureIntoDb($fixtureFile)
|
||||
{
|
||||
$realFile = realpath(BASE_PATH.'/'.$fixtureFile);
|
||||
$baseDir = realpath(Director::baseFolder());
|
||||
if(!$realFile || !file_exists($realFile)) {
|
||||
if (!$realFile || !file_exists($realFile)) {
|
||||
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");
|
||||
} else if(substr($realFile,-4) != '.yml') {
|
||||
} elseif (substr($realFile, -4) != '.yml') {
|
||||
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.");
|
||||
}
|
||||
|
||||
@ -389,15 +407,16 @@ class TestSessionEnvironment extends Object {
|
||||
/**
|
||||
* Reset the database connection to use the original database. Called by {@link self::endTestSession()}.
|
||||
*/
|
||||
public function resetDatabaseName() {
|
||||
if($this->oldDatabaseName) {
|
||||
public function resetDatabaseName()
|
||||
{
|
||||
if ($this->oldDatabaseName) {
|
||||
global $databaseConfig;
|
||||
|
||||
$databaseConfig['database'] = $this->oldDatabaseName;
|
||||
|
||||
$conn = DB::get_conn();
|
||||
|
||||
if($conn) {
|
||||
if ($conn) {
|
||||
$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()}
|
||||
*/
|
||||
public function getState() {
|
||||
public function getState()
|
||||
{
|
||||
$path = Director::getAbsFile($this->getFilePath());
|
||||
return (file_exists($path)) ? json_decode(file_get_contents($path)) : new stdClass;
|
||||
}
|
||||
|
@ -2,32 +2,37 @@
|
||||
/**
|
||||
* Sets state previously initialized through {@link TestSessionController}.
|
||||
*/
|
||||
class TestSessionRequestFilter implements RequestFilter {
|
||||
class TestSessionRequestFilter implements RequestFilter
|
||||
{
|
||||
|
||||
/**
|
||||
* @var TestSessionEnvironment
|
||||
*/
|
||||
protected $testSessionEnvironment;
|
||||
|
||||
public function __construct() {
|
||||
public function __construct()
|
||||
{
|
||||
$this->testSessionEnvironment = Injector::inst()->get('TestSessionEnvironment');
|
||||
}
|
||||
|
||||
public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model) {
|
||||
if(!$this->testSessionEnvironment->isRunningTests()) return;
|
||||
public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model)
|
||||
{
|
||||
if (!$this->testSessionEnvironment->isRunningTests()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$testState = $this->testSessionEnvironment->getState();
|
||||
|
||||
// Date and time
|
||||
if(isset($testState->datetime)) {
|
||||
if (isset($testState->datetime)) {
|
||||
SS_Datetime::set_mock_now($testState->datetime);
|
||||
}
|
||||
|
||||
// Register mailer
|
||||
if(isset($testState->mailer)) {
|
||||
if (isset($testState->mailer)) {
|
||||
$mailer = $testState->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
|
||||
@ -35,19 +40,24 @@ class TestSessionRequestFilter implements RequestFilter {
|
||||
// through {@link TestSessionStubCodeWriter}, and the session state
|
||||
// set through {@link TestSessionController->set()} and the
|
||||
// 'testsession.stubfile' state parameter.
|
||||
if(isset($testState->stubfile)) {
|
||||
if (isset($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
|
||||
global $databaseConfig;
|
||||
if ($databaseConfig) DB::connect($databaseConfig);
|
||||
if ($databaseConfig) {
|
||||
DB::connect($databaseConfig);
|
||||
}
|
||||
include_once($file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model) {
|
||||
if(!$this->testSessionEnvironment->isRunningTests()) return;
|
||||
public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
|
||||
{
|
||||
if (!$this->testSessionEnvironment->isRunningTests()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Store PHP session
|
||||
$state = $this->testSessionEnvironment->getState();
|
||||
|
@ -3,7 +3,8 @@
|
||||
* 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}.
|
||||
*/
|
||||
class TestSessionStubCodeWriter {
|
||||
class TestSessionStubCodeWriter
|
||||
{
|
||||
|
||||
/**
|
||||
* @var boolean Add debug statements to the generated PHP about
|
||||
@ -16,7 +17,8 @@ class TestSessionStubCodeWriter {
|
||||
*/
|
||||
protected $filePath;
|
||||
|
||||
public function __construct($filePath = null) {
|
||||
public function __construct($filePath = null)
|
||||
{
|
||||
$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 boolean $eval Sanity check on code.
|
||||
*/
|
||||
public function write($php, $eval = true) {
|
||||
public function write($php, $eval = true)
|
||||
{
|
||||
$trace = $this->debug ? debug_backtrace() : null;
|
||||
$path = $this->getFilePath();
|
||||
$header = '';
|
||||
|
||||
// Create file incl. header if it doesn't exist
|
||||
if(!file_exists($this->getFilePath())) {
|
||||
if (!file_exists($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";
|
||||
} else {
|
||||
$header .= "<?php\n";
|
||||
@ -44,30 +47,33 @@ class TestSessionStubCodeWriter {
|
||||
}
|
||||
|
||||
// Add content
|
||||
if($this->debug) {
|
||||
if ($this->debug) {
|
||||
$header .= "// Added by " . $trace[1]['class'] . '::' . $trace[1]['function'] . "\n";
|
||||
}
|
||||
file_put_contents($path, $header . $php . "\n", FILE_APPEND);
|
||||
}
|
||||
|
||||
public function reset() {
|
||||
if(file_exists($this->getFilePath())) {
|
||||
public function reset()
|
||||
{
|
||||
if (file_exists($this->getFilePath())) {
|
||||
unlink($this->getFilePath());
|
||||
}
|
||||
}
|
||||
|
||||
public function getFilePath() {
|
||||
public function getFilePath()
|
||||
{
|
||||
return $this->filePath;
|
||||
}
|
||||
|
||||
public function getDebug() {
|
||||
public function getDebug()
|
||||
{
|
||||
return $this->debug;
|
||||
}
|
||||
|
||||
public function setDebug($debug) {
|
||||
public function setDebug($debug)
|
||||
{
|
||||
$this->debug = $debug;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
}
|
@ -1,14 +1,19 @@
|
||||
<?php
|
||||
class TestSessionStubCodeWriterTest extends SapphireTest {
|
||||
class TestSessionStubCodeWriterTest extends SapphireTest
|
||||
{
|
||||
|
||||
public function tearDown() {
|
||||
public function tearDown()
|
||||
{
|
||||
parent::tearDown();
|
||||
|
||||
$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';
|
||||
$writer = new TestSessionStubCodeWriter($file);
|
||||
$writer->write('foo();', false);
|
||||
@ -19,7 +24,8 @@ class TestSessionStubCodeWriterTest extends SapphireTest {
|
||||
);
|
||||
}
|
||||
|
||||
public function testWritesWithAppendOnExistingFile() {
|
||||
public function testWritesWithAppendOnExistingFile()
|
||||
{
|
||||
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
|
||||
$writer = new TestSessionStubCodeWriter($file);
|
||||
$writer->write('foo();', false);
|
||||
@ -31,7 +37,8 @@ class TestSessionStubCodeWriterTest extends SapphireTest {
|
||||
);
|
||||
}
|
||||
|
||||
public function testReset() {
|
||||
public function testReset()
|
||||
{
|
||||
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
|
||||
$writer = new TestSessionStubCodeWriter($file);
|
||||
$writer->write('foo();', false);
|
||||
@ -39,5 +46,4 @@ class TestSessionStubCodeWriterTest extends SapphireTest {
|
||||
$writer->reset();
|
||||
$this->assertFileNotExists($file);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user