class FunctionalTest extends SapphireTest (View source)

SilverStripe-specific testing object designed to support functional testing of your web app. It simulates get/post requests, form submission, and can validate resulting HTML, looking up content by CSS selector.

The example below shows how it works.

  public function testMyForm() {
  // Visit a URL
  $this->get("your/url");

  // Submit a form on the page that you get in response
  $this->submitForm("MyForm_ID", "action_dologin", array("Email" => "invalid email ^&*&^"));

  // Validate the content that is returned
  $this->assertExactMatchBySelector("#MyForm_ID p.error", array("That email address is invalid."));
 }

Properties

protected static string|array $fixture_file

Path to fixture data for this test run.

from  SapphireTest
protected FixtureFactory $fixtureFactory from  SapphireTest
protected bool $skipTest from  SapphireTest
protected bool $usesDatabase from  SapphireTest
protected deprecated $originalMailer from  SapphireTest
protected $originalMemberPasswordValidator from  SapphireTest
protected $originalRequirements from  SapphireTest
protected $originalIsRunningTest from  SapphireTest
protected string $originalTheme
protected $originalNestedURLsState from  SapphireTest
protected $originalMemoryLimit from  SapphireTest
protected $mailer from  SapphireTest
protected static $regular_manifest

Pointer to the manifest that isn't a test manifest

from  SapphireTest
protected static bool $is_running_test from  SapphireTest
protected static $test_class_manifest from  SapphireTest
protected $requireDefaultRecordsFrom

By default, setUp() does not require default records. Pass class names in here, and the require/augment default records function will be called on them.

from  SapphireTest
protected $illegalExtensions

A list of extensions that can't be applied during the execution of this run. If they are applied, they will be temporarily removed and a database migration called.

from  SapphireTest
protected $requiredExtensions

A list of extensions that must be applied during the execution of this run. If they are not applied, they will be temporarily added and a database migration called.

from  SapphireTest
protected $extraDataObjects

By default, the test database won't contain any DataObjects that have the interface TestOnly.

from  SapphireTest
protected $backupGlobals

We need to disabling backing up of globals to avoid overriding the few globals SilverStripe relies on, like $lang for the i18n subsystem.

from  SapphireTest
protected deprecated array $fixtures from  SapphireTest
protected $model from  SapphireTest
protected $cache_generatedMembers

Cache for logInWithPermission()

from  SapphireTest
protected static bool $disable_themes

Set this to true on your sub-class to disable the use of themes in this test.

protected static bool $use_draft_site

Set this to true on your sub-class to use the draft site by default for every test in this class.

protected TestSession $mainSession
protected CSSContentParser $cssParser

CSSContentParser for the most recently requested page.

protected bool $autoFollowRedirection

If this is true, then 30x Location headers will be automatically followed.

Methods

public static 
bool
is_running_test()

Determines if unit tests are currently run (via TestRunner).

public static 
set_is_running_test($bool)

No description

public static 
set_test_class_manifest($manifest)

Set the manifest to be used to look up test classes by helper functions

public static 
get_test_class_manifest()

Return the manifest being used to look up test classes by helper functions

public static 
string
get_fixture_file()

No description

public
setUp()

No description

public
setUpOnce()

Called once per test case (SapphireTest subclass).

public
tearDownOnce()

tearDown method that's called once per test class rather once per test method.

public
getFixtureFactory()

No description

public
setFixtureFactory(FixtureFactory $factory)

No description

protected
int
idFromFixture($className, $identifier)

Get the ID of an object from the fixture.

protected
array
allFixtureIDs(string $className)

Return all of the IDs in the fixture of a particular class name.

protected
objFromFixture(string $className, string $identifier)

Get an object from the fixture.

public
loadFixture($fixtureFile)

Load a YAML fixture file into the database.

public
clearFixtures()

Clear all fixtures which were previously loaded through loadFixture()

