merging changes from [428]

git-svn-id: https://svn.cakephp.org/repo/trunk/cake@430 3807eeeb-6ff5-0310-8944-8be069107fe0
This commit is contained in:
phpnut 2005-07-30 02:26:59 +00:00
parent 616dd7d9aa
commit 57ef2eba9b
73 changed files with 10583 additions and 8923 deletions

7
vendors/simpletest/CAKE_README.txt vendored Normal file
View file

@ -0,0 +1,7 @@
SimpleTest is the testing suite we have decided to use for using Test Driven Development in the Cake core.
More information can be found here: http://www.lastcraft.com/simple_test.php
Note this code is not developed by the Developers of Cake.
We will update this vendors package as new releases become available
Current release is 1.0.1alpha

View file

@ -3,7 +3,45 @@ Simple Test interface changes
Because the SimpleTest tool set is still evolving it is likely that tests
written with earlier versions will fail with the newest ones. The most
dramatic changes are in the alpha releases. Here is a list of possible
problems...
problems and their fixes...
No class WantedPatternExpectation
---------------------------------
This was deprecated in 1.0.1alpha in favour of the simpler
name PatternExpectation.
No class NoUnwantedPatternExpectation
-------------------------------------
This was deprecated in 1.0.1alpha in favour of the simpler
name NoPatternExpectation.
No method assertNoUnwantedPattern()
-----------------------------------
This has been renamed to assertNoPattern() in 1.0.1alpha and
the old form is deprecated.
No method assertWantedPattern()
-------------------------------
This has been renamed to assertPattern() in 1.0.1alpha and
the old form is deprecated.
No method assertExpectation()
-----------------------------
This was renamed as assert() in 1.0.1alpha and the old form
has been deprecated.
No class WildcardExpectation
----------------------------
This was a mostly internal class for the mock objects. It was
renamed AnythingExpectation to bring it closer to JMock and
NMock in version 1.0.1alpha.
Missing UnitTestCase::assertErrorPattern()
------------------------------------------
This method is deprecated for version 1.0.1 onwards.
This method has been subsumed by assertError() that can now
take an expectation. Simply pass a PatternExpectation
into assertError() to simulate the old behaviour.
No HTML when matching page elements
-----------------------------------
@ -29,7 +67,9 @@ My custom test case ignored by tally()
--------------------------------------
The _assertTrue method has had it's signature changed due to a bug
in the PHP 5.0.1 release. You must now use getTest() from within
that method to get the test case.
that method to get the test case. Mock compatibility with other
unit testers is now deprecated as of 1.0.1alpha as PEAR::PHUnit2
should soon have mock support of it's own.
Broken code extending SimpleRunner
----------------------------------

View file

@ -1 +1 @@
1.0
1.0.1alpha

View file

@ -100,7 +100,26 @@
* @access public
*/
function isWithin($url) {
return (strpos($url->getBasePath(), $this->_root) === 0);
if ($this->_isIn($this->_root, $url->getBasePath())) {
return true;
}
if ($this->_isIn($this->_root, $url->getBasePath() . $url->getPage() . '/')) {
return true;
}
return false;
}
/**
* Tests to see if one string is a substring of
* another.
* @param string $part Small bit.
* @param string $whole Big bit.
* @return boolean True if the small bit is
* in the big bit.
* @access private
*/
function _isIn($part, $whole) {
return strpos($whole, $part) === 0;
}
}

View file

