Skip to content

Commit

Permalink
Merge pull request #49 from open-sausages/pulls/4.0/app-object
Browse files Browse the repository at this point in the history
[WIP] App object refactor
  • Loading branch information
chillu authored Jun 22, 2017
2 parents be78e58 + 2868e6b commit 787ba1c
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 151 deletions.
34 changes: 0 additions & 34 deletions .travis.yml

This file was deleted.

28 changes: 14 additions & 14 deletions _config.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,21 @@
* This closure will run every time a Resque_Event is forked (just before it is forked, so it applies to the parent
* and child process).
*/
if(class_exists('Resque_Event') && class_exists('SSResqueRun')) {
Resque_Event::listen('beforeFork', function($data) {
global $databaseConfig;
if (class_exists('Resque_Event') && class_exists('SSResqueRun')) {
Resque_Event::listen('beforeFork', function ($data) {
$databaseConfig = DB::getConfig();

// Reconnect to the database - this may connect to the old DB first, but is required because these processes
// are long-lived, and MySQL connections often get closed in between worker runs. We need to connect before
// calling {@link TestSessionEnvironment::loadFromFile()}.
DB::connect($databaseConfig);
// Reconnect to the database - this may connect to the old DB first, but is required because these processes
// are long-lived, and MySQL connections often get closed in between worker runs. We need to connect before
// calling {@link TestSessionEnvironment::loadFromFile()}.
DB::connect($databaseConfig);

$testEnv = TestSessionEnvironment::singleton();
$testEnv = TestSessionEnvironment::singleton();

if($testEnv->isRunningTests()) {
$testEnv->loadFromFile();
} else {
$testEnv->endTestSession();
}
});
if ($testEnv->isRunningTests()) {
$testEnv->loadFromFile();
} else {
$testEnv->endTestSession();
}
});
}
34 changes: 18 additions & 16 deletions src/TestSessionController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@

use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Control\Session;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\DatetimeField;
Expand All @@ -18,6 +16,7 @@
use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\TextField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\Connect\TempDatabase;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\Security\Permission;
Expand Down Expand Up @@ -104,14 +103,14 @@ public function index()
*/
public function start()
{
$params = $this->request->requestVars();
$params = $this->getRequest()->requestVars();

if (!empty($params['globalTestSession'])) {
$id = null;
} else {
$generator = Injector::inst()->get(RandomGenerator::class);
$id = substr($generator->randomToken(), 0, 10);
Session::set('TestSessionId', $id);
$this->getRequest()->getSession()->set('TestSessionId', $id);
}

// Convert datetime from form object into a single string
Expand Down Expand Up @@ -181,14 +180,15 @@ public function browsersessionstate($request)
throw new LogicException('No query parameters detected');
}

$sessionStates = (array)Session::get('_TestSessionController.BrowserSessionState');
$session = $this->getRequest()->getSession();
$sessionStates = (array)$session->get('_TestSessionController.BrowserSessionState');

foreach ($newSessionStates as $k => $v) {
Session::set($k, $v);
$session->set($k, $v);
}

// Track which state we're setting so we can unset later in end()
Session::set('_TestSessionController.BrowserSessionState', array_merge($sessionStates, $newSessionStates));
$session->set('_TestSessionController.BrowserSessionState', array_merge($sessionStates, $newSessionStates));
}

public function StartForm()
Expand Down Expand Up @@ -316,8 +316,9 @@ public function clear()

$this->extend('onBeforeClear');