protected
string
getCurrentAbsolutePath()

Useful for writing unit tests without hardcoding folder structures.

protected
string
getCurrentRelativePath()

No description

public
tearDown()

No description

public static 
assertContains($needle, $haystack, $message = '', $ignoreCase = FALSE, $checkForObjectIdentity = TRUE, $checkForNonObjectIdentity = false)

No description

public static 
assertNotContains($needle, $haystack, $message = '', $ignoreCase = FALSE, $checkForObjectIdentity = TRUE, $checkForNonObjectIdentity = false)

No description

public
clearEmails()

Clear the log of emails sent

public
array
findEmail($to, $from = null, $subject = null, $content = null)

Search for an email that was sent.

public
array
assertEmailSent($to, $from = null, $subject = null, $content = null)

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.

public
assertDOSContains($matches, $dataObjectSet)

Assert that the given SS_List includes DataObjects matching the given key-value pairs. Each match must correspond to 1 distinct record.

public
assertDOSEquals($matches, $dataObjectSet)

Assert that the given SS_List includes only DataObjects matching the given key-value pairs. Each match must correspond to 1 distinct record.

public
assertDOSAllMatch($match, $dataObjectSet)

Assert that the every record in the given SS_List matches the given key-value pairs.

protected
string
normaliseSQL(string $sql)

Removes sequences of repeated whitespace characters from SQL queries making them suitable for string comparison

public
assertSQLEquals(string $expectedSQL, string $actualSQL, string $message = '', float $delta = 0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false)

Asserts that two SQL queries are equivalent

public
assertSQLContains(string $needleSQL, string $haystackSQL, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true)

Asserts that a SQL query contains a SQL fragment

public
assertSQLNotContains(string $needleSQL, string $haystackSQL, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true)

Asserts that a SQL query contains a SQL fragment

public static 
using_temp_db()

Returns true if we are currently using a temporary database

public static 
kill_temp_db()

No description

public static 
empty_temp_db()

Remove all content from the temporary database.

public static 
create_temp_db()

No description

public static 
delete_all_temp_dbs()

No description

public
resetDBSchema($includeExtraDataObjects = false)

Reset the testing database's schema.

public
logInWithPermission($permCode = "ADMIN")

Create a member and group with the given permission code, and log in with it.

protected
useTestTheme($themeBaseDir, $theme, $callback)

Test against a theme.

public
session()

Returns the Session object for this test

protected
withBaseURL(string $url, callable $callback)

Run a test while mocking the base url with the provided value

protected
withBaseFolder(string $folder, callable $callback)

Run a test while mocking the base folder with the provided value

public
get(string $url, Session $session = null, array $headers = null, array $cookies = null)

Submit a get request

public
post(string $url, array $data, array $headers = null, Session $session = null, string $body = null, array $cookies = null)

Submit a post request

public
submitForm(string $formID, string $button = null, array $data = array())

Submit the form with the given HTML ID, filling it out with the given data.

public
string
content()

Return the most recent content

public
findAttribute(SimpleXMLElement $object, string $attribute)

Find an attribute in a SimpleXMLElement object by name.

public
cssParser()

Return a CSSContentParser for the most recent content.

public
bool
assertPartialMatchBySelector(string $selector, array|string $expectedMatches)

Assert that the most recently queried page contains a number of content tags specified by a CSS selector.

public
bool
assertExactMatchBySelector(string $selector, array|string $expectedMatches)

Assert that the most recently queried page contains a number of content tags specified by a CSS selector.

public
bool
assertPartialHTMLMatchBySelector(string $selector, array|string $expectedMatches)

Assert that the most recently queried page contains a number of content tags specified by a CSS selector.

public
bool
assertExactHTMLMatchBySelector(string $selector, array|string $expectedMatches)

Assert that the most recently queried page contains a number of content tags specified by a CSS selector.

public
logInAs($member)

Log in as the given member

public
useDraftSite($enabled = true)