@ -13,11 +13,14 @@
require_once(dirname(__FILE__) . '/http.php');
require_once(dirname(__FILE__) . '/encoding.php');
require_once(dirname(__FILE__) . '/page.php');
require_once(dirname(__FILE__) . '/selector.php');
require_once(dirname(__FILE__) . '/frames.php');
require_once(dirname(__FILE__) . '/user_agent.php');
/**#@-*/
if (!defined('DEFAULT_MAX_NESTED_FRAMES')) {
define('DEFAULT_MAX_NESTED_FRAMES', 3);
}
/**
* Browser history list.
@ -66,33 +69,18 @@
/**
* Adds a successfully fetched page to the history.
* @param string $method GET or POST.
* @param SimpleUrl $url URL of fetch.
* @param SimpleFormEncoding $parameters Any post data with the fetch.
* @param SimpleEncoding $parameters Any post data with the fetch.
* @access public
*/
function recordEntry($method, $url, $parameters) {
function recordEntry($url, $parameters) {
$this->_dropFuture();
array_push(
$this->_sequence,
array('method' => $method, 'url' => $url, 'parameters' => $parameters));
array('url' => $url, 'parameters' => $parameters));
$this->_position++;
}
/**
* Last fetching method for current history
* position.
* @return string GET or POST for this point in
* the history.
* @access public
*/
function getMethod() {
if ($this->_isEmpty()) {
return false;
}
return $this->_sequence[$this->_position]['method'];
}
/**
* Last fully qualified URL for current history
* position.
@ -201,7 +189,8 @@
* @access protected
*/
function &_createUserAgent() {
return new SimpleUserAgent();
$user_agent = &new SimpleUserAgent();
return $user_agent;
}
/**
@ -210,7 +199,8 @@
* @access protected
*/
function &_createHistory() {
return new SimpleBrowserHistory();
$history = &new SimpleBrowserHistory();
return $history;
}
/**
@ -247,7 +237,7 @@
}
$frameset = &new SimpleFrameset($page);
foreach ($page->getFrameset() as $key => $url) {
$frame = &$this->_fetch('GET', $url, array(), $depth + 1);
$frame = &$this->_fetch($url, new SimpleGetEncoding(), $depth + 1);
$frameset->addFrame($frame, $key);
}
return $frameset;
@ -255,50 +245,48 @@
/**
* Fetches a page.
* @param string $method GET or POST.
* @param string/SimpleUrl $url Target to fetch as string.
* @param SimpleFormEncoding $parameters POST parameters.
* @param string/SimpleUrl $url Target to fetch.
* @param SimpleEncoding $encoding GET/POST parameters.
* @param integer $depth Nested frameset depth protection.
* @return SimplePage Parsed page.
* @access private
*/
function &_fetch($method, $url, $parameters, $depth = 0) {
$response = &$this->_user_agent->fetchResponse($method, $url, $parameters);
function &_fetch($url, $encoding, $depth = 0) {
$response = &$this->_user_agent->fetchResponse($url, $encoding);
if ($response->isError()) {
return new SimplePage($response);
$page = &new SimplePage($response);
} else {
$page = &$this->_parse($response, $depth);
}
return $this->_parse($response, $depth);
return $page;
}
/**
* Fetches a page or a single frame if that is the current
* focus.
* @param string $method GET or POST.
* @param string/SimpleUrl $url Target to fetch as string.
* @param SimpleFormEncoding $parameters POST parameters.
* @param SimpleUrl $url Target to fetch.
* @param SimpleEncoding $parameters GET/POST parameters.
* @return string Raw content of page.
* @access private
*/
function _load($method, $url, $parameters = false) {
function _load($url, $parameters) {
$frame = $url->getTarget();
if (! $frame || ! $this->_page->hasFrames() || (strtolower($frame) == '_top')) {
return $this->_loadPage($method, $url, $parameters);
return $this->_loadPage($url, $parameters);
}
return $this->_loadFrame(array($frame), $method, $url, $parameters);
return $this->_loadFrame(array($frame), $url, $parameters);
}
/**
* Fetches a page and makes it the current page/frame.
* @param string $method GET or POST.
* @param string/SimpleUrl $url Target to fetch as string.
* @param SimpleFormEncoding $parameters POST parameters.
* @param SimplePostEncoding $parameters POST parameters.
* @return string Raw content of page.
* @access private
*/
function _loadPage($method, $url, $parameters = false) {
$this->_page = &$this->_fetch(strtoupper($method), $url, $parameters);
function _loadPage($url, $parameters) {
$this->_page = &$this->_fetch($url, $parameters);
$this->_history->recordEntry(
$this->_page->getMethod(),
$this->_page->getUrl(),
$this->_page->getRequestData());
return $this->_page->getRaw();
@ -308,14 +296,13 @@
* Fetches a frame into the existing frameset replacing the
* original.
* @param array $frames List of names to drill down.
* @param string $method GET or POST.
* @param string/SimpleUrl $url Target to fetch as string.
* @param SimpleFormEncoding $parameters POST parameters.
* @return string Raw content of page.
* @access private
*/
function _loadFrame($frames, $method, $url, $parameters = false) {
$page = &$this->_fetch(strtoupper($method), $url, $parameters);
function _loadFrame($frames, $url, $parameters) {
$page = &$this->_fetch($url, $parameters);
$this->_page->setFrame($frames, $page);
}
@ -435,7 +422,7 @@
* Fetches the page content with a HEAD request.
* Will affect cookies, but will not change the base URL.
* @param string/SimpleUrl $url Target to fetch as string.
* @param hash/SimpleFormEncoding $parameters Additional parameters for
* @param hash/SimpleHeadEncoding $parameters Additional parameters for
* HEAD request.
* @return boolean True if successful.
* @access public
@ -444,16 +431,10 @@
if (! is_object($url)) {
$url = new SimpleUrl($url);
}
if (is_array($parameters)) {
$parameters = new SimpleFormEncoding($parameters);
}
if ($this->getUrl()) {
$url = $url->makeAbsolute($this->getUrl());
}
$response = &$this->_user_agent->fetchResponse(
'HEAD',
$url,
$parameters);
$response = &$this->_user_agent->fetchResponse($url, new SimpleHeadEncoding($parameters));
return ! $response->isError();
}
@ -469,13 +450,10 @@
if (! is_object($url)) {
$url = new SimpleUrl($url);
}
if (is_array($parameters)) {
$parameters = new SimpleFormEncoding($parameters);
}
if ($this->getUrl()) {
$url = $url->makeAbsolute($this->getUrl());
}
return $this->_load('GET', $url, $parameters);
return $this->_load($url, new SimpleGetEncoding($parameters));
}
/**
@ -489,13 +467,10 @@
if (! is_object($url)) {
$url = new SimpleUrl($url);
}
if (is_array($parameters)) {
$parameters = new SimpleFormEncoding($parameters);
}
if ($this->getUrl()) {
$url = $url->makeAbsolute($this->getUrl());
}
return $this->_load('POST', $url, $parameters);
return $this->_load($url, new SimplePostEncoding($parameters));
}
/**
@ -511,16 +486,12 @@
if (count($frames) > 0) {
$this->_loadFrame(
$frames,
$this->_page->getMethod(),
$this->_page->getUrl(),
$this->_page->getRequestData());
return $this->_page->getRaw();
}
if ($method = $this->_history->getMethod()) {
$this->_page = &$this->_fetch(
$method,
$this->_history->getUrl(),
$this->_history->getParameters());
if ($url = $this->_history->getUrl()) {
$this->_page = &$this->_fetch($url, $this->_history->getParameters());
return $this->_page->getRaw();
}
return false;
@ -529,7 +500,8 @@
/**
* Equivalent to hitting the back button on the
* browser. The browser history is unchanged on
* failure.
* failure. The page content is refetched as there
* is no concept of content caching in SimpleTest.
* @return boolean True if history entry and
* fetch succeeded
* @access public
@ -548,7 +520,8 @@
/**
* Equivalent to hitting the forward button on the
* browser. The browser history is unchanged on
* failure.
* failure. The page content is refetched as there
* is no concept of content caching in SimpleTest.
* @return boolean True if history entry and
* fetch succeeded
* @access public
@ -774,6 +747,18 @@
return $this->_page->setField($name, $value);
}
/**
* Sets all form fields with that name. Will use label if
* one is available (not yet implemented).
* @param string $name Name of field in forms.
* @param string $value New value of field.
* @return boolean True if field exists, otherwise false.
* @access public
*/
function setFieldByName($name, $value) {
return $this->_page->setFieldByName($name, $value);
}
/**
* Sets all form fields with that id attribute.
* @param string/integer $id Id of field in forms.
@ -785,6 +770,19 @@
return $this->_page->setFieldById($id, $value);
}
/**
* Accessor for a form element value within the page.
* Finds the first match.
* @param string $label Field label.
* @return string/boolean A value if the field is
* present, false if unchecked
* and null if missing.
* @access public
*/
function getField($label) {
return $this->_page->getField($label);
}
/**
* Accessor for a form element value within the page.
* Finds the first match.
@ -794,8 +792,8 @@
* and null if missing.
* @access public
*/
function getField($name) {
return $this->_page->getField($name);
function getFieldByName($name) {
return $this->_page->getFieldByName($name);
}
/**
@ -824,9 +822,8 @@
return false;
}
$success = $this->_load(
$form->getMethod(),
$form->getAction(),
$form->submitButtonByLabel($label, $additional));
$form->submitButton(new SimpleByLabel($label), $additional));
return ($success ? $this->getContent() : $success);
}
@ -843,9 +840,8 @@
return false;
}
$success = $this->_load(
$form->getMethod(),
$form->getAction(),
$form->submitButtonByName($name, $additional));
$form->submitButton(new SimpleByName($name), $additional));
return ($success ? $this->getContent() : $success);
}
@ -862,9 +858,8 @@
return false;
}
$success = $this->_load(
$form->getMethod(),
$form->getAction(),
$form->submitButtonById($id, $additional));
$form->submitButton(new SimpleById($id), $additional));
return ($success ? $this->getContent() : $success);
}
@ -886,9 +881,8 @@
return false;
}
$success = $this->_load(
$form->getMethod(),
$form->getAction(),
$form->submitImageByLabel($label, $x, $y, $additional));
$form->submitImage(new SimpleByLabel($label), $x, $y, $additional));
return ($success ? $this->getContent() : $success);
}
@ -910,9 +904,8 @@
return false;
}
$success = $this->_load(
$form->getMethod(),
$form->getAction(),
$form->submitImageByName($name, $x, $y, $additional));
$form->submitImage(new SimpleByName($name), $x, $y, $additional));
return ($success ? $this->getContent() : $success);
}
@ -933,9 +926,8 @@
return false;
}
$success = $this->_load(
$form->getMethod(),
$form->getAction(),
$form->submitImageById($id, $x, $y, $additional));
$form->submitImage(new SimpleById($id), $x, $y, $additional));
return ($success ? $this->getContent() : $success);
}
@ -951,7 +943,6 @@
return false;
}
$success = $this->_load(
$form->getMethod(),
$form->getAction(),
$form->submit());
return ($success ? $this->getContent() : $success);
@ -975,7 +966,7 @@
if (count($urls) < $index + 1) {
return false;
}
$this->_load('GET', $urls[$index]);
$this->_load($urls[$index], new SimpleGetEncoding());
return $this->getContent();
}
@ -999,7 +990,7 @@
if (! ($url = $this->_page->getUrlById($id))) {
return false;
}
$this->_load('GET', $url);
$this->_load($url, new SimpleGetEncoding());
return $this->getContent();
}
@ -1012,5 +1003,23 @@
function isLinkById($id) {
return (boolean)$this->_page->getUrlById($id);
}
/**
* Clicks a visible text item. Will first try buttons,
* then links and then images.
* @param string $label Visible text or alt text.
* @return string/boolean Raw page or false.
* @access public
*/
function click($label) {
$raw = $this->clickSubmit($label);
if (! $raw) {
$raw = $this->clickLink($label);
}
if (! $raw) {
$raw = $this->clickImage($label);
}
return $raw;
}
}
?>

123
vendors/simpletest/collector.php vendored Normal file
View file

@ -0,0 +1,123 @@
<?php
/**
* This file contains the following classes: {@link SimpleCollector},
* {@link SimplePatternCollector}.
*
* @author Travis Swicegood <development@domain51.com>
* @package SimpleTest
* @subpackage UnitTester
* @version $Id: collector.php,v 1.6 2005/03/26 01:54:05 tswicegood Exp $
*/
/**
* The basic collector for {@link GroupTest}
*
* @see collect(), GroupTest::collect()
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleCollector {
/**
* Strips off any kind of slash at the end so as to normalise the path
*
* @param string $path Path to normalise.
*/
function _removeTrailingSlash($path) {
return preg_replace('|[\\/]$|', '', $path);
/**
* @internal
* Try benchmarking the following. It's more code, but by not using the
* regex, it may be faster? Also, shouldn't be looking for
* DIRECTORY_SEPERATOR instead of a manual "/"?
*/
if (substr($path, -1) == DIRECTORY_SEPERATOR) {
return substr($path, 0, -1);
} else {
return $path;
}
}
/**
* Scans the directory and adds what it can.
* @param object $test Group test with {@link GroupTest::addTestFile()} method.
* @param string $path Directory to scan.
* @see _attemptToAdd()
*/
function collect(&$test, $path) {
$path = $this->_removeTrailingSlash($path);
if ($handle = opendir($path)) {
while (($entry = readdir($handle)) !== false) {
$this->_handle($test, $path . DIRECTORY_SEPARATOR . $entry);
}
closedir($handle);
}
}
/**
* This method determines what should be done with a given file and adds
* it via {@link GroupTest::addTestFile()} if necessary.
*
* This method should be overriden to provide custom matching criteria,
* such as pattern matching, recursive matching, etc. For an example, see
* {@link SimplePatternCollector::_handle()}.
*
* @param object $test Group test with {@link GroupTest::addTestFile()} method.
* @param string $filename A filename as generated by {@link collect()}
* @see collect()
* @access protected
*/
function _handle(&$test, $file) {
if (!is_dir($file)) {
$test->addTestFile($file);
}
}
}
/**
* An extension to {@link SimpleCollector} that only adds files matching a
* given pattern.
*
* @package SimpleTest
* @subpackage UnitTester
* @see SimpleCollector
*/
class SimplePatternCollector extends SimpleCollector {
var $_pattern;
/**
* Scans the directory and adds what it can that matches a given pattern.
*
* No verification is done on the pattern, so it is incumbent about the
* developer to insure it is a proper pattern.
*
* Defaults to files ending in "php"
*
* @param object $test See {@link SimpleCollector::collect()}
* @param string $path See {@link Simplecollector::collect()}
* @param string $pattern Perl compatible regex to test name against
* See {@link http://us4.php.net/manual/en/reference.pcre.pattern.syntax.php PHP's PCRE}
* for full documentation of valid pattern.s
*/
function collect(&$test, $path, $pattern = '/php$/i') {
$this->_pattern = $pattern;
parent::collect($test, $path);
}
/**
* Attempts to add files that match a given pattern.
*
* @see SimpleCollector::_handle()
* @param object $test Group test with {@link GroupTest::addTestFile()} method.
* @param string $path Directory to scan.
* @access protected
*/
function _handle(&$test, $filename) {
if (preg_match($this->_pattern, $filename)) {
parent::_handle($test, $filename);
}
}
}
?>

View file

@ -8,7 +8,9 @@
/**
* does type matter
*/
if (!defined('TYPE_MATTERS')) {
define('TYPE_MATTERS', true);
}
/**
* Displays variables as text and does diffs.
@ -221,9 +223,10 @@
if (is_object($second) || is_array($second)) {
return $this->_describeGenericDifference($first, $second);
}
return "because " . $this->describeValue($first) .
return "because [" . $this->describeValue($first) .
"] differs from [" .
$this->describeValue($second) . "]";
$this->describeValue($second) . "] by " .
abs($first - $second);
}
/**

View file

@ -6,33 +6,214 @@
* @version $Id$
*/
/**#@+
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/socket.php');
/**#@-*/
/**
* Single post parameter.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleEncodedPair {
var $_key;
var $_value;
/**
* Stashes the data for rendering later.
* @param string $key Form element name.
* @param string $value Data to send.
*/
function SimpleEncodedPair($key, $value) {
$this->_key = $key;
$this->_value = $value;
}
/**
* The pair as a single string.
* @return string Encoded pair.
* @access public
*/
function asRequest() {
return $this->_key . '=' . urlencode($this->_value);
}
/**
* The MIME part as a string.
* @return string MIME part encoding.
* @access public
*/
function asMime() {
$part = 'Content-Disposition: form-data; ';
$part .= "name=\"" . $this->_key . "\"\r\n";
$part .= "\r\n" . $this->_value;
return $part;
}
/**
* Is this the value we are looking for?
* @param string $key Identifier.
* @return boolean True if matched.
* @access public
*/
function isKey($key) {
return $key == $this->_key;
}
/**
* Is this the value we are looking for?
* @return string Identifier.
* @access public
*/
function getKey() {
return $this->_key;
}
/**
* Is this the value we are looking for?
* @return string Content.
* @access public
*/
function getValue() {
return $this->_value;
}
}
/**
* Single post parameter.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleAttachment {
var $_key;
var $_content;
var $_filename;
/**
* Stashes the data for rendering later.
* @param string $key Key to add value to.
* @param string $content Raw data.
* @param hash $filename Original filename.
*/
function SimpleAttachment($key, $content, $filename) {
$this->_key = $key;
$this->_content = $content;
$this->_filename = $filename;
}
/**
* The pair as a single string.
* @return string Encoded pair.
* @access public
*/
function asRequest() {
return '';
}
/**
* The MIME part as a string.
* @return string MIME part encoding.
* @access public
*/
function asMime() {
$part = 'Content-Disposition: form-data; ';
$part .= 'name="' . $this->_key . '"; ';
$part .= 'filename="' . $this->_filename . '"';
$part .= "\r\nContent-Type: " . $this->_deduceMimeType();
$part .= "\r\n\r\n" . $this->_content;
return $part;
}
/**
* Attempts to figure out the MIME type from the
* file extension and the content.
* @return string MIME type.
* @access private
*/
function _deduceMimeType() {
if ($this->_isOnlyAscii($this->_content)) {
return 'text/plain';
}
return 'application/octet-stream';
}
/**
* Tests each character is in the range 0-127.
* @param string $ascii String to test.
* @access private
*/
function _isOnlyAscii($ascii) {
for ($i = 0, $length = strlen($ascii); $i < $length; $i++) {
if (ord($ascii[$i]) > 127) {
return false;
}
}
return true;
}
/**
* Is this the value we are looking for?
* @param string $key Identifier.
* @return boolean True if matched.
* @access public
*/
function isKey($key) {
return $key == $this->_key;
}
/**
* Is this the value we are looking for?
* @return string Identifier.
* @access public
*/
function getKey() {
return $this->_key;
}
/**
* Is this the value we are looking for?
* @return string Content.
* @access public
*/
function getValue() {
return $this->_filename;
}
}
/**
* Bundle of GET/POST parameters. Can include
* repeated parameters.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleFormEncoding {
class SimpleEncoding {
var $_request;
var $_x;
var $_y;
/**
* Starts empty.
* @param array $query/SimpleQueryString Hash of parameters.
* @param array $query Hash of parameters.
* Multiple values are
* as lists on a single key.
* @access public
*/
function SimpleFormEncoding($query = false) {
function SimpleEncoding($query = false) {
if (! $query) {
$query = array();
}
$this->_request = array();
$this->setCoordinates();
$this->clear();
$this->merge($query);
}
/**
* Empties the request of parameters.
* @access public
*/
function clear() {
$this->_request = array();
}
/**
* Adds a parameter to the query.
* @param string $key Key to add value to.
@ -43,18 +224,37 @@
if ($value === false) {
return;
}
if (! isset($this->_request[$key])) {
$this->_request[$key] = array();
}
if (is_array($value)) {
foreach ($value as $item) {
$this->_request[$key][] = $item;
$this->_addPair($key, $item);
}
} else {
$this->_request[$key][] = $value;
$this->_addPair($key, $value);
}
}
/**
* Adds a new value into the request.
* @param string $key Key to add value to.
* @param string/array $value New data.
* @access private
*/
function _addPair($key, $value) {
$this->_request[] = new SimpleEncodedPair($key, $value);
}
/**
* Adds a MIME part to the query. Does nothing for a
* form encoded packet.
* @param string $key Key to add value to.
* @param string $content Raw data.
* @param hash $filename Original filename.
* @access public
*/
function attach($key, $content, $filename) {
$this->_request[] = new SimpleAttachment($key, $content, $filename);
}
/**
* Adds a set of parameters to this query.
* @param array/SimpleQueryString $query Multiple values are
@ -63,12 +263,7 @@
*/
function merge($query) {
if (is_object($query)) {
foreach ($query->getKeys() as $key) {
$this->add($key, $query->getValue($key));
}
if ($query->getX() !== false) {
$this->setCoordinates($query->getX(), $query->getY());
}
$this->_request = array_merge($this->_request, $query->getAll());
} elseif (is_array($query)) {
foreach ($query as $key => $value) {
$this->add($key, $value);
@ -76,40 +271,6 @@
}
}
/**
* Sets image coordinates. Set to false to clear
* them.
* @param integer $x Horizontal position.
* @param integer $y Vertical position.
* @access public
*/
function setCoordinates($x = false, $y = false) {
if (($x === false) || ($y === false)) {
$this->_x = $this->_y = false;
return;
}
$this->_x = (integer)$x;
$this->_y = (integer)$y;
}
/**
* Accessor for horizontal image coordinate.
* @return integer X value.
* @access public
*/
function getX() {
return $this->_x;
}
/**
* Accessor for vertical image coordinate.
* @return integer Y value.
* @access public
*/
function getY() {
return $this->_y;
}
/**
* Accessor for single value.
* @return string/array False if missing, string
@ -118,22 +279,227 @@
* @access public
*/
function getValue($key) {
if (! isset($this->_request[$key])) {
$values = array();
foreach ($this->_request as $pair) {
if ($pair->isKey($key)) {
$values[] = $pair->getValue();
}
}
if (count($values) == 0) {
return false;
} elseif (count($this->_request[$key]) == 1) {
return $this->_request[$key][0];
} elseif (count($values) == 1) {
return $values[0];
} else {
return $this->_request[$key];
return $values;
}
}
/**
* Accessor for key list.
* @return array List of keys present.
* Accessor for listing of pairs.
* @return array All pair objects.
* @access public
*/
function getKeys() {
return array_keys($this->_request);
function getAll() {
return $this->_request;
}
/**
* Renders the query string as a URL encoded
* request part.
* @return string Part of URL.
* @access protected
*/
function _encode() {
$statements = array();
foreach ($this->_request as $pair) {
if ($statement = $pair->asRequest()) {
$statements[] = $statement;
}
}
return implode('&', $statements);
}
}
/**
* Bundle of GET parameters. Can include
* repeated parameters.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleGetEncoding extends SimpleEncoding {
/**
* Starts empty.
* @param array $query Hash of parameters.
* Multiple values are
* as lists on a single key.
* @access public
*/
function SimpleGetEncoding($query = false) {
$this->SimpleEncoding($query);
}
/**
* HTTP request method.
* @return string Always GET.
* @access public
*/
function getMethod() {
return 'GET';
}
/**
* Writes no extra headers.
* @param SimpleSocket $socket Socket to write to.
* @access public
*/
function writeHeadersTo(&$socket) {
}
/**
* No data is sent to the socket as the data is encoded into
* the URL.
* @param SimpleSocket $socket Socket to write to.
* @access public
*/
function writeTo(&$socket) {
}
/**
* Renders the query string as a URL encoded
* request part for attaching to a URL.
* @return string Part of URL.
* @access public
*/
function asUrlRequest() {
return $this->_encode();
}
}
/**
* Bundle of URL parameters for a HEAD request.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleHeadEncoding extends SimpleGetEncoding {
/**
* Starts empty.
* @param array $query Hash of parameters.
* Multiple values are
* as lists on a single key.
* @access public
*/
function SimpleHeadEncoding($query = false) {
$this->SimpleGetEncoding($query);
}
/**
* HTTP request method.
* @return string Always HEAD.
* @access public
*/
function getMethod() {
return 'HEAD';
}
}
/**
* Bundle of POST parameters. Can include
* repeated parameters.
* @package SimpleTest
* @subpackage WebTester
*/
class SimplePostEncoding extends SimpleEncoding {
/**
* Starts empty.
* @param array $query Hash of parameters.
* Multiple values are
* as lists on a single key.
* @access public
*/
function SimplePostEncoding($query = false) {
$this->SimpleEncoding($query);
}
/**
* HTTP request method.
* @return string Always POST.
* @access public
*/
function getMethod() {
return 'POST';
}
/**
* Dispatches the form headers down the socket.
* @param SimpleSocket $socket Socket to write to.
* @access public
*/
function writeHeadersTo(&$socket) {
$socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n");
$socket->write("Content-Type: application/x-www-form-urlencoded\r\n");
}
/**
* Dispatches the form data down the socket.
* @param SimpleSocket $socket Socket to write to.
* @access public
*/
function writeTo(&$socket) {
$socket->write($this->_encode());
}
/**
* Renders the query string as a URL encoded
* request part for attaching to a URL.
* @return string Part of URL.
* @access public
*/
function asUrlRequest() {
return '';
}
}
/**
* Bundle of POST parameters in the multipart
* format. Can include file uploads.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleMultipartEncoding extends SimplePostEncoding {
var $_boundary;
/**
* Starts empty.
* @param array $query Hash of parameters.
* Multiple values are
* as lists on a single key.
* @access public
*/
function SimpleMultipartEncoding($query = false, $boundary = false) {
$this->SimplePostEncoding($query);
$this->_boundary = ($boundary === false ? uniqid('st') : $boundary);
}
/**
* Dispatches the form headers down the socket.
* @param SimpleSocket $socket Socket to write to.
* @access public
*/
function writeHeadersTo(&$socket) {
$socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n");
$socket->write("Content-Type: multipart/form-data, boundary=" . $this->_boundary . "\r\n");
}
/**
* Dispatches the form data down the socket.
* @param SimpleSocket $socket Socket to write to.
* @access public
*/
function writeTo(&$socket) {
$socket->write($this->_encode());
}
/**
@ -142,15 +508,14 @@
* @return string Part of URL.
* @access public
*/
function asString() {
$statements = array();
foreach ($this->_request as $key => $values) {
foreach ($values as $value) {
$statements[] = "$key=" . urlencode($value);
function _encode() {
$stream = '';
foreach ($this->_request as $pair) {
$stream .= "--" . $this->_boundary . "\r\n";
$stream .= $pair->asMime() . "\r\n";
}
}
$coords = ($this->_x !== false) ? '?' . $this->_x . ',' . $this->_y : '';
return implode('&', $statements) . $coords;
$stream .= "--" . $this->_boundary . "--\r\n";
return $stream;
}
}
?>

View file

@ -103,7 +103,7 @@
* @return boolean True if correct.
* @access public
*/
function test($compare, $nasty = false) {
function test($compare) {
return (($this->_value == $compare) && ($compare == $this->_value));
}
@ -181,6 +181,127 @@
}
}
/**
* Test for being within a range.
* @package SimpleTest
* @subpackage UnitTester
*/
class WithinMarginExpectation extends SimpleExpectation {
var $_upper;
var $_lower;
/**
* Sets the value to compare against and the fuzziness of
* the match. Used for comparing floating point values.
* @param mixed $value Test value to match.
* @param mixed $margin Fuzziness of match.
* @param string $message Customised message on failure.
* @access public
*/
function WithinMarginExpectation($value, $margin, $message = '%s') {
$this->SimpleExpectation($message);
$this->_upper = $value + $margin;
$this->_lower = $value - $margin;
}
/**
* Tests the expectation. True if it matches the
* held value.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
function test($compare) {
return (($compare <= $this->_upper) && ($compare >= $this->_lower));
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
if ($this->test($compare)) {
return $this->_withinMessage($compare);
} else {
return $this->_outsideMessage($compare);
}
}
/**
* Creates a the message for being within the range.
* @param mixed $compare Value being tested.
* @access private
*/
function _withinMessage($compare) {
return "Within expectation [" . $this->_dumper->describeValue($this->_lower) . "] and [" .
$this->_dumper->describeValue($this->_upper) . "]";
}
/**
* Creates a the message for being within the range.
* @param mixed $compare Value being tested.
* @access private
*/
function _outsideMessage($compare) {
if ($compare > $this->_upper) {
return "Outside expectation " .
$this->_dumper->describeDifference($compare, $this->_upper);
} else {
return "Outside expectation " .
$this->_dumper->describeDifference($compare, $this->_lower);
}
}
}
/**
* Test for being outside of a range.
* @package SimpleTest
* @subpackage UnitTester
*/
class OutsideMarginExpectation extends WithinMarginExpectation {
/**
* Sets the value to compare against and the fuzziness of
* the match. Used for comparing floating point values.
* @param mixed $value Test value to not match.
* @param mixed $margin Fuzziness of match.
* @param string $message Customised message on failure.
* @access public
*/
function OutsideMarginExpectation($value, $margin, $message = '%s') {
$this->WithinMarginExpectation($value, $margin, $message);
}
/**
* Tests the expectation. True if it matches the
* held value.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
function test($compare) {
return ! parent::test($compare);
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
if (! $this->test($compare)) {
return $this->_withinMessage($compare);
} else {
return $this->_outsideMessage($compare);
}
}
}
/**
* Test for identity.
* @package SimpleTest
@ -280,7 +401,7 @@
* @package SimpleTest
* @subpackage UnitTester
*/
class WantedPatternExpectation extends SimpleExpectation {
class PatternExpectation extends SimpleExpectation {
var $_pattern;
/**
@ -289,7 +410,7 @@
* @param string $message Customised message on failure.
* @access public
*/
function WantedPatternExpectation($pattern, $message = '%s') {
function PatternExpectation($pattern, $message = '%s') {
$this->SimpleExpectation($message);
$this->_pattern = $pattern;
}
@ -350,13 +471,19 @@
}
}
/**
* @deprecated
*/
class WantedPatternExpectation extends PatternExpectation {
}
/**
* Fail if a pattern is detected within the
* comparison.
* @package SimpleTest
* @subpackage UnitTester
*/
class UnwantedPatternExpectation extends WantedPatternExpectation {
class NoPatternExpectation extends PatternExpectation {
/**
* Sets the reject pattern
@ -364,8 +491,8 @@
* @param string $message Customised message on failure.
* @access public
*/
function UnwantedPatternExpectation($pattern, $message = '%s') {
$this->WantedPatternExpectation($pattern, $message);
function NoPatternExpectation($pattern, $message = '%s') {
$this->PatternExpectation($pattern, $message);
}
/**
@ -398,6 +525,12 @@
}
}
/**
* @deprecated
*/
class UnwantedPatternExpectation extends NoPatternExpectation {
}
/**
* Tests either type or class name if it's an object.
* @package SimpleTest

View file

@ -9,10 +9,10 @@
/**#@+
* include SimpleTest files
*/
require_once dirname(__FILE__) . '/../dumper.php';
require_once dirname(__FILE__) . '/../options.php';
require_once dirname(__FILE__) . '/../simple_test.php';
require_once dirname(__FILE__) . '/../expectation.php';
require_once(dirname(__FILE__) . '/../dumper.php');
require_once(dirname(__FILE__) . '/../options.php');
require_once(dirname(__FILE__) . '/../simple_test.php');
require_once(dirname(__FILE__) . '/../expectation.php');
/**#@-*/
/**
@ -48,7 +48,7 @@
} else {
$expectation = &new IdenticalExpectation($first);
}
$this->assertExpectation($expectation, $second, $message);
$this->assert($expectation, $second, $message);
}
/**
@ -141,10 +141,7 @@
* @public
*/
function assertRegExp($pattern, $subject, $message = "%s") {
$this->assertExpectation(
new WantedPatternExpectation($pattern),
$subject,
$message);
$this->assert(new PatternExpectation($pattern), $subject, $message);
}
/**

View file

@ -9,10 +9,8 @@
/**#@+
* include SimpleTest files
*/
require_once dirname(__FILE__).DIRECTORY_SEPARATOR
.'..'.DIRECTORY_SEPARATOR . 'unit_tester.php';
require_once dirname(__FILE__).DIRECTORY_SEPARATOR
.'..'.DIRECTORY_SEPARATOR . 'expectation.php';
require_once(dirname(__FILE__) . '/../unit_tester.php');
require_once(dirname(__FILE__) . '/../expectation.php');
/**#@-*/
/**
@ -52,25 +50,18 @@
* @public
*/
function assertEquals($first, $second, $message = false) {
$this->assertExpectation(
new EqualExpectation($first),
$second,
$message);
parent::assert(new EqualExpectation($first), $second, $message);
}
/**
* Will test straight equality if set to loose
* typing, or identity if not.
* Simple string equality.
* @param $first First value.
* @param $second Comparison value.
* @param $message Message to display.
* @public
*/
function assertEqualsMultilineStrings($first, $second, $message = false) {
$this->assertExpectation(
new EqualExpectation($first),
$second,
$message);
parent::assert(new EqualExpectation($first), $second, $message);
}
/**
@ -81,10 +72,7 @@
* @public
*/
function assertRegexp($pattern, $subject, $message = false) {
$this->assertExpectation(
new WantedPatternExpectation($pattern),
$subject,
$message);
parent::assert(new PatternExpectation($pattern), $subject, $message);
}
/**
@ -94,7 +82,7 @@
* @public
*/
function error($message) {
parent::assertTrue(false, "Error triggered [$message]");
parent::fail("Error triggered [$message]");
}
/**

View file

@ -11,90 +11,9 @@
*/
require_once(dirname(__FILE__) . '/tag.php');
require_once(dirname(__FILE__) . '/encoding.php');
require_once(dirname(__FILE__) . '/selector.php');
/**#@-*/
/**
* Used to extract form elements for testing against.
* Searches by name attribute.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleNameSelector {
var $_name;
/**
* Stashes the name for later comparison.
* @param string $name Name attribute to match.
*/
function SimpleNameSelector($name) {
$this->_name = $name;
}
/**
* Comparison. Compares with name attribute of
* widget.
* @param SimpleWidget $widget Control to compare.
* @access public
*/
function isMatch($widget) {
return ($widget->getName() == $this->_name);
}
}
/**
* Used to extract form elements for testing against.
* Searches by visible label or alt text.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleLabelSelector {
var $_label;
/**
* Stashes the name for later comparison.
* @param string $label Visible text to match.
*/
function SimpleLabelSelector($label) {
$this->_label = $label;
}
/**
* Comparison. Compares visible text of widget.
* @param SimpleWidget $widget Control to compare.
* @access public
*/
function isMatch($widget) {
return (trim($widget->getLabel()) == trim($this->_label));
}
}
/**
* Used to extract form elements for testing against.
* Searches dy id attribute.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleIdSelector {
var $_id;
/**
* Stashes the name for later comparison.
* @param string $id ID atribute to match.
*/
function SimpleIdSelector($id) {
$this->_id = $id;
}
/**
* Comparison. Compares id attribute of widget.
* @param SimpleWidget $widget Control to compare.
* @access public
*/
function isMatch($widget) {
return $widget->isId($this->_id);
}
}
/**
* Form tag class to hold widget values.
* @package SimpleTest
@ -103,6 +22,7 @@
class SimpleForm {
var $_method;
var $_action;
var $_encoding;
var $_default_target;
var $_id;
var $_buttons;
@ -119,6 +39,7 @@
function SimpleForm($tag, $url) {
$this->_method = $tag->getAttribute('method');
$this->_action = $this->_createAction($tag->getAttribute('action'), $url);
$this->_encoding = $this->_setEncodingClass($tag);
$this->_default_target = false;
$this->_id = $tag->getAttribute('id');
$this->_buttons = array();
@ -128,6 +49,22 @@
$this->_checkboxes = array();
}
/**
* Creates the request packet to be sent by the form.
* @param SimpleTag $tag Form tag to read.
* @return string Packet class.
* @access private
*/
function _setEncodingClass($tag) {
if (strtolower($tag->getAttribute('method')) == 'post') {
if (strtolower($tag->getAttribute('enctype')) == 'multipart/form-data') {
return 'SimpleMultipartEncoding';
}
return 'SimplePostEncoding';
}
return 'SimpleGetEncoding';
}
/**
* Sets the frame target within a frameset.
* @param string $frame Name of frame.
@ -154,14 +91,10 @@
* @return SimpleUrl Absolute form target.
*/
function _createAction($action, $base) {
if ($action === false) {
if (is_bool($action)) {
return $base;
}
if ($action === true) {
$url = new SimpleUrl('');
} else {
$url = new SimpleUrl($action);
}
return $url->makeAbsolute($base);
}
@ -178,6 +111,21 @@
return $url;
}
/**
* Creates the encoding for the current values in the
* form.
* @return SimpleFormEncoding Request to submit.
* @access private
*/
function _encode() {
$class = $this->_encoding;
$encoding = new $class();
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
$this->_widgets[$i]->write($encoding);
}
return $encoding;
}
/**
* ID field of form for unique identification.
* @return string Unique tag ID.
@ -192,7 +140,7 @@
* @param SimpleWidget $tag Input tag to add.
* @access public
*/
function addWidget($tag) {
function addWidget(&$tag) {
if (strtolower($tag->getAttribute('type')) == 'submit') {
$this->_buttons[] = &$tag;
} elseif (strtolower($tag->getAttribute('type')) == 'image') {
@ -208,7 +156,7 @@
* @param SimpleWidget $tag Incoming form control.
* @access private
*/
function _setWidget($tag) {
function _setWidget(&$tag) {
if (strtolower($tag->getAttribute('type')) == 'radio') {
$this->_addRadioButton($tag);
} elseif (strtolower($tag->getAttribute('type')) == 'checkbox') {
@ -223,7 +171,7 @@
* @param SimpleRadioButtonTag $tag Incoming form control.
* @access private
*/
function _addRadioButton($tag) {
function _addRadioButton(&$tag) {
if (! isset($this->_radios[$tag->getName()])) {
$this->_widgets[] = &new SimpleRadioGroup();
$this->_radios[$tag->getName()] = count($this->_widgets) - 1;
@ -236,7 +184,7 @@
* @param SimpleCheckboxTag $tag Incoming form control.
* @access private
*/
function _addCheckbox($tag) {
function _addCheckbox(&$tag) {
if (! isset($this->_checkboxes[$tag->getName()])) {
$this->_widgets[] = &$tag;
$this->_checkboxes[$tag->getName()] = count($this->_widgets) - 1;
@ -258,7 +206,7 @@
* if not set.
* @access public
*/
function _getValueBySelector($selector) {
function getValue($selector) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($selector->isMatch($this->_widgets[$i])) {
return $this->_widgets[$i]->getValue();
@ -272,28 +220,6 @@
return null;
}
/**
* Extracts current value from form.
* @param string $name Keyed by widget name.
* @return string/array Value(s) or null
* if not set.
* @access public
*/
function getValue($name) {
return $this->_getValueBySelector(new SimpleNameSelector($name));
}
/**
* Extracts current value from form by the ID.
* @param string/integer $id Keyed by widget ID attribute.
* @return string/array Value(s) or null
* if not set.
* @access public
*/
function getValueById($id) {
return $this->_getValueBySelector(new SimpleIdSelector($id));
}
/**
* Sets a widget value within the form.
* @param SimpleSelector $selector Criteria to apply.
@ -303,7 +229,7 @@
* present, nothing will be set.
* @access public
*/
function _setFieldBySelector($selector, $value) {
function setField($selector, $value) {
$success = false;
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($selector->isMatch($this->_widgets[$i])) {
@ -316,45 +242,20 @@
}
/**
* Sets a widget value within the form.
* @param string $name Name of widget tag.
* @param string $value Value to input into the widget.
* @return boolean True if value is legal, false
* otherwise. If the field is not
* present, nothing will be set.
* Used by the page object to set widgets labels to
* external label tags.
* @param SimpleSelector $selector Criteria to apply.
* @access public
*/
function setField($name, $value) {
return $this->_setFieldBySelector(new SimpleNameSelector($name), $value);
}
/**
* Sets a widget value within the form by using the ID.
* @param string/integer $id Name of widget tag.
* @param string $value Value to input into the widget.
* @return boolean True if value is legal, false
* otherwise. If the field is not
* present, nothing will be set.
* @access public
*/
function setFieldById($id, $value) {
return $this->_setFieldBySelector(new SimpleIdSelector($id), $value);
}
/**
* Creates the encoding for the current values in the
* form.
* @return SimpleFormEncoding Request to submit.
* @access private
*/
function _getEncoding() {
$encoding = new SimpleFormEncoding();
function attachLabelBySelector($selector, $label) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
$encoding->add(
$this->_widgets[$i]->getName(),
$this->_widgets[$i]->getValue());
if ($selector->isMatch($this->_widgets[$i])) {
if (method_exists($this->_widgets[$i], 'setLabel')) {
$this->_widgets[$i]->setLabel($label);
return;
}
}
}
return $encoding;
}
/**
@ -362,8 +263,9 @@
* @param SimpleSelector $selector Criteria to apply.
* @return boolean True if present.
* @access private
* @access public
*/
function _hasSubmitBySelector($selector) {
function hasSubmit($selector) {
foreach ($this->_buttons as $button) {
if ($selector->isMatch($button)) {
return true;
@ -372,46 +274,13 @@
return false;
}
/**
* Test to see if a form has a submit button with this
* name attribute.
* @param string $name Name to look for.
* @return boolean True if present.
* @access public
*/
function hasSubmitName($name) {
return $this->_hasSubmitBySelector(new SimpleNameSelector($name));
}
/**
* Test to see if a form has a submit button with this
* value attribute.
* @param string $label Button label to search for.
* @return boolean True if present.
* @access public
*/
function hasSubmitLabel($label) {
return $this->_hasSubmitBySelector(new SimpleLabelSelector($label));
}
/**
* Test to see if a form has a submit button with this
* ID attribute.
* @param string $id Button ID attribute to search for.
* @return boolean True if present.
* @access public
*/
function hasSubmitId($id) {
return $this->_hasSubmitBySelector(new SimpleIdSelector($id));
}
/**
* Test to see if a form has an image control.
* @param SimpleSelector $selector Criteria to apply.
* @return boolean True if present.
* @access public
*/
function _hasImageBySelector($selector) {
function hasImage($selector) {
foreach ($this->_images as $image) {
if ($selector->isMatch($image)) {
return true;
@ -420,40 +289,6 @@
return false;
}
/**
* Test to see if a form has a submit button with this
* name attribute.
* @param string $label Button alt attribute to search for
* or nearest equivalent.
* @return boolean True if present.
* @access public
*/
function hasImageLabel($label) {
return $this->_hasImageBySelector(new SimpleLabelSelector($label));
}
/**
* Test to see if a form has a submittable image with this
* field name.
* @param string $name Image name to search for.
* @return boolean True if present.
* @access public
*/
function hasImageName($name) {
return $this->_hasImageBySelector(new SimpleNameSelector($name));
}
/**
* Test to see if a form has a submittable image with this
* ID attribute.
* @param string $id Button ID attribute to search for.
* @return boolean True if present.
* @access public
*/
function hasImageId($id) {
return $this->_hasImageBySelector(new SimpleIdSelector($id));
}
/**
* Gets the submit values for a selected button.
* @param SimpleSelector $selector Criteria to apply.
@ -463,10 +298,11 @@
* in the form.
* @access public
*/
function _submitButtonBySelector($selector, $additional) {
function submitButton($selector, $additional = false) {
$additional = $additional ? $additional : array();
foreach ($this->_buttons as $button) {
if ($selector->isMatch($button)) {
$encoding = $this->_getEncoding();
$encoding = $this->_encode();
$encoding->merge($button->getSubmitValues());
if ($additional) {
$encoding->merge($additional);
@ -477,51 +313,6 @@
return false;
}
/**
* Gets the submit values for a named button.
* @param string $name Button label to search for.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitButtonByName($name, $additional = false) {
return $this->_submitButtonBySelector(
new SimpleNameSelector($name),
$additional);
}
/**
* Gets the submit values for a named button.
* @param string $label Button label to search for.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitButtonByLabel($label, $additional = false) {
return $this->_submitButtonBySelector(
new SimpleLabelSelector($label),
$additional);
}
/**
* Gets the submit values for a button identified by the ID.
* @param string $id Button ID attribute to search for.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitButtonById($id, $additional = false) {
return $this->_submitButtonBySelector(
new SimpleIdSelector($id),
$additional);
}
/**
* Gets the submit values for an image.
* @param SimpleSelector $selector Criteria to apply.
@ -533,10 +324,11 @@
* form.
* @access public
*/
function _submitImageBySelector($selector, $x, $y, $additional) {
function submitImage($selector, $x, $y, $additional = false) {
$additional = $additional ? $additional : array();
foreach ($this->_images as $image) {
if ($selector->isMatch($image)) {
$encoding = $this->_getEncoding();
$encoding = $this->_encode();
$encoding->merge($image->getSubmitValues($x, $y));
if ($additional) {
$encoding->merge($additional);
@ -547,64 +339,6 @@
return false;
}
/**
* Gets the submit values for an image identified by the alt
* tag or nearest equivalent.
* @param string $label Button label to search for.
* @param integer $x X-coordinate of click.
* @param integer $y Y-coordinate of click.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitImageByLabel($label, $x, $y, $additional = false) {
return $this->_submitImageBySelector(
new SimpleLabelSelector($label),
$x,
$y,
$additional);
}
/**
* Gets the submit values for an image identified by the ID.
* @param string $name Image name to search for.
* @param integer $x X-coordinate of click.
* @param integer $y Y-coordinate of click.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitImageByName($name, $x, $y, $additional = false) {
return $this->_submitImageBySelector(
new SimpleNameSelector($name),
$x,
$y,
$additional);
}
/**
* Gets the submit values for an image identified by the ID.
* @param string/integer $id Button ID attribute to search for.
* @param integer $x X-coordinate of click.
* @param integer $y Y-coordinate of click.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitImageById($id, $x, $y, $additional = false) {
return $this->_submitImageBySelector(
new SimpleIdSelector($id),
$x,
$y,
$additional);
}
/**
* Simply submits the form without the submit button
* value. Used when there is only one button or it
@ -613,7 +347,7 @@
* @access public
*/
function submit() {
return $this->_getEncoding();
return $this->_encode();
}
}
?>

View file

@ -467,7 +467,8 @@
* @access public
*/
function &getFormBySubmitLabel($label) {
return $this->_findForm('getFormBySubmitLabel', $label);
$form = &$this->_findForm('getFormBySubmitLabel', $label);
return $form;
}
/**
@ -480,7 +481,8 @@
* @access public
*/
function &getFormBySubmitName($name) {
return $this->_findForm('getFormBySubmitName', $name);
$form = &$this->_findForm('getFormBySubmitName', $name);
return $form;
}
/**
@ -493,7 +495,8 @@
* @access public
*/
function &getFormBySubmitId($id) {
return $this->_findForm('getFormBySubmitId', $id);
$form = &$this->_findForm('getFormBySubmitId', $id);
return $form;
}
/**
@ -506,7 +509,8 @@
* @access public
*/
function &getFormByImageLabel($label) {
return $this->_findForm('getFormByImageLabel', $label);
$form = &$this->_findForm('getFormByImageLabel', $label);
return $form;
}
/**
@ -519,7 +523,8 @@
* @access public
*/
function &getFormByImageName($name) {
return $this->_findForm('getFormByImageName', $name);
$form = &$this->_findForm('getFormByImageName', $name);
return $form;
}
/**
@ -532,7 +537,8 @@
* @access public
*/
function &getFormByImageId($id) {
return $this->_findForm('getFormByImageId', $id);
$form = &$this->_findForm('getFormByImageId', $id);
return $form;
}
/**
@ -546,7 +552,8 @@
* @access public
*/
function &getFormById($id) {
return $this->_findForm('getFormById', $id);
$form = &$this->_findForm('getFormById', $id);
return $form;
}
/**
@ -559,11 +566,12 @@
*/
function &_findForm($method, $attribute) {
if (is_integer($this->_focus)) {
return $this->_findFormInFrame(
$form = &$this->_findFormInFrame(
$this->_frames[$this->_focus],
$this->_focus,
$method,
$attribute);
return $form;
}
for ($i = 0; $i < count($this->_frames); $i++) {
$form = &$this->_findFormInFrame(
@ -575,7 +583,8 @@
return $form;
}
}
return null;
$null = null;
return $null;
}
/**
@ -596,6 +605,25 @@
return $form;
}
/**
* Sets a field on each form in which the field is
* available by label and then name. labels are not
* yet implemented.
* @param string $label Field name.
* @param string $value Value to set field to.
* @return boolean True if value is valid.
* @access public
*/
function setField($label, $value) {
if (is_integer($this->_focus)) {
$this->_frames[$this->_focus]->setField($label, $value);
} else {
for ($i = 0; $i < count($this->_frames); $i++) {
$this->_frames[$i]->setField($label, $value);
}
}
}
/**
* Sets a field on each form in which the field is
* available.
@ -604,12 +632,12 @@
* @return boolean True if value is valid.
* @access public
*/
function setField($name, $value) {
function setFieldByName($name, $value) {
if (is_integer($this->_focus)) {
$this->_frames[$this->_focus]->setField($name, $value);
$this->_frames[$this->_focus]->setFieldByName($name, $value);
} else {
for ($i = 0; $i < count($this->_frames); $i++) {
$this->_frames[$i]->setField($name, $value);
$this->_frames[$i]->setFieldByName($name, $value);
}
}
}
@ -632,6 +660,25 @@
}
}
/**
* Accessor for a form element value within a frameset.
* Finds the first match amongst the frames.
* @param string $label Field label.
* @return string/boolean A string if the field is
* present, false if unchecked
* and null if missing.
* @access public
*/
function getField($label) {
for ($i = 0; $i < count($this->_frames); $i++) {
$value = $this->_frames[$i]->getField($label);
if (isset($value)) {
return $value;
}
}
return null;
}
/**
* Accessor for a form element value within a frameset.
* Finds the first match amongst the frames.
@ -641,9 +688,9 @@
* and null if missing.
* @access public
*/
function getField($name) {
function getFieldByName($name) {
for ($i = 0; $i < count($this->_frames); $i++) {
$value = $this->_frames[$i]->getField($name);
$value = $this->_frames[$i]->getFieldByName($name);
if (isset($value)) {
return $value;
}

View file

@ -304,9 +304,11 @@
*/
function &_createSocket($scheme, $host, $port, $timeout) {
if (in_array($scheme, array('https'))) {
return new SimpleSecureSocket($host, $port, $timeout);
$socket = &new SimpleSecureSocket($host, $port, $timeout);
} else {
$socket = &new SimpleSocket($host, $port, $timeout);
}
return new SimpleSocket($host, $port, $timeout);
return $socket;
}
}
@ -376,7 +378,9 @@
$this->_proxy->getHost(),
$this->_proxy->getPort() ? $this->_proxy->getPort() : 8080,
$timeout);
if (! $socket->isError()) {
if ($socket->isError()) {
return $socket;
}
$socket->write($this->_getRequestLine($method) . "\r\n");
$socket->write($this->_getHostLine() . "\r\n");
if ($this->_username && $this->_password) {
@ -385,7 +389,6 @@
"\r\n");
}
$socket->write("Connection: close\r\n");
}
return $socket;
}
}
@ -398,42 +401,41 @@
*/
class SimpleHttpRequest {
var $_route;
var $_method;
var $_encoding;
var $_headers;
var $_cookies;
/**
* Saves the URL ready for fetching.
* Builds the socket request from the different pieces.
* These include proxy information, URL, cookies, headers,
* request method and choice of encoding.
* @param SimpleRoute $route Request route.
* @param string $method HTTP request method,
* usually GET.
* @param SimpleFormEncoding $encoding Content to send with
* request or false.
* request.
* @access public
*/
function SimpleHttpRequest(&$route, $method, $encoding = false) {
function SimpleHttpRequest(&$route, $encoding) {
$this->_route = &$route;
$this->_method = $method;
$this->_encoding = $encoding;
$this->_headers = array();
$this->_cookies = array();
}
/**
* Fetches the content and parses the headers.
* Dispatches the content to the route's socket.
* @param integer $timeout Connection timeout.
* @return SimpleHttpResponse A response which may only have
* an error.
* an error, but hopefully has a
* complete web page.
* @access public
*/
function &fetch($timeout) {
$socket = &$this->_route->createConnection($this->_method, $timeout);
if ($socket->isError()) {
return $this->_createResponse($socket);
$socket = &$this->_route->createConnection($this->_encoding->getMethod(), $timeout);
if (! $socket->isError()) {
$this->_dispatchRequest($socket, $this->_encoding);
}
$this->_dispatchRequest($socket, $this->_method, $this->_encoding);
return $this->_createResponse($socket);
$response = &$this->_createResponse($socket);
return $response;
}
/**
@ -444,38 +446,21 @@
* @param SimpleFormEncoding $encoding Content to send with request.
* @access private
*/
function _dispatchRequest(&$socket, $method, $encoding) {
if ($encoding || ($method == 'POST')) {
$socket->write("Content-Length: " . $this->_getContentLength($encoding) . "\r\n");
$socket->write("Content-Type: application/x-www-form-urlencoded\r\n");
}
function _dispatchRequest(&$socket, $encoding) {
foreach ($this->_headers as $header_line) {
$socket->write($header_line . "\r\n");
}
if (count($this->_cookies) > 0) {
$socket->write("Cookie: " . $this->_marshallCookies($this->_cookies) . "\r\n");
}
$encoding->writeHeadersTo($socket);
$socket->write("\r\n");
if ($encoding) {
$socket->write($encoding->asString());
}
}
/**
* Calculates the length of the encoded content.
* @param SimpleFormEncoding $encoding Content to send with
* request or false.
*/
function _getContentLength($encoding) {
if (! $encoding) {
return 0;
}
return (integer)strlen($encoding->asString());
$encoding->writeTo($socket);
}
/**
* Adds a header line to the request.
* @param string $header_line Text of header line.
* @param string $header_line Text of full header line.
* @access public
*/
function addHeaderLine($header_line) {
@ -513,11 +498,11 @@
* @access protected
*/
function &_createResponse(&$socket) {
return new SimpleHttpResponse(
$response = &new SimpleHttpResponse(
$socket,
$this->_method,
$this->_route->getUrl(),
$this->_encoding);
return $response;
}
}
@ -657,7 +642,7 @@
* @access protected
*/
function _parseHeaderLine($header_line) {
if (preg_match('/HTTP\/(\d+\.\d+)\s+(.*?)\s/i', $header_line, $matches)) {
if (preg_match('/HTTP\/(\d+\.\d+)\s+(\S*)/i', $header_line, $matches)) {
$this->_http_version = $matches[1];
$this->_response_code = $matches[2];
}
@ -705,9 +690,8 @@
* @subpackage WebTester
*/
class SimpleHttpResponse extends SimpleStickyError {
var $_method;
var $_url;
var $_request_data;
var $_encoding;
var $_sent;
var $_content;
var $_headers;
@ -717,16 +701,14 @@
* content and headers.
* @param SimpleSocket $socket Network connection to fetch
* response text from.
* @param string $method HTTP request method.
* @param SimpleUrl $url Resource name.
* @param mixed $request_data Record of content sent.
* @param mixed $encoding Record of content sent.
* @access public
*/
function SimpleHttpResponse(&$socket, $method, $url, $request_data = '') {
function SimpleHttpResponse(&$socket, $url, $encoding) {
$this->SimpleStickyError();
$this->_method = $method;
$this->_url = $url;
$this->_request_data = $request_data;
$this->_encoding = $encoding;
$this->_sent = $socket->getSent();
$this->_content = false;
$raw = $this->_readAll($socket);
@ -761,7 +743,7 @@
* @access public
*/
function getMethod() {
return $this->_method;
return $this->_encoding->getMethod();
}
/**
@ -779,7 +761,7 @@
* @access public
*/
function getRequestData() {
return $this->_request_data;
return $this->_encoding;
}
/**

View file

@ -17,22 +17,16 @@
/**
* Default character simpletest will substitute for any value
*/
define('MOCK_WILDCARD', '*');
if (! defined('MOCK_ANYTHING')) {
define('MOCK_ANYTHING', '*');
}
/**
* A wildcard expectation always matches.
* @package SimpleTest
* @subpackage MockObjects
*/
class WildcardExpectation extends SimpleExpectation {
/**
* Chains constructor only.
* @access public
*/
function WildcardExpectation() {
$this->SimpleExpectation();
}
class AnythingExpectation extends SimpleExpectation {
/**
* Tests the expectation. Always true.
@ -373,7 +367,8 @@
function &findFirstMatch($parameters) {
$slot = $this->_findFirstSlot($parameters);
if (!isset($slot)) {
return null;
$null = null;
return $null;
}
return $slot["content"];
}
@ -404,7 +399,8 @@
return $this->_map[$i];
}
}
return null;
$null = null;
return $null;
}
}
@ -449,7 +445,7 @@
}
for ($i = 0; $i < count($args); $i++) {
if ($args[$i] === $this->_wildcard) {
$args[$i] = new WildcardExpectation();
$args[$i] = new AnythingExpectation();
}
}
return $args;
@ -466,7 +462,8 @@
$method = strtolower($method);
$step = $this->getCallCount($method);
$this->_addCall($method, $args);
return $this->_getReturn($method, $args, $step);
$result = &$this->_getReturn($method, $args, $step);
return $result;
}
/**
@ -618,13 +615,16 @@
function &_getReturn($method, $args, $step) {
if (isset($this->_return_sequence[$method][$step])) {
if ($this->_return_sequence[$method][$step]->isMatch($args)) {
return $this->_return_sequence[$method][$step]->findFirstMatch($args);
$result = &$this->_return_sequence[$method][$step]->findFirstMatch($args);
return $result;
}
}
if (isset($this->_returns[$method])) {
return $this->_returns[$method]->findFirstMatch($args);
$result = &$this->_returns[$method]->findFirstMatch($args);
return $result;
}
return null;
$null = null;
return $null;
}
}
@ -867,7 +867,8 @@
$step = $this->getCallCount($method);
$this->_addCall($method, $args);
$this->_checkExpectations($method, $args, $step);
return $this->_getReturn($method, $args, $step);
$result = &$this->_getReturn($method, $args, $step);
return $result;
}
/**
@ -989,13 +990,13 @@
* @access public
*/
function generate($class, $stub_class = false, $methods = false) {
if (! SimpleTestCompatibility::classExists($class)) {
if (! class_exists($class)) {
return false;
}
if (! $stub_class) {
$stub_class = "Stub" . $class;
}
if (SimpleTestCompatibility::classExists($stub_class)) {
if (class_exists($stub_class)) {
return false;
}
return eval(Stub::_createClassCode(
@ -1015,7 +1016,7 @@
function _createClassCode($class, $stub_class, $methods) {
$stub_base = SimpleTestOptions::getStubBaseClass();
$code = "class $stub_class extends $stub_base {\n";
$code .= " function $stub_class(\$wildcard = MOCK_WILDCARD) {\n";
$code .= " function $stub_class(\$wildcard = MOCK_ANYTHING) {\n";
$code .= " \$this->$stub_base(\$wildcard);\n";
$code .= " }\n";
$code .= Stub::_createHandlerCode($class, $stub_base, $methods);
@ -1041,20 +1042,54 @@
$code = "";
$methods = array_merge($methods, get_class_methods($class));
foreach ($methods as $method) {
if (Stub::_isSpecialMethod($method)) {
if (Stub::_isConstructor($method)) {
continue;
}
if (in_array($method, get_class_methods($base))) {
continue;
}
$code .= " function &$method() {\n";
$code .= Stub::_createFunctionDeclaration($method);
$code .= " \$args = func_get_args();\n";
$code .= " return \$this->_invoke(\"$method\", \$args);\n";
$code .= " \$result = &\$this->_invoke(\"$method\", \$args);\n";
$code .= " return \$result;\n";
$code .= " }\n";
}
return $code;
}
/**
* Creates the appropriate function declaration.
* @see _determineArguments(), _createHandlerCode()
* @param string $method Method name.
* @return string The proper function declaration
* @access private
* @static
*/
function _createFunctionDeclaration($method) {
$arguments = Stub::_determineArguments($method);
return sprintf(" function &%s(%s) {\n", $method, $arguments);
}
/**
* Returns the necessary arguments for a given method.
* @param string $method Method name
* @return string The arguments string for a method, or
* blank if no arguments are required.
* @access private
* @static
*/
function _determineArguments($method) {
$code = '';
if (Stub::_isSpecial($method)) {
$args = array(
'__call' => '$method, $value',
'__get' => '$key',
'__set' => '$key, $value');
$code = $args[$method];
}
return $code;
}
/**
* Tests to see if a special PHP method is about to
* be stubbed by mistake.
@ -1063,10 +1098,23 @@
* @access private
* @static
*/
function _isSpecialMethod($method) {
function _isConstructor($method) {
return in_array(
strtolower($method),
array('__construct', '__clone', '__get', '__set', '__call'));
array('__construct', '__clone'));
}
/**
* Tests for an special method.
* @param string $method Method name.
* @return boolean True if special.
* @access private
* @static
*/
function _isSpecial($method) {
return in_array(
strtolower($method),
array('__get', '__set', '__call'));
}
}
@ -1083,7 +1131,7 @@
* @access public
*/
function Mock() {
trigger_error("Mock factory methods are class only.");
trigger_error('Mock factory methods are class only.');
}
/**
@ -1102,13 +1150,13 @@
* @access public
*/
function generate($class, $mock_class = false, $methods = false) {
if (! SimpleTestCompatibility::classExists($class)) {
if (! class_exists($class)) {
return false;
}
if (! $mock_class) {
$mock_class = "Mock" . $class;
}
if (SimpleTestCompatibility::classExists($mock_class)) {
if (class_exists($mock_class)) {
return false;
}
return eval(Mock::_createClassCode(
@ -1130,10 +1178,10 @@
* @access public
*/
function generatePartial($class, $mock_class, $methods) {
if (! SimpleTestCompatibility::classExists($class)) {
if (! class_exists($class)) {
return false;
}
if (SimpleTestCompatibility::classExists($mock_class)) {
if (class_exists($mock_class)) {
trigger_error("Partial mock class [$mock_class] already exists");
return false;
}
@ -1152,7 +1200,7 @@
function _createClassCode($class, $mock_class, $methods) {
$mock_base = SimpleTestOptions::getMockBaseClass();
$code = "class $mock_class extends $mock_base {\n";
$code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n";
$code .= " function $mock_class(&\$test, \$wildcard = MOCK_ANYTHING) {\n";
$code .= " \$this->$mock_base(\$test, \$wildcard);\n";
$code .= " }\n";
$code .= Stub::_createHandlerCode($class, $mock_base, $methods);
@ -1177,7 +1225,7 @@
$code .= " var \$_mock;\n";
$code .= Mock::_addMethodList($methods);
$code .= "\n";
$code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n";
$code .= " function $mock_class(&\$test, \$wildcard = MOCK_ANYTHING) {\n";
$code .= " \$this->_mock = &new $mock_base(\$test, \$wildcard, false);\n";
$code .= " }\n";
$code .= Mock::_chainMockReturns();
@ -1207,7 +1255,8 @@
function _bailOutIfNotMocked($alias) {
$code = " if (! in_array($alias, \$this->_mocked_methods)) {\n";
$code .= " trigger_error(\"Method [$alias] is not mocked\");\n";
$code .= " return;\n";
$code .= " \$null = null;\n";
$code .= " return \$null;\n";
$code .= " }\n";
return $code;
}
@ -1294,9 +1343,10 @@
function _overrideMethods($methods) {
$code = "";
foreach ($methods as $method) {
$code .= " function &$method() {\n";
$code .= Stub::_createFunctionDeclaration($method);
$code .= " \$args = func_get_args();\n";
$code .= " return \$this->_mock->_invoke(\"$method\", \$args);\n";
$code .= " \$result = &\$this->_mock->_invoke(\"$method\", \$args);\n";
$code .= " return \$result;\n";
$code .= " }\n";
}
return $code;

View file

@ -101,13 +101,7 @@
}
/**
* Adds additional mock code.
* @param string $code Extra code that can be added
* to the partial mocks for
* extra functionality. Useful
* when a test tool has overridden
* the mock base classes.
* @access public
* @deprecated
*/
function addPartialMockCode($code = '') {
$registry = &SimpleTestOptions::_getRegistry();
@ -115,9 +109,7 @@
}
/**
* Accessor for additional partial mock code.
* @return string Extra code.
* @access public
* @deprecated
*/
function getPartialMockCode() {
$registry = &SimpleTestOptions::_getRegistry();
@ -210,12 +202,28 @@
*/
class SimpleTestCompatibility {
/**
* Creates a copy whether in PHP5 or PHP4.
* @param object $object Thing to copy.
* @return object A copy.
* @access public
* @static
*/
function copy($object) {
if (version_compare(phpversion(), '5') >= 0) {
eval('$copy = clone $object;');
return $copy;
}
return $object;
}
/**
* Identity test. Drops back to equality + types for PHP5
* objects as the === operator counts as the
* stronger reference constraint.
* @param mixed $first Test subject.
* @param mixed $second Comparison object.
* @return boolean True if identical.
* @access public
* @static
*/
@ -233,6 +241,7 @@
* Recursive type test.
* @param mixed $first Test subject.
* @param mixed $second Comparison object.
* @return boolean True if same type.
* @access private
* @static
*/
@ -258,6 +267,7 @@
* Recursive type test for each element of an array.
* @param mixed $first Test subject.
* @param mixed $second Comparison object.
* @return boolean True if identical.
* @access private
* @static
*/
@ -280,6 +290,7 @@
* Test for two variables being aliases.
* @param mixed $first Test subject.
* @param mixed $second Comparison object.
* @return boolean True if same.
* @access public
* @static
*/
@ -288,6 +299,13 @@
&& is_object($first)) {
return ($first === $second);
}
if (is_object($first) && is_object($second)) {
$id = uniqid("test");
$first->$id = true;
$is_ref = isset($second->$id);
unset($first->$id);
return $is_ref;
}
$temp = $first;
$first = uniqid("test");
$is_ref = ($first === $second);
@ -300,6 +318,7 @@
* class hiearchy.
* @param object $object Object to test.
* @param string $class Root name of hiearchy.
* @return boolean True if class in hiearchy.
* @access public
* @static
*/
@ -318,21 +337,6 @@
or (is_subclass_of($object, $class)));
}
/**
* Autoload safe version of class_exists().
* @param string $class Name of class to look for.
* @return boolean True if class is defined.
* @access public
* @static
*/
function classExists($class) {
if (version_compare(phpversion(), '5') >= 0) {
return class_exists($class, false);
} else {
return class_exists($class);
}
}
/**
* Sets a socket timeout for each chunk.
* @param resource $handle Socket handle.

View file

@ -13,8 +13,103 @@
require_once(dirname(__FILE__) . '/parser.php');
require_once(dirname(__FILE__) . '/tag.php');
require_once(dirname(__FILE__) . '/form.php');
require_once(dirname(__FILE__) . '/selector.php');
/**#@-*/
/**
* Creates tags and widgets given HTML tag
* attributes.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleTagBuilder {
/**
* Factory for the tag objects. Creates the
* appropriate tag object for the incoming tag name
* and attributes.
* @param string $name HTML tag name.
* @param hash $attributes Element attributes.
* @return SimpleTag Tag object.
* @access public
*/
function createTag($name, $attributes) {
static $map = array(
'a' => 'SimpleAnchorTag',
'title' => 'SimpleTitleTag',
'button' => 'SimpleButtonTag',
'textarea' => 'SimpleTextAreaTag',
'option' => 'SimpleOptionTag',
'label' => 'SimpleLabelTag',
'form' => 'SimpleFormTag',
'frame' => 'SimpleFrameTag');
$attributes = $this->_keysToLowerCase($attributes);
if (array_key_exists($name, $map)) {
$tag_class = $map[$name];
return new $tag_class($attributes);
} elseif ($name == 'select') {
return $this->_createSelectionTag($attributes);
} elseif ($name == 'input') {
return $this->_createInputTag($attributes);
}
return new SimpleTag($name, $attributes);
}
/**
* Factory for selection fields.
* @param hash $attributes Element attributes.
* @return SimpleTag Tag object.
* @access protected
*/
function _createSelectionTag($attributes) {
if (isset($attributes['multiple'])) {
return new MultipleSelectionTag($attributes);
}
return new SimpleSelectionTag($attributes);
}
/**
* Factory for input tags.
* @param hash $attributes Element attributes.
* @return SimpleTag Tag object.
* @access protected
*/
function _createInputTag($attributes) {
if (! isset($attributes['type'])) {
return new SimpleTextTag($attributes);
}
$type = strtolower(trim($attributes['type']));
$map = array(
'submit' => 'SimpleSubmitTag',
'image' => 'SimpleImageSubmitTag',
'checkbox' => 'SimpleCheckboxTag',
'radio' => 'SimpleRadioButtonTag',
'text' => 'SimpleTextTag',
'hidden' => 'SimpleTextTag',
'password' => 'SimpleTextTag',
'file' => 'SimpleUploadTag');
if (array_key_exists($type, $map)) {
$tag_class = $map[$type];
return new $tag_class($attributes);
}
return false;
}
/**
* Make the keys lower case for case insensitive look-ups.
* @param hash $map Hash to convert.
* @return hash Unchanged values, but keys lower case.
* @access private
*/
function _keysToLowerCase($map) {
$lower = array();
foreach ($map as $key => $value) {
$lower[strtolower($key)] = $value;
}
return $lower;
}
}
/**
* SAX event handler. Maintains a list of
* open tags and dispatches them as they close.
@ -24,6 +119,7 @@
class SimplePageBuilder extends SimpleSaxListener {
var $_tags;
var $_page;
var $_in_option = false;
/**
* Sets the builder up empty.
@ -40,7 +136,7 @@
* @return SimplePage Newly parsed page.
* @access public
*/
function parse($response) {
function &parse($response) {
$this->_tags = array();
$this->_page = &$this->_createPage($response);
$parser = &$this->_createParser($this);
@ -55,7 +151,8 @@
* @access protected
*/
function &_createPage($response) {
return new SimplePage($response);
$page = &new SimplePage($response);
return $page;
}
/**
@ -66,21 +163,8 @@
* @access protected
*/
function &_createParser(&$listener) {
return new SimpleSaxParser($listener);
}
/**
* Make the keys lower case for case insensitive look-ups.
* @param hash $map Hash to convert.
* @return hash Unchanged values, but keys lower case.
* @access private
*/
function _keysToLowerCase($map) {
$lower = array();
foreach ($map as $key => $value) {
$lower[strtolower($key)] = $value;
}
return $lower;
$parser = &new SimpleSaxParser($listener);
return $parser;
}
/**
@ -92,19 +176,31 @@
* @access public
*/
function startElement($name, $attributes) {
$tag = &$this->_createTag($name, $this->_keysToLowerCase($attributes));
if ($name == 'form') {
$factory = &new SimpleTagBuilder();
$tag = $factory->createTag($name, $attributes);
if (! $tag) {
return true;
}
if ($tag->getTagName() == 'label') {
$this->_page->acceptLabelStart($tag);
$this->_openTag($tag);
return true;
}
if ($tag->getTagName() == 'form') {
$this->_page->acceptFormStart($tag);
return true;
}
if ($name == 'frameset') {
if ($tag->getTagName() == 'frameset') {
$this->_page->acceptFramesetStart($tag);
return true;
}
if ($name == 'frame') {
if ($tag->getTagName() == 'frame') {
$this->_page->acceptFrame($tag);
return true;
}
if ($tag->getTagName() == 'option') {
$this->_in_option = true;
}
if ($tag->expectEndTag()) {
$this->_openTag($tag);
return true;
@ -120,6 +216,10 @@
* @access public
*/
function endElement($name) {
if ($name == 'label') {
$this->_page->acceptLabelEnd();
return true;
}
if ($name == 'form') {
$this->_page->acceptFormEnd();
return true;
@ -128,7 +228,10 @@
$this->_page->acceptFramesetEnd();
return true;
}
if (isset($this->_tags[$name]) && (count($this->_tags[$name]) > 0)) {
if ($name == 'option') {
$this->_in_option = false;
}
if ($this->_hasNamedTagOnOpenTagStack($name)) {
$tag = array_pop($this->_tags[$name]);
$this->_addContentTagToOpenTags($tag);
$this->_page->acceptTag($tag);
@ -137,6 +240,17 @@
return true;
}
/**
* Test to see if there are any open tags awaiting
* closure that match the tag name.
* @param string $name Element name.
* @return boolean True if any are still open.
* @access private
*/
function _hasNamedTagOnOpenTagStack($name) {
return isset($this->_tags[$name]) && (count($this->_tags[$name]) > 0);
}
/**
* Unparsed, but relevant data. The data is added
* to every open tag.
@ -145,18 +259,44 @@
* @access public
*/
function addContent($text) {
foreach (array_keys($this->_tags) as $name) {
for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) {
$this->_tags[$name][$i]->addContent($text);
}
if ($this->_in_option) {
$this->_addContentToOptionTag($text);
} else {
$this->_addContentToAllOpenTags($text);
}
return true;
}
/**
* Parsed relevant data. The parsed tag is added
* to every open tag.
* @param SimpleTag $tag May include unparsed tags.
* Option tags swallow content and so we want any
* new content to go only to the most current option.
* @param string $text May include unparsed tags.
* @access private
*/
function _addContentToOptionTag($text) {
$current = count($this->_tags['option']) - 1;
$this->_tags['option'][$current]->addContent($text);
}
/**
* Any content fills all currently open tags unless it
* is part of an option tag.
* @param string $text May include unparsed tags.
* @access private
*/
function _addContentToAllOpenTags($text) {
foreach (array_keys($this->_tags) as $name) {
for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) {
$this->_tags[$name][$i]->addContent($text);
}
}
}
/**
* Parsed data in tag form. The parsed tag is added
* to every open tag. Used for adding options to select
* fields only.
* @param SimpleTag $tag Option tags only.
* @access private
*/
function _addContentTagToOpenTags(&$tag) {
@ -181,75 +321,7 @@
if (! in_array($name, array_keys($this->_tags))) {
$this->_tags[$name] = array();
}
array_push($this->_tags[$name], $tag);
}
/**
* Factory for the tag objects. Creates the
* appropriate tag object for the incoming tag name.
* @param string $name HTML tag name.
* @param hash $attributes Element attributes.
* @return SimpleTag Tag object.
* @access protected
*/
function &_createTag($name, $attributes) {
if ($name == 'a') {
return new SimpleAnchorTag($attributes);
} elseif ($name == 'title') {
return new SimpleTitleTag($attributes);
} elseif ($name == 'input') {
return $this->_createInputTag($attributes);
} elseif ($name == 'button') {
return new SimpleButtonTag($attributes);
} elseif ($name == 'textarea') {
return new SimpleTextAreaTag($attributes);
} elseif ($name == 'select') {
return $this->_createSelectionTag($attributes);
} elseif ($name == 'option') {
return new SimpleOptionTag($attributes);
} elseif ($name == 'form') {
return new SimpleFormTag($attributes);
} elseif ($name == 'frame') {
return new SimpleFrameTag($attributes);
}
return new SimpleTag($name, $attributes);
}
/**
* Factory for selection fields.
* @param hash $attributes Element attributes.
* @return SimpleTag Tag object.
* @access protected
*/
function &_createSelectionTag($attributes) {
if (isset($attributes['multiple'])) {
return new MultipleSelectionTag($attributes);
}
return new SimpleSelectionTag($attributes);
}
/**
* Factory for input tags.
* @param hash $attributes Element attributes.
* @return SimpleTag Tag object.
* @access protected
*/
function &_createInputTag($attributes) {
if (! isset($attributes['type'])) {
return new SimpleTextTag($attributes);
}
$type = strtolower($attributes['type']);
if ($type == 'submit') {
return new SimpleSubmitTag($attributes);
} elseif ($type == 'image') {
return new SimpleImageSubmitTag($attributes);
} elseif ($type == 'checkbox') {
return new SimpleCheckboxTag($attributes);
} elseif ($type == 'radio') {
return new SimpleRadioButtonTag($attributes);
} else {
return new SimpleTextTag($attributes);
}
$this->_tags[$name][] = &$tag;
}
}
@ -261,6 +333,9 @@
class SimplePage {
var $_links;
var $_title;
var $_last_widget;
var $_label;
var $_left_over_labels;
var $_open_forms;
var $_complete_forms;
var $_frameset;
@ -283,6 +358,7 @@
function SimplePage($response = false) {
$this->_links = array();
$this->_title = false;
$this->_left_over_labels = array();
$this->_open_forms = array();
$this->_complete_forms = array();
$this->_frameset = false;
@ -505,6 +581,33 @@
for ($i = 0; $i < count($this->_open_forms); $i++) {
$this->_open_forms[$i]->addWidget($tag);
}
$this->_last_widget = &$tag;
}
}
/**
* Opens a label for a described widget.
* @param SimpleFormTag $tag Tag to accept.
* @access public
*/
function acceptLabelStart(&$tag) {
$this->_label = &$tag;
unset($this->_last_widget);
}
/**
* Closes the most recently opened label.
* @access public
*/
function acceptLabelEnd() {
if (isset($this->_label)) {
if (isset($this->_last_widget)) {
$this->_last_widget->setLabel($this->_label->getText());
unset($this->_last_widget);
} else {
$this->_left_over_labels[] = SimpleTestCompatibility::copy($this->_label);
}
unset($this->_label);
}
}
@ -617,6 +720,13 @@
while (count($this->_open_forms)) {
$this->_complete_forms[] = array_pop($this->_open_forms);
}
foreach ($this->_left_over_labels as $label) {
for ($i = 0, $count = count($this->_complete_forms); $i < $count; $i++) {
$this->_complete_forms[$i]->attachLabelBySelector(
new SimpleById($label->getFor()),
$label->getText());
}
}
}
/**
@ -781,11 +891,12 @@
*/
function &getFormBySubmitLabel($label) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->hasSubmitLabel($label)) {
if ($this->_complete_forms[$i]->hasSubmit(new SimpleByLabel($label))) {
return $this->_complete_forms[$i];
}
}
return null;
$null = null;
return $null;
}
/**
@ -797,11 +908,12 @@
*/
function &getFormBySubmitName($name) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->hasSubmitName($name)) {
if ($this->_complete_forms[$i]->hasSubmit(new SimpleByName($name))) {
return $this->_complete_forms[$i];
}
}
return null;
$null = null;
return $null;
}
/**
@ -813,11 +925,12 @@
*/
function &getFormBySubmitId($id) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->hasSubmitId($id)) {
if ($this->_complete_forms[$i]->hasSubmit(new SimpleById($id))) {
return $this->_complete_forms[$i];
}
}
return null;
$null = null;
return $null;
}
/**
@ -829,11 +942,12 @@
*/
function &getFormByImageLabel($label) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->hasImageLabel($label)) {
if ($this->_complete_forms[$i]->hasImage(new SimpleByLabel($label))) {
return $this->_complete_forms[$i];
}
}
return null;
$null = null;
return $null;
}
/**
@ -845,11 +959,12 @@
*/
function &getFormByImageName($name) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->hasImageName($name)) {
if ($this->_complete_forms[$i]->hasImage(new SimpleByName($name))) {
return $this->_complete_forms[$i];
}
}
return null;
$null = null;
return $null;
}
/**
@ -861,11 +976,12 @@
*/
function &getFormByImageId($id) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->hasImageId($id)) {
if ($this->_complete_forms[$i]->hasImage(new SimpleById($id))) {
return $this->_complete_forms[$i];
}
}
return null;
$null = null;
return $null;
}
/**
@ -882,21 +998,44 @@
return $this->_complete_forms[$i];
}
}
return null;
$null = null;
return $null;
}
/**
* Sets a field on each form in which the field is
* available.
* available. Sets by label, but for compatibility
* drops back to a name.
* @param string $label Field label or name.
* @param string $value Value to set field to.
* @return boolean True if value is valid.
* @access public
*/
function setField($label, $value) {
$is_set = false;
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->setField(new SimpleByLabel($label), $value)) {
$is_set = true;
}
}
if ($is_set) {
return true;
}
return $this->setFieldByName($label, $value);
}
/**
* Sets a field on each form in which the field is
* available by name.
* @param string $name Field name.
* @param string $value Value to set field to.
* @return boolean True if value is valid.
* @access public
*/
function setField($name, $value) {
function setFieldByName($name, $value) {
$is_set = false;
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->setField($name, $value)) {
if ($this->_complete_forms[$i]->setField(new SimpleByName($name), $value)) {
$is_set = true;
}
}
@ -913,7 +1052,7 @@
*/
function setFieldById($id, $value) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->setFieldById($id, $value)) {
if ($this->_complete_forms[$i]->setField(new SimpleById($id), $value)) {
return true;
}
}
@ -922,16 +1061,36 @@
/**
* Accessor for a form element value within a page.
* Finds the first match.
* Finds the first match by label first. If none are found
* then it does a search by name attribute instead.
* @param string $label Field label.
* @return string/boolean A string if the field is
* present, false if unchecked
* and null if missing.
* @access public
*/
function getField($label) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
$value = $this->_complete_forms[$i]->getValue(new SimpleByLabel($label));
if (isset($value)) {
return $value;
}
}
return $this->getFieldByName($label);
}
/**
* Accessor for a form element value within a page.
* Finds the first match by name only.
* @param string $name Field name.
* @return string/boolean A string if the field is
* present, false if unchecked
* and null if missing.
* @access public
*/
function getField($name) {
function getFieldByName($name) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
$value = $this->_complete_forms[$i]->getValue($name);
$value = $this->_complete_forms[$i]->getValue(new SimpleByName($name));
if (isset($value)) {
return $value;
}
@ -950,7 +1109,7 @@
*/
function getFieldById($id) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
$value = $this->_complete_forms[$i]->getValueById($id);
$value = $this->_complete_forms[$i]->getValue(new SimpleById($id));
if (isset($value)) {
return $value;
}

View file

@ -9,17 +9,27 @@
/**#@+
* Lexer mode stack constants
*/
define("LEXER_ENTER", 1);
define("LEXER_MATCHED", 2);
define("LEXER_UNMATCHED", 3);
define("LEXER_EXIT", 4);
define("LEXER_SPECIAL", 5);
if (! defined('LEXER_ENTER')) {
define('LEXER_ENTER', 1);
}
if (! defined('LEXER_MATCHED')) {
define('LEXER_MATCHED', 2);
}
if (! defined('LEXER_UNMATCHED')) {
define('LEXER_UNMATCHED', 3);
}
if (! defined('LEXER_EXIT')) {
define('LEXER_EXIT', 4);
}
if (! defined('LEXER_SPECIAL')) {
define('LEXER_SPECIAL', 5);
}
/**#@-*/
/**
* Compounded regular expression. Any of
* the contained patterns could match and
* when one does it's label is returned.
* when one does, it's label is returned.
* @package SimpleTest
* @subpackage WebTester
*/
@ -501,7 +511,7 @@
*/
function _getParsedTags() {
return array('a', 'title', 'form', 'input', 'button', 'textarea', 'select',
'option', 'frameset', 'frame');
'option', 'frameset', 'frame', 'label');
}
/**
@ -692,7 +702,8 @@
* @static
*/
function normalise($html) {
$text = preg_replace('|<img.*?alt\s*=\s*"(.*?)".*?>|', ' \1 ', $html);
$text = preg_replace('|<!--.*?-->|', '', $html);
$text = preg_replace('|<img.*?alt\s*=\s*"(.*?)".*?>|', ' \1 ', $text);
$text = preg_replace('|<img.*?alt\s*=\s*\'(.*?)\'.*?>|', ' \1 ', $text);
$text = preg_replace('|<img.*?alt\s*=\s*([a-zA-Z_]+).*?>|', ' \1 ', $text);
$text = preg_replace('|<.*?>|', '', $text);

View file

@ -202,7 +202,7 @@
* @param mixed $payload Message or object.
* @access public
*/
function paintSignal($type, &$payload) {
function paintSignal($type, $payload) {
}
}
@ -372,9 +372,7 @@
* @static
*/
function inCli() {
$method = getenv('REQUEST_METHOD');
return empty($method);
// return php_sapi_name() == 'cli';
return php_sapi_name() == 'cli';
}
}
?>

100
vendors/simpletest/selector.php vendored Normal file
View file

@ -0,0 +1,100 @@
<?php
/**
* Base include file for SimpleTest.
* @package SimpleTest
* @subpackage WebTester
* @version $Id: selector.php,v 1.2 2005/07/10 18:23:48 lastcraft Exp $
*/
/**#@+
* include SimpleTest files
*/
require_once(dirname(__FILE__) . '/tag.php');
require_once(dirname(__FILE__) . '/encoding.php');
/**#@-*/
/**
* Used to extract form elements for testing against.
* Searches by name attribute.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleByName {
var $_name;
/**
* Stashes the name for later comparison.
* @param string $name Name attribute to match.
*/
function SimpleByName($name) {
$this->_name = $name;
}
/**
* Compares with name attribute of widget.
* @param SimpleWidget $widget Control to compare.
* @access public
*/
function isMatch($widget) {
return ($widget->getName() == $this->_name);
}
}
/**
* Used to extract form elements for testing against.
* Searches by visible label or alt text.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleByLabel {
var $_label;
/**
* Stashes the name for later comparison.
* @param string $label Visible text to match.
*/
function SimpleByLabel($label) {
$this->_label = $label;
}
/**
* Comparison. Compares visible text of widget or
* related label.
* @param SimpleWidget $widget Control to compare.
* @access public
*/
function isMatch($widget) {
if (! method_exists($widget, 'isLabel')) {
return false;
}
return $widget->isLabel($this->_label);
}
}
/**
* Used to extract form elements for testing against.
* Searches dy id attribute.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleById {
var $_id;
/**
* Stashes the name for later comparison.
* @param string $id ID atribute to match.
*/
function SimpleById($id) {
$this->_id = $id;
}
/**
* Comparison. Compares id attribute of widget.
* @param SimpleWidget $widget Control to compare.
* @access public
*/
function isMatch($widget) {
return $widget->isId($this->_id);
}
}
?>

View file

@ -128,6 +128,40 @@
return $shell->getOutputAsList();
}
/**
* Will trigger a pass if the two parameters have
* the same value only. Otherwise a fail. This
* is for testing hand extracted text, etc.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertEqual($first, $second, $message = "%s") {
return $this->assert(
new EqualExpectation($first),
$second,
$message);
}
/**
* Will trigger a pass if the two parameters have
* a different value. Otherwise a fail. This
* is for testing hand extracted text, etc.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertNotEqual($first, $second, $message = "%s") {
return $this->assert(
new NotEqualExpectation($first),
$second,
$message);
}
/**
* Tests the last status code from the shell.
* @param integer $status Expected status of last
@ -153,7 +187,7 @@
*/
function assertOutput($expected, $message = "%s") {
$shell = &$this->_getShell();
return $this->assertExpectation(
return $this->assert(
new EqualExpectation($expected),
$shell->getOutput(),
$message);
@ -169,8 +203,8 @@
*/
function assertOutputPattern($pattern, $message = "%s") {
$shell = &$this->_getShell();
return $this->assertExpectation(
new WantedPatternExpectation($pattern),
return $this->assert(
new PatternExpectation($pattern),
$shell->getOutput(),
$message);
}
@ -185,8 +219,8 @@
*/
function assertNoOutputPattern($pattern, $message = "%s") {
$shell = &$this->_getShell();
return $this->assertExpectation(
new UnwantedPatternExpectation($pattern),
return $this->assert(
new NoPatternExpectation($pattern),
$shell->getOutput(),
$message);
}
@ -226,8 +260,8 @@
*/
function assertFilePattern($pattern, $path, $message = "%s") {
$shell = &$this->_getShell();
return $this->assertExpectation(
new WantedPatternExpectation($pattern),
return $this->assert(
new PatternExpectation($pattern),
implode('', file($path)),
$message);
}
@ -243,8 +277,8 @@
*/
function assertNoFilePattern($pattern, $path, $message = "%s") {
$shell = &$this->_getShell();
return $this->assertExpectation(
new UnwantedPatternExpectation($pattern),
return $this->assert(
new NoPatternExpectation($pattern),
implode('', file($path)),
$message);
}
@ -265,7 +299,8 @@
* @access protected
*/
function &_createShell() {
return new SimpleShell();
$shell = &new SimpleShell();
return $shell;
}
}
?>

View file

@ -30,8 +30,8 @@
* @subpackage UnitTester
*/
class SimpleTestCase {
var $_label;
var $_runner;
var $_label = false;
var $_runner = false;
/**
* Sets up the test with no display.
@ -40,8 +40,9 @@
* @access public
*/
function SimpleTestCase($label = false) {
$this->_label = $label ? $label : get_class($this);
$this->_runner = false;
if ($label) {
$this->_label = $label;
}
}
/**
@ -50,7 +51,7 @@
* @access public
*/
function getLabel() {
return $this->_label;
return $this->_label ? $this->_label : get_class($this);
}
/**
@ -59,7 +60,8 @@
* @access public
*/
function &createInvoker() {
return new SimpleErrorTrappingInvoker(new SimpleInvoker($this));
$invoker = &new SimpleErrorTrappingInvoker(new SimpleInvoker($this));
return $invoker;
}
/**
@ -71,7 +73,8 @@
* @access protected
*/
function &_createRunner(&$reporter) {
return new SimpleRunner($this, $reporter);
$runner = &new SimpleRunner($this, $reporter);
return $runner;
}
/**
@ -113,6 +116,7 @@
*/
function pass($message = "Pass") {
$this->_runner->paintPass($message . $this->getAssertionLine(' at line [%d]'));
return true;
}
/**
@ -122,6 +126,7 @@
*/
function fail($message = "Fail") {
$this->_runner->paintFail($message . $this->getAssertionLine(' at line [%d]'));
return false;
}
/**
@ -166,15 +171,22 @@
* Runs an expectation directly, for extending the
* tests with new expectation classes.
* @param SimpleExpectation $expectation Expectation subclass.
* @param mixed $test_value Value to compare.
* @param mixed $compare Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertExpectation(&$expectation, $test_value, $message = '%s') {
function assert(&$expectation, $compare, $message = '%s') {
return $this->assertTrue(
$expectation->test($test_value),
sprintf($message, $expectation->overlayMessage($test_value)));
$expectation->test($compare),
sprintf($message, $expectation->overlayMessage($compare)));
}
/**
* @deprecated
*/
function assertExpectation(&$expectation, $compare, $message = '%s') {
return $this->assert($expectation, $compare, $message);
}
/**
@ -191,11 +203,9 @@
$message = 'True assertion got ' . ($result ? 'True' : 'False');
}
if ($result) {
$this->pass($message);
return true;
return $this->pass($message);
} else {
$this->fail($message);
return false;
return $this->fail($message);
}
}
@ -291,8 +301,8 @@
* of the test.
* @access public
*/
function GroupTest($label) {
$this->_label = $label;
function GroupTest($label = false) {
$this->_label = $label ? $label : get_class($this);
$this->_test_cases = array();
$this->_old_track_errors = ini_get('track_errors');
$this->_xdebug_is_enabled = function_exists('xdebug_is_enabled') ?
@ -329,8 +339,12 @@
* @access public
*/
function addTestClass($class) {
if ($this->_getBaseTestCase($class) == 'grouptest') {
$this->_test_cases[] = &new $class();
} else {
$this->_test_cases[] = $class;
}
}
/**
* Builds a group test from a library of test cases.
@ -365,10 +379,10 @@
include($file);
$error = isset($php_errormsg) ? $php_errormsg : false;
$this->_disableErrorReporting();
$self_inflicted = array(
$self_inflicted_errors = array(
'Assigning the return value of new by reference is deprecated',
'var: Deprecated. Please use the public/private/protected modifiers');
if (in_array($error, $self_inflicted)) {
if (in_array($error, $self_inflicted_errors)) {
return false;
}
return $error;
@ -416,11 +430,10 @@
if (in_array($class, $existing_classes)) {
continue;
}
if (! $this->_isTestCase($class)) {
continue;
}
if ($this->_getBaseTestCase($class)) {
$classes[] = $class;
}
}
return $classes;
}
@ -445,20 +458,31 @@
/**
* Test to see if a class is derived from the
* TestCase class.
* SimpleTestCase class.
* @param string $class Class name.
* @access private
*/
function _isTestCase($class) {
function _getBaseTestCase($class) {
while ($class = get_parent_class($class)) {
$class = strtolower($class);
if ($class == "simpletestcase" || $class == "grouptest") {
return true;
return $class;
}
}
return false;
}
/**
* Delegates to a visiting collector to add test
* files.
* @param string $path Path to scan from.
* @param SimpleCollector $collector Directory scanner.
* @access public
*/
function collect($path, &$collector) {
$collector->collect($this, $path);
}
/**
* Invokes run() on all of the held test cases, instantiating
* them if necessary.

View file

@ -123,7 +123,7 @@
* is a workaround for PHP4 always throwing a warning
* with a secure socket.
* @param integer $block_size Size of chunk to read.
* @return integer Incoming bytes. False
* @return string/boolean Incoming bytes. False
* on error.
* @access public
*/

View file

@ -10,6 +10,7 @@
* include SimpleTest files
*/
require_once(dirname(__FILE__) . '/parser.php');
require_once(dirname(__FILE__) . '/encoding.php');
/**#@-*/
/**
@ -31,7 +32,7 @@
* converted to lower case.
*/
function SimpleTag($name, $attributes) {
$this->_name = $name;
$this->_name = strtolower(trim($name));
$this->_attributes = $attributes;
$this->_content = '';
}
@ -193,6 +194,7 @@
*/
class SimpleWidget extends SimpleTag {
var $_value;
var $_label;
var $_is_set;
/**
@ -204,6 +206,7 @@
function SimpleWidget($name, $attributes) {
$this->SimpleTag($name, $attributes);
$this->_value = false;
$this->_label = false;
$this->_is_set = false;
}
@ -267,6 +270,35 @@
function resetValue() {
$this->_is_set = false;
}
/**
* Allows setting of a label externally, say by a
* label tag.
* @param string $label Label to attach.
* @access public
*/
function setLabel($label) {
$this->_label = trim($label);
}
/**
* Reads external or internal label.
* @param string $label Label to test.
* @return boolean True is match.
* @access public
*/
function isLabel($label) {
return $this->_label == trim($label);
}
/**
* Dispatches the value into the form encoded packet.
* @param SimpleEncoding $encoding Form packet.
* @access public
*/
function write(&$encoding) {
$encoding->add($this->getName(), $this->getValue());
}
}
/**
@ -362,6 +394,16 @@
return $this->getValue();
}
/**
* Test for a label match when searching.
* @param string $label Label to test.
* @return boolean True on match.
* @access public
*/
function isLabel($label) {
return trim($label) == trim($this->getLabel());
}
/**
* Gets the values submitted as a form.
* @return array Hash of name and values.
@ -419,6 +461,16 @@
return $this->getAttribute('alt');
}
/**
* Test for a label match when searching.
* @param string $label Label to test.
* @return boolean True on match.
* @access public
*/
function isLabel($label) {
return trim($label) == trim($this->getLabel());
}
/**
* Gets the values submitted as a form.
* @return array Hash of name and values.
@ -477,6 +529,16 @@
return $this->getContent();
}
/**
* Test for a label match when searching.
* @param string $label Label to test.
* @return boolean True on match.
* @access public
*/
function isLabel($label) {
return trim($label) == trim($this->getLabel());
}
/**
* Gets the values submitted as a form. Gone
* for the Mozilla defaults values.
@ -557,6 +619,47 @@
}
}
/**
* File upload widget.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleUploadTag extends SimpleWidget {
/**
* Starts with attributes only.
* @param hash $attributes Attribute names and
* string values.
*/
function SimpleUploadTag($attributes) {
$this->SimpleWidget('input', $attributes);
}
/**
* Tag contains no content.
* @return boolean False.
* @access public
*/
function expectEndTag() {
return false;
}
/**
* Dispatches the value into the form encoded packet.
* @param SimpleEncoding $encoding Form packet.
* @access public
*/
function write(&$encoding) {
if (! file_exists($this->getValue())) {
return;
}
$encoding->attach(
$this->getName(),
implode('', file($this->getValue())),
basename($this->getValue()));
}
}
/**
* Checkbox widget.
* @package SimpleTest
@ -891,19 +994,29 @@
}
/**
* A group of tags with the same name within a form.
* A group of multiple widgets with some shared behaviour.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleCheckboxGroup {
var $_widgets;
class SimpleTagGroup {
var $_widgets = array();
/**
* Starts empty.
* Adds a tag to the group.
* @param SimpleWidget $widget
* @access public
*/
function SimpleCheckboxGroup() {
$this->_widgets = array();
function addWidget(&$widget) {
$this->_widgets[] = &$widget;
}
/**
* Accessor to widget set.
* @return array All widgets.
* @access protected
*/
function &_getWidgets() {
return $this->_widgets;
}
/**
@ -916,31 +1029,6 @@
return false;
}
/**
* Scans the checkboxes for one with the appropriate
* ID field.
* @param string $id ID value to try.
* @return boolean True if matched.
* @access public
*/
function isId($id) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($this->_widgets[$i]->isId($id)) {
return true;
}
}
return false;
}
/**
* Adds a tag to the group.
* @param SimpleWidget $widget
* @access public
*/
function addWidget(&$widget) {
$this->_widgets[] = &$widget;
}
/**
* Fetches the name for the widget from the first
* member.
@ -953,6 +1041,55 @@
}
}
/**
* Scans the widgets for one with the appropriate
* ID field.
* @param string $id ID value to try.
* @return boolean True if matched.
* @access public
*/
function isId($id) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($this->_widgets[$i]->isId($id)) {
return true;
}
}
return false;
}
/**
* Scans the widgets for one with the appropriate
* attached label.
* @param string $label Attached label to try.
* @return boolean True if matched.
* @access public
*/
function isLabel($label) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($this->_widgets[$i]->isLabel($label)) {
return true;
}
}
return false;
}
/**
* Dispatches the value into the form encoded packet.
* @param SimpleEncoding $encoding Form packet.
* @access public
*/
function write(&$encoding) {
$encoding->add($this->getName(), $this->getValue());
}
}
/**
* A group of tags with the same name within a form.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleCheckboxGroup extends SimpleTagGroup {
/**
* Accessor for current selected widget or false
* if none.
@ -961,9 +1098,10 @@
*/
function getValue() {
$values = array();
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($this->_widgets[$i]->getValue()) {
$values[] = $this->_widgets[$i]->getValue();
$widgets = &$this->_getWidgets();
for ($i = 0, $count = count($widgets); $i < $count; $i++) {
if ($widgets[$i]->getValue()) {
$values[] = $widgets[$i]->getValue();
}
}
return $this->_coerceValues($values);
@ -976,9 +1114,10 @@
*/
function getDefault() {
$values = array();
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($this->_widgets[$i]->getDefault()) {
$values[] = $this->_widgets[$i]->getDefault();
$widgets = &$this->_getWidgets();
for ($i = 0, $count = count($widgets); $i < $count; $i++) {
if ($widgets[$i]->getDefault()) {
$values[] = $widgets[$i]->getDefault();
}
}
return $this->_coerceValues($values);
@ -996,12 +1135,13 @@
if (! $this->_valuesArePossible($values)) {
return false;
}
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
$possible = $this->_widgets[$i]->getAttribute('value');
if (in_array($this->_widgets[$i]->getAttribute('value'), $values)) {
$this->_widgets[$i]->setValue($possible);
$widgets = &$this->_getWidgets();
for ($i = 0, $count = count($widgets); $i < $count; $i++) {
$possible = $widgets[$i]->getAttribute('value');
if (in_array($widgets[$i]->getAttribute('value'), $values)) {
$widgets[$i]->setValue($possible);
} else {
$this->_widgets[$i]->setValue(false);
$widgets[$i]->setValue(false);
}
}
return true;
@ -1017,8 +1157,9 @@
*/
function _valuesArePossible($values) {
$matches = array();
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
$possible = $this->_widgets[$i]->getAttribute('value');
$widgets = &$this->_getWidgets();
for ($i = 0, $count = count($widgets); $i < $count; $i++) {
$possible = $widgets[$i]->getAttribute('value');
if (in_array($possible, $values)) {
$matches[] = $possible;
}
@ -1070,63 +1211,7 @@
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleRadioGroup {
var $_widgets;
/**
* Starts empty.
* @access public
*/
function SimpleRadioGroup() {
$this->_widgets = array();
}
/**
* Accessor for an attribute.
* @param string $label Attribute name.
* @return boolean Always false.
* @access public
*/
function getAttribute($label) {
return false;
}
/**
* Scans the checkboxes for one with the appropriate
* ID field.
* @param string $id ID value to try.
* @return boolean True if matched.
* @access public
*/
function isId($id) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($this->_widgets[$i]->isId($id)) {
return true;
}
}
return false;
}
/**
* Adds a tag to the group.
* @param SimpleWidget $widget
* @access public
*/
function addWidget(&$widget) {
$this->_widgets[] = &$widget;
}
/**
* Fetches the name for the widget from the first
* member.
* @return string Name of widget.
* @access public
*/
function getName() {
if (count($this->_widgets) > 0) {
return $this->_widgets[0]->getName();
}
}
class SimpleRadioGroup extends SimpleTagGroup {
/**
* Each tag is tried in turn until one is
@ -1141,9 +1226,10 @@
return false;
}
$index = false;
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if (! $this->_widgets[$i]->setValue($value)) {
$this->_widgets[$i]->setValue(false);
$widgets = &$this->_getWidgets();
for ($i = 0, $count = count($widgets); $i < $count; $i++) {
if (! $widgets[$i]->setValue($value)) {
$widgets[$i]->setValue(false);
}
}
return true;
@ -1156,8 +1242,9 @@
* @access private
*/
function _valueIsPossible($value) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($this->_widgets[$i]->getAttribute('value') == $value) {
$widgets = &$this->_getWidgets();
for ($i = 0, $count = count($widgets); $i < $count; $i++) {
if ($widgets[$i]->getAttribute('value') == $value) {
return true;
}
}
@ -1172,9 +1259,10 @@
* @access public
*/
function getValue() {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($this->_widgets[$i]->getValue()) {
return $this->_widgets[$i]->getValue();
$widgets = &$this->_getWidgets();
for ($i = 0, $count = count($widgets); $i < $count; $i++) {
if ($widgets[$i]->getValue()) {
return $widgets[$i]->getValue();
}
}
return false;
@ -1187,15 +1275,42 @@
* @access public
*/
function getDefault() {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($this->_widgets[$i]->getDefault()) {
return $this->_widgets[$i]->getDefault();
$widgets = &$this->_getWidgets();
for ($i = 0, $count = count($widgets); $i < $count; $i++) {
if ($widgets[$i]->getDefault()) {
return $widgets[$i]->getDefault();
}
}
return false;
}
}
/**
* Tag to keep track of labels.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleLabelTag extends SimpleTag {
/**
* Starts with a named tag with attributes only.
* @param hash $attributes Attribute names and
* string values.
*/
function SimpleLabelTag($attributes) {
$this->SimpleTag('label', $attributes);
}
/**
* Access for the ID to attach the label to.
* @return string For attribute.
* @access public
*/
function getFor() {
return $this->getAttribute('for');
}
}
/**
* Tag to aid parsing the form.
* @package SimpleTest

View file

@ -10,10 +10,9 @@
function testGet() {
$browser = &new SimpleBrowser();
$browser->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
$this->assertTrue($browser->get('http://www.lastcraft.com/test/network_confirm.php'));
$this->assertWantedPattern('/target for the SimpleTest/', $browser->getContent());
$this->assertWantedPattern('/Request method.*?<dd>GET<\/dd>/', $browser->getContent());
$this->assertPattern('/target for the SimpleTest/', $browser->getContent());
$this->assertPattern('/Request method.*?<dd>GET<\/dd>/', $browser->getContent());
$this->assertEqual($browser->getTitle(), 'Simple test target file');
$this->assertEqual($browser->getResponseCode(), 200);
$this->assertEqual($browser->getMimeType(), 'text/html');
@ -23,8 +22,8 @@
$browser = &new SimpleBrowser();
$browser->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
$this->assertTrue($browser->post('http://www.lastcraft.com/test/network_confirm.php'));
$this->assertWantedPattern('/target for the SimpleTest/', $browser->getContent());
$this->assertWantedPattern('/Request method.*?<dd>POST<\/dd>/', $browser->getContent());
$this->assertPattern('/target for the SimpleTest/', $browser->getContent());
$this->assertPattern('/Request method.*?<dd>POST<\/dd>/', $browser->getContent());
}
function testAbsoluteLinkFollowing() {
@ -32,7 +31,7 @@
$browser->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
$browser->get('http://www.lastcraft.com/test/link_confirm.php');
$this->assertTrue($browser->clickLink('Absolute'));
$this->assertWantedPattern('/target for the SimpleTest/', $browser->getContent());
$this->assertPattern('/target for the SimpleTest/', $browser->getContent());
}
function testRelativeLinkFollowing() {
@ -40,7 +39,15 @@
$browser->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
$browser->get('http://www.lastcraft.com/test/link_confirm.php');
$this->assertTrue($browser->clickLink('Relative'));
$this->assertWantedPattern('/target for the SimpleTest/', $browser->getContent());
$this->assertPattern('/target for the SimpleTest/', $browser->getContent());
}
function testUnifiedClickLinkClicking() {
$browser = &new SimpleBrowser();
$browser->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
$browser->get('http://www.lastcraft.com/test/link_confirm.php');
$this->assertTrue($browser->click('Relative'));
$this->assertPattern('/target for the SimpleTest/', $browser->getContent());
}
function testIdLinkFollowing() {
@ -48,7 +55,7 @@
$browser->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
$browser->get('http://www.lastcraft.com/test/link_confirm.php');
$this->assertTrue($browser->clickLinkById(1));
$this->assertWantedPattern('/target for the SimpleTest/', $browser->getContent());
$this->assertPattern('/target for the SimpleTest/', $browser->getContent());
}
function testCookieReading() {
@ -65,22 +72,29 @@
$browser->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
$browser->get('http://www.lastcraft.com/test/form.html');
$this->assertTrue($browser->clickSubmit('Go!'));
$this->assertWantedPattern('/Request method.*?<dd>POST<\/dd>/', $browser->getContent());
$this->assertWantedPattern('/go=\[Go!\]/', $browser->getContent());
$this->assertPattern('/Request method.*?<dd>POST<\/dd>/', $browser->getContent());
$this->assertPattern('/go=\[Go!\]/', $browser->getContent());
}
function testUnifiedClickCanSubmit() {
$browser = &new SimpleBrowser();
$browser->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
$browser->get('http://www.lastcraft.com/test/form.html');
$this->assertTrue($browser->click('Go!'));
$this->assertPattern('/go=\[Go!\]/', $browser->getContent());
}
}
class TestOfLiveFetching extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
function testGet() {
$this->assertTrue($this->get('http://www.lastcraft.com/test/network_confirm.php'));
$this->assertTrue($this->getUrl() == 'http://www.lastcraft.com/test/network_confirm.php');
$this->assertWantedPattern('/target for the SimpleTest/');
$this->assertWantedPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertEqual($this->getUrl(), 'http://www.lastcraft.com/test/network_confirm.php');
$this->assertWantedText('target for the SimpleTest');
$this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertTitle('Simple test target file');
$this->assertResponse(200);
$this->assertMime('text/html');
@ -98,18 +112,18 @@
function testPost() {
$this->assertTrue($this->post('http://www.lastcraft.com/test/network_confirm.php'));
$this->assertWantedText('target for the SimpleTest');
$this->assertWantedPattern('/Request method.*?<dd>POST<\/dd>/');
$this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
}
function testGetWithData() {
$this->get('http://www.lastcraft.com/test/network_confirm.php', array("a" => "aaa"));
$this->assertWantedPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertWantedText('a=[aaa]');
}
function testPostWithData() {
$this->post('http://www.lastcraft.com/test/network_confirm.php', array("a" => "aaa"));
$this->assertWantedPattern('/Request method.*?<dd>POST<\/dd>/');
$this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
$this->assertWantedText('a=[aaa]');
}
@ -153,14 +167,13 @@
}
class TestOfLivePageLinkingWithMinimalLinks extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
function testClickToExplicitelyNamedSelfReturns() {
$this->get('http://www.lastcraft.com/test/front_controller_style/a_page.php');
$this->assertTrue($this->getUrl() == 'http://www.lastcraft.com/test/front_controller_style/a_page.php');
$this->assertEqual($this->getUrl(), 'http://www.lastcraft.com/test/front_controller_style/a_page.php');
$this->assertTitle('Simple test page with links');
$this->clickLink('Self');
$this->assertTitle('Simple test page with links');
@ -206,7 +219,6 @@
}
class TestOfLiveFrontControllerEmulation extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
@ -239,16 +251,16 @@
$this->get('http://www.lastcraft.com/test/front_controller_style/');
$this->clickLink('Empty query');
$this->assertResponse(200);
$this->assertWantedPattern('/Simple test front controller/');
$this->assertWantedPattern('/raw get data.*?\[\].*?get data/si');
$this->assertPattern('/Simple test front controller/');
$this->assertPattern('/raw get data.*?\[\].*?get data/si');
}
function testJumpToUnnamedPageWithEmptyLink() {
$this->get('http://www.lastcraft.com/test/front_controller_style/');
$this->clickLink('Empty link');
$this->assertResponse(200);
$this->assertWantedPattern('/Simple test front controller/');
$this->assertWantedPattern('/raw get data.*?\[\].*?get data/si');
$this->assertPattern('/Simple test front controller/');
$this->assertPattern('/raw get data.*?\[\].*?get data/si');
}
function testJumpBackADirectoryLevel() {
@ -294,7 +306,6 @@
}
class TestOfLiveHeaders extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
@ -309,7 +320,6 @@
}
class TestOfLiveRedirects extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
@ -356,21 +366,23 @@
}
class TestOfLiveCookies extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
function testCookieSetting() {
$this->setCookie('a', 'Test cookie a', 'www.lastcraft.com');
$this->setCookie('b', 'Test cookie b', 'www.lastcraft.com', 'test');
$this->setCookie('a', 'Test cookie a');
$this->setCookie('b', 'Test cookie b', 'www.lastcraft.com');
$this->setCookie('c', 'Test cookie c', 'www.lastcraft.com', 'test');
$this->get('http://www.lastcraft.com/test/network_confirm.php');
$this->assertWantedPattern('/Test cookie a/');
$this->assertWantedPattern('/Test cookie b/');
$this->assertPattern('/Test cookie a/');
$this->assertPattern('/Test cookie b/');
$this->assertPattern('/Test cookie c/');
$this->assertCookie('a');
$this->assertCookie('b', 'Test cookie b');
$this->assertTrue($this->getCookie('a') == 'Test cookie a');
$this->assertTrue($this->getCookie('b') == 'Test cookie b');
$this->assertTrue($this->getCookie('c') == 'Test cookie c');
}
function testCookieReading() {
@ -387,26 +399,26 @@
$this->assertCookie('day_cookie', 'C');
}
function testTimedCookieExpiry() {
function testTimedCookieExpiryWith100SecondMargin() {
$this->get('http://www.lastcraft.com/test/set_cookies.php');
$this->ageCookies(3600);
$this->restart(time() + 60); // Includes a 60 sec. clock drift margin.
$this->restart(time() + 100);
$this->assertNoCookie('session_cookie');
$this->assertNoCookie('hour_cookie');
$this->assertCookie('day_cookie', 'C');
}
function testOfClockOverDrift() {
function testNoClockOverDriftBy100Seconds() {
$this->get('http://www.lastcraft.com/test/set_cookies.php');
$this->restart(time() + 160); // Allows sixty second drift.
$this->restart(time() + 200);
$this->assertNoCookie(
'short_cookie',
'%s -> Please check your computer clock setting if you are not using NTP');
}
function testOfClockUnderDrift() {
function testNoClockUnderDriftBy100Seconds() {
$this->get('http://www.lastcraft.com/test/set_cookies.php');
$this->restart(time() + 40); // Allows sixty second drift.
$this->restart(time() + 0);
$this->assertCookie(
'short_cookie',
'B',
@ -415,15 +427,14 @@
function testCookiePath() {
$this->get('http://www.lastcraft.com/test/set_cookies.php');
$this->assertNoCookie("path_cookie", "D");
$this->assertNoCookie('path_cookie', 'D');
$this->get('./path/show_cookies.php');
$this->assertWantedPattern('/path_cookie/');
$this->assertCookie("path_cookie", "D");
$this->assertPattern('/path_cookie/');
$this->assertCookie('path_cookie', 'D');
}
}
class TestOfLiveForms extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
@ -431,21 +442,21 @@
function testSimpleSubmit() {
$this->get('http://www.lastcraft.com/test/form.html');
$this->assertTrue($this->clickSubmit('Go!'));
$this->assertWantedPattern('/Request method.*?<dd>POST<\/dd>/');
$this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
$this->assertWantedText('go=[Go!]');
}
function testDefaultFormValues() {
$this->get('http://www.lastcraft.com/test/form.html');
$this->assertField('a', '');
$this->assertField('b', 'Default text');
$this->assertField('c', '');
$this->assertField('d', 'd1');
$this->assertField('e', false);
$this->assertField('f', 'on');
$this->assertField('g', 'g3');
$this->assertField('h', 2);
$this->assertField('go', 'Go!');
$this->assertFieldByName('a', '');
$this->assertFieldByName('b', 'Default text');
$this->assertFieldByName('c', '');
$this->assertFieldByName('d', 'd1');
$this->assertFieldByName('e', false);
$this->assertFieldByName('f', 'on');
$this->assertFieldByName('g', 'g3');
$this->assertFieldByName('h', 2);
$this->assertFieldByName('go', 'Go!');
$this->assertTrue($this->clickSubmit('Go!'));
$this->assertWantedText('go=[Go!]');
$this->assertWantedText('a=[]');
@ -457,16 +468,16 @@
$this->assertWantedText('g=[g3]');
}
function testFormSubmissionByLabel() {
function testFormSubmissionByButtonLabel() {
$this->get('http://www.lastcraft.com/test/form.html');
$this->setField('a', 'aaa');
$this->setField('b', 'bbb');
$this->setField('c', 'ccc');
$this->setField('d', 'D2');
$this->setField('e', 'on');
$this->setField('f', false);
$this->setField('g', 'g2');
$this->setField('h', 1);
$this->setFieldByName('a', 'aaa');
$this->setFieldByName('b', 'bbb');
$this->setFieldByName('c', 'ccc');
$this->setFieldByName('d', 'D2');
$this->setFieldByName('e', 'on');
$this->setFieldByName('f', false);
$this->setFieldByName('g', 'g2');
$this->setFieldByName('h', 1);
$this->assertTrue($this->clickSubmit('Go!'));
$this->assertWantedText('a=[aaa]');
$this->assertWantedText('b=[bbb]');
@ -486,11 +497,12 @@
function testFormSubmissionByName() {
$this->get('http://www.lastcraft.com/test/form.html');
$this->setFieldByName('a', 'A');
$this->assertTrue($this->clickSubmitByName('go'));
$this->assertWantedText('go=[Go!]');
$this->assertWantedText('a=[A]');
}
function testFormSubmissionByNameAndadditionalParameters() {
function testFormSubmissionByNameAndAdditionalParameters() {
$this->get('http://www.lastcraft.com/test/form.html');
$this->assertTrue($this->clickSubmitByName('go', array('add' => 'A')));
$this->assertWantedText('go=[Go!]');
@ -510,20 +522,76 @@
$this->assertFieldById(3, '');
$this->assertFieldById(4, 'd1');
$this->assertFieldById(5, false);
$this->assertFieldById(6, 'on');
$this->assertFieldById(8, 'g3');
$this->assertFieldById(11, 2);
$this->setFieldById(1, 'aaa');
$this->setFieldById(2, 'bbb');
$this->setFieldById(3, 'ccc');
$this->setFieldById(4, 'D2');
$this->setFieldById(5, 'on');
$this->setFieldById(6, false);
$this->setFieldById(8, 'g2');
$this->setFieldById(11, 'H1');
$this->assertTrue($this->clickSubmitById(99));
$this->assertWantedText('a=[aaa]');
$this->assertWantedText('b=[bbb]');
$this->assertWantedText('c=[ccc]');
$this->assertWantedText('d=[d2]');
$this->assertWantedText('e=[on]');
$this->assertNoUnwantedText('f=[');
$this->assertWantedText('g=[g2]');
$this->assertWantedText('h=[1]');
$this->assertWantedText('go=[Go!]');
}
function testFormSubmissionWithLabels() {
$this->get('http://www.lastcraft.com/test/form.html');
$this->assertField('Text A', '');
$this->assertField('Text B', 'Default text');
$this->assertField('Text area C', '');
$this->assertField('Selection D', 'd1');
$this->assertField('Checkbox E', false);
$this->assertField('Checkbox F', 'on');
$this->assertField('3', 'g3');
$this->assertField('Selection H', 2);
$this->setField('Text A', 'aaa');
$this->setField('Text B', 'bbb');
$this->setField('Text area C', 'ccc');
$this->setField('Selection D', 'D2');
$this->setField('Checkbox E', 'on');
$this->setField('Checkbox F', false);
$this->setField('2', 'g2');
$this->setField('Selection H', 'H1');
$this->assertTrue($this->clickSubmit('Go!'));
$this->assertWantedText('a=[aaa]');
$this->assertWantedText('b=[bbb]');
$this->assertWantedText('c=[ccc]');
$this->assertWantedText('d=[d2]');
$this->assertWantedText('e=[on]');
$this->assertNoUnwantedText('f=[');
$this->assertWantedText('g=[g2]');
$this->assertWantedText('h=[1]');
$this->assertWantedText('go=[Go!]');
}
function testFormSubmissionWithMixedPostAndGet() {
$this->get('http://www.lastcraft.com/test/form_with_mixed_post_and_get.html');
$this->setFieldByName('a', 'A');
$this->assertTrue($this->clickSubmit('Go!'));
$this->assertWantedText('a=[A]');
$this->assertWantedText('x=[X]');
$this->assertWantedText('y=[Y]');
}
function testFormSubmissionWithoutAction() {
$this->get('http://www.lastcraft.com/test/form_without_action.php?test=test');
$this->assertWantedText('_GET : [test]');
$this->assertTrue($this->clickSubmit('Submit Post With Empty Action'));
$this->assertWantedText('_GET : [test]');
$this->assertWantedText('_POST : [test]');
}
function testImageSubmissionByLabel() {
$this->get('http://www.lastcraft.com/test/form.html');
$this->assertTrue($this->clickImage('Image go!', 10, 12));
@ -554,39 +622,74 @@
function testButtonSubmissionByLabel() {
$this->get('http://www.lastcraft.com/test/form.html');
$this->assertTrue($this->clickSubmit('Button go!', 10, 12));
$this->assertWantedPattern('/go=\[ButtonGo\]/s');
$this->assertPattern('/go=\[ButtonGo\]/s');
}
function testSelfSubmit() {
$this->get('http://www.lastcraft.com/test/self_form.php');
$this->assertNoUnwantedPattern('/<p>submitted<\/p>/i');
$this->assertNoUnwantedPattern('/<p>wrong form<\/p>/i');
$this->assertTitle('Test of form self submission');
$this->assertNoUnwantedText('[Submitted]');
$this->assertNoUnwantedText('[Wrong form]');
$this->assertTrue($this->clickSubmit());
$this->assertWantedPattern('/<p>submitted<\/p>/i');
$this->assertNoUnwantedPattern('/<p>wrong form<\/p>/i');
$this->assertWantedText('[Submitted]');
$this->assertNoUnwantedText('[Wrong form]');
$this->assertTitle('Test of form self submission');
}
function testSelfSubmitWithParameters() {
$this->get('http://www.lastcraft.com/test/self_form.php');
$this->setFieldByName('visible', 'Resent');
$this->assertTrue($this->clickSubmit());
$this->assertWantedText('[Resent]');
}
function testSettingOfBlankOption() {
$this->get('http://www.lastcraft.com/test/form.html');
$this->assertTrue($this->setField('d', ''));
$this->assertTrue($this->setFieldByName('d', ''));
$this->clickSubmit('Go!');
$this->assertWantedText('d=[]');
}
function testSendingMultipartFormDataEncodedForm() {
$this->get('http://www.lastcraft.com/test/form_data_encoded_form.html');
$this->assertField('Text A', '');
$this->assertField('Text B', 'Default text');
$this->assertField('Text area C', '');
$this->assertField('Selection D', 'd1');
$this->assertField('Checkbox E', false);
$this->assertField('Checkbox F', 'on');
$this->assertField('3', 'g3');
$this->assertField('Selection H', 2);
$this->setField('Text A', 'aaa');
$this->setField('Text B', 'bbb');
$this->setField('Text area C', 'ccc');
$this->setField('Selection D', 'D2');
$this->setField('Checkbox E', 'on');
$this->setField('Checkbox F', false);
$this->setField('2', 'g2');
$this->setField('Selection H', 'H1');
$this->assertTrue($this->clickSubmit('Go!'));
$this->assertWantedText('a=[aaa]');
$this->assertWantedText('b=[bbb]');
$this->assertWantedText('c=[ccc]');
$this->assertWantedText('d=[d2]');
$this->assertWantedText('e=[on]');
$this->assertNoUnwantedText('f=[');
$this->assertWantedText('g=[g2]');
$this->assertWantedText('h=[1]');
$this->assertWantedText('go=[Go!]');
}
}
class TestOfLiveMultiValueWidgets extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
function testDefaultFormValueSubmission() {
$this->get('http://www.lastcraft.com/test/multiple_widget_form.html');
$this->assertField('a', array('a2', 'a3'));
$this->assertField('b', array('b2', 'b3'));
$this->assertField('c[]', array('c2', 'c3'));
$this->assertFieldByName('a', array('a2', 'a3'));
$this->assertFieldByName('b', array('b2', 'b3'));
$this->assertFieldByName('c[]', array('c2', 'c3'));
$this->assertTrue($this->clickSubmit('Go!'));
$this->assertWantedText('a=[a2, a3]');
$this->assertWantedText('b=[b2, b3]');
@ -595,12 +698,12 @@
function testSubmittingMultipleValues() {
$this->get('http://www.lastcraft.com/test/multiple_widget_form.html');
$this->setField('a', array('a1', 'a4'));
$this->assertField('a', array('a1', 'a4'));
$this->assertField('a', array('a4', 'a1'));
$this->setField('b', array('b1', 'b4'));
$this->assertField('b', array('b1', 'b4'));
$this->setField('c[]', array('c1', 'c4'));
$this->setFieldByName('a', array('a1', 'a4'));
$this->assertFieldByName('a', array('a1', 'a4'));
$this->assertFieldByName('a', array('a4', 'a1'));
$this->setFieldByName('b', array('b1', 'b4'));
$this->assertFieldByName('b', array('b1', 'b4'));
$this->setFieldByName('c[]', array('c1', 'c4'));
$this->assertField('c[]', array('c1', 'c4'));
$this->assertTrue($this->clickSubmit('Go!'));
$this->assertWantedText('a=[a1, a4]');
@ -608,10 +711,22 @@
$this->assertWantedText('c=[c1, c4]');
}
function testSubmittingMultipleValuesByLabel() {
$this->get('http://www.lastcraft.com/test/multiple_widget_form.html');
$this->setField('Multiple selection A', array('a1', 'a4'));
$this->assertField('Multiple selection A', array('a1', 'a4'));
$this->assertField('Multiple selection A', array('a4', 'a1'));
$this->setField('multiple selection C', array('c1', 'c4'));
$this->assertField('multiple selection C', array('c1', 'c4'));
$this->assertTrue($this->clickSubmit('Go!'));
$this->assertWantedText('a=[a1, a4]');
$this->assertWantedText('c=[c1, c4]');
}
function testSavantStyleHiddenFieldDefaults() {
$this->get('http://www.lastcraft.com/test/savant_style_form.html');
$this->assertField('a', array('a0'));
$this->assertField('b', array('b0'));
$this->assertFieldByName('a', array('a0'));
$this->assertFieldByName('b', array('b0'));
$this->assertTrue($this->clickSubmit('Go!'));
$this->assertWantedText('a=[a0]');
$this->assertWantedText('b=[b0]');
@ -619,8 +734,8 @@
function testSavantStyleHiddenDefaultsAreOverridden() {
$this->get('http://www.lastcraft.com/test/savant_style_form.html');
$this->assertTrue($this->setField('a', array('a1')));
$this->assertTrue($this->setField('b', 'b1'));
$this->assertTrue($this->setFieldByName('a', array('a1')));
$this->assertTrue($this->setFieldByName('b', 'b1'));
$this->assertTrue($this->clickSubmit('Go!'));
$this->assertWantedText('a=[a1]');
$this->assertWantedText('b=[b1]');
@ -638,19 +753,55 @@
}
}
class TestOfLiveHistoryNavigation extends WebTestCase {
class TestOfFileUploads extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
function testSingleFileUpload() {
$this->get('http://www.lastcraft.com/test/upload_form.html');
$this->assertTrue($this->setField('Content:',
dirname(__FILE__) . '/support/upload_sample.txt'));
$this->assertField('Content:', dirname(__FILE__) . '/support/upload_sample.txt');
$this->click('Go!');
$this->assertWantedText('Sample for testing file upload');
}
function testMultipleFileUpload() {
$this->get('http://www.lastcraft.com/test/upload_form.html');
$this->assertTrue($this->setField('Content:',
dirname(__FILE__) . '/support/upload_sample.txt'));
$this->assertTrue($this->setField('Supplemental:',
dirname(__FILE__) . '/support/supplementary_upload_sample.txt'));
$this->assertField('Supplemental:',
dirname(__FILE__) . '/support/supplementary_upload_sample.txt');
$this->click('Go!');
$this->assertWantedText('Sample for testing file upload');
$this->assertWantedText('Some more text content');
}
function testBinaryFileUpload() {
$this->get('http://www.lastcraft.com/test/upload_form.html');
$this->assertTrue($this->setField('Content:',
dirname(__FILE__) . '/support/latin1_sample'));
$this->click('Go!');
$this->assertWantedText(
implode('', file(dirname(__FILE__) . '/support/latin1_sample')));
}
}
class TestOfLiveHistoryNavigation extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
function testRetry() {
$this->get('http://www.lastcraft.com/test/cookie_based_counter.php');
$this->assertWantedPattern('/count: 1/i');
$this->assertPattern('/count: 1/i');
$this->retry();
$this->assertWantedPattern('/count: 2/i');
$this->assertPattern('/count: 2/i');
$this->retry();
$this->assertWantedPattern('/count: 3/i');
$this->assertPattern('/count: 3/i');
}
function testOfBackButton() {
@ -667,10 +818,10 @@
function testGetRetryResubmitsData() {
$this->assertTrue($this->get(
'http://www.lastcraft.com/test/network_confirm.php?a=aaa'));
$this->assertWantedPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertWantedText('a=[aaa]');
$this->retry();
$this->assertWantedPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertWantedText('a=[aaa]');
}
@ -678,10 +829,10 @@
$this->assertTrue($this->get(
'http://www.lastcraft.com/test/network_confirm.php',
array('a' => 'aaa')));
$this->assertWantedPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertWantedText('a=[aaa]');
$this->retry();
$this->assertWantedPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertWantedText('a=[aaa]');
}
@ -689,26 +840,25 @@
$this->assertTrue($this->post(
'http://www.lastcraft.com/test/network_confirm.php',
array('a' => 'aaa')));
$this->assertWantedPattern('/Request method.*?<dd>POST<\/dd>/');
$this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
$this->assertWantedText('a=[aaa]');
$this->retry();
$this->assertWantedPattern('/Request method.*?<dd>POST<\/dd>/');
$this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
$this->assertWantedText('a=[aaa]');
}
function testGetRetryResubmitsRepeatedData() {
$this->assertTrue($this->get(
'http://www.lastcraft.com/test/network_confirm.php?a=1&a=2'));
$this->assertWantedPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertWantedText('a=[1, 2]');
$this->retry();
$this->assertWantedPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
$this->assertWantedText('a=[1, 2]');
}
}
class TestOfLiveAuthentication extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
@ -724,11 +874,32 @@
$this->assertResponse(200);
}
function testTrailingSlashImpliedWithinRealm() {
$this->get('http://www.lastcraft.com/test/protected/');
$this->authenticate('test', 'secret');
$this->assertResponse(200);
$this->get('http://www.lastcraft.com/test/protected');
$this->assertResponse(200);
}
function testTrailingSlashImpliedSettingRealm() {
$this->get('http://www.lastcraft.com/test/protected');
$this->authenticate('test', 'secret');
$this->assertResponse(200);
$this->get('http://www.lastcraft.com/test/protected/');
$this->assertResponse(200);
}
function testEncodedAuthenticationFetchesPage() {
$this->get('http://test:secret@www.lastcraft.com/test/protected/');
$this->assertResponse(200);
}
function testEncodedAuthenticationFetchesPageAfterTrailingSlashRedirect() {
$this->get('http://test:secret@www.lastcraft.com/test/protected');
$this->assertResponse(200);
}
function testRealmExtendsToWholeDirectory() {
$this->get('http://www.lastcraft.com/test/protected/1.html');
$this->authenticate('test', 'secret');
@ -744,6 +915,12 @@
$this->assertTitle('Simple test target file');
}
function testRedirectKeepsEncodedAuthentication() {
$this->get('http://test:secret@www.lastcraft.com/test/protected/local_redirect.php');
$this->assertResponse(200);
$this->assertTitle('Simple test target file');
}
function testSessionRestartLosesAuthentication() {
$this->get('http://www.lastcraft.com/test/protected/');
$this->authenticate('test', 'secret');
@ -755,7 +932,6 @@
}
class TestOfLoadingFrames extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
@ -881,7 +1057,7 @@
function testJumpToNamedPageReplacesJustThatFrame() {
$this->get('http://www.lastcraft.com/test/messy_frameset.html');
$this->assertWantedPattern('/Simple test front controller/');
$this->assertPattern('/Simple test front controller/');
$this->clickLink('Index');
$this->assertResponse(200);
$this->assertWantedText('[action=index]');
@ -910,30 +1086,30 @@
$this->get('http://www.lastcraft.com/test/messy_frameset.html');
$this->clickLink('Empty query');
$this->assertResponse(200);
$this->assertWantedPattern('/Simple test front controller/');
$this->assertWantedPattern('/raw get data.*?\[\].*?get data/si');
$this->assertWantedPattern('/Count: 1/');
$this->assertPattern('/Simple test front controller/');
$this->assertPattern('/raw get data.*?\[\].*?get data/si');
$this->assertPattern('/Count: 1/');
}
function testJumpToUnnamedPageWithEmptyLinkReplacesJustThatFrame() {
$this->get('http://www.lastcraft.com/test/messy_frameset.html');
$this->clickLink('Empty link');
$this->assertResponse(200);
$this->assertWantedPattern('/Simple test front controller/');
$this->assertWantedPattern('/raw get data.*?\[\].*?get data/si');
$this->assertWantedPattern('/Count: 1/');
$this->assertPattern('/Simple test front controller/');
$this->assertPattern('/raw get data.*?\[\].*?get data/si');
$this->assertPattern('/Count: 1/');
}
function testJumpBackADirectoryLevelReplacesJustThatFrame() {
$this->get('http://www.lastcraft.com/test/messy_frameset.html');
$this->clickLink('Down one');
$this->assertWantedPattern('/index of \/test/i');
$this->assertWantedPattern('/Count: 1/');
$this->assertPattern('/index of \/test/i');
$this->assertPattern('/Count: 1/');
}
function testSubmitToNamedPageReplacesJustThatFrame() {
$this->get('http://www.lastcraft.com/test/messy_frameset.html');
$this->assertWantedPattern('/Simple test front controller/');
$this->assertPattern('/Simple test front controller/');
$this->clickSubmit('Index');
$this->assertResponse(200);
$this->assertWantedText('[action=Index]');
@ -967,8 +1143,8 @@
function testSubmitBackADirectoryLevelReplacesJustThatFrame() {
$this->get('http://www.lastcraft.com/test/messy_frameset.html');
$this->clickSubmit('Down one');
$this->assertWantedPattern('/index of \/test/i');
$this->assertWantedPattern('/Count: 1/');
$this->assertPattern('/index of \/test/i');
$this->assertPattern('/Count: 1/');
}
function testTopLinkExitsFrameset() {
@ -988,6 +1164,9 @@
}
class TestOfFrameAuthentication extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
function testUnauthenticatedFrameSendsChallenge() {
$this->get('http://www.lastcraft.com/test/protected/');
@ -1029,28 +1208,31 @@
}
class TestOfNestedFrames extends WebTestCase {
function setUp() {
$this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion());
}
function testCanNavigateToSpecificContent() {
$this->get('http://www.lastcraft.com/test/nested_frameset.html');
$this->assertTitle('Nested frameset for testing of SimpleTest');
$this->assertWantedPattern('/This is frame A/');
$this->assertWantedPattern('/This is frame B/');
$this->assertWantedPattern('/Simple test front controller/');
$this->assertPattern('/This is frame A/');
$this->assertPattern('/This is frame B/');
$this->assertPattern('/Simple test front controller/');
$this->assertLink('2');
$this->assertLink('Set one to 2');
$this->assertWantedPattern('/Count: 1/');
$this->assertWantedPattern('/r=rrr/');
$this->assertPattern('/Count: 1/');
$this->assertPattern('/r=rrr/');
$this->setFrameFocus('pair');
$this->assertWantedPattern('/This is frame A/');
$this->assertWantedPattern('/This is frame B/');
$this->assertNoUnwantedPattern('/Simple test front controller/');
$this->assertPattern('/This is frame A/');
$this->assertPattern('/This is frame B/');
$this->assertNoPattern('/Simple test front controller/');
$this->assertNoLink('2');
$this->setFrameFocus('aaa');
$this->assertWantedPattern('/This is frame A/');
$this->assertNoUnwantedPattern('/This is frame B/');
$this->assertPattern('/This is frame A/');
$this->assertNoPattern('/This is frame B/');
$this->clearFrameFocus();
$this->assertResponse(200);
@ -1058,28 +1240,28 @@
$this->assertResponse(200);
$this->setFrameFocus('Front controller');
$this->assertResponse(200);
$this->assertWantedPattern('/Simple test front controller/');
$this->assertPattern('/Simple test front controller/');
$this->assertNoLink('2');
}
function testReloadingFramesetPage() {
$this->get('http://www.lastcraft.com/test/nested_frameset.html');
$this->assertWantedPattern('/Count: 1/');
$this->assertPattern('/Count: 1/');
$this->retry();
$this->assertWantedPattern('/Count: 2/');
$this->assertPattern('/Count: 2/');
$this->retry();
$this->assertWantedPattern('/Count: 3/');
$this->assertPattern('/Count: 3/');
}
function testRetryingNestedPageOnlyRetriesThatSet() {
$this->get('http://www.lastcraft.com/test/nested_frameset.html');
$this->assertWantedPattern('/Count: 1/');
$this->assertPattern('/Count: 1/');
$this->setFrameFocus('messy');
$this->retry();
$this->assertWantedPattern('/Count: 2/');
$this->assertPattern('/Count: 2/');
$this->setFrameFocus('Counter');
$this->retry();
$this->assertWantedPattern('/Count: 3/');
$this->assertPattern('/Count: 3/');
$this->clearFrameFocus();
$this->setFrameFocus('messy');
@ -1087,7 +1269,7 @@
$this->retry();
$this->clearFrameFocus();
$this->assertWantedPattern('/Count: 3/');
$this->assertPattern('/Count: 3/');
}
function testAuthenticatingNestedPage() {
@ -1100,7 +1282,7 @@
$this->authenticate('test', 'secret');
$this->assertResponse(200);
$this->assertWantedPattern('/A target for the SimpleTest test suite/');
$this->assertPattern('/A target for the SimpleTest test suite/');
}
}
?>

View file

@ -1,27 +1,10 @@
<?php
// $Id$
if (! defined('TEST')) {
define('TEST', __FILE__);
require_once('../unit_tester.php');
require_once('../shell_tester.php');
require_once('../reporter.php');
require_once('../mock_objects.php');
require_once('unit_tests.php');
// Uncomment and modify the following line if you are accessing
// the net via a proxy server.
//
// SimpleTestOptions::useProxy('http://my-proxy', 'optional username', 'optional password');
class AllTests extends GroupTest {
function AllTests() {
$this->GroupTest('All tests for SimpleTest ' . SimpleTestOptions::getVersion());
$this->addTestCase(new UnitTests());
$this->addTestFile('shell_test.php');
$this->addTestFile('live_test.php');
$this->addTestFile('acceptance_test.php');
$this->addTestFile('real_sites_test.php');
}
}
require_once(dirname(__FILE__) . '/test_groups.php');
require_once(dirname(__FILE__) . '/../reporter.php');
$test = &new AllTests();
if (SimpleReporter::inCli()) {

View file

@ -38,6 +38,14 @@
new SimpleUrl('http://www.here.com/pathmore/hello.html')));
}
function testInsideWithMissingTrailingSlash() {
$realm = &new SimpleRealm(
'Basic',
new SimpleUrl('http://www.here.com/path/'));
$this->assertTrue($realm->isWithin(
new SimpleUrl('http://www.here.com/path')));
}
function testDifferentPageNameStillInside() {
$realm = &new SimpleRealm(
'Basic',

View file

@ -24,7 +24,6 @@
function testEmptyHistoryHasFalseContents() {
$history = &new SimpleBrowserHistory();
$this->assertIdentical($history->getMethod(), false);
$this->assertIdentical($history->getUrl(), false);
$this->assertIdentical($history->getParameters(), false);
}
@ -38,130 +37,107 @@
function testCurrentTargetAccessors() {
$history = &new SimpleBrowserHistory();
$history->recordEntry(
'GET',
new SimpleUrl('http://www.here.com/'),
new SimpleFormEncoding());
$this->assertIdentical($history->getMethod(), 'GET');
new SimpleGetEncoding());
$this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.here.com/'));
$this->assertIdentical($history->getParameters(), new SimpleFormEncoding());
$this->assertIdentical($history->getParameters(), new SimpleGetEncoding());
}
function testSecondEntryAccessors() {
$history = &new SimpleBrowserHistory();
$history->recordEntry(
'GET',
new SimpleUrl('http://www.first.com/'),
new SimpleFormEncoding());
new SimpleGetEncoding());
$history->recordEntry(
'POST',
new SimpleUrl('http://www.second.com/'),
new SimpleFormEncoding(array('a' => 1)));
$this->assertIdentical($history->getMethod(), 'POST');
new SimplePostEncoding(array('a' => 1)));
$this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/'));
$this->assertIdentical(
$history->getParameters(),
new SimpleFormEncoding(array('a' => 1)));
new SimplePostEncoding(array('a' => 1)));
}
function testGoingBackwards() {
$history = &new SimpleBrowserHistory();
$history->recordEntry(
'GET',
new SimpleUrl('http://www.first.com/'),
new SimpleFormEncoding());
new SimpleGetEncoding());
$history->recordEntry(
'POST',
new SimpleUrl('http://www.second.com/'),
new SimpleFormEncoding(array('a' => 1)));
new SimplePostEncoding(array('a' => 1)));
$this->assertTrue($history->back());
$this->assertIdentical($history->getMethod(), 'GET');
$this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/'));
$this->assertIdentical($history->getParameters(), new SimpleFormEncoding());
$this->assertIdentical($history->getParameters(), new SimpleGetEncoding());
}
function testGoingBackwardsOffBeginning() {
$history = &new SimpleBrowserHistory();
$history->recordEntry(
'GET',
new SimpleUrl('http://www.first.com/'),
new SimpleFormEncoding());
new SimpleGetEncoding());
$this->assertFalse($history->back());
$this->assertIdentical($history->getMethod(), 'GET');
$this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/'));
$this->assertIdentical($history->getParameters(), new SimpleFormEncoding());
$this->assertIdentical($history->getParameters(), new SimpleGetEncoding());
}
function testGoingForwardsOffEnd() {
$history = &new SimpleBrowserHistory();
$history->recordEntry(
'GET',
new SimpleUrl('http://www.first.com/'),
new SimpleFormEncoding());
new SimpleGetEncoding());
$this->assertFalse($history->forward());
$this->assertIdentical($history->getMethod(), 'GET');
$this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/'));
$this->assertIdentical($history->getParameters(), new SimpleFormEncoding());
$this->assertIdentical($history->getParameters(), new SimpleGetEncoding());
}
function testGoingBackwardsAndForwards() {
$history = &new SimpleBrowserHistory();
$history->recordEntry(
'GET',
new SimpleUrl('http://www.first.com/'),
new SimpleFormEncoding());
new SimpleGetEncoding());
$history->recordEntry(
'POST',
new SimpleUrl('http://www.second.com/'),
new SimpleFormEncoding(array('a' => 1)));
new SimplePostEncoding(array('a' => 1)));
$this->assertTrue($history->back());
$this->assertTrue($history->forward());
$this->assertIdentical($history->getMethod(), 'POST');
$this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/'));
$this->assertIdentical(
$history->getParameters(),
new SimpleFormEncoding(array('a' => 1)));
new SimplePostEncoding(array('a' => 1)));
}
function testNewEntryReplacesNextOne() {
$history = &new SimpleBrowserHistory();
$history->recordEntry(
'GET',
new SimpleUrl('http://www.first.com/'),
new SimpleFormEncoding());
new SimpleGetEncoding());
$history->recordEntry(
'POST',
new SimpleUrl('http://www.second.com/'),
new SimpleFormEncoding(array('a' => 1)));
new SimplePostEncoding(array('a' => 1)));
$history->back();
$history->recordEntry(
'GET',
new SimpleUrl('http://www.third.com/'),
new SimpleFormEncoding());
$this->assertIdentical($history->getMethod(), 'GET');
new SimpleGetEncoding());
$this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.third.com/'));
$this->assertIdentical($history->getParameters(), new SimpleFormEncoding());
$this->assertIdentical($history->getParameters(), new SimpleGetEncoding());
}
function testNewEntryDropsFutureEntries() {
$history = &new SimpleBrowserHistory();
$history->recordEntry(
'GET',
new SimpleUrl('http://www.first.com/'),
new SimpleFormEncoding());
new SimpleGetEncoding());
$history->recordEntry(
'GET',
new SimpleUrl('http://www.second.com/'),
new SimpleFormEncoding());
new SimpleGetEncoding());
$history->recordEntry(
'GET',
new SimpleUrl('http://www.third.com/'),
new SimpleFormEncoding());
new SimpleGetEncoding());
$history->back();
$history->back();
$history->recordEntry(
'GET',
new SimpleUrl('http://www.fourth.com/'),
new SimpleFormEncoding());
new SimpleGetEncoding());
$this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.fourth.com/'));
$this->assertFalse($history->forward());
$history->back();
@ -247,17 +223,17 @@
function testFormHandling() {
$page = &new MockSimplePage($this);
$page->setReturnValue('getField', 'Value');
$page->expectOnce('getField', array('key'));
$page->expectOnce('setField', array('key', 'Value'));
$page->setReturnValue('getFieldByName', 'Value');
$page->expectOnce('getFieldByName', array('key'));
$page->expectOnce('setFieldByName', array('key', 'Value'));
$page->setReturnValue('getFieldById', 'Id value');
$page->expectOnce('getFieldById', array(99));
$page->expectOnce('setFieldById', array(99, 'Id value'));
$browser = &$this->loadPage($page);
$this->assertEqual($browser->getField('key'), 'Value');
$this->assertEqual($browser->getFieldByName('key'), 'Value');
$this->assertEqual($browser->getFieldById(99), 'Id value');
$browser->setField('key', 'Value');
$browser->setFieldByName('key', 'Value');
$browser->setFieldById(99, 'Id value');
$page->tally();
@ -280,11 +256,11 @@
$agent->expectArgumentsAt(
0,
'fetchResponse',
array('GET', new SimpleUrl('http://this.com/page.html'), false));
array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding()));
$agent->expectArgumentsAt(
1,
'fetchResponse',
array('GET', new SimpleUrl('http://this.com/new.html'), false));
array(new SimpleUrl('http://this.com/new.html'), new SimpleGetEncoding()));
$agent->expectCallCount('fetchResponse', 2);
$page = &new MockSimplePage($this);
@ -306,13 +282,13 @@
$agent->expectArgumentsAt(
0,
'fetchResponse',
array('GET', new SimpleUrl('http://this.com/page.html'), false));
array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding()));
$target = new SimpleUrl('http://this.com/new.html');
$target->setTarget('missing');
$agent->expectArgumentsAt(
1,
'fetchResponse',
array('GET', $target, false));
array($target, new SimpleGetEncoding()));
$agent->expectCallCount('fetchResponse', 2);
$parsed_url = new SimpleUrl('http://this.com/new.html');
@ -351,7 +327,7 @@
$agent->expectArgumentsAt(
1,
'fetchResponse',
array('GET', new SimpleUrl('1.html'), false));
array(new SimpleUrl('1.html'), new SimpleGetEncoding()));
$agent->expectCallCount('fetchResponse', 2);
$page = &new MockSimplePage($this);
@ -371,9 +347,8 @@
$agent = &new MockSimpleUserAgent($this);
$agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this));
$agent->expectArgumentsAt(1, 'fetchResponse', array(
'GET',
new SimpleUrl('http://this.com/link.html'),
false));
new SimpleGetEncoding()));
$agent->expectCallCount('fetchResponse', 2);
$page = &new MockSimplePage($this);
@ -405,16 +380,15 @@
$agent = &new MockSimpleUserAgent($this);
$agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this));
$agent->expectArgumentsAt(1, 'fetchResponse', array(
'POST',
new SimpleUrl('http://this.com/handler.html'),
new SimpleFormEncoding(array('a' => 'A'))));
new SimplePostEncoding(array('a' => 'A'))));
$agent->expectCallCount('fetchResponse', 2);
$form = &new MockSimpleForm($this);
$form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
$form->setReturnValue('getMethod', 'post');
$form->setReturnValue('submitButtonByLabel', new SimpleFormEncoding(array('a' => 'A')));
$form->expectOnce('submitButtonByLabel', array('Go', false));
$form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A')));
$form->expectOnce('submitButton', array(new SimpleByLabel('Go'), false));
$page = &new MockSimplePage($this);
$page->setReturnReference('getFormBySubmitLabel', $form);
@ -434,15 +408,14 @@
$agent = &new MockSimpleUserAgent($this);
$agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this));
$agent->expectArgumentsAt(1, 'fetchResponse', array(
'GET',
new SimpleUrl('http://this.com/page.html'),
new SimpleFormEncoding(array('a' => 'A'))));
new SimpleGetEncoding(array('a' => 'A'))));
$agent->expectCallCount('fetchResponse', 2);
$form = &new MockSimpleForm($this);
$form->setReturnValue('getAction', new SimpleUrl('http://this.com/page.html'));
$form->setReturnValue('getMethod', 'get');
$form->setReturnValue('submitButtonByLabel', new SimpleFormEncoding(array('a' => 'A')));
$form->setReturnValue('submitButton', new SimpleGetEncoding(array('a' => 'A')));
$page = &new MockSimplePage($this);
$page->setReturnReference('getFormBySubmitLabel', $form);
@ -466,7 +439,7 @@
$form = &new MockSimpleForm($this);
$form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
$form->setReturnValue('getMethod', 'post');
$form->setReturnValue('submitButtonByName', new SimpleFormEncoding(array('a' => 'A')));
$form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A')));
$page = &new MockSimplePage($this);
$page->setReturnReference('getFormBySubmitName', $form);
@ -487,8 +460,8 @@
$form = &new MockSimpleForm($this);
$form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
$form->setReturnValue('getMethod', 'post');
$form->setReturnValue('submitButtonById', new SimpleFormEncoding(array('a' => 'A')));
$form->expectOnce('submitButtonById', array(99, false));
$form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A')));
$form->expectOnce('submitButton', array(new SimpleById(99), false));
$page = &new MockSimplePage($this);
$page->setReturnReference('getFormBySubmitId', $form);
@ -510,8 +483,8 @@
$form = &new MockSimpleForm($this);
$form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
$form->setReturnValue('getMethod', 'post');
$form->setReturnValue('submitImageByLabel', new SimpleFormEncoding(array('a' => 'A')));
$form->expectOnce('submitImageByLabel', array('Go!', 10, 11, false));
$form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A')));
$form->expectOnce('submitImage', array(new SimpleByLabel('Go!'), 10, 11, false));
$page = &new MockSimplePage($this);
$page->setReturnReference('getFormByImageLabel', $form);
@ -533,8 +506,8 @@
$form = &new MockSimpleForm($this);
$form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
$form->setReturnValue('getMethod', 'post');
$form->setReturnValue('submitImageByName', new SimpleFormEncoding(array('a' => 'A')));
$form->expectOnce('submitImageByName', array('a', 10, 11, false));
$form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A')));
$form->expectOnce('submitImage', array(new SimpleByName('a'), 10, 11, false));
$page = &new MockSimplePage($this);
$page->setReturnReference('getFormByImageName', $form);
@ -556,8 +529,8 @@
$form = &new MockSimpleForm($this);
$form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
$form->setReturnValue('getMethod', 'post');
$form->setReturnValue('submitImageById', new SimpleFormEncoding(array('a' => 'A')));
$form->expectOnce('submitImageById', array(99, 10, 11, false));
$form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A')));
$form->expectOnce('submitImage', array(new SimpleById(99), 10, 11, false));
$page = &new MockSimplePage($this);
$page->setReturnReference('getFormByImageId', $form);
@ -576,15 +549,14 @@
$agent = &new MockSimpleUserAgent($this);
$agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this));
$agent->expectArgumentsAt(1, 'fetchResponse', array(
'POST',
new SimpleUrl('http://this.com/handler.html'),
new SimpleFormEncoding(array('a' => 'A'))));
new SimplePostEncoding(array('a' => 'A'))));
$agent->expectCallCount('fetchResponse', 2);
$form = &new MockSimpleForm($this);
$form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
$form->setReturnValue('getMethod', 'post');
$form->setReturnValue('submit', new SimpleFormEncoding(array('a' => 'A')));
$form->setReturnValue('submit', new SimplePostEncoding(array('a' => 'A')));
$page = &new MockSimplePage($this);
$page->setReturnReference('getFormById', $form);
@ -616,7 +588,7 @@
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getUrl', $url);
$response->setReturnValue('getContent', $raw);
$agent->setReturnReference('fetchResponse', $response, array('*', $url, '*'));
$agent->setReturnReference('fetchResponse', $response, array($url, '*'));
}
return $agent;
}

View file

@ -0,0 +1,59 @@
<?php
// $Id: collector_test.php,v 1.7 2005/07/27 17:19:20 lastcraft Exp $
require_once(dirname(__FILE__) . '/../collector.php');
Mock::generate('GroupTest');
class PathEqualExpectation extends EqualExpectation {
function PathEqualExpectation($value, $message = '%s') {
$this->EqualExpectation(str_replace('\\', '/', $value), $message);
}
function test($compare) {
return parent::test(str_replace('\\', '/', $compare));
}
}
class TestOfCollector extends UnitTestCase {
function testCollectionIsAddedToGroup() {
$group = &new MockGroupTest($this);
$group->expectMinimumCallCount('addTestFile', 2);
$group->expectArguments(
'addTestFile',
array(new PatternExpectation('/collectable\\.(1|2)$/')));
$collector = &new SimpleCollector();
$collector->collect($group, dirname(__FILE__) . '/support/collector/');
$group->tally();
}
}
class TestOfPatternCollector extends UnitTestCase {
function testAddingEverythingToGroup() {
$group = &new MockGroupTest($this);
$group->expectCallCount('addTestFile', 2);
$group->expectArguments(
'addTestFile',
array(new PatternExpectation('/collectable\\.(1|2)$/')));
$collector = &new SimplePatternCollector();
$collector->collect($group, dirname(__FILE__) . '/support/collector/', '/.*/');
$group->tally();
}
function testOnlyMatchedFilesAreAddedToGroup() {
$group = &new MockGroupTest($this);
$group->expectOnce('addTestFile', array(new PathEqualExpectation(
dirname(__FILE__) . '/support/collector/collectable.1')));
$collector = &new SimplePatternCollector();
$collector->collect($group, dirname(__FILE__) . '/support/collector/', '/1$/');
$group->tally();
}
}
?>

View file

@ -40,46 +40,46 @@
function testDescribeNull() {
$dumper = new SimpleDumper();
$this->assertWantedPattern('/null/i', $dumper->describeValue(null));
$this->assertPattern('/null/i', $dumper->describeValue(null));
}
function testDescribeBoolean() {
$dumper = new SimpleDumper();
$this->assertWantedPattern('/boolean/i', $dumper->describeValue(true));
$this->assertWantedPattern('/true/i', $dumper->describeValue(true));
$this->assertWantedPattern('/false/i', $dumper->describeValue(false));
$this->assertPattern('/boolean/i', $dumper->describeValue(true));
$this->assertPattern('/true/i', $dumper->describeValue(true));
$this->assertPattern('/false/i', $dumper->describeValue(false));
}
function testDescribeString() {
$dumper = new SimpleDumper();
$this->assertWantedPattern('/string/i', $dumper->describeValue('Hello'));
$this->assertWantedPattern('/Hello/', $dumper->describeValue('Hello'));
$this->assertPattern('/string/i', $dumper->describeValue('Hello'));
$this->assertPattern('/Hello/', $dumper->describeValue('Hello'));
}
function testDescribeInteger() {
$dumper = new SimpleDumper();
$this->assertWantedPattern('/integer/i', $dumper->describeValue(35));
$this->assertWantedPattern('/35/', $dumper->describeValue(35));
$this->assertPattern('/integer/i', $dumper->describeValue(35));
$this->assertPattern('/35/', $dumper->describeValue(35));
}
function testDescribeFloat() {
$dumper = new SimpleDumper();
$this->assertWantedPattern('/float/i', $dumper->describeValue(0.99));
$this->assertWantedPattern('/0\.99/', $dumper->describeValue(0.99));
$this->assertPattern('/float/i', $dumper->describeValue(0.99));
$this->assertPattern('/0\.99/', $dumper->describeValue(0.99));
}
function testDescribeArray() {
$dumper = new SimpleDumper();
$this->assertWantedPattern('/array/i', $dumper->describeValue(array(1, 4)));
$this->assertWantedPattern('/2/i', $dumper->describeValue(array(1, 4)));
$this->assertPattern('/array/i', $dumper->describeValue(array(1, 4)));
$this->assertPattern('/2/i', $dumper->describeValue(array(1, 4)));
}
function testDescribeObject() {
$dumper = new SimpleDumper();
$this->assertWantedPattern(
$this->assertPattern(
'/object/i',
$dumper->describeValue(new DumperDummy()));
$this->assertWantedPattern(
$this->assertPattern(
'/DumperDummy/i',
$dumper->describeValue(new DumperDummy()));
}

View file

@ -2,133 +2,186 @@
// $Id$
require_once(dirname(__FILE__) . '/../url.php');
require_once(dirname(__FILE__) . '/../socket.php');
class FormEncodingTestCase extends UnitTestCase {
Mock::generate('SimpleSocket');
function testEmpty() {
$encoding = &new SimpleFormEncoding();
class TestOfEncodedParts extends UnitTestCase {
function testFormEncodedAsKeyEqualsValue() {
$pair = new SimpleEncodedPair('a', 'A');
$this->assertEqual($pair->asRequest(), 'a=A');
}
function testMimeEncodedAsHeadersAndContent() {
$pair = new SimpleEncodedPair('a', 'A');
$this->assertEqual(
$pair->asMime(),
"Content-Disposition: form-data; name=\"a\"\r\n\r\nA");
}
function testAttachmentEncodedAsHeadersWithDispositionAndContent() {
$part = new SimpleAttachment('a', 'A', 'aaa.txt');
$this->assertEqual(
$part->asMime(),
"Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" .
"Content-Type: text/plain\r\n\r\nA");
}
}
class TestOfEncoding extends UnitTestCase {
var $_content_so_far;
function write($content) {
$this->_content_so_far .= $content;
}
function clear() {
$this->_content_so_far = '';
}
function assertWritten($encoding, $content, $message = '%s') {
$this->clear();
$encoding->writeTo($this);
$this->assertIdentical($this->_content_so_far, $content, $message);
}
function testGetEmpty() {
$encoding = &new SimpleGetEncoding();
$this->assertIdentical($encoding->getValue('a'), false);
$this->assertIdentical($encoding->getKeys(), array());
$this->assertIdentical($encoding->asString(), '');
$this->assertIdentical($encoding->asUrlRequest(), '');
}
function testPostEmpty() {
$encoding = &new SimplePostEncoding();
$this->assertIdentical($encoding->getValue('a'), false);
$this->assertWritten($encoding, '');
}
function testPrefilled() {
$encoding = &new SimpleFormEncoding(array('a' => 'aaa'));
$encoding = &new SimplePostEncoding(array('a' => 'aaa'));
$this->assertIdentical($encoding->getValue('a'), 'aaa');
$this->assertIdentical($encoding->getKeys(), array('a'));
$this->assertIdentical($encoding->asString(), 'a=aaa');
$this->assertWritten($encoding, 'a=aaa');
}
function testPrefilledWithObject() {
$encoding = &new SimpleFormEncoding(new SimpleFormEncoding(array('a' => 'aaa')));
$encoding = &new SimplePostEncoding(new SimpleEncoding(array('a' => 'aaa')));
$this->assertIdentical($encoding->getValue('a'), 'aaa');
$this->assertIdentical($encoding->getKeys(), array('a'));
$this->assertIdentical($encoding->asString(), 'a=aaa');
$this->assertWritten($encoding, 'a=aaa');
}
function testMultiplePrefilled() {
$encoding = &new SimpleFormEncoding(array('a' => array('a1', 'a2')));
$encoding = &new SimplePostEncoding(array('a' => array('a1', 'a2')));
$this->assertIdentical($encoding->getValue('a'), array('a1', 'a2'));
$this->assertIdentical($encoding->asString(), 'a=a1&a=a2');
$this->assertWritten($encoding, 'a=a1&a=a2');
}
function testSingleParameter() {
$encoding = &new SimpleFormEncoding();
$encoding = &new SimplePostEncoding();
$encoding->add('a', 'Hello');
$this->assertEqual($encoding->getValue('a'), 'Hello');
$this->assertIdentical($encoding->asString(), 'a=Hello');
$this->assertWritten($encoding, 'a=Hello');
}
function testFalseParameter() {
$encoding = &new SimpleFormEncoding();
$encoding = &new SimplePostEncoding();
$encoding->add('a', false);
$this->assertEqual($encoding->getValue('a'), false);
$this->assertIdentical($encoding->asString(), '');
$this->assertWritten($encoding, '');
}
function testUrlEncoding() {
$encoding = &new SimpleFormEncoding();
$encoding = &new SimplePostEncoding();
$encoding->add('a', 'Hello there!');
$this->assertIdentical($encoding->asString(), 'a=Hello+there%21');
$this->assertWritten($encoding, 'a=Hello+there%21');
}
function testMultipleParameter() {
$encoding = &new SimpleFormEncoding();
$encoding = &new SimplePostEncoding();
$encoding->add('a', 'Hello');
$encoding->add('b', 'Goodbye');
$this->assertIdentical($encoding->asString(), 'a=Hello&b=Goodbye');
$this->assertWritten($encoding, 'a=Hello&b=Goodbye');
}
function testEmptyParameters() {
$encoding = &new SimpleFormEncoding();
$encoding = &new SimplePostEncoding();
$encoding->add('a', '');
$encoding->add('b', '');
$this->assertIdentical($encoding->asString(), 'a=&b=');
$this->assertWritten($encoding, 'a=&b=');
}
function testRepeatedParameter() {
$encoding = &new SimpleFormEncoding();
$encoding = &new SimplePostEncoding();
$encoding->add('a', 'Hello');
$encoding->add('a', 'Goodbye');
$this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye'));
$this->assertIdentical($encoding->asString(), 'a=Hello&a=Goodbye');
}
function testDefaultCoordinatesAreUnset() {
$encoding = &new SimpleFormEncoding();
$this->assertIdentical($encoding->getX(), false);
$this->assertIdentical($encoding->getY(), false);
}
function testSettingCoordinates() {
$encoding = &new SimpleFormEncoding();
$encoding->setCoordinates('32', '45');
$this->assertIdentical($encoding->getX(), 32);
$this->assertIdentical($encoding->getY(), 45);
$this->assertIdentical($encoding->asString(), '?32,45');
}
function testClearingCordinates() {
$encoding = &new SimpleFormEncoding();
$encoding->setCoordinates('32', '45');
$encoding->setCoordinates();
$this->assertIdentical($encoding->getX(), false);
$this->assertIdentical($encoding->getY(), false);
$this->assertWritten($encoding, 'a=Hello&a=Goodbye');
}
function testAddingLists() {
$encoding = &new SimpleFormEncoding();
$encoding = &new SimplePostEncoding();
$encoding->add('a', array('Hello', 'Goodbye'));
$this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye'));
$this->assertIdentical($encoding->asString(), 'a=Hello&a=Goodbye');
$this->assertWritten($encoding, 'a=Hello&a=Goodbye');
}
function testMergeInHash() {
$encoding = &new SimpleFormEncoding(array('a' => 'A1', 'b' => 'B'));
$encoding = &new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B'));
$encoding->merge(array('a' => 'A2'));
$this->assertIdentical($encoding->getValue('a'), array('A1', 'A2'));
$this->assertIdentical($encoding->getValue('b'), 'B');
}
function testMergeInObject() {
$encoding = &new SimpleFormEncoding(array('a' => 'A1', 'b' => 'B'));
$encoding->merge(new SimpleFormEncoding(array('a' => 'A2')));
$encoding = &new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B'));
$encoding->merge(new SimpleEncoding(array('a' => 'A2')));
$this->assertIdentical($encoding->getValue('a'), array('A1', 'A2'));
$this->assertIdentical($encoding->getValue('b'), 'B');
}
function testMergeInObjectWithCordinates() {
$incoming = new SimpleFormEncoding(array('a' => 'A2'));
$incoming->setCoordinates(25, 24);
function testPrefilledMultipart() {
$encoding = &new SimpleMultipartEncoding(array('a' => 'aaa'), 'boundary');
$this->assertIdentical($encoding->getValue('a'), 'aaa');
$this->assertwritten($encoding,
"--boundary\r\n" .
"Content-Disposition: form-data; name=\"a\"\r\n" .
"\r\n" .
"aaa\r\n" .
"--boundary--\r\n");
}
$encoding = &new SimpleFormEncoding(array('a' => 'A1'));
$encoding->setCoordinates(1, 2);
$encoding->merge($incoming);
function testAttachment() {
$encoding = &new SimpleMultipartEncoding(array(), 'boundary');
$encoding->attach('a', 'aaa', 'aaa.txt');
$this->assertIdentical($encoding->getValue('a'), 'aaa.txt');
$this->assertwritten($encoding,
"--boundary\r\n" .
"Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" .
"Content-Type: text/plain\r\n" .
"\r\n" .
"aaa\r\n" .
"--boundary--\r\n");
}
}
$this->assertIdentical($encoding->getValue('a'), array('A1', 'A2'));
$this->assertIdentical($encoding->getX(), 25);
$this->assertIdentical($encoding->getY(), 24);
$this->assertIdentical($encoding->asString(), 'a=A1&a=A2?25,24');
class TestOfFormHeaders extends UnitTestCase {
function testEmptyEncodingWritesZeroContentLength() {
$socket = &new MockSimpleSocket($this);
$socket->expectArgumentsAt(0, 'write', array("Content-Length: 0\r\n"));
$socket->expectArgumentsAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n"));
$encoding = &new SimplePostEncoding();
$encoding->writeHeadersTo($socket);
$socket->tally();
}
function testEmptyMultipartEncodingWritesEndBoundaryContentLength() {
$socket = &new MockSimpleSocket($this);
$socket->expectArgumentsAt(0, 'write', array("Content-Length: 14\r\n"));
$socket->expectArgumentsAt(1, 'write', array("Content-Type: multipart/form-data, boundary=boundary\r\n"));
$encoding = &new SimpleMultipartEncoding(array(), 'boundary');
$encoding->writeHeadersTo($socket);
$socket->tally();
}
}
?>

View file

@ -8,10 +8,10 @@
$is_true = &new EqualExpectation(true);
$this->assertTrue($is_true->test(true));
$this->assertFalse($is_true->test(false));
$this->assertWantedPattern(
$this->assertPattern(
'/equal expectation.*?boolean: true/i',
$is_true->testMessage(true));
$this->assertWantedPattern(
$this->assertPattern(
'/fails.*?boolean.*?boolean/i',
$is_true->testMessage(false));
}
@ -20,9 +20,9 @@
$hello = &new EqualExpectation("Hello");
$this->assertTrue($hello->test("Hello"));
$this->assertFalse($hello->test("Goodbye"));
$this->assertWantedPattern('/Equal expectation.*?Hello/', $hello->testMessage("Hello"));
$this->assertWantedPattern('/fails/', $hello->testMessage("Goodbye"));
$this->assertWantedPattern('/fails.*?goodbye/i', $hello->testMessage("Goodbye"));
$this->assertPattern('/Equal expectation.*?Hello/', $hello->testMessage("Hello"));
$this->assertPattern('/fails/', $hello->testMessage("Goodbye"));
$this->assertPattern('/fails.*?goodbye/i', $hello->testMessage("Goodbye"));
}
function testStringPosition() {
@ -35,13 +35,13 @@
"z" => 0);
$str = &new EqualExpectation("abc");
foreach ($comparisons as $compare => $position) {
$this->assertWantedPattern(
$this->assertPattern(
"/at character $position/",
$str->testMessage($compare));
}
$str = &new EqualExpectation("abcd");
foreach ($comparisons as $compare => $position) {
$this->assertWantedPattern(
$this->assertPattern(
"/at character $position/",
$str->testMessage($compare));
}
@ -51,10 +51,10 @@
$fifteen = &new EqualExpectation(15);
$this->assertTrue($fifteen->test(15));
$this->assertFalse($fifteen->test(14));
$this->assertWantedPattern(
$this->assertPattern(
'/equal expectation.*?15/i',
$fifteen->testMessage(15));
$this->assertWantedPattern(
$this->assertPattern(
'/fails.*?15.*?14/i',
$fifteen->testMessage(14));
}
@ -63,10 +63,10 @@
$pi = &new EqualExpectation(3.14);
$this->assertTrue($pi->test(3.14));
$this->assertFalse($pi->test(3.15));
$this->assertWantedPattern(
$this->assertPattern(
'/float.*?3\.14/i',
$pi->testMessage(3.14));
$this->assertWantedPattern(
$this->assertPattern(
'/fails.*?3\.14.*?3\.15/i',
$pi->testMessage(3.15));
}
@ -78,14 +78,14 @@
$this->assertEqual(
$colours->testMessage(array("r", "g", "b")),
"Equal expectation [Array: 3 items]");
$this->assertWantedPattern('/fails/', $colours->testMessage(array("r", "g", "z")));
$this->assertWantedPattern(
$this->assertPattern('/fails/', $colours->testMessage(array("r", "g", "z")));
$this->assertPattern(
'/\[2\] at character 0/',
$colours->testMessage(array("r", "g", "z")));
$this->assertWantedPattern(
$this->assertPattern(
'/key.*? does not match/',
$colours->testMessage(array("r", "g")));
$this->assertWantedPattern(
$this->assertPattern(
'/key.*? does not match/',
$colours->testMessage(array("r", "g", "b", "z")));
}
@ -94,10 +94,10 @@
$is_blue = &new EqualExpectation(array("r" => 0, "g" => 0, "b" => 255));
$this->assertTrue($is_blue->test(array("r" => 0, "g" => 0, "b" => 255)));
$this->assertFalse($is_blue->test(array("r" => 0, "g" => 255, "b" => 0)));
$this->assertWantedPattern(
$this->assertPattern(
'/array.*?3 items/i',
$is_blue->testMessage(array("r" => 0, "g" => 0, "b" => 255)));
$this->assertWantedPattern(
$this->assertPattern(
'/fails.*?\[b\]/',
$is_blue->testMessage(array("r" => 0, "g" => 0, "b" => 254)));
}
@ -108,7 +108,7 @@
"b" => array(
"c" => 2,
"d" => "Three")));
$this->assertWantedPattern(
$this->assertPattern(
'/member.*?\[b\].*?\[d\].*?at character 5/',
$tree->testMessage(array(
"a" => 1,
@ -123,16 +123,37 @@
}
}
class TestOfWithin extends UnitTestCase {
function testWithinFloatingPointMargin() {
$within = new WithinMarginExpectation(1.0, 0.2);
$this->assertFalse($within->test(0.7));
$this->assertTrue($within->test(0.8));
$this->assertTrue($within->test(0.9));
$this->assertTrue($within->test(1.1));
$this->assertTrue($within->test(1.2));
$this->assertFalse($within->test(1.3));
}
function testOutsideFloatingPointMargin() {
$within = new OutsideMarginExpectation(1.0, 0.2);
$this->assertTrue($within->test(0.7));
$this->assertFalse($within->test(0.8));
$this->assertFalse($within->test(1.2));
$this->assertTrue($within->test(1.3));
}
}
class TestOfInequality extends UnitTestCase {
function testStringMismatch() {
$not_hello = &new NotEqualExpectation("Hello");
$this->assertTrue($not_hello->test("Goodbye"));
$this->assertFalse($not_hello->test("Hello"));
$this->assertWantedPattern(
$this->assertPattern(
'/at character 0/',
$not_hello->testMessage("Goodbye"));
$this->assertWantedPattern(
$this->assertPattern(
'/matches/',
$not_hello->testMessage("Hello"));
}
@ -153,13 +174,13 @@
$this->assertTrue($string->test("37"));
$this->assertFalse($string->test(37));
$this->assertFalse($string->test("38"));
$this->assertWantedPattern(
$this->assertPattern(
'/identical.*?string.*?37/i',
$string->testMessage("37"));
$this->assertWantedPattern(
$this->assertPattern(
'/fails.*?37/',
$string->testMessage(37));
$this->assertWantedPattern(
$this->assertPattern(
'/at character 1/',
$string->testMessage("38"));
}
@ -181,10 +202,10 @@
$this->assertTrue($string->test("38"));
$this->assertTrue($string->test(37));
$this->assertFalse($string->test("37"));
$this->assertWantedPattern(
$this->assertPattern(
'/at character 1/',
$string->testMessage("38"));
$this->assertWantedPattern(
$this->assertPattern(
'/passes.*?type/',
$string->testMessage(37));
}
@ -193,13 +214,13 @@
class TestOfPatterns extends UnitTestCase {
function testWanted() {
$pattern = &new WantedPatternExpectation('/hello/i');
$pattern = &new PatternExpectation('/hello/i');
$this->assertTrue($pattern->test("Hello world"));
$this->assertFalse($pattern->test("Goodbye world"));
}
function testUnwanted() {
$pattern = &new UnwantedPatternExpectation('/hello/i');
$pattern = &new NoPatternExpectation('/hello/i');
$this->assertFalse($pattern->test("Hello world"));
$this->assertTrue($pattern->test("Goodbye world"));
}

View file

@ -14,7 +14,7 @@
$form->getAction(),
new SimpleUrl('http://host/a/here.php'));
$this->assertIdentical($form->getId(), '33');
$this->assertNull($form->getValue('a'));
$this->assertNull($form->getValue(new SimpleByName('a')));
}
function testEmptyAction() {
@ -57,11 +57,11 @@
new SimpleUrl('htp://host'));
$form->addWidget(new SimpleTextTag(
array('name' => 'me', 'type' => 'text', 'value' => 'Myself')));
$this->assertIdentical($form->getValue('me'), 'Myself');
$this->assertTrue($form->setField('me', 'Not me'));
$this->assertFalse($form->setField('not_present', 'Not me'));
$this->assertIdentical($form->getValue('me'), 'Not me');
$this->assertNull($form->getValue('not_present'));
$this->assertIdentical($form->getValue(new SimpleByName('me')), 'Myself');
$this->assertTrue($form->setField(new SimpleByName('me'), 'Not me'));
$this->assertFalse($form->setField(new SimpleByName('not_present'), 'Not me'));
$this->assertIdentical($form->getValue(new SimpleByName('me')), 'Not me');
$this->assertNull($form->getValue(new SimpleByName('not_present')));
}
function testTextWidgetById() {
@ -70,16 +70,28 @@
new SimpleUrl('htp://host'));
$form->addWidget(new SimpleTextTag(
array('name' => 'me', 'type' => 'text', 'value' => 'Myself', 'id' => 50)));
$this->assertIdentical($form->getValueById(50), 'Myself');
$this->assertTrue($form->setFieldById(50, 'Not me'));
$this->assertIdentical($form->getValueById(50), 'Not me');
$this->assertIdentical($form->getValue(new SimpleById(50)), 'Myself');
$this->assertTrue($form->setField(new SimpleById(50), 'Not me'));
$this->assertIdentical($form->getValue(new SimpleById(50)), 'Not me');
}
function testTextWidgetByLabel() {
$form = &new SimpleForm(
new SimpleFormTag(array()),
new SimpleUrl('htp://host'));
$widget = &new SimpleTextTag(array('name' => 'me', 'type' => 'text', 'value' => 'a'));
$form->addWidget($widget);
$widget->setLabel('thing');
$this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'a');
$this->assertTrue($form->setField(new SimpleByLabel('thing'), 'b'));
$this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'b');
}
function testSubmitEmpty() {
$form = &new SimpleForm(
new SimpleFormTag(array()),
new SimpleUrl('htp://host'));
$this->assertIdentical($form->submit(), new SimpleFormEncoding());
$this->assertIdentical($form->submit(), new SimpleGetEncoding());
}
function testSubmitButton() {
@ -88,18 +100,18 @@
new SimpleUrl('http://host'));
$form->addWidget(new SimpleSubmitTag(
array('type' => 'submit', 'name' => 'go', 'value' => 'Go!', 'id' => '9')));
$this->assertTrue($form->hasSubmitName('go'));
$this->assertEqual($form->getValue('go'), 'Go!');
$this->assertEqual($form->getValueById(9), 'Go!');
$this->assertTrue($form->hasSubmit(new SimpleByName('go')));
$this->assertEqual($form->getValue(new SimpleByName('go')), 'Go!');
$this->assertEqual($form->getValue(new SimpleById(9)), 'Go!');
$this->assertEqual(
$form->submitButtonByName('go'),
new SimpleFormEncoding(array('go' => 'Go!')));
$form->submitButton(new SimpleByName('go')),
new SimpleGetEncoding(array('go' => 'Go!')));
$this->assertEqual(
$form->submitButtonByLabel('Go!'),
new SimpleFormEncoding(array('go' => 'Go!')));
$form->submitButton(new SimpleByLabel('Go!')),
new SimpleGetEncoding(array('go' => 'Go!')));
$this->assertEqual(
$form->submitButtonById(9),
new SimpleFormEncoding(array('go' => 'Go!')));
$form->submitButton(new SimpleById(9)),
new SimpleGetEncoding(array('go' => 'Go!')));
}
function testSubmitWithAdditionalParameters() {
@ -107,16 +119,10 @@
new SimpleFormTag(array()),
new SimpleUrl('http://host'));
$form->addWidget(new SimpleSubmitTag(
array('type' => 'submit', 'name' => 'go', 'value' => 'Go!', 'id' => '9')));
array('type' => 'submit', 'name' => 'go', 'value' => 'Go!')));
$this->assertEqual(
$form->submitButtonByName('go', array('a' => 'A')),
new SimpleFormEncoding(array('go' => 'Go!', 'a' => 'A')));
$this->assertEqual(
$form->submitButtonByLabel('Go!', array('a' => 'A')),
new SimpleFormEncoding(array('go' => 'Go!', 'a' => 'A')));
$this->assertEqual(
$form->submitButtonById(9, array('a' => 'A')),
new SimpleFormEncoding(array('go' => 'Go!', 'a' => 'A')));
$form->submitButton(new SimpleByLabel('Go!'), array('a' => 'A')),
new SimpleGetEncoding(array('go' => 'Go!', 'a' => 'A')));
}
function testSubmitButtonWithLabelOfSubmit() {
@ -124,19 +130,13 @@
new SimpleFormTag(array()),
new SimpleUrl('http://host'));
$form->addWidget(new SimpleSubmitTag(
array('type' => 'submit', 'name' => 'test', 'value' => 'Submit', 'id' => '9')));
$this->assertTrue($form->hasSubmitName('test'));
$this->assertEqual($form->getValue('test'), 'Submit');
$this->assertEqual($form->getValueById(9), 'Submit');
array('type' => 'submit', 'name' => 'test', 'value' => 'Submit')));
$this->assertEqual(
$form->submitButtonByName('test'),
new SimpleFormEncoding(array('test' => 'Submit')));
$form->submitButton(new SimpleByName('test')),
new SimpleGetEncoding(array('test' => 'Submit')));
$this->assertEqual(
$form->submitButtonByLabel('Submit'),
new SimpleFormEncoding(array('test' => 'Submit')));
$this->assertEqual(
$form->submitButtonById(9),
new SimpleFormEncoding(array('test' => 'Submit')));
$form->submitButton(new SimpleByLabel('Submit')),
new SimpleGetEncoding(array('test' => 'Submit')));
}
function testSubmitButtonWithWhitespacePaddedLabelOfSubmit() {
@ -144,12 +144,10 @@
new SimpleFormTag(array()),
new SimpleUrl('http://host'));
$form->addWidget(new SimpleSubmitTag(
array('type' => 'submit', 'name' => 'test', 'value' => ' Submit ', 'id' => '9')));
$this->assertEqual($form->getValue('test'), ' Submit ');
$this->assertEqual($form->getValueById(9), ' Submit ');
array('type' => 'submit', 'name' => 'test', 'value' => ' Submit ')));
$this->assertEqual(
$form->submitButtonByLabel('Submit'),
new SimpleFormEncoding(array('test' => ' Submit ')));
$form->submitButton(new SimpleByLabel('Submit')),
new SimpleGetEncoding(array('test' => ' Submit ')));
}
function testImageSubmitButton() {
@ -162,18 +160,18 @@
'name' => 'go',
'alt' => 'Go!',
'id' => '9')));
$this->assertTrue($form->hasImageLabel('Go!'));
$this->assertTrue($form->hasImage(new SimpleByLabel('Go!')));
$this->assertEqual(
$form->submitImageByLabel('Go!', 100, 101),
new SimpleFormEncoding(array('go.x' => 100, 'go.y' => 101)));
$this->assertTrue($form->hasImageName('go'));
$form->submitImage(new SimpleByLabel('Go!'), 100, 101),
new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101)));
$this->assertTrue($form->hasImage(new SimpleByName('go')));
$this->assertEqual(
$form->submitImageByName('go', 100, 101),
new SimpleFormEncoding(array('go.x' => 100, 'go.y' => 101)));
$this->assertTrue($form->hasImageId(9));
$form->submitImage(new SimpleByName('go'), 100, 101),
new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101)));
$this->assertTrue($form->hasImage(new SimpleById(9)));
$this->assertEqual(
$form->submitImageById(9, 100, 101),
new SimpleFormEncoding(array('go.x' => 100, 'go.y' => 101)));
$form->submitImage(new SimpleById(9), 100, 101),
new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101)));
}
function testImageSubmitButtonWithAdditionalData() {
@ -184,19 +182,10 @@
'type' => 'image',
'src' => 'source.jpg',
'name' => 'go',
'alt' => 'Go!',
'id' => '9')));
'alt' => 'Go!')));
$this->assertEqual(
$form->submitImageByLabel('Go!', 100, 101, array('a' => 'A')),
new SimpleFormEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A')));
$this->assertTrue($form->hasImageName('go'));
$this->assertEqual(
$form->submitImageByName('go', 100, 101, array('a' => 'A')),
new SimpleFormEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A')));
$this->assertTrue($form->hasImageId(9));
$this->assertEqual(
$form->submitImageById(9, 100, 101, array('a' => 'A')),
new SimpleFormEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A')));
$form->submitImage(new SimpleByLabel('Go!'), 100, 101, array('a' => 'A')),
new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A')));
}
function testButtonTag() {
@ -207,17 +196,17 @@
array('type' => 'submit', 'name' => 'go', 'value' => 'Go', 'id' => '9'));
$widget->addContent('Go!');
$form->addWidget($widget);
$this->assertTrue($form->hasSubmitName('go'));
$this->assertTrue($form->hasSubmitLabel('Go!'));
$this->assertTrue($form->hasSubmit(new SimpleByName('go')));
$this->assertTrue($form->hasSubmit(new SimpleByLabel('Go!')));
$this->assertEqual(
$form->submitButtonByName('go'),
new SimpleFormEncoding(array('go' => 'Go')));
$form->submitButton(new SimpleByName('go')),
new SimpleGetEncoding(array('go' => 'Go')));
$this->assertEqual(
$form->submitButtonByLabel('Go!'),
new SimpleFormEncoding(array('go' => 'Go')));
$form->submitButton(new SimpleByLabel('Go!')),
new SimpleGetEncoding(array('go' => 'Go')));
$this->assertEqual(
$form->submitButtonById(9),
new SimpleFormEncoding(array('go' => 'Go')));
$form->submitButton(new SimpleById(9)),
new SimpleGetEncoding(array('go' => 'Go')));
}
function testSingleSelectFieldSubmitted() {
@ -230,7 +219,20 @@
$form->addWidget($select);
$this->assertIdentical(
$form->submit(),
new SimpleFormEncoding(array('a' => 'aaa')));
new SimpleGetEncoding(array('a' => 'aaa')));
}
function testSingleSelectFieldSubmittedWithPost() {
$form = &new SimpleForm(
new SimpleFormTag(array('method' => 'post')),
new SimpleUrl('htp://host'));
$select = &new SimpleSelectionTag(array('name' => 'a'));
$select->addTag(new SimpleOptionTag(
array('value' => 'aaa', 'selected' => '')));
$form->addWidget($select);
$this->assertIdentical(
$form->submit(),
new SimplePostEncoding(array('a' => 'aaa')));
}
function testUnchecked() {
@ -239,11 +241,11 @@
new SimpleUrl('htp://host'));
$form->addWidget(new SimpleCheckboxTag(
array('name' => 'me', 'type' => 'checkbox')));
$this->assertIdentical($form->getValue('me'), false);
$this->assertTrue($form->setField('me', 'on'));
$this->assertEqual($form->getValue('me'), 'on');
$this->assertFalse($form->setField('me', 'other'));
$this->assertEqual($form->getValue('me'), 'on');
$this->assertIdentical($form->getValue(new SimpleByName('me')), false);
$this->assertTrue($form->setField(new SimpleByName('me'), 'on'));
$this->assertEqual($form->getValue(new SimpleByName('me')), 'on');
$this->assertFalse($form->setField(new SimpleByName('me'), 'other'));
$this->assertEqual($form->getValue(new SimpleByName('me')), 'on');
}
function testChecked() {
@ -252,11 +254,11 @@
new SimpleUrl('htp://host'));
$form->addWidget(new SimpleCheckboxTag(
array('name' => 'me', 'value' => 'a', 'type' => 'checkbox', 'checked' => '')));
$this->assertIdentical($form->getValue('me'), 'a');
$this->assertFalse($form->setField('me', 'on'));
$this->assertEqual($form->getValue('me'), 'a');
$this->assertTrue($form->setField('me', false));
$this->assertEqual($form->getValue('me'), false);
$this->assertIdentical($form->getValue(new SimpleByName('me')), 'a');
$this->assertTrue($form->setField(new SimpleByName('me'), 'a'));
$this->assertEqual($form->getValue(new SimpleByName('me')), 'a');
$this->assertTrue($form->setField(new SimpleByName('me'), false));
$this->assertEqual($form->getValue(new SimpleByName('me')), false);
}
function testSingleUncheckedRadioButton() {
@ -265,9 +267,9 @@
new SimpleUrl('htp://host'));
$form->addWidget(new SimpleRadioButtonTag(
array('name' => 'me', 'value' => 'a', 'type' => 'radio')));
$this->assertIdentical($form->getValue('me'), false);
$this->assertTrue($form->setField('me', 'a'));
$this->assertIdentical($form->getValue('me'), 'a');
$this->assertIdentical($form->getValue(new SimpleByName('me')), false);
$this->assertTrue($form->setField(new SimpleByName('me'), 'a'));
$this->assertEqual($form->getValue(new SimpleByName('me')), 'a');
}
function testSingleCheckedRadioButton() {
@ -276,8 +278,8 @@
new SimpleUrl('htp://host'));
$form->addWidget(new SimpleRadioButtonTag(
array('name' => 'me', 'value' => 'a', 'type' => 'radio', 'checked' => '')));
$this->assertIdentical($form->getValue('me'), 'a');
$this->assertFalse($form->setField('me', 'other'));
$this->assertIdentical($form->getValue(new SimpleByName('me')), 'a');
$this->assertFalse($form->setField(new SimpleByName('me'), 'other'));
}
function testUncheckedRadioButtons() {
@ -288,13 +290,13 @@
array('name' => 'me', 'value' => 'a', 'type' => 'radio')));
$form->addWidget(new SimpleRadioButtonTag(
array('name' => 'me', 'value' => 'b', 'type' => 'radio')));
$this->assertIdentical($form->getValue('me'), false);
$this->assertTrue($form->setField('me', 'a'));
$this->assertIdentical($form->getValue('me'), 'a');
$this->assertTrue($form->setField('me', 'b'));
$this->assertIdentical($form->getValue('me'), 'b');
$this->assertFalse($form->setField('me', 'c'));
$this->assertIdentical($form->getValue('me'), 'b');
$this->assertIdentical($form->getValue(new SimpleByName('me')), false);
$this->assertTrue($form->setField(new SimpleByName('me'), 'a'));
$this->assertIdentical($form->getValue(new SimpleByName('me')), 'a');
$this->assertTrue($form->setField(new SimpleByName('me'), 'b'));
$this->assertIdentical($form->getValue(new SimpleByName('me')), 'b');
$this->assertFalse($form->setField(new SimpleByName('me'), 'c'));
$this->assertIdentical($form->getValue(new SimpleByName('me')), 'b');
}
function testCheckedRadioButtons() {
@ -305,9 +307,9 @@
array('name' => 'me', 'value' => 'a', 'type' => 'radio')));
$form->addWidget(new SimpleRadioButtonTag(
array('name' => 'me', 'value' => 'b', 'type' => 'radio', 'checked' => '')));
$this->assertIdentical($form->getValue('me'), 'b');
$this->assertTrue($form->setField('me', 'a'));
$this->assertIdentical($form->getValue('me'), 'a');
$this->assertIdentical($form->getValue(new SimpleByName('me')), 'b');
$this->assertTrue($form->setField(new SimpleByName('me'), 'a'));
$this->assertIdentical($form->getValue(new SimpleByName('me')), 'a');
}
function testMultipleFieldsWithSameKey() {
@ -318,9 +320,9 @@
array('name' => 'a', 'type' => 'checkbox', 'value' => 'me')));
$form->addWidget(new SimpleCheckboxTag(
array('name' => 'a', 'type' => 'checkbox', 'value' => 'you')));
$this->assertIdentical($form->getValue('a'), false);
$this->assertTrue($form->setField('a', 'me'));
$this->assertIdentical($form->getValue('a'), 'me');
$this->assertIdentical($form->getValue(new SimpleByName('a')), false);
$this->assertTrue($form->setField(new SimpleByName('a'), 'me'));
$this->assertIdentical($form->getValue(new SimpleByName('a')), 'me');
}
}
?>

View file

@ -99,17 +99,17 @@
$this->assertEqual($frameset->getText(), 'Stuff1 Stuff2');
}
function testFieldIsFirstInFramelist() {
function testFieldFoundIsFirstInFramelist() {
$frame1 = &new MockSimplePage($this);
$frame1->setReturnValue('getField', null);
$frame1->expectOnce('getField', array('a'));
$frame1->setReturnValue('getFieldByName', null);
$frame1->expectOnce('getFieldByName', array('a'));
$frame2 = &new MockSimplePage($this);
$frame2->setReturnValue('getField', 'A');
$frame2->expectOnce('getField', array('a'));
$frame2->setReturnValue('getFieldByName', 'A');
$frame2->expectOnce('getFieldByName', array('a'));
$frame3 = &new MockSimplePage($this);
$frame3->expectNever('getField');
$frame3->expectNever('getFieldByName');
$page = &new MockSimplePage($this);
$frameset = &new SimpleFrameset($page);
@ -117,7 +117,7 @@
$frameset->addFrame($frame2);
$frameset->addFrame($frame3);
$this->assertIdentical($frameset->getField('a'), 'A');
$this->assertIdentical($frameset->getFieldByName('a'), 'A');
$frame1->tally();
$frame2->tally();
}
@ -512,18 +512,18 @@
function testSettingAllFrameFieldsWhenNoFrameFocus() {
$frame1 = &new MockSimplePage($this);
$frame1->expectOnce('setField', array('a', 'A'));
$frame1->expectOnce('setFieldByName', array('a', 'A'));
$frame1->expectOnce('setFieldById', array(22, 'A'));
$frame2 = &new MockSimplePage($this);
$frame2->expectOnce('setField', array('a', 'A'));
$frame2->expectOnce('setFieldByName', array('a', 'A'));
$frame2->expectOnce('setFieldById', array(22, 'A'));
$frameset = &new SimpleFrameset(new MockSimplePage($this));
$frameset->addFrame($frame1, 'A');
$frameset->addFrame($frame2, 'B');
$frameset->setField('a', 'A');
$frameset->setFieldByName('a', 'A');
$frameset->setFieldById(22, 'A');
$frame1->tally();
$frame2->tally();

View file

@ -275,8 +275,7 @@
$route = &new MockSimpleRoute($this);
$route->setReturnReference('createConnection', $socket);
$request = &new SimpleHttpRequest($route, 'GET');
$request = &new SimpleHttpRequest($route, new SimpleGetEncoding());
$reponse = &$request->fetch(15);
$this->assertTrue($reponse->isError());
}
@ -289,8 +288,7 @@
$route->setReturnReference('createConnection', $socket);
$route->expectArguments('createConnection', array('GET', 15));
$request = &new SimpleHttpRequest($route, 'GET');
$request = &new SimpleHttpRequest($route, new SimpleGetEncoding());
$this->assertIsA($request->fetch(15), 'SimpleHttpResponse');
$socket->tally();
$route->tally();
@ -305,7 +303,7 @@
$route = &new MockSimpleRoute($this);
$route->setReturnReference('createConnection', $socket);
$request = &new SimpleHttpRequest($route, 'GET');
$request = &new SimpleHttpRequest($route, new SimpleGetEncoding());
$request->addHeaderLine('My: stuff');
$request->fetch(15);
@ -321,10 +319,10 @@
$route = &new MockSimpleRoute($this);
$route->setReturnReference('createConnection', $socket);
$request = &new SimpleHttpRequest($route, 'GET');
$request = &new SimpleHttpRequest($route, new SimpleGetEncoding());
$request->setCookie(new SimpleCookie('a', 'A'));
$this->assertIsA($request->fetch(15), 'SimpleHttpResponse');
$socket->tally();
}
@ -335,24 +333,24 @@
$route = &new MockSimpleRoute($this);
$route->setReturnReference('createConnection', $socket);
$request = &new SimpleHttpRequest($route, 'GET');
$request = &new SimpleHttpRequest($route, new SimpleGetEncoding());
$request->setCookie(new SimpleCookie('a', 'A'));
$request->setCookie(new SimpleCookie('b', 'B'));
$request->fetch(15);
$socket->tally();
}
}
class TestOfHttpPostRequest extends UnitTestCase {
function testReadingBadConnection() {
function testReadingBadConnectionCausesErrorBecauseOfDeadSocket() {
$socket = &new MockSimpleSocket($this);
$route = &new MockSimpleRoute($this);
$route->setReturnReference('createConnection', $socket);
$request = &new SimpleHttpRequest($route, 'POST', '');
$request = &new SimpleHttpRequest($route, new SimplePostEncoding());
$reponse = &$request->fetch(15);
$this->assertTrue($reponse->isError());
@ -369,9 +367,9 @@
$route->setReturnReference('createConnection', $socket);
$route->expectArguments('createConnection', array('POST', 15));
$request = &new SimpleHttpRequest($route, 'POST', new SimpleFormEncoding());
$request = &new SimpleHttpRequest($route, new SimplePostEncoding());
$this->assertIsA($request->fetch(15), 'SimpleHttpResponse');
$socket->tally();
$route->tally();
}
@ -389,10 +387,9 @@
$request = &new SimpleHttpRequest(
$route,
'POST',
new SimpleFormEncoding(array('a' => 'A')));
new SimplePostEncoding(array('a' => 'A')));
$this->assertIsA($request->fetch(15), 'SimpleHttpResponse');
$socket->tally();
$route->tally();
}
@ -459,9 +456,9 @@
$socket = &new MockSimpleSocket($this);
$socket->setReturnValue('getSent', '');
$response = &new SimpleHttpResponse($socket, 'GET', new SimpleUrl('here'));
$response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
$this->assertTrue($response->isError());
$this->assertWantedPattern('/Nothing fetched/', $response->getError());
$this->assertPattern('/Nothing fetched/', $response->getError());
$this->assertIdentical($response->getContent(), false);
$this->assertIdentical($response->getSent(), '');
}
@ -473,7 +470,7 @@
$socket->setReturnValue("read", "");
$socket->setReturnValue('getSent', 'HTTP/1.1 ...');
$response = &new SimpleHttpResponse($socket, 'GET', new SimpleUrl('here'));
$response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
$this->assertTrue($response->isError());
$this->assertEqual($response->getContent(), '');
$this->assertEqual($response->getSent(), 'HTTP/1.1 ...');
@ -486,7 +483,7 @@
$socket->setReturnValueAt(2, "read", "Content-Type: text/plain\r\n");
$socket->setReturnValue("read", "");
$response = &new SimpleHttpResponse($socket, 'GET', new SimpleUrl('here'));
$response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
$this->assertTrue($response->isError());
$this->assertEqual($response->getContent(), "");
}
@ -500,7 +497,7 @@
$socket->setReturnValueAt(4, "read", "with two lines in it\n");
$socket->setReturnValue("read", "");
$response = &new SimpleHttpResponse($socket, 'GET', new SimpleUrl('here'));
$response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
$this->assertFalse($response->isError());
$this->assertEqual(
$response->getContent(),
@ -524,7 +521,7 @@
$socket->setReturnValueAt(6, "read", "\r\n");
$socket->setReturnValue("read", "");
$response = &new SimpleHttpResponse($socket, 'GET', new SimpleUrl('here'));
$response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
$this->assertFalse($response->isError());
$headers = $response->getHeaders();
$cookies = $headers->getNewCookies();
@ -543,7 +540,7 @@
$socket->setReturnValueAt(4, "read", "\r\n");
$socket->setReturnValue("read", "");
$response = &new SimpleHttpResponse($socket, 'GET', new SimpleUrl('here'));
$response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
$headers = $response->getHeaders();
$this->assertTrue($headers->isRedirect());
$this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/");
@ -558,7 +555,7 @@
$socket->setReturnValueAt(4, "read", "\r\n");
$socket->setReturnValue("read", "");
$response = &new SimpleHttpResponse($socket, 'GET', new SimpleUrl('here'));
$response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
$headers = $response->getHeaders();
$this->assertTrue($headers->isRedirect());
$this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com:80/");

View file

@ -14,8 +14,8 @@
function testBadSocket() {
$socket = &new SimpleSocket('bad_url', 111, 5);
$this->assertTrue($socket->isError());
$this->assertWantedPattern(
'/Cannot open \\[bad_url:111\\] with \\[.*?\\] within \\[5\\] seconds/',
$this->assertPattern(
'/Cannot open \\[bad_url:111\\] with \\[/',
$socket->getError());
$this->assertFalse($socket->isOpen());
$this->assertFalse($socket->write('A message'));

View file

@ -456,19 +456,47 @@
}
}
class TestOfForms extends UnitTestCase {
class TestOfFormsCreatedFromEventStream extends UnitTestCase {
function testButtons() {
function testFormCanBeSubmitted() {
$page = &new SimplePage(new MockSimpleHttpResponse($this));
$page->acceptFormStart(
new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php')));
$page->AcceptTag(
new SimpleSubmitTag(array('type' => 'submit', 'name' => 's')));
$page->acceptFormEnd();
$form = &$page->getFormBySubmitLabel('Submit');
$this->assertEqual(
$form->submitButton(new SimpleByLabel('Submit')),
new SimpleGetEncoding(array('s' => 'Submit')));
}
function testInputFieldCanBeReadBack() {
$page = &new SimplePage(new MockSimpleHttpResponse($this));
$page->acceptFormStart(
new SimpleFormTag(array("method" => "GET", "action" => "here.php")));
$page->AcceptTag(
new SimpleTextTag(array("type" => "text", "name" => "a", "value" => "A")));
$page->AcceptTag(
new SimpleSubmitTag(array("type" => "submit", "name" => "s")));
$page->acceptFormEnd();
$form = &$page->getFormBySubmitLabel("Submit");
$this->assertEqual(
$form->submitButtonByLabel("Submit"),
new SimpleFormEncoding(array("s" => "Submit")));
$this->assertEqual($page->getFieldByName('a'), 'A');
}
function testInputFieldCanBeReadBackByLabel() {
$label = &new SimpleLabelTag(array());
$page = &new SimplePage(new MockSimpleHttpResponse($this));
$page->acceptFormStart(
new SimpleFormTag(array("method" => "GET", "action" => "here.php")));
$page->acceptLabelStart($label);
$label->addContent('l');
$page->AcceptTag(
new SimpleTextTag(array("type" => "text", "name" => "a", "value" => "A")));
$page->acceptLabelEnd();
$page->AcceptTag(
new SimpleSubmitTag(array("type" => "submit", "name" => "s")));
$page->acceptFormEnd();
$this->assertEqual($page->getField('l'), 'A');
}
}
@ -476,7 +504,8 @@
function &parse($response) {
$builder = &new SimplePageBuilder();
return $builder->parse($response);
$page = &$builder->parse($response);
return $page;
}
function testEmptyPage() {
@ -522,7 +551,6 @@
function testTitle() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent', '<html><head><title>Me</title></head></html>');
$page = &$this->parse($response);
$this->assertEqual($page->getTitle(), 'Me');
}
@ -532,7 +560,6 @@
$response->setReturnValue(
'getContent',
'<html><head><Title> <b>Me&amp;Me </TITLE></b></head></html>');
$page = &$this->parse($response);
$this->assertEqual($page->getTitle(), "Me&Me");
}
@ -543,9 +570,8 @@
'<html><head><form>' .
'<input type="text" name="here" value="Hello">' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertEqual($page->getField('here'), "Hello");
$this->assertEqual($page->getFieldByName('here'), "Hello");
}
function testUnclosedForm() {
@ -554,9 +580,8 @@
'<html><head><form>' .
'<input type="text" name="here" value="Hello">' .
'</head></html>');
$page = &$this->parse($response);
$this->assertEqual($page->getField('here'), "Hello");
$this->assertEqual($page->getFieldByName('here'), "Hello");
}
function testEmptyFrameset() {
@ -564,7 +589,6 @@
$response->setReturnValue(
'getContent',
'<html><frameset></frameset></html>');
$page = &$this->parse($response);
$this->assertTrue($page->hasFrames());
$this->assertIdentical($page->getFrameset(), array());
@ -604,7 +628,6 @@
$response->setReturnValue(
'getContent',
'<html><frameset><frame></frameset></html>');
$page = &$this->parse($response);
$this->assertTrue($page->hasFrames());
$this->assertIdentical($page->getFrameset(), array());
@ -630,7 +653,8 @@
function testNamedFrames() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent', '<html><frameset>' .
$response->setReturnValue('getContent',
'<html><frameset>' .
'<frame src="a.html">' .
'<frame name="_one" src="b.html">' .
'<frame src="c.html">' .
@ -652,7 +676,6 @@
$response->setReturnValue(
'getContent',
'<html><head><form><input type="submit"></form></head></html>');
$page = &$this->parse($response);
$this->assertNull($page->getFormBySubmitLabel('submit'));
$this->assertIsA($page->getFormBySubmitName('submit'), 'SimpleForm');
@ -664,7 +687,6 @@
$response->setReturnValue(
'getContent',
'<html><head><FORM><INPUT TYPE="SUBMIT"></FORM></head></html>');
$page = &$this->parse($response);
$this->assertIsA($page->getFormBySubmitName('submit'), 'SimpleForm');
$this->assertIsA($page->getFormBySubmitLabel('Submit'), 'SimpleForm');
@ -672,10 +694,10 @@
function testFindFormByImage() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent', '<html><head><form>' .
$response->setReturnValue('getContent',
'<html><head><form>' .
'<input type="image" id=100 alt="Label" name="me">' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertIsA($page->getFormByImageLabel('Label'), 'SimpleForm');
$this->assertIsA($page->getFormByImageName('me'), 'SimpleForm');
@ -684,10 +706,10 @@
function testFindFormByButtonTag() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent', '<html><head><form>' .
$response->setReturnValue('getContent',
'<html><head><form>' .
'<button type="submit" name="b" value="B">BBB</button>' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertNull($page->getFormBySubmitLabel('b'));
$this->assertNull($page->getFormBySubmitLabel('B'));
@ -700,7 +722,6 @@
$response->setReturnValue(
'getContent',
'<html><head><form id="55"><input type="submit"></form></head></html>');
$page = &$this->parse($response);
$this->assertNull($page->getFormById(54));
$this->assertIsA($page->getFormById(55), 'SimpleForm');
@ -708,85 +729,155 @@
function testReadingTextField() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent', '<html><head><form>' .
$response->setReturnValue('getContent',
'<html><head><form>' .
'<input type="text" name="a">' .
'<input type="text" name="b" value="bbb" id=3>' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertNull($page->getField('missing'));
$this->assertIdentical($page->getField('a'), '');
$this->assertIdentical($page->getField('b'), 'bbb');
$this->assertNull($page->getFieldByName('missing'));
$this->assertIdentical($page->getFieldByName('a'), '');
$this->assertIdentical($page->getFieldByName('b'), 'bbb');
}
function testReadingTextFieldIsCaseInsensitive() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent', '<html><head><FORM>' .
$response->setReturnValue('getContent',
'<html><head><FORM>' .
'<INPUT TYPE="TEXT" NAME="a">' .
'<INPUT TYPE="TEXT" NAME="b" VALUE="bbb" id=3>' .
'</FORM></head></html>');
$page = &$this->parse($response);
$this->assertNull($page->getField('missing'));
$this->assertIdentical($page->getField('a'), '');
$this->assertIdentical($page->getField('b'), 'bbb');
$this->assertNull($page->getFieldByName('missing'));
$this->assertIdentical($page->getFieldByName('a'), '');
$this->assertIdentical($page->getFieldByName('b'), 'bbb');
}
function testSettingTextField() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent', '<html><head><form>' .
$response->setReturnValue('getContent',
'<html><head><form>' .
'<input type="text" name="a">' .
'<input type="text" name="b" id=3>' .
'<input type="submit">' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertTrue($page->setField('a', 'aaa'));
$this->assertEqual($page->getField('a'), 'aaa');
$this->assertTrue($page->setFieldByName('a', 'aaa'));
$this->assertEqual($page->getFieldByName('a'), 'aaa');
$this->assertTrue($page->setFieldById(3, 'bbb'));
$this->assertEqual($page->getFieldById(3), 'bbb');
$this->assertFalse($page->setField('z', 'zzz'));
$this->assertNull($page->getField('z'));
$this->assertFalse($page->setFieldByName('z', 'zzz'));
$this->assertNull($page->getFieldByName('z'));
}
function testSettingTextFieldByEnclosingLabel() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent',
'<html><head><form>' .
'<label>Stuff' .
'<input type="text" name="a" value="A">' .
'</label>' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertEqual($page->getFieldByName('a'), 'A');
$this->assertEqual($page->getField('Stuff'), 'A');
$this->assertTrue($page->setField('Stuff', 'aaa'));
$this->assertEqual($page->getField('Stuff'), 'aaa');
}
function testGettingTextFieldByEnclosingLabelWithConflictingOtherFields() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent',
'<html><head><form>' .
'<label>Stuff' .
'<input type="text" name="a" value="A">' .
'</label>' .
'<input type="text" name="b" value="B">' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertEqual($page->getFieldByName('a'), 'A');
$this->assertEqual($page->getFieldByName('b'), 'B');
$this->assertEqual($page->getField('Stuff'), 'A');
}
function testSettingTextFieldByExternalLabel() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent',
'<html><head><form>' .
'<label for="aaa">Stuff</label>' .
'<input id="aaa" type="text" name="a" value="A">' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertEqual($page->getField('Stuff'), 'A');
$this->assertTrue($page->setField('Stuff', 'aaa'));
$this->assertEqual($page->getField('Stuff'), 'aaa');
}
function testReadingTextArea() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent', '<html><head><form>' .
$response->setReturnValue('getContent',
'<html><head><form>' .
'<textarea name="a">aaa</textarea>' .
'<input type="submit">' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertEqual($page->getField('a'), 'aaa');
$this->assertEqual($page->getFieldByName('a'), 'aaa');
}
function testSettingTextArea() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent', '<html><head><form>' .
$response->setReturnValue('getContent',
'<html><head><form>' .
'<textarea name="a">aaa</textarea>' .
'<input type="submit">' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertTrue($page->setField('a', 'AAA'));
$this->assertEqual($page->getField('a'), 'AAA');
$this->assertTrue($page->setFieldByName('a', 'AAA'));
$this->assertEqual($page->getFieldByName('a'), 'AAA');
}
function testSettingSelectionField() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent', '<html><head><form>' .
$response->setReturnValue('getContent',
'<html><head><form>' .
'<select name="a">' .
'<option>aaa</option>' .
'<option selected>bbb</option>' .
'</select>' .
'<input type="submit">' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertEqual($page->getField('a'), 'bbb');
$this->assertFalse($page->setField('a', 'ccc'));
$this->assertTrue($page->setField('a', 'aaa'));
$this->assertEqual($page->getField('a'), 'aaa');
$this->assertEqual($page->getFieldByName('a'), 'bbb');
$this->assertFalse($page->setFieldByName('a', 'ccc'));
$this->assertTrue($page->setFieldByName('a', 'aaa'));
$this->assertEqual($page->getFieldByName('a'), 'aaa');
}
function testSettingSelectionFieldByEnclosingLabel() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent',
'<html><head><form>' .
'<label>Stuff' .
'<select name="a"><option selected>A</option><option>B</option></select>' .
'</label>' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertEqual($page->getField('Stuff'), 'A');
$this->assertTrue($page->setField('Stuff', 'B'));
$this->assertEqual($page->getField('Stuff'), 'B');
}
function testSettingRadioButonByEnclosingLabel() {
$response = &new MockSimpleHttpResponse($this);
$response->setReturnValue('getContent',
'<html><head><form>' .
'<label>A<input type="radio" name="r" value="a" checked></label>' .
'<label>B<input type="radio" name="r" value="b"></label>' .
'</form></head></html>');
$page = &$this->parse($response);
$this->assertEqual($page->getField('A'), 'a');
$this->assertTrue($page->setField('B', 'b'));
$this->assertEqual($page->getField('B'), 'b');
}
}
?>

View file

@ -561,6 +561,14 @@
$this->assertTrue($this->_parser->acceptStartToken(">", LEXER_EXIT));
}
function testSimpleLabelStart() {
$this->_parser->parse("");
$this->_listener->expectOnce("startElement", array("label", array()));
$this->_listener->setReturnValue("startElement", true);
$this->assertTrue($this->_parser->acceptStartToken("<label", LEXER_ENTER));
$this->assertTrue($this->_parser->acceptStartToken(">", LEXER_EXIT));
}
function testLinkStart() {
$this->_parser->parse("");
$this->_listener->expectOnce("startElement", array("a", array("href" => "here.html")));

View file

@ -1,6 +1,5 @@
<?php
// $Id$
// $Id: real_sites_test.php,v 1.17 2005/05/29 18:37:26 lastcraft Exp
require_once(dirname(__FILE__) . '/../web_tester.php');
class LiveSitesTestCase extends WebTestCase {
@ -20,10 +19,10 @@
$this->assertTitle('SourceForge.net: Search');
$this->assertTrue($this->clickLink('SimpleTest'));
$this->clickLink('statistics');
$this->assertWantedPattern('/Statistics for the past 7 days/');
$this->assertTrue($this->setField('report', 'Monthly'));
$this->clickSubmit('Change Stats View');
$this->assertWantedPattern('/Statistics for the past \d+ months/');
$this->assertWantedText('SimpleTest: Statistics');
$this->assertTrue($this->setField('mode', 'All Time'));
$this->clickSubmit('Change View');
$this->assertWantedText('Mar 2003');
}
}
?>

View file

@ -8,7 +8,7 @@
function testEcho() {
$shell = &new SimpleShell();
$this->assertIdentical($shell->execute('echo Hello'), 0);
$this->assertWantedPattern('/Hello/', $shell->getOutput());
$this->assertPattern('/Hello/', $shell->getOutput());
}
function testBadCommand() {

View file

@ -10,6 +10,11 @@
return $this->_mock_shell;
}
function testGenericEquality() {
$this->assertEqual('a', 'a');
$this->assertNotEqual('a', 'A');
}
function testExitCode() {
$this->_mock_shell = &new MockSimpleShell($this);
$this->_mock_shell->setReturnValue('execute', 0);

View file

@ -3,12 +3,12 @@
require_once(dirname(__FILE__) . '/../expectation.php');
class TestOfWildcardExpectation extends UnitTestCase {
class TestOfAnythingExpectation extends UnitTestCase {
function testSimpleInteger() {
$expectation = new WildcardExpectation();
$expectation = new AnythingExpectation();
$this->assertTrue($expectation->test(33));
$this->assertWantedPattern(
$this->assertPattern(
'/matches.*33/i',
$expectation->testMessage(33));
}
@ -45,8 +45,8 @@
$this->assertFalse($expectation->test(array()));
}
function testWildcardExpectations() {
$expectation = new ParametersExpectation(array(new WildcardExpectation()));
function testAnythingExpectations() {
$expectation = new ParametersExpectation(array(new AnythingExpectation()));
$this->assertFalse($expectation->test(array()));
$this->assertIdentical($expectation->test(array(null)), true);
$this->assertIdentical($expectation->test(array(13)), true);
@ -54,7 +54,7 @@
function testOtherExpectations() {
$expectation = new ParametersExpectation(
array(new WantedPatternExpectation('/hello/i')));
array(new PatternExpectation('/hello/i')));
$this->assertFalse($expectation->test(array('Goodbye')));
$this->assertTrue($expectation->test(array('hello')));
$this->assertTrue($expectation->test(array('Hello')));
@ -68,7 +68,7 @@
function testLongList() {
$expectation = new ParametersExpectation(
array("0", 0, new WildcardExpectation(), false));
array("0", 0, new AnythingExpectation(), false));
$this->assertTrue($expectation->test(array("0", 0, 37, false)));
$this->assertFalse($expectation->test(array("0", 0, 37, true)));
$this->assertFalse($expectation->test(array("0", 0, 37)));
@ -106,7 +106,7 @@
function testWildcard() {
$map = new CallMap();
$map->addValue(array(new WildcardExpectation(), 1, 3), "Fred");
$map->addValue(array(new AnythingExpectation(), 1, 3), "Fred");
$this->assertTrue($map->isMatch(array(2, 1, 3)));
$this->assertEqual($map->findFirstMatch(array(2, 1, 3)), "Fred");
}
@ -125,7 +125,7 @@
$map->addValue(array(1, 3), "1, 3");
$map->addValue(array(1), "1");
$map->addValue(array(1, 4), "1, 4");
$map->addValue(array(new WildcardExpectation()), "Any");
$map->addValue(array(new AnythingExpectation()), "Any");
$map->addValue(array(2), "2");
$map->addValue("", "Default");
$map->addValue(array(), "None");
@ -150,6 +150,10 @@
function anotherMethod() {
return true;
}
function __get($key) {
return $key;
}
}
Stub::generate("Dummy");
@ -385,7 +389,7 @@
$mock->setReturnValue(
"aMethod",
"aaa",
array(new wantedPatternExpectation('/hello/i')));
array(new PatternExpectation('/hello/i')));
$this->assertIdentical($mock->aMethod('Hello'), "aaa");
$this->assertNull($mock->aMethod('Goodbye'));
}
@ -410,6 +414,23 @@
}
}
class TestOfSpecialMethods extends UnitTestCase {
function testReturnFromSpecialMethod() {
$mock = &new MockDummy($this);
$mock->setReturnValue('__get', '1st Return', array('first'));
$mock->setReturnValue('__get', '2nd Return', array('second'));
$this->assertEqual($mock->__get('first'), '1st Return');
$this->assertEqual($mock->__get('second'), '2nd Return');
if (phpversion() >= 5) {
$this->assertEqual($mock->first, $mock->__get('first'));
$this->assertEqual($mock->second, $mock->__get('second'));
}
}
}
Mock::generate("SimpleTestCase");
class TestOfMockTally extends UnitTestCase {

View file

@ -0,0 +1 @@
ㄨ眾播輥奧禆蛺姣6

View file

@ -0,0 +1 @@
Some more text content

View file

@ -0,0 +1 @@
Sample for testing file upload

View file

@ -2,6 +2,9 @@
// $Id$
require_once(dirname(__FILE__) . '/../tag.php');
require_once(dirname(__FILE__) . '/../encoding.php');
Mock::generate('SimpleMultipartEncoding');
class TestOfTag extends UnitTestCase {
@ -58,11 +61,17 @@
class TestOfWidget extends UnitTestCase {
function testTextEmptyDefault() {
$tag = &new SimpleTextTag(array('' => 'text'));
$tag = &new SimpleTextTag(array('type' => 'text'));
$this->assertIdentical($tag->getDefault(), '');
$this->assertIdentical($tag->getValue(), '');
}
function testSettingOfExternalLabel() {
$tag = &new SimpleTextTag(array('type' => 'text'));
$tag->setLabel('it');
$this->assertTrue($tag->isLabel('it'));
}
function testTextDefault() {
$tag = &new SimpleTextTag(array('value' => 'aaa'));
$this->assertEqual($tag->getDefault(), 'aaa');
@ -393,6 +402,19 @@
$this->assertTrue($group->isId('i1'));
$this->assertTrue($group->isId('i2'));
}
function testIsLabelMatchesAnyWidgetInSet() {
$group = &new SimpleRadioGroup();
$button1 = &new SimpleRadioButtonTag(array('value' => 'A'));
$button1->setLabel('one');
$group->addWidget($button1);
$button2 = &new SimpleRadioButtonTag(array('value' => 'B'));
$button2->setLabel('two');
$group->addWidget($button2);
$this->assertFalse($group->isLabel('three'));
$this->assertTrue($group->isLabel('one'));
$this->assertTrue($group->isLabel('two'));
}
}
class TestOfTagGroup extends UnitTestCase {
@ -459,4 +481,39 @@
$this->assertTrue($group->isId(2));
}
}
class TestOfUploadWidget extends UnitTestCase {
function testValueIsFilePath() {
$upload = &new SimpleUploadTag(array('name' => 'a'));
$upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt');
$this->assertEqual($upload->getValue(), dirname(__FILE__) . '/support/upload_sample.txt');
}
function testSubmitsFileContents() {
$encoding = &new MockSimpleMultipartEncoding($this);
$encoding->expectOnce('attach', array(
'a',
'Sample for testing file upload',
'upload_sample.txt'));
$upload = &new SimpleUploadTag(array('name' => 'a'));
$upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt');
$upload->write($encoding);
$encoding->tally();
}
}
class TestOfLabelTag extends UnitTestCase {
function testLabelShouldHaveAnEndTag() {
$label = &new SimpleLabelTag(array());
$this->assertTrue($label->expectEndTag());
}
function testContentIsTextOnly() {
$label = &new SimpleLabelTag(array());
$label->addContent('Here <tag>are</tag> words');
$this->assertEqual($label->getText(), 'Here are words');
}
}
?>

55
vendors/simpletest/test/test_groups.php vendored Normal file
View file

@ -0,0 +1,55 @@
<?php
// $Id: test_groups.php,v 1.4 2005/06/14 15:20:12 tswicegood Exp $
require_once(dirname(__FILE__) . '/../unit_tester.php');
require_once(dirname(__FILE__) . '/../shell_tester.php');
require_once(dirname(__FILE__) . '/../mock_objects.php');
require_once(dirname(__FILE__) . '/../web_tester.php');
require_once(dirname(__FILE__) . '/../extensions/pear_test_case.php');
require_once(dirname(__FILE__) . '/../extensions/phpunit_test_case.php');
class UnitTests extends GroupTest {
function UnitTests() {
$this->GroupTest('Unit tests');
$test_path = dirname(__FILE__);
$this->addTestFile($test_path . '/errors_test.php');
$this->addTestFile($test_path . '/options_test.php');
$this->addTestFile($test_path . '/dumper_test.php');
$this->addTestFile($test_path . '/expectation_test.php');
$this->addTestFile($test_path . '/unit_tester_test.php');
$this->addTestFile($test_path . '/collector_test.php');
$this->addTestFile($test_path . '/simple_mock_test.php');
$this->addTestFile($test_path . '/adapter_test.php');
$this->addTestFile($test_path . '/socket_test.php');
$this->addTestFile($test_path . '/encoding_test.php');
$this->addTestFile($test_path . '/url_test.php');
$this->addTestFile($test_path . '/http_test.php');
$this->addTestFile($test_path . '/authentication_test.php');
$this->addTestFile($test_path . '/user_agent_test.php');
$this->addTestFile($test_path . '/parser_test.php');
$this->addTestFile($test_path . '/tag_test.php');
$this->addTestFile($test_path . '/form_test.php');
$this->addTestFile($test_path . '/page_test.php');
$this->addTestFile($test_path . '/frames_test.php');
$this->addTestFile($test_path . '/browser_test.php');
$this->addTestFile($test_path . '/web_tester_test.php');
$this->addTestFile($test_path . '/shell_tester_test.php');
$this->addTestFile($test_path . '/xml_test.php');
}
}
// Uncomment and modify the following line if you are accessing
// the net via a proxy server.
//
// SimpleTestOptions::useProxy('http://my-proxy', 'optional username', 'optional password');
class AllTests extends GroupTest {
function AllTests() {
$this->GroupTest('All tests for SimpleTest ' . SimpleTestOptions::getVersion());
$this->addTestCase(new UnitTests());
$this->addTestFile(dirname(__FILE__) . '/shell_test.php');
$this->addTestFile(dirname(__FILE__) . '/live_test.php');
$this->addTestFile(dirname(__FILE__) . '/acceptance_test.php');
$this->addTestFile(dirname(__FILE__) . '/real_sites_test.php');
}
}
?>

View file

@ -1,6 +1,9 @@
<?php
// $Id$
class ReferenceForTesting {
}
class TestOfUnitTester extends UnitTestCase {
function testAssertTrueReturnsAssertionAsBoolean() {
@ -23,6 +26,30 @@
$this->assertIsA($this, 'UnitTestCase');
$this->assertNotA($this, 'WebTestCase');
}
function testReferenceAssertionOnObjects() {
$a = &new ReferenceForTesting();
$b = &$a;
$this->assertReference($a, $b);
}
function testReferenceAssertionOnScalars() {
$a = 25;
$b = &$a;
$this->assertReference($a, $b);
}
function testCloneOnObjects() {
$a = &new ReferenceForTesting();
$b = &new ReferenceForTesting();
$this->assertCopy($a, $b);
}
function testCloneOnScalars() {
$a = 25;
$b = 25;
$this->assertCopy($a, $b);
}
}
class JBehaveStyleRunner extends SimpleRunner {
@ -38,7 +65,8 @@
class TestOfJBehaveStyleRunner extends UnitTestCase {
function &_createRunner(&$reporter) {
return new JBehaveStyleRunner($this, $reporter);
$runner = &new JBehaveStyleRunner($this, $reporter);
return $runner;
}
function testFail() {

View file

@ -3,41 +3,8 @@
if (! defined('TEST')) {
define('TEST', __FILE__);
}
require_once('../unit_tester.php');
require_once('../web_tester.php');
require_once('../shell_tester.php');
require_once('../reporter.php');
require_once('../mock_objects.php');
require_once('../extensions/pear_test_case.php');
require_once('../extensions/phpunit_test_case.php');
class UnitTests extends GroupTest {
function UnitTests() {
$this->GroupTest('Unit tests');
$this->addTestFile('errors_test.php');
$this->addTestFile('options_test.php');
$this->addTestFile('dumper_test.php');
$this->addTestFile('expectation_test.php');
$this->addTestFile('unit_tester_test.php');
$this->addTestFile('simple_mock_test.php');
$this->addTestFile('adapter_test.php');
$this->addTestFile('socket_test.php');
$this->addTestFile('encoding_test.php');
$this->addTestFile('url_test.php');
$this->addTestFile('http_test.php');
$this->addTestFile('authentication_test.php');
$this->addTestFile('user_agent_test.php');
$this->addTestFile('parser_test.php');
$this->addTestFile('tag_test.php');
$this->addTestFile('form_test.php');
$this->addTestFile('page_test.php');
$this->addTestFile('frames_test.php');
$this->addTestFile('browser_test.php');
$this->addTestFile('web_tester_test.php');
$this->addTestFile('shell_tester_test.php');
$this->addTestFile('xml_test.php');
}
}
require_once(dirname(__FILE__) . '/test_groups.php');
require_once(dirname(__FILE__) . '/../reporter.php');
if (TEST == __FILE__) {
$test = &new UnitTests();

View file

@ -31,39 +31,49 @@
function testParseBareParameter() {
$url = new SimpleUrl('?a');
$this->assertEqual($url->getPath(), '');
$this->assertEqual($url->getEncodedRequest(), '?a=');
$this->assertEqual($url->getEncodedRequest(), '?a');
$url->addRequestParameter('x', 'X');
$this->assertEqual($url->getEncodedRequest(), '?a=&x=X');
}
function testParseEmptyParameter() {
$url = new SimpleUrl('?a=');
$this->assertEqual($url->getPath(), '');
$this->assertEqual($url->getEncodedRequest(), '?a=');
$url->addRequestParameter('x', 'X');
$this->assertEqual($url->getEncodedRequest(), '?a=&x=X');
}
function testParseParameterPair() {
$url = new SimpleUrl('?a=A');
$this->assertEqual($url->getPath(), '');
$this->assertEqual($url->getEncodedRequest(), '?a=A');
$url->addRequestParameter('x', 'X');
$this->assertEqual($url->getEncodedRequest(), '?a=A&x=X');
}
function testParseMultipleParameters() {
$url = new SimpleUrl('?a=A&b=B');
$this->assertEqual($url->getEncodedRequest(), '?a=A&b=B');
$url->addRequestParameter('x', 'X');
$this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&x=X');
}
function testParsingParameterMixture() {
$url = new SimpleUrl('?a=A&b=&c');
$this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c=');
$this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c');
$url->addRequestParameter('x', 'X');
$this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c=&x=X');
}
function testAddParameters() {
function testAddParametersFromScratch() {
$url = new SimpleUrl('');
$url->addRequestParameter('a', 'A');
$this->assertEqual($url->getEncodedRequest(), '?a=A');
$url->addRequestParameter('b', 'B');
$this->assertEqual($url->getEncodedRequest(), '?a=A&b=B');
$url->addRequestParameter('a', 'aaa');
$this->assertEqual($url->getEncodedRequest(), '?a=A&a=aaa&b=B');
$this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&a=aaa');
}
function testClearingParameters() {
@ -93,14 +103,13 @@
$url->setCoordinates('32', '45');
$this->assertIdentical($url->getX(), 32);
$this->assertIdentical($url->getY(), 45);
$this->assertEqual($url->getEncodedRequest(), '?32,45');
$this->assertEqual($url->getEncodedRequest(), '');
}
function testParseCordinates() {
$url = new SimpleUrl('?32,45');
$this->assertIdentical($url->getX(), 32);
$this->assertIdentical($url->getY(), 45);
$this->assertEqual($url->getEncodedRequest(), '?32,45');
}
function testClearingCordinates() {
@ -114,14 +123,14 @@
$url = new SimpleUrl('?a=A&b=&c?32,45');
$this->assertIdentical($url->getX(), 32);
$this->assertIdentical($url->getY(), 45);
$this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c=?32,45');
$this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c');
}
function testParsingParameterWithBadCordinates() {
$url = new SimpleUrl('?a=A&b=&c?32');
$this->assertIdentical($url->getX(), false);
$this->assertIdentical($url->getY(), false);
$this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c?32=');
$this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c?32');
}
function testPageSplitting() {
@ -169,7 +178,7 @@
array("a" => "1"));
$this->assertUrl(
"username:password@somewhere.com:243?1,2",
array(false, "username", "password", "somewhere.com", 243, "/", "com", "?1,2", false),
array(false, "username", "password", "somewhere.com", 243, "/", "com", "", false),
array(),
array(1, 2));
$this->assertUrl(
@ -180,7 +189,7 @@
array(false, "username", false, "www.somewhere.com", 243, "/", "com", "", "anchor"));
$this->assertUrl(
"/this/that/here.php?a=1&b=2?3,4",
array(false, false, false, false, false, "/this/that/here.php", false, "?a=1&b=2?3,4", false),
array(false, false, false, false, false, "/this/that/here.php", false, "?a=1&b=2", false),
array("a" => "1", "b" => "2"),
array(3, 4));
$this->assertUrl(
@ -220,6 +229,7 @@
$this->assertPreserved('http://host?a=1&a=2');
$this->assertPreserved('http://host#stuff');
$this->assertPreserved('http://me:secret@www.here.com/a/b/c/here.html?a=A?7,6');
$this->assertPreserved('http://www.here.com/?a=A__b=B');
}
function assertUrl($raw, $parts, $params = false, $coords = false) {
@ -242,6 +252,11 @@
}
}
function testUrlWithTwoSlashesInPath() {
$url = new SimpleUrl('/article/categoryedit/insert//');
$this->assertEqual($url->getPath(), '/article/categoryedit/insert//');
}
function assertPreserved($string) {
$url = new SimpleUrl($string);
$this->assertEqual($url->asString(), $string);
@ -285,7 +300,7 @@
$this->assertEqual($absolute->getScheme(), 'http');
$this->assertEqual($absolute->getHost(), 'host.com');
$this->assertEqual($absolute->getPath(), '/I/am/here/');
$this->assertEqual($absolute->getEncodedRequest(), '?a=');
$this->assertEqual($absolute->getEncodedRequest(), '?a');
$this->assertEqual($absolute->getFragment(), 'b');
}
@ -311,6 +326,14 @@
$this->assertEqual($absolute->getPath(), '/here.html');
}
function testCarryAuthenticationFromRootPage() {
$url = new SimpleUrl('here.html');
$absolute = $url->makeAbsolute('http://test:secret@host.com/');
$this->assertEqual($absolute->getPath(), '/here.html');
$this->assertEqual($absolute->getUsername(), 'test');
$this->assertEqual($absolute->getPassword(), 'secret');
}
function testMakingCoordinateUrlAbsolute() {
$url = new SimpleUrl('?1,2');
$this->assertEqual($url->getPath(), '');
@ -347,6 +370,14 @@
$this->assertEqual($absolute->getFragment(), 'f');
}
function testMakingAbsoluteCarriesAuthenticationWhenAlreadyAbsolute() {
$url = new SimpleUrl('https://www.lastcraft.com');
$absolute = $url->makeAbsolute('http://test:secret@host.com/here/');
$this->assertEqual($absolute->getHost(), 'www.lastcraft.com');
$this->assertEqual($absolute->getUsername(), 'test');
$this->assertEqual($absolute->getPassword(), 'secret');
}
function testMakingHostOnlyAbsoluteDoesNotCarryAnyOtherInformation() {
$url = new SimpleUrl('http://www.lastcraft.com');
$absolute = $url->makeAbsolute('https://host.com:81/here/');

View file

@ -148,18 +148,17 @@
$request = &new MockSimpleHttpRequest($this);
$request->setReturnReference('fetch', $response);
$url = new SimpleUrl('http://test:secret@this.com/page.html');
$url->addRequestParameters(array('a' => 'A', 'b' => 'B'));
$agent = &new MockRequestUserAgent($this);
$agent->setReturnReference('_createHttpRequest', $request);
$agent->expectOnce('_createHttpRequest', array(
'GET',
new SimpleUrl('http://test:secret@this.com/page.html?a=A&b=B'),
new SimpleFormEncoding()));
$agent->expectOnce('_createHttpRequest', array($url, new SimpleGetEncoding()));
$agent->SimpleUserAgent();
$agent->fetchResponse(
'GET',
new SimpleUrl('http://test:secret@this.com/page.html'),
new SimpleFormEncoding(array('a' => 'A', 'b' => 'B')));
new SimpleGetEncoding(array('a' => 'A', 'b' => 'B')));
$agent->tally();
}
@ -176,21 +175,17 @@
$request = &new MockSimpleHttpRequest($this);
$request->setReturnReference('fetch', $response);
$url = new SimpleUrl('http://this.com/page.html');
$url = new SimpleUrl('http://test:secret@this.com/page.html');
$url->addRequestParameters(array('a' => 'A', 'b' => 'B'));
$agent = &new MockRequestUserAgent($this);
$agent->setReturnReference('_createHttpRequest', $request);
$agent->expectOnce('_createHttpRequest', array(
'HEAD',
new SimpleUrl('http://test:secret@this.com/page.html?a=A&b=B'),
new SimpleFormEncoding()));
$agent->expectOnce('_createHttpRequest', array($url, new SimpleHeadEncoding()));
$agent->SimpleUserAgent();
$agent->fetchResponse(
'HEAD',
new SimpleUrl('http://test:secret@this.com/page.html'),
new SimpleFormEncoding(array('a' => 'A', 'b' => 'B')));
new SimpleHeadEncoding(array('a' => 'A', 'b' => 'B')));
$agent->tally();
}
@ -207,18 +202,18 @@
$request = &new MockSimpleHttpRequest($this);
$request->setReturnReference('fetch', $response);
$encoding = new SimplePostEncoding(array('a' => 'A', 'b' => 'B'));
$agent = &new MockRequestUserAgent($this);
$agent->setReturnReference('_createHttpRequest', $request);
$agent->expectOnce('_createHttpRequest', array(
'POST',
new SimpleUrl('http://test:secret@this.com/page.html'),
new SimpleFormEncoding(array('a' => 'A', 'b' => 'B'))));
$encoding));
$agent->SimpleUserAgent();
$agent->fetchResponse(
'POST',
new SimpleUrl('http://test:secret@this.com/page.html'),
new SimpleFormEncoding(array('a' => 'A', 'b' => 'B')));
$encoding);
$agent->tally();
}
}
@ -243,7 +238,7 @@
$agent->SimpleUserAgent();
$agent->addHeader('User-Agent: SimpleTest');
$response = &$agent->fetchResponse('GET', new SimpleUrl('http://this.host/'));
$response = &$agent->fetchResponse(new SimpleUrl('http://this.host/'), new SimpleGetEncoding());
$request->tally();
}
}
@ -290,9 +285,8 @@
$agent = &$this->_createPartialFetcher($request);
$agent->setCookie('a', 'A');
$response = $agent->fetchResponse(
'GET',
new SimpleUrl('http://this.com/this/path/page.html'),
array());
new SimpleGetEncoding());
$this->assertEqual($response->getContent(), "stuff");
$request->tally();
}
@ -303,9 +297,8 @@
$agent->setCookie("a", "A");
$agent->fetchResponse(
"GET",
new SimpleUrl('http://this.com/this/path/page.html'),
array());
new SimpleGetEncoding());
$this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA");
}
@ -316,9 +309,8 @@
$agent->setCookie("a", "A", "this/path/", "Wed, 25-Dec-02 04:24:21 GMT");
$agent->fetchResponse(
'GET',
new SimpleUrl('http://this.com/this/path/page.html'),
array());
new SimpleGetEncoding());
$this->assertIdentical(
$agent->getCookieValue("this.com", "this/path/", "a"),
"b");
@ -334,9 +326,8 @@
$agent = &$this->_createPartialFetcher($request);
$agent->fetchResponse(
'GET',
new SimpleUrl('http://this.com/this/path/page.html'),
array());
new SimpleGetEncoding());
$agent->restart("Wed, 25-Dec-02 04:24:20 GMT");
$this->assertIdentical(
$agent->getCookieValue("this.com", "this/path/", "a"),
@ -355,9 +346,8 @@
$this->assertNull($agent->getBaseCookieValue("a", false));
$agent->fetchResponse(
'GET',
new SimpleUrl('http://this.com/this/path/page.html'),
array());
new SimpleGetEncoding());
$agent->setCookie("b", "BBB", "this.com", "this/path/");
$this->assertEqual(
$agent->getBaseCookieValue("a", new SimpleUrl('http://this.com/this/path/page.html')),
@ -395,7 +385,7 @@
$agent->SimpleUserAgent();
$agent->setMaximumRedirects(0);
$response = &$agent->fetchResponse('GET', new SimpleUrl('here.html'));
$response = &$agent->fetchResponse(new SimpleUrl('here.html'), new SimpleGetEncoding());
$this->assertEqual($response->getContent(), 'stuff');
$agent->tally();
@ -415,7 +405,7 @@
$agent->SimpleUserAgent();
$agent->setMaximumRedirects(1);
$response = &$agent->fetchResponse('GET', new SimpleUrl('one.html'));
$response = &$agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding());
$this->assertEqual($response->getContent(), 'second');
$agent->tally();
@ -439,7 +429,7 @@
$agent->SimpleUserAgent();
$agent->setMaximumRedirects(2);
$response = &$agent->fetchResponse('GET', new SimpleUrl('one.html'));
$response = &$agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding());
$this->assertEqual($response->getContent(), 'third');
$agent->tally();
@ -463,7 +453,7 @@
$agent->SimpleUserAgent();
$agent->setMaximumRedirects(2);
$response = &$agent->fetchResponse('GET', new SimpleUrl('one.html'));
$response = &$agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding());
$this->assertEqual($response->getContent(), 'second');
$agent->tally();
@ -475,17 +465,17 @@
0,
'_createHttpRequest',
$this->createRedirect('first', 'two.html'));
$agent->expectArgumentsAt(0, '_createHttpRequest', array('POST', '*', '*'));
$agent->expectArgumentsAt(0, '_createHttpRequest', array('*', new IsAExpectation('SimplePostEncoding')));
$agent->setReturnReferenceAt(
1,
'_createHttpRequest',
$this->createRedirect('second', 'three.html'));
$agent->expectArgumentsAt(1, '_createHttpRequest', array('GET', '*', '*'));
$agent->expectArgumentsAt(1, '_createHttpRequest', array('*', new IsAExpectation('SimpleGetEncoding')));
$agent->expectCallCount('_createHttpRequest', 2);
$agent->SimpleUserAgent();
$agent->setMaximumRedirects(1);
$response = &$agent->fetchResponse('POST', new SimpleUrl('one.html'));
$response = &$agent->fetchResponse(new SimpleUrl('one.html'), new SimplePostEncoding());
$agent->tally();
}
@ -512,8 +502,8 @@
$agent->SimpleUserAgent();
$response = &$agent->fetchResponse(
'GET',
new SimpleUrl('http://this.host/this/path/page.html'));
new SimpleUrl('http://this.host/this/path/page.html'),
new SimpleGetEncoding());
$this->assertTrue($response->isError());
}
}
@ -538,8 +528,8 @@
$agent->SimpleUserAgent();
$response = &$agent->fetchResponse(
'GET',
new SimpleUrl('http://test:secret@this.host'));
new SimpleUrl('http://test:secret@this.host'),
new SimpleGetEncoding());
$request->tally();
}
}

