Merge branch 'master' of github.com:shish/shimmie2

This commit is contained in:
Shish 2012-03-10 02:21:53 +00:00
commit b34cb84e92
50 changed files with 5376 additions and 4390 deletions

View File

@ -5,13 +5,64 @@ 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 dramatic changes are in the alpha releases. Here is a list of possible
problems and their fixes... problems and their fixes...
assertText() no longer finds a string inside a <script> tag
-----------------------------------------------------------
The assertText() method is intended to match only visible,
human-readable text on the web page. Therefore, the contents of script
tags should not be matched by this assertion. However there was a bug
in the text normalisation code of simpletest which meant that <script>
tags spanning multiple lines would not have their content stripped
out. If you want to check the content of a <script> tag, use
assertPattern(), or write a custom expectation.
Overloaded method not working
-----------------------------
All protected and private methods had underscores
removed. This means that any private/protected methods that
you overloaded with those names need to be updated.
Fatal error: Call to undefined method Classname::classname()
------------------------------------------------------------
SimpleTest renamed all of its constructors from
Classname to __construct; derived classes invoking
their parent constructors should replace parent::Classname()
with parent::__construct().
Custom CSS in HtmlReporter not being applied
--------------------------------------------
Batch rename of protected and private methods
means that _getCss() was renamed to getCss().
Please rename your method and it should work again.
setReturnReference() throws errors in E_STRICT
----------------------------------------------
Happens when an object is passed by reference.
This also happens with setReturnReferenceAt().
If you want to return objects then replace these
with calls to returns() and returnsAt() with the
same arguments. This change was forced in the 1.1
version for E_STRICT compatibility.
assertReference() throws errors in E_STRICT
-------------------------------------------
Due to language restrictions you cannot compare
both variables and objects in E_STRICT mode. Use
assertSame() in this mode with objects. This change
was forced the 1.1 version.
Cannot create GroupTest
-----------------------
The GroupTest has been renamed TestSuite (see below).
It was removed completely in 1.1 in favour of this
name.
No method getRelativeUrls() or getAbsoluteUrls() No method getRelativeUrls() or getAbsoluteUrls()
------------------------------------------------ ------------------------------------------------
These methods were always a bit weird anyway, and These methods were always a bit weird anyway, and
the new parsing of the base tag makes them more so. the new parsing of the base tag makes them more so.
They have been replaced with getUrls() instead. If They have been replaced with getUrls() instead. If
you want the old functionality then simply chop you want the old functionality then simply chop
off the current domain from getUrl(). off the current domain from getUrls().
Method setWildcard() removed in mocks Method setWildcard() removed in mocks
------------------------------------- -------------------------------------
@ -48,7 +99,7 @@ getTransferError() call on the web tester to see if
there was a socket level error in a fetch. This check there was a socket level error in a fetch. This check
is now always carried out by the WebTestCase unless is now always carried out by the WebTestCase unless
the fetch is prefaced with WebTestCase::ignoreErrors(). the fetch is prefaced with WebTestCase::ignoreErrors().
The ignore directive only lasts for test case fetching The ignore directive only lasts for the next fetching
action such as get() and click(). action such as get() and click().
No method SimpleTestOptions::ignore() No method SimpleTestOptions::ignore()

0
contrib/simpletest/simpletest/LICENSE Normal file → Executable file
View File

76
contrib/simpletest/simpletest/README Normal file → Executable file
View File

@ -1,14 +1,16 @@
SimpleTest SimpleTest
========== ==========
You probably got this package from...
http://simpletest.sourceforge.net/projects/simpletest/ You probably got this package from:
http://simpletest.org/en/download.html
If there is no licence agreement with this package please download If there is no licence agreement with this package please download
a version from the location above. You must read and accept that a version from the location above. You must read and accept that
licence to use this software. The file is titled simply LICENSE. licence to use this software. The file is titled simply LICENSE.
What is it? It's a framework for unit testing, web site testing and What is it? It's a framework for unit testing, web site testing and
mock objects for PHP 4.2.0+ (and PHP 5.0 to 5.3 without E_STRICT). mock objects for PHP 5.0.5+.
If you have used JUnit, you will find this PHP unit testing version very If you have used JUnit, you will find this PHP unit testing version very
similar. Also included is a mock objects and server stubs generator. similar. Also included is a mock objects and server stubs generator.
@ -21,48 +23,42 @@ A web tester similar in concept to JWebUnit is also included. There is no
JavaScript or tables support, but forms, authentication, cookies and JavaScript or tables support, but forms, authentication, cookies and
frames are handled. frames are handled.
You can see a release schedule at http://www.lastcraft.com/overview.php You can see a release schedule at http://simpletest.org/en/overview.html
which is also copied to the documentation folder with this release. which is also copied to the documentation folder with this release.
A full PHPDocumenter API documentation exists at A full PHPDocumenter API documentation exists at
http://simpletest.sourceforge.net/. http://simpletest.org/api/.
The user interface is minimal The user interface is minimal in the extreme, but a lot of information
in the extreme, but a lot of information flows from the test suite. flows from the test suite. After version 1.0 we will release a better
After version 1.0 we will release a better web UI, but we are leaving XUL web UI, but we are leaving XUL and GTK versions to volunteers as
and GTk versions to volunteers as everybody has their own opinion everybody has their own opinion on a good GUI, and we don't want to
on a good GUI, and we don't want to discourage development by shipping discourage development by shipping one with the toolkit. You can
one with the toolkit. YOucan download an Eclipse plug-in separately. download an Eclipse plug-in separately.
You are looking at a second full release. The unit tests for SimpleTest The unit tests for SimpleTest itself can be run here:
itself can be run here...
simpletest/test/unit_tests.php test/unit_tests.php
And tests involving live network connections as well are here... And tests involving live network connections as well are here:
simpletest/test/all_tests.php test/all_tests.php
The full tests will typically overrun the 8Mb limit often allowed The full tests will typically overrun the 8Mb limit often allowed
to a PHP process. A workaround is to run the tests on the command to a PHP process. A workaround is to run the tests on the command
with a custom php.ini file if you do not have access to your server with a custom php.ini file or with the switch -dmemory_limit=-1
version. if you do not have access to your server version.
You will have to edit the all_tests.php file if you are accesssing The full tests read some test data from simpletest.org. If the site
the internet through a proxy server. See the comments in all_tests.php
for instructions.
The full tests read some test data from the LastCraft site. If the site
is down or has been modified for a later version then you will get is down or has been modified for a later version then you will get
spurious errors. A unit_tests.php failure on the other hand would be spurious errors. A unit_tests.php failure on the other hand would be
very serious. As far as we know we haven't yet managed to check in any very serious. Please notify us if you find one.
unit test failures, so please correct us if you find one.
Even if all of the tests run please verify that your existing test suites Even if all of the tests run please verify that your existing test suites
also function as expected. If they don't see the file... also function as expected. The file:
HELP_MY_TESTS_DONT_WORK_ANYMORE HELP_MY_TESTS_DONT_WORK_ANYMORE
This contains information on interface changes. It also points out ...contains information on interface changes. It also points out
deprecated interfaces, so you should read this even if all of deprecated interfaces, so you should read this even if all of
your current tests appear to run. your current tests appear to run.
@ -70,19 +66,19 @@ There is a documentation folder which contains the core reference information
in English and French, although this information is fairly basic. in English and French, although this information is fairly basic.
You can find a tutorial on... You can find a tutorial on...
http://www.lastcraft.com/first_test_tutorial.php http://simpletest.org/en/first_test_tutorial.html
...to get you started and this material will eventually become included ...to get you started and this material will eventually become included
with the project documentation. A French translation exists at... with the project documentation. A French translation exists at:
http://www.onpk.net/index.php/2005/01/12/254-tutoriel-simpletest-decouvrir-les-tests-unitaires. http://simpletest.org/fr/first_test_tutorial.html
If you download and use, and possibly even extend this tool, please let us If you download and use, and possibly even extend this tool, please let us
know. Any feedback, even bad, is always welcome and we will work to get know. Any feedback, even bad, is always welcome and we will work to get
your suggestions into the next release. Ideally please send your your suggestions into the next release. Ideally please send your
comments to... comments to:
simpletest-support@lists.sourceforge.net simpletest-support@lists.sourceforge.net
...so that others can read them too. We usually try to respond within 48 ...so that others can read them too. We usually try to respond within 48
hours. hours.
@ -93,16 +89,14 @@ status of any bugs, but if the bug is recent then it will be fixed in SVN only.
The SVN check-ins always have all the tests passing and so SVN snapshots should The SVN check-ins always have all the tests passing and so SVN snapshots should
be pretty usable, although the code may not look so good internally. be pretty usable, although the code may not look so good internally.
Oh, yes. It is called "Simple" because it should be simple to Oh, and one last thing: SimpleTest is called "Simple" because it should
use. We intend to add a complete set of tools for a test first be simple to use. We intend to add a complete set of tools for a test
and "test as you code" type of development. "Simple" does not first and "test as you code" type of development. "Simple" does not mean
mean "Lite" in this context. "Lite" in this context.
Thanks to everyone who has sent comments and offered suggestions. They Thanks to everyone who has sent comments and offered suggestions. They
really are invaluable, but sadly you are too many to mention in full. really are invaluable, but sadly you are too many to mention in full.
Thanks to all on the advanced PHP forum on SitePoint, especially Harry Thanks to all on the advanced PHP forum on SitePoint, especially Harry
Feucks. Early adopters are always an inspiration. Fuecks. Early adopters are always an inspiration.
Marcus Baker, Jason Sweat, Travis Swicegood, Perrick Penet and Edward Z. Yang. -- Marcus Baker, Jason Sweat, Travis Swicegood, Perrick Penet and Edward Z. Yang.
--
marcus@lastcraft.com

2
contrib/simpletest/simpletest/VERSION Normal file → Executable file
View File

@ -1 +1 @@
1.0.1 1.1.0

View File

@ -0,0 +1,224 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id: dumper.php 1909 2009-07-29 15:58:11Z dgheath $
*/
/**
* Parses the command line arguments.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleArguments {
private $all = array();
/**
* Parses the command line arguments. The usual formats
* are supported:
* -f value
* -f=value
* --flag=value
* --flag value
* -f (true)
* --flag (true)
* @param array $arguments Normally the PHP $argv.
*/
function __construct($arguments) {
array_shift($arguments);
while (count($arguments) > 0) {
list($key, $value) = $this->parseArgument($arguments);
$this->assign($key, $value);
}
}
/**
* Sets the value in the argments object. If multiple
* values are added under the same key, the key will
* give an array value in the order they were added.
* @param string $key The variable to assign to.
* @param string value The value that would norally
* be colected on the command line.
*/
function assign($key, $value) {
if ($this->$key === false) {
$this->all[$key] = $value;
} elseif (! is_array($this->$key)) {
$this->all[$key] = array($this->$key, $value);
} else {
$this->all[$key][] = $value;
}
}
/**
* Extracts the next key and value from the argument list.
* @param array $arguments The remaining arguments to be parsed.
* The argument list will be reduced.
* @return array Two item array of key and value.
* If no value can be found it will
* have the value true assigned instead.
*/
private function parseArgument(&$arguments) {
$argument = array_shift($arguments);
if (preg_match('/^-(\w)=(.+)$/', $argument, $matches)) {
return array($matches[1], $matches[2]);
} elseif (preg_match('/^-(\w)$/', $argument, $matches)) {
return array($matches[1], $this->nextNonFlagElseTrue($arguments));
} elseif (preg_match('/^--(\w+)=(.+)$/', $argument, $matches)) {
return array($matches[1], $matches[2]);
} elseif (preg_match('/^--(\w+)$/', $argument, $matches)) {
return array($matches[1], $this->nextNonFlagElseTrue($arguments));
}
}
/**
* Attempts to use the next argument as a value. It
* won't use what it thinks is a flag.
* @param array $arguments Remaining arguments to be parsed.
* This variable is modified if there
* is a value to be extracted.
* @return string/boolean The next value unless it's a flag.
*/
private function nextNonFlagElseTrue(&$arguments) {
return $this->valueIsNext($arguments) ? array_shift($arguments) : true;
}
/**
* Test to see if the next available argument is a valid value.
* If it starts with "-" or "--" it's a flag and doesn't count.
* @param array $arguments Remaining arguments to be parsed.
* Not affected by this call.
* boolean True if valid value.
*/
function valueIsNext($arguments) {
return isset($arguments[0]) && ! $this->isFlag($arguments[0]);
}
/**
* It's a flag if it starts with "-" or "--".
* @param string $argument Value to be tested.
* @return boolean True if it's a flag.
*/
function isFlag($argument) {
return strncmp($argument, '-', 1) == 0;
}
/**
* The arguments are available as individual member
* variables on the object.
* @param string $key Argument name.
* @return string/array/boolean Either false for no value,
* the value as a string or
* a list of multiple values if
* the flag had been specified more
* than once.
*/
function __get($key) {
if (isset($this->all[$key])) {
return $this->all[$key];
}
return false;
}
/**
* The entire argument set as a hash.
* @return hash Each argument and it's value(s).
*/
function all() {
return $this->all;
}
}
/**
* Renders the help for the command line arguments.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleHelp {
private $overview;
private $flag_sets = array();
private $explanations = array();
/**
* Sets up the top level explanation for the program.
* @param string $overview Summary of program.
*/
function __construct($overview = '') {
$this->overview = $overview;
}
/**
* Adds the explanation for a group of flags that all
* have the same function.
* @param string/array $flags Flag and alternates. Don't
* worry about leading dashes
* as these are inserted automatically.
* @param string $explanation What that flag group does.
*/
function explainFlag($flags, $explanation) {
$flags = is_array($flags) ? $flags : array($flags);
$this->flag_sets[] = $flags;
$this->explanations[] = $explanation;
}
/**
* Generates the help text.
* @returns string The complete formatted text.
*/
function render() {
$tab_stop = $this->longestFlag($this->flag_sets) + 4;
$text = $this->overview . "\n";
for ($i = 0; $i < count($this->flag_sets); $i++) {
$text .= $this->renderFlagSet($this->flag_sets[$i], $this->explanations[$i], $tab_stop);
}
return $this->noDuplicateNewLines($text);
}
/**
* Works out the longest flag for formatting purposes.
* @param array $flag_sets The internal flag set list.
*/
private function longestFlag($flag_sets) {
$longest = 0;
foreach ($flag_sets as $flags) {
foreach ($flags as $flag) {
$longest = max($longest, strlen($this->renderFlag($flag)));
}
}
return $longest;
}
/**
* Generates the text for a single flag and it's alternate flags.
* @returns string Help text for that flag group.
*/
private function renderFlagSet($flags, $explanation, $tab_stop) {
$flag = array_shift($flags);
$text = str_pad($this->renderFlag($flag), $tab_stop, ' ') . $explanation . "\n";
foreach ($flags as $flag) {
$text .= ' ' . $this->renderFlag($flag) . "\n";
}
return $text;
}
/**
* Generates the flag name including leading dashes.
* @param string $flag Just the name.
* @returns Fag with apropriate dashes.
*/
private function renderFlag($flag) {
return (strlen($flag) == 1 ? '-' : '--') . $flag;
}
/**
* Converts multiple new lines into a single new line.
* Just there to trap accidental duplicate new lines.
* @param string $text Text to clean up.
* @returns string Text with no blank lines.
*/
private function noDuplicateNewLines($text) {
return preg_replace('/(\n+)/', "\n", $text);
}
}
?>

View File

@ -3,7 +3,7 @@
* Base include file for SimpleTest * Base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
* @version $Id: authentication.php 1720 2008-04-07 02:32:43Z lastcraft $ * @version $Id: authentication.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/** /**
* include http class * include http class
@ -16,11 +16,11 @@ require_once(dirname(__FILE__) . '/http.php');
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleRealm { class SimpleRealm {
var $_type; private $type;
var $_root; private $root;
var $_username; private $username;
var $_password; private $password;
/** /**
* Starts with the initial entry directory. * Starts with the initial entry directory.
* @param string $type Authentication type for this * @param string $type Authentication type for this
@ -30,21 +30,21 @@ class SimpleRealm {
* @access public * @access public
*/ */
function SimpleRealm($type, $url) { function SimpleRealm($type, $url) {
$this->_type = $type; $this->type = $type;
$this->_root = $url->getBasePath(); $this->root = $url->getBasePath();
$this->_username = false; $this->username = false;
$this->_password = false; $this->password = false;
} }
/** /**
* Adds another location to the realm. * Adds another location to the realm.
* @param SimpleUrl $url Somewhere in realm. * @param SimpleUrl $url Somewhere in realm.
* @access public * @access public
*/ */
function stretch($url) { function stretch($url) {
$this->_root = $this->_getCommonPath($this->_root, $url->getPath()); $this->root = $this->getCommonPath($this->root, $url->getPath());
} }
/** /**
* Finds the common starting path. * Finds the common starting path.
* @param string $first Path to compare. * @param string $first Path to compare.
@ -52,7 +52,7 @@ class SimpleRealm {
* @return string Common directories. * @return string Common directories.
* @access private * @access private
*/ */
function _getCommonPath($first, $second) { protected function getCommonPath($first, $second) {
$first = explode('/', $first); $first = explode('/', $first);
$second = explode('/', $second); $second = explode('/', $second);
for ($i = 0; $i < min(count($first), count($second)); $i++) { for ($i = 0; $i < min(count($first), count($second)); $i++) {
@ -62,7 +62,7 @@ class SimpleRealm {
} }
return implode('/', $first) . '/'; return implode('/', $first) . '/';
} }
/** /**
* Sets the identity to try within this realm. * Sets the identity to try within this realm.
* @param string $username Username in authentication dialog. * @param string $username Username in authentication dialog.
@ -70,28 +70,28 @@ class SimpleRealm {
* @access public * @access public
*/ */
function setIdentity($username, $password) { function setIdentity($username, $password) {
$this->_username = $username; $this->username = $username;
$this->_password = $password; $this->password = $password;
} }
/** /**
* Accessor for current identity. * Accessor for current identity.
* @return string Last succesful username. * @return string Last succesful username.
* @access public * @access public
*/ */
function getUsername() { function getUsername() {
return $this->_username; return $this->username;
} }
/** /**
* Accessor for current identity. * Accessor for current identity.
* @return string Last succesful password. * @return string Last succesful password.
* @access public * @access public
*/ */
function getPassword() { function getPassword() {
return $this->_password; return $this->password;
} }
/** /**
* Test to see if the URL is within the directory * Test to see if the URL is within the directory
* tree of the realm. * tree of the realm.
@ -100,15 +100,15 @@ class SimpleRealm {
* @access public * @access public
*/ */
function isWithin($url) { function isWithin($url) {
if ($this->_isIn($this->_root, $url->getBasePath())) { if ($this->isIn($this->root, $url->getBasePath())) {
return true; return true;
} }
if ($this->_isIn($this->_root, $url->getBasePath() . $url->getPage() . '/')) { if ($this->isIn($this->root, $url->getBasePath() . $url->getPage() . '/')) {
return true; return true;
} }
return false; return false;
} }
/** /**
* Tests to see if one string is a substring of * Tests to see if one string is a substring of
* another. * another.
@ -118,7 +118,7 @@ class SimpleRealm {
* in the big bit. * in the big bit.
* @access private * @access private
*/ */
function _isIn($part, $whole) { protected function isIn($part, $whole) {
return strpos($whole, $part) === 0; return strpos($whole, $part) === 0;
} }
} }
@ -129,8 +129,8 @@ class SimpleRealm {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleAuthenticator { class SimpleAuthenticator {
var $_realms; private $realms;
/** /**
* Clears the realms. * Clears the realms.
* @access public * @access public
@ -138,18 +138,18 @@ class SimpleAuthenticator {
function SimpleAuthenticator() { function SimpleAuthenticator() {
$this->restartSession(); $this->restartSession();
} }
/** /**
* Starts with no realms set up. * Starts with no realms set up.
* @access public * @access public
*/ */
function restartSession() { function restartSession() {
$this->_realms = array(); $this->realms = array();
} }
/** /**
* Adds a new realm centered the current URL. * Adds a new realm centered the current URL.
* Browsers vary wildly on their behaviour in this * Browsers privatey wildly on their behaviour in this
* regard. Mozilla ignores the realm and presents * regard. Mozilla ignores the realm and presents
* only when challenged, wasting bandwidth. IE * only when challenged, wasting bandwidth. IE
* just carries on presenting until a new challenge * just carries on presenting until a new challenge
@ -164,9 +164,9 @@ class SimpleAuthenticator {
* @access public * @access public
*/ */
function addRealm($url, $type, $realm) { function addRealm($url, $type, $realm) {
$this->_realms[$url->getHost()][$realm] = new SimpleRealm($type, $url); $this->realms[$url->getHost()][$realm] = new SimpleRealm($type, $url);
} }
/** /**
* Sets the current identity to be presented * Sets the current identity to be presented
* against that realm. * against that realm.
@ -177,29 +177,29 @@ class SimpleAuthenticator {
* @access public * @access public
*/ */
function setIdentityForRealm($host, $realm, $username, $password) { function setIdentityForRealm($host, $realm, $username, $password) {
if (isset($this->_realms[$host][$realm])) { if (isset($this->realms[$host][$realm])) {
$this->_realms[$host][$realm]->setIdentity($username, $password); $this->realms[$host][$realm]->setIdentity($username, $password);
} }
} }
/** /**
* Finds the name of the realm by comparing URLs. * Finds the name of the realm by comparing URLs.
* @param SimpleUrl $url URL to test. * @param SimpleUrl $url URL to test.
* @return SimpleRealm Name of realm. * @return SimpleRealm Name of realm.
* @access private * @access private
*/ */
function _findRealmFromUrl($url) { protected function findRealmFromUrl($url) {
if (! isset($this->_realms[$url->getHost()])) { if (! isset($this->realms[$url->getHost()])) {
return false; return false;
} }
foreach ($this->_realms[$url->getHost()] as $name => $realm) { foreach ($this->realms[$url->getHost()] as $name => $realm) {
if ($realm->isWithin($url)) { if ($realm->isWithin($url)) {
return $realm; return $realm;
} }
} }
return false; return false;
} }
/** /**
* Presents the appropriate headers for this location. * Presents the appropriate headers for this location.
* @param SimpleHttpRequest $request Request to modify. * @param SimpleHttpRequest $request Request to modify.
@ -210,7 +210,7 @@ class SimpleAuthenticator {
if ($url->getUsername() && $url->getPassword()) { if ($url->getUsername() && $url->getPassword()) {
$username = $url->getUsername(); $username = $url->getUsername();
$password = $url->getPassword(); $password = $url->getPassword();
} elseif ($realm = $this->_findRealmFromUrl($url)) { } elseif ($realm = $this->findRealmFromUrl($url)) {
$username = $realm->getUsername(); $username = $realm->getUsername();
$password = $realm->getPassword(); $password = $realm->getPassword();
} else { } else {
@ -218,7 +218,7 @@ class SimpleAuthenticator {
} }
$this->addBasicHeaders($request, $username, $password); $this->addBasicHeaders($request, $username, $password);
} }
/** /**
* Presents the appropriate headers for this * Presents the appropriate headers for this
* location for basic authentication. * location for basic authentication.
@ -226,12 +226,11 @@ class SimpleAuthenticator {
* @param string $username Username for realm. * @param string $username Username for realm.
* @param string $password Password for realm. * @param string $password Password for realm.
* @access public * @access public
* @static
*/ */
function addBasicHeaders(&$request, $username, $password) { static function addBasicHeaders(&$request, $username, $password) {
if ($username && $password) { if ($username && $password) {
$request->addHeaderLine( $request->addHeaderLine(
'Authorization: Basic ' . base64_encode("$username:$password")); 'Authorization: Basic ' . base64_encode("$username:$password"));
} }
} }
} }

View File

@ -3,38 +3,61 @@
* Autorunner which runs all tests cases found in a file * Autorunner which runs all tests cases found in a file
* that includes this module. * that includes this module.
* @package SimpleTest * @package SimpleTest
* @version $Id: autorun.php 1721 2008-04-07 19:27:10Z lastcraft $ * @version $Id: autorun.php 2037 2011-11-30 17:58:21Z pp11 $
*/
/**#@+
* include simpletest files
*/ */
require_once dirname(__FILE__) . '/unit_tester.php'; require_once dirname(__FILE__) . '/unit_tester.php';
require_once dirname(__FILE__) . '/mock_objects.php'; require_once dirname(__FILE__) . '/mock_objects.php';
require_once dirname(__FILE__) . '/collector.php'; require_once dirname(__FILE__) . '/collector.php';
require_once dirname(__FILE__) . '/default_reporter.php'; require_once dirname(__FILE__) . '/default_reporter.php';
/**#@-*/
$GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_CLASSES'] = get_declared_classes(); $GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_CLASSES'] = get_declared_classes();
$GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_PATH'] = getcwd();
register_shutdown_function('simpletest_autorun'); register_shutdown_function('simpletest_autorun');
/** /**
* Exit handler to run all recent test cases if no test has * Exit handler to run all recent test cases and exit system if in CLI
* so far been run. Uses the DefaultReporter which can have
* it's output controlled with SimpleTest::prefer().
*/ */
function simpletest_autorun() { function simpletest_autorun() {
chdir($GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_PATH']);
if (tests_have_run()) { if (tests_have_run()) {
return; return;
} }
$candidates = array_intersect( $result = run_local_tests();
capture_new_classes(),
classes_defined_in_initial_file());
$loader = new SimpleFileLoader();
$suite = $loader->createSuiteFromClasses(
basename(initial_file()),
$loader->selectRunnableTests($candidates));
$result = $suite->run(new DefaultReporter());
if (SimpleReporter::inCli()) { if (SimpleReporter::inCli()) {
exit($result ? 0 : 1); exit($result ? 0 : 1);
} }
} }
/**
* run all recent test cases if no test has
* so far been run. Uses the DefaultReporter which can have
* it's output controlled with SimpleTest::prefer().
* @return boolean/null false if there were test failures, true if
* there were no failures, null if tests are
* already running
*/
function run_local_tests() {
try {
if (tests_have_run()) {
return;
}
$candidates = capture_new_classes();
$loader = new SimpleFileLoader();
$suite = $loader->createSuiteFromClasses(
basename(initial_file()),
$loader->selectRunnableTests($candidates));
return $suite->run(new DefaultReporter());
} catch (Exception $stack_frame_fix) {
print $stack_frame_fix->getMessage();
return false;
}
}
/** /**
* Checks the current test context to see if a test has * Checks the current test context to see if a test has
* ever been run. * ever been run.
@ -54,28 +77,19 @@ function tests_have_run() {
function initial_file() { function initial_file() {
static $file = false; static $file = false;
if (! $file) { if (! $file) {
$file = reset(get_included_files()); if (isset($_SERVER, $_SERVER['SCRIPT_FILENAME'])) {
$file = $_SERVER['SCRIPT_FILENAME'];
} else {
$included_files = get_included_files();
$file = reset($included_files);
}
} }
return $file; return $file;
} }
/**
* Just the classes from the first autorun script. May
* get a few false positives, as it just does a regex based
* on following the word "class".
* @return array List of all possible classes in first
* autorun script.
*/
function classes_defined_in_initial_file() {
if (preg_match_all('/\bclass\s+(\w+)/i', file_get_contents(initial_file()), $matches)) {
return array_map('strtolower', $matches[1]);
}
return array();
}
/** /**
* Every class since the first autorun include. This * Every class since the first autorun include. This
* is safe enough if require_once() is alwyas used. * is safe enough if require_once() is always used.
* @return array Class names. * @return array Class names.
*/ */
function capture_new_classes() { function capture_new_classes() {

View File

@ -3,7 +3,7 @@
* Base include file for SimpleTest * Base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
* @version $Id: browser.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: browser.php 2013 2011-04-29 09:29:45Z pp11 $
*/ */
/**#@+ /**#@+
@ -13,12 +13,18 @@ require_once(dirname(__FILE__) . '/simpletest.php');
require_once(dirname(__FILE__) . '/http.php'); require_once(dirname(__FILE__) . '/http.php');
require_once(dirname(__FILE__) . '/encoding.php'); require_once(dirname(__FILE__) . '/encoding.php');
require_once(dirname(__FILE__) . '/page.php'); require_once(dirname(__FILE__) . '/page.php');
require_once(dirname(__FILE__) . '/php_parser.php');
require_once(dirname(__FILE__) . '/tidy_parser.php');
require_once(dirname(__FILE__) . '/selector.php'); require_once(dirname(__FILE__) . '/selector.php');
require_once(dirname(__FILE__) . '/frames.php'); require_once(dirname(__FILE__) . '/frames.php');
require_once(dirname(__FILE__) . '/user_agent.php'); require_once(dirname(__FILE__) . '/user_agent.php');
if (! SimpleTest::getParsers()) {
SimpleTest::setParsers(array(new SimpleTidyPageBuilder(), new SimplePHPPageBuilder()));
//SimpleTest::setParsers(array(new SimplePHPPageBuilder()));
}
/**#@-*/ /**#@-*/
if (!defined('DEFAULT_MAX_NESTED_FRAMES')) { if (! defined('DEFAULT_MAX_NESTED_FRAMES')) {
define('DEFAULT_MAX_NESTED_FRAMES', 3); define('DEFAULT_MAX_NESTED_FRAMES', 3);
} }
@ -28,25 +34,16 @@ if (!defined('DEFAULT_MAX_NESTED_FRAMES')) {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleBrowserHistory { class SimpleBrowserHistory {
var $_sequence; private $sequence = array();
var $_position; private $position = -1;
/**
* Starts empty.
* @access public
*/
function SimpleBrowserHistory() {
$this->_sequence = array();
$this->_position = -1;
}
/** /**
* Test for no entries yet. * Test for no entries yet.
* @return boolean True if empty. * @return boolean True if empty.
* @access private * @access private
*/ */
function _isEmpty() { protected function isEmpty() {
return ($this->_position == -1); return ($this->position == -1);
} }
/** /**
@ -54,8 +51,8 @@ class SimpleBrowserHistory {
* @return boolean True if first. * @return boolean True if first.
* @access private * @access private
*/ */
function _atBeginning() { protected function atBeginning() {
return ($this->_position == 0) && ! $this->_isEmpty(); return ($this->position == 0) && ! $this->isEmpty();
} }
/** /**
@ -63,8 +60,8 @@ class SimpleBrowserHistory {
* @return boolean True if last. * @return boolean True if last.
* @access private * @access private
*/ */
function _atEnd() { protected function atEnd() {
return ($this->_position + 1 >= count($this->_sequence)) && ! $this->_isEmpty(); return ($this->position + 1 >= count($this->sequence)) && ! $this->isEmpty();
} }
/** /**
@ -74,11 +71,11 @@ class SimpleBrowserHistory {
* @access public * @access public
*/ */
function recordEntry($url, $parameters) { function recordEntry($url, $parameters) {
$this->_dropFuture(); $this->dropFuture();
array_push( array_push(
$this->_sequence, $this->sequence,
array('url' => $url, 'parameters' => $parameters)); array('url' => $url, 'parameters' => $parameters));
$this->_position++; $this->position++;
} }
/** /**
@ -88,10 +85,10 @@ class SimpleBrowserHistory {
* @access public * @access public
*/ */
function getUrl() { function getUrl() {
if ($this->_isEmpty()) { if ($this->isEmpty()) {
return false; return false;
} }
return $this->_sequence[$this->_position]['url']; return $this->sequence[$this->position]['url'];
} }
/** /**
@ -101,10 +98,10 @@ class SimpleBrowserHistory {
* @access public * @access public
*/ */
function getParameters() { function getParameters() {
if ($this->_isEmpty()) { if ($this->isEmpty()) {
return false; return false;
} }
return $this->_sequence[$this->_position]['parameters']; return $this->sequence[$this->position]['parameters'];
} }
/** /**
@ -114,10 +111,10 @@ class SimpleBrowserHistory {
* @access public * @access public
*/ */
function back() { function back() {
if ($this->_isEmpty() || $this->_atBeginning()) { if ($this->isEmpty() || $this->atBeginning()) {
return false; return false;
} }
$this->_position--; $this->position--;
return true; return true;
} }
@ -128,10 +125,10 @@ class SimpleBrowserHistory {
* @access public * @access public
*/ */
function forward() { function forward() {
if ($this->_isEmpty() || $this->_atEnd()) { if ($this->isEmpty() || $this->atEnd()) {
return false; return false;
} }
$this->_position++; $this->position++;
return true; return true;
} }
@ -140,12 +137,12 @@ class SimpleBrowserHistory {
* point. * point.
* @access private * @access private
*/ */
function _dropFuture() { protected function dropFuture() {
if ($this->_isEmpty()) { if ($this->isEmpty()) {
return; return;
} }
while (! $this->_atEnd()) { while (! $this->atEnd()) {
array_pop($this->_sequence); array_pop($this->sequence);
} }
} }
} }
@ -158,11 +155,12 @@ class SimpleBrowserHistory {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleBrowser { class SimpleBrowser {
var $_user_agent; private $user_agent;
var $_page; private $page;
var $_history; private $history;
var $_ignore_frames; private $ignore_frames;
var $_maximum_nested_frames; private $maximum_nested_frames;
private $parser;
/** /**
* Starts with a fresh browser with no * Starts with a fresh browser with no
@ -171,16 +169,16 @@ class SimpleBrowser {
* set up if specified in the options. * set up if specified in the options.
* @access public * @access public
*/ */
function SimpleBrowser() { function __construct() {
$this->_user_agent = &$this->_createUserAgent(); $this->user_agent = $this->createUserAgent();
$this->_user_agent->useProxy( $this->user_agent->useProxy(
SimpleTest::getDefaultProxy(), SimpleTest::getDefaultProxy(),
SimpleTest::getDefaultProxyUsername(), SimpleTest::getDefaultProxyUsername(),
SimpleTest::getDefaultProxyPassword()); SimpleTest::getDefaultProxyPassword());
$this->_page = &new SimplePage(); $this->page = new SimplePage();
$this->_history = &$this->_createHistory(); $this->history = $this->createHistory();
$this->_ignore_frames = false; $this->ignore_frames = false;
$this->_maximum_nested_frames = DEFAULT_MAX_NESTED_FRAMES; $this->maximum_nested_frames = DEFAULT_MAX_NESTED_FRAMES;
} }
/** /**
@ -188,9 +186,8 @@ class SimpleBrowser {
* @return SimpleFetcher Content fetcher. * @return SimpleFetcher Content fetcher.
* @access protected * @access protected
*/ */
function &_createUserAgent() { protected function createUserAgent() {
$user_agent = &new SimpleUserAgent(); return new SimpleUserAgent();
return $user_agent;
} }
/** /**
@ -198,9 +195,33 @@ class SimpleBrowser {
* @return SimpleBrowserHistory New list. * @return SimpleBrowserHistory New list.
* @access protected * @access protected
*/ */
function &_createHistory() { protected function createHistory() {
$history = &new SimpleBrowserHistory(); return new SimpleBrowserHistory();
return $history; }
/**
* Get the HTML parser to use. Can be overridden by
* setParser. Otherwise scans through the available parsers and
* uses the first one which is available.
* @return object SimplePHPPageBuilder or SimpleTidyPageBuilder
*/
protected function getParser() {
if ($this->parser) {
return $this->parser;
}
foreach (SimpleTest::getParsers() as $parser) {
if ($parser->can()) {
return $parser;
}
}
}
/**
* Override the default HTML parser, allowing parsers to be plugged in.
* @param object A parser object instance.
*/
public function setParser($parser) {
$this->parser = $parser;
} }
/** /**
@ -209,7 +230,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function ignoreFrames() { function ignoreFrames() {
$this->_ignore_frames = true; $this->ignore_frames = true;
} }
/** /**
@ -218,23 +239,23 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function useFrames() { function useFrames() {
$this->_ignore_frames = false; $this->ignore_frames = false;
} }
/** /**
* Switches off cookie sending and recieving. * Switches off cookie sending and recieving.
* @access public * @access public
*/ */
function ignoreCookies() { function ignoreCookies() {
$this->_user_agent->ignoreCookies(); $this->user_agent->ignoreCookies();
} }
/** /**
* Switches back on the cookie sending and recieving. * Switches back on the cookie sending and recieving.
* @access public * @access public
*/ */
function useCookies() { function useCookies() {
$this->_user_agent->useCookies(); $this->user_agent->useCookies();
} }
/** /**
@ -245,37 +266,32 @@ class SimpleBrowser {
* @return SimplePage Parsed HTML. * @return SimplePage Parsed HTML.
* @access private * @access private
*/ */
function &_parse($response, $depth = 0) { protected function parse($response, $depth = 0) {
$page = &$this->_buildPage($response); $page = $this->buildPage($response);
if ($this->_ignore_frames || ! $page->hasFrames() || ($depth > $this->_maximum_nested_frames)) { if ($this->ignore_frames || ! $page->hasFrames() || ($depth > $this->maximum_nested_frames)) {
return $page; return $page;
} }
$frameset = &new SimpleFrameset($page); $frameset = new SimpleFrameset($page);
foreach ($page->getFrameset() as $key => $url) { foreach ($page->getFrameset() as $key => $url) {
$frame = &$this->_fetch($url, new SimpleGetEncoding(), $depth + 1); $frame = $this->fetch($url, new SimpleGetEncoding(), $depth + 1);
$frameset->addFrame($frame, $key); $frameset->addFrame($frame, $key);
} }
return $frameset; return $frameset;
} }
/** /**
* Assembles the parsing machinery and actually parses * Assembles the parsing machinery and actually parses
* a single page. Frees all of the builder memory and so * a single page. Frees all of the builder memory and so
* unjams the PHP memory management. * unjams the PHP memory management.
* @param SimpleHttpResponse $response Response from fetch. * @param SimpleHttpResponse $response Response from fetch.
* @return SimplePage Parsed top level page. * @return SimplePage Parsed top level page.
* @access protected
*/ */
function &_buildPage($response) { protected function buildPage($response) {
$builder = &new SimplePageBuilder(); return $this->getParser()->parse($response);
$page = &$builder->parse($response);
$builder->free();
unset($builder);
return $page;
} }
/** /**
* Fetches a page. Jointly recursive with the _parse() * Fetches a page. Jointly recursive with the parse()
* method as it descends a frameset. * method as it descends a frameset.
* @param string/SimpleUrl $url Target to fetch. * @param string/SimpleUrl $url Target to fetch.
* @param SimpleEncoding $encoding GET/POST parameters. * @param SimpleEncoding $encoding GET/POST parameters.
@ -283,14 +299,12 @@ class SimpleBrowser {
* @return SimplePage Parsed page. * @return SimplePage Parsed page.
* @access private * @access private
*/ */
function &_fetch($url, $encoding, $depth = 0) { protected function fetch($url, $encoding, $depth = 0) {
$response = &$this->_user_agent->fetchResponse($url, $encoding); $response = $this->user_agent->fetchResponse($url, $encoding);
if ($response->isError()) { if ($response->isError()) {
$page = &new SimplePage($response); return new SimplePage($response);
} else {
$page = &$this->_parse($response, $depth);
} }
return $page; return $this->parse($response, $depth);
} }
/** /**
@ -301,12 +315,12 @@ class SimpleBrowser {
* @return string Raw content of page. * @return string Raw content of page.
* @access private * @access private
*/ */
function _load($url, $parameters) { protected function load($url, $parameters) {
$frame = $url->getTarget(); $frame = $url->getTarget();
if (! $frame || ! $this->_page->hasFrames() || (strtolower($frame) == '_top')) { if (! $frame || ! $this->page->hasFrames() || (strtolower($frame) == '_top')) {
return $this->_loadPage($url, $parameters); return $this->loadPage($url, $parameters);
} }
return $this->_loadFrame(array($frame), $url, $parameters); return $this->loadFrame(array($frame), $url, $parameters);
} }
/** /**
@ -316,12 +330,12 @@ class SimpleBrowser {
* @return string Raw content of page. * @return string Raw content of page.
* @access private * @access private
*/ */
function _loadPage($url, $parameters) { protected function loadPage($url, $parameters) {
$this->_page = &$this->_fetch($url, $parameters); $this->page = $this->fetch($url, $parameters);
$this->_history->recordEntry( $this->history->recordEntry(
$this->_page->getUrl(), $this->page->getUrl(),
$this->_page->getRequestData()); $this->page->getRequestData());
return $this->_page->getRaw(); return $this->page->getRaw();
} }
/** /**
@ -333,9 +347,9 @@ class SimpleBrowser {
* @return string Raw content of page. * @return string Raw content of page.
* @access private * @access private
*/ */
function _loadFrame($frames, $url, $parameters) { protected function loadFrame($frames, $url, $parameters) {
$page = &$this->_fetch($url, $parameters); $page = $this->fetch($url, $parameters);
$this->_page->setFrame($frames, $page); $this->page->setFrame($frames, $page);
return $page->getRaw(); return $page->getRaw();
} }
@ -348,7 +362,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function restart($date = false) { function restart($date = false) {
$this->_user_agent->restart($date); $this->user_agent->restart($date);
} }
/** /**
@ -358,7 +372,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function addHeader($header) { function addHeader($header) {
$this->_user_agent->addHeader($header); $this->user_agent->addHeader($header);
} }
/** /**
@ -367,7 +381,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function ageCookies($interval) { function ageCookies($interval) {
$this->_user_agent->ageCookies($interval); $this->user_agent->ageCookies($interval);
} }
/** /**
@ -381,7 +395,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { function setCookie($name, $value, $host = false, $path = '/', $expiry = false) {
$this->_user_agent->setCookie($name, $value, $host, $path, $expiry); $this->user_agent->setCookie($name, $value, $host, $path, $expiry);
} }
/** /**
@ -395,7 +409,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getCookieValue($host, $path, $name) { function getCookieValue($host, $path, $name) {
return $this->_user_agent->getCookieValue($host, $path, $name); return $this->user_agent->getCookieValue($host, $path, $name);
} }
/** /**
@ -406,7 +420,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getCurrentCookieValue($name) { function getCurrentCookieValue($name) {
return $this->_user_agent->getBaseCookieValue($name, $this->_page->getUrl()); return $this->user_agent->getBaseCookieValue($name, $this->page->getUrl());
} }
/** /**
@ -416,7 +430,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function setMaximumRedirects($max) { function setMaximumRedirects($max) {
$this->_user_agent->setMaximumRedirects($max); $this->user_agent->setMaximumRedirects($max);
} }
/** /**
@ -426,7 +440,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function setMaximumNestedFrames($max) { function setMaximumNestedFrames($max) {
$this->_maximum_nested_frames = $max; $this->maximum_nested_frames = $max;
} }
/** /**
@ -435,7 +449,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function setConnectionTimeout($timeout) { function setConnectionTimeout($timeout) {
$this->_user_agent->setConnectionTimeout($timeout); $this->user_agent->setConnectionTimeout($timeout);
} }
/** /**
@ -448,7 +462,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function useProxy($proxy, $username = false, $password = false) { function useProxy($proxy, $username = false, $password = false) {
$this->_user_agent->useProxy($proxy, $username, $password); $this->user_agent->useProxy($proxy, $username, $password);
} }
/** /**
@ -467,7 +481,8 @@ class SimpleBrowser {
if ($this->getUrl()) { if ($this->getUrl()) {
$url = $url->makeAbsolute($this->getUrl()); $url = $url->makeAbsolute($this->getUrl());
} }
$response = &$this->_user_agent->fetchResponse($url, new SimpleHeadEncoding($parameters)); $response = $this->user_agent->fetchResponse($url, new SimpleHeadEncoding($parameters));
$this->page = new SimplePage($response);
return ! $response->isError(); return ! $response->isError();
} }
@ -486,24 +501,55 @@ class SimpleBrowser {
if ($this->getUrl()) { if ($this->getUrl()) {
$url = $url->makeAbsolute($this->getUrl()); $url = $url->makeAbsolute($this->getUrl());
} }
return $this->_load($url, new SimpleGetEncoding($parameters)); return $this->load($url, new SimpleGetEncoding($parameters));
} }
/** /**
* Fetches the page content with a POST request. * Fetches the page content with a POST request.
* @param string/SimpleUrl $url Target to fetch as string. * @param string/SimpleUrl $url Target to fetch as string.
* @param hash/SimpleFormEncoding $parameters POST parameters. * @param hash/SimpleFormEncoding $parameters POST parameters or request body.
* @param string $content_type MIME Content-Type of the request body
* @return string Content of page. * @return string Content of page.
* @access public * @access public
*/ */
function post($url, $parameters = false) { function post($url, $parameters = false, $content_type = false) {
if (! is_object($url)) { if (! is_object($url)) {
$url = new SimpleUrl($url); $url = new SimpleUrl($url);
} }
if ($this->getUrl()) { if ($this->getUrl()) {
$url = $url->makeAbsolute($this->getUrl()); $url = $url->makeAbsolute($this->getUrl());
} }
return $this->_load($url, new SimplePostEncoding($parameters)); return $this->load($url, new SimplePostEncoding($parameters, $content_type));
}
/**
* Fetches the page content with a PUT request.
* @param string/SimpleUrl $url Target to fetch as string.
* @param hash/SimpleFormEncoding $parameters PUT request body.
* @param string $content_type MIME Content-Type of the request body
* @return string Content of page.
* @access public
*/
function put($url, $parameters = false, $content_type = false) {
if (! is_object($url)) {
$url = new SimpleUrl($url);
}
return $this->load($url, new SimplePutEncoding($parameters, $content_type));
}
/**
* Sends a DELETE request and fetches the response.
* @param string/SimpleUrl $url Target to fetch.
* @param hash/SimpleFormEncoding $parameters Additional parameters for
* DELETE request.
* @return string Content of page or false.
* @access public
*/
function delete($url, $parameters = false) {
if (! is_object($url)) {
$url = new SimpleUrl($url);
}
return $this->load($url, new SimpleDeleteEncoding($parameters));
} }
/** /**
@ -515,17 +561,17 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function retry() { function retry() {
$frames = $this->_page->getFrameFocus(); $frames = $this->page->getFrameFocus();
if (count($frames) > 0) { if (count($frames) > 0) {
$this->_loadFrame( $this->loadFrame(
$frames, $frames,
$this->_page->getUrl(), $this->page->getUrl(),
$this->_page->getRequestData()); $this->page->getRequestData());
return $this->_page->getRaw(); return $this->page->getRaw();
} }
if ($url = $this->_history->getUrl()) { if ($url = $this->history->getUrl()) {
$this->_page = &$this->_fetch($url, $this->_history->getParameters()); $this->page = $this->fetch($url, $this->history->getParameters());
return $this->_page->getRaw(); return $this->page->getRaw();
} }
return false; return false;
} }
@ -540,12 +586,12 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function back() { function back() {
if (! $this->_history->back()) { if (! $this->history->back()) {
return false; return false;
} }
$content = $this->retry(); $content = $this->retry();
if (! $content) { if (! $content) {
$this->_history->forward(); $this->history->forward();
} }
return $content; return $content;
} }
@ -560,12 +606,12 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function forward() { function forward() {
if (! $this->_history->forward()) { if (! $this->history->forward()) {
return false; return false;
} }
$content = $this->retry(); $content = $this->retry();
if (! $content) { if (! $content) {
$this->_history->back(); $this->history->back();
} }
return $content; return $content;
} }
@ -581,16 +627,16 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function authenticate($username, $password) { function authenticate($username, $password) {
if (! $this->_page->getRealm()) { if (! $this->page->getRealm()) {
return false; return false;
} }
$url = $this->_page->getUrl(); $url = $this->page->getUrl();
if (! $url) { if (! $url) {
return false; return false;
} }
$this->_user_agent->setIdentity( $this->user_agent->setIdentity(
$url->getHost(), $url->getHost(),
$this->_page->getRealm(), $this->page->getRealm(),
$username, $username,
$password); $password);
return $this->retry(); return $this->retry();
@ -603,7 +649,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getFrames() { function getFrames() {
return $this->_page->getFrames(); return $this->page->getFrames();
} }
/** /**
@ -615,7 +661,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getFrameFocus() { function getFrameFocus() {
return $this->_page->getFrameFocus(); return $this->page->getFrameFocus();
} }
/** /**
@ -625,7 +671,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function setFrameFocusByIndex($choice) { function setFrameFocusByIndex($choice) {
return $this->_page->setFrameFocusByIndex($choice); return $this->page->setFrameFocusByIndex($choice);
} }
/** /**
@ -635,7 +681,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function setFrameFocus($name) { function setFrameFocus($name) {
return $this->_page->setFrameFocus($name); return $this->page->setFrameFocus($name);
} }
/** /**
@ -644,7 +690,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function clearFrameFocus() { function clearFrameFocus() {
return $this->_page->clearFrameFocus(); return $this->page->clearFrameFocus();
} }
/** /**
@ -653,7 +699,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getTransportError() { function getTransportError() {
return $this->_page->getTransportError(); return $this->page->getTransportError();
} }
/** /**
@ -662,7 +708,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getMimeType() { function getMimeType() {
return $this->_page->getMimeType(); return $this->page->getMimeType();
} }
/** /**
@ -671,7 +717,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getResponseCode() { function getResponseCode() {
return $this->_page->getResponseCode(); return $this->page->getResponseCode();
} }
/** /**
@ -681,7 +727,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getAuthentication() { function getAuthentication() {
return $this->_page->getAuthentication(); return $this->page->getAuthentication();
} }
/** /**
@ -691,7 +737,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getRealm() { function getRealm() {
return $this->_page->getRealm(); return $this->page->getRealm();
} }
/** /**
@ -701,7 +747,7 @@ class SimpleBrowser {
* a string. * a string.
*/ */
function getUrl() { function getUrl() {
$url = $this->_page->getUrl(); $url = $this->page->getUrl();
return $url ? $url->asString() : false; return $url ? $url->asString() : false;
} }
@ -710,7 +756,7 @@ class SimpleBrowser {
* @return string base URL * @return string base URL
*/ */
function getBaseUrl() { function getBaseUrl() {
$url = $this->_page->getBaseUrl(); $url = $this->page->getBaseUrl();
return $url ? $url->asString() : false; return $url ? $url->asString() : false;
} }
@ -720,7 +766,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getRequest() { function getRequest() {
return $this->_page->getRequest(); return $this->page->getRequest();
} }
/** /**
@ -729,7 +775,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getHeaders() { function getHeaders() {
return $this->_page->getHeaders(); return $this->page->getHeaders();
} }
/** /**
@ -738,7 +784,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getContent() { function getContent() {
return $this->_page->getRaw(); return $this->page->getRaw();
} }
/** /**
@ -747,7 +793,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getContentAsText() { function getContentAsText() {
return $this->_page->getText(); return $this->page->getText();
} }
/** /**
@ -756,7 +802,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getTitle() { function getTitle() {
return $this->_page->getTitle(); return $this->page->getTitle();
} }
/** /**
@ -766,7 +812,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getUrls() { function getUrls() {
return $this->_page->getUrls(); return $this->page->getUrls();
} }
/** /**
@ -777,7 +823,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function setField($label, $value, $position=false) { function setField($label, $value, $position=false) {
return $this->_page->setField(new SimpleByLabelOrName($label), $value, $position); return $this->page->setField(new SimpleByLabelOrName($label), $value, $position);
} }
/** /**
@ -789,7 +835,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function setFieldByName($name, $value, $position=false) { function setFieldByName($name, $value, $position=false) {
return $this->_page->setField(new SimpleByName($name), $value, $position); return $this->page->setField(new SimpleByName($name), $value, $position);
} }
/** /**
@ -800,7 +846,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function setFieldById($id, $value) { function setFieldById($id, $value) {
return $this->_page->setField(new SimpleById($id), $value); return $this->page->setField(new SimpleById($id), $value);
} }
/** /**
@ -813,7 +859,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getField($label) { function getField($label) {
return $this->_page->getField(new SimpleByLabelOrName($label)); return $this->page->getField(new SimpleByLabelOrName($label));
} }
/** /**
@ -826,7 +872,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getFieldByName($name) { function getFieldByName($name) {
return $this->_page->getField(new SimpleByName($name)); return $this->page->getField(new SimpleByName($name));
} }
/** /**
@ -838,7 +884,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getFieldById($id) { function getFieldById($id) {
return $this->_page->getField(new SimpleById($id)); return $this->page->getField(new SimpleById($id));
} }
/** /**
@ -851,10 +897,10 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function clickSubmit($label = 'Submit', $additional = false) { function clickSubmit($label = 'Submit', $additional = false) {
if (! ($form = &$this->_page->getFormBySubmit(new SimpleByLabel($label)))) { if (! ($form = $this->page->getFormBySubmit(new SimpleByLabel($label)))) {
return false; return false;
} }
$success = $this->_load( $success = $this->load(
$form->getAction(), $form->getAction(),
$form->submitButton(new SimpleByLabel($label), $additional)); $form->submitButton(new SimpleByLabel($label), $additional));
return ($success ? $this->getContent() : $success); return ($success ? $this->getContent() : $success);
@ -869,10 +915,10 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function clickSubmitByName($name, $additional = false) { function clickSubmitByName($name, $additional = false) {
if (! ($form = &$this->_page->getFormBySubmit(new SimpleByName($name)))) { if (! ($form = $this->page->getFormBySubmit(new SimpleByName($name)))) {
return false; return false;
} }
$success = $this->_load( $success = $this->load(
$form->getAction(), $form->getAction(),
$form->submitButton(new SimpleByName($name), $additional)); $form->submitButton(new SimpleByName($name), $additional));
return ($success ? $this->getContent() : $success); return ($success ? $this->getContent() : $success);
@ -887,15 +933,15 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function clickSubmitById($id, $additional = false) { function clickSubmitById($id, $additional = false) {
if (! ($form = &$this->_page->getFormBySubmit(new SimpleById($id)))) { if (! ($form = $this->page->getFormBySubmit(new SimpleById($id)))) {
return false; return false;
} }
$success = $this->_load( $success = $this->load(
$form->getAction(), $form->getAction(),
$form->submitButton(new SimpleById($id), $additional)); $form->submitButton(new SimpleById($id), $additional));
return ($success ? $this->getContent() : $success); return ($success ? $this->getContent() : $success);
} }
/** /**
* Tests to see if a submit button exists with this * Tests to see if a submit button exists with this
* label. * label.
@ -904,7 +950,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function isSubmit($label) { function isSubmit($label) {
return (boolean)$this->_page->getFormBySubmit(new SimpleByLabel($label)); return (boolean)$this->page->getFormBySubmit(new SimpleByLabel($label));
} }
/** /**
@ -921,10 +967,10 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function clickImage($label, $x = 1, $y = 1, $additional = false) { function clickImage($label, $x = 1, $y = 1, $additional = false) {
if (! ($form = &$this->_page->getFormByImage(new SimpleByLabel($label)))) { if (! ($form = $this->page->getFormByImage(new SimpleByLabel($label)))) {
return false; return false;
} }
$success = $this->_load( $success = $this->load(
$form->getAction(), $form->getAction(),
$form->submitImage(new SimpleByLabel($label), $x, $y, $additional)); $form->submitImage(new SimpleByLabel($label), $x, $y, $additional));
return ($success ? $this->getContent() : $success); return ($success ? $this->getContent() : $success);
@ -944,10 +990,10 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function clickImageByName($name, $x = 1, $y = 1, $additional = false) { function clickImageByName($name, $x = 1, $y = 1, $additional = false) {
if (! ($form = &$this->_page->getFormByImage(new SimpleByName($name)))) { if (! ($form = $this->page->getFormByImage(new SimpleByName($name)))) {
return false; return false;
} }
$success = $this->_load( $success = $this->load(
$form->getAction(), $form->getAction(),
$form->submitImage(new SimpleByName($name), $x, $y, $additional)); $form->submitImage(new SimpleByName($name), $x, $y, $additional));
return ($success ? $this->getContent() : $success); return ($success ? $this->getContent() : $success);
@ -966,15 +1012,15 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function clickImageById($id, $x = 1, $y = 1, $additional = false) { function clickImageById($id, $x = 1, $y = 1, $additional = false) {
if (! ($form = &$this->_page->getFormByImage(new SimpleById($id)))) { if (! ($form = $this->page->getFormByImage(new SimpleById($id)))) {
return false; return false;
} }
$success = $this->_load( $success = $this->load(
$form->getAction(), $form->getAction(),
$form->submitImage(new SimpleById($id), $x, $y, $additional)); $form->submitImage(new SimpleById($id), $x, $y, $additional));
return ($success ? $this->getContent() : $success); return ($success ? $this->getContent() : $success);
} }
/** /**
* Tests to see if an image exists with this * Tests to see if an image exists with this
* title or alt text. * title or alt text.
@ -983,7 +1029,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function isImage($label) { function isImage($label) {
return (boolean)$this->_page->getFormByImage(new SimpleByLabel($label)); return (boolean)$this->page->getFormByImage(new SimpleByLabel($label));
} }
/** /**
@ -993,13 +1039,13 @@ class SimpleBrowser {
* @return string/boolean Page on success. * @return string/boolean Page on success.
* @access public * @access public
*/ */
function submitFormById($id) { function submitFormById($id, $additional = false) {
if (! ($form = &$this->_page->getFormById($id))) { if (! ($form = $this->page->getFormById($id))) {
return false; return false;
} }
$success = $this->_load( $success = $this->load(
$form->getAction(), $form->getAction(),
$form->submit()); $form->submit($additional));
return ($success ? $this->getContent() : $success); return ($success ? $this->getContent() : $success);
} }
@ -1014,7 +1060,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getLink($label, $index = 0) { function getLink($label, $index = 0) {
$urls = $this->_page->getUrlsByLabel($label); $urls = $this->page->getUrlsByLabel($label);
if (count($urls) == 0) { if (count($urls) == 0) {
return false; return false;
} }
@ -1039,10 +1085,10 @@ class SimpleBrowser {
if ($url === false) { if ($url === false) {
return false; return false;
} }
$this->_load($url, new SimpleGetEncoding()); $this->load($url, new SimpleGetEncoding());
return $this->getContent(); return $this->getContent();
} }
/** /**
* Finds a link by id attribute. * Finds a link by id attribute.
* @param string $id ID attribute value. * @param string $id ID attribute value.
@ -1050,7 +1096,7 @@ class SimpleBrowser {
* @access public * @access public
*/ */
function getLinkById($id) { function getLinkById($id) {
return $this->_page->getUrlById($id); return $this->page->getUrlById($id);
} }
/** /**
@ -1063,7 +1109,7 @@ class SimpleBrowser {
if (! ($url = $this->getLinkById($id))) { if (! ($url = $this->getLinkById($id))) {
return false; return false;
} }
$this->_load($url, new SimpleGetEncoding()); $this->load($url, new SimpleGetEncoding());
return $this->getContent(); return $this->getContent();
} }

View File

@ -6,7 +6,7 @@
* @author Travis Swicegood <development@domain51.com> * @author Travis Swicegood <development@domain51.com>
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: collector.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: collector.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/** /**
@ -23,7 +23,7 @@ class SimpleCollector {
* @param string $path Path to normalise. * @param string $path Path to normalise.
* @return string Path without trailing slash. * @return string Path without trailing slash.
*/ */
function _removeTrailingSlash($path) { protected function removeTrailingSlash($path) {
if (substr($path, -1) == DIRECTORY_SEPARATOR) { if (substr($path, -1) == DIRECTORY_SEPARATOR) {
return substr($path, 0, -1); return substr($path, 0, -1);
} elseif (substr($path, -1) == '/') { } elseif (substr($path, -1) == '/') {
@ -40,13 +40,13 @@ class SimpleCollector {
* @see _attemptToAdd() * @see _attemptToAdd()
*/ */
function collect(&$test, $path) { function collect(&$test, $path) {
$path = $this->_removeTrailingSlash($path); $path = $this->removeTrailingSlash($path);
if ($handle = opendir($path)) { if ($handle = opendir($path)) {
while (($entry = readdir($handle)) !== false) { while (($entry = readdir($handle)) !== false) {
if ($this->_isHidden($entry)) { if ($this->isHidden($entry)) {
continue; continue;
} }
$this->_handle($test, $path . DIRECTORY_SEPARATOR . $entry); $this->handle($test, $path . DIRECTORY_SEPARATOR . $entry);
} }
closedir($handle); closedir($handle);
} }
@ -65,13 +65,13 @@ class SimpleCollector {
* @see collect() * @see collect()
* @access protected * @access protected
*/ */
function _handle(&$test, $file) { protected function handle(&$test, $file) {
if (is_dir($file)) { if (is_dir($file)) {
return; return;
} }
$test->addTestFile($file); $test->addFile($file);
} }
/** /**
* Tests for hidden files so as to skip them. Currently * Tests for hidden files so as to skip them. Currently
* only tests for Unix hidden files. * only tests for Unix hidden files.
@ -79,7 +79,7 @@ class SimpleCollector {
* @return boolean True if hidden file. * @return boolean True if hidden file.
* @access private * @access private
*/ */
function _isHidden($filename) { protected function isHidden($filename) {
return strncmp($filename, '.', 1) == 0; return strncmp($filename, '.', 1) == 0;
} }
} }
@ -93,7 +93,7 @@ class SimpleCollector {
* @see SimpleCollector * @see SimpleCollector
*/ */
class SimplePatternCollector extends SimpleCollector { class SimplePatternCollector extends SimpleCollector {
var $_pattern; private $pattern;
/** /**
* *
@ -101,8 +101,8 @@ class SimplePatternCollector extends SimpleCollector {
* See {@link http://us4.php.net/manual/en/reference.pcre.pattern.syntax.php PHP's PCRE} * See {@link http://us4.php.net/manual/en/reference.pcre.pattern.syntax.php PHP's PCRE}
* for full documentation of valid pattern.s * for full documentation of valid pattern.s
*/ */
function SimplePatternCollector($pattern = '/php$/i') { function __construct($pattern = '/php$/i') {
$this->_pattern = $pattern; $this->pattern = $pattern;
} }
/** /**
@ -113,9 +113,9 @@ class SimplePatternCollector extends SimpleCollector {
* @param string $path Directory to scan. * @param string $path Directory to scan.
* @access protected * @access protected
*/ */
function _handle(&$test, $filename) { protected function handle(&$test, $filename) {
if (preg_match($this->_pattern, $filename)) { if (preg_match($this->pattern, $filename)) {
parent::_handle($test, $filename); parent::handle($test, $filename);
} }
} }
} }

49
contrib/simpletest/simpletest/compatibility.php Normal file → Executable file
View File

@ -2,7 +2,7 @@
/** /**
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @version $Id: compatibility.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: compatibility.php 1900 2009-07-29 11:44:37Z lastcraft $
*/ */
/** /**
@ -11,22 +11,21 @@
* @package SimpleTest * @package SimpleTest
*/ */
class SimpleTestCompatibility { class SimpleTestCompatibility {
/** /**
* Creates a copy whether in PHP5 or PHP4. * Creates a copy whether in PHP5 or PHP4.
* @param object $object Thing to copy. * @param object $object Thing to copy.
* @return object A copy. * @return object A copy.
* @access public * @access public
* @static
*/ */
function copy($object) { static function copy($object) {
if (version_compare(phpversion(), '5') >= 0) { if (version_compare(phpversion(), '5') >= 0) {
eval('$copy = clone $object;'); eval('$copy = clone $object;');
return $copy; return $copy;
} }
return $object; return $object;
} }
/** /**
* Identity test. Drops back to equality + types for PHP5 * Identity test. Drops back to equality + types for PHP5
* objects as the === operator counts as the * objects as the === operator counts as the
@ -35,27 +34,25 @@ class SimpleTestCompatibility {
* @param mixed $second Comparison object. * @param mixed $second Comparison object.
* @return boolean True if identical. * @return boolean True if identical.
* @access public * @access public
* @static
*/ */
function isIdentical($first, $second) { static function isIdentical($first, $second) {
if (version_compare(phpversion(), '5') >= 0) { if (version_compare(phpversion(), '5') >= 0) {
return SimpleTestCompatibility::_isIdenticalType($first, $second); return SimpleTestCompatibility::isIdenticalType($first, $second);
} }
if ($first != $second) { if ($first != $second) {
return false; return false;
} }
return ($first === $second); return ($first === $second);
} }
/** /**
* Recursive type test. * Recursive type test.
* @param mixed $first Test subject. * @param mixed $first Test subject.
* @param mixed $second Comparison object. * @param mixed $second Comparison object.
* @return boolean True if same type. * @return boolean True if same type.
* @access private * @access private
* @static
*/ */
function _isIdenticalType($first, $second) { protected static function isIdenticalType($first, $second) {
if (gettype($first) != gettype($second)) { if (gettype($first) != gettype($second)) {
return false; return false;
} }
@ -63,33 +60,32 @@ class SimpleTestCompatibility {
if (get_class($first) != get_class($second)) { if (get_class($first) != get_class($second)) {
return false; return false;
} }
return SimpleTestCompatibility::_isArrayOfIdenticalTypes( return SimpleTestCompatibility::isArrayOfIdenticalTypes(
get_object_vars($first), (array) $first,
get_object_vars($second)); (array) $second);
} }
if (is_array($first) && is_array($second)) { if (is_array($first) && is_array($second)) {
return SimpleTestCompatibility::_isArrayOfIdenticalTypes($first, $second); return SimpleTestCompatibility::isArrayOfIdenticalTypes($first, $second);
} }
if ($first !== $second) { if ($first !== $second) {
return false; return false;
} }
return true; return true;
} }
/** /**
* Recursive type test for each element of an array. * Recursive type test for each element of an array.
* @param mixed $first Test subject. * @param mixed $first Test subject.
* @param mixed $second Comparison object. * @param mixed $second Comparison object.
* @return boolean True if identical. * @return boolean True if identical.
* @access private * @access private
* @static
*/ */
function _isArrayOfIdenticalTypes($first, $second) { protected static function isArrayOfIdenticalTypes($first, $second) {
if (array_keys($first) != array_keys($second)) { if (array_keys($first) != array_keys($second)) {
return false; return false;
} }
foreach (array_keys($first) as $key) { foreach (array_keys($first) as $key) {
$is_identical = SimpleTestCompatibility::_isIdenticalType( $is_identical = SimpleTestCompatibility::isIdenticalType(
$first[$key], $first[$key],
$second[$key]); $second[$key]);
if (! $is_identical) { if (! $is_identical) {
@ -98,16 +94,15 @@ class SimpleTestCompatibility {
} }
return true; return true;
} }
/** /**
* Test for two variables being aliases. * Test for two variables being aliases.
* @param mixed $first Test subject. * @param mixed $first Test subject.
* @param mixed $second Comparison object. * @param mixed $second Comparison object.
* @return boolean True if same. * @return boolean True if same.
* @access public * @access public
* @static
*/ */
function isReference(&$first, &$second) { static function isReference(&$first, &$second) {
if (version_compare(phpversion(), '5', '>=') && is_object($first)) { if (version_compare(phpversion(), '5', '>=') && is_object($first)) {
return ($first === $second); return ($first === $second);
} }
@ -124,7 +119,7 @@ class SimpleTestCompatibility {
$first = $temp; $first = $temp;
return $is_ref; return $is_ref;
} }
/** /**
* Test to see if an object is a member of a * Test to see if an object is a member of a
* class hiearchy. * class hiearchy.
@ -132,9 +127,8 @@ class SimpleTestCompatibility {
* @param string $class Root name of hiearchy. * @param string $class Root name of hiearchy.
* @return boolean True if class in hiearchy. * @return boolean True if class in hiearchy.
* @access public * @access public
* @static
*/ */
function isA($object, $class) { static function isA($object, $class) {
if (version_compare(phpversion(), '5') >= 0) { if (version_compare(phpversion(), '5') >= 0) {
if (! class_exists($class, false)) { if (! class_exists($class, false)) {
if (function_exists('interface_exists')) { if (function_exists('interface_exists')) {
@ -152,15 +146,14 @@ class SimpleTestCompatibility {
return ((strtolower($class) == get_class($object)) return ((strtolower($class) == get_class($object))
or (is_subclass_of($object, $class))); or (is_subclass_of($object, $class)));
} }
/** /**
* Sets a socket timeout for each chunk. * Sets a socket timeout for each chunk.
* @param resource $handle Socket handle. * @param resource $handle Socket handle.
* @param integer $timeout Limit in seconds. * @param integer $timeout Limit in seconds.
* @access public * @access public
* @static
*/ */
function setTimeout($handle, $timeout) { static function setTimeout($handle, $timeout) {
if (function_exists('stream_set_timeout')) { if (function_exists('stream_set_timeout')) {
stream_set_timeout($handle, $timeout, 0); stream_set_timeout($handle, $timeout, 0);
} elseif (function_exists('socket_set_timeout')) { } elseif (function_exists('socket_set_timeout')) {

View File

@ -3,7 +3,7 @@
* Base include file for SimpleTest * Base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
* @version $Id: cookies.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: cookies.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/**#@+ /**#@+
@ -21,13 +21,13 @@ require_once(dirname(__FILE__) . '/url.php');
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleCookie { class SimpleCookie {
var $_host; private $host;
var $_name; private $name;
var $_value; private $value;
var $_path; private $path;
var $_expiry; private $expiry;
var $_is_secure; private $is_secure;
/** /**
* Constructor. Sets the stored values. * Constructor. Sets the stored values.
* @param string $name Cookie key. * @param string $name Cookie key.
@ -36,20 +36,20 @@ class SimpleCookie {
* @param string $expiry Expiry date as string. * @param string $expiry Expiry date as string.
* @param boolean $is_secure Currently ignored. * @param boolean $is_secure Currently ignored.
*/ */
function SimpleCookie($name, $value = false, $path = false, $expiry = false, $is_secure = false) { function __construct($name, $value = false, $path = false, $expiry = false, $is_secure = false) {
$this->_host = false; $this->host = false;
$this->_name = $name; $this->name = $name;
$this->_value = $value; $this->value = $value;
$this->_path = ($path ? $this->_fixPath($path) : "/"); $this->path = ($path ? $this->fixPath($path) : "/");
$this->_expiry = false; $this->expiry = false;
if (is_string($expiry)) { if (is_string($expiry)) {
$this->_expiry = strtotime($expiry); $this->expiry = strtotime($expiry);
} elseif (is_integer($expiry)) { } elseif (is_integer($expiry)) {
$this->_expiry = $expiry; $this->expiry = $expiry;
} }
$this->_is_secure = $is_secure; $this->is_secure = $is_secure;
} }
/** /**
* Sets the host. The cookie rules determine * Sets the host. The cookie rules determine
* that the first two parts are taken for * that the first two parts are taken for
@ -61,13 +61,13 @@ class SimpleCookie {
* @access public * @access public
*/ */
function setHost($host) { function setHost($host) {
if ($host = $this->_truncateHost($host)) { if ($host = $this->truncateHost($host)) {
$this->_host = $host; $this->host = $host;
return true; return true;
} }
return false; return false;
} }
/** /**
* Accessor for the truncated host to which this * Accessor for the truncated host to which this
* cookie applies. * cookie applies.
@ -75,9 +75,9 @@ class SimpleCookie {
* @access public * @access public
*/ */
function getHost() { function getHost() {
return $this->_host; return $this->host;
} }
/** /**
* Test for a cookie being valid for a host name. * Test for a cookie being valid for a host name.
* @param string $host Host to test against. * @param string $host Host to test against.
@ -85,9 +85,9 @@ class SimpleCookie {
* here. * here.
*/ */
function isValidHost($host) { function isValidHost($host) {
return ($this->_truncateHost($host) === $this->getHost()); return ($this->truncateHost($host) === $this->getHost());
} }
/** /**
* Extracts just the domain part that determines a * Extracts just the domain part that determines a
* cookie's host validity. * cookie's host validity.
@ -95,7 +95,7 @@ class SimpleCookie {
* @return string Domain or false on a bad host. * @return string Domain or false on a bad host.
* @access private * @access private
*/ */
function _truncateHost($host) { protected function truncateHost($host) {
$tlds = SimpleUrl::getAllTopLevelDomains(); $tlds = SimpleUrl::getAllTopLevelDomains();
if (preg_match('/[a-z\-]+\.(' . $tlds . ')$/i', $host, $matches)) { if (preg_match('/[a-z\-]+\.(' . $tlds . ')$/i', $host, $matches)) {
return $matches[0]; return $matches[0];
@ -104,16 +104,16 @@ class SimpleCookie {
} }
return false; return false;
} }
/** /**
* Accessor for name. * Accessor for name.
* @return string Cookie key. * @return string Cookie key.
* @access public * @access public
*/ */
function getName() { function getName() {
return $this->_name; return $this->name;
} }
/** /**
* Accessor for value. A deleted cookie will * Accessor for value. A deleted cookie will
* have an empty string for this. * have an empty string for this.
@ -121,18 +121,18 @@ class SimpleCookie {
* @access public * @access public
*/ */
function getValue() { function getValue() {
return $this->_value; return $this->value;
} }
/** /**
* Accessor for path. * Accessor for path.
* @return string Valid cookie path. * @return string Valid cookie path.
* @access public * @access public
*/ */
function getPath() { function getPath() {
return $this->_path; return $this->path;
} }
/** /**
* Tests a path to see if the cookie applies * Tests a path to see if the cookie applies
* there. The test path must be longer or * there. The test path must be longer or
@ -143,23 +143,23 @@ class SimpleCookie {
*/ */
function isValidPath($path) { function isValidPath($path) {
return (strncmp( return (strncmp(
$this->_fixPath($path), $this->fixPath($path),
$this->getPath(), $this->getPath(),
strlen($this->getPath())) == 0); strlen($this->getPath())) == 0);
} }
/** /**
* Accessor for expiry. * Accessor for expiry.
* @return string Expiry string. * @return string Expiry string.
* @access public * @access public
*/ */
function getExpiry() { function getExpiry() {
if (! $this->_expiry) { if (! $this->expiry) {
return false; return false;
} }
return gmdate("D, d M Y H:i:s", $this->_expiry) . " GMT"; return gmdate("D, d M Y H:i:s", $this->expiry) . " GMT";
} }
/** /**
* Test to see if cookie is expired against * Test to see if cookie is expired against
* the cookie format time or timestamp. * the cookie format time or timestamp.
@ -172,15 +172,15 @@ class SimpleCookie {
* @access public * @access public
*/ */
function isExpired($now) { function isExpired($now) {
if (! $this->_expiry) { if (! $this->expiry) {
return true; return true;
} }
if (is_string($now)) { if (is_string($now)) {
$now = strtotime($now); $now = strtotime($now);
} }
return ($this->_expiry < $now); return ($this->expiry < $now);
} }
/** /**
* Ages the cookie by the specified number of * Ages the cookie by the specified number of
* seconds. * seconds.
@ -188,27 +188,27 @@ class SimpleCookie {
* @public * @public
*/ */
function agePrematurely($interval) { function agePrematurely($interval) {
if ($this->_expiry) { if ($this->expiry) {
$this->_expiry -= $interval; $this->expiry -= $interval;
} }
} }
/** /**
* Accessor for the secure flag. * Accessor for the secure flag.
* @return boolean True if cookie needs SSL. * @return boolean True if cookie needs SSL.
* @access public * @access public
*/ */
function isSecure() { function isSecure() {
return $this->_is_secure; return $this->is_secure;
} }
/** /**
* Adds a trailing and leading slash to the path * Adds a trailing and leading slash to the path
* if missing. * if missing.
* @param string $path Path to fix. * @param string $path Path to fix.
* @access private * @access private
*/ */
function _fixPath($path) { protected function fixPath($path) {
if (substr($path, 0, 1) != '/') { if (substr($path, 0, 1) != '/') {
$path = '/' . $path; $path = '/' . $path;
} }
@ -226,16 +226,16 @@ class SimpleCookie {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleCookieJar { class SimpleCookieJar {
var $_cookies; private $cookies;
/** /**
* Constructor. Jar starts empty. * Constructor. Jar starts empty.
* @access public * @access public
*/ */
function SimpleCookieJar() { function __construct() {
$this->_cookies = array(); $this->cookies = array();
} }
/** /**
* Removes expired and temporary cookies as if * Removes expired and temporary cookies as if
* the browser was closed and re-opened. * the browser was closed and re-opened.
@ -244,21 +244,21 @@ class SimpleCookieJar {
*/ */
function restartSession($date = false) { function restartSession($date = false) {
$surviving_cookies = array(); $surviving_cookies = array();
for ($i = 0; $i < count($this->_cookies); $i++) { for ($i = 0; $i < count($this->cookies); $i++) {
if (! $this->_cookies[$i]->getValue()) { if (! $this->cookies[$i]->getValue()) {
continue; continue;
} }
if (! $this->_cookies[$i]->getExpiry()) { if (! $this->cookies[$i]->getExpiry()) {
continue; continue;
} }
if ($date && $this->_cookies[$i]->isExpired($date)) { if ($date && $this->cookies[$i]->isExpired($date)) {
continue; continue;
} }
$surviving_cookies[] = $this->_cookies[$i]; $surviving_cookies[] = $this->cookies[$i];
} }
$this->_cookies = $surviving_cookies; $this->cookies = $surviving_cookies;
} }
/** /**
* Ages all cookies in the cookie jar. * Ages all cookies in the cookie jar.
* @param integer $interval The old session is moved * @param integer $interval The old session is moved
@ -268,11 +268,11 @@ class SimpleCookieJar {
* @access public * @access public
*/ */
function agePrematurely($interval) { function agePrematurely($interval) {
for ($i = 0; $i < count($this->_cookies); $i++) { for ($i = 0; $i < count($this->cookies); $i++) {
$this->_cookies[$i]->agePrematurely($interval); $this->cookies[$i]->agePrematurely($interval);
} }
} }
/** /**
* Sets an additional cookie. If a cookie has * Sets an additional cookie. If a cookie has
* the same name and path it is replaced. * the same name and path it is replaced.
@ -288,9 +288,9 @@ class SimpleCookieJar {
if ($host) { if ($host) {
$cookie->setHost($host); $cookie->setHost($host);
} }
$this->_cookies[$this->_findFirstMatch($cookie)] = $cookie; $this->cookies[$this->findFirstMatch($cookie)] = $cookie;
} }
/** /**
* Finds a matching cookie to write over or the * Finds a matching cookie to write over or the
* first empty slot if none. * first empty slot if none.
@ -298,20 +298,20 @@ class SimpleCookieJar {
* @return integer Available slot. * @return integer Available slot.
* @access private * @access private
*/ */
function _findFirstMatch($cookie) { protected function findFirstMatch($cookie) {
for ($i = 0; $i < count($this->_cookies); $i++) { for ($i = 0; $i < count($this->cookies); $i++) {
$is_match = $this->_isMatch( $is_match = $this->isMatch(
$cookie, $cookie,
$this->_cookies[$i]->getHost(), $this->cookies[$i]->getHost(),
$this->_cookies[$i]->getPath(), $this->cookies[$i]->getPath(),
$this->_cookies[$i]->getName()); $this->cookies[$i]->getName());
if ($is_match) { if ($is_match) {
return $i; return $i;
} }
} }
return count($this->_cookies); return count($this->cookies);
} }
/** /**
* Reads the most specific cookie value from the * Reads the most specific cookie value from the
* browser cookies. Looks for the longest path that * browser cookies. Looks for the longest path that
@ -325,8 +325,8 @@ class SimpleCookieJar {
*/ */
function getCookieValue($host, $path, $name) { function getCookieValue($host, $path, $name) {
$longest_path = ''; $longest_path = '';
foreach ($this->_cookies as $cookie) { foreach ($this->cookies as $cookie) {
if ($this->_isMatch($cookie, $host, $path, $name)) { if ($this->isMatch($cookie, $host, $path, $name)) {
if (strlen($cookie->getPath()) > strlen($longest_path)) { if (strlen($cookie->getPath()) > strlen($longest_path)) {
$value = $cookie->getValue(); $value = $cookie->getValue();
$longest_path = $cookie->getPath(); $longest_path = $cookie->getPath();
@ -335,7 +335,7 @@ class SimpleCookieJar {
} }
return (isset($value) ? $value : false); return (isset($value) ? $value : false);
} }
/** /**
* Tests cookie for matching against search * Tests cookie for matching against search
* criteria. * criteria.
@ -347,7 +347,7 @@ class SimpleCookieJar {
* @return boolean True if matched. * @return boolean True if matched.
* @access private * @access private
*/ */
function _isMatch($cookie, $host, $path, $name) { protected function isMatch($cookie, $host, $path, $name) {
if ($cookie->getName() != $name) { if ($cookie->getName() != $name) {
return false; return false;
} }
@ -359,7 +359,7 @@ class SimpleCookieJar {
} }
return true; return true;
} }
/** /**
* Uses a URL to sift relevant cookies by host and * Uses a URL to sift relevant cookies by host and
* path. Results are list of strings of form "name=value". * path. Results are list of strings of form "name=value".
@ -369,8 +369,8 @@ class SimpleCookieJar {
*/ */
function selectAsPairs($url) { function selectAsPairs($url) {
$pairs = array(); $pairs = array();
foreach ($this->_cookies as $cookie) { foreach ($this->cookies as $cookie) {
if ($this->_isMatch($cookie, $url->getHost(), $url->getPath(), $cookie->getName())) { if ($this->isMatch($cookie, $url->getHost(), $url->getPath(), $cookie->getName())) {
$pairs[] = $cookie->getName() . '=' . $cookie->getValue(); $pairs[] = $cookie->getName() . '=' . $cookie->getValue();
} }
} }

View File

@ -3,7 +3,7 @@
* Optional include file for SimpleTest * Optional include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: default_reporter.php 1704 2008-03-25 00:47:04Z lastcraft $ * @version $Id: default_reporter.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/**#@+ /**#@+
@ -23,75 +23,101 @@ require_once(dirname(__FILE__) . '/xml.php');
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SimpleCommandLineParser { class SimpleCommandLineParser {
var $_to_property = array( private $to_property = array(
'case' => '_case', 'c' => '_case', 'case' => 'case', 'c' => 'case',
'test' => '_test', 't' => '_test', 'test' => 'test', 't' => 'test',
'xml' => '_xml', 'x' => '_xml'); );
var $_case = ''; private $case = '';
var $_test = ''; private $test = '';
var $_xml = false; private $xml = false;
var $_no_skips = false; private $help = false;
private $no_skips = false;
/** /**
* Parses raw command line arguments into object properties. * Parses raw command line arguments into object properties.
* @param string $arguments Raw commend line arguments. * @param string $arguments Raw commend line arguments.
*/ */
function SimpleCommandLineParser($arguments) { function __construct($arguments) {
if (! is_array($arguments)) { if (! is_array($arguments)) {
return; return;
} }
foreach ($arguments as $i => $argument) { foreach ($arguments as $i => $argument) {
if (preg_match('/^--?(test|case|t|c)=(.+)$/', $argument, $matches)) { if (preg_match('/^--?(test|case|t|c)=(.+)$/', $argument, $matches)) {
$property = $this->_to_property[$matches[1]]; $property = $this->to_property[$matches[1]];
$this->$property = $matches[2]; $this->$property = $matches[2];
} elseif (preg_match('/^--?(test|case|t|c)$/', $argument, $matches)) { } elseif (preg_match('/^--?(test|case|t|c)$/', $argument, $matches)) {
$property = $this->_to_property[$matches[1]]; $property = $this->to_property[$matches[1]];
if (isset($arguments[$i + 1])) { if (isset($arguments[$i + 1])) {
$this->$property = $arguments[$i + 1]; $this->$property = $arguments[$i + 1];
} }
} elseif (preg_match('/^--?(xml|x)$/', $argument)) { } elseif (preg_match('/^--?(xml|x)$/', $argument)) {
$this->_xml = true; $this->xml = true;
} elseif (preg_match('/^--?(no-skip|no-skips|s)$/', $argument)) { } elseif (preg_match('/^--?(no-skip|no-skips|s)$/', $argument)) {
$this->_no_skips = true; $this->no_skips = true;
} elseif (preg_match('/^--?(help|h)$/', $argument)) {
$this->help = true;
} }
} }
} }
/** /**
* Run only this test. * Run only this test.
* @return string Test name to run. * @return string Test name to run.
* @access public
*/ */
function getTest() { function getTest() {
return $this->_test; return $this->test;
} }
/** /**
* Run only this test suite. * Run only this test suite.
* @return string Test class name to run. * @return string Test class name to run.
* @access public
*/ */
function getTestCase() { function getTestCase() {
return $this->_case; return $this->case;
} }
/** /**
* Output should be XML or not. * Output should be XML or not.
* @return boolean True if XML desired. * @return boolean True if XML desired.
* @access public
*/ */
function isXml() { function isXml() {
return $this->_xml; return $this->xml;
} }
/** /**
* Output should suppress skip messages. * Output should suppress skip messages.
* @return boolean True for no skips. * @return boolean True for no skips.
* @access public
*/ */
function noSkips() { function noSkips() {
return $this->_no_skips; return $this->no_skips;
} }
/**
* Output should be a help message. Disabled during XML mode.
* @return boolean True if help message desired.
*/
function help() {
return $this->help && ! $this->xml;
}
/**
* Returns plain-text help message for command line runner.
* @return string String help message
*/
function getHelpText() {
return <<<HELP
SimpleTest command line default reporter (autorun)
Usage: php <test_file> [args...]
-c <class> Run only the test-case <class>
-t <method> Run only the test method <method>
-s Suppress skip messages
-x Return test results in XML
-h Display this help message
HELP;
}
} }
/** /**
@ -102,32 +128,36 @@ class SimpleCommandLineParser {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class DefaultReporter extends SimpleReporterDecorator { class DefaultReporter extends SimpleReporterDecorator {
/** /**
* Assembles the appopriate reporter for the environment. * Assembles the appropriate reporter for the environment.
*/ */
function DefaultReporter() { function __construct() {
if (SimpleReporter::inCli()) { if (SimpleReporter::inCli()) {
global $argv; $parser = new SimpleCommandLineParser($_SERVER['argv']);
$parser = new SimpleCommandLineParser($argv);
$interfaces = $parser->isXml() ? array('XmlReporter') : array('TextReporter'); $interfaces = $parser->isXml() ? array('XmlReporter') : array('TextReporter');
$reporter = &new SelectiveReporter( if ($parser->help()) {
// I'm not sure if we should do the echo'ing here -- ezyang
echo $parser->getHelpText();
exit(1);
}
$reporter = new SelectiveReporter(
SimpleTest::preferred($interfaces), SimpleTest::preferred($interfaces),
$parser->getTestCase(), $parser->getTestCase(),
$parser->getTest()); $parser->getTest());
if ($parser->noSkips()) { if ($parser->noSkips()) {
$reporter = &new NoSkipsReporter($reporter); $reporter = new NoSkipsReporter($reporter);
} }
} else { } else {
$reporter = &new SelectiveReporter( $reporter = new SelectiveReporter(
SimpleTest::preferred('HtmlReporter'), SimpleTest::preferred('HtmlReporter'),
@$_GET['c'], @$_GET['c'],
@$_GET['t']); @$_GET['t']);
if (@$_GET['skips'] == 'no' || @$_GET['show-skips'] == 'no') { if (@$_GET['skips'] == 'no' || @$_GET['show-skips'] == 'no') {
$reporter = &new NoSkipsReporter($reporter); $reporter = new NoSkipsReporter($reporter);
} }
} }
$this->SimpleReporterDecorator($reporter); parent::__construct($reporter);
} }
} }
?> ?>

38
contrib/simpletest/simpletest/detached.php Normal file → Executable file
View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: detached.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: detached.php 1784 2008-04-26 13:07:14Z pp11 $
*/ */
/**#@+ /**#@+
@ -19,9 +19,9 @@ require_once(dirname(__FILE__) . '/shell_tester.php');
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class DetachedTestCase { class DetachedTestCase {
var $_command; private $command;
var $_dry_command; private $dry_command;
var $_size; private $size;
/** /**
* Sets the location of the remote test. * Sets the location of the remote test.
@ -29,10 +29,10 @@ class DetachedTestCase {
* @param string $dry_command Script for dry run. * @param string $dry_command Script for dry run.
* @access public * @access public
*/ */
function DetachedTestCase($command, $dry_command = false) { function __construct($command, $dry_command = false) {
$this->_command = $command; $this->command = $command;
$this->_dry_command = $dry_command ? $dry_command : $command; $this->dry_command = $dry_command ? $dry_command : $command;
$this->_size = false; $this->size = false;
} }
/** /**
@ -41,7 +41,7 @@ class DetachedTestCase {
* @access public * @access public
*/ */
function getLabel() { function getLabel() {
return $this->_command; return $this->command;
} }
/** /**
@ -54,10 +54,10 @@ class DetachedTestCase {
*/ */
function run(&$reporter) { function run(&$reporter) {
$shell = &new SimpleShell(); $shell = &new SimpleShell();
$shell->execute($this->_command); $shell->execute($this->command);
$parser = &$this->_createParser($reporter); $parser = &$this->createParser($reporter);
if (! $parser->parse($shell->getOutput())) { if (! $parser->parse($shell->getOutput())) {
trigger_error('Cannot parse incoming XML from [' . $this->_command . ']'); trigger_error('Cannot parse incoming XML from [' . $this->command . ']');
return false; return false;
} }
return true; return true;
@ -69,18 +69,18 @@ class DetachedTestCase {
* @access public * @access public
*/ */
function getSize() { function getSize() {
if ($this->_size === false) { if ($this->size === false) {
$shell = &new SimpleShell(); $shell = &new SimpleShell();
$shell->execute($this->_dry_command); $shell->execute($this->dry_command);
$reporter = &new SimpleReporter(); $reporter = &new SimpleReporter();
$parser = &$this->_createParser($reporter); $parser = &$this->createParser($reporter);
if (! $parser->parse($shell->getOutput())) { if (! $parser->parse($shell->getOutput())) {
trigger_error('Cannot parse incoming XML from [' . $this->_dry_command . ']'); trigger_error('Cannot parse incoming XML from [' . $this->dry_command . ']');
return false; return false;
} }
$this->_size = $reporter->getTestCaseCount(); $this->size = $reporter->getTestCaseCount();
} }
return $this->_size; return $this->size;
} }
/** /**
@ -89,7 +89,7 @@ class DetachedTestCase {
* @return SimpleTestXmlListener XML reader. * @return SimpleTestXmlListener XML reader.
* @access protected * @access protected
*/ */
function &_createParser(&$reporter) { protected function &createParser(&$reporter) {
return new SimpleTestXmlParser($reporter); return new SimpleTestXmlParser($reporter);
} }
} }

137
contrib/simpletest/simpletest/dumper.php Normal file → Executable file
View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: dumper.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: dumper.php 1909 2009-07-29 15:58:11Z dgheath $
*/ */
/** /**
* does type matter * does type matter
@ -18,7 +18,7 @@ if (! defined('TYPE_MATTERS')) {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SimpleDumper { class SimpleDumper {
/** /**
* Renders a variable in a shorter form than print_r(). * Renders a variable in a shorter form than print_r().
* @param mixed $value Variable to render as a string. * @param mixed $value Variable to render as a string.
@ -43,7 +43,7 @@ class SimpleDumper {
} }
return "Unknown"; return "Unknown";
} }
/** /**
* Gets the string representation of a type. * Gets the string representation of a type.
* @param mixed $value Variable to check against. * @param mixed $value Variable to check against.
@ -83,7 +83,7 @@ class SimpleDumper {
*/ */
function describeDifference($first, $second, $identical = false) { function describeDifference($first, $second, $identical = false) {
if ($identical) { if ($identical) {
if (! $this->_isTypeMatch($first, $second)) { if (! $this->isTypeMatch($first, $second)) {
return "with type mismatch as [" . $this->describeValue($first) . return "with type mismatch as [" . $this->describeValue($first) .
"] does not match [" . $this->describeValue($second) . "]"; "] does not match [" . $this->describeValue($second) . "]";
} }
@ -92,10 +92,10 @@ class SimpleDumper {
if ($type == "Unknown") { if ($type == "Unknown") {
return "with unknown type"; return "with unknown type";
} }
$method = '_describe' . $type . 'Difference'; $method = 'describe' . $type . 'Difference';
return $this->$method($first, $second, $identical); return $this->$method($first, $second, $identical);
} }
/** /**
* Tests to see if types match. * Tests to see if types match.
* @param mixed $first First variable. * @param mixed $first First variable.
@ -103,7 +103,7 @@ class SimpleDumper {
* @return boolean True if matches. * @return boolean True if matches.
* @access private * @access private
*/ */
function _isTypeMatch($first, $second) { protected function isTypeMatch($first, $second) {
return ($this->getType($first) == $this->getType($second)); return ($this->getType($first) == $this->getType($second));
} }
@ -128,7 +128,7 @@ class SimpleDumper {
$value = substr($value, $start, $size); $value = substr($value, $start, $size);
return ($start > 0 ? "..." : "") . $value . ($start + $size < $length ? "..." : ""); return ($start > 0 ? "..." : "") . $value . ($start + $size < $length ? "..." : "");
} }
/** /**
* Creates a human readable description of the * Creates a human readable description of the
* difference between two variables. The minimal * difference between two variables. The minimal
@ -138,12 +138,12 @@ class SimpleDumper {
* @return string Human readable description. * @return string Human readable description.
* @access private * @access private
*/ */
function _describeGenericDifference($first, $second) { protected function describeGenericDifference($first, $second) {
return "as [" . $this->describeValue($first) . return "as [" . $this->describeValue($first) .
"] does not match [" . "] does not match [" .
$this->describeValue($second) . "]"; $this->describeValue($second) . "]";
} }
/** /**
* Creates a human readable description of the * Creates a human readable description of the
* difference between a null and another variable. * difference between a null and another variable.
@ -153,10 +153,10 @@ class SimpleDumper {
* @return string Human readable description. * @return string Human readable description.
* @access private * @access private
*/ */
function _describeNullDifference($first, $second, $identical) { protected function describeNullDifference($first, $second, $identical) {
return $this->_describeGenericDifference($first, $second); return $this->describeGenericDifference($first, $second);
} }
/** /**
* Creates a human readable description of the * Creates a human readable description of the
* difference between a boolean and another variable. * difference between a boolean and another variable.
@ -166,10 +166,10 @@ class SimpleDumper {
* @return string Human readable description. * @return string Human readable description.
* @access private * @access private
*/ */
function _describeBooleanDifference($first, $second, $identical) { protected function describeBooleanDifference($first, $second, $identical) {
return $this->_describeGenericDifference($first, $second); return $this->describeGenericDifference($first, $second);
} }
/** /**
* Creates a human readable description of the * Creates a human readable description of the
* difference between a string and another variable. * difference between a string and another variable.
@ -179,18 +179,18 @@ class SimpleDumper {
* @return string Human readable description. * @return string Human readable description.
* @access private * @access private
*/ */
function _describeStringDifference($first, $second, $identical) { protected function describeStringDifference($first, $second, $identical) {
if (is_object($second) || is_array($second)) { if (is_object($second) || is_array($second)) {
return $this->_describeGenericDifference($first, $second); return $this->describeGenericDifference($first, $second);
} }
$position = $this->_stringDiffersAt($first, $second); $position = $this->stringDiffersAt($first, $second);
$message = "at character $position"; $message = "at character $position";
$message .= " with [" . $message .= " with [" .
$this->clipString($first, 200, $position) . "] and [" . $this->clipString($first, 200, $position) . "] and [" .
$this->clipString($second, 200, $position) . "]"; $this->clipString($second, 200, $position) . "]";
return $message; return $message;
} }
/** /**
* Creates a human readable description of the * Creates a human readable description of the
* difference between an integer and another variable. * difference between an integer and another variable.
@ -200,16 +200,16 @@ class SimpleDumper {
* @return string Human readable description. * @return string Human readable description.
* @access private * @access private
*/ */
function _describeIntegerDifference($first, $second, $identical) { protected function describeIntegerDifference($first, $second, $identical) {
if (is_object($second) || is_array($second)) { if (is_object($second) || is_array($second)) {
return $this->_describeGenericDifference($first, $second); return $this->describeGenericDifference($first, $second);
} }
return "because [" . $this->describeValue($first) . return "because [" . $this->describeValue($first) .
"] differs from [" . "] differs from [" .
$this->describeValue($second) . "] by " . $this->describeValue($second) . "] by " .
abs($first - $second); abs($first - $second);
} }
/** /**
* Creates a human readable description of the * Creates a human readable description of the
* difference between two floating point numbers. * difference between two floating point numbers.
@ -219,16 +219,16 @@ class SimpleDumper {
* @return string Human readable description. * @return string Human readable description.
* @access private * @access private
*/ */
function _describeFloatDifference($first, $second, $identical) { protected function describeFloatDifference($first, $second, $identical) {
if (is_object($second) || is_array($second)) { if (is_object($second) || is_array($second)) {
return $this->_describeGenericDifference($first, $second); return $this->describeGenericDifference($first, $second);
} }
return "because [" . $this->describeValue($first) . return "because [" . $this->describeValue($first) .
"] differs from [" . "] differs from [" .
$this->describeValue($second) . "] by " . $this->describeValue($second) . "] by " .
abs($first - $second); abs($first - $second);
} }
/** /**
* Creates a human readable description of the * Creates a human readable description of the
* difference between two arrays. * difference between two arrays.
@ -238,11 +238,11 @@ class SimpleDumper {
* @return string Human readable description. * @return string Human readable description.
* @access private * @access private
*/ */
function _describeArrayDifference($first, $second, $identical) { protected function describeArrayDifference($first, $second, $identical) {
if (! is_array($second)) { if (! is_array($second)) {
return $this->_describeGenericDifference($first, $second); return $this->describeGenericDifference($first, $second);
} }
if (! $this->_isMatchingKeys($first, $second, $identical)) { if (! $this->isMatchingKeys($first, $second, $identical)) {
return "as key list [" . return "as key list [" .
implode(", ", array_keys($first)) . "] does not match key list [" . implode(", ", array_keys($first)) . "] does not match key list [" .
implode(", ", array_keys($second)) . "]"; implode(", ", array_keys($second)) . "]";
@ -261,7 +261,7 @@ class SimpleDumper {
} }
return ""; return "";
} }
/** /**
* Compares two arrays to see if their key lists match. * Compares two arrays to see if their key lists match.
* For an identical match, the ordering and types of the keys * For an identical match, the ordering and types of the keys
@ -272,7 +272,7 @@ class SimpleDumper {
* @return boolean True if matching. * @return boolean True if matching.
* @access private * @access private
*/ */
function _isMatchingKeys($first, $second, $identical) { protected function isMatchingKeys($first, $second, $identical) {
$first_keys = array_keys($first); $first_keys = array_keys($first);
$second_keys = array_keys($second); $second_keys = array_keys($second);
if ($identical) { if ($identical) {
@ -282,7 +282,7 @@ class SimpleDumper {
sort($second_keys); sort($second_keys);
return ($first_keys == $second_keys); return ($first_keys == $second_keys);
} }
/** /**
* Creates a human readable description of the * Creates a human readable description of the
* difference between a resource and another variable. * difference between a resource and another variable.
@ -292,10 +292,10 @@ class SimpleDumper {
* @return string Human readable description. * @return string Human readable description.
* @access private * @access private
*/ */
function _describeResourceDifference($first, $second, $identical) { protected function describeResourceDifference($first, $second, $identical) {
return $this->_describeGenericDifference($first, $second); return $this->describeGenericDifference($first, $second);
} }
/** /**
* Creates a human readable description of the * Creates a human readable description of the
* difference between two objects. * difference between two objects.
@ -303,18 +303,66 @@ class SimpleDumper {
* @param mixed $second Object to compare with. * @param mixed $second Object to compare with.
* @param boolean $identical If true then type anomolies count. * @param boolean $identical If true then type anomolies count.
* @return string Human readable description. * @return string Human readable description.
* @access private
*/ */
function _describeObjectDifference($first, $second, $identical) { protected function describeObjectDifference($first, $second, $identical) {
if (! is_object($second)) { if (! is_object($second)) {
return $this->_describeGenericDifference($first, $second); return $this->describeGenericDifference($first, $second);
} }
return $this->_describeArrayDifference( return $this->describeArrayDifference(
get_object_vars($first), $this->getMembers($first),
get_object_vars($second), $this->getMembers($second),
$identical); $identical);
} }
/**
* Get all members of an object including private and protected ones.
* A safer form of casting to an array.
* @param object $object Object to list members of,
* including private ones.
* @return array Names and values in the object.
*/
protected function getMembers($object) {
$reflection = new ReflectionObject($object);
$members = array();
foreach ($reflection->getProperties() as $property) {
if (method_exists($property, 'setAccessible')) {
$property->setAccessible(true);
}
try {
$members[$property->getName()] = $property->getValue($object);
} catch (ReflectionException $e) {
$members[$property->getName()] =
$this->getPrivatePropertyNoMatterWhat($property->getName(), $object);
}
}
return $members;
}
/**
* Extracts a private member's value when reflection won't play ball.
* @param string $name Property name.
* @param object $object Object to read.
* @return mixed Value of property.
*/
private function getPrivatePropertyNoMatterWhat($name, $object) {
foreach ((array)$object as $mangled_name => $value) {
if ($this->unmangle($mangled_name) == $name) {
return $value;
}
}
}
/**
* Removes crud from property name after it's been converted
* to an array.
* @param string $mangled Name from array cast.
* @return string Cleaned up name.
*/
function unmangle($mangled) {
$parts = preg_split('/[^a-zA-Z0-9_\x7f-\xff]+/', $mangled);
return array_pop($parts);
}
/** /**
* Find the first character position that differs * Find the first character position that differs
* in two strings by binary chop. * in two strings by binary chop.
@ -324,7 +372,7 @@ class SimpleDumper {
* character. * character.
* @access private * @access private
*/ */
function _stringDiffersAt($first, $second) { protected function stringDiffersAt($first, $second) {
if (! $first || ! $second) { if (! $first || ! $second) {
return 0; return 0;
} }
@ -341,13 +389,12 @@ class SimpleDumper {
} }
return $position; return $position;
} }
/** /**
* Sends a formatted dump of a variable to a string. * Sends a formatted dump of a variable to a string.
* @param mixed $variable Variable to display. * @param mixed $variable Variable to display.
* @return string Output from print_r(). * @return string Output from print_r().
* @access public * @access public
* @static
*/ */
function dump($variable) { function dump($variable) {
ob_start(); ob_start();

View File

@ -1,9 +1,9 @@
<?php <?php
/** /**
* base include file for eclipse plugin * base include file for eclipse plugin
* @package SimpleTest * @package SimpleTest
* @subpackage Eclipse * @subpackage Eclipse
* @version $Id: eclipse.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: eclipse.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/**#@+ /**#@+
* simpletest include files * simpletest include files
@ -16,28 +16,28 @@ include_once 'mock_objects.php';
/**#@-*/ /**#@-*/
/** /**
* base reported class for eclipse plugin * base reported class for eclipse plugin
* @package SimpleTest * @package SimpleTest
* @subpackage Eclipse * @subpackage Eclipse
*/ */
class EclipseReporter extends SimpleScorer { class EclipseReporter extends SimpleScorer {
/** /**
* Reporter to be run inside of Eclipse interface. * Reporter to be run inside of Eclipse interface.
* @param object $listener Eclipse listener (?). * @param object $listener Eclipse listener (?).
* @param boolean $cc Whether to include test coverage. * @param boolean $cc Whether to include test coverage.
*/ */
function EclipseReporter(&$listener, $cc=false){ function __construct(&$listener, $cc=false){
$this->_listener = &$listener; $this->listener = &$listener;
$this->SimpleScorer(); $this->SimpleScorer();
$this->_case = ""; $this->case = "";
$this->_group = ""; $this->group = "";
$this->_method = ""; $this->method = "";
$this->_cc = $cc; $this->cc = $cc;
$this->_error = false; $this->error = false;
$this->_fail = false; $this->fail = false;
} }
/** /**
* Means to display human readable object comparisons. * Means to display human readable object comparisons.
* @return SimpleDumper Visual comparer. * @return SimpleDumper Visual comparer.
@ -45,7 +45,7 @@ class EclipseReporter extends SimpleScorer {
function getDumper() { function getDumper() {
return new SimpleDumper(); return new SimpleDumper();
} }
/** /**
* Localhost connection from Eclipse. * Localhost connection from Eclipse.
* @param integer $port Port to connect to Eclipse. * @param integer $port Port to connect to Eclipse.
@ -56,7 +56,7 @@ class EclipseReporter extends SimpleScorer {
$tmplistener = &new SimpleSocket($host, $port, 5); $tmplistener = &new SimpleSocket($host, $port, 5);
return $tmplistener; return $tmplistener;
} }
/** /**
* Wraps the test in an output buffer. * Wraps the test in an output buffer.
* @param SimpleInvoker $invoker Current test runner. * @param SimpleInvoker $invoker Current test runner.
@ -64,10 +64,10 @@ class EclipseReporter extends SimpleScorer {
* @access public * @access public
*/ */
function &createInvoker(&$invoker){ function &createInvoker(&$invoker){
$eclinvoker = &new EclipseInvoker($invoker, $this->_listener); $eclinvoker = &new EclipseInvoker($invoker, $this->listener);
return $eclinvoker; return $eclinvoker;
} }
/** /**
* C style escaping. * C style escaping.
* @param string $raw String with backslashes, quotes and whitespace. * @param string $raw String with backslashes, quotes and whitespace.
@ -78,7 +78,7 @@ class EclipseReporter extends SimpleScorer {
$replace = array('\\\\','\"','\/','\b','\f','\n','\r','\t'); $replace = array('\\\\','\"','\/','\b','\f','\n','\r','\t');
return str_replace($needle, $replace, $raw); return str_replace($needle, $replace, $raw);
} }
/** /**
* Stash the first passing item. Clicking the test * Stash the first passing item. Clicking the test
* item goes to first pass. * item goes to first pass.
@ -86,12 +86,12 @@ class EclipseReporter extends SimpleScorer {
* @access public * @access public
*/ */
function paintPass($message){ function paintPass($message){
if (! $this->_pass){ if (! $this->pass){
$this->_message = $this->escapeVal($message); $this->message = $this->escapeVal($message);
} }
$this->_pass = true; $this->pass = true;
} }
/** /**
* Stash the first failing item. Clicking the test * Stash the first failing item. Clicking the test
* item goes to first fail. * item goes to first fail.
@ -100,13 +100,13 @@ class EclipseReporter extends SimpleScorer {
*/ */
function paintFail($message){ function paintFail($message){
//only get the first failure or error //only get the first failure or error
if (! $this->_fail && ! $this->_error){ if (! $this->fail && ! $this->error){
$this->_fail = true; $this->fail = true;
$this->_message = $this->escapeVal($message); $this->message = $this->escapeVal($message);
$this->_listener->write('{status:"fail",message:"'.$this->_message.'",group:"'.$this->_group.'",case:"'.$this->_case.'",method:"'.$this->_method.'"}'); $this->listener->write('{status:"fail",message:"'.$this->message.'",group:"'.$this->group.'",case:"'.$this->case.'",method:"'.$this->method.'"}');
} }
} }
/** /**
* Stash the first error. Clicking the test * Stash the first error. Clicking the test
* item goes to first error. * item goes to first error.
@ -114,14 +114,14 @@ class EclipseReporter extends SimpleScorer {
* @access public * @access public
*/ */
function paintError($message){ function paintError($message){
if (! $this->_fail && ! $this->_error){ if (! $this->fail && ! $this->error){
$this->_error = true; $this->error = true;
$this->_message = $this->escapeVal($message); $this->message = $this->escapeVal($message);
$this->_listener->write('{status:"error",message:"'.$this->_message.'",group:"'.$this->_group.'",case:"'.$this->_case.'",method:"'.$this->_method.'"}'); $this->listener->write('{status:"error",message:"'.$this->message.'",group:"'.$this->group.'",case:"'.$this->case.'",method:"'.$this->method.'"}');
} }
} }
/** /**
* Stash the first exception. Clicking the test * Stash the first exception. Clicking the test
* item goes to first message. * item goes to first message.
@ -129,19 +129,19 @@ class EclipseReporter extends SimpleScorer {
* @access public * @access public
*/ */
function paintException($exception){ function paintException($exception){
if (! $this->_fail && ! $this->_error){ if (! $this->fail && ! $this->error){
$this->_error = true; $this->error = true;
$message = 'Unexpected exception of type[' . get_class($exception) . $message = 'Unexpected exception of type[' . get_class($exception) .
'] with message [' . $exception->getMessage() . '] in [' . '] with message [' . $exception->getMessage() . '] in [' .
$exception->getFile() .' line '. $exception->getLine() . ']'; $exception->getFile() .' line '. $exception->getLine() . ']';
$this->_message = $this->escapeVal($message); $this->message = $this->escapeVal($message);
$this->_listener->write( $this->listener->write(
'{status:"error",message:"' . $this->_message . '",group:"' . '{status:"error",message:"' . $this->message . '",group:"' .
$this->_group . '",case:"' . $this->_case . '",method:"' . $this->_method $this->group . '",case:"' . $this->case . '",method:"' . $this->method
. '"}'); . '"}');
} }
} }
/** /**
* We don't display any special header. * We don't display any special header.
@ -159,7 +159,7 @@ class EclipseReporter extends SimpleScorer {
*/ */
function paintFooter($test_name) { function paintFooter($test_name) {
} }
/** /**
* Paints nothing at the start of a test method, but stash * Paints nothing at the start of a test method, but stash
* the method name for later. * the method name for later.
@ -167,46 +167,46 @@ class EclipseReporter extends SimpleScorer {
* @access public * @access public
*/ */
function paintMethodStart($method) { function paintMethodStart($method) {
$this->_pass = false; $this->pass = false;
$this->_fail = false; $this->fail = false;
$this->_error = false; $this->error = false;
$this->_method = $this->escapeVal($method); $this->method = $this->escapeVal($method);
} }
/** /**
* Only send one message if the test passes, after that * Only send one message if the test passes, after that
* suppress the message. * suppress the message.
* @param string $test_name Name of test that is ending. * @param string $test_name Name of test that is ending.
* @access public * @access public
*/ */
function paintMethodEnd($method){ function paintMethodEnd($method){
if ($this->_fail || $this->_error || ! $this->_pass){ if ($this->fail || $this->error || ! $this->pass){
} else { } else {
$this->_listener->write( $this->listener->write(
'{status:"pass",message:"' . $this->_message . '",group:"' . '{status:"pass",message:"' . $this->message . '",group:"' .
$this->_group . '",case:"' . $this->_case . '",method:"' . $this->group . '",case:"' . $this->case . '",method:"' .
$this->_method . '"}'); $this->method . '"}');
} }
} }
/** /**
* Stashes the test case name for the later failure message. * Stashes the test case name for the later failure message.
* @param string $test_name Name of test or other label. * @param string $test_name Name of test or other label.
* @access public * @access public
*/ */
function paintCaseStart($case){ function paintCaseStart($case){
$this->_case = $this->escapeVal($case); $this->case = $this->escapeVal($case);
} }
/** /**
* Drops the name. * Drops the name.
* @param string $test_name Name of test or other label. * @param string $test_name Name of test or other label.
* @access public * @access public
*/ */
function paintCaseEnd($case){ function paintCaseEnd($case){
$this->_case = ""; $this->case = "";
} }
/** /**
* Stashes the name of the test suite. Starts test coverage * Stashes the name of the test suite. Starts test coverage
* if enabled. * if enabled.
@ -215,10 +215,10 @@ class EclipseReporter extends SimpleScorer {
* @access public * @access public
*/ */
function paintGroupStart($group, $size){ function paintGroupStart($group, $size){
$this->_group = $this->escapeVal($group); $this->group = $this->escapeVal($group);
if ($this->_cc){ if ($this->cc){
if (extension_loaded('xdebug')){ if (extension_loaded('xdebug')){
xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE); xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);
} }
} }
} }
@ -229,9 +229,9 @@ class EclipseReporter extends SimpleScorer {
* @access public * @access public
*/ */
function paintGroupEnd($group){ function paintGroupEnd($group){
$this->_group = ""; $this->group = "";
$cc = ""; $cc = "";
if ($this->_cc){ if ($this->cc){
if (extension_loaded('xdebug')){ if (extension_loaded('xdebug')){
$arrfiles = xdebug_get_code_coverage(); $arrfiles = xdebug_get_code_coverage();
xdebug_stop_code_coverage(); xdebug_stop_code_coverage();
@ -261,23 +261,23 @@ class EclipseReporter extends SimpleScorer {
} }
} }
} }
$this->_listener->write('{status:"coverage",message:"' . $this->listener->write('{status:"coverage",message:"' .
EclipseReporter::escapeVal($cc) . '"}'); EclipseReporter::escapeVal($cc) . '"}');
} }
} }
/** /**
* Invoker decorator for Eclipse. Captures output until * Invoker decorator for Eclipse. Captures output until
* the end of the test. * the end of the test.
* @package SimpleTest * @package SimpleTest
* @subpackage Eclipse * @subpackage Eclipse
*/ */
class EclipseInvoker extends SimpleInvokerDecorator{ class EclipseInvoker extends SimpleInvokerDecorator{
function EclipseInvoker(&$invoker, &$listener) { function __construct(&$invoker, &$listener) {
$this->_listener = &$listener; $this->listener = &$listener;
$this->SimpleInvokerDecorator($invoker); $this->SimpleInvokerDecorator($invoker);
} }
/** /**
* Starts output buffering. * Starts output buffering.
* @param string $method Test method to call. * @param string $method Test method to call.
@ -285,7 +285,7 @@ class EclipseInvoker extends SimpleInvokerDecorator{
*/ */
function before($method){ function before($method){
ob_start(); ob_start();
$this->_invoker->before($method); $this->invoker->before($method);
} }
/** /**
@ -295,11 +295,11 @@ class EclipseInvoker extends SimpleInvokerDecorator{
* @access public * @access public
*/ */
function after($method) { function after($method) {
$this->_invoker->after($method); $this->invoker->after($method);
$output = ob_get_contents(); $output = ob_get_contents();
ob_end_clean(); ob_end_clean();
if ($output !== ""){ if ($output !== ""){
$result = $this->_listener->write('{status:"info",message:"' . $result = $this->listener->write('{status:"info",message:"' .
EclipseReporter::escapeVal($output) . '"}'); EclipseReporter::escapeVal($output) . '"}');
} }
} }

View File

@ -3,9 +3,9 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
* @version $Id: encoding.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: encoding.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/**#@+ /**#@+
* include other SimpleTest class files * include other SimpleTest class files
*/ */
@ -18,28 +18,28 @@ require_once(dirname(__FILE__) . '/socket.php');
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleEncodedPair { class SimpleEncodedPair {
var $_key; private $key;
var $_value; private $value;
/** /**
* Stashes the data for rendering later. * Stashes the data for rendering later.
* @param string $key Form element name. * @param string $key Form element name.
* @param string $value Data to send. * @param string $value Data to send.
*/ */
function SimpleEncodedPair($key, $value) { function __construct($key, $value) {
$this->_key = $key; $this->key = $key;
$this->_value = $value; $this->value = $value;
} }
/** /**
* The pair as a single string. * The pair as a single string.
* @return string Encoded pair. * @return string Encoded pair.
* @access public * @access public
*/ */
function asRequest() { function asRequest() {
return urlencode($this->_key) . '=' . urlencode($this->_value); return urlencode($this->key) . '=' . urlencode($this->value);
} }
/** /**
* The MIME part as a string. * The MIME part as a string.
* @return string MIME part encoding. * @return string MIME part encoding.
@ -47,11 +47,11 @@ class SimpleEncodedPair {
*/ */
function asMime() { function asMime() {
$part = 'Content-Disposition: form-data; '; $part = 'Content-Disposition: form-data; ';
$part .= "name=\"" . $this->_key . "\"\r\n"; $part .= "name=\"" . $this->key . "\"\r\n";
$part .= "\r\n" . $this->_value; $part .= "\r\n" . $this->value;
return $part; return $part;
} }
/** /**
* Is this the value we are looking for? * Is this the value we are looking for?
* @param string $key Identifier. * @param string $key Identifier.
@ -59,25 +59,25 @@ class SimpleEncodedPair {
* @access public * @access public
*/ */
function isKey($key) { function isKey($key) {
return $key == $this->_key; return $key == $this->key;
} }
/** /**
* Is this the value we are looking for? * Is this the value we are looking for?
* @return string Identifier. * @return string Identifier.
* @access public * @access public
*/ */
function getKey() { function getKey() {
return $this->_key; return $this->key;
} }
/** /**
* Is this the value we are looking for? * Is this the value we are looking for?
* @return string Content. * @return string Content.
* @access public * @access public
*/ */
function getValue() { function getValue() {
return $this->_value; return $this->value;
} }
} }
@ -87,22 +87,22 @@ class SimpleEncodedPair {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleAttachment { class SimpleAttachment {
var $_key; private $key;
var $_content; private $content;
var $_filename; private $filename;
/** /**
* Stashes the data for rendering later. * Stashes the data for rendering later.
* @param string $key Key to add value to. * @param string $key Key to add value to.
* @param string $content Raw data. * @param string $content Raw data.
* @param hash $filename Original filename. * @param hash $filename Original filename.
*/ */
function SimpleAttachment($key, $content, $filename) { function __construct($key, $content, $filename) {
$this->_key = $key; $this->key = $key;
$this->_content = $content; $this->content = $content;
$this->_filename = $filename; $this->filename = $filename;
} }
/** /**
* The pair as a single string. * The pair as a single string.
* @return string Encoded pair. * @return string Encoded pair.
@ -111,7 +111,7 @@ class SimpleAttachment {
function asRequest() { function asRequest() {
return ''; return '';
} }
/** /**
* The MIME part as a string. * The MIME part as a string.
* @return string MIME part encoding. * @return string MIME part encoding.
@ -119,32 +119,32 @@ class SimpleAttachment {
*/ */
function asMime() { function asMime() {
$part = 'Content-Disposition: form-data; '; $part = 'Content-Disposition: form-data; ';
$part .= 'name="' . $this->_key . '"; '; $part .= 'name="' . $this->key . '"; ';
$part .= 'filename="' . $this->_filename . '"'; $part .= 'filename="' . $this->filename . '"';
$part .= "\r\nContent-Type: " . $this->_deduceMimeType(); $part .= "\r\nContent-Type: " . $this->deduceMimeType();
$part .= "\r\n\r\n" . $this->_content; $part .= "\r\n\r\n" . $this->content;
return $part; return $part;
} }
/** /**
* Attempts to figure out the MIME type from the * Attempts to figure out the MIME type from the
* file extension and the content. * file extension and the content.
* @return string MIME type. * @return string MIME type.
* @access private * @access private
*/ */
function _deduceMimeType() { protected function deduceMimeType() {
if ($this->_isOnlyAscii($this->_content)) { if ($this->isOnlyAscii($this->content)) {
return 'text/plain'; return 'text/plain';
} }
return 'application/octet-stream'; return 'application/octet-stream';
} }
/** /**
* Tests each character is in the range 0-127. * Tests each character is in the range 0-127.
* @param string $ascii String to test. * @param string $ascii String to test.
* @access private * @access private
*/ */
function _isOnlyAscii($ascii) { protected function isOnlyAscii($ascii) {
for ($i = 0, $length = strlen($ascii); $i < $length; $i++) { for ($i = 0, $length = strlen($ascii); $i < $length; $i++) {
if (ord($ascii[$i]) > 127) { if (ord($ascii[$i]) > 127) {
return false; return false;
@ -152,7 +152,7 @@ class SimpleAttachment {
} }
return true; return true;
} }
/** /**
* Is this the value we are looking for? * Is this the value we are looking for?
* @param string $key Identifier. * @param string $key Identifier.
@ -160,25 +160,25 @@ class SimpleAttachment {
* @access public * @access public
*/ */
function isKey($key) { function isKey($key) {
return $key == $this->_key; return $key == $this->key;
} }
/** /**
* Is this the value we are looking for? * Is this the value we are looking for?
* @return string Identifier. * @return string Identifier.
* @access public * @access public
*/ */
function getKey() { function getKey() {
return $this->_key; return $this->key;
} }
/** /**
* Is this the value we are looking for? * Is this the value we are looking for?
* @return string Content. * @return string Content.
* @access public * @access public
*/ */
function getValue() { function getValue() {
return $this->_filename; return $this->filename;
} }
} }
@ -189,8 +189,8 @@ class SimpleAttachment {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleEncoding { class SimpleEncoding {
var $_request; private $request;
/** /**
* Starts empty. * Starts empty.
* @param array $query Hash of parameters. * @param array $query Hash of parameters.
@ -198,22 +198,22 @@ class SimpleEncoding {
* as lists on a single key. * as lists on a single key.
* @access public * @access public
*/ */
function SimpleEncoding($query = false) { function __construct($query = false) {
if (! $query) { if (! $query) {
$query = array(); $query = array();
} }
$this->clear(); $this->clear();
$this->merge($query); $this->merge($query);
} }
/** /**
* Empties the request of parameters. * Empties the request of parameters.
* @access public * @access public
*/ */
function clear() { function clear() {
$this->_request = array(); $this->request = array();
} }
/** /**
* Adds a parameter to the query. * Adds a parameter to the query.
* @param string $key Key to add value to. * @param string $key Key to add value to.
@ -226,23 +226,23 @@ class SimpleEncoding {
} }
if (is_array($value)) { if (is_array($value)) {
foreach ($value as $item) { foreach ($value as $item) {
$this->_addPair($key, $item); $this->addPair($key, $item);
} }
} else { } else {
$this->_addPair($key, $value); $this->addPair($key, $value);
} }
} }
/** /**
* Adds a new value into the request. * Adds a new value into the request.
* @param string $key Key to add value to. * @param string $key Key to add value to.
* @param string/array $value New data. * @param string/array $value New data.
* @access private * @access private
*/ */
function _addPair($key, $value) { protected function addPair($key, $value) {
$this->_request[] = new SimpleEncodedPair($key, $value); $this->request[] = new SimpleEncodedPair($key, $value);
} }
/** /**
* Adds a MIME part to the query. Does nothing for a * Adds a MIME part to the query. Does nothing for a
* form encoded packet. * form encoded packet.
@ -252,9 +252,9 @@ class SimpleEncoding {
* @access public * @access public
*/ */
function attach($key, $content, $filename) { function attach($key, $content, $filename) {
$this->_request[] = new SimpleAttachment($key, $content, $filename); $this->request[] = new SimpleAttachment($key, $content, $filename);
} }
/** /**
* Adds a set of parameters to this query. * Adds a set of parameters to this query.
* @param array/SimpleQueryString $query Multiple values are * @param array/SimpleQueryString $query Multiple values are
@ -263,14 +263,14 @@ class SimpleEncoding {
*/ */
function merge($query) { function merge($query) {
if (is_object($query)) { if (is_object($query)) {
$this->_request = array_merge($this->_request, $query->getAll()); $this->request = array_merge($this->request, $query->getAll());
} elseif (is_array($query)) { } elseif (is_array($query)) {
foreach ($query as $key => $value) { foreach ($query as $key => $value) {
$this->add($key, $value); $this->add($key, $value);
} }
} }
} }
/** /**
* Accessor for single value. * Accessor for single value.
* @return string/array False if missing, string * @return string/array False if missing, string
@ -280,7 +280,7 @@ class SimpleEncoding {
*/ */
function getValue($key) { function getValue($key) {
$values = array(); $values = array();
foreach ($this->_request as $pair) { foreach ($this->request as $pair) {
if ($pair->isKey($key)) { if ($pair->isKey($key)) {
$values[] = $pair->getValue(); $values[] = $pair->getValue();
} }
@ -293,25 +293,25 @@ class SimpleEncoding {
return $values; return $values;
} }
} }
/** /**
* Accessor for listing of pairs. * Accessor for listing of pairs.
* @return array All pair objects. * @return array All pair objects.
* @access public * @access public
*/ */
function getAll() { function getAll() {
return $this->_request; return $this->request;
} }
/** /**
* Renders the query string as a URL encoded * Renders the query string as a URL encoded
* request part. * request part.
* @return string Part of URL. * @return string Part of URL.
* @access protected * @access protected
*/ */
function _encode() { protected function encode() {
$statements = array(); $statements = array();
foreach ($this->_request as $pair) { foreach ($this->request as $pair) {
if ($statement = $pair->asRequest()) { if ($statement = $pair->asRequest()) {
$statements[] = $statement; $statements[] = $statement;
} }
@ -327,7 +327,7 @@ class SimpleEncoding {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleGetEncoding extends SimpleEncoding { class SimpleGetEncoding extends SimpleEncoding {
/** /**
* Starts empty. * Starts empty.
* @param array $query Hash of parameters. * @param array $query Hash of parameters.
@ -335,10 +335,10 @@ class SimpleGetEncoding extends SimpleEncoding {
* as lists on a single key. * as lists on a single key.
* @access public * @access public
*/ */
function SimpleGetEncoding($query = false) { function __construct($query = false) {
$this->SimpleEncoding($query); parent::__construct($query);
} }
/** /**
* HTTP request method. * HTTP request method.
* @return string Always GET. * @return string Always GET.
@ -347,7 +347,7 @@ class SimpleGetEncoding extends SimpleEncoding {
function getMethod() { function getMethod() {
return 'GET'; return 'GET';
} }
/** /**
* Writes no extra headers. * Writes no extra headers.
* @param SimpleSocket $socket Socket to write to. * @param SimpleSocket $socket Socket to write to.
@ -355,7 +355,7 @@ class SimpleGetEncoding extends SimpleEncoding {
*/ */
function writeHeadersTo(&$socket) { function writeHeadersTo(&$socket) {
} }
/** /**
* No data is sent to the socket as the data is encoded into * No data is sent to the socket as the data is encoded into
* the URL. * the URL.
@ -364,7 +364,7 @@ class SimpleGetEncoding extends SimpleEncoding {
*/ */
function writeTo(&$socket) { function writeTo(&$socket) {
} }
/** /**
* Renders the query string as a URL encoded * Renders the query string as a URL encoded
* request part for attaching to a URL. * request part for attaching to a URL.
@ -372,7 +372,7 @@ class SimpleGetEncoding extends SimpleEncoding {
* @access public * @access public
*/ */
function asUrlRequest() { function asUrlRequest() {
return $this->_encode(); return $this->encode();
} }
} }
@ -382,7 +382,7 @@ class SimpleGetEncoding extends SimpleEncoding {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleHeadEncoding extends SimpleGetEncoding { class SimpleHeadEncoding extends SimpleGetEncoding {
/** /**
* Starts empty. * Starts empty.
* @param array $query Hash of parameters. * @param array $query Hash of parameters.
@ -390,10 +390,10 @@ class SimpleHeadEncoding extends SimpleGetEncoding {
* as lists on a single key. * as lists on a single key.
* @access public * @access public
*/ */
function SimpleHeadEncoding($query = false) { function __construct($query = false) {
$this->SimpleGetEncoding($query); parent::__construct($query);
} }
/** /**
* HTTP request method. * HTTP request method.
* @return string Always HEAD. * @return string Always HEAD.
@ -405,13 +405,12 @@ class SimpleHeadEncoding extends SimpleGetEncoding {
} }
/** /**
* Bundle of POST parameters. Can include * Bundle of URL parameters for a DELETE request.
* repeated parameters.
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimplePostEncoding extends SimpleEncoding { class SimpleDeleteEncoding extends SimpleGetEncoding {
/** /**
* Starts empty. * Starts empty.
* @param array $query Hash of parameters. * @param array $query Hash of parameters.
@ -419,13 +418,103 @@ class SimplePostEncoding extends SimpleEncoding {
* as lists on a single key. * as lists on a single key.
* @access public * @access public
*/ */
function SimplePostEncoding($query = false) { function __construct($query = false) {
parent::__construct($query);
}
/**
* HTTP request method.
* @return string Always DELETE.
* @access public
*/
function getMethod() {
return 'DELETE';
}
}
/**
* Bundles an entity-body for transporting
* a raw content payload with the request.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleEntityEncoding extends SimpleEncoding {
private $content_type;
private $body;
function __construct($query = false, $content_type = false) {
$this->content_type = $content_type;
if (is_string($query)) {
$this->body = $query;
parent::__construct();
} else {
parent::__construct($query);
}
}
/**
* Returns the media type of the entity body
* @return string
* @access public
*/
function getContentType() {
if (!$this->content_type) {
return ($this->body) ? 'text/plain' : 'application/x-www-form-urlencoded';
}
return $this->content_type;
}
/**
* 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: " . $this->getContentType() . "\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 request body
* @return Encoded entity body
* @access protected
*/
protected function encode() {
return ($this->body) ? $this->body : parent::encode();
}
}
/**
* Bundle of POST parameters. Can include
* repeated parameters.
* @package SimpleTest
* @subpackage WebTester
*/
class SimplePostEncoding extends SimpleEntityEncoding {
/**
* Starts empty.
* @param array $query Hash of parameters.
* Multiple values are
* as lists on a single key.
* @access public
*/
function __construct($query = false, $content_type = false) {
if (is_array($query) and $this->hasMoreThanOneLevel($query)) { if (is_array($query) and $this->hasMoreThanOneLevel($query)) {
$query = $this->rewriteArrayWithMultipleLevels($query); $query = $this->rewriteArrayWithMultipleLevels($query);
} }
$this->SimpleEncoding($query); parent::__construct($query, $content_type);
} }
function hasMoreThanOneLevel($query) { function hasMoreThanOneLevel($query) {
foreach ($query as $key => $value) { foreach ($query as $key => $value) {
if (is_array($value)) { if (is_array($value)) {
@ -449,11 +538,10 @@ class SimplePostEncoding extends SimpleEncoding {
if ($this->hasMoreThanOneLevel($query_)) { if ($this->hasMoreThanOneLevel($query_)) {
$query_ = $this->rewriteArrayWithMultipleLevels($query_); $query_ = $this->rewriteArrayWithMultipleLevels($query_);
} }
return $query_; return $query_;
} }
/** /**
* HTTP request method. * HTTP request method.
* @return string Always POST. * @return string Always POST.
@ -462,26 +550,7 @@ class SimplePostEncoding extends SimpleEncoding {
function getMethod() { function getMethod() {
return 'POST'; 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 * Renders the query string as a URL encoded
* request part for attaching to a URL. * request part for attaching to a URL.
@ -494,14 +563,12 @@ class SimplePostEncoding extends SimpleEncoding {
} }
/** /**
* Bundle of POST parameters in the multipart * Encoded entity body for a PUT request.
* format. Can include file uploads.
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleMultipartEncoding extends SimplePostEncoding { class SimplePutEncoding extends SimpleEntityEncoding {
var $_boundary;
/** /**
* Starts empty. * Starts empty.
* @param array $query Hash of parameters. * @param array $query Hash of parameters.
@ -509,43 +576,73 @@ class SimpleMultipartEncoding extends SimplePostEncoding {
* as lists on a single key. * as lists on a single key.
* @access public * @access public
*/ */
function SimpleMultipartEncoding($query = false, $boundary = false) { function __construct($query = false, $content_type = false) {
$this->SimplePostEncoding($query); parent::__construct($query, $content_type);
$this->_boundary = ($boundary === false ? uniqid('st') : $boundary);
} }
/**
* HTTP request method.
* @return string Always PUT.
* @access public
*/
function getMethod() {
return 'PUT';
}
}
/**
* Bundle of POST parameters in the multipart
* format. Can include file uploads.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleMultipartEncoding extends SimplePostEncoding {
private $boundary;
/**
* Starts empty.
* @param array $query Hash of parameters.
* Multiple values are
* as lists on a single key.
* @access public
*/
function __construct($query = false, $boundary = false) {
parent::__construct($query);
$this->boundary = ($boundary === false ? uniqid('st') : $boundary);
}
/** /**
* Dispatches the form headers down the socket. * Dispatches the form headers down the socket.
* @param SimpleSocket $socket Socket to write to. * @param SimpleSocket $socket Socket to write to.
* @access public * @access public
*/ */
function writeHeadersTo(&$socket) { function writeHeadersTo(&$socket) {
$socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n"); $socket->write("Content-Length: " . (integer)strlen($this->encode()) . "\r\n");
$socket->write("Content-Type: multipart/form-data, boundary=" . $this->_boundary . "\r\n"); $socket->write("Content-Type: multipart/form-data; boundary=" . $this->boundary . "\r\n");
} }
/** /**
* Dispatches the form data down the socket. * Dispatches the form data down the socket.
* @param SimpleSocket $socket Socket to write to. * @param SimpleSocket $socket Socket to write to.
* @access public * @access public
*/ */
function writeTo(&$socket) { function writeTo(&$socket) {
$socket->write($this->_encode()); $socket->write($this->encode());
} }
/** /**
* Renders the query string as a URL encoded * Renders the query string as a URL encoded
* request part. * request part.
* @return string Part of URL. * @return string Part of URL.
* @access public * @access public
*/ */
function _encode() { function encode() {
$stream = ''; $stream = '';
foreach ($this->_request as $pair) { foreach ($this->getAll() as $pair) {
$stream .= "--" . $this->_boundary . "\r\n"; $stream .= "--" . $this->boundary . "\r\n";
$stream .= $pair->asMime() . "\r\n"; $stream .= $pair->asMime() . "\r\n";
} }
$stream .= "--" . $this->_boundary . "--\r\n"; $stream .= "--" . $this->boundary . "--\r\n";
return $stream; return $stream;
} }
} }

View File

@ -3,16 +3,9 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: errors.php 1672 2008-03-02 04:47:34Z edwardzyang $ * @version $Id: errors.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/**
* @ignore - PHP5 compatibility fix.
*/
if (! defined('E_STRICT')) {
define('E_STRICT', 2048);
}
/**#@+ /**#@+
* Includes SimpleTest files. * Includes SimpleTest files.
*/ */
@ -32,8 +25,8 @@ class SimpleErrorTrappingInvoker extends SimpleInvokerDecorator {
* Stores the invoker to wrap. * Stores the invoker to wrap.
* @param SimpleInvoker $invoker Test method runner. * @param SimpleInvoker $invoker Test method runner.
*/ */
function SimpleErrorTrappingInvoker(&$invoker) { function __construct($invoker) {
$this->SimpleInvokerDecorator($invoker); parent::__construct($invoker);
} }
/** /**
@ -44,22 +37,22 @@ class SimpleErrorTrappingInvoker extends SimpleInvokerDecorator {
* @access public * @access public
*/ */
function invoke($method) { function invoke($method) {
$queue = &$this->_createErrorQueue(); $queue = $this->createErrorQueue();
set_error_handler('SimpleTestErrorHandler'); set_error_handler('SimpleTestErrorHandler');
parent::invoke($method); parent::invoke($method);
restore_error_handler(); restore_error_handler();
$queue->tally(); $queue->tally();
} }
/** /**
* Wires up the error queue for a single test. * Wires up the error queue for a single test.
* @return SimpleErrorQueue Queue connected to the test. * @return SimpleErrorQueue Queue connected to the test.
* @access private * @access private
*/ */
function &_createErrorQueue() { protected function createErrorQueue() {
$context = &SimpleTest::getContext(); $context = SimpleTest::getContext();
$test = &$this->getTestCase(); $test = $this->getTestCase();
$queue = &$context->get('SimpleErrorQueue'); $queue = $context->get('SimpleErrorQueue');
$queue->setTestCase($test); $queue->setTestCase($test);
return $queue; return $queue;
} }
@ -72,15 +65,15 @@ class SimpleErrorTrappingInvoker extends SimpleInvokerDecorator {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SimpleErrorQueue { class SimpleErrorQueue {
var $_queue; private $queue;
var $_expectation_queue; private $expectation_queue;
var $_test; private $test;
var $_using_expect_style = false; private $using_expect_style = false;
/** /**
* Starts with an empty queue. * Starts with an empty queue.
*/ */
function SimpleErrorQueue() { function __construct() {
$this->clear(); $this->clear();
} }
@ -89,8 +82,8 @@ class SimpleErrorQueue {
* @access public * @access public
*/ */
function clear() { function clear() {
$this->_queue = array(); $this->queue = array();
$this->_expectation_queue = array(); $this->expectation_queue = array();
} }
/** /**
@ -98,8 +91,8 @@ class SimpleErrorQueue {
* @param SimpleTestCase $test Test case to send messages to. * @param SimpleTestCase $test Test case to send messages to.
* @access public * @access public
*/ */
function setTestCase(&$test) { function setTestCase($test) {
$this->_test = &$test; $this->test = $test;
} }
/** /**
@ -112,8 +105,7 @@ class SimpleErrorQueue {
* @access public * @access public
*/ */
function expectError($expected, $message) { function expectError($expected, $message) {
$this->_using_expect_style = true; array_push($this->expectation_queue, array($expected, $message));
array_push($this->_expectation_queue, array($expected, $message));
} }
/** /**
@ -126,15 +118,9 @@ class SimpleErrorQueue {
*/ */
function add($severity, $content, $filename, $line) { function add($severity, $content, $filename, $line) {
$content = str_replace('%', '%%', $content); $content = str_replace('%', '%%', $content);
if ($this->_using_expect_style) { $this->testLatestError($severity, $content, $filename, $line);
$this->_testLatestError($severity, $content, $filename, $line);
} else {
array_push(
$this->_queue,
array($severity, $content, $filename, $line));
}
} }
/** /**
* Any errors still in the queue are sent to the test * Any errors still in the queue are sent to the test
* case. Any unfulfilled expectations trigger failures. * case. Any unfulfilled expectations trigger failures.
@ -143,10 +129,10 @@ class SimpleErrorQueue {
function tally() { function tally() {
while (list($severity, $message, $file, $line) = $this->extract()) { while (list($severity, $message, $file, $line) = $this->extract()) {
$severity = $this->getSeverityAsString($severity); $severity = $this->getSeverityAsString($severity);
$this->_test->error($severity, $message, $file, $line); $this->test->error($severity, $message, $file, $line);
} }
while (list($expected, $message) = $this->_extractExpectation()) { while (list($expected, $message) = $this->extractExpectation()) {
$this->_test->assert($expected, false, "%s -> Expected error not caught"); $this->test->assert($expected, false, "%s -> Expected error not caught");
} }
} }
@ -159,16 +145,16 @@ class SimpleErrorQueue {
* @param integer $line Line number of error. * @param integer $line Line number of error.
* @access private * @access private
*/ */
function _testLatestError($severity, $content, $filename, $line) { protected function testLatestError($severity, $content, $filename, $line) {
if ($expectation = $this->_extractExpectation()) { if ($expectation = $this->extractExpectation()) {
list($expected, $message) = $expectation; list($expected, $message) = $expectation;
$this->_test->assert($expected, $content, sprintf( $this->test->assert($expected, $content, sprintf(
$message, $message,
"%s -> PHP error [$content] severity [" . "%s -> PHP error [$content] severity [" .
$this->getSeverityAsString($severity) . $this->getSeverityAsString($severity) .
"] in [$filename] line [$line]")); "] in [$filename] line [$line]"));
} else { } else {
$this->_test->error($severity, $content, $filename, $line); $this->test->error($severity, $content, $filename, $line);
} }
} }
@ -182,8 +168,8 @@ class SimpleErrorQueue {
* @access public * @access public
*/ */
function extract() { function extract() {
if (count($this->_queue)) { if (count($this->queue)) {
return array_shift($this->_queue); return array_shift($this->queue);
} }
return false; return false;
} }
@ -193,48 +179,21 @@ class SimpleErrorQueue {
* @return SimpleExpectation False if none. * @return SimpleExpectation False if none.
* @access private * @access private
*/ */
function _extractExpectation() { protected function extractExpectation() {
if (count($this->_expectation_queue)) { if (count($this->expectation_queue)) {
return array_shift($this->_expectation_queue); return array_shift($this->expectation_queue);
} }
return false; return false;
} }
/**
* @deprecated
*/
function assertNoErrors($message) {
return $this->_test->assert(
new TrueExpectation(),
count($this->_queue) == 0,
sprintf($message, 'Should be no errors'));
}
/**
* @deprecated
*/
function assertError($expected, $message) {
if (count($this->_queue) == 0) {
$this->_test->fail(sprintf($message, 'Expected error not found'));
return false;
}
list($severity, $content, $file, $line) = $this->extract();
$severity = $this->getSeverityAsString($severity);
return $this->_test->assert(
$expected,
$content,
sprintf($message, "Expected PHP error [$content] severity [$severity] in [$file] line [$line]"));
}
/** /**
* Converts an error code into it's string * Converts an error code into it's string
* representation. * representation.
* @param $severity PHP integer error code. * @param $severity PHP integer error code.
* @return String version of error code. * @return String version of error code.
* @access public * @access public
* @static
*/ */
function getSeverityAsString($severity) { static function getSeverityAsString($severity) {
static $map = array( static $map = array(
E_STRICT => 'E_STRICT', E_STRICT => 'E_STRICT',
E_ERROR => 'E_ERROR', E_ERROR => 'E_ERROR',
@ -267,22 +226,42 @@ class SimpleErrorQueue {
* @param $filename File error occoured in. * @param $filename File error occoured in.
* @param $line Line number of error. * @param $line Line number of error.
* @param $super_globals Hash of PHP super global arrays. * @param $super_globals Hash of PHP super global arrays.
* @static
* @access public * @access public
*/ */
function SimpleTestErrorHandler($severity, $message, $filename = null, $line = null, $super_globals = null, $mask = null) { function SimpleTestErrorHandler($severity, $message, $filename = null, $line = null, $super_globals = null, $mask = null) {
$severity = $severity & error_reporting(); $severity = $severity & error_reporting();
if ($severity) { if ($severity) {
restore_error_handler(); restore_error_handler();
if (ini_get('log_errors')) { if (IsNotCausedBySimpleTest($message) && IsNotTimeZoneNag($message)) {
$label = SimpleErrorQueue::getSeverityAsString($severity); if (ini_get('log_errors')) {
error_log("$label: $message in $filename on line $line"); $label = SimpleErrorQueue::getSeverityAsString($severity);
error_log("$label: $message in $filename on line $line");
}
$queue = SimpleTest::getContext()->get('SimpleErrorQueue');
$queue->add($severity, $message, $filename, $line);
} }
$context = &SimpleTest::getContext();
$queue = &$context->get('SimpleErrorQueue');
$queue->add($severity, $message, $filename, $line);
set_error_handler('SimpleTestErrorHandler'); set_error_handler('SimpleTestErrorHandler');
} }
return true; return true;
} }
/**
* Certain messages can be caused by the unit tester itself.
* These have to be filtered.
* @param string $message Message to filter.
* @return boolean True if genuine failure.
*/
function IsNotCausedBySimpleTest($message) {
return ! preg_match('/returned by reference/', $message);
}
/**
* Certain messages caused by PHP are just noise.
* These have to be filtered.
* @param string $message Message to filter.
* @return boolean True if genuine failure.
*/
function IsNotTimeZoneNag($message) {
return ! preg_match('/not safe to rely .* timezone settings/', $message);
}
?> ?>

50
contrib/simpletest/simpletest/exceptions.php Normal file → Executable file
View File

@ -3,11 +3,11 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: exceptions.php 1672 2008-03-02 04:47:34Z edwardzyang $ * @version $Id: exceptions.php 1882 2009-07-01 14:30:05Z lastcraft $
*/ */
/**#@+ /**#@+
* Include required SimpleTest files * Include required SimpleTest files
*/ */
require_once dirname(__FILE__) . '/invoker.php'; require_once dirname(__FILE__) . '/invoker.php';
require_once dirname(__FILE__) . '/expectation.php'; require_once dirname(__FILE__) . '/expectation.php';
@ -25,8 +25,8 @@ class SimpleExceptionTrappingInvoker extends SimpleInvokerDecorator {
* Stores the invoker to be wrapped. * Stores the invoker to be wrapped.
* @param SimpleInvoker $invoker Test method runner. * @param SimpleInvoker $invoker Test method runner.
*/ */
function SimpleExceptionTrappingInvoker($invoker) { function __construct($invoker) {
$this->SimpleInvokerDecorator($invoker); parent::__construct($invoker);
} }
/** /**
@ -136,6 +136,7 @@ class ExceptionExpectation extends SimpleExpectation {
*/ */
class SimpleExceptionTrap { class SimpleExceptionTrap {
private $expected; private $expected;
private $ignored;
private $message; private $message;
/** /**
@ -154,16 +155,20 @@ class SimpleExceptionTrap {
* @access public * @access public
*/ */
function expectException($expected = false, $message = '%s') { function expectException($expected = false, $message = '%s') {
if ($expected === false) { $this->expected = $this->coerceToExpectation($expected);
$expected = new AnythingExpectation();
}
if (! SimpleExpectation::isExpectation($expected)) {
$expected = new ExceptionExpectation($expected);
}
$this->expected = $expected;
$this->message = $message; $this->message = $message;
} }
/**
* Adds an exception to the ignore list. This is the list
* of exceptions that when thrown do not affect the test.
* @param SimpleExpectation $ignored Exception to skip.
* @access public
*/
function ignoreException($ignored) {
$this->ignored[] = $this->coerceToExpectation($ignored);
}
/** /**
* Compares the expected exception with any * Compares the expected exception with any
* in the queue. Issues a pass or fail and * in the queue. Issues a pass or fail and
@ -176,9 +181,31 @@ class SimpleExceptionTrap {
if ($this->expected) { if ($this->expected) {
return $test->assert($this->expected, $exception, $this->message); return $test->assert($this->expected, $exception, $this->message);
} }
foreach ($this->ignored as $ignored) {
if ($ignored->test($exception)) {
return true;
}
}
return false; return false;
} }
/**
* Turns an expected exception into a SimpleExpectation object.
* @param mixed $exception Exception, expectation or
* class name of exception.
* @return SimpleExpectation Expectation that will match the
* exception.
*/
private function coerceToExpectation($exception) {
if ($exception === false) {
return new AnythingExpectation();
}
if (! SimpleExpectation::isExpectation($exception)) {
return new ExceptionExpectation($exception);
}
return $exception;
}
/** /**
* Tests for any left over exception. * Tests for any left over exception.
* @return string/false The failure message or false if none. * @return string/false The failure message or false if none.
@ -193,6 +220,7 @@ class SimpleExceptionTrap {
function clear() { function clear() {
$this->expected = false; $this->expected = false;
$this->message = false; $this->message = false;
$this->ignored = array();
} }
} }
?> ?>

371
contrib/simpletest/simpletest/expectation.php Normal file → Executable file
View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: expectation.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: expectation.php 2009 2011-04-28 08:57:25Z pp11 $
*/ */
/**#@+ /**#@+
@ -21,16 +21,16 @@ require_once(dirname(__FILE__) . '/compatibility.php');
* @abstract * @abstract
*/ */
class SimpleExpectation { class SimpleExpectation {
var $_dumper = false; protected $dumper = false;
var $_message; private $message;
/** /**
* Creates a dumper for displaying values and sets * Creates a dumper for displaying values and sets
* the test message. * the test message.
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
*/ */
function SimpleExpectation($message = '%s') { function __construct($message = '%s') {
$this->_message = $message; $this->message = $message;
} }
/** /**
@ -64,8 +64,8 @@ class SimpleExpectation {
* @access public * @access public
*/ */
function overlayMessage($compare, $dumper) { function overlayMessage($compare, $dumper) {
$this->_dumper = $dumper; $this->dumper = $dumper;
return sprintf($this->_message, $this->testMessage($compare)); return sprintf($this->message, $this->testMessage($compare));
} }
/** /**
@ -73,25 +73,24 @@ class SimpleExpectation {
* @return SimpleDumper Current value dumper. * @return SimpleDumper Current value dumper.
* @access protected * @access protected
*/ */
function &_getDumper() { protected function getDumper() {
if (! $this->_dumper) { if (! $this->dumper) {
$dumper = &new SimpleDumper(); $dumper = new SimpleDumper();
return $dumper; return $dumper;
} }
return $this->_dumper; return $this->dumper;
} }
/** /**
* Test to see if a value is an expectation object. * Test to see if a value is an expectation object.
* A useful utility method. * A useful utility method.
* @param mixed $expectation Hopefully an Epectation * @param mixed $expectation Hopefully an Expectation
* class. * class.
* @return boolean True if descended from * @return boolean True if descended from
* this class. * this class.
* @access public * @access public
* @static
*/ */
function isExpectation($expectation) { static function isExpectation($expectation) {
return is_object($expectation) && return is_object($expectation) &&
SimpleTestCompatibility::isA($expectation, 'SimpleExpectation'); SimpleTestCompatibility::isA($expectation, 'SimpleExpectation');
} }
@ -122,7 +121,7 @@ class AnythingExpectation extends SimpleExpectation {
* @access public * @access public
*/ */
function testMessage($compare) { function testMessage($compare) {
$dumper = &$this->_getDumper(); $dumper = $this->getDumper();
return 'Anything always matches [' . $dumper->describeValue($compare) . ']'; return 'Anything always matches [' . $dumper->describeValue($compare) . ']';
} }
} }
@ -151,7 +150,7 @@ class FailedExpectation extends SimpleExpectation {
* @access public * @access public
*/ */
function testMessage($compare) { function testMessage($compare) {
$dumper = &$this->_getDumper(); $dumper = $this->getDumper();
return 'Failed expectation never matches [' . $dumper->describeValue($compare) . ']'; return 'Failed expectation never matches [' . $dumper->describeValue($compare) . ']';
} }
} }
@ -181,7 +180,7 @@ class TrueExpectation extends SimpleExpectation {
* @access public * @access public
*/ */
function testMessage($compare) { function testMessage($compare) {
$dumper = &$this->_getDumper(); $dumper = $this->getDumper();
return 'Expected true, got [' . $dumper->describeValue($compare) . ']'; return 'Expected true, got [' . $dumper->describeValue($compare) . ']';
} }
} }
@ -211,7 +210,7 @@ class FalseExpectation extends SimpleExpectation {
* @access public * @access public
*/ */
function testMessage($compare) { function testMessage($compare) {
$dumper = &$this->_getDumper(); $dumper = $this->getDumper();
return 'Expected false, got [' . $dumper->describeValue($compare) . ']'; return 'Expected false, got [' . $dumper->describeValue($compare) . ']';
} }
} }
@ -222,7 +221,7 @@ class FalseExpectation extends SimpleExpectation {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class EqualExpectation extends SimpleExpectation { class EqualExpectation extends SimpleExpectation {
var $_value; private $value;
/** /**
* Sets the value to compare against. * Sets the value to compare against.
@ -230,9 +229,9 @@ class EqualExpectation extends SimpleExpectation {
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
* @access public * @access public
*/ */
function EqualExpectation($value, $message = '%s') { function __construct($value, $message = '%s') {
$this->SimpleExpectation($message); parent::__construct($message);
$this->_value = $value; $this->value = $value;
} }
/** /**
@ -243,7 +242,7 @@ class EqualExpectation extends SimpleExpectation {
* @access public * @access public
*/ */
function test($compare) { function test($compare) {
return (($this->_value == $compare) && ($compare == $this->_value)); return (($this->value == $compare) && ($compare == $this->value));
} }
/** /**
@ -255,10 +254,10 @@ class EqualExpectation extends SimpleExpectation {
*/ */
function testMessage($compare) { function testMessage($compare) {
if ($this->test($compare)) { if ($this->test($compare)) {
return "Equal expectation [" . $this->_dumper->describeValue($this->_value) . "]"; return "Equal expectation [" . $this->dumper->describeValue($this->value) . "]";
} else { } else {
return "Equal expectation fails " . return "Equal expectation fails " .
$this->_dumper->describeDifference($this->_value, $compare); $this->dumper->describeDifference($this->value, $compare);
} }
} }
@ -267,8 +266,8 @@ class EqualExpectation extends SimpleExpectation {
* @return mixed Held value to compare with. * @return mixed Held value to compare with.
* @access protected * @access protected
*/ */
function _getValue() { protected function getValue() {
return $this->_value; return $this->value;
} }
} }
@ -285,8 +284,8 @@ class NotEqualExpectation extends EqualExpectation {
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
* @access public * @access public
*/ */
function NotEqualExpectation($value, $message = '%s') { function __construct($value, $message = '%s') {
$this->EqualExpectation($value, $message); parent::__construct($value, $message);
} }
/** /**
@ -308,13 +307,13 @@ class NotEqualExpectation extends EqualExpectation {
* @access public * @access public
*/ */
function testMessage($compare) { function testMessage($compare) {
$dumper = &$this->_getDumper(); $dumper = $this->getDumper();
if ($this->test($compare)) { if ($this->test($compare)) {
return "Not equal expectation passes " . return "Not equal expectation passes " .
$dumper->describeDifference($this->_getValue(), $compare); $dumper->describeDifference($this->getValue(), $compare);
} else { } else {
return "Not equal expectation fails [" . return "Not equal expectation fails [" .
$dumper->describeValue($this->_getValue()) . $dumper->describeValue($this->getValue()) .
"] matches"; "] matches";
} }
} }
@ -326,8 +325,8 @@ class NotEqualExpectation extends EqualExpectation {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class WithinMarginExpectation extends SimpleExpectation { class WithinMarginExpectation extends SimpleExpectation {
var $_upper; private $upper;
var $_lower; private $lower;
/** /**
* Sets the value to compare against and the fuzziness of * Sets the value to compare against and the fuzziness of
@ -337,10 +336,10 @@ class WithinMarginExpectation extends SimpleExpectation {
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
* @access public * @access public
*/ */
function WithinMarginExpectation($value, $margin, $message = '%s') { function __construct($value, $margin, $message = '%s') {
$this->SimpleExpectation($message); parent::__construct($message);
$this->_upper = $value + $margin; $this->upper = $value + $margin;
$this->_lower = $value - $margin; $this->lower = $value - $margin;
} }
/** /**
@ -351,7 +350,7 @@ class WithinMarginExpectation extends SimpleExpectation {
* @access public * @access public
*/ */
function test($compare) { function test($compare) {
return (($compare <= $this->_upper) && ($compare >= $this->_lower)); return (($compare <= $this->upper) && ($compare >= $this->lower));
} }
/** /**
@ -363,9 +362,9 @@ class WithinMarginExpectation extends SimpleExpectation {
*/ */
function testMessage($compare) { function testMessage($compare) {
if ($this->test($compare)) { if ($this->test($compare)) {
return $this->_withinMessage($compare); return $this->withinMessage($compare);
} else { } else {
return $this->_outsideMessage($compare); return $this->outsideMessage($compare);
} }
} }
@ -374,9 +373,9 @@ class WithinMarginExpectation extends SimpleExpectation {
* @param mixed $compare Value being tested. * @param mixed $compare Value being tested.
* @access private * @access private
*/ */
function _withinMessage($compare) { protected function withinMessage($compare) {
return "Within expectation [" . $this->_dumper->describeValue($this->_lower) . "] and [" . return "Within expectation [" . $this->dumper->describeValue($this->lower) . "] and [" .
$this->_dumper->describeValue($this->_upper) . "]"; $this->dumper->describeValue($this->upper) . "]";
} }
/** /**
@ -384,13 +383,13 @@ class WithinMarginExpectation extends SimpleExpectation {
* @param mixed $compare Value being tested. * @param mixed $compare Value being tested.
* @access private * @access private
*/ */
function _outsideMessage($compare) { protected function outsideMessage($compare) {
if ($compare > $this->_upper) { if ($compare > $this->upper) {
return "Outside expectation " . return "Outside expectation " .
$this->_dumper->describeDifference($compare, $this->_upper); $this->dumper->describeDifference($compare, $this->upper);
} else { } else {
return "Outside expectation " . return "Outside expectation " .
$this->_dumper->describeDifference($compare, $this->_lower); $this->dumper->describeDifference($compare, $this->lower);
} }
} }
} }
@ -410,8 +409,8 @@ class OutsideMarginExpectation extends WithinMarginExpectation {
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
* @access public * @access public
*/ */
function OutsideMarginExpectation($value, $margin, $message = '%s') { function __construct($value, $margin, $message = '%s') {
$this->WithinMarginExpectation($value, $margin, $message); parent::__construct($value, $margin, $message);
} }
/** /**
@ -434,9 +433,9 @@ class OutsideMarginExpectation extends WithinMarginExpectation {
*/ */
function testMessage($compare) { function testMessage($compare) {
if (! $this->test($compare)) { if (! $this->test($compare)) {
return $this->_withinMessage($compare); return $this->withinMessage($compare);
} else { } else {
return $this->_outsideMessage($compare); return $this->outsideMessage($compare);
} }
} }
} }
@ -446,8 +445,8 @@ class OutsideMarginExpectation extends WithinMarginExpectation {
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class ReferenceExpectation extends SimpleExpectation { class ReferenceExpectation {
var $_value; private $value;
/** /**
* Sets the reference value to compare against. * Sets the reference value to compare against.
@ -455,9 +454,9 @@ class ReferenceExpectation extends SimpleExpectation {
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
* @access public * @access public
*/ */
function ReferenceExpectation(&$value, $message = '%s') { function __construct(&$value, $message = '%s') {
$this->SimpleExpectation($message); $this->message = $message;
$this->_value =& $value; $this->value = &$value;
} }
/** /**
@ -468,7 +467,7 @@ class ReferenceExpectation extends SimpleExpectation {
* @access public * @access public
*/ */
function test(&$compare) { function test(&$compare) {
return SimpleTestCompatibility::isReference($this->_value, $compare); return SimpleTestCompatibility::isReference($this->value, $compare);
} }
/** /**
@ -480,15 +479,38 @@ class ReferenceExpectation extends SimpleExpectation {
*/ */
function testMessage($compare) { function testMessage($compare) {
if ($this->test($compare)) { if ($this->test($compare)) {
return "Reference expectation [" . $this->_dumper->describeValue($this->_value) . "]"; return "Reference expectation [" . $this->dumper->describeValue($this->value) . "]";
} else { } else {
return "Reference expectation fails " . return "Reference expectation fails " .
$this->_dumper->describeDifference($this->_value, $compare); $this->dumper->describeDifference($this->value, $compare);
} }
} }
function _getValue() { /**
return $this->_value; * Overlays the generated message onto the stored user
* message. An additional message can be interjected.
* @param mixed $compare Comparison value.
* @param SimpleDumper $dumper For formatting the results.
* @return string Description of success
* or failure.
* @access public
*/
function overlayMessage($compare, $dumper) {
$this->dumper = $dumper;
return sprintf($this->message, $this->testMessage($compare));
}
/**
* Accessor for the dumper.
* @return SimpleDumper Current value dumper.
* @access protected
*/
protected function getDumper() {
if (! $this->dumper) {
$dumper = new SimpleDumper();
return $dumper;
}
return $this->dumper;
} }
} }
@ -505,8 +527,8 @@ class IdenticalExpectation extends EqualExpectation {
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
* @access public * @access public
*/ */
function IdenticalExpectation($value, $message = '%s') { function __construct($value, $message = '%s') {
$this->EqualExpectation($value, $message); parent::__construct($value, $message);
} }
/** /**
@ -517,7 +539,7 @@ class IdenticalExpectation extends EqualExpectation {
* @access public * @access public
*/ */
function test($compare) { function test($compare) {
return SimpleTestCompatibility::isIdentical($this->_getValue(), $compare); return SimpleTestCompatibility::isIdentical($this->getValue(), $compare);
} }
/** /**
@ -528,14 +550,14 @@ class IdenticalExpectation extends EqualExpectation {
* @access public * @access public
*/ */
function testMessage($compare) { function testMessage($compare) {
$dumper = &$this->_getDumper(); $dumper = $this->getDumper();
if ($this->test($compare)) { if ($this->test($compare)) {
return "Identical expectation [" . $dumper->describeValue($this->_getValue()) . "]"; return "Identical expectation [" . $dumper->describeValue($this->getValue()) . "]";
} else { } else {
return "Identical expectation [" . $dumper->describeValue($this->_getValue()) . return "Identical expectation [" . $dumper->describeValue($this->getValue()) .
"] fails with [" . "] fails with [" .
$dumper->describeValue($compare) . "] " . $dumper->describeValue($compare) . "] " .
$dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS); $dumper->describeDifference($this->getValue(), $compare, TYPE_MATTERS);
} }
} }
} }
@ -553,8 +575,8 @@ class NotIdenticalExpectation extends IdenticalExpectation {
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
* @access public * @access public
*/ */
function NotIdenticalExpectation($value, $message = '%s') { function __construct($value, $message = '%s') {
$this->IdenticalExpectation($value, $message); parent::__construct($value, $message);
} }
/** /**
@ -576,12 +598,12 @@ class NotIdenticalExpectation extends IdenticalExpectation {
* @access public * @access public
*/ */
function testMessage($compare) { function testMessage($compare) {
$dumper = &$this->_getDumper(); $dumper = $this->getDumper();
if ($this->test($compare)) { if ($this->test($compare)) {
return "Not identical expectation passes " . return "Not identical expectation passes " .
$dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS); $dumper->describeDifference($this->getValue(), $compare, TYPE_MATTERS);
} else { } else {
return "Not identical expectation [" . $dumper->describeValue($this->_getValue()) . "] matches"; return "Not identical expectation [" . $dumper->describeValue($this->getValue()) . "] matches";
} }
} }
} }
@ -592,7 +614,7 @@ class NotIdenticalExpectation extends IdenticalExpectation {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class PatternExpectation extends SimpleExpectation { class PatternExpectation extends SimpleExpectation {
var $_pattern; private $pattern;
/** /**
* Sets the value to compare against. * Sets the value to compare against.
@ -600,9 +622,9 @@ class PatternExpectation extends SimpleExpectation {
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
* @access public * @access public
*/ */
function PatternExpectation($pattern, $message = '%s') { function __construct($pattern, $message = '%s') {
$this->SimpleExpectation($message); parent::__construct($message);
$this->_pattern = $pattern; $this->pattern = $pattern;
} }
/** /**
@ -610,8 +632,8 @@ class PatternExpectation extends SimpleExpectation {
* @return string Perl regex as string. * @return string Perl regex as string.
* @access protected * @access protected
*/ */
function _getPattern() { protected function getPattern() {
return $this->_pattern; return $this->pattern;
} }
/** /**
@ -622,7 +644,7 @@ class PatternExpectation extends SimpleExpectation {
* @access public * @access public
*/ */
function test($compare) { function test($compare) {
return (boolean)preg_match($this->_getPattern(), $compare); return (boolean)preg_match($this->getPattern(), $compare);
} }
/** /**
@ -634,10 +656,10 @@ class PatternExpectation extends SimpleExpectation {
*/ */
function testMessage($compare) { function testMessage($compare) {
if ($this->test($compare)) { if ($this->test($compare)) {
return $this->_describePatternMatch($this->_getPattern(), $compare); return $this->describePatternMatch($this->getPattern(), $compare);
} else { } else {
$dumper = &$this->_getDumper(); $dumper = $this->getDumper();
return "Pattern [" . $this->_getPattern() . return "Pattern [" . $this->getPattern() .
"] not detected in [" . "] not detected in [" .
$dumper->describeValue($compare) . "]"; $dumper->describeValue($compare) . "]";
} }
@ -650,10 +672,10 @@ class PatternExpectation extends SimpleExpectation {
* @param string $subject Subject to search. * @param string $subject Subject to search.
* @access protected * @access protected
*/ */
function _describePatternMatch($pattern, $subject) { protected function describePatternMatch($pattern, $subject) {
preg_match($pattern, $subject, $matches); preg_match($pattern, $subject, $matches);
$position = strpos($subject, $matches[0]); $position = strpos($subject, $matches[0]);
$dumper = $this->_getDumper(); $dumper = $this->getDumper();
return "Pattern [$pattern] detected at character [$position] in [" . return "Pattern [$pattern] detected at character [$position] in [" .
$dumper->describeValue($subject) . "] as [" . $dumper->describeValue($subject) . "] as [" .
$matches[0] . "] in region [" . $matches[0] . "] in region [" .
@ -661,14 +683,6 @@ class PatternExpectation extends SimpleExpectation {
} }
} }
/**
* @package SimpleTest
* @subpackage UnitTester
* @deprecated
*/
class WantedPatternExpectation extends PatternExpectation {
}
/** /**
* Fail if a pattern is detected within the * Fail if a pattern is detected within the
* comparison. * comparison.
@ -683,8 +697,8 @@ class NoPatternExpectation extends PatternExpectation {
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
* @access public * @access public
*/ */
function NoPatternExpectation($pattern, $message = '%s') { function __construct($pattern, $message = '%s') {
$this->PatternExpectation($pattern, $message); parent::__construct($pattern, $message);
} }
/** /**
@ -707,31 +721,23 @@ class NoPatternExpectation extends PatternExpectation {
*/ */
function testMessage($compare) { function testMessage($compare) {
if ($this->test($compare)) { if ($this->test($compare)) {
$dumper = &$this->_getDumper(); $dumper = $this->getDumper();
return "Pattern [" . $this->_getPattern() . return "Pattern [" . $this->getPattern() .
"] not detected in [" . "] not detected in [" .
$dumper->describeValue($compare) . "]"; $dumper->describeValue($compare) . "]";
} else { } else {
return $this->_describePatternMatch($this->_getPattern(), $compare); return $this->describePatternMatch($this->getPattern(), $compare);
} }
} }
} }
/**
* @package SimpleTest
* @subpackage UnitTester
* @deprecated
*/
class UnwantedPatternExpectation extends NoPatternExpectation {
}
/** /**
* Tests either type or class name if it's an object. * Tests either type or class name if it's an object.
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class IsAExpectation extends SimpleExpectation { class IsAExpectation extends SimpleExpectation {
var $_type; private $type;
/** /**
* Sets the type to compare with. * Sets the type to compare with.
@ -739,9 +745,9 @@ class IsAExpectation extends SimpleExpectation {
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
* @access public * @access public
*/ */
function IsAExpectation($type, $message = '%s') { function __construct($type, $message = '%s') {
$this->SimpleExpectation($message); parent::__construct($message);
$this->_type = $type; $this->type = $type;
} }
/** /**
@ -749,8 +755,8 @@ class IsAExpectation extends SimpleExpectation {
* @return string Type or class name. * @return string Type or class name.
* @access protected * @access protected
*/ */
function _getType() { protected function getType() {
return $this->_type; return $this->type;
} }
/** /**
@ -762,25 +768,25 @@ class IsAExpectation extends SimpleExpectation {
*/ */
function test($compare) { function test($compare) {
if (is_object($compare)) { if (is_object($compare)) {
return SimpleTestCompatibility::isA($compare, $this->_type); return SimpleTestCompatibility::isA($compare, $this->type);
} else { } else {
return (strtolower(gettype($compare)) == $this->_canonicalType($this->_type)); $function = 'is_'.$this->canonicalType($this->type);
if (is_callable($function)) {
return $function($compare);
}
return false;
} }
} }
/** /**
* Coerces type name into a gettype() match. * Coerces type name into a is_*() match.
* @param string $type User type. * @param string $type User type.
* @return string Simpler type. * @return string Simpler type.
* @access private * @access private
*/ */
function _canonicalType($type) { protected function canonicalType($type) {
$type = strtolower($type); $type = strtolower($type);
$map = array( $map = array('boolean' => 'bool');
'bool' => 'boolean',
'float' => 'double',
'real' => 'double',
'int' => 'integer');
if (isset($map[$type])) { if (isset($map[$type])) {
$type = $map[$type]; $type = $map[$type];
} }
@ -795,9 +801,9 @@ class IsAExpectation extends SimpleExpectation {
* @access public * @access public
*/ */
function testMessage($compare) { function testMessage($compare) {
$dumper = &$this->_getDumper(); $dumper = $this->getDumper();
return "Value [" . $dumper->describeValue($compare) . return "Value [" . $dumper->describeValue($compare) .
"] should be type [" . $this->_type . "]"; "] should be type [" . $this->type . "]";
} }
} }
@ -808,7 +814,7 @@ class IsAExpectation extends SimpleExpectation {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class NotAExpectation extends IsAExpectation { class NotAExpectation extends IsAExpectation {
var $_type; private $type;
/** /**
* Sets the type to compare with. * Sets the type to compare with.
@ -816,8 +822,8 @@ class NotAExpectation extends IsAExpectation {
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
* @access public * @access public
*/ */
function NotAExpectation($type, $message = '%s') { function __construct($type, $message = '%s') {
$this->IsAExpectation($type, $message); parent::__construct($type, $message);
} }
/** /**
@ -839,40 +845,38 @@ class NotAExpectation extends IsAExpectation {
* @access public * @access public
*/ */
function testMessage($compare) { function testMessage($compare) {
$dumper = &$this->_getDumper(); $dumper = $this->getDumper();
return "Value [" . $dumper->describeValue($compare) . return "Value [" . $dumper->describeValue($compare) .
"] should not be type [" . $this->_getType() . "]"; "] should not be type [" . $this->getType() . "]";
} }
} }
/** /**
* Tests for existance of a method in an object * Tests for existance of a method in an object
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class MethodExistsExpectation extends SimpleExpectation { class MethodExistsExpectation extends SimpleExpectation {
var $_method; private $method;
/** /**
* Sets the value to compare against. * Sets the value to compare against.
* @param string $method Method to check. * @param string $method Method to check.
* @param string $message Customised message on failure. * @param string $message Customised message on failure.
* @access public
* @return void * @return void
*/ */
function MethodExistsExpectation($method, $message = '%s') { function __construct($method, $message = '%s') {
$this->SimpleExpectation($message); parent::__construct($message);
$this->_method = &$method; $this->method = &$method;
} }
/** /**
* Tests the expectation. True if the method exists in the test object. * Tests the expectation. True if the method exists in the test object.
* @param string $compare Comparison method name. * @param string $compare Comparison method name.
* @return boolean True if correct. * @return boolean True if correct.
* @access public
*/ */
function test($compare) { function test($compare) {
return (boolean)(is_object($compare) && method_exists($compare, $this->_method)); return (boolean)(is_object($compare) && method_exists($compare, $this->method));
} }
/** /**
@ -880,16 +884,101 @@ class MethodExistsExpectation extends SimpleExpectation {
* @param mixed $compare Comparison value. * @param mixed $compare Comparison value.
* @return string Description of success * @return string Description of success
* or failure. * or failure.
* @access public
*/ */
function testMessage($compare) { function testMessage($compare) {
$dumper = &$this->_getDumper(); $dumper = $this->getDumper();
if (! is_object($compare)) { if (! is_object($compare)) {
return 'No method on non-object [' . $dumper->describeValue($compare) . ']'; return 'No method on non-object [' . $dumper->describeValue($compare) . ']';
} }
$method = $this->_method; $method = $this->method;
return "Object [" . $dumper->describeValue($compare) . return "Object [" . $dumper->describeValue($compare) .
"] should contain method [$method]"; "] should contain method [$method]";
} }
} }
/**
* Compares an object member's value even if private.
* @package SimpleTest
* @subpackage UnitTester
*/
class MemberExpectation extends IdenticalExpectation {
private $name;
/**
* Sets the value to compare against.
* @param string $method Method to check.
* @param string $message Customised message on failure.
* @return void
*/
function __construct($name, $expected) {
$this->name = $name;
parent::__construct($expected);
}
/**
* Tests the expectation. True if the property value is identical.
* @param object $actual Comparison object.
* @return boolean True if identical.
*/
function test($actual) {
if (! is_object($actual)) {
return false;
}
return parent::test($this->getProperty($this->name, $actual));
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
*/
function testMessage($actual) {
return parent::testMessage($this->getProperty($this->name, $actual));
}
/**
* Extracts the member value even if private using reflection.
* @param string $name Property name.
* @param object $object Object to read.
* @return mixed Value of property.
*/
private function getProperty($name, $object) {
$reflection = new ReflectionObject($object);
$property = $reflection->getProperty($name);
if (method_exists($property, 'setAccessible')) {
$property->setAccessible(true);
}
try {
return $property->getValue($object);
} catch (ReflectionException $e) {
return $this->getPrivatePropertyNoMatterWhat($name, $object);
}
}
/**
* Extracts a private member's value when reflection won't play ball.
* @param string $name Property name.
* @param object $object Object to read.
* @return mixed Value of property.
*/
private function getPrivatePropertyNoMatterWhat($name, $object) {
foreach ((array)$object as $mangled_name => $value) {
if ($this->unmangle($mangled_name) == $name) {
return $value;
}
}
}
/**
* Removes crud from property name after it's been converted
* to an array.
* @param string $mangled Name from array cast.
* @return string Cleaned up name.
*/
function unmangle($mangled) {
$parts = preg_split('/[^a-zA-Z0-9_\x7f-\xff]+/', $mangled);
return array_pop($parts);
}
}
?> ?>

View File

@ -3,7 +3,7 @@
* adapter for SimpleTest to use PEAR PHPUnit test cases * adapter for SimpleTest to use PEAR PHPUnit test cases
* @package SimpleTest * @package SimpleTest
* @subpackage Extensions * @subpackage Extensions
* @version $Id: pear_test_case.php 1388 2006-11-10 20:59:59Z lastcraft $ * @version $Id: pear_test_case.php 1836 2008-12-21 00:02:26Z edwardzyang $
*/ */
/**#@+ /**#@+
@ -22,15 +22,15 @@
* @subpackage Extensions * @subpackage Extensions
*/ */
class PHPUnit_TestCase extends SimpleTestCase { class PHPUnit_TestCase extends SimpleTestCase {
var $_loosely_typed; private $_loosely_typed;
/** /**
* Constructor. Sets the test name. * Constructor. Sets the test name.
* @param $label Test name to display. * @param $label Test name to display.
* @public * @public
*/ */
function PHPUnit_TestCase($label = false) { function __construct($label = false) {
$this->SimpleTestCase($label); parent::__construct($label);
$this->_loosely_typed = false; $this->_loosely_typed = false;
} }
@ -44,9 +44,9 @@
*/ */
function assertEquals($first, $second, $message = "%s", $delta = 0) { function assertEquals($first, $second, $message = "%s", $delta = 0) {
if ($this->_loosely_typed) { if ($this->_loosely_typed) {
$expectation = &new EqualExpectation($first); $expectation = new EqualExpectation($first);
} else { } else {
$expectation = &new IdenticalExpectation($first); $expectation = new IdenticalExpectation($first);
} }
$this->assert($expectation, $second, $message); $this->assert($expectation, $second, $message);
} }
@ -72,15 +72,14 @@
} }
/** /**
* In PHP5 the identity test tests for the same * Identity test tests for the same object.
* object. This is a reference test in PHP4.
* @param $first First object handle. * @param $first First object handle.
* @param $second Hopefully the same handle. * @param $second Hopefully the same handle.
* @param $message Message to display. * @param $message Message to display.
* @public * @public
*/ */
function assertSame(&$first, &$second, $message = "%s") { function assertSame($first, $second, $message = "%s") {
$dumper = &new SimpleDumper(); $dumper = new SimpleDumper();
$message = sprintf( $message = sprintf(
$message, $message,
"[" . $dumper->describeValue($first) . "[" . $dumper->describeValue($first) .
@ -93,15 +92,14 @@
} }
/** /**
* In PHP5 the identity test tests for the same * Inverted identity test.
* object. This is a reference test in PHP4.
* @param $first First object handle. * @param $first First object handle.
* @param $second Hopefully a different handle. * @param $second Hopefully a different handle.
* @param $message Message to display. * @param $message Message to display.
* @public * @public
*/ */
function assertNotSame(&$first, &$second, $message = "%s") { function assertNotSame($first, $second, $message = "%s") {
$dumper = &new SimpleDumper(); $dumper = new SimpleDumper();
$message = sprintf( $message = sprintf(
$message, $message,
"[" . $dumper->describeValue($first) . "[" . $dumper->describeValue($first) .
@ -195,4 +193,4 @@
function setName($name) { function setName($name) {
} }
} }
?> ?>

View File

@ -1,96 +0,0 @@
<?php
/**
* adapter for SimpleTest to use PHPUnit test cases
* @package SimpleTest
* @subpackage Extensions
* @version $Id: phpunit_test_case.php 1530 2007-06-04 23:35:45Z lastcraft $
*/
/**#@+
* include SimpleTest files
*/
require_once(dirname(__FILE__) . '/../unit_tester.php');
require_once(dirname(__FILE__) . '/../expectation.php');
/**#@-*/
/**
* Adapter for sourceforge PHPUnit test case to allow
* legacy test cases to be used with SimpleTest.
* @package SimpleTest
* @subpackage Extensions
*/
class TestCase extends SimpleTestCase {
/**
* Constructor. Sets the test name.
* @param $label Test name to display.
* @public
*/
function TestCase($label = false) {
$this->SimpleTestCase($label);
}
/**
* Sends pass if the test condition resolves true,
* a fail otherwise.
* @param $condition Condition to test true.
* @param $message Message to display.
* @public
*/
function assert($condition, $message = false) {
parent::assert(new TrueExpectation(), $condition, $message);
}
/**
* Will test straight equality if set to loose
* typing, or identity if not.
* @param $first First value.
* @param $second Comparison value.
* @param $message Message to display.
* @public
*/
function assertEquals($first, $second, $message = false) {
parent::assert(new EqualExpectation($first), $second, $message);
}
/**
* Simple string equality.
* @param $first First value.
* @param $second Comparison value.
* @param $message Message to display.
* @public
*/
function assertEqualsMultilineStrings($first, $second, $message = false) {
parent::assert(new EqualExpectation($first), $second, $message);
}
/**
* Tests a regex match.
* @param $pattern Regex to match.
* @param $subject String to search in.
* @param $message Message to display.
* @public
*/
function assertRegexp($pattern, $subject, $message = false) {
parent::assert(new PatternExpectation($pattern), $subject, $message);
}
/**
* Sends an error which we interpret as a fail
* with a different message for compatibility.
* @param $message Message to display.
* @public
*/
function error($message) {
parent::fail("Error triggered [$message]");
}
/**
* Accessor for name.
* @public
*/
function name() {
return $this->getLabel();
}
}
?>

23
contrib/simpletest/simpletest/extensions/testdox.php Normal file → Executable file
View File

@ -1,11 +1,22 @@
<?php <?php
/**
* Extension for a TestDox reporter
* @package SimpleTest
* @subpackage Extensions
* @version $Id: testdox.php 2004 2010-10-31 13:44:14Z jsweat $
*/
/**
* TestDox reporter
* @package SimpleTest
* @subpackage Extensions
*/
class TestDoxReporter extends SimpleReporter class TestDoxReporter extends SimpleReporter
{ {
var $_test_case_pattern = '/^TestOf(.*)$/'; var $_test_case_pattern = '/^TestOf(.*)$/';
function TestDoxReporter($test_case_pattern = '/^TestOf(.*)$/') { function __construct($test_case_pattern = '/^TestOf(.*)$/') {
parent::SimpleScorer(); parent::__construct();
$this->_test_case_pattern = empty($test_case_pattern) ? '/^(.*)$/' : $test_case_pattern; $this->_test_case_pattern = empty($test_case_pattern) ? '/^(.*)$/' : $test_case_pattern;
} }
@ -18,7 +29,7 @@ class TestDoxReporter extends SimpleReporter
} }
} }
function paintCaseEnd() { function paintCaseEnd($test_name) {
echo "\n"; echo "\n";
} }
@ -27,16 +38,16 @@ class TestDoxReporter extends SimpleReporter
return; return;
} }
$test_name = $matches[1]; $test_name = $matches[1];
$test_name = preg_replace('/([A-Z])([A-Z])/', '$1 $2', $test_name); $test_name = preg_replace('/([A-Z])([A-Z])/', '$1 $2', $test_name);
echo '- ' . strtolower(preg_replace('/([a-zA-Z])([A-Z0-9])/', '$1 $2', $test_name)); echo '- ' . strtolower(preg_replace('/([a-zA-Z])([A-Z0-9])/', '$1 $2', $test_name));
} }
function paintMethodEnd() { function paintMethodEnd($test_name) {
echo "\n"; echo "\n";
} }
function paintFail() { function paintFail($message) {
echo " [FAILED]"; echo " [FAILED]";
} }
} }
?>

View File

@ -1,5 +1,5 @@
<?php <?php
// $Id: test.php 1641 2008-01-22 20:13:52Z pp11 $ // $Id: test.php 1748 2008-04-14 01:50:41Z lastcraft $
require_once dirname(__FILE__) . '/../../autorun.php'; require_once dirname(__FILE__) . '/../../autorun.php';
require_once dirname(__FILE__) . '/../testdox.php'; require_once dirname(__FILE__) . '/../testdox.php';
@ -19,7 +19,7 @@ class TestOfTestDoxReporter extends UnitTestCase
ob_start(); ob_start();
$dox->paintCaseStart('TestOfTestDoxReporter'); $dox->paintCaseStart('TestOfTestDoxReporter');
$buffer = ob_get_clean(); $buffer = ob_get_clean();
$this->assertWantedPattern('/^TestDoxReporter/', $buffer); $this->assertPattern('/^TestDoxReporter/', $buffer);
} }
function testOutputOfTestCaseNameFilteredByConstructParameter() { function testOutputOfTestCaseNameFilteredByConstructParameter() {
@ -27,7 +27,7 @@ class TestOfTestDoxReporter extends UnitTestCase
ob_start(); ob_start();
$dox->paintCaseStart('SomeGreatWidgetTest'); $dox->paintCaseStart('SomeGreatWidgetTest');
$buffer = ob_get_clean(); $buffer = ob_get_clean();
$this->assertWantedPattern('/^SomeGreatWidget/', $buffer); $this->assertPattern('/^SomeGreatWidget/', $buffer);
} }
function testIfTest_case_patternIsEmptyAssumeEverythingMatches() { function testIfTest_case_patternIsEmptyAssumeEverythingMatches() {
@ -35,7 +35,7 @@ class TestOfTestDoxReporter extends UnitTestCase
ob_start(); ob_start();
$dox->paintCaseStart('TestOfTestDoxReporter'); $dox->paintCaseStart('TestOfTestDoxReporter');
$buffer = ob_get_clean(); $buffer = ob_get_clean();
$this->assertWantedPattern('/^TestOfTestDoxReporter/', $buffer); $this->assertPattern('/^TestOfTestDoxReporter/', $buffer);
} }
function testEmptyLineInsertedWhenCaseEnds() { function testEmptyLineInsertedWhenCaseEnds() {
@ -75,7 +75,6 @@ class TestOfTestDoxReporter extends UnitTestCase
$dox->paintMethodEnd('someMethod'); $dox->paintMethodEnd('someMethod');
$buffer = ob_get_clean(); $buffer = ob_get_clean();
$this->assertEqual("\n", $buffer); $this->assertEqual("\n", $buffer);
$this->assertNoErrors();
} }
function testProperlySpacesSingleLettersInMethodName() { function testProperlySpacesSingleLettersInMethodName() {
@ -89,7 +88,7 @@ class TestOfTestDoxReporter extends UnitTestCase
function testOnFailureThisPrintsFailureNotice() { function testOnFailureThisPrintsFailureNotice() {
$dox = new TestDoxReporter(); $dox = new TestDoxReporter();
ob_start(); ob_start();
$dox->paintFail(); $dox->paintFail('');
$buffer = ob_get_clean(); $buffer = ob_get_clean();
$this->assertEqual(' [FAILED]', $buffer); $this->assertEqual(' [FAILED]', $buffer);
} }
@ -105,4 +104,4 @@ class TestOfTestDoxReporter extends UnitTestCase
); );
} }
} }
?>

View File

@ -3,9 +3,9 @@
* Base include file for SimpleTest. * Base include file for SimpleTest.
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
* @version $Id: form.php 1672 2008-03-02 04:47:34Z edwardzyang $ * @version $Id: form.php 2013 2011-04-29 09:29:45Z pp11 $
*/ */
/**#@+ /**#@+
* include SimpleTest files * include SimpleTest files
*/ */
@ -20,42 +20,42 @@ require_once(dirname(__FILE__) . '/selector.php');
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleForm { class SimpleForm {
var $_method; private $method;
var $_action; private $action;
var $_encoding; private $encoding;
var $_default_target; private $default_target;
var $_id; private $id;
var $_buttons; private $buttons;
var $_images; private $images;
var $_widgets; private $widgets;
var $_radios; private $radios;
var $_checkboxes; private $checkboxes;
/** /**
* Starts with no held controls/widgets. * Starts with no held controls/widgets.
* @param SimpleTag $tag Form tag to read. * @param SimpleTag $tag Form tag to read.
* @param SimplePage $page Holding page. * @param SimplePage $page Holding page.
*/ */
function SimpleForm($tag, &$page) { function __construct($tag, $page) {
$this->_method = $tag->getAttribute('method'); $this->method = $tag->getAttribute('method');
$this->_action = $this->_createAction($tag->getAttribute('action'), $page); $this->action = $this->createAction($tag->getAttribute('action'), $page);
$this->_encoding = $this->_setEncodingClass($tag); $this->encoding = $this->setEncodingClass($tag);
$this->_default_target = false; $this->default_target = false;
$this->_id = $tag->getAttribute('id'); $this->id = $tag->getAttribute('id');
$this->_buttons = array(); $this->buttons = array();
$this->_images = array(); $this->images = array();
$this->_widgets = array(); $this->widgets = array();
$this->_radios = array(); $this->radios = array();
$this->_checkboxes = array(); $this->checkboxes = array();
} }
/** /**
* Creates the request packet to be sent by the form. * Creates the request packet to be sent by the form.
* @param SimpleTag $tag Form tag to read. * @param SimpleTag $tag Form tag to read.
* @return string Packet class. * @return string Packet class.
* @access private * @access private
*/ */
function _setEncodingClass($tag) { protected function setEncodingClass($tag) {
if (strtolower($tag->getAttribute('method')) == 'post') { if (strtolower($tag->getAttribute('method')) == 'post') {
if (strtolower($tag->getAttribute('enctype')) == 'multipart/form-data') { if (strtolower($tag->getAttribute('enctype')) == 'multipart/form-data') {
return 'SimpleMultipartEncoding'; return 'SimpleMultipartEncoding';
@ -64,25 +64,25 @@ class SimpleForm {
} }
return 'SimpleGetEncoding'; return 'SimpleGetEncoding';
} }
/** /**
* Sets the frame target within a frameset. * Sets the frame target within a frameset.
* @param string $frame Name of frame. * @param string $frame Name of frame.
* @access public * @access public
*/ */
function setDefaultTarget($frame) { function setDefaultTarget($frame) {
$this->_default_target = $frame; $this->default_target = $frame;
} }
/** /**
* Accessor for method of form submission. * Accessor for method of form submission.
* @return string Either get or post. * @return string Either get or post.
* @access public * @access public
*/ */
function getMethod() { function getMethod() {
return ($this->_method ? strtolower($this->_method) : 'get'); return ($this->method ? strtolower($this->method) : 'get');
} }
/** /**
* Combined action attribute with current location * Combined action attribute with current location
* to get an absolute form target. * to get an absolute form target.
@ -90,114 +90,116 @@ class SimpleForm {
* @param SimpleUrl $base Page location. * @param SimpleUrl $base Page location.
* @return SimpleUrl Absolute form target. * @return SimpleUrl Absolute form target.
*/ */
function _createAction($action, &$page) { protected function createAction($action, $page) {
if (($action === '') || ($action === false)) { if (($action === '') || ($action === false)) {
return $page->expandUrl($page->getUrl()); return $page->expandUrl($page->getUrl());
} }
return $page->expandUrl(new SimpleUrl($action));; return $page->expandUrl(new SimpleUrl($action));;
} }
/** /**
* Absolute URL of the target. * Absolute URL of the target.
* @return SimpleUrl URL target. * @return SimpleUrl URL target.
* @access public * @access public
*/ */
function getAction() { function getAction() {
$url = $this->_action; $url = $this->action;
if ($this->_default_target && ! $url->getTarget()) { if ($this->default_target && ! $url->getTarget()) {
$url->setTarget($this->_default_target); $url->setTarget($this->default_target);
}
if ($this->getMethod() == 'get') {
$url->clearRequest();
} }
return $url; return $url;
} }
/** /**
* Creates the encoding for the current values in the * Creates the encoding for the current values in the
* form. * form.
* @return SimpleFormEncoding Request to submit. * @return SimpleFormEncoding Request to submit.
* @access private * @access private
*/ */
function _encode() { protected function encode() {
$class = $this->_encoding; $class = $this->encoding;
$encoding = new $class(); $encoding = new $class();
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
$this->_widgets[$i]->write($encoding); $this->widgets[$i]->write($encoding);
} }
return $encoding; return $encoding;
} }
/** /**
* ID field of form for unique identification. * ID field of form for unique identification.
* @return string Unique tag ID. * @return string Unique tag ID.
* @access public * @access public
*/ */
function getId() { function getId() {
return $this->_id; return $this->id;
} }
/** /**
* Adds a tag contents to the form. * Adds a tag contents to the form.
* @param SimpleWidget $tag Input tag to add. * @param SimpleWidget $tag Input tag to add.
* @access public
*/ */
function addWidget(&$tag) { function addWidget($tag) {
if (strtolower($tag->getAttribute('type')) == 'submit') { if (strtolower($tag->getAttribute('type')) == 'submit') {
$this->_buttons[] = &$tag; $this->buttons[] = $tag;
} elseif (strtolower($tag->getAttribute('type')) == 'image') { } elseif (strtolower($tag->getAttribute('type')) == 'image') {
$this->_images[] = &$tag; $this->images[] = $tag;
} elseif ($tag->getName()) { } elseif ($tag->getName()) {
$this->_setWidget($tag); $this->setWidget($tag);
} }
} }
/** /**
* Sets the widget into the form, grouping radio * Sets the widget into the form, grouping radio
* buttons if any. * buttons if any.
* @param SimpleWidget $tag Incoming form control. * @param SimpleWidget $tag Incoming form control.
* @access private * @access private
*/ */
function _setWidget(&$tag) { protected function setWidget($tag) {
if (strtolower($tag->getAttribute('type')) == 'radio') { if (strtolower($tag->getAttribute('type')) == 'radio') {
$this->_addRadioButton($tag); $this->addRadioButton($tag);
} elseif (strtolower($tag->getAttribute('type')) == 'checkbox') { } elseif (strtolower($tag->getAttribute('type')) == 'checkbox') {
$this->_addCheckbox($tag); $this->addCheckbox($tag);
} else { } else {
$this->_widgets[] = &$tag; $this->widgets[] = &$tag;
} }
} }
/** /**
* Adds a radio button, building a group if necessary. * Adds a radio button, building a group if necessary.
* @param SimpleRadioButtonTag $tag Incoming form control. * @param SimpleRadioButtonTag $tag Incoming form control.
* @access private * @access private
*/ */
function _addRadioButton(&$tag) { protected function addRadioButton($tag) {
if (! isset($this->_radios[$tag->getName()])) { if (! isset($this->radios[$tag->getName()])) {
$this->_widgets[] = &new SimpleRadioGroup(); $this->widgets[] = new SimpleRadioGroup();
$this->_radios[$tag->getName()] = count($this->_widgets) - 1; $this->radios[$tag->getName()] = count($this->widgets) - 1;
} }
$this->_widgets[$this->_radios[$tag->getName()]]->addWidget($tag); $this->widgets[$this->radios[$tag->getName()]]->addWidget($tag);
} }
/** /**
* Adds a checkbox, making it a group on a repeated name. * Adds a checkbox, making it a group on a repeated name.
* @param SimpleCheckboxTag $tag Incoming form control. * @param SimpleCheckboxTag $tag Incoming form control.
* @access private * @access private
*/ */
function _addCheckbox(&$tag) { protected function addCheckbox($tag) {
if (! isset($this->_checkboxes[$tag->getName()])) { if (! isset($this->checkboxes[$tag->getName()])) {
$this->_widgets[] = &$tag; $this->widgets[] = $tag;
$this->_checkboxes[$tag->getName()] = count($this->_widgets) - 1; $this->checkboxes[$tag->getName()] = count($this->widgets) - 1;
} else { } else {
$index = $this->_checkboxes[$tag->getName()]; $index = $this->checkboxes[$tag->getName()];
if (! SimpleTestCompatibility::isA($this->_widgets[$index], 'SimpleCheckboxGroup')) { if (! SimpleTestCompatibility::isA($this->widgets[$index], 'SimpleCheckboxGroup')) {
$previous = &$this->_widgets[$index]; $previous = $this->widgets[$index];
$this->_widgets[$index] = &new SimpleCheckboxGroup(); $this->widgets[$index] = new SimpleCheckboxGroup();
$this->_widgets[$index]->addWidget($previous); $this->widgets[$index]->addWidget($previous);
} }
$this->_widgets[$index]->addWidget($tag); $this->widgets[$index]->addWidget($tag);
} }
} }
/** /**
* Extracts current value from form. * Extracts current value from form.
* @param SimpleSelector $selector Criteria to apply. * @param SimpleSelector $selector Criteria to apply.
@ -206,19 +208,19 @@ class SimpleForm {
* @access public * @access public
*/ */
function getValue($selector) { function getValue($selector) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
if ($selector->isMatch($this->_widgets[$i])) { if ($selector->isMatch($this->widgets[$i])) {
return $this->_widgets[$i]->getValue(); return $this->widgets[$i]->getValue();
} }
} }
foreach ($this->_buttons as $button) { foreach ($this->buttons as $button) {
if ($selector->isMatch($button)) { if ($selector->isMatch($button)) {
return $button->getValue(); return $button->getValue();
} }
} }
return null; return null;
} }
/** /**
* Sets a widget value within the form. * Sets a widget value within the form.
* @param SimpleSelector $selector Criteria to apply. * @param SimpleSelector $selector Criteria to apply.
@ -231,11 +233,11 @@ class SimpleForm {
function setField($selector, $value, $position=false) { function setField($selector, $value, $position=false) {
$success = false; $success = false;
$_position = 0; $_position = 0;
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
if ($selector->isMatch($this->_widgets[$i])) { if ($selector->isMatch($this->widgets[$i])) {
$_position++; $_position++;
if ($position === false or $_position === (int)$position) { if ($position === false or $_position === (int)$position) {
if ($this->_widgets[$i]->setValue($value)) { if ($this->widgets[$i]->setValue($value)) {
$success = true; $success = true;
} }
} }
@ -243,7 +245,7 @@ class SimpleForm {
} }
return $success; return $success;
} }
/** /**
* Used by the page object to set widgets labels to * Used by the page object to set widgets labels to
* external label tags. * external label tags.
@ -251,16 +253,16 @@ class SimpleForm {
* @access public * @access public
*/ */
function attachLabelBySelector($selector, $label) { function attachLabelBySelector($selector, $label) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
if ($selector->isMatch($this->_widgets[$i])) { if ($selector->isMatch($this->widgets[$i])) {
if (method_exists($this->_widgets[$i], 'setLabel')) { if (method_exists($this->widgets[$i], 'setLabel')) {
$this->_widgets[$i]->setLabel($label); $this->widgets[$i]->setLabel($label);
return; return;
} }
} }
} }
} }
/** /**
* Test to see if a form has a submit button. * Test to see if a form has a submit button.
* @param SimpleSelector $selector Criteria to apply. * @param SimpleSelector $selector Criteria to apply.
@ -268,14 +270,14 @@ class SimpleForm {
* @access public * @access public
*/ */
function hasSubmit($selector) { function hasSubmit($selector) {
foreach ($this->_buttons as $button) { foreach ($this->buttons as $button) {
if ($selector->isMatch($button)) { if ($selector->isMatch($button)) {
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* Test to see if a form has an image control. * Test to see if a form has an image control.
* @param SimpleSelector $selector Criteria to apply. * @param SimpleSelector $selector Criteria to apply.
@ -283,14 +285,14 @@ class SimpleForm {
* @access public * @access public
*/ */
function hasImage($selector) { function hasImage($selector) {
foreach ($this->_images as $image) { foreach ($this->images as $image) {
if ($selector->isMatch($image)) { if ($selector->isMatch($image)) {
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* Gets the submit values for a selected button. * Gets the submit values for a selected button.
* @param SimpleSelector $selector Criteria to apply. * @param SimpleSelector $selector Criteria to apply.
@ -302,19 +304,19 @@ class SimpleForm {
*/ */
function submitButton($selector, $additional = false) { function submitButton($selector, $additional = false) {
$additional = $additional ? $additional : array(); $additional = $additional ? $additional : array();
foreach ($this->_buttons as $button) { foreach ($this->buttons as $button) {
if ($selector->isMatch($button)) { if ($selector->isMatch($button)) {
$encoding = $this->_encode(); $encoding = $this->encode();
$button->write($encoding); $button->write($encoding);
if ($additional) { if ($additional) {
$encoding->merge($additional); $encoding->merge($additional);
} }
return $encoding; return $encoding;
} }
} }
return false; return false;
} }
/** /**
* Gets the submit values for an image. * Gets the submit values for an image.
* @param SimpleSelector $selector Criteria to apply. * @param SimpleSelector $selector Criteria to apply.
@ -328,19 +330,19 @@ class SimpleForm {
*/ */
function submitImage($selector, $x, $y, $additional = false) { function submitImage($selector, $x, $y, $additional = false) {
$additional = $additional ? $additional : array(); $additional = $additional ? $additional : array();
foreach ($this->_images as $image) { foreach ($this->images as $image) {
if ($selector->isMatch($image)) { if ($selector->isMatch($image)) {
$encoding = $this->_encode(); $encoding = $this->encode();
$image->write($encoding, $x, $y); $image->write($encoding, $x, $y);
if ($additional) { if ($additional) {
$encoding->merge($additional); $encoding->merge($additional);
} }
return $encoding; return $encoding;
} }
} }
return false; return false;
} }
/** /**
* Simply submits the form without the submit button * Simply submits the form without the submit button
* value. Used when there is only one button or it * value. Used when there is only one button or it
@ -348,8 +350,12 @@ class SimpleForm {
* @return hash Submitted values. * @return hash Submitted values.
* @access public * @access public
*/ */
function submit() { function submit($additional = false) {
return $this->_encode(); $encoding = $this->encode();
if ($additional) {
$encoding->merge($additional);
}
return $encoding;
} }
} }
?> ?>

246
contrib/simpletest/simpletest/frames.php Normal file → Executable file
View File

@ -3,7 +3,7 @@
* Base include file for SimpleTest * Base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
* @version $Id: frames.php 1672 2008-03-02 04:47:34Z edwardzyang $ * @version $Id: frames.php 1784 2008-04-26 13:07:14Z pp11 $
*/ */
/**#@+ /**#@+
@ -22,21 +22,21 @@ require_once(dirname(__FILE__) . '/user_agent.php');
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleFrameset { class SimpleFrameset {
var $_frameset; private $frameset;
var $_frames; private $frames;
var $_focus; private $focus;
var $_names; private $names;
/** /**
* Stashes the frameset page. Will make use of the * Stashes the frameset page. Will make use of the
* browser to fetch the sub frames recursively. * browser to fetch the sub frames recursively.
* @param SimplePage $page Frameset page. * @param SimplePage $page Frameset page.
*/ */
function SimpleFrameset(&$page) { function __construct($page) {
$this->_frameset = &$page; $this->frameset = $page;
$this->_frames = array(); $this->frames = array();
$this->_focus = false; $this->focus = false;
$this->_names = array(); $this->names = array();
} }
/** /**
@ -45,10 +45,10 @@ class SimpleFrameset {
* @param string $name Name of frame in frameset. * @param string $name Name of frame in frameset.
* @access public * @access public
*/ */
function addFrame(&$page, $name = false) { function addFrame($page, $name = false) {
$this->_frames[] = &$page; $this->frames[] = $page;
if ($name) { if ($name) {
$this->_names[$name] = count($this->_frames) - 1; $this->names[$name] = count($this->frames) - 1;
} }
} }
@ -60,18 +60,18 @@ class SimpleFrameset {
* @param SimplePage $page Frame source. * @param SimplePage $page Frame source.
* @access public * @access public
*/ */
function setFrame($path, &$page) { function setFrame($path, $page) {
$name = array_shift($path); $name = array_shift($path);
if (isset($this->_names[$name])) { if (isset($this->names[$name])) {
$index = $this->_names[$name]; $index = $this->names[$name];
} else { } else {
$index = $name - 1; $index = $name - 1;
} }
if (count($path) == 0) { if (count($path) == 0) {
$this->_frames[$index] = &$page; $this->frames[$index] = &$page;
return; return;
} }
$this->_frames[$index]->setFrame($path, $page); $this->frames[$index]->setFrame($path, $page);
} }
/** /**
@ -82,12 +82,12 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getFrameFocus() { function getFrameFocus() {
if ($this->_focus === false) { if ($this->focus === false) {
return array(); return array();
} }
return array_merge( return array_merge(
array($this->_getPublicNameFromIndex($this->_focus)), array($this->getPublicNameFromIndex($this->focus)),
$this->_frames[$this->_focus]->getFrameFocus()); $this->frames[$this->focus]->getFrameFocus());
} }
/** /**
@ -98,8 +98,8 @@ class SimpleFrameset {
* @return integer/string Public name. * @return integer/string Public name.
* @access private * @access private
*/ */
function _getPublicNameFromIndex($subject) { protected function getPublicNameFromIndex($subject) {
foreach ($this->_names as $name => $index) { foreach ($this->names as $name => $index) {
if ($subject == $index) { if ($subject == $index) {
return $name; return $name;
} }
@ -116,15 +116,15 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function setFrameFocusByIndex($choice) { function setFrameFocusByIndex($choice) {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
if ($this->_frames[$this->_focus]->hasFrames()) { if ($this->frames[$this->focus]->hasFrames()) {
return $this->_frames[$this->_focus]->setFrameFocusByIndex($choice); return $this->frames[$this->focus]->setFrameFocusByIndex($choice);
} }
} }
if (($choice < 1) || ($choice > count($this->_frames))) { if (($choice < 1) || ($choice > count($this->frames))) {
return false; return false;
} }
$this->_focus = $choice - 1; $this->focus = $choice - 1;
return true; return true;
} }
@ -137,13 +137,13 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function setFrameFocus($name) { function setFrameFocus($name) {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
if ($this->_frames[$this->_focus]->hasFrames()) { if ($this->frames[$this->focus]->hasFrames()) {
return $this->_frames[$this->_focus]->setFrameFocus($name); return $this->frames[$this->focus]->setFrameFocus($name);
} }
} }
if (in_array($name, array_keys($this->_names))) { if (in_array($name, array_keys($this->names))) {
$this->_focus = $this->_names[$name]; $this->focus = $this->names[$name];
return true; return true;
} }
return false; return false;
@ -154,17 +154,17 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function clearFrameFocus() { function clearFrameFocus() {
$this->_focus = false; $this->focus = false;
$this->_clearNestedFramesFocus(); $this->clearNestedFramesFocus();
} }
/** /**
* Clears the frame focus for any nested frames. * Clears the frame focus for any nested frames.
* @access private * @access private
*/ */
function _clearNestedFramesFocus() { protected function clearNestedFramesFocus() {
for ($i = 0; $i < count($this->_frames); $i++) { for ($i = 0; $i < count($this->frames); $i++) {
$this->_frames[$i]->clearFrameFocus(); $this->frames[$i]->clearFrameFocus();
} }
} }
@ -186,9 +186,9 @@ class SimpleFrameset {
*/ */
function getFrames() { function getFrames() {
$report = array(); $report = array();
for ($i = 0; $i < count($this->_frames); $i++) { for ($i = 0; $i < count($this->frames); $i++) {
$report[$this->_getPublicNameFromIndex($i)] = $report[$this->getPublicNameFromIndex($i)] =
$this->_frames[$i]->getFrames(); $this->frames[$i]->getFrames();
} }
return $report; return $report;
} }
@ -200,12 +200,12 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getRaw() { function getRaw() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_frames[$this->_focus]->getRaw(); return $this->frames[$this->focus]->getRaw();
} }
$raw = ''; $raw = '';
for ($i = 0; $i < count($this->_frames); $i++) { for ($i = 0; $i < count($this->frames); $i++) {
$raw .= $this->_frames[$i]->getRaw(); $raw .= $this->frames[$i]->getRaw();
} }
return $raw; return $raw;
} }
@ -217,12 +217,12 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getText() { function getText() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_frames[$this->_focus]->getText(); return $this->frames[$this->focus]->getText();
} }
$raw = ''; $raw = '';
for ($i = 0; $i < count($this->_frames); $i++) { for ($i = 0; $i < count($this->frames); $i++) {
$raw .= ' ' . $this->_frames[$i]->getText(); $raw .= ' ' . $this->frames[$i]->getText();
} }
return trim($raw); return trim($raw);
} }
@ -233,10 +233,10 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getTransportError() { function getTransportError() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_frames[$this->_focus]->getTransportError(); return $this->frames[$this->focus]->getTransportError();
} }
return $this->_frameset->getTransportError(); return $this->frameset->getTransportError();
} }
/** /**
@ -245,10 +245,10 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getMethod() { function getMethod() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_frames[$this->_focus]->getMethod(); return $this->frames[$this->focus]->getMethod();
} }
return $this->_frameset->getMethod(); return $this->frameset->getMethod();
} }
/** /**
@ -257,11 +257,11 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getUrl() { function getUrl() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
$url = $this->_frames[$this->_focus]->getUrl(); $url = $this->frames[$this->focus]->getUrl();
$url->setTarget($this->_getPublicNameFromIndex($this->_focus)); $url->setTarget($this->getPublicNameFromIndex($this->focus));
} else { } else {
$url = $this->_frameset->getUrl(); $url = $this->frameset->getUrl();
} }
return $url; return $url;
} }
@ -272,10 +272,10 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getBaseUrl() { function getBaseUrl() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
$url = $this->_frames[$this->_focus]->getBaseUrl(); $url = $this->frames[$this->focus]->getBaseUrl();
} else { } else {
$url = $this->_frameset->getBaseUrl(); $url = $this->frameset->getBaseUrl();
} }
return $url; return $url;
} }
@ -288,7 +288,7 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function expandUrl($url) { function expandUrl($url) {
return $this->_frameset->expandUrl($url); return $this->frameset->expandUrl($url);
} }
/** /**
@ -297,10 +297,10 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getRequestData() { function getRequestData() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_frames[$this->_focus]->getRequestData(); return $this->frames[$this->focus]->getRequestData();
} }
return $this->_frameset->getRequestData(); return $this->frameset->getRequestData();
} }
/** /**
@ -309,10 +309,10 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getMimeType() { function getMimeType() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_frames[$this->_focus]->getMimeType(); return $this->frames[$this->focus]->getMimeType();
} }
return $this->_frameset->getMimeType(); return $this->frameset->getMimeType();
} }
/** /**
@ -321,10 +321,10 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getResponseCode() { function getResponseCode() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_frames[$this->_focus]->getResponseCode(); return $this->frames[$this->focus]->getResponseCode();
} }
return $this->_frameset->getResponseCode(); return $this->frameset->getResponseCode();
} }
/** /**
@ -334,10 +334,10 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getAuthentication() { function getAuthentication() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_frames[$this->_focus]->getAuthentication(); return $this->frames[$this->focus]->getAuthentication();
} }
return $this->_frameset->getAuthentication(); return $this->frameset->getAuthentication();
} }
/** /**
@ -347,10 +347,10 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getRealm() { function getRealm() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_frames[$this->_focus]->getRealm(); return $this->frames[$this->focus]->getRealm();
} }
return $this->_frameset->getRealm(); return $this->frameset->getRealm();
} }
/** /**
@ -359,10 +359,10 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getRequest() { function getRequest() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_frames[$this->_focus]->getRequest(); return $this->frames[$this->focus]->getRequest();
} }
return $this->_frameset->getRequest(); return $this->frameset->getRequest();
} }
/** /**
@ -371,10 +371,10 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getHeaders() { function getHeaders() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_frames[$this->_focus]->getHeaders(); return $this->frames[$this->focus]->getHeaders();
} }
return $this->_frameset->getHeaders(); return $this->frameset->getHeaders();
} }
/** /**
@ -383,7 +383,7 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getTitle() { function getTitle() {
return $this->_frameset->getTitle(); return $this->frameset->getTitle();
} }
/** /**
@ -392,11 +392,11 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getUrls() { function getUrls() {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_frames[$this->_focus]->getUrls(); return $this->frames[$this->focus]->getUrls();
} }
$urls = array(); $urls = array();
foreach ($this->_frames as $frame) { foreach ($this->frames as $frame) {
$urls = array_merge($urls, $frame->getUrls()); $urls = array_merge($urls, $frame->getUrls());
} }
return array_values(array_unique($urls)); return array_values(array_unique($urls));
@ -410,16 +410,16 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getUrlsByLabel($label) { function getUrlsByLabel($label) {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
return $this->_tagUrlsWithFrame( return $this->tagUrlsWithFrame(
$this->_frames[$this->_focus]->getUrlsByLabel($label), $this->frames[$this->focus]->getUrlsByLabel($label),
$this->_focus); $this->focus);
} }
$urls = array(); $urls = array();
foreach ($this->_frames as $index => $frame) { foreach ($this->frames as $index => $frame) {
$urls = array_merge( $urls = array_merge(
$urls, $urls,
$this->_tagUrlsWithFrame( $this->tagUrlsWithFrame(
$frame->getUrlsByLabel($label), $frame->getUrlsByLabel($label),
$index)); $index));
} }
@ -436,10 +436,10 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getUrlById($id) { function getUrlById($id) {
foreach ($this->_frames as $index => $frame) { foreach ($this->frames as $index => $frame) {
if ($url = $frame->getUrlById($id)) { if ($url = $frame->getUrlById($id)) {
if (! $url->gettarget()) { if (! $url->gettarget()) {
$url->setTarget($this->_getPublicNameFromIndex($index)); $url->setTarget($this->getPublicNameFromIndex($index));
} }
return $url; return $url;
} }
@ -454,11 +454,11 @@ class SimpleFrameset {
* @return array List of tagged URLs. * @return array List of tagged URLs.
* @access private * @access private
*/ */
function _tagUrlsWithFrame($urls, $frame) { protected function tagUrlsWithFrame($urls, $frame) {
$tagged = array(); $tagged = array();
foreach ($urls as $url) { foreach ($urls as $url) {
if (! $url->getTarget()) { if (! $url->getTarget()) {
$url->setTarget($this->_getPublicNameFromIndex($frame)); $url->setTarget($this->getPublicNameFromIndex($frame));
} }
$tagged[] = $url; $tagged[] = $url;
} }
@ -473,9 +473,8 @@ class SimpleFrameset {
* the button. * the button.
* @access public * @access public
*/ */
function &getFormBySubmit($selector) { function getFormBySubmit($selector) {
$form = &$this->_findForm('getFormBySubmit', $selector); return $this->findForm('getFormBySubmit', $selector);
return $form;
} }
/** /**
@ -488,9 +487,8 @@ class SimpleFrameset {
* the image. * the image.
* @access public * @access public
*/ */
function &getFormByImage($selector) { function getFormByImage($selector) {
$form = &$this->_findForm('getFormByImage', $selector); return $this->findForm('getFormByImage', $selector);
return $form;
} }
/** /**
@ -503,9 +501,8 @@ class SimpleFrameset {
* @return SimpleForm Form object containing the matching ID. * @return SimpleForm Form object containing the matching ID.
* @access public * @access public
*/ */
function &getFormById($id) { function getFormById($id) {
$form = &$this->_findForm('getFormById', $id); return $this->findForm('getFormById', $id);
return $form;
} }
/** /**
@ -516,18 +513,17 @@ class SimpleFrameset {
* @return SimpleForm Form object containing the matching ID. * @return SimpleForm Form object containing the matching ID.
* @access private * @access private
*/ */
function &_findForm($method, $attribute) { protected function findForm($method, $attribute) {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
$form = &$this->_findFormInFrame( return $this->findFormInFrame(
$this->_frames[$this->_focus], $this->frames[$this->focus],
$this->_focus, $this->focus,
$method, $method,
$attribute); $attribute);
return $form;
} }
for ($i = 0; $i < count($this->_frames); $i++) { for ($i = 0; $i < count($this->frames); $i++) {
$form = &$this->_findFormInFrame( $form = $this->findFormInFrame(
$this->_frames[$i], $this->frames[$i],
$i, $i,
$method, $method,
$attribute); $attribute);
@ -549,10 +545,10 @@ class SimpleFrameset {
* @return SimpleForm Form object containing the matching ID. * @return SimpleForm Form object containing the matching ID.
* @access private * @access private
*/ */
function &_findFormInFrame(&$page, $index, $method, $attribute) { protected function findFormInFrame($page, $index, $method, $attribute) {
$form = &$this->_frames[$index]->$method($attribute); $form = $this->frames[$index]->$method($attribute);
if (isset($form)) { if (isset($form)) {
$form->setDefaultTarget($this->_getPublicNameFromIndex($index)); $form->setDefaultTarget($this->getPublicNameFromIndex($index));
} }
return $form; return $form;
} }
@ -566,11 +562,11 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function setField($selector, $value) { function setField($selector, $value) {
if (is_integer($this->_focus)) { if (is_integer($this->focus)) {
$this->_frames[$this->_focus]->setField($selector, $value); $this->frames[$this->focus]->setField($selector, $value);
} else { } else {
for ($i = 0; $i < count($this->_frames); $i++) { for ($i = 0; $i < count($this->frames); $i++) {
$this->_frames[$i]->setField($selector, $value); $this->frames[$i]->setField($selector, $value);
} }
} }
} }
@ -584,8 +580,8 @@ class SimpleFrameset {
* @access public * @access public
*/ */
function getField($selector) { function getField($selector) {
for ($i = 0; $i < count($this->_frames); $i++) { for ($i = 0; $i < count($this->frames); $i++) {
$value = $this->_frames[$i]->getField($selector); $value = $this->frames[$i]->getField($selector);
if (isset($value)) { if (isset($value)) {
return $value; return $value;
} }

View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
* @version $Id: http.php 1722 2008-04-07 19:30:56Z lastcraft $ * @version $Id: http.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/**#@+ /**#@+
@ -21,50 +21,50 @@ require_once(dirname(__FILE__) . '/url.php');
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleRoute { class SimpleRoute {
var $_url; private $url;
/** /**
* Sets the target URL. * Sets the target URL.
* @param SimpleUrl $url URL as object. * @param SimpleUrl $url URL as object.
* @access public * @access public
*/ */
function SimpleRoute($url) { function __construct($url) {
$this->_url = $url; $this->url = $url;
} }
/** /**
* Resource name. * Resource name.
* @return SimpleUrl Current url. * @return SimpleUrl Current url.
* @access protected * @access protected
*/ */
function getUrl() { function getUrl() {
return $this->_url; return $this->url;
} }
/** /**
* Creates the first line which is the actual request. * Creates the first line which is the actual request.
* @param string $method HTTP request method, usually GET. * @param string $method HTTP request method, usually GET.
* @return string Request line content. * @return string Request line content.
* @access protected * @access protected
*/ */
function _getRequestLine($method) { protected function getRequestLine($method) {
return $method . ' ' . $this->_url->getPath() . return $method . ' ' . $this->url->getPath() .
$this->_url->getEncodedRequest() . ' HTTP/1.0'; $this->url->getEncodedRequest() . ' HTTP/1.0';
} }
/** /**
* Creates the host part of the request. * Creates the host part of the request.
* @return string Host line content. * @return string Host line content.
* @access protected * @access protected
*/ */
function _getHostLine() { protected function getHostLine() {
$line = 'Host: ' . $this->_url->getHost(); $line = 'Host: ' . $this->url->getHost();
if ($this->_url->getPort()) { if ($this->url->getPort()) {
$line .= ':' . $this->_url->getPort(); $line .= ':' . $this->url->getPort();
} }
return $line; return $line;
} }
/** /**
* Opens a socket to the route. * Opens a socket to the route.
* @param string $method HTTP request method, usually GET. * @param string $method HTTP request method, usually GET.
@ -72,21 +72,21 @@ class SimpleRoute {
* @return SimpleSocket New socket. * @return SimpleSocket New socket.
* @access public * @access public
*/ */
function &createConnection($method, $timeout) { function createConnection($method, $timeout) {
$default_port = ('https' == $this->_url->getScheme()) ? 443 : 80; $default_port = ('https' == $this->url->getScheme()) ? 443 : 80;
$socket = &$this->_createSocket( $socket = $this->createSocket(
$this->_url->getScheme() ? $this->_url->getScheme() : 'http', $this->url->getScheme() ? $this->url->getScheme() : 'http',
$this->_url->getHost(), $this->url->getHost(),
$this->_url->getPort() ? $this->_url->getPort() : $default_port, $this->url->getPort() ? $this->url->getPort() : $default_port,
$timeout); $timeout);
if (! $socket->isError()) { if (! $socket->isError()) {
$socket->write($this->_getRequestLine($method) . "\r\n"); $socket->write($this->getRequestLine($method) . "\r\n");
$socket->write($this->_getHostLine() . "\r\n"); $socket->write($this->getHostLine() . "\r\n");
$socket->write("Connection: close\r\n"); $socket->write("Connection: close\r\n");
} }
return $socket; return $socket;
} }
/** /**
* Factory for socket. * Factory for socket.
* @param string $scheme Protocol to use. * @param string $scheme Protocol to use.
@ -96,13 +96,14 @@ class SimpleRoute {
* @return SimpleSocket/SimpleSecureSocket New socket. * @return SimpleSocket/SimpleSecureSocket New socket.
* @access protected * @access protected
*/ */
function &_createSocket($scheme, $host, $port, $timeout) { protected function createSocket($scheme, $host, $port, $timeout) {
if (in_array($scheme, array('https'))) { if (in_array($scheme, array('file'))) {
$socket = &new SimpleSecureSocket($host, $port, $timeout); return new SimpleFileSocket($this->url);
} elseif (in_array($scheme, array('https'))) {
return new SimpleSecureSocket($host, $port, $timeout);
} else { } else {
$socket = &new SimpleSocket($host, $port, $timeout); return new SimpleSocket($host, $port, $timeout);
} }
return $socket;
} }
} }
@ -113,10 +114,10 @@ class SimpleRoute {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleProxyRoute extends SimpleRoute { class SimpleProxyRoute extends SimpleRoute {
var $_proxy; private $proxy;
var $_username; private $username;
var $_password; private $password;
/** /**
* Stashes the proxy address. * Stashes the proxy address.
* @param SimpleUrl $url URL as object. * @param SimpleUrl $url URL as object.
@ -125,13 +126,13 @@ class SimpleProxyRoute extends SimpleRoute {
* @param string $password Password for autentication. * @param string $password Password for autentication.
* @access public * @access public
*/ */
function SimpleProxyRoute($url, $proxy, $username = false, $password = false) { function __construct($url, $proxy, $username = false, $password = false) {
$this->SimpleRoute($url); parent::__construct($url);
$this->_proxy = $proxy; $this->proxy = $proxy;
$this->_username = $username; $this->username = $username;
$this->_password = $password; $this->password = $password;
} }
/** /**
* Creates the first line which is the actual request. * Creates the first line which is the actual request.
* @param string $method HTTP request method, usually GET. * @param string $method HTTP request method, usually GET.
@ -139,26 +140,26 @@ class SimpleProxyRoute extends SimpleRoute {
* @return string Request line content. * @return string Request line content.
* @access protected * @access protected
*/ */
function _getRequestLine($method) { function getRequestLine($method) {
$url = $this->getUrl(); $url = $this->getUrl();
$scheme = $url->getScheme() ? $url->getScheme() : 'http'; $scheme = $url->getScheme() ? $url->getScheme() : 'http';
$port = $url->getPort() ? ':' . $url->getPort() : ''; $port = $url->getPort() ? ':' . $url->getPort() : '';
return $method . ' ' . $scheme . '://' . $url->getHost() . $port . return $method . ' ' . $scheme . '://' . $url->getHost() . $port .
$url->getPath() . $url->getEncodedRequest() . ' HTTP/1.0'; $url->getPath() . $url->getEncodedRequest() . ' HTTP/1.0';
} }
/** /**
* Creates the host part of the request. * Creates the host part of the request.
* @param SimpleUrl $url URL as object. * @param SimpleUrl $url URL as object.
* @return string Host line content. * @return string Host line content.
* @access protected * @access protected
*/ */
function _getHostLine() { function getHostLine() {
$host = 'Host: ' . $this->_proxy->getHost(); $host = 'Host: ' . $this->proxy->getHost();
$port = $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080; $port = $this->proxy->getPort() ? $this->proxy->getPort() : 8080;
return "$host:$port"; return "$host:$port";
} }
/** /**
* Opens a socket to the route. * Opens a socket to the route.
* @param string $method HTTP request method, usually GET. * @param string $method HTTP request method, usually GET.
@ -166,20 +167,20 @@ class SimpleProxyRoute extends SimpleRoute {
* @return SimpleSocket New socket. * @return SimpleSocket New socket.
* @access public * @access public
*/ */
function &createConnection($method, $timeout) { function createConnection($method, $timeout) {
$socket = &$this->_createSocket( $socket = $this->createSocket(
$this->_proxy->getScheme() ? $this->_proxy->getScheme() : 'http', $this->proxy->getScheme() ? $this->proxy->getScheme() : 'http',
$this->_proxy->getHost(), $this->proxy->getHost(),
$this->_proxy->getPort() ? $this->_proxy->getPort() : 8080, $this->proxy->getPort() ? $this->proxy->getPort() : 8080,
$timeout); $timeout);
if ($socket->isError()) { if ($socket->isError()) {
return $socket; return $socket;
} }
$socket->write($this->_getRequestLine($method) . "\r\n"); $socket->write($this->getRequestLine($method) . "\r\n");
$socket->write($this->_getHostLine() . "\r\n"); $socket->write($this->getHostLine() . "\r\n");
if ($this->_username && $this->_password) { if ($this->username && $this->password) {
$socket->write('Proxy-Authorization: Basic ' . $socket->write('Proxy-Authorization: Basic ' .
base64_encode($this->_username . ':' . $this->_password) . base64_encode($this->username . ':' . $this->password) .
"\r\n"); "\r\n");
} }
$socket->write("Connection: close\r\n"); $socket->write("Connection: close\r\n");
@ -194,11 +195,11 @@ class SimpleProxyRoute extends SimpleRoute {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleHttpRequest { class SimpleHttpRequest {
var $_route; private $route;
var $_encoding; private $encoding;
var $_headers; private $headers;
var $_cookies; private $cookies;
/** /**
* Builds the socket request from the different pieces. * Builds the socket request from the different pieces.
* These include proxy information, URL, cookies, headers, * These include proxy information, URL, cookies, headers,
@ -208,13 +209,13 @@ class SimpleHttpRequest {
* request. * request.
* @access public * @access public
*/ */
function SimpleHttpRequest(&$route, $encoding) { function __construct($route, $encoding) {
$this->_route = &$route; $this->route = $route;
$this->_encoding = $encoding; $this->encoding = $encoding;
$this->_headers = array(); $this->headers = array();
$this->_cookies = array(); $this->cookies = array();
} }
/** /**
* Dispatches the content to the route's socket. * Dispatches the content to the route's socket.
* @param integer $timeout Connection timeout. * @param integer $timeout Connection timeout.
@ -223,15 +224,14 @@ class SimpleHttpRequest {
* complete web page. * complete web page.
* @access public * @access public
*/ */
function &fetch($timeout) { function fetch($timeout) {
$socket = &$this->_route->createConnection($this->_encoding->getMethod(), $timeout); $socket = $this->route->createConnection($this->encoding->getMethod(), $timeout);
if (! $socket->isError()) { if (! $socket->isError()) {
$this->_dispatchRequest($socket, $this->_encoding); $this->dispatchRequest($socket, $this->encoding);
} }
$response = &$this->_createResponse($socket); return $this->createResponse($socket);
return $response;
} }
/** /**
* Sends the headers. * Sends the headers.
* @param SimpleSocket $socket Open socket. * @param SimpleSocket $socket Open socket.
@ -240,27 +240,27 @@ class SimpleHttpRequest {
* @param SimpleFormEncoding $encoding Content to send with request. * @param SimpleFormEncoding $encoding Content to send with request.
* @access private * @access private
*/ */
function _dispatchRequest(&$socket, $encoding) { protected function dispatchRequest($socket, $encoding) {
foreach ($this->_headers as $header_line) { foreach ($this->headers as $header_line) {
$socket->write($header_line . "\r\n"); $socket->write($header_line . "\r\n");
} }
if (count($this->_cookies) > 0) { if (count($this->cookies) > 0) {
$socket->write("Cookie: " . implode(";", $this->_cookies) . "\r\n"); $socket->write("Cookie: " . implode(";", $this->cookies) . "\r\n");
} }
$encoding->writeHeadersTo($socket); $encoding->writeHeadersTo($socket);
$socket->write("\r\n"); $socket->write("\r\n");
$encoding->writeTo($socket); $encoding->writeTo($socket);
} }
/** /**
* Adds a header line to the request. * Adds a header line to the request.
* @param string $header_line Text of full header line. * @param string $header_line Text of full header line.
* @access public * @access public
*/ */
function addHeaderLine($header_line) { function addHeaderLine($header_line) {
$this->_headers[] = $header_line; $this->headers[] = $header_line;
} }
/** /**
* Reads all the relevant cookies from the * Reads all the relevant cookies from the
* cookie jar. * cookie jar.
@ -269,20 +269,21 @@ class SimpleHttpRequest {
* @access public * @access public
*/ */
function readCookiesFromJar($jar, $url) { function readCookiesFromJar($jar, $url) {
$this->_cookies = $jar->selectAsPairs($url); $this->cookies = $jar->selectAsPairs($url);
} }
/** /**
* Wraps the socket in a response parser. * Wraps the socket in a response parser.
* @param SimpleSocket $socket Responding socket. * @param SimpleSocket $socket Responding socket.
* @return SimpleHttpResponse Parsed response object. * @return SimpleHttpResponse Parsed response object.
* @access protected * @access protected
*/ */
function &_createResponse(&$socket) { protected function createResponse($socket) {
$response = &new SimpleHttpResponse( $response = new SimpleHttpResponse(
$socket, $socket,
$this->_route->getUrl(), $this->route->getUrl(),
$this->_encoding); $this->encoding);
$socket->close();
return $response; return $response;
} }
} }
@ -293,61 +294,61 @@ class SimpleHttpRequest {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleHttpHeaders { class SimpleHttpHeaders {
var $_raw_headers; private $raw_headers;
var $_response_code; private $response_code;
var $_http_version; private $http_version;
var $_mime_type; private $mime_type;
var $_location; private $location;
var $_cookies; private $cookies;
var $_authentication; private $authentication;
var $_realm; private $realm;
/** /**
* Parses the incoming header block. * Parses the incoming header block.
* @param string $headers Header block. * @param string $headers Header block.
* @access public * @access public
*/ */
function SimpleHttpHeaders($headers) { function __construct($headers) {
$this->_raw_headers = $headers; $this->raw_headers = $headers;
$this->_response_code = false; $this->response_code = false;
$this->_http_version = false; $this->http_version = false;
$this->_mime_type = ''; $this->mime_type = '';
$this->_location = false; $this->location = false;
$this->_cookies = array(); $this->cookies = array();
$this->_authentication = false; $this->authentication = false;
$this->_realm = false; $this->realm = false;
foreach (explode("\r\n", $headers) as $header_line) { foreach (explode("\r\n", $headers) as $header_line) {
$this->_parseHeaderLine($header_line); $this->parseHeaderLine($header_line);
} }
} }
/** /**
* Accessor for parsed HTTP protocol version. * Accessor for parsed HTTP protocol version.
* @return integer HTTP error code. * @return integer HTTP error code.
* @access public * @access public
*/ */
function getHttpVersion() { function getHttpVersion() {
return $this->_http_version; return $this->http_version;
} }
/** /**
* Accessor for raw header block. * Accessor for raw header block.
* @return string All headers as raw string. * @return string All headers as raw string.
* @access public * @access public
*/ */
function getRaw() { function getRaw() {
return $this->_raw_headers; return $this->raw_headers;
} }
/** /**
* Accessor for parsed HTTP error code. * Accessor for parsed HTTP error code.
* @return integer HTTP error code. * @return integer HTTP error code.
* @access public * @access public
*/ */
function getResponseCode() { function getResponseCode() {
return (integer)$this->_response_code; return (integer)$this->response_code;
} }
/** /**
* Returns the redirected URL or false if * Returns the redirected URL or false if
* no redirection. * no redirection.
@ -355,19 +356,19 @@ class SimpleHttpHeaders {
* @access public * @access public
*/ */
function getLocation() { function getLocation() {
return $this->_location; return $this->location;
} }
/** /**
* Test to see if the response is a valid redirect. * Test to see if the response is a valid redirect.
* @return boolean True if valid redirect. * @return boolean True if valid redirect.
* @access public * @access public
*/ */
function isRedirect() { function isRedirect() {
return in_array($this->_response_code, array(301, 302, 303, 307)) && return in_array($this->response_code, array(301, 302, 303, 307)) &&
(boolean)$this->getLocation(); (boolean)$this->getLocation();
} }
/** /**
* Test to see if the response is an authentication * Test to see if the response is an authentication
* challenge. * challenge.
@ -375,46 +376,46 @@ class SimpleHttpHeaders {
* @access public * @access public
*/ */
function isChallenge() { function isChallenge() {
return ($this->_response_code == 401) && return ($this->response_code == 401) &&
(boolean)$this->_authentication && (boolean)$this->authentication &&
(boolean)$this->_realm; (boolean)$this->realm;
} }
/** /**
* Accessor for MIME type header information. * Accessor for MIME type header information.
* @return string MIME type. * @return string MIME type.
* @access public * @access public
*/ */
function getMimeType() { function getMimeType() {
return $this->_mime_type; return $this->mime_type;
} }
/** /**
* Accessor for authentication type. * Accessor for authentication type.
* @return string Type. * @return string Type.
* @access public * @access public
*/ */
function getAuthentication() { function getAuthentication() {
return $this->_authentication; return $this->authentication;
} }
/** /**
* Accessor for security realm. * Accessor for security realm.
* @return string Realm. * @return string Realm.
* @access public * @access public
*/ */
function getRealm() { function getRealm() {
return $this->_realm; return $this->realm;
} }
/** /**
* Writes new cookies to the cookie jar. * Writes new cookies to the cookie jar.
* @param SimpleCookieJar $jar Jar to write to. * @param SimpleCookieJar $jar Jar to write to.
* @param SimpleUrl $url Host and path to write under. * @param SimpleUrl $url Host and path to write under.
* @access public * @access public
*/ */
function writeCookiesToJar(&$jar, $url) { function writeCookiesToJar($jar, $url) {
foreach ($this->_cookies as $cookie) { foreach ($this->cookies as $cookie) {
$jar->setCookie( $jar->setCookie(
$cookie->getName(), $cookie->getName(),
$cookie->getValue(), $cookie->getValue(),
@ -430,33 +431,33 @@ class SimpleHttpHeaders {
* @param string $header_line One line of header. * @param string $header_line One line of header.
* @access protected * @access protected
*/ */
function _parseHeaderLine($header_line) { protected function parseHeaderLine($header_line) {
if (preg_match('/HTTP\/(\d+\.\d+)\s+(\d+)/i', $header_line, $matches)) { if (preg_match('/HTTP\/(\d+\.\d+)\s+(\d+)/i', $header_line, $matches)) {
$this->_http_version = $matches[1]; $this->http_version = $matches[1];
$this->_response_code = $matches[2]; $this->response_code = $matches[2];
} }
if (preg_match('/Content-type:\s*(.*)/i', $header_line, $matches)) { if (preg_match('/Content-type:\s*(.*)/i', $header_line, $matches)) {
$this->_mime_type = trim($matches[1]); $this->mime_type = trim($matches[1]);
} }
if (preg_match('/Location:\s*(.*)/i', $header_line, $matches)) { if (preg_match('/Location:\s*(.*)/i', $header_line, $matches)) {
$this->_location = trim($matches[1]); $this->location = trim($matches[1]);
} }
if (preg_match('/Set-cookie:(.*)/i', $header_line, $matches)) { if (preg_match('/Set-cookie:(.*)/i', $header_line, $matches)) {
$this->_cookies[] = $this->_parseCookie($matches[1]); $this->cookies[] = $this->parseCookie($matches[1]);
} }
if (preg_match('/WWW-Authenticate:\s+(\S+)\s+realm=\"(.*?)\"/i', $header_line, $matches)) { if (preg_match('/WWW-Authenticate:\s+(\S+)\s+realm=\"(.*?)\"/i', $header_line, $matches)) {
$this->_authentication = $matches[1]; $this->authentication = $matches[1];
$this->_realm = trim($matches[2]); $this->realm = trim($matches[2]);
} }
} }
/** /**
* Parse the Set-cookie content. * Parse the Set-cookie content.
* @param string $cookie_line Text after "Set-cookie:" * @param string $cookie_line Text after "Set-cookie:"
* @return SimpleCookie New cookie object. * @return SimpleCookie New cookie object.
* @access private * @access private
*/ */
function _parseCookie($cookie_line) { protected function parseCookie($cookie_line) {
$parts = explode(";", $cookie_line); $parts = explode(";", $cookie_line);
$cookie = array(); $cookie = array();
preg_match('/\s*(.*?)\s*=(.*)/', array_shift($parts), $cookie); preg_match('/\s*(.*?)\s*=(.*)/', array_shift($parts), $cookie);
@ -479,12 +480,12 @@ class SimpleHttpHeaders {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleHttpResponse extends SimpleStickyError { class SimpleHttpResponse extends SimpleStickyError {
var $_url; private $url;
var $_encoding; private $encoding;
var $_sent; private $sent;
var $_content; private $content;
var $_headers; private $headers;
/** /**
* Constructor. Reads and parses the incoming * Constructor. Reads and parses the incoming
* content and headers. * content and headers.
@ -494,74 +495,77 @@ class SimpleHttpResponse extends SimpleStickyError {
* @param mixed $encoding Record of content sent. * @param mixed $encoding Record of content sent.
* @access public * @access public
*/ */
function SimpleHttpResponse(&$socket, $url, $encoding) { function __construct($socket, $url, $encoding) {
$this->SimpleStickyError(); parent::__construct();
$this->_url = $url; $this->url = $url;
$this->_encoding = $encoding; $this->encoding = $encoding;
$this->_sent = $socket->getSent(); $this->sent = $socket->getSent();
$this->_content = false; $this->content = false;
$raw = $this->_readAll($socket); $raw = $this->readAll($socket);
if ($socket->isError()) { if ($socket->isError()) {
$this->_setError('Error reading socket [' . $socket->getError() . ']'); $this->setError('Error reading socket [' . $socket->getError() . ']');
return; return;
} }
$this->_parse($raw); $this->parse($raw);
} }
/** /**
* Splits up the headers and the rest of the content. * Splits up the headers and the rest of the content.
* @param string $raw Content to parse. * @param string $raw Content to parse.
* @access private * @access private
*/ */
function _parse($raw) { protected function parse($raw) {
if (! $raw) { if (! $raw) {
$this->_setError('Nothing fetched'); $this->setError('Nothing fetched');
$this->_headers = &new SimpleHttpHeaders(''); $this->headers = new SimpleHttpHeaders('');
} elseif ('file' == $this->url->getScheme()) {
$this->headers = new SimpleHttpHeaders('');
$this->content = $raw;
} elseif (! strstr($raw, "\r\n\r\n")) { } elseif (! strstr($raw, "\r\n\r\n")) {
$this->_setError('Could not split headers from content'); $this->setError('Could not split headers from content');
$this->_headers = &new SimpleHttpHeaders($raw); $this->headers = new SimpleHttpHeaders($raw);
} else { } else {
list($headers, $this->_content) = explode("\r\n\r\n", $raw, 2); list($headers, $this->content) = explode("\r\n\r\n", $raw, 2);
$this->_headers = &new SimpleHttpHeaders($headers); $this->headers = new SimpleHttpHeaders($headers);
} }
} }
/** /**
* Original request method. * Original request method.
* @return string GET, POST or HEAD. * @return string GET, POST or HEAD.
* @access public * @access public
*/ */
function getMethod() { function getMethod() {
return $this->_encoding->getMethod(); return $this->encoding->getMethod();
} }
/** /**
* Resource name. * Resource name.
* @return SimpleUrl Current url. * @return SimpleUrl Current url.
* @access public * @access public
*/ */
function getUrl() { function getUrl() {
return $this->_url; return $this->url;
} }
/** /**
* Original request data. * Original request data.
* @return mixed Sent content. * @return mixed Sent content.
* @access public * @access public
*/ */
function getRequestData() { function getRequestData() {
return $this->_encoding; return $this->encoding;
} }
/** /**
* Raw request that was sent down the wire. * Raw request that was sent down the wire.
* @return string Bytes actually sent. * @return string Bytes actually sent.
* @access public * @access public
*/ */
function getSent() { function getSent() {
return $this->_sent; return $this->sent;
} }
/** /**
* Accessor for the content after the last * Accessor for the content after the last
* header line. * header line.
@ -569,9 +573,9 @@ class SimpleHttpResponse extends SimpleStickyError {
* @access public * @access public
*/ */
function getContent() { function getContent() {
return $this->_content; return $this->content;
} }
/** /**
* Accessor for header block. The response is the * Accessor for header block. The response is the
* combination of this and the content. * combination of this and the content.
@ -579,18 +583,18 @@ class SimpleHttpResponse extends SimpleStickyError {
* @access public * @access public
*/ */
function getHeaders() { function getHeaders() {
return $this->_headers; return $this->headers;
} }
/** /**
* Accessor for any new cookies. * Accessor for any new cookies.
* @return array List of new cookies. * @return array List of new cookies.
* @access public * @access public
*/ */
function getNewCookies() { function getNewCookies() {
return $this->_headers->getNewCookies(); return $this->headers->getNewCookies();
} }
/** /**
* Reads the whole of the socket output into a * Reads the whole of the socket output into a
* single string. * single string.
@ -599,14 +603,14 @@ class SimpleHttpResponse extends SimpleStickyError {
* else false. * else false.
* @access private * @access private
*/ */
function _readAll(&$socket) { protected function readAll($socket) {
$all = ''; $all = '';
while (! $this->_isLastPacket($next = $socket->read())) { while (! $this->isLastPacket($next = $socket->read())) {
$all .= $next; $all .= $next;
} }
return $all; return $all;
} }
/** /**
* Test to see if the packet from the socket is the * Test to see if the packet from the socket is the
* last one. * last one.
@ -614,11 +618,11 @@ class SimpleHttpResponse extends SimpleStickyError {
* @return boolean True if empty or EOF. * @return boolean True if empty or EOF.
* @access private * @access private
*/ */
function _isLastPacket($packet) { protected function isLastPacket($packet) {
if (is_string($packet)) { if (is_string($packet)) {
return $packet === ''; return $packet === '';
} }
return ! $packet; return ! $packet;
} }
} }
?> ?>

38
contrib/simpletest/simpletest/invoker.php Normal file → Executable file
View File

@ -3,7 +3,7 @@
* Base include file for SimpleTest * Base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: invoker.php 1722 2008-04-07 19:30:56Z lastcraft $ * @version $Id: invoker.php 1785 2008-04-26 13:56:41Z pp11 $
*/ */
/**#@+ /**#@+
@ -28,14 +28,14 @@ if (! defined('SIMPLE_TEST')) {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SimpleInvoker { class SimpleInvoker {
var $_test_case; private $test_case;
/** /**
* Stashes the test case for later. * Stashes the test case for later.
* @param SimpleTestCase $test_case Test case to run. * @param SimpleTestCase $test_case Test case to run.
*/ */
function SimpleInvoker(&$test_case) { function __construct($test_case) {
$this->_test_case = &$test_case; $this->test_case = $test_case;
} }
/** /**
@ -43,8 +43,8 @@ class SimpleInvoker {
* @return SimpleTestCase Test case. * @return SimpleTestCase Test case.
* @access public * @access public
*/ */
function &getTestCase() { function getTestCase() {
return $this->_test_case; return $this->test_case;
} }
/** /**
@ -54,7 +54,7 @@ class SimpleInvoker {
* @access public * @access public
*/ */
function before($method) { function before($method) {
$this->_test_case->before($method); $this->test_case->before($method);
} }
/** /**
@ -64,9 +64,9 @@ class SimpleInvoker {
* @access public * @access public
*/ */
function invoke($method) { function invoke($method) {
$this->_test_case->setUp(); $this->test_case->setUp();
$this->_test_case->$method(); $this->test_case->$method();
$this->_test_case->tearDown(); $this->test_case->tearDown();
} }
/** /**
@ -76,7 +76,7 @@ class SimpleInvoker {
* @access public * @access public
*/ */
function after($method) { function after($method) {
$this->_test_case->after($method); $this->test_case->after($method);
} }
} }
@ -87,14 +87,14 @@ class SimpleInvoker {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SimpleInvokerDecorator { class SimpleInvokerDecorator {
var $_invoker; private $invoker;
/** /**
* Stores the invoker to wrap. * Stores the invoker to wrap.
* @param SimpleInvoker $invoker Test method runner. * @param SimpleInvoker $invoker Test method runner.
*/ */
function SimpleInvokerDecorator(&$invoker) { function __construct($invoker) {
$this->_invoker = &$invoker; $this->invoker = $invoker;
} }
/** /**
@ -102,8 +102,8 @@ class SimpleInvokerDecorator {
* @return SimpleTestCase Test case. * @return SimpleTestCase Test case.
* @access public * @access public
*/ */
function &getTestCase() { function getTestCase() {
return $this->_invoker->getTestCase(); return $this->invoker->getTestCase();
} }
/** /**
@ -113,7 +113,7 @@ class SimpleInvokerDecorator {
* @access public * @access public
*/ */
function before($method) { function before($method) {
$this->_invoker->before($method); $this->invoker->before($method);
} }
/** /**
@ -123,7 +123,7 @@ class SimpleInvokerDecorator {
* @access public * @access public
*/ */
function invoke($method) { function invoke($method) {
$this->_invoker->invoke($method); $this->invoker->invoke($method);
} }
/** /**
@ -133,7 +133,7 @@ class SimpleInvokerDecorator {
* @access public * @access public
*/ */
function after($method) { function after($method) {
$this->_invoker->after($method); $this->invoker->after($method);
} }
} }
?> ?>

1004
contrib/simpletest/simpletest/mock_objects.php Normal file → Executable file

File diff suppressed because it is too large Load Diff

685
contrib/simpletest/simpletest/page.php Normal file → Executable file
View File

@ -3,374 +3,51 @@
* Base include file for SimpleTest * Base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
* @version $Id: page.php 1672 2008-03-02 04:47:34Z edwardzyang $ * @version $Id: page.php 1938 2009-08-05 17:16:23Z dgheath $
*/ */
/**#@+ /**#@+
* include other SimpleTest class files * include other SimpleTest class files
*/ */
require_once(dirname(__FILE__) . '/http.php'); require_once(dirname(__FILE__) . '/http.php');
require_once(dirname(__FILE__) . '/parser.php'); require_once(dirname(__FILE__) . '/php_parser.php');
require_once(dirname(__FILE__) . '/tag.php'); require_once(dirname(__FILE__) . '/tag.php');
require_once(dirname(__FILE__) . '/form.php'); require_once(dirname(__FILE__) . '/form.php');
require_once(dirname(__FILE__) . '/selector.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',
'base' => 'SimpleBaseTag',
'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.
* @package SimpleTest
* @subpackage WebTester
*/
class SimplePageBuilder extends SimpleSaxListener {
var $_tags;
var $_page;
var $_private_content_tag;
/**
* Sets the builder up empty.
* @access public
*/
function SimplePageBuilder() {
$this->SimpleSaxListener();
}
/**
* Frees up any references so as to allow the PHP garbage
* collection from unset() to work.
* @access public
*/
function free() {
unset($this->_tags);
unset($this->_page);
unset($this->_private_content_tags);
}
/**
* Reads the raw content and send events
* into the page to be built.
* @param $response SimpleHttpResponse Fetched response.
* @return SimplePage Newly parsed page.
* @access public
*/
function &parse($response) {
$this->_tags = array();
$this->_page = &$this->_createPage($response);
$parser = &$this->_createParser($this);
$parser->parse($response->getContent());
$this->_page->acceptPageEnd();
return $this->_page;
}
/**
* Creates an empty page.
* @return SimplePage New unparsed page.
* @access protected
*/
function &_createPage($response) {
$page = &new SimplePage($response);
return $page;
}
/**
* Creates the parser used with the builder.
* @param $listener SimpleSaxListener Target of parser.
* @return SimpleSaxParser Parser to generate
* events for the builder.
* @access protected
*/
function &_createParser(&$listener) {
$parser = &new SimpleHtmlSaxParser($listener);
return $parser;
}
/**
* Start of element event. Opens a new tag.
* @param string $name Element name.
* @param hash $attributes Attributes without content
* are marked as true.
* @return boolean False on parse error.
* @access public
*/
function startElement($name, $attributes) {
$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 ($tag->getTagName() == 'frameset') {
$this->_page->acceptFramesetStart($tag);
return true;
}
if ($tag->getTagName() == 'frame') {
$this->_page->acceptFrame($tag);
return true;
}
if ($tag->isPrivateContent() && ! isset($this->_private_content_tag)) {
$this->_private_content_tag = &$tag;
}
if ($tag->expectEndTag()) {
$this->_openTag($tag);
return true;
}
$this->_page->acceptTag($tag);
return true;
}
/**
* End of element event.
* @param string $name Element name.
* @return boolean False on parse error.
* @access public
*/
function endElement($name) {
if ($name == 'label') {
$this->_page->acceptLabelEnd();
return true;
}
if ($name == 'form') {
$this->_page->acceptFormEnd();
return true;
}
if ($name == 'frameset') {
$this->_page->acceptFramesetEnd();
return true;
}
if ($this->_hasNamedTagOnOpenTagStack($name)) {
$tag = array_pop($this->_tags[$name]);
if ($tag->isPrivateContent() && $this->_private_content_tag->getTagName() == $name) {
unset($this->_private_content_tag);
}
$this->_addContentTagToOpenTags($tag);
$this->_page->acceptTag($tag);
return true;
}
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.
* @param string $text May include unparsed tags.
* @return boolean False on parse error.
* @access public
*/
function addContent($text) {
if (isset($this->_private_content_tag)) {
$this->_private_content_tag->addContent($text);
} else {
$this->_addContentToAllOpenTags($text);
}
return true;
}
/**
* 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) {
if ($tag->getTagName() != 'option') {
return;
}
foreach (array_keys($this->_tags) as $name) {
for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) {
$this->_tags[$name][$i]->addTag($tag);
}
}
}
/**
* Opens a tag for receiving content. Multiple tags
* will be receiving input at the same time.
* @param SimpleTag $tag New content tag.
* @access private
*/
function _openTag(&$tag) {
$name = $tag->getTagName();
if (! in_array($name, array_keys($this->_tags))) {
$this->_tags[$name] = array();
}
$this->_tags[$name][] = &$tag;
}
}
/** /**
* A wrapper for a web page. * A wrapper for a web page.
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimplePage { class SimplePage {
var $_links; private $links = array();
var $_title; private $title = false;
var $_last_widget; private $last_widget;
var $_label; private $label;
var $_left_over_labels; private $forms = array();
var $_open_forms; private $frames = array();
var $_complete_forms; private $transport_error;
var $_frameset; private $raw;
var $_frames; private $text = false;
var $_frameset_nesting_level; private $sent;
var $_transport_error; private $headers;
var $_raw; private $method;
var $_text; private $url;
var $_sent; private $base = false;
var $_headers; private $request_data;
var $_method;
var $_url;
var $_base = false;
var $_request_data;
/** /**
* Parses a page ready to access it's contents. * Parses a page ready to access it's contents.
* @param SimpleHttpResponse $response Result of HTTP fetch. * @param SimpleHttpResponse $response Result of HTTP fetch.
* @access public * @access public
*/ */
function SimplePage($response = false) { function __construct($response = false) {
$this->_links = array();
$this->_title = false;
$this->_left_over_labels = array();
$this->_open_forms = array();
$this->_complete_forms = array();
$this->_frameset = false;
$this->_frames = array();
$this->_frameset_nesting_level = 0;
$this->_text = false;
if ($response) { if ($response) {
$this->_extractResponse($response); $this->extractResponse($response);
} else { } else {
$this->_noResponse(); $this->noResponse();
} }
} }
@ -379,28 +56,28 @@ class SimplePage {
* @param SimpleHttpResponse $response Response being parsed. * @param SimpleHttpResponse $response Response being parsed.
* @access private * @access private
*/ */
function _extractResponse($response) { protected function extractResponse($response) {
$this->_transport_error = $response->getError(); $this->transport_error = $response->getError();
$this->_raw = $response->getContent(); $this->raw = $response->getContent();
$this->_sent = $response->getSent(); $this->sent = $response->getSent();
$this->_headers = $response->getHeaders(); $this->headers = $response->getHeaders();
$this->_method = $response->getMethod(); $this->method = $response->getMethod();
$this->_url = $response->getUrl(); $this->url = $response->getUrl();
$this->_request_data = $response->getRequestData(); $this->request_data = $response->getRequestData();
} }
/** /**
* Sets up a missing response. * Sets up a missing response.
* @access private * @access private
*/ */
function _noResponse() { protected function noResponse() {
$this->_transport_error = 'No page fetched yet'; $this->transport_error = 'No page fetched yet';
$this->_raw = false; $this->raw = false;
$this->_sent = false; $this->sent = false;
$this->_headers = false; $this->headers = false;
$this->_method = 'GET'; $this->method = 'GET';
$this->_url = false; $this->url = false;
$this->_request_data = false; $this->request_data = false;
} }
/** /**
@ -409,7 +86,7 @@ class SimplePage {
* @access public * @access public
*/ */
function getRequest() { function getRequest() {
return $this->_sent; return $this->sent;
} }
/** /**
@ -418,7 +95,7 @@ class SimplePage {
* @access public * @access public
*/ */
function getRaw() { function getRaw() {
return $this->_raw; return $this->raw;
} }
/** /**
@ -428,10 +105,10 @@ class SimplePage {
* @access public * @access public
*/ */
function getText() { function getText() {
if (! $this->_text) { if (! $this->text) {
$this->_text = SimpleHtmlSaxParser::normalise($this->_raw); $this->text = SimplePage::normalise($this->raw);
} }
return $this->_text; return $this->text;
} }
/** /**
@ -440,8 +117,8 @@ class SimplePage {
* @access public * @access public
*/ */
function getHeaders() { function getHeaders() {
if ($this->_headers) { if ($this->headers) {
return $this->_headers->getRaw(); return $this->headers->getRaw();
} }
return false; return false;
} }
@ -452,7 +129,7 @@ class SimplePage {
* @access public * @access public
*/ */
function getMethod() { function getMethod() {
return $this->_method; return $this->method;
} }
/** /**
@ -461,7 +138,7 @@ class SimplePage {
* @access public * @access public
*/ */
function getUrl() { function getUrl() {
return $this->_url; return $this->url;
} }
/** /**
@ -470,7 +147,7 @@ class SimplePage {
* @access public * @access public
*/ */
function getBaseUrl() { function getBaseUrl() {
return $this->_base; return $this->base;
} }
/** /**
@ -479,7 +156,7 @@ class SimplePage {
* @access public * @access public
*/ */
function getRequestData() { function getRequestData() {
return $this->_request_data; return $this->request_data;
} }
/** /**
@ -488,7 +165,7 @@ class SimplePage {
* @access public * @access public
*/ */
function getTransportError() { function getTransportError() {
return $this->_transport_error; return $this->transport_error;
} }
/** /**
@ -497,8 +174,8 @@ class SimplePage {
* @access public * @access public
*/ */
function getMimeType() { function getMimeType() {
if ($this->_headers) { if ($this->headers) {
return $this->_headers->getMimeType(); return $this->headers->getMimeType();
} }
return false; return false;
} }
@ -509,8 +186,8 @@ class SimplePage {
* @access public * @access public
*/ */
function getResponseCode() { function getResponseCode() {
if ($this->_headers) { if ($this->headers) {
return $this->_headers->getResponseCode(); return $this->headers->getResponseCode();
} }
return false; return false;
} }
@ -522,8 +199,8 @@ class SimplePage {
* @access public * @access public
*/ */
function getAuthentication() { function getAuthentication() {
if ($this->_headers) { if ($this->headers) {
return $this->_headers->getAuthentication(); return $this->headers->getAuthentication();
} }
return false; return false;
} }
@ -535,8 +212,8 @@ class SimplePage {
* @access public * @access public
*/ */
function getRealm() { function getRealm() {
if ($this->_headers) { if ($this->headers) {
return $this->_headers->getRealm(); return $this->headers->getRealm();
} }
return false; return false;
} }
@ -579,129 +256,10 @@ class SimplePage {
} }
/** /**
* Adds a tag to the page. * TODO: write docs
* @param SimpleTag $tag Tag to accept.
* @access public
*/ */
function acceptTag(&$tag) { function setFrames($frames) {
if ($tag->getTagName() == "a") { $this->frames = $frames;
$this->_addLink($tag);
} elseif ($tag->getTagName() == "base") {
$this->_setBase($tag);
} elseif ($tag->getTagName() == "title") {
$this->_setTitle($tag);
} elseif ($this->_isFormElement($tag->getTagName())) {
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);
}
}
/**
* Tests to see if a tag is a possible form
* element.
* @param string $name HTML element name.
* @return boolean True if form element.
* @access private
*/
function _isFormElement($name) {
return in_array($name, array('input', 'button', 'textarea', 'select'));
}
/**
* Opens a form. New widgets go here.
* @param SimpleFormTag $tag Tag to accept.
* @access public
*/
function acceptFormStart(&$tag) {
$this->_open_forms[] = &new SimpleForm($tag, $this);
}
/**
* Closes the most recently opened form.
* @access public
*/
function acceptFormEnd() {
if (count($this->_open_forms)) {
$this->_complete_forms[] = array_pop($this->_open_forms);
}
}
/**
* Opens a frameset. A frameset may contain nested
* frameset tags.
* @param SimpleFramesetTag $tag Tag to accept.
* @access public
*/
function acceptFramesetStart(&$tag) {
if (! $this->_isLoadingFrames()) {
$this->_frameset = &$tag;
}
$this->_frameset_nesting_level++;
}
/**
* Closes the most recently opened frameset.
* @access public
*/
function acceptFramesetEnd() {
if ($this->_isLoadingFrames()) {
$this->_frameset_nesting_level--;
}
}
/**
* Takes a single frame tag and stashes it in
* the current frame set.
* @param SimpleFrameTag $tag Tag to accept.
* @access public
*/
function acceptFrame(&$tag) {
if ($this->_isLoadingFrames()) {
if ($tag->getAttribute('src')) {
$this->_frames[] = &$tag;
}
}
}
/**
* Test to see if in the middle of reading
* a frameset.
* @return boolean True if inframeset.
* @access private
*/
function _isLoadingFrames() {
if (! $this->_frameset) {
return false;
}
return ($this->_frameset_nesting_level > 0);
} }
/** /**
@ -710,7 +268,7 @@ class SimplePage {
* @return boolean True if absolute. * @return boolean True if absolute.
* @access protected * @access protected
*/ */
function _linkIsAbsolute($url) { protected function linkIsAbsolute($url) {
$parsed = new SimpleUrl($url); $parsed = new SimpleUrl($url);
return (boolean)($parsed->getScheme() && $parsed->getHost()); return (boolean)($parsed->getScheme() && $parsed->getHost());
} }
@ -718,28 +276,17 @@ class SimplePage {
/** /**
* Adds a link to the page. * Adds a link to the page.
* @param SimpleAnchorTag $tag Link to accept. * @param SimpleAnchorTag $tag Link to accept.
* @access protected
*/ */
function _addLink($tag) { function addLink($tag) {
$this->_links[] = $tag; $this->links[] = $tag;
} }
/** /**
* Marker for end of complete page. Any work in * Set the forms
* progress can now be closed. * @param array $forms An array of SimpleForm objects
* @access public
*/ */
function acceptPageEnd() { function setForms($forms) {
while (count($this->_open_forms)) { $this->forms = $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());
}
}
} }
/** /**
@ -748,7 +295,7 @@ class SimplePage {
* @access public * @access public
*/ */
function hasFrames() { function hasFrames() {
return (boolean)$this->_frameset; return count($this->frames) > 0;
} }
/** /**
@ -761,13 +308,13 @@ class SimplePage {
* @access public * @access public
*/ */
function getFrameset() { function getFrameset() {
if (! $this->_frameset) { if (! $this->hasFrames()) {
return false; return false;
} }
$urls = array(); $urls = array();
for ($i = 0; $i < count($this->_frames); $i++) { for ($i = 0; $i < count($this->frames); $i++) {
$name = $this->_frames[$i]->getAttribute('name'); $name = $this->frames[$i]->getAttribute('name');
$url = new SimpleUrl($this->_frames[$i]->getAttribute('src')); $url = new SimpleUrl($this->frames[$i]->getAttribute('src'));
$urls[$name ? $name : $i + 1] = $this->expandUrl($url); $urls[$name ? $name : $i + 1] = $this->expandUrl($url);
} }
return $urls; return $urls;
@ -791,8 +338,8 @@ class SimplePage {
*/ */
function getUrls() { function getUrls() {
$all = array(); $all = array();
foreach ($this->_links as $link) { foreach ($this->links as $link) {
$url = $this->_getUrlFromLink($link); $url = $this->getUrlFromLink($link);
$all[] = $url->asString(); $all[] = $url->asString();
} }
return $all; return $all;
@ -807,9 +354,9 @@ class SimplePage {
*/ */
function getUrlsByLabel($label) { function getUrlsByLabel($label) {
$matches = array(); $matches = array();
foreach ($this->_links as $link) { foreach ($this->links as $link) {
if ($link->getText() == $label) { if ($link->getText() == $label) {
$matches[] = $this->_getUrlFromLink($link); $matches[] = $this->getUrlFromLink($link);
} }
} }
return $matches; return $matches;
@ -822,9 +369,9 @@ class SimplePage {
* @access public * @access public
*/ */
function getUrlById($id) { function getUrlById($id) {
foreach ($this->_links as $link) { foreach ($this->links as $link) {
if ($link->getAttribute('id') === (string)$id) { if ($link->getAttribute('id') === (string)$id) {
return $this->_getUrlFromLink($link); return $this->getUrlFromLink($link);
} }
} }
return false; return false;
@ -836,7 +383,7 @@ class SimplePage {
* @return SimpleUrl URL with frame target if any. * @return SimpleUrl URL with frame target if any.
* @access private * @access private
*/ */
function _getUrlFromLink($link) { protected function getUrlFromLink($link) {
$url = $this->expandUrl($link->getHref()); $url = $this->expandUrl($link->getHref());
if ($link->getAttribute('target')) { if ($link->getAttribute('target')) {
$url->setTarget($link->getAttribute('target')); $url->setTarget($link->getAttribute('target'));
@ -861,21 +408,18 @@ class SimplePage {
/** /**
* Sets the base url for the page. * Sets the base url for the page.
* @param SimpleTag $tag Base URL for page. * @param string $url Base URL for page.
* @access protected
*/ */
function _setBase(&$tag) { function setBase($url) {
$url = $tag->getAttribute('href'); $this->base = new SimpleUrl($url);
$this->_base = new SimpleUrl($url);
} }
/** /**
* Sets the title tag contents. * Sets the title tag contents.
* @param SimpleTitleTag $tag Title of page. * @param SimpleTitleTag $tag Title of page.
* @access protected
*/ */
function _setTitle(&$tag) { function setTitle($tag) {
$this->_title = &$tag; $this->title = $tag;
} }
/** /**
@ -884,8 +428,8 @@ class SimplePage {
* @access public * @access public
*/ */
function getTitle() { function getTitle() {
if ($this->_title) { if ($this->title) {
return $this->_title->getText(); return $this->title->getText();
} }
return false; return false;
} }
@ -898,14 +442,13 @@ class SimplePage {
* the button. * the button.
* @access public * @access public
*/ */
function &getFormBySubmit($selector) { function getFormBySubmit($selector) {
for ($i = 0; $i < count($this->_complete_forms); $i++) { for ($i = 0; $i < count($this->forms); $i++) {
if ($this->_complete_forms[$i]->hasSubmit($selector)) { if ($this->forms[$i]->hasSubmit($selector)) {
return $this->_complete_forms[$i]; return $this->forms[$i];
} }
} }
$null = null; return null;
return $null;
} }
/** /**
@ -916,14 +459,13 @@ class SimplePage {
* the image. * the image.
* @access public * @access public
*/ */
function &getFormByImage($selector) { function getFormByImage($selector) {
for ($i = 0; $i < count($this->_complete_forms); $i++) { for ($i = 0; $i < count($this->forms); $i++) {
if ($this->_complete_forms[$i]->hasImage($selector)) { if ($this->forms[$i]->hasImage($selector)) {
return $this->_complete_forms[$i]; return $this->forms[$i];
} }
} }
$null = null; return null;
return $null;
} }
/** /**
@ -934,14 +476,13 @@ class SimplePage {
* @return SimpleForm Form object containing the matching ID. * @return SimpleForm Form object containing the matching ID.
* @access public * @access public
*/ */
function &getFormById($id) { function getFormById($id) {
for ($i = 0; $i < count($this->_complete_forms); $i++) { for ($i = 0; $i < count($this->forms); $i++) {
if ($this->_complete_forms[$i]->getId() == $id) { if ($this->forms[$i]->getId() == $id) {
return $this->_complete_forms[$i]; return $this->forms[$i];
} }
} }
$null = null; return null;
return $null;
} }
/** /**
@ -954,8 +495,8 @@ class SimplePage {
*/ */
function setField($selector, $value, $position=false) { function setField($selector, $value, $position=false) {
$is_set = false; $is_set = false;
for ($i = 0; $i < count($this->_complete_forms); $i++) { for ($i = 0; $i < count($this->forms); $i++) {
if ($this->_complete_forms[$i]->setField($selector, $value, $position)) { if ($this->forms[$i]->setField($selector, $value, $position)) {
$is_set = true; $is_set = true;
} }
} }
@ -971,13 +512,31 @@ class SimplePage {
* @access public * @access public
*/ */
function getField($selector) { function getField($selector) {
for ($i = 0; $i < count($this->_complete_forms); $i++) { for ($i = 0; $i < count($this->forms); $i++) {
$value = $this->_complete_forms[$i]->getValue($selector); $value = $this->forms[$i]->getValue($selector);
if (isset($value)) { if (isset($value)) {
return $value; return $value;
} }
} }
return null; return null;
} }
/**
* Turns HTML into text browser visible text. Images
* are converted to their alt text and tags are supressed.
* Entities are converted to their visible representation.
* @param string $html HTML to convert.
* @return string Plain text.
* @access public
*/
static function normalise($html) {
$text = preg_replace('#<!--.*?-->#si', '', $html);
$text = preg_replace('#<(script|option|textarea)[^>]*>.*?</\1>#si', '', $text);
$text = preg_replace('#<img[^>]*alt\s*=\s*("([^"]*)"|\'([^\']*)\'|([a-zA-Z_]+))[^>]*>#', ' \2\3\4 ', $text);
$text = preg_replace('#<[^>]*>#', '', $text);
$text = html_entity_decode($text, ENT_QUOTES);
$text = preg_replace('#\s+#', ' ', $text);
return trim(trim($text), "\xA0"); // TODO: The \xAO is a &nbsp;. Add a test for this.
}
} }
?> ?>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,101 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage Extensions
* @author Rene vd O (original code)
* @author Perrick Penet
* @author Marcus Baker
* @version $Id: recorder.php 2011 2011-04-29 08:22:48Z pp11 $
*/
/**
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/scorer.php');
/**
* A single test result.
* @package SimpleTest
* @subpackage Extensions
*/
abstract class SimpleResult {
public $time;
public $breadcrumb;
public $message;
/**
* Records the test result as public members.
* @param array $breadcrumb Test stack at the time of the event.
* @param string $message The messsage to the human.
*/
function __construct($breadcrumb, $message) {
list($this->time, $this->breadcrumb, $this->message) =
array(time(), $breadcrumb, $message);
}
}
/**
* A single pass captured for later.
* @package SimpleTest
* @subpackage Extensions
*/
class SimpleResultOfPass extends SimpleResult { }
/**
* A single failure captured for later.
* @package SimpleTest
* @subpackage Extensions
*/
class SimpleResultOfFail extends SimpleResult { }
/**
* A single exception captured for later.
* @package SimpleTest
* @subpackage Extensions
*/
class SimpleResultOfException extends SimpleResult { }
/**
* Array-based test recorder. Returns an array
* with timestamp, status, test name and message for each pass and failure.
* @package SimpleTest
* @subpackage Extensions
*/
class Recorder extends SimpleReporterDecorator {
public $results = array();
/**
* Stashes the pass as a SimpleResultOfPass
* for later retrieval.
* @param string $message Pass message to be displayed
* eventually.
*/
function paintPass($message) {
parent::paintPass($message);
$this->results[] = new SimpleResultOfPass(parent::getTestList(), $message);
}
/**
* Stashes the fail as a SimpleResultOfFail
* for later retrieval.
* @param string $message Failure message to be displayed
* eventually.
*/
function paintFail($message) {
parent::paintFail($message);
$this->results[] = new SimpleResultOfFail(parent::getTestList(), $message);
}
/**
* Stashes the exception as a SimpleResultOfException
* for later retrieval.
* @param string $message Exception message to be displayed
* eventually.
*/
function paintException($message) {
parent::paintException($message);
$this->results[] = new SimpleResultOfException(parent::getTestList(), $message);
}
}
?>

View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: reflection_php4.php 1672 2008-03-02 04:47:34Z edwardzyang $ * @version $Id: reflection_php4.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/** /**
@ -112,7 +112,7 @@ class SimpleReflection {
function isInterface() { function isInterface() {
return false; return false;
} }
/** /**
* Scans for final methods, but as it's PHP 4 there * Scans for final methods, but as it's PHP 4 there
* aren't any. * aren't any.

View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: reflection_php5.php 1683 2008-03-05 21:57:08Z lastcraft $ * @version $Id: reflection_php5.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/** /**
@ -12,15 +12,15 @@
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SimpleReflection { class SimpleReflection {
var $_interface; private $interface;
/** /**
* Stashes the class/interface. * Stashes the class/interface.
* @param string $interface Class or interface * @param string $interface Class or interface
* to inspect. * to inspect.
*/ */
function SimpleReflection($interface) { function __construct($interface) {
$this->_interface = $interface; $this->interface = $interface;
} }
/** /**
@ -31,10 +31,10 @@ class SimpleReflection {
* @access public * @access public
*/ */
function classExists() { function classExists() {
if (! class_exists($this->_interface)) { if (! class_exists($this->interface)) {
return false; return false;
} }
$reflection = new ReflectionClass($this->_interface); $reflection = new ReflectionClass($this->interface);
return ! $reflection->isInterface(); return ! $reflection->isInterface();
} }
@ -45,7 +45,7 @@ class SimpleReflection {
* @access public * @access public
*/ */
function classExistsSansAutoload() { function classExistsSansAutoload() {
return class_exists($this->_interface, false); return class_exists($this->interface, false);
} }
/** /**
@ -55,7 +55,7 @@ class SimpleReflection {
* @access public * @access public
*/ */
function classOrInterfaceExists() { function classOrInterfaceExists() {
return $this->_classOrInterfaceExistsWithAutoload($this->_interface, true); return $this->classOrInterfaceExistsWithAutoload($this->interface, true);
} }
/** /**
@ -65,7 +65,7 @@ class SimpleReflection {
* @access public * @access public
*/ */
function classOrInterfaceExistsSansAutoload() { function classOrInterfaceExistsSansAutoload() {
return $this->_classOrInterfaceExistsWithAutoload($this->_interface, false); return $this->classOrInterfaceExistsWithAutoload($this->interface, false);
} }
/** /**
@ -76,13 +76,13 @@ class SimpleReflection {
* @return boolean True if interface defined. * @return boolean True if interface defined.
* @access private * @access private
*/ */
function _classOrInterfaceExistsWithAutoload($interface, $autoload) { protected function classOrInterfaceExistsWithAutoload($interface, $autoload) {
if (function_exists('interface_exists')) { if (function_exists('interface_exists')) {
if (interface_exists($this->_interface, $autoload)) { if (interface_exists($this->interface, $autoload)) {
return true; return true;
} }
} }
return class_exists($this->_interface, $autoload); return class_exists($this->interface, $autoload);
} }
/** /**
@ -92,7 +92,7 @@ class SimpleReflection {
* @access public * @access public
*/ */
function getMethods() { function getMethods() {
return array_unique(get_class_methods($this->_interface)); return array_unique(get_class_methods($this->interface));
} }
/** /**
@ -103,11 +103,11 @@ class SimpleReflection {
* @access public * @access public
*/ */
function getInterfaces() { function getInterfaces() {
$reflection = new ReflectionClass($this->_interface); $reflection = new ReflectionClass($this->interface);
if ($reflection->isInterface()) { if ($reflection->isInterface()) {
return array($this->_interface); return array($this->interface);
} }
return $this->_onlyParents($reflection->getInterfaces()); return $this->onlyParents($reflection->getInterfaces());
} }
/** /**
@ -131,7 +131,7 @@ class SimpleReflection {
* @returns boolean True if enforced. * @returns boolean True if enforced.
* @access private * @access private
*/ */
function _isInterfaceMethod($method) { protected function isInterfaceMethod($method) {
return in_array($method, $this->getInterfaceMethods()); return in_array($method, $this->getInterfaceMethods());
} }
@ -141,7 +141,7 @@ class SimpleReflection {
* @access public * @access public
*/ */
function getParent() { function getParent() {
$reflection = new ReflectionClass($this->_interface); $reflection = new ReflectionClass($this->interface);
$parent = $reflection->getParentClass(); $parent = $reflection->getParentClass();
if ($parent) { if ($parent) {
return $parent->getName(); return $parent->getName();
@ -155,7 +155,7 @@ class SimpleReflection {
* @access public * @access public
*/ */
function isAbstract() { function isAbstract() {
$reflection = new ReflectionClass($this->_interface); $reflection = new ReflectionClass($this->interface);
return $reflection->isAbstract(); return $reflection->isAbstract();
} }
@ -165,7 +165,7 @@ class SimpleReflection {
* @access public * @access public
*/ */
function isInterface() { function isInterface() {
$reflection = new ReflectionClass($this->_interface); $reflection = new ReflectionClass($this->interface);
return $reflection->isInterface(); return $reflection->isInterface();
} }
@ -176,7 +176,7 @@ class SimpleReflection {
* @access public * @access public
*/ */
function hasFinal() { function hasFinal() {
$reflection = new ReflectionClass($this->_interface); $reflection = new ReflectionClass($this->interface);
foreach ($reflection->getMethods() as $method) { foreach ($reflection->getMethods() as $method) {
if ($method->isFinal()) { if ($method->isFinal()) {
return true; return true;
@ -193,7 +193,7 @@ class SimpleReflection {
* @returns array List of parent interface names. * @returns array List of parent interface names.
* @access private * @access private
*/ */
function _onlyParents($interfaces) { protected function onlyParents($interfaces) {
$parents = array(); $parents = array();
$blacklist = array(); $blacklist = array();
foreach ($interfaces as $interface) { foreach ($interfaces as $interface) {
@ -218,8 +218,8 @@ class SimpleReflection {
* @return bool true if method is abstract, else false * @return bool true if method is abstract, else false
* @access private * @access private
*/ */
function _isAbstractMethod($name) { protected function isAbstractMethod($name) {
$interface = new ReflectionClass($this->_interface); $interface = new ReflectionClass($this->interface);
if (! $interface->hasMethod($name)) { if (! $interface->hasMethod($name)) {
return false; return false;
} }
@ -232,8 +232,8 @@ class SimpleReflection {
* @return bool true if method is the constructor * @return bool true if method is the constructor
* @access private * @access private
*/ */
function _isConstructor($name) { protected function isConstructor($name) {
return ($name == '__construct') || ($name == $this->_interface); return ($name == '__construct') || ($name == $this->interface);
} }
/** /**
@ -242,8 +242,8 @@ class SimpleReflection {
* @return bool true if method is abstract in parent, else false * @return bool true if method is abstract in parent, else false
* @access private * @access private
*/ */
function _isAbstractMethodInParents($name) { protected function isAbstractMethodInParents($name) {
$interface = new ReflectionClass($this->_interface); $interface = new ReflectionClass($this->interface);
$parent = $interface->getParentClass(); $parent = $interface->getParentClass();
while($parent) { while($parent) {
if (! $parent->hasMethod($name)) { if (! $parent->hasMethod($name)) {
@ -263,8 +263,8 @@ class SimpleReflection {
* @return bool true if method is static, else false * @return bool true if method is static, else false
* @access private * @access private
*/ */
function _isStaticMethod($name) { protected function isStaticMethod($name) {
$interface = new ReflectionClass($this->_interface); $interface = new ReflectionClass($this->interface);
if (! $interface->hasMethod($name)) { if (! $interface->hasMethod($name)) {
return false; return false;
} }
@ -294,13 +294,19 @@ class SimpleReflection {
if ($name == '__toString') { if ($name == '__toString') {
return "function $name()"; return "function $name()";
} }
if ($this->_isInterfaceMethod($name) ||
$this->_isAbstractMethod($name) || // This wonky try-catch is a work around for a faulty method_exists()
$this->_isAbstractMethodInParents($name) || // in early versions of PHP 5 which would return false for static
$this->_isStaticMethod($name)) { // methods. The Reflection classes work fine, but hasMethod()
return $this->_getFullSignature($name); // doesn't exist prior to PHP 5.1.0, so we need to use a more crude
// detection method.
try {
$interface = new ReflectionClass($this->interface);
$interface->getMethod($name);
} catch (ReflectionException $e) {
return "function $name()";
} }
return "function $name()"; return $this->getFullSignature($name);
} }
/** /**
@ -311,13 +317,13 @@ class SimpleReflection {
* bracket. * bracket.
* @access private * @access private
*/ */
function _getFullSignature($name) { protected function getFullSignature($name) {
$interface = new ReflectionClass($this->_interface); $interface = new ReflectionClass($this->interface);
$method = $interface->getMethod($name); $method = $interface->getMethod($name);
$reference = $method->returnsReference() ? '&' : ''; $reference = $method->returnsReference() ? '&' : '';
$static = $method->isStatic() ? 'static ' : ''; $static = $method->isStatic() ? 'static ' : '';
return "{$static}function $reference$name(" . return "{$static}function $reference$name(" .
implode(', ', $this->_getParameterSignatures($method)) . implode(', ', $this->getParameterSignatures($method)) .
")"; ")";
} }
@ -329,7 +335,7 @@ class SimpleReflection {
* a snippet of code. * a snippet of code.
* @access private * @access private
*/ */
function _getParameterSignatures($method) { protected function getParameterSignatures($method) {
$signatures = array(); $signatures = array();
foreach ($method->getParameters() as $parameter) { foreach ($method->getParameters() as $parameter) {
$signature = ''; $signature = '';
@ -342,8 +348,8 @@ class SimpleReflection {
if ($parameter->isPassedByReference()) { if ($parameter->isPassedByReference()) {
$signature .= '&'; $signature .= '&';
} }
$signature .= '$' . $this->_suppressSpurious($parameter->getName()); $signature .= '$' . $this->suppressSpurious($parameter->getName());
if ($this->_isOptional($parameter)) { if ($this->isOptional($parameter)) {
$signature .= ' = null'; $signature .= ' = null';
} }
$signatures[] = $signature; $signatures[] = $signature;
@ -359,7 +365,7 @@ class SimpleReflection {
* @return string Cleaner name. * @return string Cleaner name.
* @access private * @access private
*/ */
function _suppressSpurious($name) { protected function suppressSpurious($name) {
return str_replace(array('[', ']', ' '), '', $name); return str_replace(array('[', ']', ' '), '', $name);
} }
@ -370,11 +376,11 @@ class SimpleReflection {
* @return boolean True if optional. * @return boolean True if optional.
* @access private * @access private
*/ */
function _isOptional($parameter) { protected function isOptional($parameter) {
if (method_exists($parameter, 'isOptional')) { if (method_exists($parameter, 'isOptional')) {
return $parameter->isOptional(); return $parameter->isOptional();
} }
return false; return false;
} }
} }
?> ?>

View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: remote.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: remote.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/**#@+ /**#@+
@ -20,29 +20,29 @@ require_once(dirname(__FILE__) . '/test_case.php');
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class RemoteTestCase { class RemoteTestCase {
var $_url; private $url;
var $_dry_url; private $dry_url;
var $_size; private $size;
/** /**
* Sets the location of the remote test. * Sets the location of the remote test.
* @param string $url Test location. * @param string $url Test location.
* @param string $dry_url Location for dry run. * @param string $dry_url Location for dry run.
* @access public * @access public
*/ */
function RemoteTestCase($url, $dry_url = false) { function __construct($url, $dry_url = false) {
$this->_url = $url; $this->url = $url;
$this->_dry_url = $dry_url ? $dry_url : $url; $this->dry_url = $dry_url ? $dry_url : $url;
$this->_size = false; $this->size = false;
} }
/** /**
* Accessor for the test name for subclasses. * Accessor for the test name for subclasses.
* @return string Name of the test. * @return string Name of the test.
* @access public * @access public
*/ */
function getLabel() { function getLabel() {
return $this->_url; return $this->url;
} }
/** /**
@ -53,65 +53,63 @@ class RemoteTestCase {
* @returns boolean True if no failures. * @returns boolean True if no failures.
* @access public * @access public
*/ */
function run(&$reporter) { function run($reporter) {
$browser = &$this->_createBrowser(); $browser = $this->createBrowser();
$xml = $browser->get($this->_url); $xml = $browser->get($this->url);
if (! $xml) { if (! $xml) {
trigger_error('Cannot read remote test URL [' . $this->_url . ']'); trigger_error('Cannot read remote test URL [' . $this->url . ']');
return false; return false;
} }
$parser = &$this->_createParser($reporter); $parser = $this->createParser($reporter);
if (! $parser->parse($xml)) { if (! $parser->parse($xml)) {
trigger_error('Cannot parse incoming XML from [' . $this->_url . ']'); trigger_error('Cannot parse incoming XML from [' . $this->url . ']');
return false; return false;
} }
return true; return true;
} }
/** /**
* Creates a new web browser object for fetching * Creates a new web browser object for fetching
* the XML report. * the XML report.
* @return SimpleBrowser New browser. * @return SimpleBrowser New browser.
* @access protected * @access protected
*/ */
function &_createBrowser() { protected function createBrowser() {
$browser = &new SimpleBrowser(); return new SimpleBrowser();
return $browser;
} }
/** /**
* Creates the XML parser. * Creates the XML parser.
* @param SimpleReporter $reporter Target of test results. * @param SimpleReporter $reporter Target of test results.
* @return SimpleTestXmlListener XML reader. * @return SimpleTestXmlListener XML reader.
* @access protected * @access protected
*/ */
function &_createParser(&$reporter) { protected function createParser($reporter) {
$parser = &new SimpleTestXmlParser($reporter); return new SimpleTestXmlParser($reporter);
return $parser;
} }
/** /**
* Accessor for the number of subtests. * Accessor for the number of subtests.
* @return integer Number of test cases. * @return integer Number of test cases.
* @access public * @access public
*/ */
function getSize() { function getSize() {
if ($this->_size === false) { if ($this->size === false) {
$browser = &$this->_createBrowser(); $browser = $this->createBrowser();
$xml = $browser->get($this->_dry_url); $xml = $browser->get($this->dry_url);
if (! $xml) { if (! $xml) {
trigger_error('Cannot read remote test URL [' . $this->_dry_url . ']'); trigger_error('Cannot read remote test URL [' . $this->dry_url . ']');
return false; return false;
} }
$reporter = &new SimpleReporter(); $reporter = new SimpleReporter();
$parser = &$this->_createParser($reporter); $parser = $this->createParser($reporter);
if (! $parser->parse($xml)) { if (! $parser->parse($xml)) {
trigger_error('Cannot parse incoming XML from [' . $this->_dry_url . ']'); trigger_error('Cannot parse incoming XML from [' . $this->dry_url . ']');
return false; return false;
} }
$this->_size = $reporter->getTestCaseCount(); $this->size = $reporter->getTestCaseCount();
} }
return $this->_size; return $this->size;
} }
} }
?> ?>

116
contrib/simpletest/simpletest/reporter.php Normal file → Executable file
View File

@ -3,13 +3,14 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: reporter.php 1702 2008-03-25 00:08:04Z lastcraft $ * @version $Id: reporter.php 2005 2010-11-02 14:09:34Z lastcraft $
*/ */
/**#@+ /**#@+
* include other SimpleTest class files * include other SimpleTest class files
*/ */
require_once(dirname(__FILE__) . '/scorer.php'); require_once(dirname(__FILE__) . '/scorer.php');
//require_once(dirname(__FILE__) . '/arguments.php');
/**#@-*/ /**#@-*/
/** /**
@ -19,7 +20,7 @@ require_once(dirname(__FILE__) . '/scorer.php');
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class HtmlReporter extends SimpleReporter { class HtmlReporter extends SimpleReporter {
var $_character_set; private $character_set;
/** /**
* Does nothing yet. The first output will * Does nothing yet. The first output will
@ -27,9 +28,9 @@ class HtmlReporter extends SimpleReporter {
* by a web browser. * by a web browser.
* @access public * @access public
*/ */
function HtmlReporter($character_set = 'ISO-8859-1') { function __construct($character_set = 'ISO-8859-1') {
$this->SimpleReporter(); parent::__construct();
$this->_character_set = $character_set; $this->character_set = $character_set;
} }
/** /**
@ -43,9 +44,9 @@ class HtmlReporter extends SimpleReporter {
print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"; print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
print "<html>\n<head>\n<title>$test_name</title>\n"; print "<html>\n<head>\n<title>$test_name</title>\n";
print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" . print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" .
$this->_character_set . "\">\n"; $this->character_set . "\">\n";
print "<style type=\"text/css\">\n"; print "<style type=\"text/css\">\n";
print $this->_getCss() . "\n"; print $this->getCss() . "\n";
print "</style>\n"; print "</style>\n";
print "</head>\n<body>\n"; print "</head>\n<body>\n";
print "<h1>$test_name</h1>\n"; print "<h1>$test_name</h1>\n";
@ -57,9 +58,8 @@ class HtmlReporter extends SimpleReporter {
* reloaded on every request. Otherwise you could be * reloaded on every request. Otherwise you could be
* scratching your head over out of date test data. * scratching your head over out of date test data.
* @access public * @access public
* @static
*/ */
function sendNoCacheHeaders() { static function sendNoCacheHeaders() {
if (! headers_sent()) { if (! headers_sent()) {
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
@ -74,7 +74,7 @@ class HtmlReporter extends SimpleReporter {
* @return string CSS code as text. * @return string CSS code as text.
* @access protected * @access protected
*/ */
function _getCss() { protected function getCss() {
return ".fail { background-color: inherit; color: red; }" . return ".fail { background-color: inherit; color: red; }" .
".pass { background-color: inherit; color: green; }" . ".pass { background-color: inherit; color: green; }" .
" pre { background-color: lightgray; color: inherit; }"; " pre { background-color: lightgray; color: inherit; }";
@ -106,7 +106,6 @@ class HtmlReporter extends SimpleReporter {
* top level test. * top level test.
* @param string $message Failure message displayed in * @param string $message Failure message displayed in
* the context of the other tests. * the context of the other tests.
* @access public
*/ */
function paintFail($message) { function paintFail($message) {
parent::paintFail($message); parent::paintFail($message);
@ -114,7 +113,7 @@ class HtmlReporter extends SimpleReporter {
$breadcrumb = $this->getTestList(); $breadcrumb = $this->getTestList();
array_shift($breadcrumb); array_shift($breadcrumb);
print implode(" -&gt; ", $breadcrumb); print implode(" -&gt; ", $breadcrumb);
print " -&gt; " . $this->_htmlEntities($message) . "<br />\n"; print " -&gt; " . $this->htmlEntities($message) . "<br />\n";
} }
/** /**
@ -128,7 +127,7 @@ class HtmlReporter extends SimpleReporter {
$breadcrumb = $this->getTestList(); $breadcrumb = $this->getTestList();
array_shift($breadcrumb); array_shift($breadcrumb);
print implode(" -&gt; ", $breadcrumb); print implode(" -&gt; ", $breadcrumb);
print " -&gt; <strong>" . $this->_htmlEntities($message) . "</strong><br />\n"; print " -&gt; <strong>" . $this->htmlEntities($message) . "</strong><br />\n";
} }
/** /**
@ -146,9 +145,9 @@ class HtmlReporter extends SimpleReporter {
'] with message ['. $exception->getMessage() . '] with message ['. $exception->getMessage() .
'] in ['. $exception->getFile() . '] in ['. $exception->getFile() .
' line ' . $exception->getLine() . ']'; ' line ' . $exception->getLine() . ']';
print " -&gt; <strong>" . $this->_htmlEntities($message) . "</strong><br />\n"; print " -&gt; <strong>" . $this->htmlEntities($message) . "</strong><br />\n";
} }
/** /**
* Prints the message for skipping tests. * Prints the message for skipping tests.
* @param string $message Text of skip condition. * @param string $message Text of skip condition.
@ -160,16 +159,16 @@ class HtmlReporter extends SimpleReporter {
$breadcrumb = $this->getTestList(); $breadcrumb = $this->getTestList();
array_shift($breadcrumb); array_shift($breadcrumb);
print implode(" -&gt; ", $breadcrumb); print implode(" -&gt; ", $breadcrumb);
print " -&gt; " . $this->_htmlEntities($message) . "<br />\n"; print " -&gt; " . $this->htmlEntities($message) . "<br />\n";
} }
/** /**
* Paints formatted text such as dumped variables. * Paints formatted text such as dumped privateiables.
* @param string $message Text to show. * @param string $message Text to show.
* @access public * @access public
*/ */
function paintFormattedMessage($message) { function paintFormattedMessage($message) {
print '<pre>' . $this->_htmlEntities($message) . '</pre>'; print '<pre>' . $this->htmlEntities($message) . '</pre>';
} }
/** /**
@ -178,8 +177,8 @@ class HtmlReporter extends SimpleReporter {
* @return string Browser readable message. * @return string Browser readable message.
* @access protected * @access protected
*/ */
function _htmlEntities($message) { protected function htmlEntities($message) {
return htmlentities($message, ENT_COMPAT, $this->_character_set); return htmlentities($message, ENT_COMPAT, $this->character_set);
} }
} }
@ -197,10 +196,9 @@ class TextReporter extends SimpleReporter {
/** /**
* Does nothing yet. The first output will * Does nothing yet. The first output will
* be sent on the first test start. * be sent on the first test start.
* @access public
*/ */
function TextReporter() { function __construct() {
$this->SimpleReporter(); parent::__construct();
} }
/** /**
@ -283,7 +281,7 @@ class TextReporter extends SimpleReporter {
print "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); print "\tin " . implode("\n\tin ", array_reverse($breadcrumb));
print "\n"; print "\n";
} }
/** /**
* Prints the message for skipping tests. * Prints the message for skipping tests.
* @param string $message Text of skip condition. * @param string $message Text of skip condition.
@ -295,7 +293,7 @@ class TextReporter extends SimpleReporter {
} }
/** /**
* Paints formatted text such as dumped variables. * Paints formatted text such as dumped privateiables.
* @param string $message Text to show. * @param string $message Text to show.
* @access public * @access public
*/ */
@ -312,10 +310,10 @@ class TextReporter extends SimpleReporter {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SelectiveReporter extends SimpleReporterDecorator { class SelectiveReporter extends SimpleReporterDecorator {
var $_just_this_case = false; private $just_this_case = false;
var $_just_this_test = false; private $just_this_test = false;
var $_on; private $on;
/** /**
* Selects the test case or group to be run, * Selects the test case or group to be run,
* and optionally a specific test. * and optionally a specific test.
@ -323,17 +321,17 @@ class SelectiveReporter extends SimpleReporterDecorator {
* @param string $just_this_case Only this case or group will run. * @param string $just_this_case Only this case or group will run.
* @param string $just_this_test Only this test method will run. * @param string $just_this_test Only this test method will run.
*/ */
function SelectiveReporter(&$reporter, $just_this_case = false, $just_this_test = false) { function __construct($reporter, $just_this_case = false, $just_this_test = false) {
if (isset($just_this_case) && $just_this_case) { if (isset($just_this_case) && $just_this_case) {
$this->_just_this_case = strtolower($just_this_case); $this->just_this_case = strtolower($just_this_case);
$this->_off(); $this->off();
} else { } else {
$this->_on(); $this->on();
} }
if (isset($just_this_test) && $just_this_test) { if (isset($just_this_test) && $just_this_test) {
$this->_just_this_test = strtolower($just_this_test); $this->just_this_test = strtolower($just_this_test);
} }
$this->SimpleReporterDecorator($reporter); parent::__construct($reporter);
} }
/** /**
@ -342,8 +340,8 @@ class SelectiveReporter extends SimpleReporterDecorator {
* @return boolean True if matched. * @return boolean True if matched.
* @access protected * @access protected
*/ */
function _matchesTestCase($test_case) { protected function matchesTestCase($test_case) {
return $this->_just_this_case == strtolower($test_case); return $this->just_this_case == strtolower($test_case);
} }
/** /**
@ -354,40 +352,40 @@ class SelectiveReporter extends SimpleReporterDecorator {
* @return boolean True if matched. * @return boolean True if matched.
* @access protected * @access protected
*/ */
function _shouldRunTest($test_case, $method) { protected function shouldRunTest($test_case, $method) {
if ($this->_isOn() || $this->_matchesTestCase($test_case)) { if ($this->isOn() || $this->matchesTestCase($test_case)) {
if ($this->_just_this_test) { if ($this->just_this_test) {
return $this->_just_this_test == strtolower($method); return $this->just_this_test == strtolower($method);
} else { } else {
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* Switch on testing for the group or subgroup. * Switch on testing for the group or subgroup.
* @access private * @access private
*/ */
function _on() { protected function on() {
$this->_on = true; $this->on = true;
} }
/** /**
* Switch off testing for the group or subgroup. * Switch off testing for the group or subgroup.
* @access private * @access private
*/ */
function _off() { protected function off() {
$this->_on = false; $this->on = false;
} }
/** /**
* Is this group actually being tested? * Is this group actually being tested?
* @return boolean True if the current test group is active. * @return boolean True if the current test group is active.
* @access private * @access private
*/ */
function _isOn() { protected function isOn() {
return $this->_on; return $this->on;
} }
/** /**
@ -398,8 +396,8 @@ class SelectiveReporter extends SimpleReporterDecorator {
* @access public * @access public
*/ */
function shouldInvoke($test_case, $method) { function shouldInvoke($test_case, $method) {
if ($this->_shouldRunTest($test_case, $method)) { if ($this->shouldRunTest($test_case, $method)) {
return $this->_reporter->shouldInvoke($test_case, $method); return $this->reporter->shouldInvoke($test_case, $method);
} }
return false; return false;
} }
@ -411,10 +409,10 @@ class SelectiveReporter extends SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintGroupStart($test_case, $size) { function paintGroupStart($test_case, $size) {
if ($this->_just_this_case && $this->_matchesTestCase($test_case)) { if ($this->just_this_case && $this->matchesTestCase($test_case)) {
$this->_on(); $this->on();
} }
$this->_reporter->paintGroupStart($test_case, $size); $this->reporter->paintGroupStart($test_case, $size);
} }
/** /**
@ -423,9 +421,9 @@ class SelectiveReporter extends SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintGroupEnd($test_case) { function paintGroupEnd($test_case) {
$this->_reporter->paintGroupEnd($test_case); $this->reporter->paintGroupEnd($test_case);
if ($this->_just_this_case && $this->_matchesTestCase($test_case)) { if ($this->just_this_case && $this->matchesTestCase($test_case)) {
$this->_off(); $this->off();
} }
} }
} }
@ -436,7 +434,7 @@ class SelectiveReporter extends SimpleReporterDecorator {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class NoSkipsReporter extends SimpleReporterDecorator { class NoSkipsReporter extends SimpleReporterDecorator {
/** /**
* Does nothing. * Does nothing.
* @param string $message Text of skip condition. * @param string $message Text of skip condition.

View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: scorer.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: scorer.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/**#@+*/ /**#@+*/
@ -19,20 +19,20 @@ require_once(dirname(__FILE__) . '/invoker.php');
* @abstract * @abstract
*/ */
class SimpleScorer { class SimpleScorer {
var $_passes; private $passes;
var $_fails; private $fails;
var $_exceptions; private $exceptions;
var $_is_dry_run; private $is_dry_run;
/** /**
* Starts the test run with no results. * Starts the test run with no results.
* @access public * @access public
*/ */
function SimpleScorer() { function __construct() {
$this->_passes = 0; $this->passes = 0;
$this->_fails = 0; $this->fails = 0;
$this->_exceptions = 0; $this->exceptions = 0;
$this->_is_dry_run = false; $this->is_dry_run = false;
} }
/** /**
@ -43,7 +43,7 @@ class SimpleScorer {
* @access public * @access public
*/ */
function makeDry($is_dry = true) { function makeDry($is_dry = true) {
$this->_is_dry_run = $is_dry; $this->is_dry_run = $is_dry;
} }
/** /**
@ -53,7 +53,7 @@ class SimpleScorer {
* @access public * @access public
*/ */
function shouldInvoke($test_case_name, $method) { function shouldInvoke($test_case_name, $method) {
return ! $this->_is_dry_run; return ! $this->is_dry_run;
} }
/** /**
@ -63,7 +63,7 @@ class SimpleScorer {
* @return SimpleInvoker Wrapped test runner. * @return SimpleInvoker Wrapped test runner.
* @access public * @access public
*/ */
function &createInvoker(&$invoker) { function createInvoker($invoker) {
return $invoker; return $invoker;
} }
@ -75,7 +75,7 @@ class SimpleScorer {
* @access public * @access public
*/ */
function getStatus() { function getStatus() {
if ($this->_exceptions + $this->_fails > 0) { if ($this->exceptions + $this->fails > 0) {
return false; return false;
} }
return true; return true;
@ -136,7 +136,7 @@ class SimpleScorer {
* @access public * @access public
*/ */
function paintPass($message) { function paintPass($message) {
$this->_passes++; $this->passes++;
} }
/** /**
@ -145,7 +145,7 @@ class SimpleScorer {
* @access public * @access public
*/ */
function paintFail($message) { function paintFail($message) {
$this->_fails++; $this->fails++;
} }
/** /**
@ -155,7 +155,7 @@ class SimpleScorer {
* @access public * @access public
*/ */
function paintError($message) { function paintError($message) {
$this->_exceptions++; $this->exceptions++;
} }
/** /**
@ -164,9 +164,9 @@ class SimpleScorer {
* @access public * @access public
*/ */
function paintException($exception) { function paintException($exception) {
$this->_exceptions++; $this->exceptions++;
} }
/** /**
* Prints the message for skipping tests. * Prints the message for skipping tests.
* @param string $message Text of skip condition. * @param string $message Text of skip condition.
@ -181,7 +181,7 @@ class SimpleScorer {
* @access public * @access public
*/ */
function getPassCount() { function getPassCount() {
return $this->_passes; return $this->passes;
} }
/** /**
@ -190,7 +190,7 @@ class SimpleScorer {
* @access public * @access public
*/ */
function getFailCount() { function getFailCount() {
return $this->_fails; return $this->fails;
} }
/** /**
@ -200,7 +200,7 @@ class SimpleScorer {
* @access public * @access public
*/ */
function getExceptionCount() { function getExceptionCount() {
return $this->_exceptions; return $this->exceptions;
} }
/** /**
@ -213,7 +213,7 @@ class SimpleScorer {
/** /**
* Paints a formatted ASCII message such as a * Paints a formatted ASCII message such as a
* variable dump. * privateiable dump.
* @param string $message Text to display. * @param string $message Text to display.
* @access public * @access public
*/ */
@ -239,24 +239,23 @@ class SimpleScorer {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SimpleReporter extends SimpleScorer { class SimpleReporter extends SimpleScorer {
var $_test_stack; private $test_stack;
var $_size; private $size;
var $_progress; private $progress;
/** /**
* Starts the display with no results in. * Starts the display with no results in.
* @access public * @access public
*/ */
function SimpleReporter() { function __construct() {
$this->SimpleScorer(); parent::__construct();
$this->_test_stack = array(); $this->test_stack = array();
$this->_size = null; $this->size = null;
$this->_progress = 0; $this->progress = 0;
} }
/** /**
* Gets the formatter for variables and other small * Gets the formatter for small generic data items.
* generic data items.
* @return SimpleDumper Formatter. * @return SimpleDumper Formatter.
* @access public * @access public
*/ */
@ -274,13 +273,13 @@ class SimpleReporter extends SimpleScorer {
* @access public * @access public
*/ */
function paintGroupStart($test_name, $size) { function paintGroupStart($test_name, $size) {
if (! isset($this->_size)) { if (! isset($this->size)) {
$this->_size = $size; $this->size = $size;
} }
if (count($this->_test_stack) == 0) { if (count($this->test_stack) == 0) {
$this->paintHeader($test_name); $this->paintHeader($test_name);
} }
$this->_test_stack[] = $test_name; $this->test_stack[] = $test_name;
} }
/** /**
@ -291,8 +290,8 @@ class SimpleReporter extends SimpleScorer {
* @access public * @access public
*/ */
function paintGroupEnd($test_name) { function paintGroupEnd($test_name) {
array_pop($this->_test_stack); array_pop($this->test_stack);
if (count($this->_test_stack) == 0) { if (count($this->test_stack) == 0) {
$this->paintFooter($test_name); $this->paintFooter($test_name);
} }
} }
@ -306,13 +305,13 @@ class SimpleReporter extends SimpleScorer {
* @access public * @access public
*/ */
function paintCaseStart($test_name) { function paintCaseStart($test_name) {
if (! isset($this->_size)) { if (! isset($this->size)) {
$this->_size = 1; $this->size = 1;
} }
if (count($this->_test_stack) == 0) { if (count($this->test_stack) == 0) {
$this->paintHeader($test_name); $this->paintHeader($test_name);
} }
$this->_test_stack[] = $test_name; $this->test_stack[] = $test_name;
} }
/** /**
@ -322,9 +321,9 @@ class SimpleReporter extends SimpleScorer {
* @access public * @access public
*/ */
function paintCaseEnd($test_name) { function paintCaseEnd($test_name) {
$this->_progress++; $this->progress++;
array_pop($this->_test_stack); array_pop($this->test_stack);
if (count($this->_test_stack) == 0) { if (count($this->test_stack) == 0) {
$this->paintFooter($test_name); $this->paintFooter($test_name);
} }
} }
@ -335,7 +334,7 @@ class SimpleReporter extends SimpleScorer {
* @access public * @access public
*/ */
function paintMethodStart($test_name) { function paintMethodStart($test_name) {
$this->_test_stack[] = $test_name; $this->test_stack[] = $test_name;
} }
/** /**
@ -345,7 +344,7 @@ class SimpleReporter extends SimpleScorer {
* @access public * @access public
*/ */
function paintMethodEnd($test_name) { function paintMethodEnd($test_name) {
array_pop($this->_test_stack); array_pop($this->test_stack);
} }
/** /**
@ -375,7 +374,7 @@ class SimpleReporter extends SimpleScorer {
* @access public * @access public
*/ */
function getTestList() { function getTestList() {
return $this->_test_stack; return $this->test_stack;
} }
/** /**
@ -386,7 +385,7 @@ class SimpleReporter extends SimpleScorer {
* @access public * @access public
*/ */
function getTestCaseCount() { function getTestCaseCount() {
return $this->_size; return $this->size;
} }
/** /**
@ -396,16 +395,15 @@ class SimpleReporter extends SimpleScorer {
* @access public * @access public
*/ */
function getTestCaseProgress() { function getTestCaseProgress() {
return $this->_progress; return $this->progress;
} }
/** /**
* Static check for running in the comand line. * Static check for running in the comand line.
* @return boolean True if CLI. * @return boolean True if CLI.
* @access public * @access public
* @static
*/ */
function inCli() { static function inCli() {
return php_sapi_name() == 'cli'; return php_sapi_name() == 'cli';
} }
} }
@ -416,14 +414,14 @@ class SimpleReporter extends SimpleScorer {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SimpleReporterDecorator { class SimpleReporterDecorator {
var $_reporter; protected $reporter;
/** /**
* Mediates between the reporter and the test case. * Mediates between the reporter and the test case.
* @param SimpleScorer $reporter Reporter to receive events. * @param SimpleScorer $reporter Reporter to receive events.
*/ */
function SimpleReporterDecorator(&$reporter) { function __construct($reporter) {
$this->_reporter = &$reporter; $this->reporter = $reporter;
} }
/** /**
@ -434,7 +432,7 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function makeDry($is_dry = true) { function makeDry($is_dry = true) {
$this->_reporter->makeDry($is_dry); $this->reporter->makeDry($is_dry);
} }
/** /**
@ -445,39 +443,53 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function getStatus() { function getStatus() {
return $this->_reporter->getStatus(); return $this->reporter->getStatus();
}
/**
* The nesting of the test cases so far. Not
* all reporters have this facility.
* @return array Test list if accessible.
* @access public
*/
function getTestList() {
if (method_exists($this->reporter, 'getTestList')) {
return $this->reporter->getTestList();
} else {
return array();
}
} }
/** /**
* The reporter has a veto on what should be run. * The reporter has a veto on what should be run.
* @param string $test_case_name name of test case. * @param string $test_case_name Name of test case.
* @param string $method Name of test method. * @param string $method Name of test method.
* @return boolean True if test should be run. * @return boolean True if test should be run.
* @access public * @access public
*/ */
function shouldInvoke($test_case_name, $method) { function shouldInvoke($test_case_name, $method) {
return $this->_reporter->shouldInvoke($test_case_name, $method); return $this->reporter->shouldInvoke($test_case_name, $method);
} }
/** /**
* Can wrap the invoker in preperation for running * Can wrap the invoker in preparation for running
* a test. * a test.
* @param SimpleInvoker $invoker Individual test runner. * @param SimpleInvoker $invoker Individual test runner.
* @return SimpleInvoker Wrapped test runner. * @return SimpleInvoker Wrapped test runner.
* @access public * @access public
*/ */
function &createInvoker(&$invoker) { function createInvoker($invoker) {
return $this->_reporter->createInvoker($invoker); return $this->reporter->createInvoker($invoker);
} }
/** /**
* Gets the formatter for variables and other small * Gets the formatter for privateiables and other small
* generic data items. * generic data items.
* @return SimpleDumper Formatter. * @return SimpleDumper Formatter.
* @access public * @access public
*/ */
function getDumper() { function getDumper() {
return $this->_reporter->getDumper(); return $this->reporter->getDumper();
} }
/** /**
@ -487,7 +499,7 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintGroupStart($test_name, $size) { function paintGroupStart($test_name, $size) {
$this->_reporter->paintGroupStart($test_name, $size); $this->reporter->paintGroupStart($test_name, $size);
} }
/** /**
@ -496,7 +508,7 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintGroupEnd($test_name) { function paintGroupEnd($test_name) {
$this->_reporter->paintGroupEnd($test_name); $this->reporter->paintGroupEnd($test_name);
} }
/** /**
@ -505,7 +517,7 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintCaseStart($test_name) { function paintCaseStart($test_name) {
$this->_reporter->paintCaseStart($test_name); $this->reporter->paintCaseStart($test_name);
} }
/** /**
@ -514,7 +526,7 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintCaseEnd($test_name) { function paintCaseEnd($test_name) {
$this->_reporter->paintCaseEnd($test_name); $this->reporter->paintCaseEnd($test_name);
} }
/** /**
@ -523,7 +535,7 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintMethodStart($test_name) { function paintMethodStart($test_name) {
$this->_reporter->paintMethodStart($test_name); $this->reporter->paintMethodStart($test_name);
} }
/** /**
@ -532,7 +544,7 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintMethodEnd($test_name) { function paintMethodEnd($test_name) {
$this->_reporter->paintMethodEnd($test_name); $this->reporter->paintMethodEnd($test_name);
} }
/** /**
@ -541,7 +553,7 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintPass($message) { function paintPass($message) {
$this->_reporter->paintPass($message); $this->reporter->paintPass($message);
} }
/** /**
@ -550,7 +562,7 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintFail($message) { function paintFail($message) {
$this->_reporter->paintFail($message); $this->reporter->paintFail($message);
} }
/** /**
@ -560,7 +572,7 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintError($message) { function paintError($message) {
$this->_reporter->paintError($message); $this->reporter->paintError($message);
} }
/** /**
@ -569,16 +581,16 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintException($exception) { function paintException($exception) {
$this->_reporter->paintException($exception); $this->reporter->paintException($exception);
} }
/** /**
* Prints the message for skipping tests. * Prints the message for skipping tests.
* @param string $message Text of skip condition. * @param string $message Text of skip condition.
* @access public * @access public
*/ */
function paintSkip($message) { function paintSkip($message) {
$this->_reporter->paintSkip($message); $this->reporter->paintSkip($message);
} }
/** /**
@ -587,7 +599,7 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintMessage($message) { function paintMessage($message) {
$this->_reporter->paintMessage($message); $this->reporter->paintMessage($message);
} }
/** /**
@ -596,7 +608,7 @@ class SimpleReporterDecorator {
* @access public * @access public
*/ */
function paintFormattedMessage($message) { function paintFormattedMessage($message) {
$this->_reporter->paintFormattedMessage($message); $this->reporter->paintFormattedMessage($message);
} }
/** /**
@ -608,8 +620,8 @@ class SimpleReporterDecorator {
* test suite. * test suite.
* @access public * @access public
*/ */
function paintSignal($type, &$payload) { function paintSignal($type, $payload) {
$this->_reporter->paintSignal($type, $payload); $this->reporter->paintSignal($type, $payload);
} }
} }
@ -620,15 +632,15 @@ class SimpleReporterDecorator {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class MultipleReporter { class MultipleReporter {
var $_reporters = array(); private $reporters = array();
/** /**
* Adds a reporter to the subscriber list. * Adds a reporter to the subscriber list.
* @param SimpleScorer $reporter Reporter to receive events. * @param SimpleScorer $reporter Reporter to receive events.
* @access public * @access public
*/ */
function attachReporter(&$reporter) { function attachReporter($reporter) {
$this->_reporters[] = &$reporter; $this->reporters[] = $reporter;
} }
/** /**
@ -639,8 +651,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function makeDry($is_dry = true) { function makeDry($is_dry = true) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->makeDry($is_dry); $this->reporters[$i]->makeDry($is_dry);
} }
} }
@ -653,8 +665,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function getStatus() { function getStatus() {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
if (! $this->_reporters[$i]->getStatus()) { if (! $this->reporters[$i]->getStatus()) {
return false; return false;
} }
} }
@ -669,8 +681,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function shouldInvoke($test_case_name, $method) { function shouldInvoke($test_case_name, $method) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
if (! $this->_reporters[$i]->shouldInvoke($test_case_name, $method)) { if (! $this->reporters[$i]->shouldInvoke($test_case_name, $method)) {
return false; return false;
} }
} }
@ -683,15 +695,15 @@ class MultipleReporter {
* @return SimpleInvoker Wrapped test runner. * @return SimpleInvoker Wrapped test runner.
* @access public * @access public
*/ */
function &createInvoker(&$invoker) { function createInvoker($invoker) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$invoker = &$this->_reporters[$i]->createInvoker($invoker); $invoker = $this->reporters[$i]->createInvoker($invoker);
} }
return $invoker; return $invoker;
} }
/** /**
* Gets the formatter for variables and other small * Gets the formatter for privateiables and other small
* generic data items. * generic data items.
* @return SimpleDumper Formatter. * @return SimpleDumper Formatter.
* @access public * @access public
@ -707,8 +719,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function paintGroupStart($test_name, $size) { function paintGroupStart($test_name, $size) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintGroupStart($test_name, $size); $this->reporters[$i]->paintGroupStart($test_name, $size);
} }
} }
@ -718,8 +730,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function paintGroupEnd($test_name) { function paintGroupEnd($test_name) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintGroupEnd($test_name); $this->reporters[$i]->paintGroupEnd($test_name);
} }
} }
@ -729,8 +741,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function paintCaseStart($test_name) { function paintCaseStart($test_name) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintCaseStart($test_name); $this->reporters[$i]->paintCaseStart($test_name);
} }
} }
@ -740,8 +752,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function paintCaseEnd($test_name) { function paintCaseEnd($test_name) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintCaseEnd($test_name); $this->reporters[$i]->paintCaseEnd($test_name);
} }
} }
@ -751,8 +763,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function paintMethodStart($test_name) { function paintMethodStart($test_name) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintMethodStart($test_name); $this->reporters[$i]->paintMethodStart($test_name);
} }
} }
@ -762,8 +774,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function paintMethodEnd($test_name) { function paintMethodEnd($test_name) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintMethodEnd($test_name); $this->reporters[$i]->paintMethodEnd($test_name);
} }
} }
@ -773,8 +785,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function paintPass($message) { function paintPass($message) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintPass($message); $this->reporters[$i]->paintPass($message);
} }
} }
@ -784,8 +796,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function paintFail($message) { function paintFail($message) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintFail($message); $this->reporters[$i]->paintFail($message);
} }
} }
@ -796,19 +808,19 @@ class MultipleReporter {
* @access public * @access public
*/ */
function paintError($message) { function paintError($message) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintError($message); $this->reporters[$i]->paintError($message);
} }
} }
/** /**
* Chains to the wrapped reporter. * Chains to the wrapped reporter.
* @param Exception $exception Exception to display. * @param Exception $exception Exception to display.
* @access public * @access public
*/ */
function paintException($exception) { function paintException($exception) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintException($exception); $this->reporters[$i]->paintException($exception);
} }
} }
@ -818,8 +830,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function paintSkip($message) { function paintSkip($message) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintSkip($message); $this->reporters[$i]->paintSkip($message);
} }
} }
@ -829,8 +841,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function paintMessage($message) { function paintMessage($message) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintMessage($message); $this->reporters[$i]->paintMessage($message);
} }
} }
@ -840,8 +852,8 @@ class MultipleReporter {
* @access public * @access public
*/ */
function paintFormattedMessage($message) { function paintFormattedMessage($message) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintFormattedMessage($message); $this->reporters[$i]->paintFormattedMessage($message);
} }
} }
@ -854,9 +866,9 @@ class MultipleReporter {
* test suite. * test suite.
* @access public * @access public
*/ */
function paintSignal($type, &$payload) { function paintSignal($type, $payload) {
for ($i = 0; $i < count($this->_reporters); $i++) { for ($i = 0; $i < count($this->reporters); $i++) {
$this->_reporters[$i]->paintSignal($type, $payload); $this->reporters[$i]->paintSignal($type, $payload);
} }
} }
} }

42
contrib/simpletest/simpletest/selector.php Normal file → Executable file
View File

@ -3,7 +3,7 @@
* Base include file for SimpleTest. * Base include file for SimpleTest.
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
* @version $Id: selector.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: selector.php 1786 2008-04-26 17:32:20Z pp11 $
*/ */
/**#@+ /**#@+
@ -20,18 +20,22 @@ require_once(dirname(__FILE__) . '/encoding.php');
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleByName { class SimpleByName {
var $_name; private $name;
/** /**
* Stashes the name for later comparison. * Stashes the name for later comparison.
* @param string $name Name attribute to match. * @param string $name Name attribute to match.
*/ */
function SimpleByName($name) { function __construct($name) {
$this->_name = $name; $this->name = $name;
} }
/**
* Accessor for name.
* @returns string $name Name to match.
*/
function getName() { function getName() {
return $this->_name; return $this->name;
} }
/** /**
@ -40,7 +44,7 @@ class SimpleByName {
* @access public * @access public
*/ */
function isMatch($widget) { function isMatch($widget) {
return ($widget->getName() == $this->_name); return ($widget->getName() == $this->name);
} }
} }
@ -51,14 +55,14 @@ class SimpleByName {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleByLabel { class SimpleByLabel {
var $_label; private $label;
/** /**
* Stashes the name for later comparison. * Stashes the name for later comparison.
* @param string $label Visible text to match. * @param string $label Visible text to match.
*/ */
function SimpleByLabel($label) { function __construct($label) {
$this->_label = $label; $this->label = $label;
} }
/** /**
@ -71,7 +75,7 @@ class SimpleByLabel {
if (! method_exists($widget, 'isLabel')) { if (! method_exists($widget, 'isLabel')) {
return false; return false;
} }
return $widget->isLabel($this->_label); return $widget->isLabel($this->label);
} }
} }
@ -82,14 +86,14 @@ class SimpleByLabel {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleById { class SimpleById {
var $_id; private $id;
/** /**
* Stashes the name for later comparison. * Stashes the name for later comparison.
* @param string $id ID atribute to match. * @param string $id ID atribute to match.
*/ */
function SimpleById($id) { function __construct($id) {
$this->_id = $id; $this->id = $id;
} }
/** /**
@ -98,7 +102,7 @@ class SimpleById {
* @access public * @access public
*/ */
function isMatch($widget) { function isMatch($widget) {
return $widget->isId($this->_id); return $widget->isId($this->id);
} }
} }
@ -109,14 +113,14 @@ class SimpleById {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleByLabelOrName { class SimpleByLabelOrName {
var $_label; private $label;
/** /**
* Stashes the name/label for later comparison. * Stashes the name/label for later comparison.
* @param string $label Visible text to match. * @param string $label Visible text to match.
*/ */
function SimpleByLabelOrName($label) { function __construct($label) {
$this->_label = $label; $this->label = $label;
} }
/** /**
@ -127,11 +131,11 @@ class SimpleByLabelOrName {
*/ */
function isMatch($widget) { function isMatch($widget) {
if (method_exists($widget, 'isLabel')) { if (method_exists($widget, 'isLabel')) {
if ($widget->isLabel($this->_label)) { if ($widget->isLabel($this->label)) {
return true; return true;
} }
} }
return ($widget->getName() == $this->_label); return ($widget->getName() == $this->label);
} }
} }
?> ?>

View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: shell_tester.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: shell_tester.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/**#@+ /**#@+
@ -18,14 +18,14 @@ require_once(dirname(__FILE__) . '/test_case.php');
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SimpleShell { class SimpleShell {
var $_output; private $output;
/** /**
* Executes the shell comand and stashes the output. * Executes the shell comand and stashes the output.
* @access public * @access public
*/ */
function SimpleShell() { function __construct() {
$this->_output = false; $this->output = false;
} }
/** /**
@ -37,8 +37,8 @@ class SimpleShell {
* @access public * @access public
*/ */
function execute($command) { function execute($command) {
$this->_output = false; $this->output = false;
exec($command, $this->_output, $ret); exec($command, $this->output, $ret);
return $ret; return $ret;
} }
@ -48,7 +48,7 @@ class SimpleShell {
* @access public * @access public
*/ */
function getOutput() { function getOutput() {
return implode("\n", $this->_output); return implode("\n", $this->output);
} }
/** /**
@ -57,7 +57,7 @@ class SimpleShell {
* @access public * @access public
*/ */
function getOutputAsList() { function getOutputAsList() {
return $this->_output; return $this->output;
} }
} }
@ -69,9 +69,9 @@ class SimpleShell {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class ShellTestCase extends SimpleTestCase { class ShellTestCase extends SimpleTestCase {
var $_current_shell; private $current_shell;
var $_last_status; private $last_status;
var $_last_command; private $last_command;
/** /**
* Creates an empty test case. Should be subclassed * Creates an empty test case. Should be subclassed
@ -80,11 +80,11 @@ class ShellTestCase extends SimpleTestCase {
* the class name if none specified. * the class name if none specified.
* @access public * @access public
*/ */
function ShellTestCase($label = false) { function __construct($label = false) {
$this->SimpleTestCase($label); parent::__construct($label);
$this->_current_shell = &$this->_createShell(); $this->current_shell = $this->createShell();
$this->_last_status = false; $this->last_status = false;
$this->_last_command = ''; $this->last_command = '';
} }
/** /**
@ -94,10 +94,10 @@ class ShellTestCase extends SimpleTestCase {
* @access public * @access public
*/ */
function execute($command) { function execute($command) {
$shell = &$this->_getShell(); $shell = $this->getShell();
$this->_last_status = $shell->execute($command); $this->last_status = $shell->execute($command);
$this->_last_command = $command; $this->last_command = $command;
return ($this->_last_status === 0); return ($this->last_status === 0);
} }
/** /**
@ -114,7 +114,7 @@ class ShellTestCase extends SimpleTestCase {
* @access public * @access public
*/ */
function getOutput() { function getOutput() {
$shell = &$this->_getShell(); $shell = $this->getShell();
return $shell->getOutput(); return $shell->getOutput();
} }
@ -124,7 +124,7 @@ class ShellTestCase extends SimpleTestCase {
* @access public * @access public
*/ */
function getOutputAsList() { function getOutputAsList() {
$shell = &$this->_getShell(); $shell = $this->getShell();
return $shell->getOutputAsList(); return $shell->getOutputAsList();
} }
@ -154,7 +154,7 @@ class ShellTestCase extends SimpleTestCase {
function assertFalse($result, $message = '%s') { function assertFalse($result, $message = '%s') {
return $this->assert(new FalseExpectation(), $result, $message); return $this->assert(new FalseExpectation(), $result, $message);
} }
/** /**
* Will trigger a pass if the two parameters have * Will trigger a pass if the two parameters have
* the same value only. Otherwise a fail. This * the same value only. Otherwise a fail. This
@ -171,7 +171,7 @@ class ShellTestCase extends SimpleTestCase {
$second, $second,
$message); $message);
} }
/** /**
* Will trigger a pass if the two parameters have * Will trigger a pass if the two parameters have
* a different value. Otherwise a fail. This * a different value. Otherwise a fail. This
@ -199,9 +199,9 @@ class ShellTestCase extends SimpleTestCase {
*/ */
function assertExitCode($status, $message = "%s") { function assertExitCode($status, $message = "%s") {
$message = sprintf($message, "Expected status code of [$status] from [" . $message = sprintf($message, "Expected status code of [$status] from [" .
$this->_last_command . "], but got [" . $this->last_command . "], but got [" .
$this->_last_status . "]"); $this->last_status . "]");
return $this->assertTrue($status === $this->_last_status, $message); return $this->assertTrue($status === $this->last_status, $message);
} }
/** /**
@ -213,7 +213,7 @@ class ShellTestCase extends SimpleTestCase {
* @access public * @access public
*/ */
function assertOutput($expected, $message = "%s") { function assertOutput($expected, $message = "%s") {
$shell = &$this->_getShell(); $shell = $this->getShell();
return $this->assert( return $this->assert(
new EqualExpectation($expected), new EqualExpectation($expected),
$shell->getOutput(), $shell->getOutput(),
@ -229,7 +229,7 @@ class ShellTestCase extends SimpleTestCase {
* @access public * @access public
*/ */
function assertOutputPattern($pattern, $message = "%s") { function assertOutputPattern($pattern, $message = "%s") {
$shell = &$this->_getShell(); $shell = $this->getShell();
return $this->assert( return $this->assert(
new PatternExpectation($pattern), new PatternExpectation($pattern),
$shell->getOutput(), $shell->getOutput(),
@ -245,7 +245,7 @@ class ShellTestCase extends SimpleTestCase {
* @access public * @access public
*/ */
function assertNoOutputPattern($pattern, $message = "%s") { function assertNoOutputPattern($pattern, $message = "%s") {
$shell = &$this->_getShell(); $shell = $this->getShell();
return $this->assert( return $this->assert(
new NoPatternExpectation($pattern), new NoPatternExpectation($pattern),
$shell->getOutput(), $shell->getOutput(),
@ -286,7 +286,6 @@ class ShellTestCase extends SimpleTestCase {
* @access public * @access public
*/ */
function assertFilePattern($pattern, $path, $message = "%s") { function assertFilePattern($pattern, $path, $message = "%s") {
$shell = &$this->_getShell();
return $this->assert( return $this->assert(
new PatternExpectation($pattern), new PatternExpectation($pattern),
implode('', file($path)), implode('', file($path)),
@ -303,7 +302,6 @@ class ShellTestCase extends SimpleTestCase {
* @access public * @access public
*/ */
function assertNoFilePattern($pattern, $path, $message = "%s") { function assertNoFilePattern($pattern, $path, $message = "%s") {
$shell = &$this->_getShell();
return $this->assert( return $this->assert(
new NoPatternExpectation($pattern), new NoPatternExpectation($pattern),
implode('', file($path)), implode('', file($path)),
@ -316,8 +314,8 @@ class ShellTestCase extends SimpleTestCase {
* @return Shell Current shell. * @return Shell Current shell.
* @access protected * @access protected
*/ */
function &_getShell() { protected function getShell() {
return $this->_current_shell; return $this->current_shell;
} }
/** /**
@ -325,9 +323,8 @@ class ShellTestCase extends SimpleTestCase {
* @return Shell New shell object. * @return Shell New shell object.
* @access protected * @access protected
*/ */
function &_createShell() { protected function createShell() {
$shell = &new SimpleShell(); return new SimpleShell();
return $shell;
} }
} }
?> ?>

View File

@ -3,17 +3,13 @@
* Global state for SimpleTest and kicker script in future versions. * Global state for SimpleTest and kicker script in future versions.
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: simpletest.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: simpletest.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/**#@+ /**#@+
* include SimpleTest files * include SimpleTest files
*/ */
if (version_compare(phpversion(), '5') >= 0) { require_once(dirname(__FILE__) . '/reflection_php5.php');
require_once(dirname(__FILE__) . '/reflection_php5.php');
} else {
require_once(dirname(__FILE__) . '/reflection_php4.php');
}
require_once(dirname(__FILE__) . '/default_reporter.php'); require_once(dirname(__FILE__) . '/default_reporter.php');
require_once(dirname(__FILE__) . '/compatibility.php'); require_once(dirname(__FILE__) . '/compatibility.php');
/**#@-*/ /**#@-*/
@ -29,10 +25,8 @@ class SimpleTest {
/** /**
* Reads the SimpleTest version from the release file. * Reads the SimpleTest version from the release file.
* @return string Version string. * @return string Version string.
* @static
* @access public
*/ */
function getVersion() { static function getVersion() {
$content = file(dirname(__FILE__) . '/VERSION'); $content = file(dirname(__FILE__) . '/VERSION');
return trim($content[0]); return trim($content[0]);
} }
@ -40,14 +34,10 @@ class SimpleTest {
/** /**
* Sets the name of a test case to ignore, usually * Sets the name of a test case to ignore, usually
* because the class is an abstract case that should * because the class is an abstract case that should
* not be run. Once PHP4 is dropped this will disappear
* as a public method and "abstract" will rule.
* @param string $class Add a class to ignore. * @param string $class Add a class to ignore.
* @static
* @access public
*/ */
function ignore($class) { static function ignore($class) {
$registry = &SimpleTest::_getRegistry(); $registry = &SimpleTest::getRegistry();
$registry['IgnoreList'][strtolower($class)] = true; $registry['IgnoreList'][strtolower($class)] = true;
} }
@ -63,11 +53,9 @@ class SimpleTest {
* the ignore() calls. It's just nice to have the ignore() * the ignore() calls. It's just nice to have the ignore()
* calls at the top of the file before the actual declarations. * calls at the top of the file before the actual declarations.
* @param array $classes Class names of interest. * @param array $classes Class names of interest.
* @static
* @access public
*/ */
function ignoreParentsIfIgnored($classes) { static function ignoreParentsIfIgnored($classes) {
$registry = &SimpleTest::_getRegistry(); $registry = &SimpleTest::getRegistry();
foreach ($classes as $class) { foreach ($classes as $class) {
if (SimpleTest::isIgnored($class)) { if (SimpleTest::isIgnored($class)) {
$reflection = new SimpleReflection($class); $reflection = new SimpleReflection($class);
@ -83,13 +71,11 @@ class SimpleTest {
* which can be retrieved with SimpleTest :: preferred() method. * which can be retrieved with SimpleTest :: preferred() method.
* Instances of the same class are overwritten. * Instances of the same class are overwritten.
* @param object $object Preferred object * @param object $object Preferred object
* @static
* @access public
* @see preferred() * @see preferred()
*/ */
function prefer(&$object) { static function prefer($object) {
$registry = &SimpleTest::_getRegistry(); $registry = &SimpleTest::getRegistry();
$registry['Preferred'][] = &$object; $registry['Preferred'][] = $object;
} }
/** /**
@ -97,16 +83,14 @@ class SimpleTest {
* can be applied in order to retrieve the object of the specific * can be applied in order to retrieve the object of the specific
* class * class
* @param array|string $classes Allowed classes or interfaces. * @param array|string $classes Allowed classes or interfaces.
* @static
* @access public
* @return array|object|null * @return array|object|null
* @see prefer() * @see prefer()
*/ */
function &preferred($classes) { static function preferred($classes) {
if (! is_array($classes)) { if (! is_array($classes)) {
$classes = array($classes); $classes = array($classes);
} }
$registry = &SimpleTest::_getRegistry(); $registry = &SimpleTest::getRegistry();
for ($i = count($registry['Preferred']) - 1; $i >= 0; $i--) { for ($i = count($registry['Preferred']) - 1; $i >= 0; $i--) {
foreach ($classes as $class) { foreach ($classes as $class) {
if (SimpleTestCompatibility::isA($registry['Preferred'][$i], $class)) { if (SimpleTestCompatibility::isA($registry['Preferred'][$i], $class)) {
@ -125,30 +109,12 @@ class SimpleTest {
* use it. * use it.
* @param string $class Class name to test. * @param string $class Class name to test.
* @return boolean True if should not be run. * @return boolean True if should not be run.
* @access public
* @static
*/ */
function isIgnored($class) { static function isIgnored($class) {
$registry = &SimpleTest::_getRegistry(); $registry = &SimpleTest::getRegistry();
return isset($registry['IgnoreList'][strtolower($class)]); return isset($registry['IgnoreList'][strtolower($class)]);
} }
/**
* @deprecated
*/
function setMockBaseClass($mock_base) {
$registry = &SimpleTest::_getRegistry();
$registry['MockBaseClass'] = $mock_base;
}
/**
* @deprecated
*/
function getMockBaseClass() {
$registry = &SimpleTest::_getRegistry();
return $registry['MockBaseClass'];
}
/** /**
* Sets proxy to use on all requests for when * Sets proxy to use on all requests for when
* testing from behind a firewall. Set host * testing from behind a firewall. Set host
@ -157,10 +123,9 @@ class SimpleTest {
* @param string $proxy Proxy host as URL. * @param string $proxy Proxy host as URL.
* @param string $username Proxy username for authentication. * @param string $username Proxy username for authentication.
* @param string $password Proxy password for authentication. * @param string $password Proxy password for authentication.
* @access public
*/ */
function useProxy($proxy, $username = false, $password = false) { static function useProxy($proxy, $username = false, $password = false) {
$registry = &SimpleTest::_getRegistry(); $registry = &SimpleTest::getRegistry();
$registry['DefaultProxy'] = $proxy; $registry['DefaultProxy'] = $proxy;
$registry['DefaultProxyUsername'] = $username; $registry['DefaultProxyUsername'] = $username;
$registry['DefaultProxyPassword'] = $password; $registry['DefaultProxyPassword'] = $password;
@ -169,43 +134,60 @@ class SimpleTest {
/** /**
* Accessor for default proxy host. * Accessor for default proxy host.
* @return string Proxy URL. * @return string Proxy URL.
* @access public
*/ */
function getDefaultProxy() { static function getDefaultProxy() {
$registry = &SimpleTest::_getRegistry(); $registry = &SimpleTest::getRegistry();
return $registry['DefaultProxy']; return $registry['DefaultProxy'];
} }
/** /**
* Accessor for default proxy username. * Accessor for default proxy username.
* @return string Proxy username for authentication. * @return string Proxy username for authentication.
* @access public
*/ */
function getDefaultProxyUsername() { static function getDefaultProxyUsername() {
$registry = &SimpleTest::_getRegistry(); $registry = &SimpleTest::getRegistry();
return $registry['DefaultProxyUsername']; return $registry['DefaultProxyUsername'];
} }
/** /**
* Accessor for default proxy password. * Accessor for default proxy password.
* @return string Proxy password for authentication. * @return string Proxy password for authentication.
* @access public
*/ */
function getDefaultProxyPassword() { static function getDefaultProxyPassword() {
$registry = &SimpleTest::_getRegistry(); $registry = &SimpleTest::getRegistry();
return $registry['DefaultProxyPassword']; return $registry['DefaultProxyPassword'];
} }
/**
* Accessor for default HTML parsers.
* @return array List of parsers to try in
* order until one responds true
* to can().
*/
static function getParsers() {
$registry = &SimpleTest::getRegistry();
return $registry['Parsers'];
}
/**
* Set the list of HTML parsers to attempt to use by default.
* @param array $parsers List of parsers to try in
* order until one responds true
* to can().
*/
static function setParsers($parsers) {
$registry = &SimpleTest::getRegistry();
$registry['Parsers'] = $parsers;
}
/** /**
* Accessor for global registry of options. * Accessor for global registry of options.
* @return hash All stored values. * @return hash All stored values.
* @access private
* @static
*/ */
function &_getRegistry() { protected static function &getRegistry() {
static $registry = false; static $registry = false;
if (! $registry) { if (! $registry) {
$registry = SimpleTest::_getDefaults(); $registry = SimpleTest::getDefaults();
} }
return $registry; return $registry;
} }
@ -214,10 +196,8 @@ class SimpleTest {
* Accessor for the context of the current * Accessor for the context of the current
* test run. * test run.
* @return SimpleTestContext Current test run. * @return SimpleTestContext Current test run.
* @access public
* @static
*/ */
function &getContext() { static function getContext() {
static $context = false; static $context = false;
if (! $context) { if (! $context) {
$context = new SimpleTestContext(); $context = new SimpleTestContext();
@ -228,12 +208,10 @@ class SimpleTest {
/** /**
* Constant default values. * Constant default values.
* @return hash All registry defaults. * @return hash All registry defaults.
* @access private
* @static
*/ */
function _getDefaults() { protected static function getDefaults() {
return array( return array(
'StubBaseClass' => 'SimpleStub', 'Parsers' => false,
'MockBaseClass' => 'SimpleMock', 'MockBaseClass' => 'SimpleMock',
'IgnoreList' => array(), 'IgnoreList' => array(),
'DefaultProxy' => false, 'DefaultProxy' => false,
@ -241,6 +219,22 @@ class SimpleTest {
'DefaultProxyPassword' => false, 'DefaultProxyPassword' => false,
'Preferred' => array(new HtmlReporter(), new TextReporter(), new XmlReporter())); 'Preferred' => array(new HtmlReporter(), new TextReporter(), new XmlReporter()));
} }
/**
* @deprecated
*/
static function setMockBaseClass($mock_base) {
$registry = &SimpleTest::getRegistry();
$registry['MockBaseClass'] = $mock_base;
}
/**
* @deprecated
*/
static function getMockBaseClass() {
$registry = &SimpleTest::getRegistry();
return $registry['MockBaseClass'];
}
} }
/** /**
@ -252,16 +246,16 @@ class SimpleTest {
* @package SimpleTest * @package SimpleTest
*/ */
class SimpleTestContext { class SimpleTestContext {
var $_test; private $test;
var $_reporter; private $reporter;
var $_resources; private $resources;
/** /**
* Clears down the current context. * Clears down the current context.
* @access public * @access public
*/ */
function clear() { function clear() {
$this->_resources = array(); $this->resources = array();
} }
/** /**
@ -269,20 +263,18 @@ class SimpleTestContext {
* global instance can be used by the mock objects * global instance can be used by the mock objects
* to send message to the test cases. * to send message to the test cases.
* @param SimpleTestCase $test Test case to register. * @param SimpleTestCase $test Test case to register.
* @access public
*/ */
function setTest(&$test) { function setTest($test) {
$this->clear(); $this->clear();
$this->_test = &$test; $this->test = $test;
} }
/** /**
* Accessor for currently running test case. * Accessor for currently running test case.
* @return SimpleTestCase Current test. * @return SimpleTestCase Current test.
* @access public
*/ */
function &getTest() { function getTest() {
return $this->_test; return $this->test;
} }
/** /**
@ -290,33 +282,29 @@ class SimpleTestContext {
* global instance can be used by the mock objects * global instance can be used by the mock objects
* to send messages. * to send messages.
* @param SimpleReporter $reporter Reporter to register. * @param SimpleReporter $reporter Reporter to register.
* @access public
*/ */
function setReporter(&$reporter) { function setReporter($reporter) {
$this->clear(); $this->clear();
$this->_reporter = &$reporter; $this->reporter = $reporter;
} }
/** /**
* Accessor for current reporter. * Accessor for current reporter.
* @return SimpleReporter Current reporter. * @return SimpleReporter Current reporter.
* @access public
*/ */
function &getReporter() { function getReporter() {
return $this->_reporter; return $this->reporter;
} }
/** /**
* Accessor for the Singleton resource. * Accessor for the Singleton resource.
* @return object Global resource. * @return object Global resource.
* @access public
* @static
*/ */
function &get($resource) { function get($resource) {
if (! isset($this->_resources[$resource])) { if (! isset($this->resources[$resource])) {
$this->_resources[$resource] = &new $resource(); $this->resources[$resource] = new $resource();
} }
return $this->_resources[$resource]; return $this->resources[$resource];
} }
} }
@ -327,15 +315,15 @@ class SimpleTestContext {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SimpleStackTrace { class SimpleStackTrace {
var $_prefixes; private $prefixes;
/** /**
* Stashes the list of target prefixes. * Stashes the list of target prefixes.
* @param array $prefixes List of method prefixes * @param array $prefixes List of method prefixes
* to search for. * to search for.
*/ */
function SimpleStackTrace($prefixes) { function __construct($prefixes) {
$this->_prefixes = $prefixes; $this->prefixes = $prefixes;
} }
/** /**
@ -344,15 +332,14 @@ class SimpleStackTrace {
* @param array $stack List of stack frames. * @param array $stack List of stack frames.
* @return string Snippet of test report with line * @return string Snippet of test report with line
* number and file. * number and file.
* @access public
*/ */
function traceMethod($stack = false) { function traceMethod($stack = false) {
$stack = $stack ? $stack : $this->_captureTrace(); $stack = $stack ? $stack : $this->captureTrace();
foreach ($stack as $frame) { foreach ($stack as $frame) {
if ($this->_frameLiesWithinSimpleTestFolder($frame)) { if ($this->frameLiesWithinSimpleTestFolder($frame)) {
continue; continue;
} }
if ($this->_frameMatchesPrefix($frame)) { if ($this->frameMatchesPrefix($frame)) {
return ' at [' . $frame['file'] . ' line ' . $frame['line'] . ']'; return ' at [' . $frame['file'] . ' line ' . $frame['line'] . ']';
} }
} }
@ -363,9 +350,8 @@ class SimpleStackTrace {
* Test to see if error is generated by SimpleTest itself. * Test to see if error is generated by SimpleTest itself.
* @param array $frame PHP stack frame. * @param array $frame PHP stack frame.
* @return boolean True if a SimpleTest file. * @return boolean True if a SimpleTest file.
* @access private
*/ */
function _frameLiesWithinSimpleTestFolder($frame) { protected function frameLiesWithinSimpleTestFolder($frame) {
if (isset($frame['file'])) { if (isset($frame['file'])) {
$path = substr(SIMPLE_TEST, 0, -1); $path = substr(SIMPLE_TEST, 0, -1);
if (strpos($frame['file'], $path) === 0) { if (strpos($frame['file'], $path) === 0) {
@ -381,10 +367,9 @@ class SimpleStackTrace {
* Tries to determine if the method call is an assert, etc. * Tries to determine if the method call is an assert, etc.
* @param array $frame PHP stack frame. * @param array $frame PHP stack frame.
* @return boolean True if matches a target. * @return boolean True if matches a target.
* @access private
*/ */
function _frameMatchesPrefix($frame) { protected function frameMatchesPrefix($frame) {
foreach ($this->_prefixes as $prefix) { foreach ($this->prefixes as $prefix) {
if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) { if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) {
return true; return true;
} }
@ -395,84 +380,12 @@ class SimpleStackTrace {
/** /**
* Grabs a current stack trace. * Grabs a current stack trace.
* @return array Fulle trace. * @return array Fulle trace.
* @access private
*/ */
function _captureTrace() { protected function captureTrace() {
if (function_exists('debug_backtrace')) { if (function_exists('debug_backtrace')) {
return array_reverse(debug_backtrace()); return array_reverse(debug_backtrace());
} }
return array(); return array();
} }
} }
?>
/**
* @package SimpleTest
* @subpackage UnitTester
* @deprecated
*/
class SimpleTestOptions extends SimpleTest {
/**
* @deprecated
*/
function getVersion() {
return Simpletest::getVersion();
}
/**
* @deprecated
*/
function ignore($class) {
return Simpletest::ignore($class);
}
/**
* @deprecated
*/
function isIgnored($class) {
return Simpletest::isIgnored($class);
}
/**
* @deprecated
*/
function setMockBaseClass($mock_base) {
return Simpletest::setMockBaseClass($mock_base);
}
/**
* @deprecated
*/
function getMockBaseClass() {
return Simpletest::getMockBaseClass();
}
/**
* @deprecated
*/
function useProxy($proxy, $username = false, $password = false) {
return Simpletest::useProxy($proxy, $username, $password);
}
/**
* @deprecated
*/
function getDefaultProxy() {
return Simpletest::getDefaultProxy();
}
/**
* @deprecated
*/
function getDefaultProxyUsername() {
return Simpletest::getDefaultProxyUsername();
}
/**
* @deprecated
*/
function getDefaultProxyPassword() {
return Simpletest::getDefaultProxyPassword();
}
}
?>

168
contrib/simpletest/simpletest/socket.php Normal file → Executable file
View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage MockObjects * @subpackage MockObjects
* @version $Id: socket.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: socket.php 1953 2009-09-20 01:26:25Z jsweat $
*/ */
/**#@+ /**#@+
@ -19,14 +19,14 @@ require_once(dirname(__FILE__) . '/compatibility.php');
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleStickyError { class SimpleStickyError {
var $_error = 'Constructor not chained'; private $error = 'Constructor not chained';
/** /**
* Sets the error to empty. * Sets the error to empty.
* @access public * @access public
*/ */
function SimpleStickyError() { function __construct() {
$this->_clearError(); $this->clearError();
} }
/** /**
@ -35,7 +35,7 @@ class SimpleStickyError {
* @access public * @access public
*/ */
function isError() { function isError() {
return ($this->_error != ''); return ($this->error != '');
} }
/** /**
@ -45,7 +45,7 @@ class SimpleStickyError {
* @access public * @access public
*/ */
function getError() { function getError() {
return $this->_error; return $this->error;
} }
/** /**
@ -53,16 +53,112 @@ class SimpleStickyError {
* @param string Error message to stash. * @param string Error message to stash.
* @access protected * @access protected
*/ */
function _setError($error) { function setError($error) {
$this->_error = $error; $this->error = $error;
} }
/** /**
* Resets the error state to no error. * Resets the error state to no error.
* @access protected * @access protected
*/ */
function _clearError() { function clearError() {
$this->_setError(''); $this->setError('');
}
}
/**
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleFileSocket extends SimpleStickyError {
private $handle;
private $is_open = false;
private $sent = '';
private $block_size;
/**
* Opens a socket for reading and writing.
* @param SimpleUrl $file Target URI to fetch.
* @param integer $block_size Size of chunk to read.
* @access public
*/
function __construct($file, $block_size = 1024) {
parent::__construct();
if (! ($this->handle = $this->openFile($file, $error))) {
$file_string = $file->asString();
$this->setError("Cannot open [$file_string] with [$error]");
return;
}
$this->is_open = true;
$this->block_size = $block_size;
}
/**
* Writes some data to the socket and saves alocal copy.
* @param string $message String to send to socket.
* @return boolean True if successful.
* @access public
*/
function write($message) {
return true;
}
/**
* Reads data from the socket. The error suppresion
* is a workaround for PHP4 always throwing a warning
* with a secure socket.
* @return integer/boolean Incoming bytes. False
* on error.
* @access public
*/
function read() {
$raw = @fread($this->handle, $this->block_size);
if ($raw === false) {
$this->setError('Cannot read from socket');
$this->close();
}
return $raw;
}
/**
* Accessor for socket open state.
* @return boolean True if open.
* @access public
*/
function isOpen() {
return $this->is_open;
}
/**
* Closes the socket preventing further reads.
* Cannot be reopened once closed.
* @return boolean True if successful.
* @access public
*/
function close() {
if (!$this->is_open) return false;
$this->is_open = false;
return fclose($this->handle);
}
/**
* Accessor for content so far.
* @return string Bytes sent only.
* @access public
*/
function getSent() {
return $this->sent;
}
/**
* Actually opens the low level socket.
* @param SimpleUrl $file SimpleUrl file target.
* @param string $error Recipient of error message.
* @param integer $timeout Maximum time to wait for connection.
* @access protected
*/
protected function openFile($file, &$error) {
return @fopen($file->asString(), 'r');
} }
} }
@ -72,10 +168,10 @@ class SimpleStickyError {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleSocket extends SimpleStickyError { class SimpleSocket extends SimpleStickyError {
var $_handle; private $handle;
var $_is_open = false; private $is_open = false;
var $_sent = ''; private $sent = '';
var $lock_size; private $lock_size;
/** /**
* Opens a socket for reading and writing. * Opens a socket for reading and writing.
@ -85,15 +181,15 @@ class SimpleSocket extends SimpleStickyError {
* @param integer $block_size Size of chunk to read. * @param integer $block_size Size of chunk to read.
* @access public * @access public
*/ */
function SimpleSocket($host, $port, $timeout, $block_size = 255) { function __construct($host, $port, $timeout, $block_size = 255) {
$this->SimpleStickyError(); parent::__construct();
if (! ($this->_handle = $this->_openSocket($host, $port, $error_number, $error, $timeout))) { if (! ($this->handle = $this->openSocket($host, $port, $error_number, $error, $timeout))) {
$this->_setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds"); $this->setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds");
return; return;
} }
$this->_is_open = true; $this->is_open = true;
$this->_block_size = $block_size; $this->block_size = $block_size;
SimpleTestCompatibility::setTimeout($this->_handle, $timeout); SimpleTestCompatibility::setTimeout($this->handle, $timeout);
} }
/** /**
@ -106,16 +202,16 @@ class SimpleSocket extends SimpleStickyError {
if ($this->isError() || ! $this->isOpen()) { if ($this->isError() || ! $this->isOpen()) {
return false; return false;
} }
$count = fwrite($this->_handle, $message); $count = fwrite($this->handle, $message);
if (! $count) { if (! $count) {
if ($count === false) { if ($count === false) {
$this->_setError('Cannot write to socket'); $this->setError('Cannot write to socket');
$this->close(); $this->close();
} }
return false; return false;
} }
fflush($this->_handle); fflush($this->handle);
$this->_sent .= $message; $this->sent .= $message;
return true; return true;
} }
@ -131,9 +227,9 @@ class SimpleSocket extends SimpleStickyError {
if ($this->isError() || ! $this->isOpen()) { if ($this->isError() || ! $this->isOpen()) {
return false; return false;
} }
$raw = @fread($this->_handle, $this->_block_size); $raw = @fread($this->handle, $this->block_size);
if ($raw === false) { if ($raw === false) {
$this->_setError('Cannot read from socket'); $this->setError('Cannot read from socket');
$this->close(); $this->close();
} }
return $raw; return $raw;
@ -145,7 +241,7 @@ class SimpleSocket extends SimpleStickyError {
* @access public * @access public
*/ */
function isOpen() { function isOpen() {
return $this->_is_open; return $this->is_open;
} }
/** /**
@ -155,8 +251,8 @@ class SimpleSocket extends SimpleStickyError {
* @access public * @access public
*/ */
function close() { function close() {
$this->_is_open = false; $this->is_open = false;
return fclose($this->_handle); return fclose($this->handle);
} }
/** /**
@ -165,7 +261,7 @@ class SimpleSocket extends SimpleStickyError {
* @access public * @access public
*/ */
function getSent() { function getSent() {
return $this->_sent; return $this->sent;
} }
/** /**
@ -177,7 +273,7 @@ class SimpleSocket extends SimpleStickyError {
* @param integer $timeout Maximum time to wait for connection. * @param integer $timeout Maximum time to wait for connection.
* @access protected * @access protected
*/ */
function _openSocket($host, $port, &$error_number, &$error, $timeout) { protected function openSocket($host, $port, &$error_number, &$error, $timeout) {
return @fsockopen($host, $port, $error_number, $error, $timeout); return @fsockopen($host, $port, $error_number, $error, $timeout);
} }
} }
@ -196,8 +292,8 @@ class SimpleSecureSocket extends SimpleSocket {
* @param integer $timeout Connection timeout in seconds. * @param integer $timeout Connection timeout in seconds.
* @access public * @access public
*/ */
function SimpleSecureSocket($host, $port, $timeout) { function __construct($host, $port, $timeout) {
$this->SimpleSocket($host, $port, $timeout); parent::__construct($host, $port, $timeout);
} }
/** /**
@ -209,8 +305,8 @@ class SimpleSecureSocket extends SimpleSocket {
* @param integer $timeout Maximum time to wait for connection. * @param integer $timeout Maximum time to wait for connection.
* @access protected * @access protected
*/ */
function _openSocket($host, $port, &$error_number, &$error, $timeout) { function openSocket($host, $port, &$error_number, &$error, $timeout) {
return parent::_openSocket("tls://$host", $port, $error_number, $error, $timeout); return parent::openSocket("tls://$host", $port, $error_number, $error, $timeout);
} }
} }
?> ?>

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@
* Base include file for SimpleTest * Base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: test_case.php 1726 2008-04-08 01:20:10Z lastcraft $ * @version $Id: test_case.php 2012 2011-04-29 08:57:00Z pp11 $
*/ */
/**#@+ /**#@+
@ -17,19 +17,15 @@ require_once(dirname(__FILE__) . '/scorer.php');
require_once(dirname(__FILE__) . '/expectation.php'); require_once(dirname(__FILE__) . '/expectation.php');
require_once(dirname(__FILE__) . '/dumper.php'); require_once(dirname(__FILE__) . '/dumper.php');
require_once(dirname(__FILE__) . '/simpletest.php'); require_once(dirname(__FILE__) . '/simpletest.php');
if (version_compare(phpversion(), '5') >= 0) { require_once(dirname(__FILE__) . '/exceptions.php');
require_once(dirname(__FILE__) . '/exceptions.php'); require_once(dirname(__FILE__) . '/reflection_php5.php');
require_once(dirname(__FILE__) . '/reflection_php5.php'); /**#@-*/
} else {
require_once(dirname(__FILE__) . '/reflection_php4.php');
}
if (! defined('SIMPLE_TEST')) { if (! defined('SIMPLE_TEST')) {
/** /**
* @ignore * @ignore
*/ */
define('SIMPLE_TEST', dirname(__FILE__) . DIRECTORY_SEPARATOR); define('SIMPLE_TEST', dirname(__FILE__) . DIRECTORY_SEPARATOR);
} }
/**#@-*/
/** /**
* Basic test case. This is the smallest unit of a test * Basic test case. This is the smallest unit of a test
@ -40,10 +36,10 @@ if (! defined('SIMPLE_TEST')) {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SimpleTestCase { class SimpleTestCase {
var $_label = false; private $label = false;
var $_reporter; protected $reporter;
var $_observers; private $observers;
var $_should_skip = false; private $should_skip = false;
/** /**
* Sets up the test with no display. * Sets up the test with no display.
@ -51,9 +47,9 @@ class SimpleTestCase {
* the class name is used. * the class name is used.
* @access public * @access public
*/ */
function SimpleTestCase($label = false) { function __construct($label = false) {
if ($label) { if ($label) {
$this->_label = $label; $this->label = $label;
} }
} }
@ -63,7 +59,7 @@ class SimpleTestCase {
* @access public * @access public
*/ */
function getLabel() { function getLabel() {
return $this->_label ? $this->_label : get_class($this); return $this->label ? $this->label : get_class($this);
} }
/** /**
@ -83,13 +79,21 @@ class SimpleTestCase {
* @access public * @access public
*/ */
function skipIf($should_skip, $message = '%s') { function skipIf($should_skip, $message = '%s') {
if ($should_skip && ! $this->_should_skip) { if ($should_skip && ! $this->should_skip) {
$this->_should_skip = true; $this->should_skip = true;
$message = sprintf($message, 'Skipping [' . get_class($this) . ']'); $message = sprintf($message, 'Skipping [' . get_class($this) . ']');
$this->_reporter->paintSkip($message . $this->getAssertionLine()); $this->reporter->paintSkip($message . $this->getAssertionLine());
} }
} }
/**
* Accessor for the private variable $_shoud_skip
* @access public
*/
function shouldSkip() {
return $this->should_skip;
}
/** /**
* Will issue a message to the reporter and tell the test * Will issue a message to the reporter and tell the test
* case to skip if the incoming flag is false. * case to skip if the incoming flag is false.
@ -106,12 +110,9 @@ class SimpleTestCase {
* @return SimpleInvoker Individual test runner. * @return SimpleInvoker Individual test runner.
* @access public * @access public
*/ */
function &createInvoker() { function createInvoker() {
$invoker = &new SimpleErrorTrappingInvoker(new SimpleInvoker($this)); return new SimpleErrorTrappingInvoker(
if (version_compare(phpversion(), '5') >= 0) { new SimpleExceptionTrappingInvoker(new SimpleInvoker($this)));
$invoker = &new SimpleExceptionTrappingInvoker($invoker);
}
return $invoker;
} }
/** /**
@ -122,23 +123,23 @@ class SimpleTestCase {
* @return boolean True if all tests passed. * @return boolean True if all tests passed.
* @access public * @access public
*/ */
function run(&$reporter) { function run($reporter) {
$context = &SimpleTest::getContext(); $context = SimpleTest::getContext();
$context->setTest($this); $context->setTest($this);
$context->setReporter($reporter); $context->setReporter($reporter);
$this->_reporter = &$reporter; $this->reporter = $reporter;
$started = false; $started = false;
foreach ($this->getTests() as $method) { foreach ($this->getTests() as $method) {
if ($reporter->shouldInvoke($this->getLabel(), $method)) { if ($reporter->shouldInvoke($this->getLabel(), $method)) {
$this->skip(); $this->skip();
if ($this->_should_skip) { if ($this->should_skip) {
break; break;
} }
if (! $started) { if (! $started) {
$reporter->paintCaseStart($this->getLabel()); $reporter->paintCaseStart($this->getLabel());
$started = true; $started = true;
} }
$invoker = &$this->_reporter->createInvoker($this->createInvoker()); $invoker = $this->reporter->createInvoker($this->createInvoker());
$invoker->before($method); $invoker->before($method);
$invoker->invoke($method); $invoker->invoke($method);
$invoker->after($method); $invoker->after($method);
@ -147,7 +148,8 @@ class SimpleTestCase {
if ($started) { if ($started) {
$reporter->paintCaseEnd($this->getLabel()); $reporter->paintCaseEnd($this->getLabel());
} }
unset($this->_reporter); unset($this->reporter);
$context->setTest(null);
return $reporter->getStatus(); return $reporter->getStatus();
} }
@ -162,7 +164,7 @@ class SimpleTestCase {
function getTests() { function getTests() {
$methods = array(); $methods = array();
foreach (get_class_methods(get_class($this)) as $method) { foreach (get_class_methods(get_class($this)) as $method) {
if ($this->_isTest($method)) { if ($this->isTest($method)) {
$methods[] = $method; $methods[] = $method;
} }
} }
@ -177,7 +179,7 @@ class SimpleTestCase {
* @return boolean True if test method. * @return boolean True if test method.
* @access protected * @access protected
*/ */
function _isTest($method) { protected function isTest($method) {
if (strtolower(substr($method, 0, 4)) == 'test') { if (strtolower(substr($method, 0, 4)) == 'test') {
return ! SimpleTestCompatibility::isA($this, strtolower($method)); return ! SimpleTestCompatibility::isA($this, strtolower($method));
} }
@ -190,8 +192,8 @@ class SimpleTestCase {
* @access public * @access public
*/ */
function before($method) { function before($method) {
$this->_reporter->paintMethodStart($method); $this->reporter->paintMethodStart($method);
$this->_observers = array(); $this->observers = array();
} }
/** /**
@ -217,10 +219,10 @@ class SimpleTestCase {
* @access public * @access public
*/ */
function after($method) { function after($method) {
for ($i = 0; $i < count($this->_observers); $i++) { for ($i = 0; $i < count($this->observers); $i++) {
$this->_observers[$i]->atTestEnd($method, $this); $this->observers[$i]->atTestEnd($method, $this);
} }
$this->_reporter->paintMethodEnd($method); $this->reporter->paintMethodEnd($method);
} }
/** /**
@ -229,18 +231,18 @@ class SimpleTestCase {
* method. * method.
* @access public * @access public
*/ */
function tell(&$observer) { function tell($observer) {
$this->_observers[] = &$observer; $this->observers[] = &$observer;
} }
/** /**
* @deprecated * @deprecated
*/ */
function pass($message = "Pass") { function pass($message = "Pass") {
if (! isset($this->_reporter)) { if (! isset($this->reporter)) {
trigger_error('Can only make assertions within test methods'); trigger_error('Can only make assertions within test methods');
} }
$this->_reporter->paintPass( $this->reporter->paintPass(
$message . $this->getAssertionLine()); $message . $this->getAssertionLine());
return true; return true;
} }
@ -251,10 +253,10 @@ class SimpleTestCase {
* @access public * @access public
*/ */
function fail($message = "Fail") { function fail($message = "Fail") {
if (! isset($this->_reporter)) { if (! isset($this->reporter)) {
trigger_error('Can only make assertions within test methods'); trigger_error('Can only make assertions within test methods');
} }
$this->_reporter->paintFail( $this->reporter->paintFail(
$message . $this->getAssertionLine()); $message . $this->getAssertionLine());
return false; return false;
} }
@ -269,10 +271,10 @@ class SimpleTestCase {
* @access public * @access public
*/ */
function error($severity, $message, $file, $line) { function error($severity, $message, $file, $line) {
if (! isset($this->_reporter)) { if (! isset($this->reporter)) {
trigger_error('Can only make assertions within test methods'); trigger_error('Can only make assertions within test methods');
} }
$this->_reporter->paintError( $this->reporter->paintError(
"Unexpected PHP error [$message] severity [$severity] in [$file line $line]"); "Unexpected PHP error [$message] severity [$severity] in [$file line $line]");
} }
@ -283,17 +285,19 @@ class SimpleTestCase {
* @access public * @access public
*/ */
function exception($exception) { function exception($exception) {
$this->_reporter->paintException($exception); $this->reporter->paintException($exception);
} }
/** /**
* @deprecated * For user defined expansion of the available messages.
* @param string $type Tag for sorting the signals.
* @param mixed $payload Extra user specific information.
*/ */
function signal($type, &$payload) { function signal($type, $payload) {
if (! isset($this->_reporter)) { if (! isset($this->reporter)) {
trigger_error('Can only make assertions within test methods'); trigger_error('Can only make assertions within test methods');
} }
$this->_reporter->paintSignal($type, $payload); $this->reporter->paintSignal($type, $payload);
} }
/** /**
@ -305,25 +309,18 @@ class SimpleTestCase {
* @return boolean True on pass * @return boolean True on pass
* @access public * @access public
*/ */
function assert(&$expectation, $compare, $message = '%s') { function assert($expectation, $compare, $message = '%s') {
if ($expectation->test($compare)) { if ($expectation->test($compare)) {
return $this->pass(sprintf( return $this->pass(sprintf(
$message, $message,
$expectation->overlayMessage($compare, $this->_reporter->getDumper()))); $expectation->overlayMessage($compare, $this->reporter->getDumper())));
} else { } else {
return $this->fail(sprintf( return $this->fail(sprintf(
$message, $message,
$expectation->overlayMessage($compare, $this->_reporter->getDumper()))); $expectation->overlayMessage($compare, $this->reporter->getDumper())));
} }
} }
/**
* @deprecated
*/
function assertExpectation(&$expectation, $compare, $message = '%s') {
return $this->assert($expectation, $compare, $message);
}
/** /**
* Uses a stack trace to find the line of an assertion. * Uses a stack trace to find the line of an assertion.
* @return string Line number of first assert* * @return string Line number of first assert*
@ -345,27 +342,19 @@ class SimpleTestCase {
* @access public * @access public
*/ */
function dump($variable, $message = false) { function dump($variable, $message = false) {
$dumper = $this->_reporter->getDumper(); $dumper = $this->reporter->getDumper();
$formatted = $dumper->dump($variable); $formatted = $dumper->dump($variable);
if ($message) { if ($message) {
$formatted = $message . "\n" . $formatted; $formatted = $message . "\n" . $formatted;
} }
$this->_reporter->paintFormattedMessage($formatted); $this->reporter->paintFormattedMessage($formatted);
return $variable; return $variable;
} }
/**
* @deprecated
*/
function sendMessage($message) {
$this->_reporter->PaintMessage($message);
}
/** /**
* Accessor for the number of subtests including myelf. * Accessor for the number of subtests including myelf.
* @return integer Number of test cases. * @return integer Number of test cases.
* @access public * @access public
* @static
*/ */
function getSize() { function getSize() {
return 1; return 1;
@ -374,6 +363,8 @@ class SimpleTestCase {
/** /**
* Helps to extract test cases automatically from a file. * Helps to extract test cases automatically from a file.
* @package SimpleTest
* @subpackage UnitTester
*/ */
class SimpleFileLoader { class SimpleFileLoader {
@ -385,34 +376,33 @@ class SimpleFileLoader {
* @return TestSuite The new test suite. * @return TestSuite The new test suite.
* @access public * @access public
*/ */
function &load($test_file) { function load($test_file) {
$existing_classes = get_declared_classes(); $existing_classes = get_declared_classes();
$existing_globals = get_defined_vars(); $existing_globals = get_defined_vars();
include_once($test_file); include_once($test_file);
$new_globals = get_defined_vars(); $new_globals = get_defined_vars();
$this->_makeFileVariablesGlobal($existing_globals, $new_globals); $this->makeFileVariablesGlobal($existing_globals, $new_globals);
$new_classes = array_diff(get_declared_classes(), $existing_classes); $new_classes = array_diff(get_declared_classes(), $existing_classes);
if (empty($new_classes)) { if (empty($new_classes)) {
$new_classes = $this->_scrapeClassesFromFile($test_file); $new_classes = $this->scrapeClassesFromFile($test_file);
} }
$classes = $this->selectRunnableTests($new_classes); $classes = $this->selectRunnableTests($new_classes);
$suite = &$this->createSuiteFromClasses($test_file, $classes); return $this->createSuiteFromClasses($test_file, $classes);
return $suite;
} }
/** /**
* Imports new variables into the global namespace. * Imports new variables into the global namespace.
* @param hash $existing Variables before the file was loaded. * @param hash $existing Variables before the file was loaded.
* @param hash $new Variables after the file was loaded. * @param hash $new Variables after the file was loaded.
* @access private * @access private
*/ */
function _makeFileVariablesGlobal($existing, $new) { protected function makeFileVariablesGlobal($existing, $new) {
$globals = array_diff(array_keys($new), array_keys($existing)); $globals = array_diff(array_keys($new), array_keys($existing));
foreach ($globals as $global) { foreach ($globals as $global) {
$_GLOBALS[$global] = $new[$global]; $GLOBALS[$global] = $new[$global];
} }
} }
/** /**
* Lookup classnames from file contents, in case the * Lookup classnames from file contents, in case the
* file may have been included before. * file may have been included before.
@ -423,7 +413,7 @@ class SimpleFileLoader {
* @param string $test_file File name with classes. * @param string $test_file File name with classes.
* @access private * @access private
*/ */
function _scrapeClassesFromFile($test_file) { protected function scrapeClassesFromFile($test_file) {
preg_match_all('~^\s*class\s+(\w+)(\s+(extends|implements)\s+\w+)*\s*\{~mi', preg_match_all('~^\s*class\s+(\w+)(\s+(extends|implements)\s+\w+)*\s*\{~mi',
file_get_contents($test_file), file_get_contents($test_file),
$matches ); $matches );
@ -461,16 +451,16 @@ class SimpleFileLoader {
* test cases. * test cases.
* @access public * @access public
*/ */
function &createSuiteFromClasses($title, $classes) { function createSuiteFromClasses($title, $classes) {
if (count($classes) == 0) { if (count($classes) == 0) {
$suite = &new BadTestSuite($title, "No runnable test cases in [$title]"); $suite = new BadTestSuite($title, "No runnable test cases in [$title]");
return $suite; return $suite;
} }
SimpleTest::ignoreParentsIfIgnored($classes); SimpleTest::ignoreParentsIfIgnored($classes);
$suite = &new TestSuite($title); $suite = new TestSuite($title);
foreach ($classes as $class) { foreach ($classes as $class) {
if (! SimpleTest::isIgnored($class)) { if (! SimpleTest::isIgnored($class)) {
$suite->addTestClass($class); $suite->add($class);
} }
} }
return $suite; return $suite;
@ -485,8 +475,8 @@ class SimpleFileLoader {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class TestSuite { class TestSuite {
var $_label; private $label;
var $_test_cases; private $test_cases;
/** /**
* Sets the name of the test suite. * Sets the name of the test suite.
@ -495,8 +485,8 @@ class TestSuite {
* @access public * @access public
*/ */
function TestSuite($label = false) { function TestSuite($label = false) {
$this->_label = $label; $this->label = $label;
$this->_test_cases = array(); $this->test_cases = array();
} }
/** /**
@ -506,29 +496,11 @@ class TestSuite {
* @access public * @access public
*/ */
function getLabel() { function getLabel() {
if (! $this->_label) { if (! $this->label) {
return ($this->getSize() == 1) ? return ($this->getSize() == 1) ?
get_class($this->_test_cases[0]) : get_class($this); get_class($this->test_cases[0]) : get_class($this);
} else { } else {
return $this->_label; return $this->label;
}
}
/**
* @deprecated
*/
function addTestCase(&$test_case) {
$this->_test_cases[] = &$test_case;
}
/**
* @deprecated
*/
function addTestClass($class) {
if (TestSuite::getBaseTestCase($class) == 'testsuite') {
$this->_test_cases[] = &new $class();
} else {
$this->_test_cases[] = $class;
} }
} }
@ -540,23 +512,16 @@ class TestSuite {
* runnable test interface. * runnable test interface.
* @access public * @access public
*/ */
function add(&$test_case) { function add($test_case) {
if (! is_string($test_case)) { if (! is_string($test_case)) {
$this->_test_cases[] = &$test_case; $this->test_cases[] = $test_case;
} elseif (TestSuite::getBaseTestCase($class) == 'testsuite') { } elseif (TestSuite::getBaseTestCase($test_case) == 'testsuite') {
$this->_test_cases[] = &new $class(); $this->test_cases[] = new $test_case();
} else { } else {
$this->_test_cases[] = $class; $this->test_cases[] = $test_case;
} }
} }
/**
* @deprecated
*/
function addTestFile($test_file) {
$this->addFile($test_file);
}
/** /**
* Builds a test suite from a library of test cases. * Builds a test suite from a library of test cases.
* The new suite is composed into this one. * The new suite is composed into this one.
@ -576,7 +541,7 @@ class TestSuite {
* @param SimpleCollector $collector Directory scanner. * @param SimpleCollector $collector Directory scanner.
* @access public * @access public
*/ */
function collect($path, &$collector) { function collect($path, $collector) {
$collector->collect($this, $path); $collector->collect($this, $path);
} }
@ -586,16 +551,16 @@ class TestSuite {
* @param SimpleReporter $reporter Current test reporter. * @param SimpleReporter $reporter Current test reporter.
* @access public * @access public
*/ */
function run(&$reporter) { function run($reporter) {
$reporter->paintGroupStart($this->getLabel(), $this->getSize()); $reporter->paintGroupStart($this->getLabel(), $this->getSize());
for ($i = 0, $count = count($this->_test_cases); $i < $count; $i++) { for ($i = 0, $count = count($this->test_cases); $i < $count; $i++) {
if (is_string($this->_test_cases[$i])) { if (is_string($this->test_cases[$i])) {
$class = $this->_test_cases[$i]; $class = $this->test_cases[$i];
$test = &new $class(); $test = new $class();
$test->run($reporter); $test->run($reporter);
unset($test); unset($test);
} else { } else {
$this->_test_cases[$i]->run($reporter); $this->test_cases[$i]->run($reporter);
} }
} }
$reporter->paintGroupEnd($this->getLabel()); $reporter->paintGroupEnd($this->getLabel());
@ -609,7 +574,7 @@ class TestSuite {
*/ */
function getSize() { function getSize() {
$count = 0; $count = 0;
foreach ($this->_test_cases as $case) { foreach ($this->test_cases as $case) {
if (is_string($case)) { if (is_string($case)) {
if (! SimpleTest::isIgnored($case)) { if (! SimpleTest::isIgnored($case)) {
$count++; $count++;
@ -626,9 +591,8 @@ class TestSuite {
* SimpleTestCase class. * SimpleTestCase class.
* @param string $class Class name. * @param string $class Class name.
* @access public * @access public
* @static
*/ */
function getBaseTestCase($class) { static function getBaseTestCase($class) {
while ($class = get_parent_class($class)) { while ($class = get_parent_class($class)) {
$class = strtolower($class); $class = strtolower($class);
if ($class == 'simpletestcase' || $class == 'testsuite') { if ($class == 'simpletestcase' || $class == 'testsuite') {
@ -639,13 +603,6 @@ class TestSuite {
} }
} }
/**
* @package SimpleTest
* @subpackage UnitTester
* @deprecated
*/
class GroupTest extends TestSuite { }
/** /**
* This is a failing group test for when a test suite hasn't * This is a failing group test for when a test suite hasn't
* loaded properly. * loaded properly.
@ -653,8 +610,8 @@ class GroupTest extends TestSuite { }
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class BadTestSuite { class BadTestSuite {
var $_label; private $label;
var $_error; private $error;
/** /**
* Sets the name of the test suite and error message. * Sets the name of the test suite and error message.
@ -663,8 +620,8 @@ class BadTestSuite {
* @access public * @access public
*/ */
function BadTestSuite($label, $error) { function BadTestSuite($label, $error) {
$this->_label = $label; $this->label = $label;
$this->_error = $error; $this->error = $error;
} }
/** /**
@ -673,7 +630,7 @@ class BadTestSuite {
* @access public * @access public
*/ */
function getLabel() { function getLabel() {
return $this->_label; return $this->label;
} }
/** /**
@ -681,10 +638,10 @@ class BadTestSuite {
* @param SimpleReporter $reporter Current test reporter. * @param SimpleReporter $reporter Current test reporter.
* @access public * @access public
*/ */
function run(&$reporter) { function run($reporter) {
$reporter->paintGroupStart($this->getLabel(), $this->getSize()); $reporter->paintGroupStart($this->getLabel(), $this->getSize());
$reporter->paintFail('Bad TestSuite [' . $this->getLabel() . $reporter->paintFail('Bad TestSuite [' . $this->getLabel() .
'] with error [' . $this->_error . ']'); '] with error [' . $this->error . ']');
$reporter->paintGroupEnd($this->getLabel()); $reporter->paintGroupEnd($this->getLabel());
return $reporter->getStatus(); return $reporter->getStatus();
} }
@ -698,11 +655,4 @@ class BadTestSuite {
return 0; return 0;
} }
} }
/**
* @package SimpleTest
* @subpackage UnitTester
* @deprecated
*/
class BadGroupTest extends BadTestSuite { }
?> ?>

View File

@ -0,0 +1,382 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
* @version $Id: php_parser.php 1911 2009-07-29 16:38:04Z lastcraft $
*/
/**
* Builds the page object.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleTidyPageBuilder {
private $page;
private $forms = array();
private $labels = array();
private $widgets_by_id = array();
public function __destruct() {
$this->free();
}
/**
* Frees up any references so as to allow the PHP garbage
* collection from unset() to work.
*/
private function free() {
unset($this->page);
$this->forms = array();
$this->labels = array();
}
/**
* This builder is only available if the 'tidy' extension is loaded.
* @return boolean True if available.
*/
function can() {
return extension_loaded('tidy');
}
/**
* Reads the raw content the page using HTML Tidy.
* @param $response SimpleHttpResponse Fetched response.
* @return SimplePage Newly parsed page.
*/
function parse($response) {
$this->page = new SimplePage($response);
$tidied = tidy_parse_string($input = $this->insertGuards($response->getContent()),
array('output-xml' => false, 'wrap' => '0', 'indent' => 'no'),
'latin1');
$this->walkTree($tidied->html());
$this->attachLabels($this->widgets_by_id, $this->labels);
$this->page->setForms($this->forms);
$page = $this->page;
$this->free();
return $page;
}
/**
* Stops HTMLTidy stripping content that we wish to preserve.
* @param string The raw html.
* @return string The html with guard tags inserted.
*/
private function insertGuards($html) {
return $this->insertEmptyTagGuards($this->insertTextareaSimpleWhitespaceGuards($html));
}
/**
* Removes the extra content added during the parse stage
* in order to preserve content we don't want stripped
* out by HTMLTidy.
* @param string The raw html.
* @return string The html with guard tags removed.
*/
private function stripGuards($html) {
return $this->stripTextareaWhitespaceGuards($this->stripEmptyTagGuards($html));
}
/**
* HTML tidy strips out empty tags such as <option> which we
* need to preserve. This method inserts an additional marker.
* @param string The raw html.
* @return string The html with guards inserted.
*/
private function insertEmptyTagGuards($html) {
return preg_replace('#<(option|textarea)([^>]*)>(\s*)</(option|textarea)>#is',
'<\1\2>___EMPTY___\3</\4>',
$html);
}
/**
* HTML tidy strips out empty tags such as <option> which we
* need to preserve. This method strips additional markers
* inserted by SimpleTest to the tidy output used to make the
* tags non-empty. This ensures their preservation.
* @param string The raw html.
* @return string The html with guards removed.
*/
private function stripEmptyTagGuards($html) {
return preg_replace('#(^|>)(\s*)___EMPTY___(\s*)(</|$)#i', '\2\3', $html);
}
/**
* By parsing the XML output of tidy, we lose some whitespace
* information in textarea tags. We temporarily recode this
* data ourselves so as not to lose it.
* @param string The raw html.
* @return string The html with guards inserted.
*/
private function insertTextareaSimpleWhitespaceGuards($html) {
return preg_replace_callback('#<textarea([^>]*)>(.*?)</textarea>#is',
array($this, 'insertWhitespaceGuards'),
$html);
}
/**
* Callback for insertTextareaSimpleWhitespaceGuards().
* @param array $matches Result of preg_replace_callback().
* @return string Guard tags now replace whitespace.
*/
private function insertWhitespaceGuards($matches) {
return '<textarea' . $matches[1] . '>' .
str_replace(array("\n", "\r", "\t", ' '),
array('___NEWLINE___', '___CR___', '___TAB___', '___SPACE___'),
$matches[2]) .
'</textarea>';
}
/**
* Removes the whitespace preserving guards we added
* before parsing.
* @param string The raw html.
* @return string The html with guards removed.
*/
private function stripTextareaWhitespaceGuards($html) {
return str_replace(array('___NEWLINE___', '___CR___', '___TAB___', '___SPACE___'),
array("\n", "\r", "\t", ' '),
$html);
}
/**
* Visits the given node and all children
* @param object $node Tidy XML node.
*/
private function walkTree($node) {
if ($node->name == 'a') {
$this->page->addLink($this->tags()->createTag($node->name, (array)$node->attribute)
->addContent($this->innerHtml($node)));
} elseif ($node->name == 'base' and isset($node->attribute['href'])) {
$this->page->setBase($node->attribute['href']);
} elseif ($node->name == 'title') {
$this->page->setTitle($this->tags()->createTag($node->name, (array)$node->attribute)
->addContent($this->innerHtml($node)));
} elseif ($node->name == 'frameset') {
$this->page->setFrames($this->collectFrames($node));
} elseif ($node->name == 'form') {
$this->forms[] = $this->walkForm($node, $this->createEmptyForm($node));
} elseif ($node->name == 'label') {
$this->labels[] = $this->tags()->createTag($node->name, (array)$node->attribute)
->addContent($this->innerHtml($node));
} else {
$this->walkChildren($node);
}
}
/**
* Helper method for traversing the XML tree.
* @param object $node Tidy XML node.
*/
private function walkChildren($node) {
if ($node->hasChildren()) {
foreach ($node->child as $child) {
$this->walkTree($child);
}
}
}
/**
* Facade for forms containing preparsed widgets.
* @param object $node Tidy XML node.
* @return SimpleForm Facade for SimpleBrowser.
*/
private function createEmptyForm($node) {
return new SimpleForm($this->tags()->createTag($node->name, (array)$node->attribute), $this->page);
}
/**
* Visits the given node and all children
* @param object $node Tidy XML node.
*/
private function walkForm($node, $form, $enclosing_label = '') {
if ($node->name == 'a') {
$this->page->addLink($this->tags()->createTag($node->name, (array)$node->attribute)
->addContent($this->innerHtml($node)));
} elseif (in_array($node->name, array('input', 'button', 'textarea', 'select'))) {
$this->addWidgetToForm($node, $form, $enclosing_label);
} elseif ($node->name == 'label') {
$this->labels[] = $this->tags()->createTag($node->name, (array)$node->attribute)
->addContent($this->innerHtml($node));
if ($node->hasChildren()) {
foreach ($node->child as $child) {
$this->walkForm($child, $form, SimplePage::normalise($this->innerHtml($node)));
}
}
} elseif ($node->hasChildren()) {
foreach ($node->child as $child) {
$this->walkForm($child, $form);
}
}
return $form;
}
/**
* Tests a node for a "for" atribute. Used for
* attaching labels.
* @param object $node Tidy XML node.
* @return boolean True if the "for" attribute exists.
*/
private function hasFor($node) {
return isset($node->attribute) and $node->attribute['for'];
}
/**
* Adds the widget into the form container.
* @param object $node Tidy XML node of widget.
* @param SimpleForm $form Form to add it to.
* @param string $enclosing_label The label of any label
* tag we might be in.
*/
private function addWidgetToForm($node, $form, $enclosing_label) {
$widget = $this->tags()->createTag($node->name, $this->attributes($node));
if (! $widget) {
return;
}
$widget->setLabel($enclosing_label)
->addContent($this->innerHtml($node));
if ($node->name == 'select') {
$widget->addTags($this->collectSelectOptions($node));
}
$form->addWidget($widget);
$this->indexWidgetById($widget);
}
/**
* Fills the widget cache to speed up searching.
* @param SimpleTag $widget Parsed widget to cache.
*/
private function indexWidgetById($widget) {
$id = $widget->getAttribute('id');
if (! $id) {
return;
}
if (! isset($this->widgets_by_id[$id])) {
$this->widgets_by_id[$id] = array();
}
$this->widgets_by_id[$id][] = $widget;
}
/**
* Parses the options from inside an XML select node.
* @param object $node Tidy XML node.
* @return array List of SimpleTag options.
*/
private function collectSelectOptions($node) {
$options = array();
if ($node->name == 'option') {
$options[] = $this->tags()->createTag($node->name, $this->attributes($node))
->addContent($this->innerHtml($node));
}
if ($node->hasChildren()) {
foreach ($node->child as $child) {
$options = array_merge($options, $this->collectSelectOptions($child));
}
}
return $options;
}
/**
* Convenience method for collecting all the attributes
* of a tag. Not sure why Tidy does not have this.
* @param object $node Tidy XML node.
* @return array Hash of attribute strings.
*/
private function attributes($node) {
if (! preg_match('|<[^ ]+\s(.*?)/?>|s', $node->value, $first_tag_contents)) {
return array();
}
$attributes = array();
preg_match_all('/\S+\s*=\s*\'[^\']*\'|(\S+\s*=\s*"[^"]*")|([^ =]+\s*=\s*[^ "\']+?)|[^ "\']+/', $first_tag_contents[1], $matches);
foreach($matches[0] as $unparsed) {
$attributes = $this->mergeAttribute($attributes, $unparsed);
}
return $attributes;
}
/**
* Overlay an attribute into the attributes hash.
* @param array $attributes Current attribute list.
* @param string $raw Raw attribute string with
* both key and value.
* @return array New attribute hash.
*/
private function mergeAttribute($attributes, $raw) {
$parts = explode('=', $raw);
list($name, $value) = count($parts) == 1 ? array($parts[0], $parts[0]) : $parts;
$attributes[trim($name)] = html_entity_decode($this->dequote(trim($value)), ENT_QUOTES);
return $attributes;
}
/**
* Remove start and end quotes.
* @param string $quoted A quoted string.
* @return string Quotes are gone.
*/
private function dequote($quoted) {
if (preg_match('/^(\'([^\']*)\'|"([^"]*)")$/', $quoted, $matches)) {
return isset($matches[3]) ? $matches[3] : $matches[2];
}
return $quoted;
}
/**
* Collects frame information inside a frameset tag.
* @param object $node Tidy XML node.
* @return array List of SimpleTag frame descriptions.
*/
private function collectFrames($node) {
$frames = array();
if ($node->name == 'frame') {
$frames = array($this->tags()->createTag($node->name, (array)$node->attribute));
} else if ($node->hasChildren()) {
$frames = array();
foreach ($node->child as $child) {
$frames = array_merge($frames, $this->collectFrames($child));
}
}
return $frames;
}
/**
* Extracts the XML node text.
* @param object $node Tidy XML node.
* @return string The text only.
*/
private function innerHtml($node) {
$raw = '';
if ($node->hasChildren()) {
foreach ($node->child as $child) {
$raw .= $child->value;
}
}
return $this->stripGuards($raw);
}
/**
* Factory for parsed content holders.
* @return SimpleTagBuilder Factory.
*/
private function tags() {
return new SimpleTagBuilder();
}
/**
* Called at the end of a parse run. Attaches any
* non-wrapping labels to their form elements.
* @param array $widgets_by_id Cached SimpleTag hash.
* @param array $labels SimpleTag label elements.
*/
private function attachLabels($widgets_by_id, $labels) {
foreach ($labels as $label) {
$for = $label->getFor();
if ($for and isset($widgets_by_id[$for])) {
$text = $label->getText();
foreach ($widgets_by_id[$for] as $widget) {
$widget->setLabel($text);
}
}
}
}
}
?>

139
contrib/simpletest/simpletest/unit_tester.php Normal file → Executable file
View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: unit_tester.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: unit_tester.php 1882 2009-07-01 14:30:05Z lastcraft $
*/ */
/**#@+ /**#@+
@ -29,11 +29,11 @@ class UnitTestCase extends SimpleTestCase {
* the class name if none specified. * the class name if none specified.
* @access public * @access public
*/ */
function UnitTestCase($label = false) { function __construct($label = false) {
if (! $label) { if (! $label) {
$label = get_class($this); $label = get_class($this);
} }
$this->SimpleTestCase($label); parent::__construct($label);
} }
/** /**
@ -45,7 +45,7 @@ class UnitTestCase extends SimpleTestCase {
* @return boolean True on pass * @return boolean True on pass
* @access public * @access public
*/ */
function assertTrue($result, $message = false) { function assertTrue($result, $message = '%s') {
return $this->assert(new TrueExpectation(), $result, $message); return $this->assert(new TrueExpectation(), $result, $message);
} }
@ -71,7 +71,7 @@ class UnitTestCase extends SimpleTestCase {
* @access public * @access public
*/ */
function assertNull($value, $message = '%s') { function assertNull($value, $message = '%s') {
$dumper = &new SimpleDumper(); $dumper = new SimpleDumper();
$message = sprintf( $message = sprintf(
$message, $message,
'[' . $dumper->describeValue($value) . '] should be null'); '[' . $dumper->describeValue($value) . '] should be null');
@ -86,7 +86,7 @@ class UnitTestCase extends SimpleTestCase {
* @access public * @access public
*/ */
function assertNotNull($value, $message = '%s') { function assertNotNull($value, $message = '%s') {
$dumper = &new SimpleDumper(); $dumper = new SimpleDumper();
$message = sprintf( $message = sprintf(
$message, $message,
'[' . $dumper->describeValue($value) . '] should not be null'); '[' . $dumper->describeValue($value) . '] should not be null');
@ -227,15 +227,18 @@ class UnitTestCase extends SimpleTestCase {
/** /**
* Will trigger a pass if both parameters refer * Will trigger a pass if both parameters refer
* to the same object. Fail otherwise. * to the same object or value. Fail otherwise.
* @param mixed $first Object reference to check. * This will cause problems testing objects under
* @param mixed $second Hopefully the same object. * E_STRICT.
* TODO: Replace with expectation.
* @param mixed $first Reference to check.
* @param mixed $second Hopefully the same variable.
* @param string $message Message to display. * @param string $message Message to display.
* @return boolean True on pass * @return boolean True on pass
* @access public * @access public
*/ */
function assertReference(&$first, &$second, $message = '%s') { function assertReference(&$first, &$second, $message = '%s') {
$dumper = &new SimpleDumper(); $dumper = new SimpleDumper();
$message = sprintf( $message = sprintf(
$message, $message,
'[' . $dumper->describeValue($first) . '[' . $dumper->describeValue($first) .
@ -246,6 +249,29 @@ class UnitTestCase extends SimpleTestCase {
$message); $message);
} }
/**
* Will trigger a pass if both parameters refer
* to the same object. Fail otherwise. This has
* the same semantics at the PHPUnit assertSame.
* That is, if values are passed in it has roughly
* the same affect as assertIdentical.
* TODO: Replace with expectation.
* @param mixed $first Object reference to check.
* @param mixed $second Hopefully the same object.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertSame($first, $second, $message = '%s') {
$dumper = new SimpleDumper();
$message = sprintf(
$message,
'[' . $dumper->describeValue($first) .
'] and [' . $dumper->describeValue($second) .
'] should reference the same object');
return $this->assertTrue($first === $second, $message);
}
/** /**
* Will trigger a pass if both parameters refer * Will trigger a pass if both parameters refer
* to different objects. Fail otherwise. The objects * to different objects. Fail otherwise. The objects
@ -256,25 +282,33 @@ class UnitTestCase extends SimpleTestCase {
* @return boolean True on pass * @return boolean True on pass
* @access public * @access public
*/ */
function assertClone(&$first, &$second, $message = '%s') { function assertClone($first, $second, $message = '%s') {
$dumper = &new SimpleDumper(); $dumper = new SimpleDumper();
$message = sprintf( $message = sprintf(
$message, $message,
'[' . $dumper->describeValue($first) . '[' . $dumper->describeValue($first) .
'] and [' . $dumper->describeValue($second) . '] and [' . $dumper->describeValue($second) .
'] should not be the same object'); '] should not be the same object');
$identical = &new IdenticalExpectation($first); $identical = new IdenticalExpectation($first);
return $this->assertTrue( return $this->assertTrue(
$identical->test($second) && $identical->test($second) && ! ($first === $second),
! SimpleTestCompatibility::isReference($first, $second),
$message); $message);
} }
/** /**
* @deprecated * Will trigger a pass if both parameters refer
* to different variables. Fail otherwise. The objects
* have to be identical references though.
* This will fail under E_STRICT with objects. Use
* assertClone() for this.
* @param mixed $first Object reference to check.
* @param mixed $second Hopefully not the same object.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/ */
function assertCopy(&$first, &$second, $message = "%s") { function assertCopy(&$first, &$second, $message = "%s") {
$dumper = &new SimpleDumper(); $dumper = new SimpleDumper();
$message = sprintf( $message = sprintf(
$message, $message,
"[" . $dumper->describeValue($first) . "[" . $dumper->describeValue($first) .
@ -302,13 +336,6 @@ class UnitTestCase extends SimpleTestCase {
$message); $message);
} }
/**
* @deprecated
*/
function assertWantedPattern($pattern, $subject, $message = '%s') {
return $this->assertPattern($pattern, $subject, $message);
}
/** /**
* Will trigger a pass if the perl regex pattern * Will trigger a pass if the perl regex pattern
* is not present in subject. Fail if found. * is not present in subject. Fail if found.
@ -326,40 +353,6 @@ class UnitTestCase extends SimpleTestCase {
$message); $message);
} }
/**
* @deprecated
*/
function assertNoUnwantedPattern($pattern, $subject, $message = '%s') {
return $this->assertNoPattern($pattern, $subject, $message);
}
/**
* @deprecated
*/
function swallowErrors() {
$context = &SimpleTest::getContext();
$queue = &$context->get('SimpleErrorQueue');
$queue->clear();
}
/**
* @deprecated
*/
function assertNoErrors($message = '%s') {
$context = &SimpleTest::getContext();
$queue = &$context->get('SimpleErrorQueue');
return $queue->assertNoErrors($message);
}
/**
* @deprecated
*/
function assertError($expected = false, $message = '%s') {
$context = &SimpleTest::getContext();
$queue = &$context->get('SimpleErrorQueue');
return $queue->assertError($this->_coerceExpectation($expected), $message);
}
/** /**
* Prepares for an error. If the error mismatches it * Prepares for an error. If the error mismatches it
* passes through, otherwise it is swallowed. Any * passes through, otherwise it is swallowed. Any
@ -369,9 +362,8 @@ class UnitTestCase extends SimpleTestCase {
* @access public * @access public
*/ */
function expectError($expected = false, $message = '%s') { function expectError($expected = false, $message = '%s') {
$context = &SimpleTest::getContext(); $queue = SimpleTest::getContext()->get('SimpleErrorQueue');
$queue = &$context->get('SimpleErrorQueue'); $queue->expectError($this->coerceExpectation($expected), $message);
$queue->expectError($this->_coerceExpectation($expected), $message);
} }
/** /**
@ -383,14 +375,22 @@ class UnitTestCase extends SimpleTestCase {
* @access public * @access public
*/ */
function expectException($expected = false, $message = '%s') { function expectException($expected = false, $message = '%s') {
$context = &SimpleTest::getContext(); $queue = SimpleTest::getContext()->get('SimpleExceptionTrap');
$queue = &$context->get('SimpleExceptionTrap');
// :HACK: Directly substituting in seems to cause a segfault with
// Zend Optimizer on some systems
$line = $this->getAssertionLine(); $line = $this->getAssertionLine();
$queue->expectException($expected, $message . $line); $queue->expectException($expected, $message . $line);
} }
/**
* Tells SimpleTest to ignore an upcoming exception as not relevant
* to the current test. It doesn't affect the test, whether thrown or
* not.
* @param SimpleExpectation/Exception $ignored The error to ignore.
* @access public
*/
function ignoreException($ignored = false) {
SimpleTest::getContext()->get('SimpleExceptionTrap')->ignoreException($ignored);
}
/** /**
* Creates an equality expectation if the * Creates an equality expectation if the
* object/value is not already some type * object/value is not already some type
@ -399,7 +399,7 @@ class UnitTestCase extends SimpleTestCase {
* @return SimpleExpectation Expectation object. * @return SimpleExpectation Expectation object.
* @access private * @access private
*/ */
function _coerceExpectation($expected) { protected function coerceExpectation($expected) {
if ($expected == false) { if ($expected == false) {
return new TrueExpectation(); return new TrueExpectation();
} }
@ -409,12 +409,5 @@ class UnitTestCase extends SimpleTestCase {
return new EqualExpectation( return new EqualExpectation(
is_string($expected) ? str_replace('%', '%%', $expected) : $expected); is_string($expected) ? str_replace('%', '%%', $expected) : $expected);
} }
/**
* @deprecated
*/
function assertErrorPattern($pattern, $message = '%s') {
return $this->assertError(new PatternExpectation($pattern), $message);
}
} }
?> ?>

View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
* @version $Id: url.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: url.php 2011 2011-04-29 08:22:48Z pp11 $
*/ */
/**#@+ /**#@+
@ -23,41 +23,55 @@ require_once(dirname(__FILE__) . '/encoding.php');
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleUrl { class SimpleUrl {
var $_scheme; private $scheme;
var $_username; private $username;
var $_password; private $password;
var $_host; private $host;
var $_port; private $port;
var $_path; public $path;
var $_request; private $request;
var $_fragment; private $fragment;
var $_x; private $x;
var $_y; private $y;
var $_target; private $target;
var $_raw = false; private $raw = false;
/** /**
* Constructor. Parses URL into sections. * Constructor. Parses URL into sections.
* @param string $url Incoming URL. * @param string $url Incoming URL.
* @access public * @access public
*/ */
function SimpleUrl($url = '') { function __construct($url = '') {
list($x, $y) = $this->_chompCoordinates($url); list($x, $y) = $this->chompCoordinates($url);
$this->setCoordinates($x, $y); $this->setCoordinates($x, $y);
$this->_scheme = $this->_chompScheme($url); $this->scheme = $this->chompScheme($url);
list($this->_username, $this->_password) = $this->_chompLogin($url); if ($this->scheme === 'file') {
$this->_host = $this->_chompHost($url); // Unescaped backslashes not used in directory separator context
$this->_port = false; // will get caught by this, but they should have been urlencoded
if (preg_match('/(.*?):(.*)/', $this->_host, $host_parts)) { // anyway so we don't care. If this ends up being a problem, the
$this->_host = $host_parts[1]; // host regexp must be modified to match for backslashes when
$this->_port = (integer)$host_parts[2]; // the scheme is file.
$url = str_replace('\\', '/', $url);
} }
$this->_path = $this->_chompPath($url); list($this->username, $this->password) = $this->chompLogin($url);
$this->_request = $this->_parseRequest($this->_chompRequest($url)); $this->host = $this->chompHost($url);
$this->_fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false); $this->port = false;
$this->_target = false; if (preg_match('/(.*?):(.*)/', $this->host, $host_parts)) {
if ($this->scheme === 'file' && strlen($this->host) === 2) {
// DOS drive was placed in authority; promote it to path.
$url = '/' . $this->host . $url;
$this->host = false;
} else {
$this->host = $host_parts[1];
$this->port = (integer)$host_parts[2];
}
}
$this->path = $this->chompPath($url);
$this->request = $this->parseRequest($this->chompRequest($url));
$this->fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false);
$this->target = false;
} }
/** /**
* Extracts the X, Y coordinate pair from an image map. * Extracts the X, Y coordinate pair from an image map.
* @param string $url URL so far. The coordinates will be * @param string $url URL so far. The coordinates will be
@ -65,14 +79,14 @@ class SimpleUrl {
* @return array X, Y as a pair of integers. * @return array X, Y as a pair of integers.
* @access private * @access private
*/ */
function _chompCoordinates(&$url) { protected function chompCoordinates(&$url) {
if (preg_match('/(.*)\?(\d+),(\d+)$/', $url, $matches)) { if (preg_match('/(.*)\?(\d+),(\d+)$/', $url, $matches)) {
$url = $matches[1]; $url = $matches[1];
return array((integer)$matches[2], (integer)$matches[3]); return array((integer)$matches[2], (integer)$matches[3]);
} }
return array(false, false); return array(false, false);
} }
/** /**
* Extracts the scheme part of an incoming URL. * Extracts the scheme part of an incoming URL.
* @param string $url URL so far. The scheme will be * @param string $url URL so far. The scheme will be
@ -80,14 +94,14 @@ class SimpleUrl {
* @return string Scheme part or false. * @return string Scheme part or false.
* @access private * @access private
*/ */
function _chompScheme(&$url) { protected function chompScheme(&$url) {
if (preg_match('/^([^\/:]*):(\/\/)(.*)/', $url, $matches)) { if (preg_match('#^([^/:]*):(//)(.*)#', $url, $matches)) {
$url = $matches[2] . $matches[3]; $url = $matches[2] . $matches[3];
return $matches[1]; return $matches[1];
} }
return false; return false;
} }
/** /**
* Extracts the username and password from the * Extracts the username and password from the
* incoming URL. The // prefix will be reattached * incoming URL. The // prefix will be reattached
@ -98,13 +112,13 @@ class SimpleUrl {
* password. Will urldecode() them. * password. Will urldecode() them.
* @access private * @access private
*/ */
function _chompLogin(&$url) { protected function chompLogin(&$url) {
$prefix = ''; $prefix = '';
if (preg_match('/^(\/\/)(.*)/', $url, $matches)) { if (preg_match('#^(//)(.*)#', $url, $matches)) {
$prefix = $matches[1]; $prefix = $matches[1];
$url = $matches[2]; $url = $matches[2];
} }
if (preg_match('/^([^\/]*)@(.*)/', $url, $matches)) { if (preg_match('#^([^/]*)@(.*)#', $url, $matches)) {
$url = $prefix . $matches[2]; $url = $prefix . $matches[2];
$parts = explode(":", $matches[1]); $parts = explode(":", $matches[1]);
return array( return array(
@ -114,7 +128,7 @@ class SimpleUrl {
$url = $prefix . $url; $url = $prefix . $url;
return array(false, false); return array(false, false);
} }
/** /**
* Extracts the host part of an incoming URL. * Extracts the host part of an incoming URL.
* Includes the port number part. Will extract * Includes the port number part. Will extract
@ -126,12 +140,12 @@ class SimpleUrl {
* @return string Host part guess or false. * @return string Host part guess or false.
* @access private * @access private
*/ */
function _chompHost(&$url) { protected function chompHost(&$url) {
if (preg_match('/^(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) { if (preg_match('!^(//)(.*?)(/.*|\?.*|#.*|$)!', $url, $matches)) {
$url = $matches[3]; $url = $matches[3];
return $matches[2]; return $matches[2];
} }
if (preg_match('/(.*?)(\.\.\/|\.\/|\/|\?|#|$)(.*)/', $url, $matches)) { if (preg_match('!(.*?)(\.\./|\./|/|\?|#|$)(.*)!', $url, $matches)) {
$tlds = SimpleUrl::getAllTopLevelDomains(); $tlds = SimpleUrl::getAllTopLevelDomains();
if (preg_match('/[a-z0-9\-]+\.(' . $tlds . ')/i', $matches[1])) { if (preg_match('/[a-z0-9\-]+\.(' . $tlds . ')/i', $matches[1])) {
$url = $matches[2] . $matches[3]; $url = $matches[2] . $matches[3];
@ -143,7 +157,7 @@ class SimpleUrl {
} }
return false; return false;
} }
/** /**
* Extracts the path information from the incoming * Extracts the path information from the incoming
* URL. Strips this path from the URL. * URL. Strips this path from the URL.
@ -152,14 +166,14 @@ class SimpleUrl {
* @return string Path part or '/'. * @return string Path part or '/'.
* @access private * @access private
*/ */
function _chompPath(&$url) { protected function chompPath(&$url) {
if (preg_match('/(.*?)(\?|#|$)(.*)/', $url, $matches)) { if (preg_match('/(.*?)(\?|#|$)(.*)/', $url, $matches)) {
$url = $matches[2] . $matches[3]; $url = $matches[2] . $matches[3];
return ($matches[1] ? $matches[1] : ''); return ($matches[1] ? $matches[1] : '');
} }
return ''; return '';
} }
/** /**
* Strips off the request data. * Strips off the request data.
* @param string $url URL so far. The request will be * @param string $url URL so far. The request will be
@ -167,33 +181,33 @@ class SimpleUrl {
* @return string Raw request part. * @return string Raw request part.
* @access private * @access private
*/ */
function _chompRequest(&$url) { protected function chompRequest(&$url) {
if (preg_match('/\?(.*?)(#|$)(.*)/', $url, $matches)) { if (preg_match('/\?(.*?)(#|$)(.*)/', $url, $matches)) {
$url = $matches[2] . $matches[3]; $url = $matches[2] . $matches[3];
return $matches[1]; return $matches[1];
} }
return ''; return '';
} }
/** /**
* Breaks the request down into an object. * Breaks the request down into an object.
* @param string $raw Raw request. * @param string $raw Raw request.
* @return SimpleFormEncoding Parsed data. * @return SimpleFormEncoding Parsed data.
* @access private * @access private
*/ */
function _parseRequest($raw) { protected function parseRequest($raw) {
$this->_raw = $raw; $this->raw = $raw;
$request = new SimpleGetEncoding(); $request = new SimpleGetEncoding();
foreach (explode("&", $raw) as $pair) { foreach (explode("&", $raw) as $pair) {
if (preg_match('/(.*?)=(.*)/', $pair, $matches)) { if (preg_match('/(.*?)=(.*)/', $pair, $matches)) {
$request->add($matches[1], urldecode($matches[2])); $request->add(urldecode($matches[1]), urldecode($matches[2]));
} elseif ($pair) { } elseif ($pair) {
$request->add($pair, ''); $request->add(urldecode($pair), '');
} }
} }
return $request; return $request;
} }
/** /**
* Accessor for protocol part. * Accessor for protocol part.
* @param string $default Value to use if not present. * @param string $default Value to use if not present.
@ -201,27 +215,27 @@ class SimpleUrl {
* @access public * @access public
*/ */
function getScheme($default = false) { function getScheme($default = false) {
return $this->_scheme ? $this->_scheme : $default; return $this->scheme ? $this->scheme : $default;
} }
/** /**
* Accessor for user name. * Accessor for user name.
* @return string Username preceding host. * @return string Username preceding host.
* @access public * @access public
*/ */
function getUsername() { function getUsername() {
return $this->_username; return $this->username;
} }
/** /**
* Accessor for password. * Accessor for password.
* @return string Password preceding host. * @return string Password preceding host.
* @access public * @access public
*/ */
function getPassword() { function getPassword() {
return $this->_password; return $this->password;
} }
/** /**
* Accessor for hostname and port. * Accessor for hostname and port.
* @param string $default Value to use if not present. * @param string $default Value to use if not present.
@ -229,9 +243,9 @@ class SimpleUrl {
* @access public * @access public
*/ */
function getHost($default = false) { function getHost($default = false) {
return $this->_host ? $this->_host : $default; return $this->host ? $this->host : $default;
} }
/** /**
* Accessor for top level domain. * Accessor for top level domain.
* @return string Last part of host. * @return string Last part of host.
@ -241,28 +255,28 @@ class SimpleUrl {
$path_parts = pathinfo($this->getHost()); $path_parts = pathinfo($this->getHost());
return (isset($path_parts['extension']) ? $path_parts['extension'] : false); return (isset($path_parts['extension']) ? $path_parts['extension'] : false);
} }
/** /**
* Accessor for port number. * Accessor for port number.
* @return integer TCP/IP port number. * @return integer TCP/IP port number.
* @access public * @access public
*/ */
function getPort() { function getPort() {
return $this->_port; return $this->port;
} }
/** /**
* Accessor for path. * Accessor for path.
* @return string Full path including leading slash if implied. * @return string Full path including leading slash if implied.
* @access public * @access public
*/ */
function getPath() { function getPath() {
if (! $this->_path && $this->_host) { if (! $this->path && $this->host) {
return '/'; return '/';
} }
return $this->_path; return $this->path;
} }
/** /**
* Accessor for page if any. This may be a * Accessor for page if any. This may be a
* directory name if ambiguious. * directory name if ambiguious.
@ -275,7 +289,7 @@ class SimpleUrl {
} }
return $matches[1]; return $matches[1];
} }
/** /**
* Gets the path to the page. * Gets the path to the page.
* @return string Path less the page. * @return string Path less the page.
@ -287,16 +301,16 @@ class SimpleUrl {
} }
return $matches[1]; return $matches[1];
} }
/** /**
* Accessor for fragment at end of URL after the "#". * Accessor for fragment at end of URL after the "#".
* @return string Part after "#". * @return string Part after "#".
* @access public * @access public
*/ */
function getFragment() { function getFragment() {
return $this->_fragment; return $this->fragment;
} }
/** /**
* Sets image coordinates. Set to false to clear * Sets image coordinates. Set to false to clear
* them. * them.
@ -306,31 +320,31 @@ class SimpleUrl {
*/ */
function setCoordinates($x = false, $y = false) { function setCoordinates($x = false, $y = false) {
if (($x === false) || ($y === false)) { if (($x === false) || ($y === false)) {
$this->_x = $this->_y = false; $this->x = $this->y = false;
return; return;
} }
$this->_x = (integer)$x; $this->x = (integer)$x;
$this->_y = (integer)$y; $this->y = (integer)$y;
} }
/** /**
* Accessor for horizontal image coordinate. * Accessor for horizontal image coordinate.
* @return integer X value. * @return integer X value.
* @access public * @access public
*/ */
function getX() { function getX() {
return $this->_x; return $this->x;
} }
/** /**
* Accessor for vertical image coordinate. * Accessor for vertical image coordinate.
* @return integer Y value. * @return integer Y value.
* @access public * @access public
*/ */
function getY() { function getY() {
return $this->_y; return $this->y;
} }
/** /**
* Accessor for current request parameters * Accessor for current request parameters
* in URL string form. Will return teh original request * in URL string form. Will return teh original request
@ -340,17 +354,17 @@ class SimpleUrl {
* @access public * @access public
*/ */
function getEncodedRequest() { function getEncodedRequest() {
if ($this->_raw) { if ($this->raw) {
$encoded = $this->_raw; $encoded = $this->raw;
} else { } else {
$encoded = $this->_request->asUrlRequest(); $encoded = $this->request->asUrlRequest();
} }
if ($encoded) { if ($encoded) {
return '?' . preg_replace('/^\?/', '', $encoded); return '?' . preg_replace('/^\?/', '', $encoded);
} }
return ''; return '';
} }
/** /**
* Adds an additional parameter to the request. * Adds an additional parameter to the request.
* @param string $key Name of parameter. * @param string $key Name of parameter.
@ -358,10 +372,10 @@ class SimpleUrl {
* @access public * @access public
*/ */
function addRequestParameter($key, $value) { function addRequestParameter($key, $value) {
$this->_raw = false; $this->raw = false;
$this->_request->add($key, $value); $this->request->add($key, $value);
} }
/** /**
* Adds additional parameters to the request. * Adds additional parameters to the request.
* @param hash/SimpleFormEncoding $parameters Additional * @param hash/SimpleFormEncoding $parameters Additional
@ -369,19 +383,19 @@ class SimpleUrl {
* @access public * @access public
*/ */
function addRequestParameters($parameters) { function addRequestParameters($parameters) {
$this->_raw = false; $this->raw = false;
$this->_request->merge($parameters); $this->request->merge($parameters);
} }
/** /**
* Clears down all parameters. * Clears down all parameters.
* @access public * @access public
*/ */
function clearRequest() { function clearRequest() {
$this->_raw = false; $this->raw = false;
$this->_request = &new SimpleGetEncoding(); $this->request = new SimpleGetEncoding();
} }
/** /**
* Gets the frame target if present. Although * Gets the frame target if present. Although
* not strictly part of the URL specification it * not strictly part of the URL specification it
@ -390,44 +404,53 @@ class SimpleUrl {
* @access public * @access public
*/ */
function getTarget() { function getTarget() {
return $this->_target; return $this->target;
} }
/** /**
* Attaches a frame target. * Attaches a frame target.
* @param string $frame Name of frame. * @param string $frame Name of frame.
* @access public * @access public
*/ */
function setTarget($frame) { function setTarget($frame) {
$this->_raw = false; $this->raw = false;
$this->_target = $frame; $this->target = $frame;
} }
/** /**
* Renders the URL back into a string. * Renders the URL back into a string.
* @return string URL in canonical form. * @return string URL in canonical form.
* @access public * @access public
*/ */
function asString() { function asString() {
$path = $this->_path; $path = $this->path;
$scheme = $identity = $host = $encoded = $fragment = ''; $scheme = $identity = $host = $port = $encoded = $fragment = '';
if ($this->_username && $this->_password) { if ($this->username && $this->password) {
$identity = $this->_username . ':' . $this->_password . '@'; $identity = $this->username . ':' . $this->password . '@';
} }
if ($this->getHost()) { if ($this->getHost()) {
$scheme = $this->getScheme() ? $this->getScheme() : 'http'; $scheme = $this->getScheme() ? $this->getScheme() : 'http';
$scheme .= "://"; $scheme .= '://';
$host = $this->getHost(); $host = $this->getHost();
} elseif ($this->getScheme() === 'file') {
// Safest way; otherwise, file URLs on Windows have an extra
// leading slash. It might be possible to convert file://
// URIs to local file paths, but that requires more research.
$scheme = 'file://';
} }
if (substr($this->_path, 0, 1) == '/') { if ($this->getPort() && $this->getPort() != 80 ) {
$path = $this->normalisePath($this->_path); $port = ':'.$this->getPort();
}
if (substr($this->path, 0, 1) == '/') {
$path = $this->normalisePath($this->path);
} }
$encoded = $this->getEncodedRequest(); $encoded = $this->getEncodedRequest();
$fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; $fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
$coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
return "$scheme$identity$host$path$encoded$fragment$coords"; return "$scheme$identity$host$port$path$encoded$fragment$coords";
} }
/** /**
* Replaces unknown sections to turn a relative * Replaces unknown sections to turn a relative
* URL into an absolute one. The base URL can * URL into an absolute one. The base URL can
@ -453,13 +476,13 @@ class SimpleUrl {
$port = $base->getPort() ? ':' . $base->getPort() : ''; $port = $base->getPort() ? ':' . $base->getPort() : '';
$identity = $base->getIdentity() ? $base->getIdentity() . '@' : ''; $identity = $base->getIdentity() ? $base->getIdentity() . '@' : '';
} }
$path = $this->normalisePath($this->_extractAbsolutePath($base)); $path = $this->normalisePath($this->extractAbsolutePath($base));
$encoded = $this->getEncodedRequest(); $encoded = $this->getEncodedRequest();
$fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; $fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
$coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords"); return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords");
} }
/** /**
* Replaces unknown sections of the path with base parts * Replaces unknown sections of the path with base parts
* to return a complete absolute one. * to return a complete absolute one.
@ -467,29 +490,29 @@ class SimpleUrl {
* @param string Absolute path. * @param string Absolute path.
* @access private * @access private
*/ */
function _extractAbsolutePath($base) { protected function extractAbsolutePath($base) {
if ($this->getHost()) { if ($this->getHost()) {
return $this->_path; return $this->path;
} }
if (! $this->_isRelativePath($this->_path)) { if (! $this->isRelativePath($this->path)) {
return $this->_path; return $this->path;
} }
if ($this->_path) { if ($this->path) {
return $base->getBasePath() . $this->_path; return $base->getBasePath() . $this->path;
} }
return $base->getPath(); return $base->getPath();
} }
/** /**
* Simple test to see if a path part is relative. * Simple test to see if a path part is relative.
* @param string $path Path to test. * @param string $path Path to test.
* @return boolean True if starts with a "/". * @return boolean True if starts with a "/".
* @access private * @access private
*/ */
function _isRelativePath($path) { protected function isRelativePath($path) {
return (substr($path, 0, 1) != '/'); return (substr($path, 0, 1) != '/');
} }
/** /**
* Extracts the username and password for use in rendering * Extracts the username and password for use in rendering
* a URL. * a URL.
@ -497,12 +520,12 @@ class SimpleUrl {
* @access public * @access public
*/ */
function getIdentity() { function getIdentity() {
if ($this->_username && $this->_password) { if ($this->username && $this->password) {
return $this->_username . ':' . $this->_password; return $this->username . ':' . $this->password;
} }
return false; return false;
} }
/** /**
* Replaces . and .. sections of the path. * Replaces . and .. sections of the path.
* @param string $path Unoptimised path. * @param string $path Unoptimised path.
@ -513,16 +536,15 @@ class SimpleUrl {
$path = preg_replace('|/\./|', '/', $path); $path = preg_replace('|/\./|', '/', $path);
return preg_replace('|/[^/]+/\.\./|', '/', $path); return preg_replace('|/[^/]+/\.\./|', '/', $path);
} }
/** /**
* A pipe seperated list of all TLDs that result in two part * A pipe seperated list of all TLDs that result in two part
* domain names. * domain names.
* @return string Pipe separated list. * @return string Pipe separated list.
* @access public * @access public
* @static
*/ */
function getAllTopLevelDomains() { static function getAllTopLevelDomains() {
return 'com|edu|net|org|gov|mil|int|biz|info|name|pro|aero|coop|museum'; return 'com|edu|net|org|gov|mil|int|biz|info|name|pro|aero|coop|museum';
} }
} }
?> ?>

View File

@ -3,7 +3,7 @@
* Base include file for SimpleTest * Base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
* @version $Id: user_agent.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: user_agent.php 2039 2011-11-30 18:16:15Z pp11 $
*/ */
/**#@+ /**#@+
@ -29,25 +29,25 @@ if (! defined('DEFAULT_CONNECTION_TIMEOUT')) {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleUserAgent { class SimpleUserAgent {
var $_cookie_jar; private $cookie_jar;
var $_cookies_enabled = true; private $cookies_enabled = true;
var $_authenticator; private $authenticator;
var $_max_redirects = DEFAULT_MAX_REDIRECTS; private $max_redirects = DEFAULT_MAX_REDIRECTS;
var $_proxy = false; private $proxy = false;
var $_proxy_username = false; private $proxy_username = false;
var $_proxy_password = false; private $proxy_password = false;
var $_connection_timeout = DEFAULT_CONNECTION_TIMEOUT; private $connection_timeout = DEFAULT_CONNECTION_TIMEOUT;
var $_additional_headers = array(); private $additional_headers = array();
/** /**
* Starts with no cookies, realms or proxies. * Starts with no cookies, realms or proxies.
* @access public * @access public
*/ */
function SimpleUserAgent() { function __construct() {
$this->_cookie_jar = &new SimpleCookieJar(); $this->cookie_jar = new SimpleCookieJar();
$this->_authenticator = &new SimpleAuthenticator(); $this->authenticator = new SimpleAuthenticator();
} }
/** /**
* Removes expired and temporary cookies as if * Removes expired and temporary cookies as if
* the browser was closed and re-opened. Authorisation * the browser was closed and re-opened. Authorisation
@ -58,10 +58,10 @@ class SimpleUserAgent {
* @access public * @access public
*/ */
function restart($date = false) { function restart($date = false) {
$this->_cookie_jar->restartSession($date); $this->cookie_jar->restartSession($date);
$this->_authenticator->restartSession(); $this->authenticator->restartSession();
} }
/** /**
* Adds a header to every fetch. * Adds a header to every fetch.
* @param string $header Header line to add to every * @param string $header Header line to add to every
@ -69,18 +69,18 @@ class SimpleUserAgent {
* @access public * @access public
*/ */
function addHeader($header) { function addHeader($header) {
$this->_additional_headers[] = $header; $this->additional_headers[] = $header;
} }
/** /**
* Ages the cookies by the specified time. * Ages the cookies by the specified time.
* @param integer $interval Amount in seconds. * @param integer $interval Amount in seconds.
* @access public * @access public
*/ */
function ageCookies($interval) { function ageCookies($interval) {
$this->_cookie_jar->agePrematurely($interval); $this->cookie_jar->agePrematurely($interval);
} }
/** /**
* Sets an additional cookie. If a cookie has * Sets an additional cookie. If a cookie has
* the same name and path it is replaced. * the same name and path it is replaced.
@ -92,9 +92,9 @@ class SimpleUserAgent {
* @access public * @access public
*/ */
function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { function setCookie($name, $value, $host = false, $path = '/', $expiry = false) {
$this->_cookie_jar->setCookie($name, $value, $host, $path, $expiry); $this->cookie_jar->setCookie($name, $value, $host, $path, $expiry);
} }
/** /**
* Reads the most specific cookie value from the * Reads the most specific cookie value from the
* browser cookies. * browser cookies.
@ -106,9 +106,9 @@ class SimpleUserAgent {
* @access public * @access public
*/ */
function getCookieValue($host, $path, $name) { function getCookieValue($host, $path, $name) {
return $this->_cookie_jar->getCookieValue($host, $path, $name); return $this->cookie_jar->getCookieValue($host, $path, $name);
} }
/** /**
* Reads the current cookies within the base URL. * Reads the current cookies within the base URL.
* @param string $name Key of cookie to find. * @param string $name Key of cookie to find.
@ -123,32 +123,32 @@ class SimpleUserAgent {
} }
return $this->getCookieValue($base->getHost(), $base->getPath(), $name); return $this->getCookieValue($base->getHost(), $base->getPath(), $name);
} }
/** /**
* Switches off cookie sending and recieving. * Switches off cookie sending and recieving.
* @access public * @access public
*/ */
function ignoreCookies() { function ignoreCookies() {
$this->_cookies_enabled = false; $this->cookies_enabled = false;
} }
/** /**
* Switches back on the cookie sending and recieving. * Switches back on the cookie sending and recieving.
* @access public * @access public
*/ */
function useCookies() { function useCookies() {
$this->_cookies_enabled = true; $this->cookies_enabled = true;
} }
/** /**
* Sets the socket timeout for opening a connection. * Sets the socket timeout for opening a connection.
* @param integer $timeout Maximum time in seconds. * @param integer $timeout Maximum time in seconds.
* @access public * @access public
*/ */
function setConnectionTimeout($timeout) { function setConnectionTimeout($timeout) {
$this->_connection_timeout = $timeout; $this->connection_timeout = $timeout;
} }
/** /**
* Sets the maximum number of redirects before * Sets the maximum number of redirects before
* a page will be loaded anyway. * a page will be loaded anyway.
@ -156,9 +156,9 @@ class SimpleUserAgent {
* @access public * @access public
*/ */
function setMaximumRedirects($max) { function setMaximumRedirects($max) {
$this->_max_redirects = $max; $this->max_redirects = $max;
} }
/** /**
* Sets proxy to use on all requests for when * Sets proxy to use on all requests for when
* testing from behind a firewall. Set URL * testing from behind a firewall. Set URL
@ -170,27 +170,27 @@ class SimpleUserAgent {
*/ */
function useProxy($proxy, $username, $password) { function useProxy($proxy, $username, $password) {
if (! $proxy) { if (! $proxy) {
$this->_proxy = false; $this->proxy = false;
return; return;
} }
if ((strncmp($proxy, 'http://', 7) != 0) && (strncmp($proxy, 'https://', 8) != 0)) { if ((strncmp($proxy, 'http://', 7) != 0) && (strncmp($proxy, 'https://', 8) != 0)) {
$proxy = 'http://'. $proxy; $proxy = 'http://'. $proxy;
} }
$this->_proxy = &new SimpleUrl($proxy); $this->proxy = new SimpleUrl($proxy);
$this->_proxy_username = $username; $this->proxy_username = $username;
$this->_proxy_password = $password; $this->proxy_password = $password;
} }
/** /**
* Test to see if the redirect limit is passed. * Test to see if the redirect limit is passed.
* @param integer $redirects Count so far. * @param integer $redirects Count so far.
* @return boolean True if over. * @return boolean True if over.
* @access private * @access private
*/ */
function _isTooManyRedirects($redirects) { protected function isTooManyRedirects($redirects) {
return ($redirects > $this->_max_redirects); return ($redirects > $this->max_redirects);
} }
/** /**
* Sets the identity for the current realm. * Sets the identity for the current realm.
* @param string $host Host to which realm applies. * @param string $host Host to which realm applies.
@ -200,9 +200,9 @@ class SimpleUserAgent {
* @access public * @access public
*/ */
function setIdentity($host, $realm, $username, $password) { function setIdentity($host, $realm, $username, $password) {
$this->_authenticator->setIdentityForRealm($host, $realm, $username, $password); $this->authenticator->setIdentityForRealm($host, $realm, $username, $password);
} }
/** /**
* Fetches a URL as a response object. Will keep trying if redirected. * Fetches a URL as a response object. Will keep trying if redirected.
* It will also collect authentication realm information. * It will also collect authentication realm information.
@ -211,15 +211,15 @@ class SimpleUserAgent {
* @return SimpleHttpResponse Hopefully the target page. * @return SimpleHttpResponse Hopefully the target page.
* @access public * @access public
*/ */
function &fetchResponse($url, $encoding) { function fetchResponse($url, $encoding) {
if ($encoding->getMethod() != 'POST') { if ($encoding->getMethod() != 'POST') {
$url->addRequestParameters($encoding); $url->addRequestParameters($encoding);
$encoding->clear(); $encoding->clear();
} }
$response = &$this->_fetchWhileRedirected($url, $encoding); $response = $this->fetchWhileRedirected($url, $encoding);
if ($headers = $response->getHeaders()) { if ($headers = $response->getHeaders()) {
if ($headers->isChallenge()) { if ($headers->isChallenge()) {
$this->_authenticator->addRealm( $this->authenticator->addRealm(
$url, $url,
$headers->getAuthentication(), $headers->getAuthentication(),
$headers->getRealm()); $headers->getRealm());
@ -227,7 +227,7 @@ class SimpleUserAgent {
} }
return $response; return $response;
} }
/** /**
* Fetches the page until no longer redirected or * Fetches the page until no longer redirected or
* until the redirect limit runs out. * until the redirect limit runs out.
@ -236,27 +236,27 @@ class SimpleUserAgent {
* @return SimpleHttpResponse Hopefully the target page. * @return SimpleHttpResponse Hopefully the target page.
* @access private * @access private
*/ */
function &_fetchWhileRedirected($url, $encoding) { protected function fetchWhileRedirected($url, $encoding) {
$redirects = 0; $redirects = 0;
do { do {
$response = &$this->_fetch($url, $encoding); $response = $this->fetch($url, $encoding);
if ($response->isError()) { if ($response->isError()) {
return $response; return $response;
} }
$headers = $response->getHeaders(); $headers = $response->getHeaders();
$location = new SimpleUrl($headers->getLocation()); if ($this->cookies_enabled) {
$url = $location->makeAbsolute($url); $headers->writeCookiesToJar($this->cookie_jar, $url);
if ($this->_cookies_enabled) {
$headers->writeCookiesToJar($this->_cookie_jar, $url);
} }
if (! $headers->isRedirect()) { if (! $headers->isRedirect()) {
break; break;
} }
$location = new SimpleUrl($headers->getLocation());
$url = $location->makeAbsolute($url);
$encoding = new SimpleGetEncoding(); $encoding = new SimpleGetEncoding();
} while (! $this->_isTooManyRedirects(++$redirects)); } while (! $this->isTooManyRedirects(++$redirects));
return $response; return $response;
} }
/** /**
* Actually make the web request. * Actually make the web request.
* @param SimpleUrl $url Target to fetch. * @param SimpleUrl $url Target to fetch.
@ -264,12 +264,11 @@ class SimpleUserAgent {
* @return SimpleHttpResponse Headers and hopefully content. * @return SimpleHttpResponse Headers and hopefully content.
* @access protected * @access protected
*/ */
function &_fetch($url, $encoding) { protected function fetch($url, $encoding) {
$request = &$this->_createRequest($url, $encoding); $request = $this->createRequest($url, $encoding);
$response = &$request->fetch($this->_connection_timeout); return $request->fetch($this->connection_timeout);
return $response;
} }
/** /**
* Creates a full page request. * Creates a full page request.
* @param SimpleUrl $url Target to fetch as url object. * @param SimpleUrl $url Target to fetch as url object.
@ -277,16 +276,16 @@ class SimpleUserAgent {
* @return SimpleHttpRequest New request. * @return SimpleHttpRequest New request.
* @access private * @access private
*/ */
function &_createRequest($url, $encoding) { protected function createRequest($url, $encoding) {
$request = &$this->_createHttpRequest($url, $encoding); $request = $this->createHttpRequest($url, $encoding);
$this->_addAdditionalHeaders($request); $this->addAdditionalHeaders($request);
if ($this->_cookies_enabled) { if ($this->cookies_enabled) {
$request->readCookiesFromJar($this->_cookie_jar, $url); $request->readCookiesFromJar($this->cookie_jar, $url);
} }
$this->_authenticator->addHeaders($request, $url); $this->authenticator->addHeaders($request, $url);
return $request; return $request;
} }
/** /**
* Builds the appropriate HTTP request object. * Builds the appropriate HTTP request object.
* @param SimpleUrl $url Target to fetch as url object. * @param SimpleUrl $url Target to fetch as url object.
@ -294,37 +293,34 @@ class SimpleUserAgent {
* @return SimpleHttpRequest New request object. * @return SimpleHttpRequest New request object.
* @access protected * @access protected
*/ */
function &_createHttpRequest($url, $encoding) { protected function createHttpRequest($url, $encoding) {
$request = &new SimpleHttpRequest($this->_createRoute($url), $encoding); return new SimpleHttpRequest($this->createRoute($url), $encoding);
return $request;
} }
/** /**
* Sets up either a direct route or via a proxy. * Sets up either a direct route or via a proxy.
* @param SimpleUrl $url Target to fetch as url object. * @param SimpleUrl $url Target to fetch as url object.
* @return SimpleRoute Route to take to fetch URL. * @return SimpleRoute Route to take to fetch URL.
* @access protected * @access protected
*/ */
function &_createRoute($url) { protected function createRoute($url) {
if ($this->_proxy) { if ($this->proxy) {
$route = &new SimpleProxyRoute( return new SimpleProxyRoute(
$url, $url,
$this->_proxy, $this->proxy,
$this->_proxy_username, $this->proxy_username,
$this->_proxy_password); $this->proxy_password);
} else {
$route = &new SimpleRoute($url);
} }
return $route; return new SimpleRoute($url);
} }
/** /**
* Adds additional manual headers. * Adds additional manual headers.
* @param SimpleHttpRequest $request Outgoing request. * @param SimpleHttpRequest $request Outgoing request.
* @access private * @access private
*/ */
function _addAdditionalHeaders(&$request) { protected function addAdditionalHeaders(&$request) {
foreach ($this->_additional_headers as $header) { foreach ($this->additional_headers as $header) {
$request->addHeaderLine($header); $request->addHeaderLine($header);
} }
} }

File diff suppressed because it is too large Load Diff

242
contrib/simpletest/simpletest/xml.php Normal file → Executable file
View File

@ -3,7 +3,7 @@
* base include file for SimpleTest * base include file for SimpleTest
* @package SimpleTest * @package SimpleTest
* @subpackage UnitTester * @subpackage UnitTester
* @version $Id: xml.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: xml.php 1787 2008-04-26 20:35:39Z pp11 $
*/ */
/**#@+ /**#@+
@ -19,8 +19,8 @@ require_once(dirname(__FILE__) . '/scorer.php');
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class XmlReporter extends SimpleReporter { class XmlReporter extends SimpleReporter {
var $_indent; private $indent;
var $_namespace; private $namespace;
/** /**
* Sets up indentation and namespace. * Sets up indentation and namespace.
@ -28,10 +28,10 @@ class XmlReporter extends SimpleReporter {
* @param string $indent Indenting to add on each nesting. * @param string $indent Indenting to add on each nesting.
* @access public * @access public
*/ */
function XmlReporter($namespace = false, $indent = ' ') { function __construct($namespace = false, $indent = ' ') {
$this->SimpleReporter(); parent::__construct();
$this->_namespace = ($namespace ? $namespace . ':' : ''); $this->namespace = ($namespace ? $namespace . ':' : '');
$this->_indent = $indent; $this->indent = $indent;
} }
/** /**
@ -41,9 +41,9 @@ class XmlReporter extends SimpleReporter {
* @return string Leading space. * @return string Leading space.
* @access protected * @access protected
*/ */
function _getIndent($offset = 0) { protected function getIndent($offset = 0) {
return str_repeat( return str_repeat(
$this->_indent, $this->indent,
count($this->getTestList()) + $offset); count($this->getTestList()) + $offset);
} }
@ -69,12 +69,12 @@ class XmlReporter extends SimpleReporter {
*/ */
function paintGroupStart($test_name, $size) { function paintGroupStart($test_name, $size) {
parent::paintGroupStart($test_name, $size); parent::paintGroupStart($test_name, $size);
print $this->_getIndent(); print $this->getIndent();
print "<" . $this->_namespace . "group size=\"$size\">\n"; print "<" . $this->namespace . "group size=\"$size\">\n";
print $this->_getIndent(1); print $this->getIndent(1);
print "<" . $this->_namespace . "name>" . print "<" . $this->namespace . "name>" .
$this->toParsedXml($test_name) . $this->toParsedXml($test_name) .
"</" . $this->_namespace . "name>\n"; "</" . $this->namespace . "name>\n";
} }
/** /**
@ -83,8 +83,8 @@ class XmlReporter extends SimpleReporter {
* @access public * @access public
*/ */
function paintGroupEnd($test_name) { function paintGroupEnd($test_name) {
print $this->_getIndent(); print $this->getIndent();
print "</" . $this->_namespace . "group>\n"; print "</" . $this->namespace . "group>\n";
parent::paintGroupEnd($test_name); parent::paintGroupEnd($test_name);
} }
@ -95,12 +95,12 @@ class XmlReporter extends SimpleReporter {
*/ */
function paintCaseStart($test_name) { function paintCaseStart($test_name) {
parent::paintCaseStart($test_name); parent::paintCaseStart($test_name);
print $this->_getIndent(); print $this->getIndent();
print "<" . $this->_namespace . "case>\n"; print "<" . $this->namespace . "case>\n";
print $this->_getIndent(1); print $this->getIndent(1);
print "<" . $this->_namespace . "name>" . print "<" . $this->namespace . "name>" .
$this->toParsedXml($test_name) . $this->toParsedXml($test_name) .
"</" . $this->_namespace . "name>\n"; "</" . $this->namespace . "name>\n";
} }
/** /**
@ -109,8 +109,8 @@ class XmlReporter extends SimpleReporter {
* @access public * @access public
*/ */
function paintCaseEnd($test_name) { function paintCaseEnd($test_name) {
print $this->_getIndent(); print $this->getIndent();
print "</" . $this->_namespace . "case>\n"; print "</" . $this->namespace . "case>\n";
parent::paintCaseEnd($test_name); parent::paintCaseEnd($test_name);
} }
@ -121,12 +121,12 @@ class XmlReporter extends SimpleReporter {
*/ */
function paintMethodStart($test_name) { function paintMethodStart($test_name) {
parent::paintMethodStart($test_name); parent::paintMethodStart($test_name);
print $this->_getIndent(); print $this->getIndent();
print "<" . $this->_namespace . "test>\n"; print "<" . $this->namespace . "test>\n";
print $this->_getIndent(1); print $this->getIndent(1);
print "<" . $this->_namespace . "name>" . print "<" . $this->namespace . "name>" .
$this->toParsedXml($test_name) . $this->toParsedXml($test_name) .
"</" . $this->_namespace . "name>\n"; "</" . $this->namespace . "name>\n";
} }
/** /**
@ -136,8 +136,8 @@ class XmlReporter extends SimpleReporter {
* @access public * @access public
*/ */
function paintMethodEnd($test_name) { function paintMethodEnd($test_name) {
print $this->_getIndent(); print $this->getIndent();
print "</" . $this->_namespace . "test>\n"; print "</" . $this->namespace . "test>\n";
parent::paintMethodEnd($test_name); parent::paintMethodEnd($test_name);
} }
@ -148,10 +148,10 @@ class XmlReporter extends SimpleReporter {
*/ */
function paintPass($message) { function paintPass($message) {
parent::paintPass($message); parent::paintPass($message);
print $this->_getIndent(1); print $this->getIndent(1);
print "<" . $this->_namespace . "pass>"; print "<" . $this->namespace . "pass>";
print $this->toParsedXml($message); print $this->toParsedXml($message);
print "</" . $this->_namespace . "pass>\n"; print "</" . $this->namespace . "pass>\n";
} }
/** /**
@ -161,10 +161,10 @@ class XmlReporter extends SimpleReporter {
*/ */
function paintFail($message) { function paintFail($message) {
parent::paintFail($message); parent::paintFail($message);
print $this->_getIndent(1); print $this->getIndent(1);
print "<" . $this->_namespace . "fail>"; print "<" . $this->namespace . "fail>";
print $this->toParsedXml($message); print $this->toParsedXml($message);
print "</" . $this->_namespace . "fail>\n"; print "</" . $this->namespace . "fail>\n";
} }
/** /**
@ -174,10 +174,10 @@ class XmlReporter extends SimpleReporter {
*/ */
function paintError($message) { function paintError($message) {
parent::paintError($message); parent::paintError($message);
print $this->_getIndent(1); print $this->getIndent(1);
print "<" . $this->_namespace . "exception>"; print "<" . $this->namespace . "exception>";
print $this->toParsedXml($message); print $this->toParsedXml($message);
print "</" . $this->_namespace . "exception>\n"; print "</" . $this->namespace . "exception>\n";
} }
/** /**
@ -187,14 +187,14 @@ class XmlReporter extends SimpleReporter {
*/ */
function paintException($exception) { function paintException($exception) {
parent::paintException($exception); parent::paintException($exception);
print $this->_getIndent(1); print $this->getIndent(1);
print "<" . $this->_namespace . "exception>"; print "<" . $this->namespace . "exception>";
$message = 'Unexpected exception of type [' . get_class($exception) . $message = 'Unexpected exception of type [' . get_class($exception) .
'] with message ['. $exception->getMessage() . '] with message ['. $exception->getMessage() .
'] in ['. $exception->getFile() . '] in ['. $exception->getFile() .
' line ' . $exception->getLine() . ']'; ' line ' . $exception->getLine() . ']';
print $this->toParsedXml($message); print $this->toParsedXml($message);
print "</" . $this->_namespace . "exception>\n"; print "</" . $this->namespace . "exception>\n";
} }
/** /**
@ -204,10 +204,10 @@ class XmlReporter extends SimpleReporter {
*/ */
function paintSkip($message) { function paintSkip($message) {
parent::paintSkip($message); parent::paintSkip($message);
print $this->_getIndent(1); print $this->getIndent(1);
print "<" . $this->_namespace . "skip>"; print "<" . $this->namespace . "skip>";
print $this->toParsedXml($message); print $this->toParsedXml($message);
print "</" . $this->_namespace . "skip>\n"; print "</" . $this->namespace . "skip>\n";
} }
/** /**
@ -217,24 +217,24 @@ class XmlReporter extends SimpleReporter {
*/ */
function paintMessage($message) { function paintMessage($message) {
parent::paintMessage($message); parent::paintMessage($message);
print $this->_getIndent(1); print $this->getIndent(1);
print "<" . $this->_namespace . "message>"; print "<" . $this->namespace . "message>";
print $this->toParsedXml($message); print $this->toParsedXml($message);
print "</" . $this->_namespace . "message>\n"; print "</" . $this->namespace . "message>\n";
} }
/** /**
* Paints a formatted ASCII message such as a * Paints a formatted ASCII message such as a
* variable dump. * privateiable dump.
* @param string $message Text to display. * @param string $message Text to display.
* @access public * @access public
*/ */
function paintFormattedMessage($message) { function paintFormattedMessage($message) {
parent::paintFormattedMessage($message); parent::paintFormattedMessage($message);
print $this->_getIndent(1); print $this->getIndent(1);
print "<" . $this->_namespace . "formatted>"; print "<" . $this->namespace . "formatted>";
print "<![CDATA[$message]]>"; print "<![CDATA[$message]]>";
print "</" . $this->_namespace . "formatted>\n"; print "</" . $this->namespace . "formatted>\n";
} }
/** /**
@ -245,10 +245,10 @@ class XmlReporter extends SimpleReporter {
*/ */
function paintSignal($type, $payload) { function paintSignal($type, $payload) {
parent::paintSignal($type, $payload); parent::paintSignal($type, $payload);
print $this->_getIndent(1); print $this->getIndent(1);
print "<" . $this->_namespace . "signal type=\"$type\">"; print "<" . $this->namespace . "signal type=\"$type\">";
print "<![CDATA[" . serialize($payload) . "]]>"; print "<![CDATA[" . serialize($payload) . "]]>";
print "</" . $this->_namespace . "signal>\n"; print "</" . $this->namespace . "signal>\n";
} }
/** /**
@ -263,12 +263,12 @@ class XmlReporter extends SimpleReporter {
header('Content-type: text/xml'); header('Content-type: text/xml');
} }
print "<?xml version=\"1.0\""; print "<?xml version=\"1.0\"";
if ($this->_namespace) { if ($this->namespace) {
print " xmlns:" . $this->_namespace . print " xmlns:" . $this->namespace .
"=\"www.lastcraft.com/SimpleTest/Beta3/Report\""; "=\"www.lastcraft.com/SimpleTest/Beta3/Report\"";
} }
print "?>\n"; print "?>\n";
print "<" . $this->_namespace . "run>\n"; print "<" . $this->namespace . "run>\n";
} }
/** /**
@ -278,7 +278,7 @@ class XmlReporter extends SimpleReporter {
* @abstract * @abstract
*/ */
function paintFooter($test_name) { function paintFooter($test_name) {
print "</" . $this->_namespace . "run>\n"; print "</" . $this->namespace . "run>\n";
} }
} }
@ -290,8 +290,8 @@ class XmlReporter extends SimpleReporter {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class NestingXmlTag { class NestingXmlTag {
var $_name; private $name;
var $_attributes; private $attributes;
/** /**
* Sets the basic test information except * Sets the basic test information except
@ -300,8 +300,8 @@ class NestingXmlTag {
* @access public * @access public
*/ */
function NestingXmlTag($attributes) { function NestingXmlTag($attributes) {
$this->_name = false; $this->name = false;
$this->_attributes = $attributes; $this->attributes = $attributes;
} }
/** /**
@ -310,7 +310,7 @@ class NestingXmlTag {
* @access public * @access public
*/ */
function setName($name) { function setName($name) {
$this->_name = $name; $this->name = $name;
} }
/** /**
@ -319,7 +319,7 @@ class NestingXmlTag {
* @access public * @access public
*/ */
function getName() { function getName() {
return $this->_name; return $this->name;
} }
/** /**
@ -327,8 +327,8 @@ class NestingXmlTag {
* @return hash All attributes. * @return hash All attributes.
* @access protected * @access protected
*/ */
function _getAttributes() { protected function getAttributes() {
return $this->_attributes; return $this->attributes;
} }
} }
@ -457,7 +457,7 @@ class NestingGroupTag extends NestingXmlTag {
* @access public * @access public
*/ */
function getSize() { function getSize() {
$attributes = $this->_getAttributes(); $attributes = $this->getAttributes();
if (isset($attributes['SIZE'])) { if (isset($attributes['SIZE'])) {
return (integer)$attributes['SIZE']; return (integer)$attributes['SIZE'];
} }
@ -472,12 +472,12 @@ class NestingGroupTag extends NestingXmlTag {
* @subpackage UnitTester * @subpackage UnitTester
*/ */
class SimpleTestXmlParser { class SimpleTestXmlParser {
var $_listener; private $listener;
var $_expat; private $expat;
var $_tag_stack; private $tag_stack;
var $_in_content_tag; private $in_content_tag;
var $_content; private $content;
var $_attributes; private $attributes;
/** /**
* Loads a listener with the SimpleReporter * Loads a listener with the SimpleReporter
@ -486,12 +486,12 @@ class SimpleTestXmlParser {
* @access public * @access public
*/ */
function SimpleTestXmlParser(&$listener) { function SimpleTestXmlParser(&$listener) {
$this->_listener = &$listener; $this->listener = &$listener;
$this->_expat = &$this->_createParser(); $this->expat = &$this->createParser();
$this->_tag_stack = array(); $this->tag_stack = array();
$this->_in_content_tag = false; $this->in_content_tag = false;
$this->_content = ''; $this->content = '';
$this->_attributes = array(); $this->attributes = array();
} }
/** /**
@ -502,9 +502,9 @@ class SimpleTestXmlParser {
* @access public * @access public
*/ */
function parse($chunk) { function parse($chunk) {
if (! xml_parse($this->_expat, $chunk)) { if (! xml_parse($this->expat, $chunk)) {
trigger_error('XML parse error with ' . trigger_error('XML parse error with ' .
xml_error_string(xml_get_error_code($this->_expat))); xml_error_string(xml_get_error_code($this->expat)));
return false; return false;
} }
return true; return true;
@ -515,12 +515,12 @@ class SimpleTestXmlParser {
* @return resource Expat handle. * @return resource Expat handle.
* @access protected * @access protected
*/ */
function &_createParser() { protected function &createParser() {
$expat = xml_parser_create(); $expat = xml_parser_create();
xml_set_object($expat, $this); xml_set_object($expat, $this);
xml_set_element_handler($expat, '_startElement', '_endElement'); xml_set_element_handler($expat, 'startElement', 'endElement');
xml_set_character_data_handler($expat, '_addContent'); xml_set_character_data_handler($expat, 'addContent');
xml_set_default_handler($expat, '_default'); xml_set_default_handler($expat, 'defaultContent');
return $expat; return $expat;
} }
@ -530,8 +530,8 @@ class SimpleTestXmlParser {
* to start. * to start.
* @access private * @access private
*/ */
function _pushNestingTag($nested) { protected function pushNestingTag($nested) {
array_unshift($this->_tag_stack, $nested); array_unshift($this->tag_stack, $nested);
} }
/** /**
@ -540,8 +540,8 @@ class SimpleTestXmlParser {
* being parsed. * being parsed.
* @access private * @access private
*/ */
function &_getCurrentNestingTag() { protected function &getCurrentNestingTag() {
return $this->_tag_stack[0]; return $this->tag_stack[0];
} }
/** /**
@ -550,8 +550,8 @@ class SimpleTestXmlParser {
* just finished. * just finished.
* @access private * @access private
*/ */
function _popNestingTag() { protected function popNestingTag() {
return array_shift($this->_tag_stack); return array_shift($this->tag_stack);
} }
/** /**
@ -560,7 +560,7 @@ class SimpleTestXmlParser {
* @return @boolean True if leaf, false if nesting. * @return @boolean True if leaf, false if nesting.
* @private * @private
*/ */
function _isLeaf($tag) { protected function isLeaf($tag) {
return in_array($tag, array( return in_array($tag, array(
'NAME', 'PASS', 'FAIL', 'EXCEPTION', 'SKIP', 'MESSAGE', 'FORMATTED', 'SIGNAL')); 'NAME', 'PASS', 'FAIL', 'EXCEPTION', 'SKIP', 'MESSAGE', 'FORMATTED', 'SIGNAL'));
} }
@ -574,17 +574,17 @@ class SimpleTestXmlParser {
* are marked as true. * are marked as true.
* @access protected * @access protected
*/ */
function _startElement($expat, $tag, $attributes) { protected function startElement($expat, $tag, $attributes) {
$this->_attributes = $attributes; $this->attributes = $attributes;
if ($tag == 'GROUP') { if ($tag == 'GROUP') {
$this->_pushNestingTag(new NestingGroupTag($attributes)); $this->pushNestingTag(new NestingGroupTag($attributes));
} elseif ($tag == 'CASE') { } elseif ($tag == 'CASE') {
$this->_pushNestingTag(new NestingCaseTag($attributes)); $this->pushNestingTag(new NestingCaseTag($attributes));
} elseif ($tag == 'TEST') { } elseif ($tag == 'TEST') {
$this->_pushNestingTag(new NestingMethodTag($attributes)); $this->pushNestingTag(new NestingMethodTag($attributes));
} elseif ($this->_isLeaf($tag)) { } elseif ($this->isLeaf($tag)) {
$this->_in_content_tag = true; $this->in_content_tag = true;
$this->_content = ''; $this->content = '';
} }
} }
@ -594,31 +594,31 @@ class SimpleTestXmlParser {
* @param string $tag Element name. * @param string $tag Element name.
* @access protected * @access protected
*/ */
function _endElement($expat, $tag) { protected function endElement($expat, $tag) {
$this->_in_content_tag = false; $this->in_content_tag = false;
if (in_array($tag, array('GROUP', 'CASE', 'TEST'))) { if (in_array($tag, array('GROUP', 'CASE', 'TEST'))) {
$nesting_tag = $this->_popNestingTag(); $nesting_tag = $this->popNestingTag();
$nesting_tag->paintEnd($this->_listener); $nesting_tag->paintEnd($this->listener);
} elseif ($tag == 'NAME') { } elseif ($tag == 'NAME') {
$nesting_tag = &$this->_getCurrentNestingTag(); $nesting_tag = &$this->getCurrentNestingTag();
$nesting_tag->setName($this->_content); $nesting_tag->setName($this->content);
$nesting_tag->paintStart($this->_listener); $nesting_tag->paintStart($this->listener);
} elseif ($tag == 'PASS') { } elseif ($tag == 'PASS') {
$this->_listener->paintPass($this->_content); $this->listener->paintPass($this->content);
} elseif ($tag == 'FAIL') { } elseif ($tag == 'FAIL') {
$this->_listener->paintFail($this->_content); $this->listener->paintFail($this->content);
} elseif ($tag == 'EXCEPTION') { } elseif ($tag == 'EXCEPTION') {
$this->_listener->paintError($this->_content); $this->listener->paintError($this->content);
} elseif ($tag == 'SKIP') { } elseif ($tag == 'SKIP') {
$this->_listener->paintSkip($this->_content); $this->listener->paintSkip($this->content);
} elseif ($tag == 'SIGNAL') { } elseif ($tag == 'SIGNAL') {
$this->_listener->paintSignal( $this->listener->paintSignal(
$this->_attributes['TYPE'], $this->attributes['TYPE'],
unserialize($this->_content)); unserialize($this->content));
} elseif ($tag == 'MESSAGE') { } elseif ($tag == 'MESSAGE') {
$this->_listener->paintMessage($this->_content); $this->listener->paintMessage($this->content);
} elseif ($tag == 'FORMATTED') { } elseif ($tag == 'FORMATTED') {
$this->_listener->paintFormattedMessage($this->_content); $this->listener->paintFormattedMessage($this->content);
} }
} }
@ -628,9 +628,9 @@ class SimpleTestXmlParser {
* @param string $text Usually output messages. * @param string $text Usually output messages.
* @access protected * @access protected
*/ */
function _addContent($expat, $text) { protected function addContent($expat, $text) {
if ($this->_in_content_tag) { if ($this->in_content_tag) {
$this->_content .= $text; $this->content .= $text;
} }
return true; return true;
} }
@ -641,7 +641,7 @@ class SimpleTestXmlParser {
* @param string $default Text of default content. * @param string $default Text of default content.
* @access protected * @access protected
*/ */
function _default($expat, $default) { protected function defaultContent($expat, $default) {
} }
} }
?> ?>