Use the draft (stage) site for testing.

public
mixed
stat(string $varName)

Return a static variable from this class.

public static 
bool
get_disable_themes()

No description

public static 
bool
get_use_draft_site()

No description

Details

static bool is_running_test()

Determines if unit tests are currently run (via TestRunner).

This is used as a cheap replacement for fully mockable state in certain contiditions (e.g. access checks). Caution: When set to FALSE, certain controllers might bypass access checks, so this is a very security sensitive setting.

Return Value

bool

static set_is_running_test($bool)

No description

Parameters

$bool

static set_test_class_manifest($manifest)

Set the manifest to be used to look up test classes by helper functions

Parameters

$manifest

static get_test_class_manifest()

Return the manifest being used to look up test classes by helper functions

static string get_fixture_file()

No description

Return Value

string

setUp()

No description

setUpOnce()

Called once per test case (SapphireTest subclass).

This is different to 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 tearDownOnce() for tearing down the state again.

tearDownOnce()

tearDown method that's called once per test class rather once per test method.

FixtureFactory getFixtureFactory()

No description

Return Value

FixtureFactory

setFixtureFactory(FixtureFactory $factory)

No description

Parameters

FixtureFactory $factory

protected int idFromFixture($className, $identifier)

Get the ID of an object from the fixture.

Parameters

$className

The data class, as specified in your fixture file. Parent classes won't work

$identifier

The identifier string, as provided in your fixture file

Return Value

int

protected array allFixtureIDs(string $className)

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.

Parameters

string $className

Return Value

array

A map of fixture-identifier => object-id

protected DataObject objFromFixture(string $className, string $identifier)

Get an object from the fixture.

Parameters

string $className

The data class, as specified in your fixture file. Parent classes won't work

string $identifier

The identifier string, as provided in your fixture file

Return Value

DataObject

loadFixture($fixtureFile)

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.

Parameters

$fixtureFile

The location of the .yml fixture file, relative to the site base dir

clearFixtures()

Clear all fixtures which were previously loaded through loadFixture()

protected string getCurrentAbsolutePath()

Useful for writing unit tests without hardcoding folder structures.

Return Value

string

Absolute path to current class.

protected string getCurrentRelativePath()

No description

Return Value

string

File path relative to webroot

tearDown()

No description

static assertContains($needle, $haystack, $message = '', $ignoreCase = FALSE, $checkForObjectIdentity = TRUE, $checkForNonObjectIdentity = false)

No description

Parameters

$needle
$haystack
$message
$ignoreCase
$checkForObjectIdentity
$checkForNonObjectIdentity

static assertNotContains($needle, $haystack, $message = '', $ignoreCase = FALSE, $checkForObjectIdentity = TRUE, $checkForNonObjectIdentity = false)

No description

Parameters

$needle
$haystack
$message
$ignoreCase
$checkForObjectIdentity
$checkForNonObjectIdentity

clearEmails()

Clear the log of emails sent

array findEmail($to, $from = null, $subject = null, $content = null)

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.

Parameters

$to
$from
$subject
$content

Return Value

array

Contains keys: 'type', 'to', 'from', 'subject','content', 'plainContent', 'attachedFiles', 'customHeaders', 'htmlContent', 'inlineImages'

array assertEmailSent($to, $from = null, $subject = null, $content = null)

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.

Parameters

$to
$from
$subject
$content

Return Value

array

Contains the keys: 'type', 'to', 'from', 'subject', 'content', 'plainContent', 'attachedFiles', 'customHeaders', 'htmlContent', inlineImages'

assertDOSContains($matches, $dataObjectSet)

Assert that the given SS_List includes DataObjects matching the given key-value pairs. Each match must correspond to 1 distinct record.

Parameters

$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.

$dataObjectSet

The SS_List to test.

Examples

Check that $members includes an entry with Email = [email protected]: $this->assertDOSContains(array('Email' => '[email protected]'), $members);