View file

@ -44,8 +44,8 @@
function testExpectation() {
$expectation = &new EqualExpectation(25, 'My expectation message: %s');
$this->assertExpectation($expectation, 25, 'My assert message : %s');
$this->assertExpectation($expectation, 24, 'My assert message : %s'); // Fail.
$this->assert($expectation, 25, 'My assert message : %s');
$this->assert($expectation, 24, 'My assert message : %s'); // Fail.
}
function testNull() {
@ -93,6 +93,16 @@
$this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "Z"), "%s -> Pass");
}
function testWithin() {
$this->assertWithinMargin(5, 5.4, 0.5, "%s -> Pass");
$this->assertWithinMargin(5, 5.6, 0.5, "%s -> Fail"); // Fail.
}
function testOutside() {
$this->assertOutsideMargin(5, 5.4, 0.5, "%s -> Fail"); // Fail.
$this->assertOutsideMargin(5, 5.6, 0.5, "%s -> Pass");
}
function testStringIdentity() {
$a = "fred";
$b = $a;
@ -143,10 +153,10 @@
}
function testPatterns() {
$this->assertWantedPattern('/hello/i', "Hello there", "%s -> Pass");
$this->assertNoUnwantedPattern('/hello/', "Hello there", "%s -> Pass");
$this->assertWantedPattern('/hello/', "Hello there", "%s -> Fail"); // Fail.
$this->assertNoUnwantedPattern('/hello/i', "Hello there", "%s -> Fail"); // Fail.
$this->assertPattern('/hello/i', "Hello there", "%s -> Pass");
$this->assertNoPattern('/hello/', "Hello there", "%s -> Pass");
$this->assertPattern('/hello/', "Hello there", "%s -> Fail"); // Fail.
$this->assertNoPattern('/hello/i', "Hello there", "%s -> Fail"); // Fail.
}
function testLongStrings() {
@ -366,7 +376,7 @@
}
}
$test = &new GroupTest("Visual test with 49 passes, 49 fails and 4 exceptions");
$test = &new GroupTest("Visual test with 51 passes, 51 fails and 4 exceptions");
$test->addTestCase(new TestOfUnitTestCaseOutput());
$test->addTestCase(new TestOfMockObjectsOutput());
$test->addTestCase(new TestOfPastBugs());

