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,394 +2,416 @@
|
|||||||
/**
|
/**
|
||||||
* 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(
|
|
||||||
'index',
|
private static $allowed_actions = array(
|
||||||
'start',
|
'index',
|
||||||
'set',
|
'start',
|
||||||
'end',
|
'set',
|
||||||
'clear',
|
'end',
|
||||||
'browsersessionstate',
|
'clear',
|
||||||
'StartForm',
|
'browsersessionstate',
|
||||||
'ProgressForm',
|
'StartForm',
|
||||||
);
|
'ProgressForm',
|
||||||
|
);
|
||||||
private static $alternative_database_name = -1;
|
|
||||||
|
private static $alternative_database_name = -1;
|
||||||
/**
|
|
||||||
* @var String Absolute path to a folder containing *.sql dumps.
|
/**
|
||||||
*/
|
* @var String Absolute path to a folder containing *.sql dumps.
|
||||||
private static $database_templates_path;
|
*/
|
||||||
|
private static $database_templates_path;
|
||||||
/**
|
|
||||||
* @var TestSessionEnvironment
|
/**
|
||||||
*/
|
* @var TestSessionEnvironment
|
||||||
protected $environment;
|
*/
|
||||||
|
protected $environment;
|
||||||
public function __construct() {
|
|
||||||
parent::__construct();
|
public function __construct()
|
||||||
|
{
|
||||||
$this->environment = Injector::inst()->get('TestSessionEnvironment');
|
parent::__construct();
|
||||||
}
|
|
||||||
|
$this->environment = Injector::inst()->get('TestSessionEnvironment');
|
||||||
public function init() {
|
}
|
||||||
parent::init();
|
|
||||||
|
public function init()
|
||||||
$this->extend('init');
|
{
|
||||||
|
parent::init();
|
||||||
$canAccess = (
|
|
||||||
!Director::isLive()
|
$this->extend('init');
|
||||||
&& (Director::isDev() || Director::isTest() || Director::is_cli() || Permission::check("ADMIN"))
|
|
||||||
);
|
$canAccess = (
|
||||||
if(!$canAccess) return Security::permissionFailure($this);
|
!Director::isLive()
|
||||||
|
&& (Director::isDev() || Director::isTest() || Director::is_cli() || Permission::check("ADMIN"))
|
||||||
Requirements::javascript('framework/thirdparty/jquery/jquery.js');
|
);
|
||||||
Requirements::javascript('testsession/javascript/testsession.js');
|
if (!$canAccess) {
|
||||||
}
|
return Security::permissionFailure($this);
|
||||||
|
}
|
||||||
public function Link($action = null) {
|
|
||||||
return Controller::join_links(Director::baseUrl(), 'dev/testsession', $action);
|
Requirements::javascript('framework/thirdparty/jquery/jquery.js');
|
||||||
}
|
Requirements::javascript('testsession/javascript/testsession.js');
|
||||||
|
}
|
||||||
public function index() {
|
|
||||||
if($this->environment->isRunningTests()) {
|
public function Link($action = null)
|
||||||
return $this->renderWith('TestSession_inprogress');
|
{
|
||||||
} else {
|
return Controller::join_links(Director::baseUrl(), 'dev/testsession', $action);
|
||||||
return $this->renderWith('TestSession_start');
|
}
|
||||||
}
|
|
||||||
}
|
public function index()
|
||||||
|
{
|
||||||
/**
|
if ($this->environment->isRunningTests()) {
|
||||||
* Start a test session. If you wish to extend how the test session is started (and add additional test state),
|
return $this->renderWith('TestSession_inprogress');
|
||||||
* then take a look at {@link TestSessionEnvironment::startTestSession()} and
|
} else {
|
||||||
* {@link TestSessionEnvironment::applyState()} to see the extension points.
|
return $this->renderWith('TestSession_start');
|
||||||
*/
|
}
|
||||||
public function start() {
|
}
|
||||||
$params = $this->request->requestVars();
|
|
||||||
|
/**
|
||||||
if(!empty($params['globalTestSession'])) {
|
* Start a test session. If you wish to extend how the test session is started (and add additional test state),
|
||||||
$id = null;
|
* then take a look at {@link TestSessionEnvironment::startTestSession()} and
|
||||||
} else {
|
* {@link TestSessionEnvironment::applyState()} to see the extension points.
|
||||||
$generator = Injector::inst()->get('RandomGenerator');
|
*/
|
||||||
$id = substr($generator->randomToken(), 0, 10);
|
public function start()
|
||||||
Session::set('TestSessionId', $id);
|
{
|
||||||
}
|
$params = $this->request->requestVars();
|
||||||
|
|
||||||
// Convert datetime from form object into a single string
|
if (!empty($params['globalTestSession'])) {
|
||||||
$params = $this->fixDatetimeFormField($params);
|
$id = null;
|
||||||
|
} else {
|
||||||
// Remove unnecessary items of form-specific data from being saved in the test session
|
$generator = Injector::inst()->get('RandomGenerator');
|
||||||
$params = array_diff_key(
|
$id = substr($generator->randomToken(), 0, 10);
|
||||||
$params,
|
Session::set('TestSessionId', $id);
|
||||||
array(
|
}
|
||||||
'action_set' => true,
|
|
||||||
'action_start' => true,
|
// Convert datetime from form object into a single string
|
||||||
'SecurityID' => true,
|
$params = $this->fixDatetimeFormField($params);
|
||||||
'url' => true,
|
|
||||||
'flush' => true,
|
// Remove unnecessary items of form-specific data from being saved in the test session
|
||||||
)
|
$params = array_diff_key(
|
||||||
);
|
$params,
|
||||||
|
array(
|
||||||
$this->environment->startTestSession($params, $id);
|
'action_set' => true,
|
||||||
|
'action_start' => true,
|
||||||
// Optionally import database
|
'SecurityID' => true,
|
||||||
if(!empty($params['importDatabasePath']) || !empty($params['importDatabaseFilename'])) {
|
'url' => true,
|
||||||
$absPath = '';
|
'flush' => true,
|
||||||
|
)
|
||||||
// by path
|
);
|
||||||
if(!empty($params['importDatabasePath'])) {
|
|
||||||
$absPath = $params['importDatabasePath'];
|
$this->environment->startTestSession($params, $id);
|
||||||
|
|
||||||
// by filename
|
// Optionally import database
|
||||||
}else if(!empty($params['importDatabaseFilename'])) {
|
if (!empty($params['importDatabasePath']) || !empty($params['importDatabaseFilename'])) {
|
||||||
foreach($this->getDatabaseTemplates() as $tAbsPath => $tFilename){
|
$absPath = '';
|
||||||
if($tFilename === $params['importDatabaseFilename']){
|
|
||||||
$absPath = $tAbsPath;
|
// by path
|
||||||
break;
|
if (!empty($params['importDatabasePath'])) {
|
||||||
}
|
$absPath = $params['importDatabasePath'];
|
||||||
}
|
|
||||||
}
|
// by filename
|
||||||
$this->environment->importDatabase(
|
} elseif (!empty($params['importDatabaseFilename'])) {
|
||||||
$absPath,
|
foreach ($this->getDatabaseTemplates() as $tAbsPath => $tFilename) {
|
||||||
!empty($params['requireDefaultRecords']) ? $params['requireDefaultRecords'] : false
|
if ($tFilename === $params['importDatabaseFilename']) {
|
||||||
);
|
$absPath = $tAbsPath;
|
||||||
} else if(!empty($params['requireDefaultRecords']) && $params['requireDefaultRecords']) {
|
break;
|
||||||
$this->environment->requireDefaultRecords();
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
// Fixtures
|
$this->environment->importDatabase(
|
||||||
$fixtureFile = (!empty($params['fixture'])) ? $params['fixture'] : null;
|
$absPath,
|
||||||
if($fixtureFile) {
|
!empty($params['requireDefaultRecords']) ? $params['requireDefaultRecords'] : false
|
||||||
$this->environment->loadFixtureIntoDb($fixtureFile);
|
);
|
||||||
}
|
} elseif (!empty($params['requireDefaultRecords']) && $params['requireDefaultRecords']) {
|
||||||
|
$this->environment->requireDefaultRecords();
|
||||||
return $this->renderWith('TestSession_inprogress');
|
}
|
||||||
}
|
|
||||||
|
// Fixtures
|
||||||
/**
|
$fixtureFile = (!empty($params['fixture'])) ? $params['fixture'] : null;
|
||||||
* Set $_SESSION state for the current browser session.
|
if ($fixtureFile) {
|
||||||
*/
|
$this->environment->loadFixtureIntoDb($fixtureFile);
|
||||||
public function browsersessionstate($request) {
|
}
|
||||||
if(!$this->environment->isRunningTests()) {
|
|
||||||
throw new LogicException("No test session in progress.");
|
return $this->renderWith('TestSession_inprogress');
|
||||||
}
|
}
|
||||||
|
|
||||||
$newSessionStates = array_diff_key($request->getVars(), array('url' => true));
|
/**
|
||||||
if(!$newSessionStates) {
|
* Set $_SESSION state for the current browser session.
|
||||||
throw new LogicException('No query parameters detected');
|
*/
|
||||||
}
|
public function browsersessionstate($request)
|
||||||
|
{
|
||||||
$sessionStates = (array)Session::get('_TestSessionController.BrowserSessionState');
|
if (!$this->environment->isRunningTests()) {
|
||||||
|
throw new LogicException("No test session in progress.");
|
||||||
foreach($newSessionStates as $k => $v) {
|
}
|
||||||
Session::set($k, $v);
|
|
||||||
}
|
$newSessionStates = array_diff_key($request->getVars(), array('url' => true));
|
||||||
|
if (!$newSessionStates) {
|
||||||
// Track which state we're setting so we can unset later in end()
|
throw new LogicException('No query parameters detected');
|
||||||
Session::set('_TestSessionController.BrowserSessionState', array_merge($sessionStates, $newSessionStates));
|
}
|
||||||
}
|
|
||||||
|
$sessionStates = (array)Session::get('_TestSessionController.BrowserSessionState');
|
||||||
public function StartForm() {
|
|
||||||
$databaseTemplates = $this->getDatabaseTemplates();
|
foreach ($newSessionStates as $k => $v) {
|
||||||
$fields = new FieldList(
|
Session::set($k, $v);
|
||||||
new CheckboxField('createDatabase', 'Create temporary database?', 1)
|
}
|
||||||
);
|
|
||||||
if($databaseTemplates) {
|
// Track which state we're setting so we can unset later in end()
|
||||||
$fields->push(
|
Session::set('_TestSessionController.BrowserSessionState', array_merge($sessionStates, $newSessionStates));
|
||||||
$dropdown = new DropdownField('importDatabasePath', false)
|
}
|
||||||
);
|
|
||||||
|
public function StartForm()
|
||||||
$dropdown->setSource($databaseTemplates)
|
{
|
||||||
->setEmptyString('Empty database');
|
$databaseTemplates = $this->getDatabaseTemplates();
|
||||||
}
|
$fields = new FieldList(
|
||||||
$fields->push(new CheckboxField('requireDefaultRecords', 'Create default data?'));
|
new CheckboxField('createDatabase', 'Create temporary database?', 1)
|
||||||
if(Director::isDev()) {
|
);
|
||||||
$fields->push(
|
if ($databaseTemplates) {
|
||||||
CheckboxField::create('globalTestSession', 'Use global test session?')
|
$fields->push(
|
||||||
->setDescription('Caution: Will apply to all users across browsers')
|
$dropdown = new DropdownField('importDatabasePath', false)
|
||||||
);
|
);
|
||||||
}
|
|
||||||
$fields->merge($this->getBaseFields());
|
$dropdown->setSource($databaseTemplates)
|
||||||
$form = new Form(
|
->setEmptyString('Empty database');
|
||||||
$this,
|
}
|
||||||
'StartForm',
|
$fields->push(new CheckboxField('requireDefaultRecords', 'Create default data?'));
|
||||||
$fields,
|
if (Director::isDev()) {
|
||||||
new FieldList(
|
$fields->push(
|
||||||
new FormAction('start', 'Start Session')
|
CheckboxField::create('globalTestSession', 'Use global test session?')
|
||||||
)
|
->setDescription('Caution: Will apply to all users across browsers')
|
||||||
);
|
);
|
||||||
|
}
|
||||||
$this->extend('updateStartForm', $form);
|
$fields->merge($this->getBaseFields());
|
||||||
|
$form = new Form(
|
||||||
return $form;
|
$this,
|
||||||
}
|
'StartForm',
|
||||||
|
$fields,
|
||||||
/**
|
new FieldList(
|
||||||
* Shows state which is allowed to be modified while a test session is in progress.
|
new FormAction('start', 'Start Session')
|
||||||
*/
|
)
|
||||||
public function ProgressForm() {
|
);
|
||||||
$fields = $this->getBaseFields();
|
|
||||||
$form = new Form(
|
$this->extend('updateStartForm', $form);
|
||||||
$this,
|
|
||||||
'ProgressForm',
|
return $form;
|
||||||
$fields,
|
}
|
||||||
new FieldList(
|
|
||||||
new FormAction('set', 'Set testing state')
|
/**
|
||||||
)
|
* Shows state which is allowed to be modified while a test session is in progress.
|
||||||
);
|
*/
|
||||||
|
public function ProgressForm()
|
||||||
|
{
|
||||||
$form->setFormAction($this->Link('set'));
|
$fields = $this->getBaseFields();
|
||||||
|
$form = new Form(
|
||||||
$this->extend('updateProgressForm', $form);
|
$this,
|
||||||
|
'ProgressForm',
|
||||||
return $form;
|
$fields,
|
||||||
}
|
new FieldList(
|
||||||
|
new FormAction('set', 'Set testing state')
|
||||||
protected function getBaseFields() {
|
)
|
||||||
$testState = $this->environment->getState();
|
);
|
||||||
|
|
||||||
$fields = new FieldList(
|
|
||||||
$textfield = new TextField('fixture', 'Fixture YAML file path'),
|
$form->setFormAction($this->Link('set'));
|
||||||
$datetimeField = new DatetimeField('datetime', 'Custom date'),
|
|
||||||
new HiddenField('flush', null, 1)
|
$this->extend('updateProgressForm', $form);
|
||||||
);
|
|
||||||
$textfield->setAttribute('placeholder', 'Example: framework/tests/security/MemberTest.yml');
|
return $form;
|
||||||
$datetimeField->getDateField()
|
}
|
||||||
->setConfig('dateformat', 'yyyy-MM-dd')
|
|
||||||
->setConfig('showcalendar', true)
|
protected function getBaseFields()
|
||||||
->setAttribute('placeholder', 'Date (yyyy-MM-dd)');
|
{
|
||||||
$datetimeField->getTimeField()
|
$testState = $this->environment->getState();
|
||||||
->setConfig('timeformat', 'HH:mm:ss')
|
|
||||||
->setAttribute('placeholder', 'Time (HH:mm:ss)');
|
$fields = new FieldList(
|
||||||
$datetimeField->setValue((isset($testState->datetime) ? $testState->datetime : null));
|
$textfield = new TextField('fixture', 'Fixture YAML file path'),
|
||||||
|
$datetimeField = new DatetimeField('datetime', 'Custom date'),
|
||||||
$this->extend('updateBaseFields', $fields);
|
new HiddenField('flush', null, 1)
|
||||||
|
);
|
||||||
return $fields;
|
$textfield->setAttribute('placeholder', 'Example: framework/tests/security/MemberTest.yml');
|
||||||
}
|
$datetimeField->getDateField()
|
||||||
|
->setConfig('dateformat', 'yyyy-MM-dd')
|
||||||
public function DatabaseName() {
|
->setConfig('showcalendar', true)
|
||||||
$db = DB::get_conn();
|
->setAttribute('placeholder', 'Date (yyyy-MM-dd)');
|
||||||
return $db->getSelectedDatabase();
|
$datetimeField->getTimeField()
|
||||||
}
|
->setConfig('timeformat', 'HH:mm:ss')
|
||||||
|
->setAttribute('placeholder', 'Time (HH:mm:ss)');
|
||||||
/**
|
$datetimeField->setValue((isset($testState->datetime) ? $testState->datetime : null));
|
||||||
* Updates an in-progress {@link TestSessionEnvironment} object with new details. This could be loading in new
|
|
||||||
* fixtures, setting the mocked date to another value etc.
|
$this->extend('updateBaseFields', $fields);
|
||||||
*
|
|
||||||
* @return HTMLText Rendered Template
|
return $fields;
|
||||||
* @throws LogicException
|
}
|
||||||
*/
|
|
||||||
public function set() {
|
public function DatabaseName()
|
||||||
if(!$this->environment->isRunningTests()) {
|
{
|
||||||
throw new LogicException("No test session in progress.");
|
$db = DB::get_conn();
|
||||||
}
|
return $db->getSelectedDatabase();
|
||||||
|
}
|
||||||
$params = $this->request->requestVars();
|
|
||||||
|
/**
|
||||||
// Convert datetime from form object into a single string
|
* Updates an in-progress {@link TestSessionEnvironment} object with new details. This could be loading in new
|
||||||
$params = $this->fixDatetimeFormField($params);
|
* fixtures, setting the mocked date to another value etc.
|
||||||
|
*
|
||||||
// Remove unnecessary items of form-specific data from being saved in the test session
|
* @return HTMLText Rendered Template
|
||||||
$params = array_diff_key(
|
* @throws LogicException
|
||||||
$params,
|
*/
|
||||||
array(
|
public function set()
|
||||||
'action_set' => true,
|
{
|
||||||
'action_start' => true,
|
if (!$this->environment->isRunningTests()) {
|
||||||
'SecurityID' => true,
|
throw new LogicException("No test session in progress.");
|
||||||
'url' => true,
|
}
|
||||||
'flush' => true,
|
|
||||||
)
|
$params = $this->request->requestVars();
|
||||||
);
|
|
||||||
|
// Convert datetime from form object into a single string
|
||||||
$this->environment->updateTestSession($params);
|
$params = $this->fixDatetimeFormField($params);
|
||||||
|
|
||||||
return $this->renderWith('TestSession_inprogress');
|
// Remove unnecessary items of form-specific data from being saved in the test session
|
||||||
}
|
$params = array_diff_key(
|
||||||
|
$params,
|
||||||
public function clear() {
|
array(
|
||||||
if(!$this->environment->isRunningTests()) {
|
'action_set' => true,
|
||||||
throw new LogicException("No test session in progress.");
|
'action_start' => true,
|
||||||
}
|
'SecurityID' => true,
|
||||||
|
'url' => true,
|
||||||
$this->extend('onBeforeClear');
|
'flush' => true,
|
||||||
|
)
|
||||||
if(SapphireTest::using_temp_db()) {
|
);
|
||||||
SapphireTest::empty_temp_db();
|
|
||||||
}
|
$this->environment->updateTestSession($params);
|
||||||
|
|
||||||
if(isset($_SESSION['_testsession_codeblocks'])) {
|
return $this->renderWith('TestSession_inprogress');
|
||||||
unset($_SESSION['_testsession_codeblocks']);
|
}
|
||||||
}
|
|
||||||
|
public function clear()
|
||||||
$this->extend('onAfterClear');
|
{
|
||||||
|
if (!$this->environment->isRunningTests()) {
|
||||||
return "Cleared database and test state";
|
throw new LogicException("No test session in progress.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
$this->extend('onBeforeClear');
|
||||||
* As with {@link self::start()}, if you want to extend the functionality of this, then look at
|
|
||||||
* {@link TestSessionEnvironent::endTestSession()} as the extension points have moved to there now that the logic
|
if (SapphireTest::using_temp_db()) {
|
||||||
* is there.
|
SapphireTest::empty_temp_db();
|
||||||
*/
|
}
|
||||||
public function end() {
|
|
||||||
if(!$this->environment->isRunningTests()) {
|
if (isset($_SESSION['_testsession_codeblocks'])) {
|
||||||
throw new LogicException("No test session in progress.");
|
unset($_SESSION['_testsession_codeblocks']);
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->environment->endTestSession();
|
$this->extend('onAfterClear');
|
||||||
Session::clear('TestSessionId');
|
|
||||||
|
return "Cleared database and test state";
|
||||||
// Clear out all PHP session states which have been set previously
|
}
|
||||||
if($sessionStates = Session::get('_TestSessionController.BrowserSessionState')) {
|
|
||||||
foreach($sessionStates as $k => $v) {
|
/**
|
||||||
Session::clear($k);
|
* As with {@link self::start()}, if you want to extend the functionality of this, then look at
|
||||||
}
|
* {@link TestSessionEnvironent::endTestSession()} as the extension points have moved to there now that the logic
|
||||||
Session::clear('_TestSessionController');
|
* is there.
|
||||||
}
|
*/
|
||||||
|
public function end()
|
||||||
|
{
|
||||||
return $this->renderWith('TestSession_end');
|
if (!$this->environment->isRunningTests()) {
|
||||||
}
|
throw new LogicException("No test session in progress.");
|
||||||
|
}
|
||||||
/**
|
|
||||||
* @return boolean
|
$this->environment->endTestSession();
|
||||||
*/
|
Session::clear('TestSessionId');
|
||||||
public function isTesting() {
|
|
||||||
return SapphireTest::using_temp_db();
|
// Clear out all PHP session states which have been set previously
|
||||||
}
|
if ($sessionStates = Session::get('_TestSessionController.BrowserSessionState')) {
|
||||||
|
foreach ($sessionStates as $k => $v) {
|
||||||
public function setState($data) {
|
Session::clear($k);
|
||||||
Deprecation::notice('3.1', 'TestSessionController::setState() is no longer used, please use '
|
}
|
||||||
. 'TestSessionEnvironment instead.');
|
Session::clear('_TestSessionController');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @return ArrayList
|
return $this->renderWith('TestSession_end');
|
||||||
*/
|
}
|
||||||
public function getState() {
|
|
||||||
$stateObj = $this->environment->getState();
|
/**
|
||||||
$state = array();
|
* @return boolean
|
||||||
|
*/
|
||||||
// Convert the stdObject of state into ArrayData
|
public function isTesting()
|
||||||
foreach($stateObj as $k => $v) {
|
{
|
||||||
$state[] = new ArrayData(array(
|
return SapphireTest::using_temp_db();
|
||||||
'Name' => $k,
|
}
|
||||||
'Value' => var_export($v, true)
|
|
||||||
));
|
public function setState($data)
|
||||||
}
|
{
|
||||||
|
Deprecation::notice('3.1', 'TestSessionController::setState() is no longer used, please use '
|
||||||
return new ArrayList($state);
|
. 'TestSessionEnvironment instead.');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all *.sql database files located in a specific path,
|
* @return ArrayList
|
||||||
* keyed by their file name.
|
*/
|
||||||
*
|
public function getState()
|
||||||
* @param String $path Absolute folder path
|
{
|
||||||
* @return array
|
$stateObj = $this->environment->getState();
|
||||||
*/
|
$state = array();
|
||||||
protected function getDatabaseTemplates($path = null) {
|
|
||||||
$templates = array();
|
// Convert the stdObject of state into ArrayData
|
||||||
|
foreach ($stateObj as $k => $v) {
|
||||||
if(!$path) {
|
$state[] = new ArrayData(array(
|
||||||
$path = $this->config()->database_templates_path;
|
'Name' => $k,
|
||||||
}
|
'Value' => var_export($v, true)
|
||||||
|
));
|
||||||
// TODO Remove once we can set BASE_PATH through the config layer
|
}
|
||||||
if($path && !Director::is_absolute($path)) {
|
|
||||||
$path = BASE_PATH . '/' . $path;
|
return new ArrayList($state);
|
||||||
}
|
}
|
||||||
|
|
||||||
if($path && file_exists($path)) {
|
/**
|
||||||
$it = new FilesystemIterator($path);
|
* Get all *.sql database files located in a specific path,
|
||||||
foreach($it as $fileinfo) {
|
* keyed by their file name.
|
||||||
if($fileinfo->getExtension() != 'sql') continue;
|
*
|
||||||
$templates[$fileinfo->getRealPath()] = $fileinfo->getFilename();
|
* @param String $path Absolute folder path
|
||||||
}
|
* @return array
|
||||||
}
|
*/
|
||||||
|
protected function getDatabaseTemplates($path = null)
|
||||||
return $templates;
|
{
|
||||||
}
|
$templates = array();
|
||||||
|
|
||||||
/**
|
if (!$path) {
|
||||||
* @param $params array The form fields as passed through from ->start() or ->set()
|
$path = $this->config()->database_templates_path;
|
||||||
* @return array The form fields, after fixing the datetime field if necessary
|
}
|
||||||
*/
|
|
||||||
private function fixDatetimeFormField($params) {
|
// TODO Remove once we can set BASE_PATH through the config layer
|
||||||
if(isset($params['datetime']) && is_array($params['datetime']) && !empty($params['datetime']['date'])) {
|
if ($path && !Director::is_absolute($path)) {
|
||||||
// Convert DatetimeField format from array into string
|
$path = BASE_PATH . '/' . $path;
|
||||||
$datetime = $params['datetime']['date'];
|
}
|
||||||
$datetime .= ' ';
|
|
||||||
$datetime .= (@$params['datetime']['time']) ? $params['datetime']['time'] : '00:00:00';
|
if ($path && file_exists($path)) {
|
||||||
$params['datetime'] = $datetime;
|
$it = new FilesystemIterator($path);
|
||||||
} else if(isset($params['datetime']) && empty($params['datetime']['date'])) {
|
foreach ($it as $fileinfo) {
|
||||||
unset($params['datetime']); // No datetime, so remove the param entirely
|
if ($fileinfo->getExtension() != 'sql') {
|
||||||
}
|
continue;
|
||||||
|
}
|
||||||
return $params;
|
$templates[$fileinfo->getRealPath()] = $fileinfo->getFilename();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $templates;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @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'])) {
|
||||||
|
// 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;
|
||||||
|
} elseif (isset($params['datetime']) && empty($params['datetime']['date'])) {
|
||||||
|
unset($params['datetime']); // No datetime, so remove the param entirely
|
||||||
|
}
|
||||||
|
|
||||||
|
return $params;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -24,390 +24,410 @@
|
|||||||
*
|
*
|
||||||
* 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.
|
||||||
*/
|
*/
|
||||||
protected $id;
|
protected $id;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @var string The original database name, before we overrode it with our tmpdb.
|
* @var string The original database name, before we overrode it with our tmpdb.
|
||||||
*
|
*
|
||||||
* Used in {@link self::resetDatabaseName()} when we want to restore the normal DB connection.
|
* Used in {@link self::resetDatabaseName()} when we want to restore the normal DB connection.
|
||||||
*/
|
*/
|
||||||
private $oldDatabaseName;
|
private $oldDatabaseName;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @config
|
* @config
|
||||||
* @var string Path (from web-root) to the test state file that indicates a testsession is in progress.
|
* @var string Path (from web-root) to the test state file that indicates a testsession is in progress.
|
||||||
* Defaults to value stored in testsession/_config/_config.yml
|
* Defaults to value stored in testsession/_config/_config.yml
|
||||||
*/
|
*/
|
||||||
private static $test_state_file = 'TESTS_RUNNING.json';
|
private static $test_state_file = 'TESTS_RUNNING.json';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @config
|
* @config
|
||||||
* @var [type]
|
* @var [type]
|
||||||
*/
|
*/
|
||||||
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();
|
||||||
// $_SESSION != Session::get() in some execution paths, suspect Controller->pushCurrent()
|
// $_SESSION != Session::get() in some execution paths, suspect Controller->pushCurrent()
|
||||||
// as part of the issue, easiest resolution is to use session directly for now
|
// as part of the issue, easiest resolution is to use session directly for now
|
||||||
$this->id = (isset($_SESSION['TestSessionId'])) ? $_SESSION['TestSessionId'] : null;
|
$this->id = (isset($_SESSION['TestSessionId'])) ? $_SESSION['TestSessionId'] : null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @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) {
|
{
|
||||||
$path = Director::getAbsFile(sprintf($this->config()->test_state_id_file, $this->id));
|
if ($this->id) {
|
||||||
} else {
|
$path = Director::getAbsFile(sprintf($this->config()->test_state_id_file, $this->id));
|
||||||
$path = Director::getAbsFile($this->config()->test_state_file);
|
} else {
|
||||||
}
|
$path = Director::getAbsFile($this->config()->test_state_file);
|
||||||
|
}
|
||||||
|
|
||||||
return $path;
|
return $path;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a temp database, sets up any extra requirements, and writes the state file. The database will be
|
* Creates a temp database, sets up any extra requirements, and writes the state file. The database will be
|
||||||
* connected to as part of {@link self::applyState()}, so if you're continuing script execution after calling this
|
* connected to as part of {@link self::applyState()}, so if you're continuing script execution after calling this
|
||||||
* method, be aware that the database will be different - so various things may break (e.g. administrator logins
|
* method, be aware that the database will be different - so various things may break (e.g. administrator logins
|
||||||
* using the SS_DEFAULT_USERNAME / SS_DEFAULT_PASSWORD constants).
|
* using the SS_DEFAULT_USERNAME / SS_DEFAULT_PASSWORD constants).
|
||||||
*
|
*
|
||||||
* If something isn't explicitly handled here, and needs special handling, then it should be taken care of by an
|
* If something isn't explicitly handled here, and needs special handling, then it should be taken care of by an
|
||||||
* extension to TestSessionEnvironment. You can either extend onBeforeStartTestSession() or
|
* extension to TestSessionEnvironment. You can either extend onBeforeStartTestSession() or
|
||||||
* onAfterStartTestSession(). Alternatively, for more fine-grained control, you can also extend
|
* onAfterStartTestSession(). Alternatively, for more fine-grained control, you can also extend
|
||||||
* onBeforeApplyState() and onAfterApplyState(). See the {@link self::applyState()} method for more.
|
* onBeforeApplyState() and onAfterApplyState(). See the {@link self::applyState()} method for more.
|
||||||
*
|
*
|
||||||
* @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();
|
{
|
||||||
$this->removeStateFile();
|
if (!$state) {
|
||||||
$this->id = $id;
|
$state = array();
|
||||||
|
}
|
||||||
|
$this->removeStateFile();
|
||||||
|
$this->id = $id;
|
||||||
|
|
||||||
// Assumes state will be modified by reference
|
// Assumes state will be modified by reference
|
||||||
$this->extend('onBeforeStartTestSession', $state);
|
$this->extend('onBeforeStartTestSession', $state);
|
||||||
|
|
||||||
// Convert to JSON and back so we can share the applyState() code between this and ->loadFromFile()
|
// Convert to JSON and back so we can share the applyState() code between this and ->loadFromFile()
|
||||||
$json = json_encode($state, JSON_FORCE_OBJECT);
|
$json = json_encode($state, JSON_FORCE_OBJECT);
|
||||||
$state = json_decode($json);
|
$state = json_decode($json);
|
||||||
|
|
||||||
$this->applyState($state);
|
$this->applyState($state);
|
||||||
|
|
||||||
$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()
|
||||||
$json = json_encode($state, JSON_FORCE_OBJECT);
|
$json = json_encode($state, JSON_FORCE_OBJECT);
|
||||||
$state = json_decode($json);
|
$state = json_decode($json);
|
||||||
|
|
||||||
$this->applyState($state);
|
$this->applyState($state);
|
||||||
|
|
||||||
$this->extend('onAfterUpdateTestSession');
|
$this->extend('onAfterUpdateTestSession');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Assumes the database has already been created in startTestSession(), as this method can be called from
|
* Assumes the database has already been created in startTestSession(), as this method can be called from
|
||||||
* _config.php where we don't yet have a DB connection.
|
* _config.php where we don't yet have a DB connection.
|
||||||
*
|
*
|
||||||
* Persists the state to the filesystem.
|
* Persists the state to the filesystem.
|
||||||
*
|
*
|
||||||
* You can extend this by creating an Extension object and implementing either onBeforeApplyState() or
|
* You can extend this by creating an Extension object and implementing either onBeforeApplyState() or
|
||||||
* onAfterApplyState() to add your own test state handling in.
|
* onAfterApplyState() to add your own test state handling in.
|
||||||
*
|
*
|
||||||
* @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;
|
||||||
|
|
||||||
// back up source
|
// back up source
|
||||||
global $databaseConfig;
|
global $databaseConfig;
|
||||||
$this->oldDatabaseName = $databaseConfig['database'];
|
$this->oldDatabaseName = $databaseConfig['database'];
|
||||||
|
|
||||||
// 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Connect to database
|
// Connect to database
|
||||||
DB::connect($databaseConfig);
|
DB::connect($databaseConfig);
|
||||||
} 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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();
|
||||||
|
|
||||||
$state->database = $dbName; // In case it's changed by the call to SapphireTest::create_temp_db();
|
$state->database = $dbName; // In case it's changed by the call to SapphireTest::create_temp_db();
|
||||||
|
|
||||||
// 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");
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->oldDatabaseName = $databaseConfig['database'];
|
$this->oldDatabaseName = $databaseConfig['database'];
|
||||||
$databaseConfig['database'] = $dbName; // Instead of calling DB::set_alternative_db_name();
|
$databaseConfig['database'] = $dbName; // Instead of calling DB::set_alternative_db_name();
|
||||||
|
|
||||||
// Connect to the new database, overwriting the old DB connection (if any)
|
// Connect to the new database, overwriting the old DB connection (if any)
|
||||||
DB::connect($databaseConfig);
|
DB::connect($databaseConfig);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->saveState($state);
|
$this->saveState($state);
|
||||||
$this->extend('onAfterApplyState');
|
$this->extend('onAfterApplyState');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Import the database
|
* Import the database
|
||||||
*
|
*
|
||||||
* @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
|
||||||
$sqlCmds = array_filter(
|
$sqlCmds = array_filter(
|
||||||
preg_split('/;\n/',
|
preg_split('/;\n/',
|
||||||
preg_replace(array('/^$\n/m', '/^(\/|#).*$\n/m'), '', $sql)
|
preg_replace(array('/^$\n/m', '/^(\/|#).*$\n/m'), '', $sql)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
// Execute each query
|
// Execute each query
|
||||||
foreach($sqlCmds as $sqlCmd) {
|
foreach ($sqlCmds as $sqlCmd) {
|
||||||
DB::query($sqlCmd);
|
DB::query($sqlCmd);
|
||||||
}
|
}
|
||||||
|
|
||||||
// In case the dump involved CREATE TABLE commands, we need to ensure the schema is still up to date
|
// In case the dump involved CREATE TABLE commands, we need to ensure the schema is still up to date
|
||||||
$dbAdmin = new DatabaseAdmin();
|
$dbAdmin = new DatabaseAdmin();
|
||||||
Versioned::set_reading_mode('');
|
Versioned::set_reading_mode('');
|
||||||
$dbAdmin->doBuild(true, $requireDefaultRecords);
|
$dbAdmin->doBuild(true, $requireDefaultRecords);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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();
|
{
|
||||||
Versioned::set_reading_mode('');
|
$dbAdmin = new DatabaseAdmin();
|
||||||
$dbAdmin->doBuild(true, true);
|
Versioned::set_reading_mode('');
|
||||||
}
|
$dbAdmin->doBuild(true, true);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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')) {
|
{
|
||||||
$content = json_encode($state, JSON_PRETTY_PRINT);
|
if (defined('JSON_PRETTY_PRINT')) {
|
||||||
} else {
|
$content = json_encode($state, JSON_PRETTY_PRINT);
|
||||||
$content = json_encode($state);
|
} else {
|
||||||
}
|
$content = json_encode($state);
|
||||||
$old = umask(0);
|
}
|
||||||
file_put_contents($this->getFilePath(), $content, LOCK_EX);
|
$old = umask(0);
|
||||||
umask($old);
|
file_put_contents($this->getFilePath(), $content, LOCK_EX);
|
||||||
}
|
umask($old);
|
||||||
|
}
|
||||||
|
|
||||||
public function loadFromFile() {
|
public function loadFromFile()
|
||||||
if($this->isRunningTests()) {
|
{
|
||||||
try {
|
if ($this->isRunningTests()) {
|
||||||
$contents = file_get_contents($this->getFilePath());
|
try {
|
||||||
$json = json_decode($contents);
|
$contents = file_get_contents($this->getFilePath());
|
||||||
|
$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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cleans up the test session state by restoring the normal database connect (for the rest of this request, if any)
|
* Cleans up the test session state by restoring the normal database connect (for the rest of this request, if any)
|
||||||
* and removes the {@link self::$test_state_file} so that future requests don't use this test state.
|
* and removes the {@link self::$test_state_file} so that future requests don't use this test state.
|
||||||
*
|
*
|
||||||
* Can be extended by implementing either onBeforeEndTestSession() or onAfterEndTestSession().
|
* Can be extended by implementing either onBeforeEndTestSession() or onAfterEndTestSession().
|
||||||
*
|
*
|
||||||
* This should implement itself cleanly in case it is called twice (e.g. don't throw errors when the state file
|
* This should implement itself cleanly in case it is called twice (e.g. don't throw errors when the state file
|
||||||
* doesn't exist anymore because it's already been cleaned up etc.) This is because during behat test runs where
|
* doesn't exist anymore because it's already been cleaned up etc.) This is because during behat test runs where
|
||||||
* 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->removeStateFile();
|
$this->removeStateFile();
|
||||||
|
|
||||||
$this->extend('onAfterEndTestSession');
|
$this->extend('onAfterEndTestSession');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Loads a YAML fixture into the database as part of the {@link TestSessionController}.
|
* Loads a YAML fixture into the database as part of the {@link TestSessionController}.
|
||||||
*
|
*
|
||||||
* @param string $fixtureFile The .yml file to load
|
* @param string $fixtureFile The .yml file to load
|
||||||
* @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);
|
{
|
||||||
$baseDir = realpath(Director::baseFolder());
|
$realFile = realpath(BASE_PATH.'/'.$fixtureFile);
|
||||||
if(!$realFile || !file_exists($realFile)) {
|
$baseDir = realpath(Director::baseFolder());
|
||||||
throw new LogicException("Fixture file doesn't exist");
|
if (!$realFile || !file_exists($realFile)) {
|
||||||
} else if(substr($realFile,0,strlen($baseDir)) != $baseDir) {
|
throw new LogicException("Fixture file doesn't exist");
|
||||||
throw new LogicException("Fixture file must be inside $baseDir");
|
} elseif (substr($realFile, 0, strlen($baseDir)) != $baseDir) {
|
||||||
} else if(substr($realFile,-4) != '.yml') {
|
throw new LogicException("Fixture file must be inside $baseDir");
|
||||||
throw new LogicException("Fixture file must be a .yml file");
|
} elseif (substr($realFile, -4) != '.yml') {
|
||||||
} else if(!preg_match('/^([^\/.][^\/]+)\/tests\//', $fixtureFile)) {
|
throw new LogicException("Fixture file must be a .yml file");
|
||||||
throw new LogicException("Fixture file must be inside the tests subfolder of one of your modules.");
|
} elseif (!preg_match('/^([^\/.][^\/]+)\/tests\//', $fixtureFile)) {
|
||||||
}
|
throw new LogicException("Fixture file must be inside the tests subfolder of one of your modules.");
|
||||||
|
}
|
||||||
|
|
||||||
$factory = Injector::inst()->create('FixtureFactory');
|
$factory = Injector::inst()->create('FixtureFactory');
|
||||||
$fixture = Injector::inst()->create('YamlFixture', $fixtureFile);
|
$fixture = Injector::inst()->create('YamlFixture', $fixtureFile);
|
||||||
$fixture->writeInto($factory);
|
$fixture->writeInto($factory);
|
||||||
|
|
||||||
$state = $this->getState();
|
$state = $this->getState();
|
||||||
$state->fixtures[] = $fixtureFile;
|
$state->fixtures[] = $fixtureFile;
|
||||||
$this->applyState($state);
|
$this->applyState($state);
|
||||||
|
|
||||||
return $fixture;
|
return $fixture;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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) {
|
{
|
||||||
global $databaseConfig;
|
if ($this->oldDatabaseName) {
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @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());
|
{
|
||||||
return (file_exists($path)) ? json_decode(file_get_contents($path)) : new stdClass;
|
$path = Director::getAbsFile($this->getFilePath());
|
||||||
}
|
return (file_exists($path)) ? json_decode(file_get_contents($path)) : new stdClass;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,56 +2,66 @@
|
|||||||
/**
|
/**
|
||||||
* 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
|
||||||
// to set up required test state. The file can be generated
|
// to set up required test state. The file can be generated
|
||||||
// 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) {
|
||||||
include_once($file);
|
DB::connect($databaseConfig);
|
||||||
}
|
}
|
||||||
}
|
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();
|
||||||
$state->session = Session::get_all();
|
$state->session = Session::get_all();
|
||||||
$this->testSessionEnvironment->applyState($state);
|
$this->testSessionEnvironment->applyState($state);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -3,71 +3,77 @@
|
|||||||
* 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
|
||||||
* the generator's origin code location.
|
* the generator's origin code location.
|
||||||
*/
|
*/
|
||||||
protected $debug = false;
|
protected $debug = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @var String Absolute path to a PHP file, essentially the "name" of the stub.
|
* @var String Absolute path to a PHP file, essentially the "name" of the stub.
|
||||||
*/
|
*/
|
||||||
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';
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Writes arbitrary PHP code to {@link $filePath} for later inclusion.
|
* Writes arbitrary PHP code to {@link $filePath} for later inclusion.
|
||||||
* Creates the file if it doesn't exist.
|
* Creates the file if it doesn't exist.
|
||||||
* Adds debug information about the origin of this code if {@link $debug} is set.
|
* Adds debug information about the origin of this code if {@link $debug} is set.
|
||||||
*
|
*
|
||||||
* @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;
|
{
|
||||||
$path = $this->getFilePath();
|
$trace = $this->debug ? debug_backtrace() : null;
|
||||||
$header = '';
|
$path = $this->getFilePath();
|
||||||
|
$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";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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())) {
|
{
|
||||||
unlink($this->getFilePath());
|
if (file_exists($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;
|
||||||
|
}
|
||||||
}
|
}
|
@ -1,43 +1,49 @@
|
|||||||
<?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';
|
{
|
||||||
$writer = new TestSessionStubCodeWriter($file);
|
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
|
||||||
$writer->write('foo();', false);
|
$writer = new TestSessionStubCodeWriter($file);
|
||||||
$this->assertFileExists($file);
|
$writer->write('foo();', false);
|
||||||
$this->assertEquals(
|
$this->assertFileExists($file);
|
||||||
file_get_contents($writer->getFilePath()),
|
$this->assertEquals(
|
||||||
"<?php\nfoo();\n"
|
file_get_contents($writer->getFilePath()),
|
||||||
);
|
"<?php\nfoo();\n"
|
||||||
}
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public function testWritesWithAppendOnExistingFile() {
|
public function testWritesWithAppendOnExistingFile()
|
||||||
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
|
{
|
||||||
$writer = new TestSessionStubCodeWriter($file);
|
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
|
||||||
$writer->write('foo();', false);
|
$writer = new TestSessionStubCodeWriter($file);
|
||||||
$writer->write('bar();', false);
|
$writer->write('foo();', false);
|
||||||
$this->assertFileExists($file);
|
$writer->write('bar();', false);
|
||||||
$this->assertEquals(
|
$this->assertFileExists($file);
|
||||||
file_get_contents($writer->getFilePath()),
|
$this->assertEquals(
|
||||||
"<?php\nfoo();\nbar();\n"
|
file_get_contents($writer->getFilePath()),
|
||||||
);
|
"<?php\nfoo();\nbar();\n"
|
||||||
}
|
);
|
||||||
|
}
|
||||||
public function testReset() {
|
|
||||||
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
|
|
||||||
$writer = new TestSessionStubCodeWriter($file);
|
|
||||||
$writer->write('foo();', false);
|
|
||||||
$this->assertFileExists($file);
|
|
||||||
$writer->reset();
|
|
||||||
$this->assertFileNotExists($file);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
public function testReset()
|
||||||
|
{
|
||||||
|
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
|
||||||
|
$writer = new TestSessionStubCodeWriter($file);
|
||||||
|
$writer->write('foo();', false);
|
||||||
|
$this->assertFileExists($file);
|
||||||
|
$writer->reset();
|
||||||
|
$this->assertFileNotExists($file);
|
||||||
|
}
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user