Check that $members includes entries with Email = [email protected] and with Email = [email protected]: $this->assertDOSContains(array( array('Email' => '[email protected]'), array('Email' => '[email protected]'), ), $members);

assertDOSEquals($matches, $dataObjectSet)

Assert that the given SS_List includes only DataObjects matching the given key-value pairs. Each match must correspond to 1 distinct record.

Parameters

$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.

$dataObjectSet

The SS_List 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);

assertDOSAllMatch($match, $dataObjectSet)

Assert that the every record in the given SS_List matches the given key-value pairs.

Parameters

$match

The pattern to match. The pattern is a map of key-value pairs.

$dataObjectSet

The SS_List to test.

Example

Check that every entry in $members has a Status of 'Active': $this->assertDOSAllMatch(array('Status' => 'Active'), $members);

protected string normaliseSQL(string $sql)

Removes sequences of repeated whitespace characters from SQL queries making them suitable for string comparison

Parameters

string $sql

Return Value

string

The cleaned and normalised SQL string

assertSQLEquals(string $expectedSQL, string $actualSQL, string $message = '', float $delta = 0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false)

Asserts that two SQL queries are equivalent

Parameters

string $expectedSQL
string $actualSQL
string $message
float $delta
int $maxDepth
bool $canonicalize
bool $ignoreCase

assertSQLContains(string $needleSQL, string $haystackSQL, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true)

Asserts that a SQL query contains a SQL fragment

Parameters

string $needleSQL
string $haystackSQL
string $message
bool $ignoreCase
bool $checkForObjectIdentity

assertSQLNotContains(string $needleSQL, string $haystackSQL, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true)

Asserts that a SQL query contains a SQL fragment

Parameters

string $needleSQL
string $haystackSQL
string $message
bool $ignoreCase
bool $checkForObjectIdentity

static using_temp_db()

Returns true if we are currently using a temporary database

static kill_temp_db()

No description

static empty_temp_db()

Remove all content from the temporary database.

static create_temp_db()

No description

static delete_all_temp_dbs()

No description

resetDBSchema($includeExtraDataObjects = false)

Reset the testing database's schema.

Parameters

$includeExtraDataObjects

If true, the extraDataObjects tables will also be included

logInWithPermission($permCode = "ADMIN")

Create a member and group with the given permission code, and log in with it.

Returns the member ID.

Parameters

$permCode

protected useTestTheme($themeBaseDir, $theme, $callback)

Test against a theme.

Parameters

$themeBaseDir

string - themes directory

$theme

string - theme name

$callback Closure

Session session()

Returns the Session object for this test

Return Value

Session

protected withBaseURL(string $url, callable $callback)

Run a test while mocking the base url with the provided value

Parameters

string $url

The base URL to use for this test

callable $callback

The test to run

protected withBaseFolder(string $folder, callable $callback)

Run a test while mocking the base folder with the provided value

Parameters

string $folder

The base folder to use for this test

callable $callback

The test to run

SS_HTTPResponse get(string $url, Session $session = null, array $headers = null, array $cookies = null)

Submit a get request

Parameters

string $url
Session $session
array $headers
array $cookies

Return Value

SS_HTTPResponse

SS_HTTPResponse post(string $url, array $data, array $headers = null, Session $session = null, string $body = null, array $cookies = null)

Submit a post request

Parameters

string $url
array $data
array $headers
Session $session
string $body
array $cookies

Return Value

SS_HTTPResponse

SS_HTTPResponse submitForm(string $formID, string $button = null, array $data = array())

Submit the form with the given HTML ID, filling it out with the given data.

Acts on the most recent response.

Any data parameters have to be present in the form, with exact form field name and values, otherwise they are removed from the submission.