View file

@ -65,6 +65,14 @@
$this->assertIdentical($expectation->test(' a : AB '), false);
}
function testHeaderValueWithColons() {
$expectation = new HttpHeaderExpectation('a', 'A:B:C');
$this->assertIdentical($expectation->test('a: A'), false);
$this->assertIdentical($expectation->test('a: A:B'), false);
$this->assertIdentical($expectation->test('a: A:B:C'), true);
$this->assertIdentical($expectation->test('a: A:B:C:D'), false);
}
function testMultilineSearch() {
$expectation = new HttpHeaderExpectation('a', 'A');
$this->assertIdentical($expectation->test("aa: A\r\nb: B\r\nc: C"), false);
@ -130,4 +138,12 @@
$this->assertIdentical($expectation->test('the wanted text is here'), false);
}
}
class TestOfGenericAssertionsInWebTester extends WebTestCase {
function testEquality() {
$this->assertEqual('a', 'a');
$this->assertNotEqual('a', 'A');
}
}
?>

View file

@ -78,7 +78,7 @@
* @access public
*/
function assertIsA($object, $type, $message = "%s") {
return $this->assertExpectation(
return $this->assert(
new IsAExpectation($type),
$object,
$message);
@ -95,7 +95,7 @@
* @access public
*/
function assertNotA($object, $type, $message = "%s") {
return $this->assertExpectation(
return $this->assert(
new NotAExpectation($type),
$object,
$message);
@ -111,7 +111,7 @@
* @access public
*/
function assertEqual($first, $second, $message = "%s") {
return $this->assertExpectation(
return $this->assert(
new EqualExpectation($first),
$second,
$message);
@ -127,12 +127,46 @@
* @access public
*/
function assertNotEqual($first, $second, $message = "%s") {
return $this->assertExpectation(
return $this->assert(
new NotEqualExpectation($first),
$second,
$message);
}
/**
* Will trigger a pass if the if the first parameter
* is near enough to the second by the margin.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param mixed $margin Fuzziness of match.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertWithinMargin($first, $second, $margin, $message = "%s") {
return $this->assert(
new WithinMarginExpectation($first, $margin),
$second,
$message);
}
/**
* Will trigger a pass if the two parameters differ
* by more than the margin.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param mixed $margin Fuzziness of match.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertOutsideMargin($first, $second, $margin, $message = "%s") {
return $this->assert(
new OutsideMarginExpectation($first, $margin),
$second,
$message);
}
/**
* Will trigger a pass if the two parameters have
* the same value and same type. Otherwise a fail.
@ -143,7 +177,7 @@
* @access public
*/
function assertIdentical($first, $second, $message = "%s") {
return $this->assertExpectation(
return $this->assert(
new IdenticalExpectation($first),
$second,
$message);
@ -159,7 +193,7 @@
* @access public
*/
function assertNotIdentical($first, $second, $message = "%s") {
return $this->assertExpectation(
return $this->assert(
new NotIdenticalExpectation($first),
$second,
$message);
@ -217,13 +251,20 @@
* @return boolean True on pass
* @access public
*/
function assertWantedPattern($pattern, $subject, $message = "%s") {
return $this->assertExpectation(
new WantedPatternExpectation($pattern),
function assertPattern($pattern, $subject, $message = "%s") {
return $this->assert(
new PatternExpectation($pattern),
$subject,
$message);
}
/**
* @deprecated
*/
function assertWantedPattern($pattern, $subject, $message = "%s") {
return $this->assertPattern($pattern, $subject, $message);
}
/**
* Will trigger a pass if the perl regex pattern
* is not present in subject. Fail if found.
@ -234,13 +275,20 @@
* @return boolean True on pass
* @access public
*/
function assertNoUnwantedPattern($pattern, $subject, $message = "%s") {
return $this->assertExpectation(
new UnwantedPatternExpectation($pattern),
function assertNoPattern($pattern, $subject, $message = "%s") {
return $this->assert(
new NoPatternExpectation($pattern),
$subject,
$message);
}
/**
* @deprecated
*/
function assertNoUnwantedPattern($pattern, $subject, $message = "%s") {
return $this->assertNoPattern($pattern, $subject, $message);
}
/**
* Confirms that no errors have occoured so
* far in the test method.
@ -272,32 +320,37 @@
}
list($severity, $content, $file, $line, $globals) = $queue->extract();
$severity = SimpleErrorQueue::getSeverityAsString($severity);
return $this->assertTrue(
! $expected || ($expected == $content),
"Expected [$expected] in PHP error [$content] severity [$severity] in [$file] line [$line]");
if (! $expected) {
return $this->pass(
"Captured a PHP error of [$content] severity [$severity] in [$file] line [$line] -> %s");
}
$expected = $this->_coerceToExpectation($expected);
return $this->assert(
$expected,
$content,
"Expected PHP error [$content] severity [$severity] in [$file] line [$line] -> %s");
}
/**
* Confirms that an error has occoured and
* that the error text matches a Perl regular
* expression.
* @param string $pattern Perl regular expresion to
* match against.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
* Creates an equality expectation if the
* object/value is not already some type
* of expectation.
* @param mixed $expected Expected value.
* @return SimpleExpectation Expectation object.
* @access private
*/
function _coerceToExpectation($expected) {
if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) {
return $expected;
}
return new EqualExpectation($expected);
}
/**
* @deprecated
*/
function assertErrorPattern($pattern, $message = "%s") {
$queue = &SimpleErrorQueue::instance();
if ($queue->isEmpty()) {
$this->fail(sprintf($message, "Expected error not found"));
return;
}
list($severity, $content, $file, $line, $globals) = $queue->extract();
$severity = SimpleErrorQueue::getSeverityAsString($severity);
return $this->assertTrue(
(boolean)preg_match($pattern, $content),
"Expected pattern match [$pattern] in PHP error [$content] severity [$severity] in [$file] line [$line]");
return $this->assertError(new PatternExpectation($pattern), $message);
}
}
?>

View file

@ -17,7 +17,8 @@
* got broken in PHP 4.3.0. Adds some browser specific
* functionality such as expandomatics.
* Guesses a bit trying to separate the host from
* the path.
* the path and tries to keep a raw, possibly unparsable,
* request string as long as possible.
* @package SimpleTest
* @subpackage WebTester
*/
@ -30,7 +31,10 @@
var $_path;
var $_request;
var $_fragment;
var $_x;
var $_y;
var $_target;
var $_raw = false;
/**
* Constructor. Parses URL into sections.
@ -39,6 +43,7 @@
*/
function SimpleUrl($url) {
list($x, $y) = $this->_chompCoordinates($url);
$this->setCoordinates($x, $y);
$this->_scheme = $this->_chompScheme($url);
list($this->_username, $this->_password) = $this->_chompLogin($url);
$this->_host = $this->_chompHost($url);
@ -49,7 +54,6 @@
}
$this->_path = $this->_chompPath($url);
$this->_request = $this->_parseRequest($this->_chompRequest($url));
$this->_request->setCoordinates($x, $y);
$this->_fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false);
$this->_target = false;
}
@ -96,7 +100,7 @@
*/
function _chompLogin(&$url) {
$prefix = '';
if (preg_match('/(\/\/)(.*)/', $url, $matches)) {
if (preg_match('/^(\/\/)(.*)/', $url, $matches)) {
$prefix = $matches[1];
$url = $matches[2];
}
@ -123,7 +127,7 @@
* @access private
*/
function _chompHost(&$url) {
if (preg_match('/(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) {
if (preg_match('/^(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) {
$url = $matches[3];
return $matches[2];
}
@ -178,7 +182,8 @@
* @access private
*/
function _parseRequest($raw) {
$request = new SimpleFormEncoding();
$this->_raw = $raw;
$request = new SimpleGetEncoding();
foreach (split("&", $raw) as $pair) {
if (preg_match('/(.*?)=(.*)/', $pair, $matches)) {
$request->add($matches[1], urldecode($matches[2]));
@ -292,13 +297,29 @@
return $this->_fragment;
}
/**
* Sets image coordinates. Set to false to clear
* them.
* @param integer $x Horizontal position.
* @param integer $y Vertical position.
* @access public
*/
function setCoordinates($x = false, $y = false) {
if (($x === false) || ($y === false)) {
$this->_x = $this->_y = false;
return;
}
$this->_x = (integer)$x;
$this->_y = (integer)$y;
}
/**
* Accessor for horizontal image coordinate.
* @return integer X value.
* @access public
*/
function getX() {
return $this->_request->getX();
return $this->_x;
}
/**
@ -307,17 +328,23 @@
* @access public
*/
function getY() {
return $this->_request->getY();
return $this->_y;
}
/**
* Accessor for current request parameters
* in URL string form
* in URL string form. Will return teh original request
* if at all possible even if it doesn't make much
* sense.
* @return string Form is string "?a=1&b=2", etc.
* @access public
*/
function getEncodedRequest() {
$encoded = $this->_request->asString();
if ($this->_raw) {
$encoded = $this->_raw;
} else {
$encoded = $this->_request->asUrlRequest();
}
if ($encoded) {
return '?' . preg_replace('/^\?/', '', $encoded);
}
@ -331,6 +358,7 @@
* @access public
*/
function addRequestParameter($key, $value) {
$this->_raw = false;
$this->_request->add($key, $value);
}
@ -341,6 +369,7 @@
* @access public
*/
function addRequestParameters($parameters) {
$this->_raw = false;
$this->_request->merge($parameters);
}
@ -349,18 +378,8 @@
* @access public
*/
function clearRequest() {
$this->_request = &new SimpleFormEncoding();
}
/**
* Sets image coordinates. Set to flase to clear
* them.
* @param integer $x Horizontal position.
* @param integer $y Vertical position.
* @access public
*/
function setCoordinates($x = false, $y = false) {
$this->_request->setCoordinates($x, $y);
$this->_raw = false;
$this->_request = &new SimpleGetEncoding();
}
/**
@ -380,6 +399,7 @@
* @access public
*/
function setTarget($frame) {
$this->_raw = false;
$this->_target = $frame;
}
@ -402,7 +422,8 @@
}
$encoded = $this->getEncodedRequest();
$fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
return "$scheme://$identity$host$path$encoded$fragment";
$coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
return "$scheme://$identity$host$path$encoded$fragment$coords";
}
/**
@ -417,27 +438,23 @@
$base = new SimpleUrl($base);
}
$scheme = $this->getScheme() ? $this->getScheme() : $base->getScheme();
$host = $this->getHost() ? $this->getHost() : $base->getHost();
$port = $this->_extractAbsolutePort($base);
if ($this->getHost()) {
$host = $this->getHost();
$port = $this->getPort() ? ':' . $this->getPort() : '';
$identity = $this->getIdentity() ? $this->getIdentity() . '@' : '';
if (! $identity) {
$identity = $base->getIdentity() ? $base->getIdentity() . '@' : '';
}
} else {
$host = $base->getHost();
$port = $base->getPort() ? ':' . $base->getPort() : '';
$identity = $base->getIdentity() ? $base->getIdentity() . '@' : '';
}
$path = $this->normalisePath($this->_extractAbsolutePath($base));
$identity = $this->_getIdentity() ? $this->_getIdentity() . '@' : '';
$encoded = $this->getEncodedRequest();
$fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment");
}
/**
* Extracts the port from the base URL if it's needed, but
* not present, in the current URL.
* @param string/SimpleUrl $base Base URL.
* @param string Absolute port number.
* @access private
*/
function _extractAbsolutePort($base) {
if ($this->getHost()) {
return ($this->getPort() ? ':' . $this->getPort() : '');
}
return ($base->getPort() ? ':' . $base->getPort() : '');
$coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords");
}
/**
@ -474,9 +491,9 @@
* Extracts the username and password for use in rendering
* a URL.
* @return string/boolean Form of username:password@ or false.
* @access private
* @access public
*/
function _getIdentity() {
function getIdentity() {
if ($this->_username && $this->_password) {
return $this->_username . ':' . $this->_password;
}

View file

@ -14,8 +14,13 @@
require_once(dirname(__FILE__) . '/authentication.php');
/**#@-*/
if (!defined('DEFAULT_MAX_REDIRECTS')) {
define('DEFAULT_MAX_REDIRECTS', 3);
}
if (!defined('DEFAULT_CONNECTION_TIMEOUT')) {
define('DEFAULT_CONNECTION_TIMEOUT', 15);
}
/**
* Repository for cookies. This stuff is a
@ -338,18 +343,17 @@
/**
* Fetches a URL as a response object. Will keep trying if redirected.
* It will also collect authentication realm information.
* @param string $method GET, POST, etc.
* @param string/SimpleUrl $url Target to fetch.
* @param SimpleFormEncoding $parameters Additional parameters for request.
* @param SimpleEncoding $encoding Additional parameters for request.
* @return SimpleHttpResponse Hopefully the target page.
* @access public
*/
function &fetchResponse($method, $url, $parameters = false) {
if ($method != 'POST') {
$url->addRequestParameters($parameters);
$parameters = false;
function &fetchResponse($url, $encoding) {
if ($encoding->getMethod() != 'POST') {
$url->addRequestParameters($encoding);
$encoding->clear();
}
$response = &$this->_fetchWhileRedirected($method, $url, $parameters);
$response = &$this->_fetchWhileRedirected($url, $encoding);
if ($headers = $response->getHeaders()) {
if ($headers->isChallenge()) {
$this->_authenticator->addRealm(
@ -364,16 +368,15 @@
/**
* Fetches the page until no longer redirected or
* until the redirect limit runs out.
* @param string $method GET, POST, etc.
* @param SimpleUrl $url Target to fetch.
* @param SimpelFormEncoding $parameters Additional parameters for request.
* @param SimpelFormEncoding $encoding Additional parameters for request.
* @return SimpleHttpResponse Hopefully the target page.
* @access private
*/
function &_fetchWhileRedirected($method, $url, $parameters) {
function &_fetchWhileRedirected($url, $encoding) {
$redirects = 0;
do {
$response = &$this->_fetch($method, $url, $parameters);
$response = &$this->_fetch($url, $encoding);
if ($response->isError()) {
return $response;
}
@ -384,38 +387,33 @@
if (! $headers->isRedirect()) {
break;
}
$method = 'GET';
$parameters = false;
$encoding = new SimpleGetEncoding();
} while (! $this->_isTooManyRedirects(++$redirects));
return $response;
}
/**
* Actually make the web request.
* @param string $method GET, POST, etc.
* @param SimpleUrl $url Target to fetch.
* @param SimpleFormEncoding $parameters Additional parameters for request.
* @param SimpleFormEncoding $encoding Additional parameters for request.
* @return SimpleHttpResponse Headers and hopefully content.
* @access protected
*/
function &_fetch($method, $url, $parameters) {
if (! $parameters) {
$parameters = new SimpleFormEncoding();
}
$request = &$this->_createRequest($method, $url, $parameters);
return $request->fetch($this->_connection_timeout);
function &_fetch($url, $encoding) {
$request = &$this->_createRequest($url, $encoding);
$response = &$request->fetch($this->_connection_timeout);
return $response;
}
/**
* Creates a full page request.
* @param string $method Fetching method.
* @param SimpleUrl $url Target to fetch as url object.
* @param SimpleFormEncoding $parameters POST/GET parameters.
* @param SimpleFormEncoding $encoding POST/GET parameters.
* @return SimpleHttpRequest New request.
* @access private
*/
function &_createRequest($method, $url, $parameters) {
$request = &$this->_createHttpRequest($method, $url, $parameters);
function &_createRequest($url, $encoding) {
$request = &$this->_createHttpRequest($url, $encoding);
$this->_addAdditionalHeaders($request);
$this->_cookie_jar->addHeaders($request, $url);
$this->_authenticator->addHeaders($request, $url);
@ -424,25 +422,15 @@
/**
* Builds the appropriate HTTP request object.
* @param string $method Fetching method.
* @param SimpleUrl $url Target to fetch as url object.
* @param SimpleFormEncoding $parameters POST/GET parameters.
* @return SimpleHttpRequest New request object.
* @access protected
*/
function &_createHttpRequest($method, $url, $parameters) {
if ($method == 'POST') {
$request = &new SimpleHttpRequest(
$this->_createRoute($url),
'POST',
$parameters);
function &_createHttpRequest($url, $encoding) {
$request = &new SimpleHttpRequest($this->_createRoute($url), $encoding);
return $request;
}
if ($parameters) {
$url->addRequestParameters($parameters);
}
return new SimpleHttpRequest($this->_createRoute($url), $method);
}
/**
* Sets up either a direct route or via a proxy.
@ -452,13 +440,15 @@
*/
function &_createRoute($url) {
if ($this->_proxy) {
return new SimpleProxyRoute(
$route = &new SimpleProxyRoute(
$url,
$this->_proxy,
$this->_proxy_username,
$this->_proxy_password);
} else {
$route = &new SimpleRoute($url);
}
return new SimpleRoute($url);
return $route;
}
/**

View file

@ -198,7 +198,7 @@
* @access private
*/
function _testHeaderLine($line) {
if (count($parsed = split(':', $line)) < 2) {
if (count($parsed = split(':', $line, 2)) < 2) {
return false;
}
list($header, $value) = $parsed;
@ -495,7 +495,8 @@
* @access public
*/
function &createInvoker() {
return new WebTestCaseInvoker(parent::createInvoker());
$invoker = &new WebTestCaseInvoker(parent::createInvoker());
return $invoker;
}
/**
@ -536,7 +537,8 @@
* @access public
*/
function &createBrowser() {
return new SimpleBrowser();
$browser = &new SimpleBrowser();
return $browser;
}
/**
@ -582,6 +584,14 @@
$this->dump($this->_browser->getContent());
}
/**
* Dumps the visible text only for debugging.
* @access public
*/
function showText() {
$this->dump(wordwrap($this->_browser->getContentAsText(), 80));
}
/**
* Simulates the closing and reopening of the browser.
* Temporary cookies will be discarded and timed
@ -673,15 +683,11 @@
* the base URL reflects the new location.
* @param string $url URL to fetch.
* @param hash $parameters Optional additional GET data.
* @return boolean True on success.
* @return boolean/string Raw page on success.
* @access public
*/
function get($url, $parameters = false) {
$content = $this->_browser->get($url, $parameters);
if ($content === false) {
return false;
}
return true;
return $this->_browser->get($url, $parameters);
}
/**
@ -691,15 +697,11 @@
* the base URL reflects the new location.
* @param string $url URL to fetch.
* @param hash $parameters Optional additional GET data.
* @return boolean True on success.
* @return boolean/string Raw page on success.
* @access public
*/
function post($url, $parameters = false) {
$content = $this->_browser->post($url, $parameters);
if ($content === false) {
return false;
}
return true;
return $this->_browser->post($url, $parameters);
}
/**
@ -824,13 +826,24 @@
return $this->_browser->clearFrameFocus();
}
/**
* Clicks a visible text item. Will first try buttons,
* then links and then images.
* @param string $label Visible text or alt text.
* @return string/boolean Raw page or false.
* @access public
*/
function click($label) {
return $this->_browser->click($label);
}
/**
* Clicks the submit button by label. The owning
* form will be submitted by this.
* @param string $label Button label. An unlabeled
* button can be triggered by 'Submit'.
* @param hash $additional Additional form values.
* @return boolean/string Page on success.
* @return boolean/string Page on success, else false.
* @access public
*/
function clickSubmit($label = 'Submit', $additional = false) {
@ -946,6 +959,40 @@
return $this->_browser->clickLinkById($id);
}
/**
* Will trigger a pass if the two parameters have
* the same value only. Otherwise a fail. This
* is for testing hand extracted text, etc.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertEqual($first, $second, $message = "%s") {
return $this->assert(
new EqualExpectation($first),
$second,
$message);
}
/**
* Will trigger a pass if the two parameters have
* a different value. Otherwise a fail. This
* is for testing hand extracted text, etc.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertNotEqual($first, $second, $message = "%s") {
return $this->assert(
new NotEqualExpectation($first),
$second,
$message);
}
/**
* Tests for the presence of a link label. Match is
* case insensitive with normalised space.
@ -1006,6 +1053,18 @@
sprintf($message, "Link ID [$id] should not exist"));
}
/**
* Sets all form fields with that label, or name if there
* is no label attached.
* @param string $name Name of field in forms.
* @param string $value New value of field.
* @return boolean True if field exists, otherwise false.
* @access public
*/
function setField($label, $value) {
return $this->_browser->setField($label, $value);
}
/**
* Sets all form fields with that name.
* @param string $name Name of field in forms.
@ -1013,8 +1072,8 @@
* @return boolean True if field exists, otherwise false.
* @access public
*/
function setField($name, $value) {
return $this->_browser->setField($name, $value);
function setFieldByName($name, $value) {
return $this->_browser->setFieldByName($name, $value);
}
/**
@ -1041,17 +1100,44 @@
* @return boolean True if pass.
* @access public
*/
function assertField($name, $expected = true, $message = "%s") {
$value = $this->_browser->getField($name);
function assertField($label, $expected = true, $message = "%s") {
$value = $this->_browser->getField($label);
if ($expected === true) {
return $this->assertTrue(
isset($value),
sprintf($message, "Field [$name] should exist"));
sprintf($message, "Field [$label] should exist"));
} else {
return $this->assertExpectation(
return $this->assert(
new FieldExpectation($expected),
$value,
sprintf($message, "Field [$name] should match with [%s]"));
sprintf($message, "Field [$label] should match with [%s]"));
}
}
/**
* Confirms that the form element is currently set
* to the expected value. A missing form element will always
* fail. If no value is given then only the existence
* of the field is checked.
* @param string $name Name of field in forms.
* @param mixed $expected Expected string/array value or
* false for unset fields.
* @param string $message Message to display. Default
* can be embedded with %s.
* @return boolean True if pass.
* @access public
*/
function assertFieldByName($name, $expected = true, $message = "%s") {
$value = $this->_browser->getFieldByName($name);
if ($expected === true) {
return $this->assertTrue(
isset($value),
sprintf($message, "Field name [$name] should exist"));
} else {
return $this->assert(
new FieldExpectation($expected),
$value,
sprintf($message, "Field name [$name] should match with [%s]"));
}
}
@ -1075,7 +1161,7 @@
isset($value),
sprintf($message, "Field of ID [$id] should exist"));
} else {
return $this->assertExpectation(
return $this->assert(
new FieldExpectation($expected),
$value,
sprintf($message, "Field of ID [$id] should match with [%s]"));
@ -1177,7 +1263,7 @@
* @access public
*/
function assertHeader($header, $value = false, $message = '%s') {
return $this->assertExpectation(
return $this->assert(
new HttpHeaderExpectation($header, $value),
$this->_browser->getHeaders(),
$message);
@ -1191,7 +1277,7 @@
* @access public
*/
function assertHeaderPattern($header, $pattern, $message = '%s') {
return $this->assertExpectation(
return $this->assert(
new HttpHeaderPatternExpectation($header, $pattern),
$this->_browser->getHeaders(),
$message);
@ -1207,7 +1293,7 @@
* @access public
*/
function assertNoUnwantedHeader($header, $message = '%s') {
return $this->assertExpectation(
return $this->assert(
new HttpUnwantedHeaderExpectation($header),
$this->_browser->getHeaders(),
$message);
@ -1237,7 +1323,7 @@
* @access public
*/
function assertWantedText($text, $message = '%s') {
return $this->assertExpectation(
return $this->assert(
new WantedTextExpectation($text),
$this->_browser->getContentAsText(),
$message);
@ -1252,7 +1338,7 @@
* @access public
*/
function assertNoUnwantedText($text, $message = '%s') {
return $this->assertExpectation(
return $this->assert(
new UnwantedTextExpectation($text),
$this->_browser->getContentAsText(),
$message);
@ -1267,13 +1353,20 @@
* @return boolean True if pass.
* @access public
*/
function assertWantedPattern($pattern, $message = '%s') {
return $this->assertExpectation(
new WantedPatternExpectation($pattern),
function assertPattern($pattern, $message = '%s') {
return $this->assert(
new PatternExpectation($pattern),
$this->_browser->getContent(),
$message);
}
/**
* @deprecated
*/
function assertWantedPattern($pattern, $message = '%s') {
return $this->assertPattern($pattern, $message);
}
/**
* Will trigger a pass if the perl regex pattern
* is not present in raw content.
@ -1283,13 +1376,20 @@
* @return boolean True if pass.
* @access public
*/
function assertNoUnwantedPattern($pattern, $message = '%s') {
return $this->assertExpectation(
new UnwantedPatternExpectation($pattern),
function assertNoPattern($pattern, $message = '%s') {
return $this->assert(
new NoPatternExpectation($pattern),
$this->_browser->getContent(),
$message);
}
/**
* @deprecated
*/
function assertNoUnwantedPattern($pattern, $message = '%s') {
return $this->assertNoPattern($pattern, $message);
}
/**
* Checks that a cookie is set for the current page
* and optionally checks the value.

View file

@ -530,9 +530,8 @@
* @private
*/
function _isLeaf($tag) {
return in_array(
$tag,
array('NAME', 'PASS', 'FAIL', 'EXCEPTION', 'MESSAGE', 'FORMATTED', 'SIGNAL'));
return in_array($tag, array(
'NAME', 'PASS', 'FAIL', 'EXCEPTION', 'MESSAGE', 'FORMATTED', 'SIGNAL'));
}
/**