mirror of
https://github.com/silverstripe/silverstripe-framework
synced 2024-10-22 14:05:37 +02:00
19769e3841
git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@85073 467b73ca-7a2a-4603-9d3b-597d59a354a9
487 lines
15 KiB
PHP
487 lines
15 KiB
PHP
<?php
|
|
require_once 'TestRunner.php';
|
|
if(hasPhpUnit()) {
|
|
require_once 'PHPUnit/Framework.php';
|
|
}
|
|
|
|
/**
|
|
* Test case class for the Sapphire framework.
|
|
* Sapphire unit testing is based on PHPUnit, but provides a number of hooks into our data model that make it easier to work with.
|
|
*
|
|
* @package sapphire
|
|
* @subpackage testing
|
|
*/
|
|
class SapphireTest extends PHPUnit_Framework_TestCase {
|
|
/**
|
|
* Path to fixture data for this test run.
|
|
* If passed as an array, multiple fixture files will be loaded.
|
|
* Please note that you won't be able to refer with "=>" notation
|
|
* between the fixtures, they act independent of each other.
|
|
*
|
|
* @var string|array
|
|
*/
|
|
static $fixture_file = null;
|
|
|
|
protected $originalMailer;
|
|
protected $originalMemberPasswordValidator;
|
|
protected $originalRequirements;
|
|
protected $originalIsRunningTest;
|
|
|
|
protected $mailer;
|
|
|
|
protected static $is_running_test = false;
|
|
|
|
public static function is_running_test() {
|
|
return self::$is_running_test;
|
|
}
|
|
|
|
/**
|
|
* @var array $fixtures Array of {@link YamlFixture} instances
|
|
*/
|
|
protected $fixtures;
|
|
|
|
function setUp() {
|
|
// Mark test as being run
|
|
$this->originalIsRunningTest = self::$is_running_test;
|
|
self::$is_running_test = true;
|
|
|
|
// Remove password validation
|
|
$this->originalMemberPasswordValidator = Member::password_validator();
|
|
$this->originalRequirements = Requirements::backend();
|
|
Member::set_password_validator(null);
|
|
Cookie::set_report_errors(false);
|
|
|
|
// Reset Translatable and Versioned
|
|
Translatable::reset();
|
|
Versioned::reset();
|
|
DataObject::reset();
|
|
Controller::curr()->setSession(new Session(array()));
|
|
|
|
$className = get_class($this);
|
|
$fixtureFile = eval("return {$className}::\$fixture_file;");
|
|
|
|
// Set up fixture
|
|
if($fixtureFile) {
|
|
if(substr(DB::getConn()->currentDatabase(),0,5) != 'tmpdb') {
|
|
//echo "Re-creating temp database... ";
|
|
self::create_temp_db();
|
|
//echo "done.\n";
|
|
}
|
|
|
|
singleton('DataObject')->flushCache();
|
|
|
|
$dbadmin = new DatabaseAdmin();
|
|
$dbadmin->clearAllData();
|
|
|
|
$fixtureFiles = (is_array($fixtureFile)) ? $fixtureFile : array($fixtureFile);
|
|
|
|
$i = 0;
|
|
foreach($fixtureFiles as $fixtureFilePath) {
|
|
$fixture = new YamlFixture($fixtureFilePath);
|
|
$fixture->saveIntoDatabase();
|
|
$this->fixtures[] = $fixture;
|
|
|
|
// backwards compatibility: Load first fixture into $this->fixture
|
|
if($i == 0) $this->fixture = $fixture;
|
|
$i++;
|
|
}
|
|
|
|
|
|
}
|
|
|
|
// Set up email
|
|
$this->originalMailer = Email::mailer();
|
|
$this->mailer = new TestMailer();
|
|
Email::set_mailer($this->mailer);
|
|
Email::send_all_emails_to(null);
|
|
}
|
|
|
|
/**
|
|
* Called once per test case ({@link SapphireTest} subclass).
|
|
* This is different to {@link setUp()}, which gets called once
|
|
* per method. Useful to initialize expensive operations which
|
|
* don't change state for any called method inside the test,
|
|
* e.g. dynamically adding an extension. See {@link tear_down_once()}
|
|
* for tearing down the state again.
|
|
*/
|
|
static function set_up_once() {
|
|
}
|
|
|
|
/**
|
|
* Array
|
|
*/
|
|
protected $fixtureDictionary;
|
|
|
|
|
|
/**
|
|
* Get the ID of an object from the fixture.
|
|
* @param $className The data class, as specified in your fixture file. Parent classes won't work
|
|
* @param $identifier The identifier string, as provided in your fixture file
|
|
* @return int
|
|
*/
|
|
protected function idFromFixture($className, $identifier) {
|
|
if(!$this->fixtures) {
|
|
user_error("You've called idFromFixture() but you haven't specified static \$fixture_file.\n", E_USER_WARNING);
|
|
return;
|
|
}
|
|
|
|
foreach($this->fixtures as $fixture) {
|
|
$match = $fixture->idFromFixture($className, $identifier);
|
|
if($match) return $match;
|
|
}
|
|
|
|
$fixtureFiles = Object::get_static(get_class($this), 'fixture_file');
|
|
user_error(sprintf(
|
|
"Couldn't find object '%s' (class: %s) in files %s",
|
|
$identifier,
|
|
$className,
|
|
(is_array($fixtureFiles)) ? implode(',', $fixtureFiles) : $fixtureFiles
|
|
), E_USER_ERROR);
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Return all of the IDs in the fixture of a particular class name.
|
|
* Will collate all IDs form all fixtures if multiple fixtures are provided.
|
|
*
|
|
* @param string $className
|
|
* @return A map of fixture-identifier => object-id
|
|
*/
|
|
protected function allFixtureIDs($className) {
|
|
if(!$this->fixtures) {
|
|
user_error("You've called allFixtureIDs() but you haven't specified static \$fixture_file.\n", E_USER_WARNING);
|
|
return;
|
|
}
|
|
|
|
$ids = array();
|
|
foreach($this->fixtures as $fixture) {
|
|
$ids += $fixture->allFixtureIDs($className);
|
|
}
|
|
|
|
return $ids;
|
|
}
|
|
|
|
/**
|
|
* Get an object from the fixture.
|
|
* @param $className The data class, as specified in your fixture file. Parent classes won't work
|
|
* @param $identifier The identifier string, as provided in your fixture file
|
|
*/
|
|
protected function objFromFixture($className, $identifier) {
|
|
if(!$this->fixtures) {
|
|
user_error("You've called objFromFixture() but you haven't specified static \$fixture_file.\n", E_USER_WARNING);
|
|
return;
|
|
}
|
|
|
|
foreach($this->fixtures as $fixture) {
|
|
$match = $fixture->objFromFixture($className, $identifier);
|
|
if($match) return $match;
|
|
}
|
|
|
|
$fixtureFiles = Object::get_static(get_class($this), 'fixture_file');
|
|
user_error(sprintf(
|
|
"Couldn't find object '%s' (class: %s) in files %s",
|
|
$identifier,
|
|
$className,
|
|
(is_array($fixtureFiles)) ? implode(',', $fixtureFiles) : $fixtureFiles
|
|
), E_USER_ERROR);
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Load a YAML fixture file into the database.
|
|
* Once loaded, you can use idFromFixture() and objFromFixture() to get items from the fixture.
|
|
* Doesn't clear existing fixtures.
|
|
*
|
|
* @param $fixtureFile The location of the .yml fixture file, relative to the site base dir
|
|
*/
|
|
function loadFixture($fixtureFile) {
|
|
$parser = new Spyc();
|
|
$fixtureContent = $parser->load(Director::baseFolder().'/'.$fixtureFile);
|
|
|
|
$fixture = new YamlFixture($fixtureFile);
|
|
$fixture->saveIntoDatabase();
|
|
$this->fixtures[] = $fixture;
|
|
}
|
|
|
|
/**
|
|
* Clear all fixtures which were previously loaded through
|
|
* {@link loadFixture()}.
|
|
*/
|
|
function clearFixtures() {
|
|
$this->fixtures = array();
|
|
}
|
|
|
|
function tearDown() {
|
|
// Restore email configuration
|
|
Email::set_mailer($this->originalMailer);
|
|
$this->originalMailer = null;
|
|
$this->mailer = null;
|
|
|
|
// Restore password validation
|
|
Member::set_password_validator($this->originalMemberPasswordValidator);
|
|
|
|
// Restore requirements
|
|
Requirements::set_backend($this->originalRequirements);
|
|
|
|
// Mark test as no longer being run - we use originalIsRunningTest to allow for nested SapphireTest calls
|
|
self::$is_running_test = $this->originalIsRunningTest;
|
|
$this->originalIsRunningTest = null;
|
|
}
|
|
|
|
static function tear_down_once() {
|
|
}
|
|
|
|
/**
|
|
* Clear the log of emails sent
|
|
*/
|
|
function clearEmails() {
|
|
return $this->mailer->clearEmails();
|
|
}
|
|
|
|
/**
|
|
* Search for an email that was sent.
|
|
* All of the parameters can either be a string, or, if they start with "/", a PREG-compatible regular expression.
|
|
* @param $to
|
|
* @param $from
|
|
* @param $subject
|
|
* @param $content
|
|
* @return An array containing the keys: 'type','to','from','subject','content', 'plainContent','attachedFiles','customHeaders','htmlContent',inlineImages'
|
|
*/
|
|
function findEmail($to, $from = null, $subject = null, $content = null) {
|
|
return $this->mailer->findEmail($to, $from, $subject, $content);
|
|
}
|
|
|
|
/**
|
|
* Assert that the matching email was sent since the last call to clearEmails()
|
|
* All of the parameters can either be a string, or, if they start with "/", a PREG-compatible regular expression.
|
|
* @param $to
|
|
* @param $from
|
|
* @param $subject
|
|
* @param $content
|
|
* @return An array containing the keys: 'type','to','from','subject','content', 'plainContent','attachedFiles','customHeaders','htmlContent',inlineImages'
|
|
*/
|
|
function assertEmailSent($to, $from = null, $subject = null, $content = null) {
|
|
// To do - this needs to be turned into a "real" PHPUnit ass
|
|
if(!$this->findEmail($to, $from, $subject, $content)) {
|
|
|
|
$infoParts = "";
|
|
$withParts = array();
|
|
if($to) $infoParts .= " to '$to'";
|
|
if($from) $infoParts .= " from '$from'";
|
|
if($subject) $withParts[] = "subject '$subject'";
|
|
if($content) $withParts[] = "content '$content'";
|
|
if($withParts) $infoParts .= " with " . implode(" and ", $withParts);
|
|
|
|
throw new PHPUnit_Framework_AssertionFailedError(
|
|
"Failed asserting that an email was sent$infoParts."
|
|
);
|
|
}
|
|
}
|
|
|
|
|
|
/**
|
|
* Assert that the given {@link DataObjectSet} includes DataObjects matching the given key-value
|
|
* pairs. Each match must correspond to 1 distinct record.
|
|
*
|
|
* @param $matches The patterns to match. Each pattern is a map of key-value pairs. You can
|
|
* either pass a single pattern or an array of patterns.
|
|
* @param $dataObjectSet The {@link DataObjectSet} to test.
|
|
*
|
|
* Examples
|
|
* --------
|
|
* Check that $members includes an entry with Email = sam@example.com:
|
|
* $this->assertDOSContains(array('Email' => '...@example.com'), $members);
|
|
*
|
|
* Check that $members includes entries with Email = sam@example.com and with
|
|
* Email = ingo@example.com:
|
|
* $this->assertDOSContains(array(
|
|
* array('Email' => '...@example.com'),
|
|
* array('Email' => 'i...@example.com'),
|
|
* ), $members);
|
|
*/
|
|
function assertDOSContains($matches, $dataObjectSet) {
|
|
$extracted = array();
|
|
foreach($dataObjectSet as $item) $extracted[] = $item->toMap();
|
|
|
|
foreach($matches as $match) {
|
|
$matched = false;
|
|
foreach($extracted as $i => $item) {
|
|
if($this->dataObjectArrayMatch($item, $match)) {
|
|
// Remove it from $extracted so that we don't get duplicate mapping.
|
|
unset($extracted[$i]);
|
|
$matched = true;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// We couldn't find a match - assertion failed
|
|
if(!$matched) {
|
|
throw new PHPUnit_Framework_AssertionFailedError(
|
|
"Failed asserting that the DataObjectSet contains an item matching "
|
|
. var_export($match, true) . "\n\nIn the following DataObjectSet:\n"
|
|
. $this->DOSSummaryForMatch($dataObjectSet, $match)
|
|
);
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Assert that the given {@link DataObjectSet} includes only DataObjects matching the given
|
|
* key-value pairs. Each match must correspond to 1 distinct record.
|
|
*
|
|
* @param $matches The patterns to match. Each pattern is a map of key-value pairs. You can
|
|
* either pass a single pattern or an array of patterns.
|
|
* @param $dataObjectSet The {@link DataObjectSet} to test.
|
|
*
|
|
* Example
|
|
* --------
|
|
* Check that *only* the entries Sam Minnee and Ingo Schommer exist in $members. Order doesn't
|
|
* matter:
|
|
* $this->assertDOSEquals(array(
|
|
* array('FirstName' =>'Sam', 'Surname' => 'Minnee'),
|
|
* array('FirstName' => 'Ingo', 'Surname' => 'Schommer'),
|
|
* ), $members);
|
|
*/
|
|
function assertDOSEquals($matches, $dataObjectSet) {
|
|
$extracted = array();
|
|
foreach($dataObjectSet as $item) $extracted[] = $item->toMap();
|
|
|
|
foreach($matches as $match) {
|
|
$matched = false;
|
|
foreach($extracted as $i => $item) {
|
|
if($this->dataObjectArrayMatch($item, $match)) {
|
|
// Remove it from $extracted so that we don't get duplicate mapping.
|
|
unset($extracted[$i]);
|
|
$matched = true;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// We couldn't find a match - assertion failed
|
|
if(!$matched) {
|
|
throw new PHPUnit_Framework_AssertionFailedError(
|
|
"Failed asserting that the DataObjectSet contains an item matching "
|
|
. var_export($match, true) . "\n\nIn the following DataObjectSet:\n"
|
|
. $this->DOSSummaryForMatch($dataObjectSet, $match)
|
|
);
|
|
}
|
|
}
|
|
|
|
// If we have leftovers than the DOS has extra data that shouldn't be there
|
|
if($extracted) {
|
|
// If we didn't break by this point then we couldn't find a match
|
|
throw new PHPUnit_Framework_AssertionFailedError(
|
|
"Failed asserting that the DataObjectSet contained only the given items, the "
|
|
. "following items were left over:\n" . var_export($extracted, true)
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Assert that the every record in the given {@link DataObjectSet} matches the given key-value
|
|
* pairs.
|
|
*
|
|
* @param $match The pattern to match. The pattern is a map of key-value pairs.
|
|
* @param $dataObjectSet The {@link DataObjectSet} to test.
|
|
*
|
|
* Example
|
|
* --------
|
|
* Check that every entry in $members has a Status of 'Active':
|
|
* $this->assertDOSAllMatch(array('Status' => 'Active'), $members);
|
|
*/
|
|
function assertDOSAllMatch($match, $dataObjectSet) {
|
|
$extracted = array();
|
|
foreach($dataObjectSet as $item) $extracted[] = $item->toMap();
|
|
|
|
foreach($extracted as $i => $item) {
|
|
if(!$this->dataObjectArrayMatch($item, $match)) {
|
|
throw new PHPUnit_Framework_AssertionFailedError(
|
|
"Failed asserting that the the following item matched "
|
|
. var_export($match, true) . ": " . var_export($item, true)
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Helper function for the DOS matchers
|
|
*/
|
|
private function dataObjectArrayMatch($item, $match) {
|
|
foreach($match as $k => $v) {
|
|
if(!isset($item[$k]) || $item[$k] != $v) return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Helper function for the DOS matchers
|
|
*/
|
|
private function DOSSummaryForMatch($dataObjectSet, $match) {
|
|
$extracted = array();
|
|
foreach($dataObjectSet as $item) $extracted[] = array_intersect_key($item->toMap(), $match);
|
|
return var_export($extracted, true);
|
|
}
|
|
|
|
/**
|
|
* Returns true if we are currently using a temporary database
|
|
*/
|
|
static function using_temp_db() {
|
|
$dbConn = DB::getConn();
|
|
return $dbConn && (substr($dbConn->currentDatabase(),0,5) == 'tmpdb');
|
|
}
|
|
|
|
/**
|
|
* @todo Make this db agnostic
|
|
*/
|
|
static function kill_temp_db() {
|
|
// Delete our temporary database
|
|
if(self::using_temp_db()) {
|
|
$dbConn = DB::getConn();
|
|
$dbName = $dbConn->currentDatabase();
|
|
if($dbName && DB::getConn()->databaseExists($dbName)) {
|
|
// echo "Deleted temp database " . $dbConn->currentDatabase() . "\n";
|
|
$dbConn->dropDatabase();
|
|
|
|
// Todo: it would be good to remove this inappropriate coupling, somehow.
|
|
// The versioned class keeps a static cache of information about temporary tables.
|
|
Versioned::on_db_reset();
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @todo Make this db agnostic
|
|
*/
|
|
static function create_temp_db() {
|
|
// Create a temporary database
|
|
$dbConn = DB::getConn();
|
|
$dbname = 'tmpdb' . rand(1000000,9999999);
|
|
while(!$dbname || $dbConn->databaseExists($dbname)) {
|
|
$dbname = 'tmpdb' . rand(1000000,9999999);
|
|
}
|
|
|
|
$dbConn->selectDatabase($dbname);
|
|
$dbConn->createDatabase();
|
|
|
|
$dbadmin = new DatabaseAdmin();
|
|
$dbadmin->doBuild(true, false, true);
|
|
|
|
return $dbname;
|
|
}
|
|
|
|
static function delete_all_temp_dbs() {
|
|
foreach(DB::getConn()->allDatabaseNames() as $dbName) {
|
|
if(preg_match('/^tmpdb[0-9]+$/', $dbName)) {
|
|
DB::getConn()->dropDatabaseByName($dbName);
|
|
echo "<li>Dropped databse \"$dbName\"\n";
|
|
flush();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
?>
|