Caution: Parameter names have to be formatted as they are in the form submission, not as they are interpreted by PHP. Wrong: array('mycheckboxvalues' => array(1 => 'one', 2 => 'two')) Right: array('mycheckboxvalues[1]' => 'one', 'mycheckboxvalues[2]' => 'two')

Parameters

string $formID

HTML 'id' attribute of a form (loaded through a previous response)

string $button

HTML 'name' attribute of the button (NOT the 'id' attribute)

array $data

Map of GET/POST data.

Return Value

SS_HTTPResponse

See also

http://www.simpletest.org/en/form_testing_documentation.html

string content()

Return the most recent content

Return Value

string

SimpleXMLElement findAttribute(SimpleXMLElement $object, string $attribute)

Find an attribute in a SimpleXMLElement object by name.

Parameters

SimpleXMLElement $object
string $attribute

Name of attribute to find

Return Value

SimpleXMLElement

object of the attribute

CSSContentParser cssParser()

Return a CSSContentParser for the most recent content.

Return Value

CSSContentParser

bool assertPartialMatchBySelector(string $selector, array|string $expectedMatches)

Assert that the most recently queried page contains a number of content tags specified by a CSS selector.

The given CSS selector will be applied to the HTML of the most recent page. The content of every matching tag will be examined. The assertion fails if one of the expectedMatches fails to appear.

Note:   characters are stripped from the content; make sure that your assertions take this into account.

Parameters

string $selector

A basic CSS selector, e.g. 'li.jobs h3'

array|string $expectedMatches

The content of at least one of the matched tags

Return Value

bool

Exceptions

PHPUnit_Framework_AssertionFailedError

bool assertExactMatchBySelector(string $selector, array|string $expectedMatches)

Assert that the most recently queried page contains a number of content tags specified by a CSS selector.

The given CSS selector will be applied to the HTML of the most recent page. The full HTML of every matching tag will be examined. The assertion fails if one of the expectedMatches fails to appear.

Note:   characters are stripped from the content; make sure that your assertions take this into account.

Parameters

string $selector

A basic CSS selector, e.g. 'li.jobs h3'

array|string $expectedMatches

The content of all matching tags as an array

Return Value

bool

Exceptions

PHPUnit_Framework_AssertionFailedError

bool assertPartialHTMLMatchBySelector(string $selector, array|string $expectedMatches)

Assert that the most recently queried page contains a number of content tags specified by a CSS selector.

The given CSS selector will be applied to the HTML of the most recent page. The content of every matching tag will be examined. The assertion fails if one of the expectedMatches fails to appear.

Note:   characters are stripped from the content; make sure that your assertions take this into account.

Parameters

string $selector

A basic CSS selector, e.g. 'li.jobs h3'

array|string $expectedMatches

The content of at least one of the matched tags

Return Value

bool

Exceptions

PHPUnit_Framework_AssertionFailedError

bool assertExactHTMLMatchBySelector(string $selector, array|string $expectedMatches)

Assert that the most recently queried page contains a number of content tags specified by a CSS selector.

The given CSS selector will be applied to the HTML of the most recent page. The full HTML of every matching tag will be examined. The assertion fails if one of the expectedMatches fails to appear.

Note:   characters are stripped from the content; make sure that your assertions take this into account.

Parameters

string $selector

A basic CSS selector, e.g. 'li.jobs h3'

array|string $expectedMatches

The content of all matched tags as an array

Return Value

bool

Exceptions

PHPUnit_Framework_AssertionFailedError

logInAs($member)

Log in as the given member

Parameters

$member

The ID, fixture codename, or Member object of the member that you want to log in

useDraftSite($enabled = true)

Use the draft (stage) site for testing.

This is helpful if you're not testing publication functionality and don't want "stage management" cluttering your test.

Parameters

$enabled

mixed stat(string $varName)

Return a static variable from this class.

Parameters

string $varName

Return Value

mixed

static bool get_disable_themes()

No description

Return Value

bool

static bool get_use_draft_site()

No description

Return Value

bool