PHPDoc cleanup

This commit is contained in:
Damian Mooyman 2014-07-29 09:24:40 +12:00
parent 7bbc74e576
commit 08c58844ac
2 changed files with 187 additions and 90 deletions

View File

@ -3,22 +3,22 @@
/**
* 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.
*
*
* <code>
* 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", array("Email" => "invalid email ^&*&^"));
*
* // Validate the content that is returned
* $this->assertExactMatchBySelector("#MyForm_ID p.error", array("That email address is invalid."));
* }
* }
* </code>
*
*
* @package framework
* @subpackage testing
*/
@ -27,37 +27,48 @@ class FunctionalTest extends SapphireTest {
* Set this to true on your sub-class to disable the use of themes in this test.
* This can be handy for functional testing of modules without having to worry about whether a user has changed
* behaviour by replacing the theme.
*
* @var bool
*/
protected static $disable_themes = false;
/**
* Set this to true on your sub-class to use the draft site by default for every test in this class.
*
* @var bool
*/
protected static $use_draft_site = false;
/**
* @var TestSession
*/
protected $mainSession = null;
/**
* CSSContentParser for the most recently requested page.
*
*
* @var CSSContentParser
*/
protected $cssParser = null;
/**
* If this is true, then 30x Location headers will be automatically followed.
* If not, then you will have to manaully call $this->mainSession->followRedirection() to follow them.
* However, this will let you inspect the intermediary headers
*
* @var bool
*/
protected $autoFollowRedirection = true;
/**
* @var String
* @var string
*/
protected $originalTheme = null;
/**
* Returns the {@link Session} object for this test
*
* @return Session
*/
public function session() {
return $this->mainSession->session();
@ -66,7 +77,7 @@ class FunctionalTest extends SapphireTest {
public function setUp() {
// Skip calling FunctionalTest directly.
if(get_class($this) == "FunctionalTest") $this->skipTest = true;
parent::setUp();
$this->mainSession = new TestSession();
@ -75,22 +86,22 @@ class FunctionalTest extends SapphireTest {
$this->originalTheme = Config::inst()->get('SSViewer', 'theme');
Config::inst()->update('SSViewer', 'theme', null);
}
// Switch to draft site, if necessary
if(static::get_use_draft_site()) {
$this->useDraftSite();
}
// Unprotect the site, tests are running with the assumption it's off. They will enable it on a case-by-case
// basis.
BasicAuth::protect_entire_site(false);
SecurityToken::disable();
}
public function tearDown() {
SecurityToken::enable();
parent::tearDown();
unset($this->mainSession);
@ -102,6 +113,12 @@ class FunctionalTest extends SapphireTest {
/**
* Submit a get request
* @uses Director::test()
*
* @param string $url
* @param Session $session
* @param array $headers
* @param array $cookies
* @return SS_HTTPResponse
*/
public function get($url, $session = null, $headers = null, $cookies = null) {
$this->cssParser = null;
@ -114,7 +131,15 @@ class FunctionalTest extends SapphireTest {
/**
* Submit a post request
*
* @uses Director::test()
* @param string $url
* @param array $data
* @param array $headers
* @param Session $session
* @param string $body
* @param array $cookies
* @return SS_HTTPResponse
*/
public function post($url, $data, $headers = null, $session = null, $body = null, $cookies = null) {
$this->cssParser = null;
@ -124,24 +149,24 @@ class FunctionalTest extends SapphireTest {
}
return $response;
}
/**
* 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')
*
*
* @see http://www.simpletest.org/en/form_testing_documentation.html
*
* @param String $formID HTML 'id' attribute of a form (loaded through a previous response)
* @param String $button HTML 'name' attribute of the button (NOT the 'id' attribute)
* @param Array $data Map of GET/POST data.
*
* @param string $formID HTML 'id' attribute of a form (loaded through a previous response)
* @param string $button HTML 'name' attribute of the button (NOT the 'id' attribute)
* @param array $data Map of GET/POST data.
* @return SS_HTTPResponse
*/
public function submitForm($formID, $button = null, $data = array()) {
@ -152,9 +177,11 @@ class FunctionalTest extends SapphireTest {
}
return $response;
}
/**
* Return the most recent content
*
* @return string
*/
public function content() {
return $this->mainSession->lastContent();
@ -162,7 +189,7 @@ class FunctionalTest extends SapphireTest {
/**
* Find an attribute in a SimpleXMLElement object by name.
* @param SimpleXMLElement object
* @param SimpleXMLElement $object
* @param string $attribute Name of attribute to find
* @return SimpleXMLElement object of the attribute
*/
@ -175,24 +202,24 @@ class FunctionalTest extends SapphireTest {
}
return $found;
}
/**
* Return a CSSContentParser for the most recent content.
*
*
* @return CSSContentParser
*/
public function cssParser() {
if(!$this->cssParser) $this->cssParser = new CSSContentParser($this->mainSession->lastContent());
return $this->cssParser;
}
/**
* 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: &nbsp; characters are stripped from the content; make sure that your assertions take this into account.
*
*
* @param string $selector A basic CSS selector, e.g. 'li.jobs h3'
* @param array|string $expectedMatches The content of at least one of the matched tags
* @throws PHPUnit_Framework_AssertionFailedError
@ -200,22 +227,22 @@ class FunctionalTest extends SapphireTest {
*/
public function assertPartialMatchBySelector($selector, $expectedMatches) {
if(is_string($expectedMatches)) $expectedMatches = array($expectedMatches);
$items = $this->cssParser()->getBySelector($selector);
$actuals = array();
if($items) foreach($items as $item) $actuals[trim(preg_replace("/[ \n\r\t]+/", " ", $item. ''))] = true;
foreach($expectedMatches as $match) {
$this->assertTrue(
isset($actuals[$match]),
"Failed asserting the CSS selector '$selector' has a partial match to the expected elements:\n'"
. implode("'\n'", $expectedMatches) . "'\n\n"
. implode("'\n'", $expectedMatches) . "'\n\n"
. "Instead the following elements were found:\n'" . implode("'\n'", array_keys($actuals)) . "'"
);
return false;
}
return true;
}
@ -225,7 +252,7 @@ class FunctionalTest extends SapphireTest {
* will be examined. The assertion fails if one of the expectedMatches fails to appear.
*
* Note: &nbsp; characters are stripped from the content; make sure that your assertions take this into account.
*
*
* @param string $selector A basic CSS selector, e.g. 'li.jobs h3'
* @param array|string $expectedMatches The content of *all* matching tags as an array
* @throws PHPUnit_Framework_AssertionFailedError
@ -233,19 +260,19 @@ class FunctionalTest extends SapphireTest {
*/
public function assertExactMatchBySelector($selector, $expectedMatches) {
if(is_string($expectedMatches)) $expectedMatches = array($expectedMatches);
$items = $this->cssParser()->getBySelector($selector);
$actuals = array();
if($items) foreach($items as $item) $actuals[] = trim(preg_replace("/[ \n\r\t]+/", " ", $item. ''));
$this->assertTrue(
$expectedMatches == $actuals,
"Failed asserting the CSS selector '$selector' has an exact match to the expected elements:\n'"
. implode("'\n'", $expectedMatches) . "'\n\n"
. implode("'\n'", $expectedMatches) . "'\n\n"
. "Instead the following elements were found:\n'" . implode("'\n'", $actuals) . "'"
);
return true;
}
@ -263,21 +290,21 @@ class FunctionalTest extends SapphireTest {
*/
public function assertPartialHTMLMatchBySelector($selector, $expectedMatches) {
if(is_string($expectedMatches)) $expectedMatches = array($expectedMatches);
$items = $this->cssParser()->getBySelector($selector);
$actuals = array();
if($items) foreach($items as $item) $actuals[$item->asXML()] = true;
foreach($expectedMatches as $match) {
$this->assertTrue(
isset($actuals[$match]),
"Failed asserting the CSS selector '$selector' has a partial match to the expected elements:\n'"
. implode("'\n'", $expectedMatches) . "'\n\n"
. implode("'\n'", $expectedMatches) . "'\n\n"
. "Instead the following elements were found:\n'" . implode("'\n'", array_keys($actuals)) . "'"
);
}
return true;
}
@ -287,7 +314,7 @@ class FunctionalTest extends SapphireTest {
* will be examined. The assertion fails if one of the expectedMatches fails to appear.
*
* Note: &nbsp; characters are stripped from the content; make sure that your assertions take this into account.
*
*
* @param string $selector A basic CSS selector, e.g. 'li.jobs h3'
* @param array|string $expectedMatches The content of *all* matched tags as an array
* @throws PHPUnit_Framework_AssertionFailedError
@ -298,15 +325,15 @@ class FunctionalTest extends SapphireTest {
$actuals = array();
if($items) foreach($items as $item) $actuals[] = $item->asXML();
$this->assertTrue(
$expectedMatches == $actuals,
"Failed asserting the CSS selector '$selector' has an exact match to the expected elements:\n'"
. implode("'\n'", $expectedMatches) . "'\n\n"
. implode("'\n'", $expectedMatches) . "'\n\n"
. "Instead the following elements were found:\n'" . implode("'\n'", $actuals) . "'"
);
}
/**
* Log in as the given member
* @param $member The ID, fixture codename, or Member object of the member that you want to log in
@ -315,10 +342,10 @@ class FunctionalTest extends SapphireTest {
if(is_object($member)) $memberID = $member->ID;
elseif(is_numeric($member)) $memberID = $member;
else $memberID = $this->idFromFixture('Member', $member);
$this->session()->inst_set('loggedInAs', $memberID);
}
/**
* Use the draft (stage) site for testing.
* This is helpful if you're not testing publication functionality and don't want "stage management" cluttering
@ -333,26 +360,29 @@ class FunctionalTest extends SapphireTest {
}
else {
$this->session()->inst_set('readingMode', 'Stage.Live');
$this->session()->inst_set('unsecuredDraftSite', false);
$this->session()->inst_set('unsecuredDraftSite', false);
}
}
/**
* Return a static variable from this class.
*
* @param string $varName
* @return mixed
*/
public function stat($varName) {
return static::$varName;
}
/**
* @return Boolean
* @return bool
*/
public static function get_disable_themes() {
return static::$disable_themes;
}
/**
* @return Boolean
* @return bool
*/
public static function get_use_draft_site() {
return static::$use_draft_site;

View File

@ -2,23 +2,35 @@
/**
* Represents a test usage session of a web-app
* It will maintain session-state from request to request
*
*
* @package framework
* @subpackage testing
*/
class TestSession {
private $session;
private $lastResponse;
/**
* @param Controller $controller Necessary to use the mock session
* @var Session
*/
private $session;
/**
* @var SS_HTTPResponse
*/
private $lastResponse;
/**
* Necessary to use the mock session
* created in {@link session} in the normal controller stack,
* e.g. to overwrite Member::currentUser() with custom login data.
*
* @var Controller
*/
protected $controller;
/**
* @var string $lastUrl Fake HTTP Referer Tracking, set in {@link get()} and {@link post()}.
* Fake HTTP Referer Tracking, set in {@link get()} and {@link post()}.
*
* @var string
*/
private $lastUrl;
@ -28,7 +40,7 @@ class TestSession {
$this->controller->setSession($this->session);
$this->controller->pushCurrent();
}
public function __destruct() {
// Shift off anything else that's on the stack. This can happen if something throws
// an exception that causes a premature TestSession::__destruct() call
@ -36,15 +48,21 @@ class TestSession {
if(Controller::has_curr()) $this->controller->popCurrent();
}
/**
* Submit a get request
*
* @uses Director::test()
* @param string $url
* @param Session $session
* @param array $headers
* @param array $cookies
* @return SS_HTTPResponse
*/
public function get($url, $session = null, $headers = null, $cookies = null) {
$headers = (array) $headers;
if($this->lastUrl && !isset($headers['Referer'])) $headers['Referer'] = $this->lastUrl;
$this->lastResponse
$this->lastResponse
= Director::test($url, null, $session ? $session : $this->session, null, null, $headers, $cookies);
$this->lastUrl = $url;
if(!$this->lastResponse) user_error("Director::test($url) returned null", E_USER_WARNING);
@ -53,7 +71,15 @@ class TestSession {
/**
* Submit a post request
*
* @uses Director::test()
* @param string $url
* @param array $data
* @param array $headers
* @param Session $session
* @param string $body
* @param array $cookies
* @return SS_HTTPResponse
*/
public function post($url, $data, $headers = null, $session = null, $body = null, $cookies = null) {
$headers = (array) $headers;
@ -64,24 +90,24 @@ class TestSession {
if(!$this->lastResponse) user_error("Director::test($url) returned null", E_USER_WARNING);
return $this->lastResponse;
}
/**
* 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')
*
*
* @see http://www.simpletest.org/en/form_testing_documentation.html
*
* @param String $formID HTML 'id' attribute of a form (loaded through a previous response)
* @param String $button HTML 'name' attribute of the button (NOT the 'id' attribute)
* @param Array $data Map of GET/POST data.
*
* @param string $formID HTML 'id' attribute of a form (loaded through a previous response)
* @param string $button HTML 'name' attribute of the button (NOT the 'id' attribute)
* @param array $data Map of GET/POST data.
* @return SS_HTTPResponse
*/
public function submitForm($formID, $button = null, $data = array()) {
@ -108,15 +134,17 @@ class TestSession {
$postVars = array();
parse_str($submission->_encode(), $postVars);
return $this->post($url, $postVars);
} else {
user_error("TestSession::submitForm called when there is no form loaded."
. " Visit the page with the form first", E_USER_WARNING);
}
}
/**
* If the last request was a 3xx response, then follow the redirection
*
* @return SS_HTTPResponse The response given, or null if no redirect occurred
*/
public function followRedirection() {
if($this->lastResponse->getHeader('Location')) {
@ -125,25 +153,29 @@ class TestSession {
return $this->get($url);
}
}
/**
* Returns true if the last response was a 3xx redirection
*
* @return bool
*/
public function wasRedirected() {
$code = $this->lastResponse->getStatusCode();
return $code >= 300 && $code < 400;
}
/**
* Get the most recent response, as an SS_HTTPResponse object
* Get the most recent response
*
* @return SS_HTTPResponse
*/
public function lastResponse() {
return $this->lastResponse;
}
/**
* Return the fake HTTP_REFERER; set each time get() or post() is called.
*
*
* @return string
*/
public function lastUrl() {
@ -152,19 +184,27 @@ class TestSession {
/**
* Get the most recent response's content
*
* @return string
*/
public function lastContent() {
if(is_string($this->lastResponse)) return $this->lastResponse;
else return $this->lastResponse->getBody();
}
/**
* Return a CSSContentParser containing the most recent response
*
* @return CSSContentParser
*/
public function cssParser() {
return new CSSContentParser($this->lastContent());
}
/**
* Get the last response as a SimplePage object
*
* @return SimplePage The response if available
*/
public function lastPage() {
require_once("thirdparty/simpletest/http.php");
@ -176,13 +216,15 @@ class TestSession {
$page = &$builder->parse(new TestSession_STResponseWrapper($this->lastResponse));
$builder->free();
unset($builder);
return $page;
}
}
/**
* Get the current session, as a Session object
*
* @return Session
*/
public function session() {
return $this->session;
@ -191,41 +233,66 @@ class TestSession {
/**
* Wrapper around SS_HTTPResponse to make it look like a SimpleHTTPResposne
*
*
* @package framework
* @subpackage testing
*/
class TestSession_STResponseWrapper {
/**
* @var SS_HTTPResponse
*/
private $response;
public function __construct(SS_HTTPResponse $response) {
$this->response = $response;
}
/**
* @return string
*/
public function getContent() {
return $this->response->getBody();
}
/**
* @return string
*/
public function getError() {
return "";
}
/**
* @return null
*/
public function getSent() {
return null;
}
/**
* @return string
*/
public function getHeaders() {
return "";
}
/**
* @return string 'GET'
*/
public function getMethod() {
return "GET";
}
/**
* @return string
*/
public function getUrl() {
return "";
}
/**
* @return null
*/
public function getRequestData() {
return null;
}