if (SapphireTest::using_temp_db()) {
SapphireTest::empty_temp_db();
$tempDB = new TempDatabase();
if ($tempDB->isUsed()) {
$tempDB->clearAllData();
}

if (isset($_SESSION['_testsession_codeblocks'])) {
Expand All @@ -341,17 +342,17 @@ public function end()
}

$this->environment->endTestSession();
Session::clear('TestSessionId');
$session = Controller::curr()->getRequest()->getSession();
$session->clear('TestSessionId');

// Clear out all PHP session states which have been set previously
if ($sessionStates = Session::get('_TestSessionController.BrowserSessionState')) {
if ($sessionStates = $session->get('_TestSessionController.BrowserSessionState')) {
foreach ($sessionStates as $k => $v) {
Session::clear($k);
$session->clear($k);
}
Session::clear('_TestSessionController');
$session->clear('_TestSessionController');
}


return $this->renderWith('TestSession_end');
}

Expand All @@ -360,7 +361,8 @@ public function end()
*/
public function isTesting()
{
return SapphireTest::using_temp_db();
$tempDB = new TempDatabase();
return $tempDB->isUsed();
}

/**
Expand Down Expand Up @@ -394,7 +396,7 @@ protected function getDatabaseTemplates($path = null)
$templates = array();

if (!$path) {
$path = $this->config()->database_templates_path;
$path = $this->config()->get('database_templates_path');
}

// TODO Remove once we can set BASE_PATH through the config layer
Expand Down
49 changes: 28 additions & 21 deletions src/TestSessionEnvironment.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,21 @@

namespace SilverStripe\TestSession;

use Exception;
use InvalidArgumentException;
use LogicException;
use SilverStripe\Control\Director;
use SilverStripe\Control\Session;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Extensible;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\FixtureFactory;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\Connect\TempDatabase;
use SilverStripe\ORM\DatabaseAdmin;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\Versioned\Versioned;
use InvalidArgumentException;
use LogicException;
use Exception;
use stdClass;

/**
Expand Down Expand Up @@ -77,19 +77,23 @@ class TestSessionEnvironment
public function __construct($id = null)
{
$this->constructExtensions();

if ($id) {
$this->id = $id;
} else {
Session::start();
}
}

public function init(HTTPRequest $request)
{
if (!$this->id) {
$request->getSession()->init();
// $_SESSION != Session::get() in some execution paths, suspect Controller->pushCurrent()
// as part of the issue, easiest resolution is to use session directly for now
$this->id = (isset($_SESSION['TestSessionId'])) ? $_SESSION['TestSessionId'] : null;
$this->id = $request->getSession()->get('TestSessionId');
}
}

/**
* @return String Absolute path to the file persisting our state.
* @return string Absolute path to the file persisting our state.
*/
public function getFilePath()
{
Expand Down Expand Up @@ -191,7 +195,7 @@ public function applyState($state)
$this->extend('onBeforeApplyState', $state);

// back up source
global $databaseConfig;
$databaseConfig = DB::getConfig();
$this->oldDatabaseName = $databaseConfig['database'];

// Load existing state from $this->state into $state, if there is any
Expand Down Expand Up @@ -239,7 +243,8 @@ public function applyState($state)

if (!$dbExists) {
// Create a new one with a randomized name
$dbName = SapphireTest::create_temp_db();
$tempDB = new TempDatabase();
$dbName = $tempDB->build();

$state->database = $dbName; // In case it's changed by the call to SapphireTest::create_temp_db();

Expand Down Expand Up @@ -351,9 +356,12 @@ public function loadFromFile()

$this->applyState($json);
} 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());
throw new Exception(
"A test session appears to be in progress, but we can't retrieve the details.\n"
. "Try removing the " . $this->getFilePath() . " file.\n"
. "Inner error: " . $e->getMessage() . "\n"
. "Stacktrace: " . $e->getTraceAsString()
);
}
}
}
Expand Down Expand Up @@ -385,7 +393,8 @@ public function endTestSession()
{
$this->extend('onBeforeEndTestSession');

if (SapphireTest::using_temp_db()) {
$tempDB = new TempDatabase();
if ($tempDB->isUsed()) {
$state = $this->getState();
$dbConn = DB::get_schema();
$dbExists = $dbConn->databaseExists($state->database);
Expand All @@ -396,8 +405,6 @@ public function endTestSession()
}
// End test session mode
$this->resetDatabaseName();

SapphireTest::set_is_running_test(false);
}

$this->removeStateFile();
Expand Down Expand Up @@ -443,9 +450,9 @@ public function loadFixtureIntoDb($fixtureFile)
public function resetDatabaseName()
{
if ($this->oldDatabaseName) {
global $databaseConfig;

$databaseConfig = DB::getConfig();
$databaseConfig['database'] = $this->oldDatabaseName;
DB::setConfig($databaseConfig);

$conn = DB::get_conn();

Expand Down
21 changes: 10 additions & 11 deletions src/TestSessionRequestFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,15 @@

namespace SilverStripe\TestSession;

use SilverStripe\Control\Director;
use SilverStripe\Control\Email\Email;
use SilverStripe\Control\Email\Mailer;
use SilverStripe\ORM\DataModel;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\ORM\DB;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Control\Session;
use SilverStripe\Control\Director;
use SilverStripe\Control\RequestFilter;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\RequestFilter;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\FieldType\DBDatetime;

/**
* Sets state previously initialized through {@link TestSessionController}.
Expand All @@ -29,9 +27,10 @@ public function __construct()
$this->testSessionEnvironment = TestSessionEnvironment::singleton();
}

public function preRequest(HTTPRequest $request, Session $session, DataModel $model)
public function preRequest(HTTPRequest $request)
{
$isRunningTests = $this->testSessionEnvironment->isRunningTests();
$this->testSessionEnvironment->init($request);
if (!$isRunningTests) {
return;
}
Expand Down Expand Up @@ -59,7 +58,7 @@ public function preRequest(HTTPRequest $request, Session $session, DataModel $mo
$file = $testState->stubfile;
if (!Director::isLive() && $file && file_exists($file)) {
// Connect to the database so the included code can interact with it
global $databaseConfig;
$databaseConfig = DB::getConfig();
if ($databaseConfig) {
DB::connect($databaseConfig);
}
Expand All @@ -68,15 +67,15 @@ public function preRequest(HTTPRequest $request, Session $session, DataModel $mo
}
}

public function postRequest(HTTPRequest $request, HTTPResponse $response, DataModel $model)
public function postRequest(HTTPRequest $request, HTTPResponse $response)
{
if (!$this->testSessionEnvironment->isRunningTests()) {
return;
}

// Store PHP session
$state = $this->testSessionEnvironment->getState();
$state->session = Session::get_all();
$state->session = $request->getSession()->getAll();
$this->testSessionEnvironment->applyState($state);
}
}
Loading

0 comments on commit 787ba1c

Please sign in to comment.