upgrade simpletest library, hopefully get rid of deprecation warnings...

This commit is contained in:
Shish 2012-03-09 23:08:58 +00:00
parent 91a97f2b00
commit 2943750822
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
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()
------------------------------------------------
These methods were always a bit weird anyway, and
the new parsing of the base tag makes them more so.
They have been replaced with getUrls() instead. If
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
-------------------------------------
@ -48,7 +99,7 @@ getTransferError() call on the web tester to see if
there was a socket level error in a fetch. This check
is now always carried out by the WebTestCase unless
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().
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
==========
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
a version from the location above. You must read and accept that
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
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
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
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.
A full PHPDocumenter API documentation exists at
http://simpletest.sourceforge.net/.
http://simpletest.org/api/.
The user interface is minimal
in the extreme, but a lot of information flows from the test suite.
After version 1.0 we will release a better web UI, but we are leaving XUL
and GTk versions to volunteers as everybody has their own opinion
on a good GUI, and we don't want to discourage development by shipping
one with the toolkit. YOucan download an Eclipse plug-in separately.
The user interface is minimal in the extreme, but a lot of information
flows from the test suite. After version 1.0 we will release a better
web UI, but we are leaving XUL and GTK versions to volunteers as
everybody has their own opinion on a good GUI, and we don't want to
discourage development by shipping one with the toolkit. You can
download an Eclipse plug-in separately.
You are looking at a second full release. The unit tests for SimpleTest
itself can be run here...
The unit tests for SimpleTest 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
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
version.
with a custom php.ini file or with the switch -dmemory_limit=-1
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 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
The full tests read some test data from simpletest.org. If the site
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
very serious. As far as we know we haven't yet managed to check in any
unit test failures, so please correct us if you find one.
very serious. Please notify us if you find one.
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
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.
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
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
know. Any feedback, even bad, is always welcome and we will work to get
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
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
be pretty usable, although the code may not look so good internally.
Oh, yes. It is called "Simple" because it should be simple to
use. We intend to add a complete set of tools for a test first
and "test as you code" type of development. "Simple" does not
mean "Lite" in this context.
Oh, and one last thing: SimpleTest is called "Simple" because it should
be simple to use. We intend to add a complete set of tools for a test
first and "test as you code" type of development. "Simple" does not mean
"Lite" in this context.
Thanks to everyone who has sent comments and offered suggestions. They
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
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@lastcraft.com
-- Marcus Baker, Jason Sweat, Travis Swicegood, Perrick Penet and Edward Z. Yang.

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
* @package SimpleTest
* @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
@ -16,11 +16,11 @@ require_once(dirname(__FILE__) . '/http.php');
* @subpackage WebTester
*/
class SimpleRealm {
var $_type;
var $_root;
var $_username;
var $_password;
private $type;
private $root;
private $username;
private $password;
/**
* Starts with the initial entry directory.
* @param string $type Authentication type for this
@ -30,21 +30,21 @@ class SimpleRealm {
* @access public
*/
function SimpleRealm($type, $url) {
$this->_type = $type;
$this->_root = $url->getBasePath();
$this->_username = false;
$this->_password = false;
$this->type = $type;
$this->root = $url->getBasePath();
$this->username = false;
$this->password = false;
}
/**
* Adds another location to the realm.
* @param SimpleUrl $url Somewhere in realm.
* @access public
*/
function stretch($url) {
$this->_root = $this->_getCommonPath($this->_root, $url->getPath());
$this->root = $this->getCommonPath($this->root, $url->getPath());
}
/**
* Finds the common starting path.
* @param string $first Path to compare.
@ -52,7 +52,7 @@ class SimpleRealm {
* @return string Common directories.
* @access private
*/
function _getCommonPath($first, $second) {
protected function getCommonPath($first, $second) {
$first = explode('/', $first);
$second = explode('/', $second);
for ($i = 0; $i < min(count($first), count($second)); $i++) {
@ -62,7 +62,7 @@ class SimpleRealm {
}
return implode('/', $first) . '/';
}
/**
* Sets the identity to try within this realm.
* @param string $username Username in authentication dialog.
@ -70,28 +70,28 @@ class SimpleRealm {
* @access public
*/
function setIdentity($username, $password) {
$this->_username = $username;
$this->_password = $password;
$this->username = $username;
$this->password = $password;
}
/**
* Accessor for current identity.
* @return string Last succesful username.
* @access public
*/
function getUsername() {
return $this->_username;
return $this->username;
}
/**
* Accessor for current identity.
* @return string Last succesful password.
* @access public
*/
function getPassword() {
return $this->_password;
return $this->password;
}
/**
* Test to see if the URL is within the directory
* tree of the realm.
@ -100,15 +100,15 @@ class SimpleRealm {
* @access public
*/
function isWithin($url) {
if ($this->_isIn($this->_root, $url->getBasePath())) {
if ($this->isIn($this->root, $url->getBasePath())) {
return true;
}
if ($this->_isIn($this->_root, $url->getBasePath() . $url->getPage() . '/')) {
if ($this->isIn($this->root, $url->getBasePath() . $url->getPage() . '/')) {
return true;
}
return false;
}
/**
* Tests to see if one string is a substring of
* another.
@ -118,7 +118,7 @@ class SimpleRealm {
* in the big bit.
* @access private
*/
function _isIn($part, $whole) {
protected function isIn($part, $whole) {
return strpos($whole, $part) === 0;
}
}
@ -129,8 +129,8 @@ class SimpleRealm {
* @subpackage WebTester
*/
class SimpleAuthenticator {
var $_realms;
private $realms;
/**
* Clears the realms.
* @access public
@ -138,18 +138,18 @@ class SimpleAuthenticator {
function SimpleAuthenticator() {
$this->restartSession();
}
/**
* Starts with no realms set up.
* @access public
*/
function restartSession() {
$this->_realms = array();
$this->realms = array();
}
/**
* 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
* only when challenged, wasting bandwidth. IE
* just carries on presenting until a new challenge
@ -164,9 +164,9 @@ class SimpleAuthenticator {
* @access public
*/
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
* against that realm.
@ -177,29 +177,29 @@ class SimpleAuthenticator {
* @access public
*/
function setIdentityForRealm($host, $realm, $username, $password) {
if (isset($this->_realms[$host][$realm])) {
$this->_realms[$host][$realm]->setIdentity($username, $password);
if (isset($this->realms[$host][$realm])) {
$this->realms[$host][$realm]->setIdentity($username, $password);
}
}
/**
* Finds the name of the realm by comparing URLs.
* @param SimpleUrl $url URL to test.
* @return SimpleRealm Name of realm.
* @access private
*/
function _findRealmFromUrl($url) {
if (! isset($this->_realms[$url->getHost()])) {
protected function findRealmFromUrl($url) {
if (! isset($this->realms[$url->getHost()])) {
return false;
}
foreach ($this->_realms[$url->getHost()] as $name => $realm) {
foreach ($this->realms[$url->getHost()] as $name => $realm) {
if ($realm->isWithin($url)) {
return $realm;
}
}
return false;
}
/**
* Presents the appropriate headers for this location.
* @param SimpleHttpRequest $request Request to modify.
@ -210,7 +210,7 @@ class SimpleAuthenticator {
if ($url->getUsername() && $url->getPassword()) {
$username = $url->getUsername();
$password = $url->getPassword();
} elseif ($realm = $this->_findRealmFromUrl($url)) {
} elseif ($realm = $this->findRealmFromUrl($url)) {
$username = $realm->getUsername();
$password = $realm->getPassword();
} else {
@ -218,7 +218,7 @@ class SimpleAuthenticator {
}
$this->addBasicHeaders($request, $username, $password);
}
/**
* Presents the appropriate headers for this
* location for basic authentication.
@ -226,12 +226,11 @@ class SimpleAuthenticator {
* @param string $username Username for realm.
* @param string $password Password for realm.
* @access public
* @static
*/
function addBasicHeaders(&$request, $username, $password) {
static function addBasicHeaders(&$request, $username, $password) {
if ($username && $password) {
$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
* that includes this module.
* @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__) . '/mock_objects.php';
require_once dirname(__FILE__) . '/collector.php';
require_once dirname(__FILE__) . '/default_reporter.php';
/**#@-*/
$GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_CLASSES'] = get_declared_classes();
$GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_PATH'] = getcwd();
register_shutdown_function('simpletest_autorun');
/**
* Exit handler to 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().
* Exit handler to run all recent test cases and exit system if in CLI
*/
function simpletest_autorun() {
chdir($GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_PATH']);
if (tests_have_run()) {
return;
}
$candidates = array_intersect(
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());
$result = run_local_tests();
if (SimpleReporter::inCli()) {
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
* ever been run.
@ -54,28 +77,19 @@ function tests_have_run() {
function initial_file() {
static $file = false;
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;
}
/**
* 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
* is safe enough if require_once() is alwyas used.
* is safe enough if require_once() is always used.
* @return array Class names.
*/
function capture_new_classes() {

View File

@ -3,7 +3,7 @@
* Base include file for SimpleTest
* @package SimpleTest
* @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__) . '/encoding.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__) . '/frames.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);
}
@ -28,25 +34,16 @@ if (!defined('DEFAULT_MAX_NESTED_FRAMES')) {
* @subpackage WebTester
*/
class SimpleBrowserHistory {
var $_sequence;
var $_position;
/**
* Starts empty.
* @access public
*/
function SimpleBrowserHistory() {
$this->_sequence = array();
$this->_position = -1;
}
private $sequence = array();
private $position = -1;
/**
* Test for no entries yet.
* @return boolean True if empty.
* @access private
*/
function _isEmpty() {
return ($this->_position == -1);
protected function isEmpty() {
return ($this->position == -1);
}
/**
@ -54,8 +51,8 @@ class SimpleBrowserHistory {
* @return boolean True if first.
* @access private
*/
function _atBeginning() {
return ($this->_position == 0) && ! $this->_isEmpty();
protected function atBeginning() {
return ($this->position == 0) && ! $this->isEmpty();
}
/**
@ -63,8 +60,8 @@ class SimpleBrowserHistory {
* @return boolean True if last.
* @access private
*/
function _atEnd() {
return ($this->_position + 1 >= count($this->_sequence)) && ! $this->_isEmpty();
protected function atEnd() {
return ($this->position + 1 >= count($this->sequence)) && ! $this->isEmpty();
}
/**
@ -74,11 +71,11 @@ class SimpleBrowserHistory {
* @access public
*/
function recordEntry($url, $parameters) {
$this->_dropFuture();
$this->dropFuture();
array_push(
$this->_sequence,
$this->sequence,
array('url' => $url, 'parameters' => $parameters));
$this->_position++;
$this->position++;
}
/**
@ -88,10 +85,10 @@ class SimpleBrowserHistory {
* @access public
*/
function getUrl() {
if ($this->_isEmpty()) {
if ($this->isEmpty()) {
return false;
}
return $this->_sequence[$this->_position]['url'];
return $this->sequence[$this->position]['url'];
}
/**
@ -101,10 +98,10 @@ class SimpleBrowserHistory {
* @access public
*/
function getParameters() {
if ($this->_isEmpty()) {
if ($this->isEmpty()) {
return false;
}
return $this->_sequence[$this->_position]['parameters'];
return $this->sequence[$this->position]['parameters'];
}
/**
@ -114,10 +111,10 @@ class SimpleBrowserHistory {
* @access public
*/
function back() {
if ($this->_isEmpty() || $this->_atBeginning()) {
if ($this->isEmpty() || $this->atBeginning()) {
return false;
}
$this->_position--;
$this->position--;
return true;
}
@ -128,10 +125,10 @@ class SimpleBrowserHistory {
* @access public
*/
function forward() {
if ($this->_isEmpty() || $this->_atEnd()) {
if ($this->isEmpty() || $this->atEnd()) {
return false;
}
$this->_position++;
$this->position++;
return true;
}
@ -140,12 +137,12 @@ class SimpleBrowserHistory {
* point.
* @access private
*/
function _dropFuture() {
if ($this->_isEmpty()) {
protected function dropFuture() {
if ($this->isEmpty()) {
return;
}
while (! $this->_atEnd()) {
array_pop($this->_sequence);
while (! $this->atEnd()) {
array_pop($this->sequence);
}
}
}
@ -158,11 +155,12 @@ class SimpleBrowserHistory {
* @subpackage WebTester
*/
class SimpleBrowser {
var $_user_agent;
var $_page;
var $_history;
var $_ignore_frames;
var $_maximum_nested_frames;
private $user_agent;
private $page;
private $history;
private $ignore_frames;
private $maximum_nested_frames;
private $parser;
/**
* Starts with a fresh browser with no
@ -171,16 +169,16 @@ class SimpleBrowser {
* set up if specified in the options.
* @access public
*/
function SimpleBrowser() {
$this->_user_agent = &$this->_createUserAgent();
$this->_user_agent->useProxy(
function __construct() {
$this->user_agent = $this->createUserAgent();
$this->user_agent->useProxy(
SimpleTest::getDefaultProxy(),
SimpleTest::getDefaultProxyUsername(),
SimpleTest::getDefaultProxyPassword());
$this->_page = &new SimplePage();
$this->_history = &$this->_createHistory();
$this->_ignore_frames = false;
$this->_maximum_nested_frames = DEFAULT_MAX_NESTED_FRAMES;
$this->page = new SimplePage();
$this->history = $this->createHistory();
$this->ignore_frames = false;
$this->maximum_nested_frames = DEFAULT_MAX_NESTED_FRAMES;
}
/**
@ -188,9 +186,8 @@ class SimpleBrowser {
* @return SimpleFetcher Content fetcher.
* @access protected
*/
function &_createUserAgent() {
$user_agent = &new SimpleUserAgent();
return $user_agent;
protected function createUserAgent() {
return new SimpleUserAgent();
}
/**
@ -198,9 +195,33 @@ class SimpleBrowser {
* @return SimpleBrowserHistory New list.
* @access protected
*/
function &_createHistory() {
$history = &new SimpleBrowserHistory();
return $history;
protected function createHistory() {
return new SimpleBrowserHistory();
}
/**
* 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
*/
function ignoreFrames() {
$this->_ignore_frames = true;
$this->ignore_frames = true;
}
/**
@ -218,23 +239,23 @@ class SimpleBrowser {
* @access public
*/
function useFrames() {
$this->_ignore_frames = false;
$this->ignore_frames = false;
}
/**
* Switches off cookie sending and recieving.
* @access public
*/
function ignoreCookies() {
$this->_user_agent->ignoreCookies();
$this->user_agent->ignoreCookies();
}
/**
* Switches back on the cookie sending and recieving.
* @access public
*/
function useCookies() {
$this->_user_agent->useCookies();
$this->user_agent->useCookies();
}
/**
@ -245,37 +266,32 @@ class SimpleBrowser {
* @return SimplePage Parsed HTML.
* @access private
*/
function &_parse($response, $depth = 0) {
$page = &$this->_buildPage($response);
if ($this->_ignore_frames || ! $page->hasFrames() || ($depth > $this->_maximum_nested_frames)) {
protected function parse($response, $depth = 0) {
$page = $this->buildPage($response);
if ($this->ignore_frames || ! $page->hasFrames() || ($depth > $this->maximum_nested_frames)) {
return $page;
}
$frameset = &new SimpleFrameset($page);
$frameset = new SimpleFrameset($page);
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);
}
return $frameset;
}
/**
* Assembles the parsing machinery and actually parses
* a single page. Frees all of the builder memory and so
* unjams the PHP memory management.
* @param SimpleHttpResponse $response Response from fetch.
* @return SimplePage Parsed top level page.
* @access protected
*/
function &_buildPage($response) {
$builder = &new SimplePageBuilder();
$page = &$builder->parse($response);
$builder->free();
unset($builder);
return $page;
protected function buildPage($response) {
return $this->getParser()->parse($response);
}
/**
* Fetches a page. Jointly recursive with the _parse()
* Fetches a page. Jointly recursive with the parse()
* method as it descends a frameset.
* @param string/SimpleUrl $url Target to fetch.
* @param SimpleEncoding $encoding GET/POST parameters.
@ -283,14 +299,12 @@ class SimpleBrowser {
* @return SimplePage Parsed page.
* @access private
*/
function &_fetch($url, $encoding, $depth = 0) {
$response = &$this->_user_agent->fetchResponse($url, $encoding);
protected function fetch($url, $encoding, $depth = 0) {
$response = $this->user_agent->fetchResponse($url, $encoding);
if ($response->isError()) {
$page = &new SimplePage($response);
} else {
$page = &$this->_parse($response, $depth);
return new SimplePage($response);
}
return $page;
return $this->parse($response, $depth);
}
/**
@ -301,12 +315,12 @@ class SimpleBrowser {
* @return string Raw content of page.
* @access private
*/
function _load($url, $parameters) {
protected function load($url, $parameters) {
$frame = $url->getTarget();
if (! $frame || ! $this->_page->hasFrames() || (strtolower($frame) == '_top')) {
return $this->_loadPage($url, $parameters);
if (! $frame || ! $this->page->hasFrames() || (strtolower($frame) == '_top')) {
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.
* @access private
*/
function _loadPage($url, $parameters) {
$this->_page = &$this->_fetch($url, $parameters);
$this->_history->recordEntry(
$this->_page->getUrl(),
$this->_page->getRequestData());
return $this->_page->getRaw();
protected function loadPage($url, $parameters) {
$this->page = $this->fetch($url, $parameters);
$this->history->recordEntry(
$this->page->getUrl(),
$this->page->getRequestData());
return $this->page->getRaw();
}
/**
@ -333,9 +347,9 @@ class SimpleBrowser {
* @return string Raw content of page.
* @access private
*/
function _loadFrame($frames, $url, $parameters) {
$page = &$this->_fetch($url, $parameters);
$this->_page->setFrame($frames, $page);
protected function loadFrame($frames, $url, $parameters) {
$page = $this->fetch($url, $parameters);
$this->page->setFrame($frames, $page);
return $page->getRaw();
}
@ -348,7 +362,7 @@ class SimpleBrowser {
* @access public
*/
function restart($date = false) {
$this->_user_agent->restart($date);
$this->user_agent->restart($date);
}
/**
@ -358,7 +372,7 @@ class SimpleBrowser {
* @access public
*/
function addHeader($header) {
$this->_user_agent->addHeader($header);
$this->user_agent->addHeader($header);
}
/**
@ -367,7 +381,7 @@ class SimpleBrowser {
* @access public
*/
function ageCookies($interval) {
$this->_user_agent->ageCookies($interval);
$this->user_agent->ageCookies($interval);
}
/**
@ -381,7 +395,7 @@ class SimpleBrowser {
* @access public
*/
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
*/
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
*/
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
*/
function setMaximumRedirects($max) {
$this->_user_agent->setMaximumRedirects($max);
$this->user_agent->setMaximumRedirects($max);
}
/**
@ -426,7 +440,7 @@ class SimpleBrowser {
* @access public
*/
function setMaximumNestedFrames($max) {
$this->_maximum_nested_frames = $max;
$this->maximum_nested_frames = $max;
}
/**
@ -435,7 +449,7 @@ class SimpleBrowser {
* @access public
*/
function setConnectionTimeout($timeout) {
$this->_user_agent->setConnectionTimeout($timeout);
$this->user_agent->setConnectionTimeout($timeout);
}
/**
@ -448,7 +462,7 @@ class SimpleBrowser {
* @access public
*/
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()) {
$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();
}
@ -486,24 +501,55 @@ class SimpleBrowser {
if ($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.
* @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.
* @access public
*/
function post($url, $parameters = false) {
function post($url, $parameters = false, $content_type = false) {
if (! is_object($url)) {
$url = new SimpleUrl($url);
}
if ($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
*/
function retry() {
$frames = $this->_page->getFrameFocus();
$frames = $this->page->getFrameFocus();
if (count($frames) > 0) {
$this->_loadFrame(
$this->loadFrame(
$frames,
$this->_page->getUrl(),
$this->_page->getRequestData());
return $this->_page->getRaw();
$this->page->getUrl(),
$this->page->getRequestData());
return $this->page->getRaw();
}
if ($url = $this->_history->getUrl()) {
$this->_page = &$this->_fetch($url, $this->_history->getParameters());
return $this->_page->getRaw();
if ($url = $this->history->getUrl()) {
$this->page = $this->fetch($url, $this->history->getParameters());
return $this->page->getRaw();
}
return false;
}
@ -540,12 +586,12 @@ class SimpleBrowser {
* @access public
*/
function back() {
if (! $this->_history->back()) {
if (! $this->history->back()) {
return false;
}
$content = $this->retry();
if (! $content) {
$this->_history->forward();
$this->history->forward();
}
return $content;
}
@ -560,12 +606,12 @@ class SimpleBrowser {
* @access public
*/
function forward() {
if (! $this->_history->forward()) {
if (! $this->history->forward()) {
return false;
}
$content = $this->retry();
if (! $content) {
$this->_history->back();
$this->history->back();
}
return $content;
}
@ -581,16 +627,16 @@ class SimpleBrowser {
* @access public
*/
function authenticate($username, $password) {
if (! $this->_page->getRealm()) {
if (! $this->page->getRealm()) {
return false;
}
$url = $this->_page->getUrl();
$url = $this->page->getUrl();
if (! $url) {
return false;
}
$this->_user_agent->setIdentity(
$this->user_agent->setIdentity(
$url->getHost(),
$this->_page->getRealm(),
$this->page->getRealm(),
$username,
$password);
return $this->retry();
@ -603,7 +649,7 @@ class SimpleBrowser {
* @access public
*/
function getFrames() {
return $this->_page->getFrames();
return $this->page->getFrames();
}
/**
@ -615,7 +661,7 @@ class SimpleBrowser {
* @access public
*/
function getFrameFocus() {
return $this->_page->getFrameFocus();
return $this->page->getFrameFocus();
}
/**
@ -625,7 +671,7 @@ class SimpleBrowser {
* @access public
*/
function setFrameFocusByIndex($choice) {
return $this->_page->setFrameFocusByIndex($choice);
return $this->page->setFrameFocusByIndex($choice);
}
/**
@ -635,7 +681,7 @@ class SimpleBrowser {
* @access public
*/
function setFrameFocus($name) {
return $this->_page->setFrameFocus($name);
return $this->page->setFrameFocus($name);
}
/**
@ -644,7 +690,7 @@ class SimpleBrowser {
* @access public
*/
function clearFrameFocus() {
return $this->_page->clearFrameFocus();
return $this->page->clearFrameFocus();
}
/**
@ -653,7 +699,7 @@ class SimpleBrowser {
* @access public
*/
function getTransportError() {
return $this->_page->getTransportError();
return $this->page->getTransportError();
}
/**
@ -662,7 +708,7 @@ class SimpleBrowser {
* @access public
*/
function getMimeType() {
return $this->_page->getMimeType();
return $this->page->getMimeType();
}
/**
@ -671,7 +717,7 @@ class SimpleBrowser {
* @access public
*/
function getResponseCode() {
return $this->_page->getResponseCode();
return $this->page->getResponseCode();
}
/**
@ -681,7 +727,7 @@ class SimpleBrowser {
* @access public
*/
function getAuthentication() {
return $this->_page->getAuthentication();
return $this->page->getAuthentication();
}
/**
@ -691,7 +737,7 @@ class SimpleBrowser {
* @access public
*/
function getRealm() {
return $this->_page->getRealm();
return $this->page->getRealm();
}
/**
@ -701,7 +747,7 @@ class SimpleBrowser {
* a string.
*/
function getUrl() {
$url = $this->_page->getUrl();
$url = $this->page->getUrl();
return $url ? $url->asString() : false;
}
@ -710,7 +756,7 @@ class SimpleBrowser {
* @return string base URL
*/
function getBaseUrl() {
$url = $this->_page->getBaseUrl();
$url = $this->page->getBaseUrl();
return $url ? $url->asString() : false;
}
@ -720,7 +766,7 @@ class SimpleBrowser {
* @access public
*/
function getRequest() {
return $this->_page->getRequest();
return $this->page->getRequest();
}
/**
@ -729,7 +775,7 @@ class SimpleBrowser {
* @access public
*/
function getHeaders() {
return $this->_page->getHeaders();
return $this->page->getHeaders();
}
/**
@ -738,7 +784,7 @@ class SimpleBrowser {
* @access public
*/
function getContent() {
return $this->_page->getRaw();
return $this->page->getRaw();
}
/**
@ -747,7 +793,7 @@ class SimpleBrowser {
* @access public
*/
function getContentAsText() {
return $this->_page->getText();
return $this->page->getText();
}
/**
@ -756,7 +802,7 @@ class SimpleBrowser {
* @access public
*/
function getTitle() {
return $this->_page->getTitle();
return $this->page->getTitle();
}
/**
@ -766,7 +812,7 @@ class SimpleBrowser {
* @access public
*/
function getUrls() {
return $this->_page->getUrls();
return $this->page->getUrls();
}
/**
@ -777,7 +823,7 @@ class SimpleBrowser {
* @access public
*/
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
*/
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
*/
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
*/
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
*/
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
*/
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
*/
function clickSubmit($label = 'Submit', $additional = false) {
if (! ($form = &$this->_page->getFormBySubmit(new SimpleByLabel($label)))) {
if (! ($form = $this->page->getFormBySubmit(new SimpleByLabel($label)))) {
return false;
}
$success = $this->_load(
$success = $this->load(
$form->getAction(),
$form->submitButton(new SimpleByLabel($label), $additional));
return ($success ? $this->getContent() : $success);
@ -869,10 +915,10 @@ class SimpleBrowser {
* @access public
*/
function clickSubmitByName($name, $additional = false) {
if (! ($form = &$this->_page->getFormBySubmit(new SimpleByName($name)))) {
if (! ($form = $this->page->getFormBySubmit(new SimpleByName($name)))) {
return false;
}
$success = $this->_load(
$success = $this->load(
$form->getAction(),
$form->submitButton(new SimpleByName($name), $additional));
return ($success ? $this->getContent() : $success);
@ -887,15 +933,15 @@ class SimpleBrowser {
* @access public
*/
function clickSubmitById($id, $additional = false) {
if (! ($form = &$this->_page->getFormBySubmit(new SimpleById($id)))) {
if (! ($form = $this->page->getFormBySubmit(new SimpleById($id)))) {
return false;
}
$success = $this->_load(
$success = $this->load(
$form->getAction(),
$form->submitButton(new SimpleById($id), $additional));
return ($success ? $this->getContent() : $success);
}
/**
* Tests to see if a submit button exists with this
* label.
@ -904,7 +950,7 @@ class SimpleBrowser {
* @access public
*/
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
*/
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;
}
$success = $this->_load(
$success = $this->load(
$form->getAction(),
$form->submitImage(new SimpleByLabel($label), $x, $y, $additional));
return ($success ? $this->getContent() : $success);
@ -944,10 +990,10 @@ class SimpleBrowser {
* @access public
*/
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;
}
$success = $this->_load(
$success = $this->load(
$form->getAction(),
$form->submitImage(new SimpleByName($name), $x, $y, $additional));
return ($success ? $this->getContent() : $success);
@ -966,15 +1012,15 @@ class SimpleBrowser {
* @access public
*/
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;
}
$success = $this->_load(
$success = $this->load(
$form->getAction(),
$form->submitImage(new SimpleById($id), $x, $y, $additional));
return ($success ? $this->getContent() : $success);
}
/**
* Tests to see if an image exists with this
* title or alt text.
@ -983,7 +1029,7 @@ class SimpleBrowser {
* @access public
*/
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.
* @access public
*/
function submitFormById($id) {
if (! ($form = &$this->_page->getFormById($id))) {
function submitFormById($id, $additional = false) {
if (! ($form = $this->page->getFormById($id))) {
return false;
}
$success = $this->_load(
$success = $this->load(
$form->getAction(),
$form->submit());
$form->submit($additional));
return ($success ? $this->getContent() : $success);
}
@ -1014,7 +1060,7 @@ class SimpleBrowser {
* @access public
*/
function getLink($label, $index = 0) {
$urls = $this->_page->getUrlsByLabel($label);
$urls = $this->page->getUrlsByLabel($label);
if (count($urls) == 0) {
return false;
}
@ -1039,10 +1085,10 @@ class SimpleBrowser {
if ($url === false) {
return false;
}
$this->_load($url, new SimpleGetEncoding());
$this->load($url, new SimpleGetEncoding());
return $this->getContent();
}
/**
* Finds a link by id attribute.
* @param string $id ID attribute value.
@ -1050,7 +1096,7 @@ class SimpleBrowser {
* @access public
*/
function getLinkById($id) {
return $this->_page->getUrlById($id);
return $this->page->getUrlById($id);
}
/**
@ -1063,7 +1109,7 @@ class SimpleBrowser {
if (! ($url = $this->getLinkById($id))) {
return false;
}
$this->_load($url, new SimpleGetEncoding());
$this->load($url, new SimpleGetEncoding());
return $this->getContent();
}

View File

@ -6,7 +6,7 @@
* @author Travis Swicegood <development@domain51.com>
* @package SimpleTest
* @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.
* @return string Path without trailing slash.
*/
function _removeTrailingSlash($path) {
protected function removeTrailingSlash($path) {
if (substr($path, -1) == DIRECTORY_SEPARATOR) {
return substr($path, 0, -1);
} elseif (substr($path, -1) == '/') {
@ -40,13 +40,13 @@ class SimpleCollector {
* @see _attemptToAdd()
*/
function collect(&$test, $path) {
$path = $this->_removeTrailingSlash($path);
$path = $this->removeTrailingSlash($path);
if ($handle = opendir($path)) {
while (($entry = readdir($handle)) !== false) {
if ($this->_isHidden($entry)) {
if ($this->isHidden($entry)) {
continue;
}
$this->_handle($test, $path . DIRECTORY_SEPARATOR . $entry);
$this->handle($test, $path . DIRECTORY_SEPARATOR . $entry);
}
closedir($handle);
}
@ -65,13 +65,13 @@ class SimpleCollector {
* @see collect()
* @access protected
*/
function _handle(&$test, $file) {
protected function handle(&$test, $file) {
if (is_dir($file)) {
return;
}
$test->addTestFile($file);
$test->addFile($file);
}
/**
* Tests for hidden files so as to skip them. Currently
* only tests for Unix hidden files.
@ -79,7 +79,7 @@ class SimpleCollector {
* @return boolean True if hidden file.
* @access private
*/
function _isHidden($filename) {
protected function isHidden($filename) {
return strncmp($filename, '.', 1) == 0;
}
}
@ -93,7 +93,7 @@ class SimpleCollector {
* @see 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}
* for full documentation of valid pattern.s
*/
function SimplePatternCollector($pattern = '/php$/i') {
$this->_pattern = $pattern;
function __construct($pattern = '/php$/i') {
$this->pattern = $pattern;
}
/**
@ -113,9 +113,9 @@ class SimplePatternCollector extends SimpleCollector {
* @param string $path Directory to scan.
* @access protected
*/
function _handle(&$test, $filename) {
if (preg_match($this->_pattern, $filename)) {
parent::_handle($test, $filename);
protected function handle(&$test, $filename) {
if (preg_match($this->pattern, $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
* @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
*/
class SimpleTestCompatibility {
/**
* Creates a copy whether in PHP5 or PHP4.
* @param object $object Thing to copy.
* @return object A copy.
* @access public
* @static
*/
function copy($object) {
static function copy($object) {
if (version_compare(phpversion(), '5') >= 0) {
eval('$copy = clone $object;');
return $copy;
}
return $object;
}
/**
* Identity test. Drops back to equality + types for PHP5
* objects as the === operator counts as the
@ -35,27 +34,25 @@ class SimpleTestCompatibility {
* @param mixed $second Comparison object.
* @return boolean True if identical.
* @access public
* @static
*/
function isIdentical($first, $second) {
static function isIdentical($first, $second) {
if (version_compare(phpversion(), '5') >= 0) {
return SimpleTestCompatibility::_isIdenticalType($first, $second);
return SimpleTestCompatibility::isIdenticalType($first, $second);
}
if ($first != $second) {
return false;
}
return ($first === $second);
}
/**
* Recursive type test.
* @param mixed $first Test subject.
* @param mixed $second Comparison object.
* @return boolean True if same type.
* @access private
* @static
*/
function _isIdenticalType($first, $second) {
protected static function isIdenticalType($first, $second) {
if (gettype($first) != gettype($second)) {
return false;
}
@ -63,33 +60,32 @@ class SimpleTestCompatibility {
if (get_class($first) != get_class($second)) {
return false;
}
return SimpleTestCompatibility::_isArrayOfIdenticalTypes(
get_object_vars($first),
get_object_vars($second));
return SimpleTestCompatibility::isArrayOfIdenticalTypes(
(array) $first,
(array) $second);
}
if (is_array($first) && is_array($second)) {
return SimpleTestCompatibility::_isArrayOfIdenticalTypes($first, $second);
return SimpleTestCompatibility::isArrayOfIdenticalTypes($first, $second);
}
if ($first !== $second) {
return false;
}
return true;
}
/**
* Recursive type test for each element of an array.
* @param mixed $first Test subject.
* @param mixed $second Comparison object.
* @return boolean True if identical.
* @access private
* @static
*/
function _isArrayOfIdenticalTypes($first, $second) {
protected static function isArrayOfIdenticalTypes($first, $second) {
if (array_keys($first) != array_keys($second)) {
return false;
}
foreach (array_keys($first) as $key) {
$is_identical = SimpleTestCompatibility::_isIdenticalType(
$is_identical = SimpleTestCompatibility::isIdenticalType(
$first[$key],
$second[$key]);
if (! $is_identical) {
@ -98,16 +94,15 @@ class SimpleTestCompatibility {
}
return true;
}
/**
* Test for two variables being aliases.
* @param mixed $first Test subject.
* @param mixed $second Comparison object.
* @return boolean True if same.
* @access public
* @static
*/
function isReference(&$first, &$second) {
static function isReference(&$first, &$second) {
if (version_compare(phpversion(), '5', '>=') && is_object($first)) {
return ($first === $second);
}
@ -124,7 +119,7 @@ class SimpleTestCompatibility {
$first = $temp;
return $is_ref;
}
/**
* Test to see if an object is a member of a
* class hiearchy.
@ -132,9 +127,8 @@ class SimpleTestCompatibility {
* @param string $class Root name of hiearchy.
* @return boolean True if class in hiearchy.
* @access public
* @static
*/
function isA($object, $class) {
static function isA($object, $class) {
if (version_compare(phpversion(), '5') >= 0) {
if (! class_exists($class, false)) {
if (function_exists('interface_exists')) {
@ -152,15 +146,14 @@ class SimpleTestCompatibility {
return ((strtolower($class) == get_class($object))
or (is_subclass_of($object, $class)));
}
/**
* Sets a socket timeout for each chunk.
* @param resource $handle Socket handle.
* @param integer $timeout Limit in seconds.
* @access public
* @static
*/
function setTimeout($handle, $timeout) {
static function setTimeout($handle, $timeout) {
if (function_exists('stream_set_timeout')) {
stream_set_timeout($handle, $timeout, 0);
} elseif (function_exists('socket_set_timeout')) {

View File

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

View File

@ -3,7 +3,7 @@
* Optional include file for SimpleTest
* @package SimpleTest
* @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
*/
class SimpleCommandLineParser {
var $_to_property = array(
'case' => '_case', 'c' => '_case',
'test' => '_test', 't' => '_test',
'xml' => '_xml', 'x' => '_xml');
var $_case = '';
var $_test = '';
var $_xml = false;
var $_no_skips = false;
private $to_property = array(
'case' => 'case', 'c' => 'case',
'test' => 'test', 't' => 'test',
);
private $case = '';
private $test = '';
private $xml = false;
private $help = false;
private $no_skips = false;
/**
* Parses raw command line arguments into object properties.
* @param string $arguments Raw commend line arguments.
*/
function SimpleCommandLineParser($arguments) {
function __construct($arguments) {
if (! is_array($arguments)) {
return;
}
foreach ($arguments as $i => $argument) {
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];
} 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])) {
$this->$property = $arguments[$i + 1];
}
} elseif (preg_match('/^--?(xml|x)$/', $argument)) {
$this->_xml = true;
$this->xml = true;
} 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.
* @return string Test name to run.
* @access public
*/
function getTest() {
return $this->_test;
return $this->test;
}
/**
* Run only this test suite.
* @return string Test class name to run.
* @access public
*/
function getTestCase() {
return $this->_case;
return $this->case;
}
/**
* Output should be XML or not.
* @return boolean True if XML desired.
* @access public
*/
function isXml() {
return $this->_xml;
return $this->xml;
}
/**
* Output should suppress skip messages.
* @return boolean True for no skips.
* @access public
*/
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
*/
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()) {
global $argv;
$parser = new SimpleCommandLineParser($argv);
$parser = new SimpleCommandLineParser($_SERVER['argv']);
$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),
$parser->getTestCase(),
$parser->getTest());
if ($parser->noSkips()) {
$reporter = &new NoSkipsReporter($reporter);
$reporter = new NoSkipsReporter($reporter);
}
} else {
$reporter = &new SelectiveReporter(
$reporter = new SelectiveReporter(
SimpleTest::preferred('HtmlReporter'),
@$_GET['c'],
@$_GET['t']);
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
* @package SimpleTest
* @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
*/
class DetachedTestCase {
var $_command;
var $_dry_command;
var $_size;
private $command;
private $dry_command;
private $size;
/**
* Sets the location of the remote test.
@ -29,10 +29,10 @@ class DetachedTestCase {
* @param string $dry_command Script for dry run.
* @access public
*/
function DetachedTestCase($command, $dry_command = false) {
$this->_command = $command;
$this->_dry_command = $dry_command ? $dry_command : $command;
$this->_size = false;
function __construct($command, $dry_command = false) {
$this->command = $command;
$this->dry_command = $dry_command ? $dry_command : $command;
$this->size = false;
}
/**
@ -41,7 +41,7 @@ class DetachedTestCase {
* @access public
*/
function getLabel() {
return $this->_command;
return $this->command;
}
/**
@ -54,10 +54,10 @@ class DetachedTestCase {
*/
function run(&$reporter) {
$shell = &new SimpleShell();
$shell->execute($this->_command);
$parser = &$this->_createParser($reporter);
$shell->execute($this->command);
$parser = &$this->createParser($reporter);
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 true;
@ -69,18 +69,18 @@ class DetachedTestCase {
* @access public
*/
function getSize() {
if ($this->_size === false) {
if ($this->size === false) {
$shell = &new SimpleShell();
$shell->execute($this->_dry_command);
$shell->execute($this->dry_command);
$reporter = &new SimpleReporter();
$parser = &$this->_createParser($reporter);
$parser = &$this->createParser($reporter);
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;
}
$this->_size = $reporter->getTestCaseCount();
$this->size = $reporter->getTestCaseCount();
}
return $this->_size;
return $this->size;
}
/**
@ -89,7 +89,7 @@ class DetachedTestCase {
* @return SimpleTestXmlListener XML reader.
* @access protected
*/
function &_createParser(&$reporter) {
protected function &createParser(&$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
* @package SimpleTest
* @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
@ -18,7 +18,7 @@ if (! defined('TYPE_MATTERS')) {
* @subpackage UnitTester
*/
class SimpleDumper {
/**
* Renders a variable in a shorter form than print_r().
* @param mixed $value Variable to render as a string.
@ -43,7 +43,7 @@ class SimpleDumper {
}
return "Unknown";
}
/**
* Gets the string representation of a type.
* @param mixed $value Variable to check against.
@ -83,7 +83,7 @@ class SimpleDumper {
*/
function describeDifference($first, $second, $identical = false) {
if ($identical) {
if (! $this->_isTypeMatch($first, $second)) {
if (! $this->isTypeMatch($first, $second)) {
return "with type mismatch as [" . $this->describeValue($first) .
"] does not match [" . $this->describeValue($second) . "]";
}
@ -92,10 +92,10 @@ class SimpleDumper {
if ($type == "Unknown") {
return "with unknown type";
}
$method = '_describe' . $type . 'Difference';
$method = 'describe' . $type . 'Difference';
return $this->$method($first, $second, $identical);
}
/**
* Tests to see if types match.
* @param mixed $first First variable.
@ -103,7 +103,7 @@ class SimpleDumper {
* @return boolean True if matches.
* @access private
*/
function _isTypeMatch($first, $second) {
protected function isTypeMatch($first, $second) {
return ($this->getType($first) == $this->getType($second));
}
@ -128,7 +128,7 @@ class SimpleDumper {
$value = substr($value, $start, $size);
return ($start > 0 ? "..." : "") . $value . ($start + $size < $length ? "..." : "");
}
/**
* Creates a human readable description of the
* difference between two variables. The minimal
@ -138,12 +138,12 @@ class SimpleDumper {
* @return string Human readable description.
* @access private
*/
function _describeGenericDifference($first, $second) {
protected function describeGenericDifference($first, $second) {
return "as [" . $this->describeValue($first) .
"] does not match [" .
$this->describeValue($second) . "]";
}
/**
* Creates a human readable description of the
* difference between a null and another variable.
@ -153,10 +153,10 @@ class SimpleDumper {
* @return string Human readable description.
* @access private
*/
function _describeNullDifference($first, $second, $identical) {
return $this->_describeGenericDifference($first, $second);
protected function describeNullDifference($first, $second, $identical) {
return $this->describeGenericDifference($first, $second);
}
/**
* Creates a human readable description of the
* difference between a boolean and another variable.
@ -166,10 +166,10 @@ class SimpleDumper {
* @return string Human readable description.
* @access private
*/
function _describeBooleanDifference($first, $second, $identical) {
return $this->_describeGenericDifference($first, $second);
protected function describeBooleanDifference($first, $second, $identical) {
return $this->describeGenericDifference($first, $second);
}
/**
* Creates a human readable description of the
* difference between a string and another variable.
@ -179,18 +179,18 @@ class SimpleDumper {
* @return string Human readable description.
* @access private
*/
function _describeStringDifference($first, $second, $identical) {
protected function describeStringDifference($first, $second, $identical) {
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 .= " with [" .
$this->clipString($first, 200, $position) . "] and [" .
$this->clipString($second, 200, $position) . "]";
return $message;
}
/**
* Creates a human readable description of the
* difference between an integer and another variable.
@ -200,16 +200,16 @@ class SimpleDumper {
* @return string Human readable description.
* @access private
*/
function _describeIntegerDifference($first, $second, $identical) {
protected function describeIntegerDifference($first, $second, $identical) {
if (is_object($second) || is_array($second)) {
return $this->_describeGenericDifference($first, $second);
return $this->describeGenericDifference($first, $second);
}
return "because [" . $this->describeValue($first) .
"] differs from [" .
$this->describeValue($second) . "] by " .
abs($first - $second);
}
/**
* Creates a human readable description of the
* difference between two floating point numbers.
@ -219,16 +219,16 @@ class SimpleDumper {
* @return string Human readable description.
* @access private
*/
function _describeFloatDifference($first, $second, $identical) {
protected function describeFloatDifference($first, $second, $identical) {
if (is_object($second) || is_array($second)) {
return $this->_describeGenericDifference($first, $second);
return $this->describeGenericDifference($first, $second);
}
return "because [" . $this->describeValue($first) .
"] differs from [" .
$this->describeValue($second) . "] by " .
abs($first - $second);
}
/**
* Creates a human readable description of the
* difference between two arrays.
@ -238,11 +238,11 @@ class SimpleDumper {
* @return string Human readable description.
* @access private
*/
function _describeArrayDifference($first, $second, $identical) {
protected function describeArrayDifference($first, $second, $identical) {
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 [" .
implode(", ", array_keys($first)) . "] does not match key list [" .
implode(", ", array_keys($second)) . "]";
@ -261,7 +261,7 @@ class SimpleDumper {
}
return "";
}
/**
* Compares two arrays to see if their key lists match.
* For an identical match, the ordering and types of the keys
@ -272,7 +272,7 @@ class SimpleDumper {
* @return boolean True if matching.
* @access private
*/
function _isMatchingKeys($first, $second, $identical) {
protected function isMatchingKeys($first, $second, $identical) {
$first_keys = array_keys($first);
$second_keys = array_keys($second);
if ($identical) {
@ -282,7 +282,7 @@ class SimpleDumper {
sort($second_keys);
return ($first_keys == $second_keys);
}
/**
* Creates a human readable description of the
* difference between a resource and another variable.
@ -292,10 +292,10 @@ class SimpleDumper {
* @return string Human readable description.
* @access private
*/
function _describeResourceDifference($first, $second, $identical) {
return $this->_describeGenericDifference($first, $second);
protected function describeResourceDifference($first, $second, $identical) {
return $this->describeGenericDifference($first, $second);
}
/**
* Creates a human readable description of the
* difference between two objects.
@ -303,18 +303,66 @@ class SimpleDumper {
* @param mixed $second Object to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
function _describeObjectDifference($first, $second, $identical) {
protected function describeObjectDifference($first, $second, $identical) {
if (! is_object($second)) {
return $this->_describeGenericDifference($first, $second);
return $this->describeGenericDifference($first, $second);
}
return $this->_describeArrayDifference(
get_object_vars($first),
get_object_vars($second),
return $this->describeArrayDifference(
$this->getMembers($first),
$this->getMembers($second),
$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
* in two strings by binary chop.
@ -324,7 +372,7 @@ class SimpleDumper {
* character.
* @access private
*/
function _stringDiffersAt($first, $second) {
protected function stringDiffersAt($first, $second) {
if (! $first || ! $second) {
return 0;
}
@ -341,13 +389,12 @@ class SimpleDumper {
}
return $position;
}
/**
* Sends a formatted dump of a variable to a string.
* @param mixed $variable Variable to display.
* @return string Output from print_r().
* @access public
* @static
*/
function dump($variable) {
ob_start();

View File

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

View File

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

View File

@ -3,16 +3,9 @@
* base include file for SimpleTest
* @package SimpleTest
* @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.
*/
@ -32,8 +25,8 @@ class SimpleErrorTrappingInvoker extends SimpleInvokerDecorator {
* Stores the invoker to wrap.
* @param SimpleInvoker $invoker Test method runner.
*/
function SimpleErrorTrappingInvoker(&$invoker) {
$this->SimpleInvokerDecorator($invoker);
function __construct($invoker) {
parent::__construct($invoker);
}
/**
@ -44,22 +37,22 @@ class SimpleErrorTrappingInvoker extends SimpleInvokerDecorator {
* @access public
*/
function invoke($method) {
$queue = &$this->_createErrorQueue();
$queue = $this->createErrorQueue();
set_error_handler('SimpleTestErrorHandler');
parent::invoke($method);
restore_error_handler();
$queue->tally();
}
/**
* Wires up the error queue for a single test.
* @return SimpleErrorQueue Queue connected to the test.
* @access private
*/
function &_createErrorQueue() {
$context = &SimpleTest::getContext();
$test = &$this->getTestCase();
$queue = &$context->get('SimpleErrorQueue');
protected function createErrorQueue() {
$context = SimpleTest::getContext();
$test = $this->getTestCase();
$queue = $context->get('SimpleErrorQueue');
$queue->setTestCase($test);
return $queue;
}
@ -72,15 +65,15 @@ class SimpleErrorTrappingInvoker extends SimpleInvokerDecorator {
* @subpackage UnitTester
*/
class SimpleErrorQueue {
var $_queue;
var $_expectation_queue;
var $_test;
var $_using_expect_style = false;
private $queue;
private $expectation_queue;
private $test;
private $using_expect_style = false;
/**
* Starts with an empty queue.
*/
function SimpleErrorQueue() {
function __construct() {
$this->clear();
}
@ -89,8 +82,8 @@ class SimpleErrorQueue {
* @access public
*/
function clear() {
$this->_queue = array();
$this->_expectation_queue = array();
$this->queue = array();
$this->expectation_queue = array();
}
/**
@ -98,8 +91,8 @@ class SimpleErrorQueue {
* @param SimpleTestCase $test Test case to send messages to.
* @access public
*/
function setTestCase(&$test) {
$this->_test = &$test;
function setTestCase($test) {
$this->test = $test;
}
/**
@ -112,8 +105,7 @@ class SimpleErrorQueue {
* @access public
*/
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) {
$content = str_replace('%', '%%', $content);
if ($this->_using_expect_style) {
$this->_testLatestError($severity, $content, $filename, $line);
} else {
array_push(
$this->_queue,
array($severity, $content, $filename, $line));
}
$this->testLatestError($severity, $content, $filename, $line);
}
/**
* Any errors still in the queue are sent to the test
* case. Any unfulfilled expectations trigger failures.
@ -143,10 +129,10 @@ class SimpleErrorQueue {
function tally() {
while (list($severity, $message, $file, $line) = $this->extract()) {
$severity = $this->getSeverityAsString($severity);
$this->_test->error($severity, $message, $file, $line);
$this->test->error($severity, $message, $file, $line);
}
while (list($expected, $message) = $this->_extractExpectation()) {
$this->_test->assert($expected, false, "%s -> Expected error not caught");
while (list($expected, $message) = $this->extractExpectation()) {
$this->test->assert($expected, false, "%s -> Expected error not caught");
}
}
@ -159,16 +145,16 @@ class SimpleErrorQueue {
* @param integer $line Line number of error.
* @access private
*/
function _testLatestError($severity, $content, $filename, $line) {
if ($expectation = $this->_extractExpectation()) {
protected function testLatestError($severity, $content, $filename, $line) {
if ($expectation = $this->extractExpectation()) {
list($expected, $message) = $expectation;
$this->_test->assert($expected, $content, sprintf(
$this->test->assert($expected, $content, sprintf(
$message,
"%s -> PHP error [$content] severity [" .
$this->getSeverityAsString($severity) .
"] in [$filename] line [$line]"));
} else {
$this->_test->error($severity, $content, $filename, $line);
$this->test->error($severity, $content, $filename, $line);
}
}
@ -182,8 +168,8 @@ class SimpleErrorQueue {
* @access public
*/
function extract() {
if (count($this->_queue)) {
return array_shift($this->_queue);
if (count($this->queue)) {
return array_shift($this->queue);
}
return false;
}
@ -193,48 +179,21 @@ class SimpleErrorQueue {
* @return SimpleExpectation False if none.
* @access private
*/
function _extractExpectation() {
if (count($this->_expectation_queue)) {
return array_shift($this->_expectation_queue);
protected function extractExpectation() {
if (count($this->expectation_queue)) {
return array_shift($this->expectation_queue);
}
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
* representation.
* @param $severity PHP integer error code.
* @return String version of error code.
* @access public
* @static
*/
function getSeverityAsString($severity) {
static function getSeverityAsString($severity) {
static $map = array(
E_STRICT => 'E_STRICT',
E_ERROR => 'E_ERROR',
@ -267,22 +226,42 @@ class SimpleErrorQueue {
* @param $filename File error occoured in.
* @param $line Line number of error.
* @param $super_globals Hash of PHP super global arrays.
* @static
* @access public
*/
function SimpleTestErrorHandler($severity, $message, $filename = null, $line = null, $super_globals = null, $mask = null) {
$severity = $severity & error_reporting();
if ($severity) {
restore_error_handler();
if (ini_get('log_errors')) {
$label = SimpleErrorQueue::getSeverityAsString($severity);
error_log("$label: $message in $filename on line $line");
if (IsNotCausedBySimpleTest($message) && IsNotTimeZoneNag($message)) {
if (ini_get('log_errors')) {
$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');
}
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
* @package SimpleTest
* @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__) . '/expectation.php';
@ -25,8 +25,8 @@ class SimpleExceptionTrappingInvoker extends SimpleInvokerDecorator {
* Stores the invoker to be wrapped.
* @param SimpleInvoker $invoker Test method runner.
*/
function SimpleExceptionTrappingInvoker($invoker) {
$this->SimpleInvokerDecorator($invoker);
function __construct($invoker) {
parent::__construct($invoker);
}
/**
@ -136,6 +136,7 @@ class ExceptionExpectation extends SimpleExpectation {
*/
class SimpleExceptionTrap {
private $expected;
private $ignored;
private $message;
/**
@ -154,16 +155,20 @@ class SimpleExceptionTrap {
* @access public
*/
function expectException($expected = false, $message = '%s') {
if ($expected === false) {
$expected = new AnythingExpectation();
}
if (! SimpleExpectation::isExpectation($expected)) {
$expected = new ExceptionExpectation($expected);
}
$this->expected = $expected;
$this->expected = $this->coerceToExpectation($expected);
$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
* in the queue. Issues a pass or fail and
@ -176,9 +181,31 @@ class SimpleExceptionTrap {
if ($this->expected) {
return $test->assert($this->expected, $exception, $this->message);
}
foreach ($this->ignored as $ignored) {
if ($ignored->test($exception)) {
return true;
}
}
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.
* @return string/false The failure message or false if none.
@ -193,6 +220,7 @@ class SimpleExceptionTrap {
function clear() {
$this->expected = 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
* @package SimpleTest
* @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
*/
class SimpleExpectation {
var $_dumper = false;
var $_message;
protected $dumper = false;
private $message;
/**
* Creates a dumper for displaying values and sets
* the test message.
* @param string $message Customised message on failure.
*/
function SimpleExpectation($message = '%s') {
$this->_message = $message;
function __construct($message = '%s') {
$this->message = $message;
}
/**
@ -64,8 +64,8 @@ class SimpleExpectation {
* @access public
*/
function overlayMessage($compare, $dumper) {
$this->_dumper = $dumper;
return sprintf($this->_message, $this->testMessage($compare));
$this->dumper = $dumper;
return sprintf($this->message, $this->testMessage($compare));
}
/**
@ -73,25 +73,24 @@ class SimpleExpectation {
* @return SimpleDumper Current value dumper.
* @access protected
*/
function &_getDumper() {
if (! $this->_dumper) {
$dumper = &new SimpleDumper();
protected function getDumper() {
if (! $this->dumper) {
$dumper = new SimpleDumper();
return $dumper;
}
return $this->_dumper;
return $this->dumper;
}
/**
* Test to see if a value is an expectation object.
* A useful utility method.
* @param mixed $expectation Hopefully an Epectation
* @param mixed $expectation Hopefully an Expectation
* class.
* @return boolean True if descended from
* this class.
* @access public
* @static
*/
function isExpectation($expectation) {
static function isExpectation($expectation) {
return is_object($expectation) &&
SimpleTestCompatibility::isA($expectation, 'SimpleExpectation');
}
@ -122,7 +121,7 @@ class AnythingExpectation extends SimpleExpectation {
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
$dumper = $this->getDumper();
return 'Anything always matches [' . $dumper->describeValue($compare) . ']';
}
}
@ -151,7 +150,7 @@ class FailedExpectation extends SimpleExpectation {
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
$dumper = $this->getDumper();
return 'Failed expectation never matches [' . $dumper->describeValue($compare) . ']';
}
}
@ -181,7 +180,7 @@ class TrueExpectation extends SimpleExpectation {
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
$dumper = $this->getDumper();
return 'Expected true, got [' . $dumper->describeValue($compare) . ']';
}
}
@ -211,7 +210,7 @@ class FalseExpectation extends SimpleExpectation {
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
$dumper = $this->getDumper();
return 'Expected false, got [' . $dumper->describeValue($compare) . ']';
}
}
@ -222,7 +221,7 @@ class FalseExpectation extends SimpleExpectation {
* @subpackage UnitTester
*/
class EqualExpectation extends SimpleExpectation {
var $_value;
private $value;
/**
* Sets the value to compare against.
@ -230,9 +229,9 @@ class EqualExpectation extends SimpleExpectation {
* @param string $message Customised message on failure.
* @access public
*/
function EqualExpectation($value, $message = '%s') {
$this->SimpleExpectation($message);
$this->_value = $value;
function __construct($value, $message = '%s') {
parent::__construct($message);
$this->value = $value;
}
/**
@ -243,7 +242,7 @@ class EqualExpectation extends SimpleExpectation {
* @access public
*/
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) {
if ($this->test($compare)) {
return "Equal expectation [" . $this->_dumper->describeValue($this->_value) . "]";
return "Equal expectation [" . $this->dumper->describeValue($this->value) . "]";
} else {
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.
* @access protected
*/
function _getValue() {
return $this->_value;
protected function getValue() {
return $this->value;
}
}
@ -285,8 +284,8 @@ class NotEqualExpectation extends EqualExpectation {
* @param string $message Customised message on failure.
* @access public
*/
function NotEqualExpectation($value, $message = '%s') {
$this->EqualExpectation($value, $message);
function __construct($value, $message = '%s') {
parent::__construct($value, $message);
}
/**
@ -308,13 +307,13 @@ class NotEqualExpectation extends EqualExpectation {
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
$dumper = $this->getDumper();
if ($this->test($compare)) {
return "Not equal expectation passes " .
$dumper->describeDifference($this->_getValue(), $compare);
$dumper->describeDifference($this->getValue(), $compare);
} else {
return "Not equal expectation fails [" .
$dumper->describeValue($this->_getValue()) .
$dumper->describeValue($this->getValue()) .
"] matches";
}
}
@ -326,8 +325,8 @@ class NotEqualExpectation extends EqualExpectation {
* @subpackage UnitTester
*/
class WithinMarginExpectation extends SimpleExpectation {
var $_upper;
var $_lower;
private $upper;
private $lower;
/**
* 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.
* @access public
*/
function WithinMarginExpectation($value, $margin, $message = '%s') {
$this->SimpleExpectation($message);
$this->_upper = $value + $margin;
$this->_lower = $value - $margin;
function __construct($value, $margin, $message = '%s') {
parent::__construct($message);
$this->upper = $value + $margin;
$this->lower = $value - $margin;
}
/**
@ -351,7 +350,7 @@ class WithinMarginExpectation extends SimpleExpectation {
* @access public
*/
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) {
if ($this->test($compare)) {
return $this->_withinMessage($compare);
return $this->withinMessage($compare);
} else {
return $this->_outsideMessage($compare);
return $this->outsideMessage($compare);
}
}
@ -374,9 +373,9 @@ class WithinMarginExpectation extends SimpleExpectation {
* @param mixed $compare Value being tested.
* @access private
*/
function _withinMessage($compare) {
return "Within expectation [" . $this->_dumper->describeValue($this->_lower) . "] and [" .
$this->_dumper->describeValue($this->_upper) . "]";
protected function withinMessage($compare) {
return "Within expectation [" . $this->dumper->describeValue($this->lower) . "] and [" .
$this->dumper->describeValue($this->upper) . "]";
}
/**
@ -384,13 +383,13 @@ class WithinMarginExpectation extends SimpleExpectation {
* @param mixed $compare Value being tested.
* @access private
*/
function _outsideMessage($compare) {
if ($compare > $this->_upper) {
protected function outsideMessage($compare) {
if ($compare > $this->upper) {
return "Outside expectation " .
$this->_dumper->describeDifference($compare, $this->_upper);
$this->dumper->describeDifference($compare, $this->upper);
} else {
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.
* @access public
*/
function OutsideMarginExpectation($value, $margin, $message = '%s') {
$this->WithinMarginExpectation($value, $margin, $message);
function __construct($value, $margin, $message = '%s') {
parent::__construct($value, $margin, $message);
}
/**
@ -434,9 +433,9 @@ class OutsideMarginExpectation extends WithinMarginExpectation {
*/
function testMessage($compare) {
if (! $this->test($compare)) {
return $this->_withinMessage($compare);
return $this->withinMessage($compare);
} else {
return $this->_outsideMessage($compare);
return $this->outsideMessage($compare);
}
}
}
@ -446,8 +445,8 @@ class OutsideMarginExpectation extends WithinMarginExpectation {
* @package SimpleTest
* @subpackage UnitTester
*/
class ReferenceExpectation extends SimpleExpectation {
var $_value;
class ReferenceExpectation {
private $value;
/**
* Sets the reference value to compare against.
@ -455,9 +454,9 @@ class ReferenceExpectation extends SimpleExpectation {
* @param string $message Customised message on failure.
* @access public
*/
function ReferenceExpectation(&$value, $message = '%s') {
$this->SimpleExpectation($message);
$this->_value =& $value;
function __construct(&$value, $message = '%s') {
$this->message = $message;
$this->value = &$value;
}
/**
@ -468,7 +467,7 @@ class ReferenceExpectation extends SimpleExpectation {
* @access public
*/
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) {
if ($this->test($compare)) {
return "Reference expectation [" . $this->_dumper->describeValue($this->_value) . "]";
return "Reference expectation [" . $this->dumper->describeValue($this->value) . "]";
} else {
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.
* @access public
*/
function IdenticalExpectation($value, $message = '%s') {
$this->EqualExpectation($value, $message);
function __construct($value, $message = '%s') {
parent::__construct($value, $message);
}
/**
@ -517,7 +539,7 @@ class IdenticalExpectation extends EqualExpectation {
* @access public
*/
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
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
$dumper = $this->getDumper();
if ($this->test($compare)) {
return "Identical expectation [" . $dumper->describeValue($this->_getValue()) . "]";
return "Identical expectation [" . $dumper->describeValue($this->getValue()) . "]";
} else {
return "Identical expectation [" . $dumper->describeValue($this->_getValue()) .
return "Identical expectation [" . $dumper->describeValue($this->getValue()) .
"] fails with [" .
$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.
* @access public
*/
function NotIdenticalExpectation($value, $message = '%s') {
$this->IdenticalExpectation($value, $message);
function __construct($value, $message = '%s') {
parent::__construct($value, $message);
}
/**
@ -576,12 +598,12 @@ class NotIdenticalExpectation extends IdenticalExpectation {
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
$dumper = $this->getDumper();
if ($this->test($compare)) {
return "Not identical expectation passes " .
$dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS);
$dumper->describeDifference($this->getValue(), $compare, TYPE_MATTERS);
} 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
*/
class PatternExpectation extends SimpleExpectation {
var $_pattern;
private $pattern;
/**
* Sets the value to compare against.
@ -600,9 +622,9 @@ class PatternExpectation extends SimpleExpectation {
* @param string $message Customised message on failure.
* @access public
*/
function PatternExpectation($pattern, $message = '%s') {
$this->SimpleExpectation($message);
$this->_pattern = $pattern;
function __construct($pattern, $message = '%s') {
parent::__construct($message);
$this->pattern = $pattern;
}
/**
@ -610,8 +632,8 @@ class PatternExpectation extends SimpleExpectation {
* @return string Perl regex as string.
* @access protected
*/
function _getPattern() {
return $this->_pattern;
protected function getPattern() {
return $this->pattern;
}
/**
@ -622,7 +644,7 @@ class PatternExpectation extends SimpleExpectation {
* @access public
*/
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) {
if ($this->test($compare)) {
return $this->_describePatternMatch($this->_getPattern(), $compare);
return $this->describePatternMatch($this->getPattern(), $compare);
} else {
$dumper = &$this->_getDumper();
return "Pattern [" . $this->_getPattern() .
$dumper = $this->getDumper();
return "Pattern [" . $this->getPattern() .
"] not detected in [" .
$dumper->describeValue($compare) . "]";
}
@ -650,10 +672,10 @@ class PatternExpectation extends SimpleExpectation {
* @param string $subject Subject to search.
* @access protected
*/
function _describePatternMatch($pattern, $subject) {
protected function describePatternMatch($pattern, $subject) {
preg_match($pattern, $subject, $matches);
$position = strpos($subject, $matches[0]);
$dumper = $this->_getDumper();
$dumper = $this->getDumper();
return "Pattern [$pattern] detected at character [$position] in [" .
$dumper->describeValue($subject) . "] as [" .
$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
* comparison.
@ -683,8 +697,8 @@ class NoPatternExpectation extends PatternExpectation {
* @param string $message Customised message on failure.
* @access public
*/
function NoPatternExpectation($pattern, $message = '%s') {
$this->PatternExpectation($pattern, $message);
function __construct($pattern, $message = '%s') {
parent::__construct($pattern, $message);
}
/**
@ -707,31 +721,23 @@ class NoPatternExpectation extends PatternExpectation {
*/
function testMessage($compare) {
if ($this->test($compare)) {
$dumper = &$this->_getDumper();
return "Pattern [" . $this->_getPattern() .
$dumper = $this->getDumper();
return "Pattern [" . $this->getPattern() .
"] not detected in [" .
$dumper->describeValue($compare) . "]";
} 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.
* @package SimpleTest
* @subpackage UnitTester
*/
class IsAExpectation extends SimpleExpectation {
var $_type;
private $type;
/**
* Sets the type to compare with.
@ -739,9 +745,9 @@ class IsAExpectation extends SimpleExpectation {
* @param string $message Customised message on failure.
* @access public
*/
function IsAExpectation($type, $message = '%s') {
$this->SimpleExpectation($message);
$this->_type = $type;
function __construct($type, $message = '%s') {
parent::__construct($message);
$this->type = $type;
}
/**
@ -749,8 +755,8 @@ class IsAExpectation extends SimpleExpectation {
* @return string Type or class name.
* @access protected
*/
function _getType() {
return $this->_type;
protected function getType() {
return $this->type;
}
/**
@ -762,25 +768,25 @@ class IsAExpectation extends SimpleExpectation {
*/
function test($compare) {
if (is_object($compare)) {
return SimpleTestCompatibility::isA($compare, $this->_type);
return SimpleTestCompatibility::isA($compare, $this->type);
} 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.
* @return string Simpler type.
* @access private
*/
function _canonicalType($type) {
protected function canonicalType($type) {
$type = strtolower($type);
$map = array(
'bool' => 'boolean',
'float' => 'double',
'real' => 'double',
'int' => 'integer');
$map = array('boolean' => 'bool');
if (isset($map[$type])) {
$type = $map[$type];
}
@ -795,9 +801,9 @@ class IsAExpectation extends SimpleExpectation {
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
$dumper = $this->getDumper();
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
*/
class NotAExpectation extends IsAExpectation {
var $_type;
private $type;
/**
* Sets the type to compare with.
@ -816,8 +822,8 @@ class NotAExpectation extends IsAExpectation {
* @param string $message Customised message on failure.
* @access public
*/
function NotAExpectation($type, $message = '%s') {
$this->IsAExpectation($type, $message);
function __construct($type, $message = '%s') {
parent::__construct($type, $message);
}
/**
@ -839,40 +845,38 @@ class NotAExpectation extends IsAExpectation {
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
$dumper = $this->getDumper();
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
* @package SimpleTest
* @subpackage UnitTester
* @package SimpleTest
* @subpackage UnitTester
*/
class MethodExistsExpectation extends SimpleExpectation {
var $_method;
private $method;
/**
* Sets the value to compare against.
* @param string $method Method to check.
* @param string $message Customised message on failure.
* @access public
* @return void
*/
function MethodExistsExpectation($method, $message = '%s') {
$this->SimpleExpectation($message);
$this->_method = &$method;
function __construct($method, $message = '%s') {
parent::__construct($message);
$this->method = &$method;
}
/**
* Tests the expectation. True if the method exists in the test object.
* @param string $compare Comparison method name.
* @return boolean True if correct.
* @access public
*/
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.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
$dumper = $this->getDumper();
if (! is_object($compare)) {
return 'No method on non-object [' . $dumper->describeValue($compare) . ']';
}
$method = $this->_method;
$method = $this->method;
return "Object [" . $dumper->describeValue($compare) .
"] 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
* @package SimpleTest
* @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
*/
class PHPUnit_TestCase extends SimpleTestCase {
var $_loosely_typed;
private $_loosely_typed;
/**
* Constructor. Sets the test name.
* @param $label Test name to display.
* @public
*/
function PHPUnit_TestCase($label = false) {
$this->SimpleTestCase($label);
function __construct($label = false) {
parent::__construct($label);
$this->_loosely_typed = false;
}
@ -44,9 +44,9 @@
*/
function assertEquals($first, $second, $message = "%s", $delta = 0) {
if ($this->_loosely_typed) {
$expectation = &new EqualExpectation($first);
$expectation = new EqualExpectation($first);
} else {
$expectation = &new IdenticalExpectation($first);
$expectation = new IdenticalExpectation($first);
}
$this->assert($expectation, $second, $message);
}
@ -72,15 +72,14 @@
}
/**
* In PHP5 the identity test tests for the same
* object. This is a reference test in PHP4.
* Identity test tests for the same object.
* @param $first First object handle.
* @param $second Hopefully the same handle.
* @param $message Message to display.
* @public
*/
function assertSame(&$first, &$second, $message = "%s") {
$dumper = &new SimpleDumper();
function assertSame($first, $second, $message = "%s") {
$dumper = new SimpleDumper();
$message = sprintf(
$message,
"[" . $dumper->describeValue($first) .
@ -93,15 +92,14 @@
}
/**
* In PHP5 the identity test tests for the same
* object. This is a reference test in PHP4.
* Inverted identity test.
* @param $first First object handle.
* @param $second Hopefully a different handle.
* @param $message Message to display.
* @public
*/
function assertNotSame(&$first, &$second, $message = "%s") {
$dumper = &new SimpleDumper();
function assertNotSame($first, $second, $message = "%s") {
$dumper = new SimpleDumper();
$message = sprintf(
$message,
"[" . $dumper->describeValue($first) .
@ -195,4 +193,4 @@
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
/**
* 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
{
var $_test_case_pattern = '/^TestOf(.*)$/';
function TestDoxReporter($test_case_pattern = '/^TestOf(.*)$/') {
parent::SimpleScorer();
function __construct($test_case_pattern = '/^TestOf(.*)$/') {
parent::__construct();
$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";
}
@ -27,16 +38,16 @@ class TestDoxReporter extends SimpleReporter
return;
}
$test_name = $matches[1];
$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));
}
function paintMethodEnd() {
function paintMethodEnd($test_name) {
echo "\n";
}
function paintFail() {
function paintFail($message) {
echo " [FAILED]";
}
}
?>

View File

@ -1,5 +1,5 @@
<?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__) . '/../testdox.php';
@ -19,7 +19,7 @@ class TestOfTestDoxReporter extends UnitTestCase
ob_start();
$dox->paintCaseStart('TestOfTestDoxReporter');
$buffer = ob_get_clean();
$this->assertWantedPattern('/^TestDoxReporter/', $buffer);
$this->assertPattern('/^TestDoxReporter/', $buffer);
}
function testOutputOfTestCaseNameFilteredByConstructParameter() {
@ -27,7 +27,7 @@ class TestOfTestDoxReporter extends UnitTestCase
ob_start();
$dox->paintCaseStart('SomeGreatWidgetTest');
$buffer = ob_get_clean();
$this->assertWantedPattern('/^SomeGreatWidget/', $buffer);
$this->assertPattern('/^SomeGreatWidget/', $buffer);
}
function testIfTest_case_patternIsEmptyAssumeEverythingMatches() {
@ -35,7 +35,7 @@ class TestOfTestDoxReporter extends UnitTestCase
ob_start();
$dox->paintCaseStart('TestOfTestDoxReporter');
$buffer = ob_get_clean();
$this->assertWantedPattern('/^TestOfTestDoxReporter/', $buffer);
$this->assertPattern('/^TestOfTestDoxReporter/', $buffer);
}
function testEmptyLineInsertedWhenCaseEnds() {
@ -75,7 +75,6 @@ class TestOfTestDoxReporter extends UnitTestCase
$dox->paintMethodEnd('someMethod');
$buffer = ob_get_clean();
$this->assertEqual("\n", $buffer);
$this->assertNoErrors();
}
function testProperlySpacesSingleLettersInMethodName() {
@ -89,7 +88,7 @@ class TestOfTestDoxReporter extends UnitTestCase
function testOnFailureThisPrintsFailureNotice() {
$dox = new TestDoxReporter();
ob_start();
$dox->paintFail();
$dox->paintFail('');
$buffer = ob_get_clean();
$this->assertEqual(' [FAILED]', $buffer);
}
@ -105,4 +104,4 @@ class TestOfTestDoxReporter extends UnitTestCase
);
}
}
?>

View File

@ -3,9 +3,9 @@
* Base include file for SimpleTest.
* @package SimpleTest
* @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
*/
@ -20,42 +20,42 @@ require_once(dirname(__FILE__) . '/selector.php');
* @subpackage WebTester
*/
class SimpleForm {
var $_method;
var $_action;
var $_encoding;
var $_default_target;
var $_id;
var $_buttons;
var $_images;
var $_widgets;
var $_radios;
var $_checkboxes;
private $method;
private $action;
private $encoding;
private $default_target;
private $id;
private $buttons;
private $images;
private $widgets;
private $radios;
private $checkboxes;
/**
* Starts with no held controls/widgets.
* @param SimpleTag $tag Form tag to read.
* @param SimplePage $page Holding page.
*/
function SimpleForm($tag, &$page) {
$this->_method = $tag->getAttribute('method');
$this->_action = $this->_createAction($tag->getAttribute('action'), $page);
$this->_encoding = $this->_setEncodingClass($tag);
$this->_default_target = false;
$this->_id = $tag->getAttribute('id');
$this->_buttons = array();
$this->_images = array();
$this->_widgets = array();
$this->_radios = array();
$this->_checkboxes = array();
function __construct($tag, $page) {
$this->method = $tag->getAttribute('method');
$this->action = $this->createAction($tag->getAttribute('action'), $page);
$this->encoding = $this->setEncodingClass($tag);
$this->default_target = false;
$this->id = $tag->getAttribute('id');
$this->buttons = array();
$this->images = array();
$this->widgets = array();
$this->radios = array();
$this->checkboxes = array();
}
/**
* Creates the request packet to be sent by the form.
* @param SimpleTag $tag Form tag to read.
* @return string Packet class.
* @access private
*/
function _setEncodingClass($tag) {
protected function setEncodingClass($tag) {
if (strtolower($tag->getAttribute('method')) == 'post') {
if (strtolower($tag->getAttribute('enctype')) == 'multipart/form-data') {
return 'SimpleMultipartEncoding';
@ -64,25 +64,25 @@ class SimpleForm {
}
return 'SimpleGetEncoding';
}
/**
* Sets the frame target within a frameset.
* @param string $frame Name of frame.
* @access public
*/
function setDefaultTarget($frame) {
$this->_default_target = $frame;
$this->default_target = $frame;
}
/**
* Accessor for method of form submission.
* @return string Either get or post.
* @access public
*/
function getMethod() {
return ($this->_method ? strtolower($this->_method) : 'get');
return ($this->method ? strtolower($this->method) : 'get');
}
/**
* Combined action attribute with current location
* to get an absolute form target.
@ -90,114 +90,116 @@ class SimpleForm {
* @param SimpleUrl $base Page location.
* @return SimpleUrl Absolute form target.
*/
function _createAction($action, &$page) {
protected function createAction($action, $page) {
if (($action === '') || ($action === false)) {
return $page->expandUrl($page->getUrl());
}
return $page->expandUrl(new SimpleUrl($action));;
}
/**
* Absolute URL of the target.
* @return SimpleUrl URL target.
* @access public
*/
function getAction() {
$url = $this->_action;
if ($this->_default_target && ! $url->getTarget()) {
$url->setTarget($this->_default_target);
$url = $this->action;
if ($this->default_target && ! $url->getTarget()) {
$url->setTarget($this->default_target);
}
if ($this->getMethod() == 'get') {
$url->clearRequest();
}
return $url;
}
/**
* Creates the encoding for the current values in the
* form.
* @return SimpleFormEncoding Request to submit.
* @access private
*/
function _encode() {
$class = $this->_encoding;
protected function encode() {
$class = $this->encoding;
$encoding = new $class();
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
$this->_widgets[$i]->write($encoding);
for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
$this->widgets[$i]->write($encoding);
}
return $encoding;
}
/**
* ID field of form for unique identification.
* @return string Unique tag ID.
* @access public
*/
function getId() {
return $this->_id;
return $this->id;
}
/**
* Adds a tag contents to the form.
* @param SimpleWidget $tag Input tag to add.
* @access public
*/
function addWidget(&$tag) {
function addWidget($tag) {
if (strtolower($tag->getAttribute('type')) == 'submit') {
$this->_buttons[] = &$tag;
$this->buttons[] = $tag;
} elseif (strtolower($tag->getAttribute('type')) == 'image') {
$this->_images[] = &$tag;
$this->images[] = $tag;
} elseif ($tag->getName()) {
$this->_setWidget($tag);
$this->setWidget($tag);
}
}
/**
* Sets the widget into the form, grouping radio
* buttons if any.
* @param SimpleWidget $tag Incoming form control.
* @access private
*/
function _setWidget(&$tag) {
protected function setWidget($tag) {
if (strtolower($tag->getAttribute('type')) == 'radio') {
$this->_addRadioButton($tag);
$this->addRadioButton($tag);
} elseif (strtolower($tag->getAttribute('type')) == 'checkbox') {
$this->_addCheckbox($tag);
$this->addCheckbox($tag);
} else {
$this->_widgets[] = &$tag;
$this->widgets[] = &$tag;
}
}
/**
* Adds a radio button, building a group if necessary.
* @param SimpleRadioButtonTag $tag Incoming form control.
* @access private
*/
function _addRadioButton(&$tag) {
if (! isset($this->_radios[$tag->getName()])) {
$this->_widgets[] = &new SimpleRadioGroup();
$this->_radios[$tag->getName()] = count($this->_widgets) - 1;
protected function addRadioButton($tag) {
if (! isset($this->radios[$tag->getName()])) {
$this->widgets[] = new SimpleRadioGroup();
$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.
* @param SimpleCheckboxTag $tag Incoming form control.
* @access private
*/
function _addCheckbox(&$tag) {
if (! isset($this->_checkboxes[$tag->getName()])) {
$this->_widgets[] = &$tag;
$this->_checkboxes[$tag->getName()] = count($this->_widgets) - 1;
protected function addCheckbox($tag) {
if (! isset($this->checkboxes[$tag->getName()])) {
$this->widgets[] = $tag;
$this->checkboxes[$tag->getName()] = count($this->widgets) - 1;
} else {
$index = $this->_checkboxes[$tag->getName()];
if (! SimpleTestCompatibility::isA($this->_widgets[$index], 'SimpleCheckboxGroup')) {
$previous = &$this->_widgets[$index];
$this->_widgets[$index] = &new SimpleCheckboxGroup();
$this->_widgets[$index]->addWidget($previous);
$index = $this->checkboxes[$tag->getName()];
if (! SimpleTestCompatibility::isA($this->widgets[$index], 'SimpleCheckboxGroup')) {
$previous = $this->widgets[$index];
$this->widgets[$index] = new SimpleCheckboxGroup();
$this->widgets[$index]->addWidget($previous);
}
$this->_widgets[$index]->addWidget($tag);
$this->widgets[$index]->addWidget($tag);
}
}
/**
* Extracts current value from form.
* @param SimpleSelector $selector Criteria to apply.
@ -206,19 +208,19 @@ class SimpleForm {
* @access public
*/
function getValue($selector) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($selector->isMatch($this->_widgets[$i])) {
return $this->_widgets[$i]->getValue();
for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
if ($selector->isMatch($this->widgets[$i])) {
return $this->widgets[$i]->getValue();
}
}
foreach ($this->_buttons as $button) {
foreach ($this->buttons as $button) {
if ($selector->isMatch($button)) {
return $button->getValue();
}
}
return null;
}
/**
* Sets a widget value within the form.
* @param SimpleSelector $selector Criteria to apply.
@ -231,11 +233,11 @@ class SimpleForm {
function setField($selector, $value, $position=false) {
$success = false;
$_position = 0;
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($selector->isMatch($this->_widgets[$i])) {
for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
if ($selector->isMatch($this->widgets[$i])) {
$_position++;
if ($position === false or $_position === (int)$position) {
if ($this->_widgets[$i]->setValue($value)) {
if ($this->widgets[$i]->setValue($value)) {
$success = true;
}
}
@ -243,7 +245,7 @@ class SimpleForm {
}
return $success;
}
/**
* Used by the page object to set widgets labels to
* external label tags.
@ -251,16 +253,16 @@ class SimpleForm {
* @access public
*/
function attachLabelBySelector($selector, $label) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($selector->isMatch($this->_widgets[$i])) {
if (method_exists($this->_widgets[$i], 'setLabel')) {
$this->_widgets[$i]->setLabel($label);
for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
if ($selector->isMatch($this->widgets[$i])) {
if (method_exists($this->widgets[$i], 'setLabel')) {
$this->widgets[$i]->setLabel($label);
return;
}
}
}
}
/**
* Test to see if a form has a submit button.
* @param SimpleSelector $selector Criteria to apply.
@ -268,14 +270,14 @@ class SimpleForm {
* @access public
*/
function hasSubmit($selector) {
foreach ($this->_buttons as $button) {
foreach ($this->buttons as $button) {
if ($selector->isMatch($button)) {
return true;
}
}
return false;
}
/**
* Test to see if a form has an image control.
* @param SimpleSelector $selector Criteria to apply.
@ -283,14 +285,14 @@ class SimpleForm {
* @access public
*/
function hasImage($selector) {
foreach ($this->_images as $image) {
foreach ($this->images as $image) {
if ($selector->isMatch($image)) {
return true;
}
}
return false;
}
/**
* Gets the submit values for a selected button.
* @param SimpleSelector $selector Criteria to apply.
@ -302,19 +304,19 @@ class SimpleForm {
*/
function submitButton($selector, $additional = false) {
$additional = $additional ? $additional : array();
foreach ($this->_buttons as $button) {
foreach ($this->buttons as $button) {
if ($selector->isMatch($button)) {
$encoding = $this->_encode();
$encoding = $this->encode();
$button->write($encoding);
if ($additional) {
$encoding->merge($additional);
}
return $encoding;
return $encoding;
}
}
return false;
}
/**
* Gets the submit values for an image.
* @param SimpleSelector $selector Criteria to apply.
@ -328,19 +330,19 @@ class SimpleForm {
*/
function submitImage($selector, $x, $y, $additional = false) {
$additional = $additional ? $additional : array();
foreach ($this->_images as $image) {
foreach ($this->images as $image) {
if ($selector->isMatch($image)) {
$encoding = $this->_encode();
$encoding = $this->encode();
$image->write($encoding, $x, $y);
if ($additional) {
$encoding->merge($additional);
}
return $encoding;
return $encoding;
}
}
return false;
}
/**
* Simply submits the form without the submit button
* value. Used when there is only one button or it
@ -348,8 +350,12 @@ class SimpleForm {
* @return hash Submitted values.
* @access public
*/
function submit() {
return $this->_encode();
function submit($additional = false) {
$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
* @package SimpleTest
* @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
*/
class SimpleFrameset {
var $_frameset;
var $_frames;
var $_focus;
var $_names;
private $frameset;
private $frames;
private $focus;
private $names;
/**
* Stashes the frameset page. Will make use of the
* browser to fetch the sub frames recursively.
* @param SimplePage $page Frameset page.
*/
function SimpleFrameset(&$page) {
$this->_frameset = &$page;
$this->_frames = array();
$this->_focus = false;
$this->_names = array();
function __construct($page) {
$this->frameset = $page;
$this->frames = array();
$this->focus = false;
$this->names = array();
}
/**
@ -45,10 +45,10 @@ class SimpleFrameset {
* @param string $name Name of frame in frameset.
* @access public
*/
function addFrame(&$page, $name = false) {
$this->_frames[] = &$page;
function addFrame($page, $name = false) {
$this->frames[] = $page;
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.
* @access public
*/
function setFrame($path, &$page) {
function setFrame($path, $page) {
$name = array_shift($path);
if (isset($this->_names[$name])) {
$index = $this->_names[$name];
if (isset($this->names[$name])) {
$index = $this->names[$name];
} else {
$index = $name - 1;
}
if (count($path) == 0) {
$this->_frames[$index] = &$page;
$this->frames[$index] = &$page;
return;
}
$this->_frames[$index]->setFrame($path, $page);
$this->frames[$index]->setFrame($path, $page);
}
/**
@ -82,12 +82,12 @@ class SimpleFrameset {
* @access public
*/
function getFrameFocus() {
if ($this->_focus === false) {
if ($this->focus === false) {
return array();
}
return array_merge(
array($this->_getPublicNameFromIndex($this->_focus)),
$this->_frames[$this->_focus]->getFrameFocus());
array($this->getPublicNameFromIndex($this->focus)),
$this->frames[$this->focus]->getFrameFocus());
}
/**
@ -98,8 +98,8 @@ class SimpleFrameset {
* @return integer/string Public name.
* @access private
*/
function _getPublicNameFromIndex($subject) {
foreach ($this->_names as $name => $index) {
protected function getPublicNameFromIndex($subject) {
foreach ($this->names as $name => $index) {
if ($subject == $index) {
return $name;
}
@ -116,15 +116,15 @@ class SimpleFrameset {
* @access public
*/
function setFrameFocusByIndex($choice) {
if (is_integer($this->_focus)) {
if ($this->_frames[$this->_focus]->hasFrames()) {
return $this->_frames[$this->_focus]->setFrameFocusByIndex($choice);
if (is_integer($this->focus)) {
if ($this->frames[$this->focus]->hasFrames()) {
return $this->frames[$this->focus]->setFrameFocusByIndex($choice);
}
}
if (($choice < 1) || ($choice > count($this->_frames))) {
if (($choice < 1) || ($choice > count($this->frames))) {
return false;
}
$this->_focus = $choice - 1;
$this->focus = $choice - 1;
return true;
}
@ -137,13 +137,13 @@ class SimpleFrameset {
* @access public
*/
function setFrameFocus($name) {
if (is_integer($this->_focus)) {
if ($this->_frames[$this->_focus]->hasFrames()) {
return $this->_frames[$this->_focus]->setFrameFocus($name);
if (is_integer($this->focus)) {
if ($this->frames[$this->focus]->hasFrames()) {
return $this->frames[$this->focus]->setFrameFocus($name);
}
}
if (in_array($name, array_keys($this->_names))) {
$this->_focus = $this->_names[$name];
if (in_array($name, array_keys($this->names))) {
$this->focus = $this->names[$name];
return true;
}
return false;
@ -154,17 +154,17 @@ class SimpleFrameset {
* @access public
*/
function clearFrameFocus() {
$this->_focus = false;
$this->_clearNestedFramesFocus();
$this->focus = false;
$this->clearNestedFramesFocus();
}
/**
* Clears the frame focus for any nested frames.
* @access private
*/
function _clearNestedFramesFocus() {
for ($i = 0; $i < count($this->_frames); $i++) {
$this->_frames[$i]->clearFrameFocus();
protected function clearNestedFramesFocus() {
for ($i = 0; $i < count($this->frames); $i++) {
$this->frames[$i]->clearFrameFocus();
}
}
@ -186,9 +186,9 @@ class SimpleFrameset {
*/
function getFrames() {
$report = array();
for ($i = 0; $i < count($this->_frames); $i++) {
$report[$this->_getPublicNameFromIndex($i)] =
$this->_frames[$i]->getFrames();
for ($i = 0; $i < count($this->frames); $i++) {
$report[$this->getPublicNameFromIndex($i)] =
$this->frames[$i]->getFrames();
}
return $report;
}
@ -200,12 +200,12 @@ class SimpleFrameset {
* @access public
*/
function getRaw() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getRaw();
if (is_integer($this->focus)) {
return $this->frames[$this->focus]->getRaw();
}
$raw = '';
for ($i = 0; $i < count($this->_frames); $i++) {
$raw .= $this->_frames[$i]->getRaw();
for ($i = 0; $i < count($this->frames); $i++) {
$raw .= $this->frames[$i]->getRaw();
}
return $raw;
}
@ -217,12 +217,12 @@ class SimpleFrameset {
* @access public
*/
function getText() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getText();
if (is_integer($this->focus)) {
return $this->frames[$this->focus]->getText();
}
$raw = '';
for ($i = 0; $i < count($this->_frames); $i++) {
$raw .= ' ' . $this->_frames[$i]->getText();
for ($i = 0; $i < count($this->frames); $i++) {
$raw .= ' ' . $this->frames[$i]->getText();
}
return trim($raw);
}
@ -233,10 +233,10 @@ class SimpleFrameset {
* @access public
*/
function getTransportError() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getTransportError();
if (is_integer($this->focus)) {
return $this->frames[$this->focus]->getTransportError();
}
return $this->_frameset->getTransportError();
return $this->frameset->getTransportError();
}
/**
@ -245,10 +245,10 @@ class SimpleFrameset {
* @access public
*/
function getMethod() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getMethod();
if (is_integer($this->focus)) {
return $this->frames[$this->focus]->getMethod();
}
return $this->_frameset->getMethod();
return $this->frameset->getMethod();
}
/**
@ -257,11 +257,11 @@ class SimpleFrameset {
* @access public
*/
function getUrl() {
if (is_integer($this->_focus)) {
$url = $this->_frames[$this->_focus]->getUrl();
$url->setTarget($this->_getPublicNameFromIndex($this->_focus));
if (is_integer($this->focus)) {
$url = $this->frames[$this->focus]->getUrl();
$url->setTarget($this->getPublicNameFromIndex($this->focus));
} else {
$url = $this->_frameset->getUrl();
$url = $this->frameset->getUrl();
}
return $url;
}
@ -272,10 +272,10 @@ class SimpleFrameset {
* @access public
*/
function getBaseUrl() {
if (is_integer($this->_focus)) {
$url = $this->_frames[$this->_focus]->getBaseUrl();
if (is_integer($this->focus)) {
$url = $this->frames[$this->focus]->getBaseUrl();
} else {
$url = $this->_frameset->getBaseUrl();
$url = $this->frameset->getBaseUrl();
}
return $url;
}
@ -288,7 +288,7 @@ class SimpleFrameset {
* @access public
*/
function expandUrl($url) {
return $this->_frameset->expandUrl($url);
return $this->frameset->expandUrl($url);
}
/**
@ -297,10 +297,10 @@ class SimpleFrameset {
* @access public
*/
function getRequestData() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getRequestData();
if (is_integer($this->focus)) {
return $this->frames[$this->focus]->getRequestData();
}
return $this->_frameset->getRequestData();
return $this->frameset->getRequestData();
}
/**
@ -309,10 +309,10 @@ class SimpleFrameset {
* @access public
*/
function getMimeType() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getMimeType();
if (is_integer($this->focus)) {
return $this->frames[$this->focus]->getMimeType();
}
return $this->_frameset->getMimeType();
return $this->frameset->getMimeType();
}
/**
@ -321,10 +321,10 @@ class SimpleFrameset {
* @access public
*/
function getResponseCode() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getResponseCode();
if (is_integer($this->focus)) {
return $this->frames[$this->focus]->getResponseCode();
}
return $this->_frameset->getResponseCode();
return $this->frameset->getResponseCode();
}
/**
@ -334,10 +334,10 @@ class SimpleFrameset {
* @access public
*/
function getAuthentication() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getAuthentication();
if (is_integer($this->focus)) {
return $this->frames[$this->focus]->getAuthentication();
}
return $this->_frameset->getAuthentication();
return $this->frameset->getAuthentication();
}
/**
@ -347,10 +347,10 @@ class SimpleFrameset {
* @access public
*/
function getRealm() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getRealm();
if (is_integer($this->focus)) {
return $this->frames[$this->focus]->getRealm();
}
return $this->_frameset->getRealm();
return $this->frameset->getRealm();
}
/**
@ -359,10 +359,10 @@ class SimpleFrameset {
* @access public
*/
function getRequest() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getRequest();
if (is_integer($this->focus)) {
return $this->frames[$this->focus]->getRequest();
}
return $this->_frameset->getRequest();
return $this->frameset->getRequest();
}
/**
@ -371,10 +371,10 @@ class SimpleFrameset {
* @access public
*/
function getHeaders() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getHeaders();
if (is_integer($this->focus)) {
return $this->frames[$this->focus]->getHeaders();
}
return $this->_frameset->getHeaders();
return $this->frameset->getHeaders();
}
/**
@ -383,7 +383,7 @@ class SimpleFrameset {
* @access public
*/
function getTitle() {
return $this->_frameset->getTitle();
return $this->frameset->getTitle();
}
/**
@ -392,11 +392,11 @@ class SimpleFrameset {
* @access public
*/
function getUrls() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getUrls();
if (is_integer($this->focus)) {
return $this->frames[$this->focus]->getUrls();
}
$urls = array();
foreach ($this->_frames as $frame) {
foreach ($this->frames as $frame) {
$urls = array_merge($urls, $frame->getUrls());
}
return array_values(array_unique($urls));
@ -410,16 +410,16 @@ class SimpleFrameset {
* @access public
*/
function getUrlsByLabel($label) {
if (is_integer($this->_focus)) {
return $this->_tagUrlsWithFrame(
$this->_frames[$this->_focus]->getUrlsByLabel($label),
$this->_focus);
if (is_integer($this->focus)) {
return $this->tagUrlsWithFrame(
$this->frames[$this->focus]->getUrlsByLabel($label),
$this->focus);
}
$urls = array();
foreach ($this->_frames as $index => $frame) {
foreach ($this->frames as $index => $frame) {
$urls = array_merge(
$urls,
$this->_tagUrlsWithFrame(
$this->tagUrlsWithFrame(
$frame->getUrlsByLabel($label),
$index));
}
@ -436,10 +436,10 @@ class SimpleFrameset {
* @access public
*/
function getUrlById($id) {
foreach ($this->_frames as $index => $frame) {
foreach ($this->frames as $index => $frame) {
if ($url = $frame->getUrlById($id)) {
if (! $url->gettarget()) {
$url->setTarget($this->_getPublicNameFromIndex($index));
$url->setTarget($this->getPublicNameFromIndex($index));
}
return $url;
}
@ -454,11 +454,11 @@ class SimpleFrameset {
* @return array List of tagged URLs.
* @access private
*/
function _tagUrlsWithFrame($urls, $frame) {
protected function tagUrlsWithFrame($urls, $frame) {
$tagged = array();
foreach ($urls as $url) {
if (! $url->getTarget()) {
$url->setTarget($this->_getPublicNameFromIndex($frame));
$url->setTarget($this->getPublicNameFromIndex($frame));
}
$tagged[] = $url;
}
@ -473,9 +473,8 @@ class SimpleFrameset {
* the button.
* @access public
*/
function &getFormBySubmit($selector) {
$form = &$this->_findForm('getFormBySubmit', $selector);
return $form;
function getFormBySubmit($selector) {
return $this->findForm('getFormBySubmit', $selector);
}
/**
@ -488,9 +487,8 @@ class SimpleFrameset {
* the image.
* @access public
*/
function &getFormByImage($selector) {
$form = &$this->_findForm('getFormByImage', $selector);
return $form;
function getFormByImage($selector) {
return $this->findForm('getFormByImage', $selector);
}
/**
@ -503,9 +501,8 @@ class SimpleFrameset {
* @return SimpleForm Form object containing the matching ID.
* @access public
*/
function &getFormById($id) {
$form = &$this->_findForm('getFormById', $id);
return $form;
function getFormById($id) {
return $this->findForm('getFormById', $id);
}
/**
@ -516,18 +513,17 @@ class SimpleFrameset {
* @return SimpleForm Form object containing the matching ID.
* @access private
*/
function &_findForm($method, $attribute) {
if (is_integer($this->_focus)) {
$form = &$this->_findFormInFrame(
$this->_frames[$this->_focus],
$this->_focus,
protected function findForm($method, $attribute) {
if (is_integer($this->focus)) {
return $this->findFormInFrame(
$this->frames[$this->focus],
$this->focus,
$method,
$attribute);
return $form;
}
for ($i = 0; $i < count($this->_frames); $i++) {
$form = &$this->_findFormInFrame(
$this->_frames[$i],
for ($i = 0; $i < count($this->frames); $i++) {
$form = $this->findFormInFrame(
$this->frames[$i],
$i,
$method,
$attribute);
@ -549,10 +545,10 @@ class SimpleFrameset {
* @return SimpleForm Form object containing the matching ID.
* @access private
*/
function &_findFormInFrame(&$page, $index, $method, $attribute) {
$form = &$this->_frames[$index]->$method($attribute);
protected function findFormInFrame($page, $index, $method, $attribute) {
$form = $this->frames[$index]->$method($attribute);
if (isset($form)) {
$form->setDefaultTarget($this->_getPublicNameFromIndex($index));
$form->setDefaultTarget($this->getPublicNameFromIndex($index));
}
return $form;
}
@ -566,11 +562,11 @@ class SimpleFrameset {
* @access public
*/
function setField($selector, $value) {
if (is_integer($this->_focus)) {
$this->_frames[$this->_focus]->setField($selector, $value);
if (is_integer($this->focus)) {
$this->frames[$this->focus]->setField($selector, $value);
} else {
for ($i = 0; $i < count($this->_frames); $i++) {
$this->_frames[$i]->setField($selector, $value);
for ($i = 0; $i < count($this->frames); $i++) {
$this->frames[$i]->setField($selector, $value);
}
}
}
@ -584,8 +580,8 @@ class SimpleFrameset {
* @access public
*/
function getField($selector) {
for ($i = 0; $i < count($this->_frames); $i++) {
$value = $this->_frames[$i]->getField($selector);
for ($i = 0; $i < count($this->frames); $i++) {
$value = $this->frames[$i]->getField($selector);
if (isset($value)) {
return $value;
}

View File

@ -3,7 +3,7 @@
* base include file for SimpleTest
* @package SimpleTest
* @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
*/
class SimpleRoute {
var $_url;
private $url;
/**
* Sets the target URL.
* @param SimpleUrl $url URL as object.
* @access public
*/
function SimpleRoute($url) {
$this->_url = $url;
function __construct($url) {
$this->url = $url;
}
/**
* Resource name.
* @return SimpleUrl Current url.
* @access protected
*/
function getUrl() {
return $this->_url;
return $this->url;
}
/**
* Creates the first line which is the actual request.
* @param string $method HTTP request method, usually GET.
* @return string Request line content.
* @access protected
*/
function _getRequestLine($method) {
return $method . ' ' . $this->_url->getPath() .
$this->_url->getEncodedRequest() . ' HTTP/1.0';
protected function getRequestLine($method) {
return $method . ' ' . $this->url->getPath() .
$this->url->getEncodedRequest() . ' HTTP/1.0';
}
/**
* Creates the host part of the request.
* @return string Host line content.
* @access protected
*/
function _getHostLine() {
$line = 'Host: ' . $this->_url->getHost();
if ($this->_url->getPort()) {
$line .= ':' . $this->_url->getPort();
protected function getHostLine() {
$line = 'Host: ' . $this->url->getHost();
if ($this->url->getPort()) {
$line .= ':' . $this->url->getPort();
}
return $line;
}
/**
* Opens a socket to the route.
* @param string $method HTTP request method, usually GET.
@ -72,21 +72,21 @@ class SimpleRoute {
* @return SimpleSocket New socket.
* @access public
*/
function &createConnection($method, $timeout) {
$default_port = ('https' == $this->_url->getScheme()) ? 443 : 80;
$socket = &$this->_createSocket(
$this->_url->getScheme() ? $this->_url->getScheme() : 'http',
$this->_url->getHost(),
$this->_url->getPort() ? $this->_url->getPort() : $default_port,
function createConnection($method, $timeout) {
$default_port = ('https' == $this->url->getScheme()) ? 443 : 80;
$socket = $this->createSocket(
$this->url->getScheme() ? $this->url->getScheme() : 'http',
$this->url->getHost(),
$this->url->getPort() ? $this->url->getPort() : $default_port,
$timeout);
if (! $socket->isError()) {
$socket->write($this->_getRequestLine($method) . "\r\n");
$socket->write($this->_getHostLine() . "\r\n");
$socket->write($this->getRequestLine($method) . "\r\n");
$socket->write($this->getHostLine() . "\r\n");
$socket->write("Connection: close\r\n");
}
return $socket;
}
/**
* Factory for socket.
* @param string $scheme Protocol to use.
@ -96,13 +96,14 @@ class SimpleRoute {
* @return SimpleSocket/SimpleSecureSocket New socket.
* @access protected
*/
function &_createSocket($scheme, $host, $port, $timeout) {
if (in_array($scheme, array('https'))) {
$socket = &new SimpleSecureSocket($host, $port, $timeout);
protected function createSocket($scheme, $host, $port, $timeout) {
if (in_array($scheme, array('file'))) {
return new SimpleFileSocket($this->url);
} elseif (in_array($scheme, array('https'))) {
return new SimpleSecureSocket($host, $port, $timeout);
} else {
$socket = &new SimpleSocket($host, $port, $timeout);
return new SimpleSocket($host, $port, $timeout);
}
return $socket;
}
}
@ -113,10 +114,10 @@ class SimpleRoute {
* @subpackage WebTester
*/
class SimpleProxyRoute extends SimpleRoute {
var $_proxy;
var $_username;
var $_password;
private $proxy;
private $username;
private $password;
/**
* Stashes the proxy address.
* @param SimpleUrl $url URL as object.
@ -125,13 +126,13 @@ class SimpleProxyRoute extends SimpleRoute {
* @param string $password Password for autentication.
* @access public
*/
function SimpleProxyRoute($url, $proxy, $username = false, $password = false) {
$this->SimpleRoute($url);
$this->_proxy = $proxy;
$this->_username = $username;
$this->_password = $password;
function __construct($url, $proxy, $username = false, $password = false) {
parent::__construct($url);
$this->proxy = $proxy;
$this->username = $username;
$this->password = $password;
}
/**
* Creates the first line which is the actual request.
* @param string $method HTTP request method, usually GET.
@ -139,26 +140,26 @@ class SimpleProxyRoute extends SimpleRoute {
* @return string Request line content.
* @access protected
*/
function _getRequestLine($method) {
function getRequestLine($method) {
$url = $this->getUrl();
$scheme = $url->getScheme() ? $url->getScheme() : 'http';
$port = $url->getPort() ? ':' . $url->getPort() : '';
return $method . ' ' . $scheme . '://' . $url->getHost() . $port .
$url->getPath() . $url->getEncodedRequest() . ' HTTP/1.0';
}
/**
* Creates the host part of the request.
* @param SimpleUrl $url URL as object.
* @return string Host line content.
* @access protected
*/
function _getHostLine() {
$host = 'Host: ' . $this->_proxy->getHost();
$port = $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080;
function getHostLine() {
$host = 'Host: ' . $this->proxy->getHost();
$port = $this->proxy->getPort() ? $this->proxy->getPort() : 8080;
return "$host:$port";
}
/**
* Opens a socket to the route.
* @param string $method HTTP request method, usually GET.
@ -166,20 +167,20 @@ class SimpleProxyRoute extends SimpleRoute {
* @return SimpleSocket New socket.
* @access public
*/
function &createConnection($method, $timeout) {
$socket = &$this->_createSocket(
$this->_proxy->getScheme() ? $this->_proxy->getScheme() : 'http',
$this->_proxy->getHost(),
$this->_proxy->getPort() ? $this->_proxy->getPort() : 8080,
function createConnection($method, $timeout) {
$socket = $this->createSocket(
$this->proxy->getScheme() ? $this->proxy->getScheme() : 'http',
$this->proxy->getHost(),
$this->proxy->getPort() ? $this->proxy->getPort() : 8080,
$timeout);
if ($socket->isError()) {
return $socket;
}
$socket->write($this->_getRequestLine($method) . "\r\n");
$socket->write($this->_getHostLine() . "\r\n");
if ($this->_username && $this->_password) {
$socket->write($this->getRequestLine($method) . "\r\n");
$socket->write($this->getHostLine() . "\r\n");
if ($this->username && $this->password) {
$socket->write('Proxy-Authorization: Basic ' .
base64_encode($this->_username . ':' . $this->_password) .
base64_encode($this->username . ':' . $this->password) .
"\r\n");
}
$socket->write("Connection: close\r\n");
@ -194,11 +195,11 @@ class SimpleProxyRoute extends SimpleRoute {
* @subpackage WebTester
*/
class SimpleHttpRequest {
var $_route;
var $_encoding;
var $_headers;
var $_cookies;
private $route;
private $encoding;
private $headers;
private $cookies;
/**
* Builds the socket request from the different pieces.
* These include proxy information, URL, cookies, headers,
@ -208,13 +209,13 @@ class SimpleHttpRequest {
* request.
* @access public
*/
function SimpleHttpRequest(&$route, $encoding) {
$this->_route = &$route;
$this->_encoding = $encoding;
$this->_headers = array();
$this->_cookies = array();
function __construct($route, $encoding) {
$this->route = $route;
$this->encoding = $encoding;
$this->headers = array();
$this->cookies = array();
}
/**
* Dispatches the content to the route's socket.
* @param integer $timeout Connection timeout.
@ -223,15 +224,14 @@ class SimpleHttpRequest {
* complete web page.
* @access public
*/
function &fetch($timeout) {
$socket = &$this->_route->createConnection($this->_encoding->getMethod(), $timeout);
function fetch($timeout) {
$socket = $this->route->createConnection($this->encoding->getMethod(), $timeout);
if (! $socket->isError()) {
$this->_dispatchRequest($socket, $this->_encoding);
$this->dispatchRequest($socket, $this->encoding);
}
$response = &$this->_createResponse($socket);
return $response;
return $this->createResponse($socket);
}
/**
* Sends the headers.
* @param SimpleSocket $socket Open socket.
@ -240,27 +240,27 @@ class SimpleHttpRequest {
* @param SimpleFormEncoding $encoding Content to send with request.
* @access private
*/
function _dispatchRequest(&$socket, $encoding) {
foreach ($this->_headers as $header_line) {
protected function dispatchRequest($socket, $encoding) {
foreach ($this->headers as $header_line) {
$socket->write($header_line . "\r\n");
}
if (count($this->_cookies) > 0) {
$socket->write("Cookie: " . implode(";", $this->_cookies) . "\r\n");
if (count($this->cookies) > 0) {
$socket->write("Cookie: " . implode(";", $this->cookies) . "\r\n");
}
$encoding->writeHeadersTo($socket);
$socket->write("\r\n");
$encoding->writeTo($socket);
}
/**
* Adds a header line to the request.
* @param string $header_line Text of full header line.
* @access public
*/
function addHeaderLine($header_line) {
$this->_headers[] = $header_line;
$this->headers[] = $header_line;
}
/**
* Reads all the relevant cookies from the
* cookie jar.
@ -269,20 +269,21 @@ class SimpleHttpRequest {
* @access public
*/
function readCookiesFromJar($jar, $url) {
$this->_cookies = $jar->selectAsPairs($url);
$this->cookies = $jar->selectAsPairs($url);
}
/**
* Wraps the socket in a response parser.
* @param SimpleSocket $socket Responding socket.
* @return SimpleHttpResponse Parsed response object.
* @access protected
*/
function &_createResponse(&$socket) {
$response = &new SimpleHttpResponse(
protected function createResponse($socket) {
$response = new SimpleHttpResponse(
$socket,
$this->_route->getUrl(),
$this->_encoding);
$this->route->getUrl(),
$this->encoding);
$socket->close();
return $response;
}
}
@ -293,61 +294,61 @@ class SimpleHttpRequest {
* @subpackage WebTester
*/
class SimpleHttpHeaders {
var $_raw_headers;
var $_response_code;
var $_http_version;
var $_mime_type;
var $_location;
var $_cookies;
var $_authentication;
var $_realm;
private $raw_headers;
private $response_code;
private $http_version;
private $mime_type;
private $location;
private $cookies;
private $authentication;
private $realm;
/**
* Parses the incoming header block.
* @param string $headers Header block.
* @access public
*/
function SimpleHttpHeaders($headers) {
$this->_raw_headers = $headers;
$this->_response_code = false;
$this->_http_version = false;
$this->_mime_type = '';
$this->_location = false;
$this->_cookies = array();
$this->_authentication = false;
$this->_realm = false;
function __construct($headers) {
$this->raw_headers = $headers;
$this->response_code = false;
$this->http_version = false;
$this->mime_type = '';
$this->location = false;
$this->cookies = array();
$this->authentication = false;
$this->realm = false;
foreach (explode("\r\n", $headers) as $header_line) {
$this->_parseHeaderLine($header_line);
$this->parseHeaderLine($header_line);
}
}
/**
* Accessor for parsed HTTP protocol version.
* @return integer HTTP error code.
* @access public
*/
function getHttpVersion() {
return $this->_http_version;
return $this->http_version;
}
/**
* Accessor for raw header block.
* @return string All headers as raw string.
* @access public
*/
function getRaw() {
return $this->_raw_headers;
return $this->raw_headers;
}
/**
* Accessor for parsed HTTP error code.
* @return integer HTTP error code.
* @access public
*/
function getResponseCode() {
return (integer)$this->_response_code;
return (integer)$this->response_code;
}
/**
* Returns the redirected URL or false if
* no redirection.
@ -355,19 +356,19 @@ class SimpleHttpHeaders {
* @access public
*/
function getLocation() {
return $this->_location;
return $this->location;
}
/**
* Test to see if the response is a valid redirect.
* @return boolean True if valid redirect.
* @access public
*/
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();
}
/**
* Test to see if the response is an authentication
* challenge.
@ -375,46 +376,46 @@ class SimpleHttpHeaders {
* @access public
*/
function isChallenge() {
return ($this->_response_code == 401) &&
(boolean)$this->_authentication &&
(boolean)$this->_realm;
return ($this->response_code == 401) &&
(boolean)$this->authentication &&
(boolean)$this->realm;
}
/**
* Accessor for MIME type header information.
* @return string MIME type.
* @access public
*/
function getMimeType() {
return $this->_mime_type;
return $this->mime_type;
}
/**
* Accessor for authentication type.
* @return string Type.
* @access public
*/
function getAuthentication() {
return $this->_authentication;
return $this->authentication;
}
/**
* Accessor for security realm.
* @return string Realm.
* @access public
*/
function getRealm() {
return $this->_realm;
return $this->realm;
}
/**
* Writes new cookies to the cookie jar.
* @param SimpleCookieJar $jar Jar to write to.
* @param SimpleUrl $url Host and path to write under.
* @access public
*/
function writeCookiesToJar(&$jar, $url) {
foreach ($this->_cookies as $cookie) {
function writeCookiesToJar($jar, $url) {
foreach ($this->cookies as $cookie) {
$jar->setCookie(
$cookie->getName(),
$cookie->getValue(),
@ -430,33 +431,33 @@ class SimpleHttpHeaders {
* @param string $header_line One line of header.
* @access protected
*/
function _parseHeaderLine($header_line) {
protected function parseHeaderLine($header_line) {
if (preg_match('/HTTP\/(\d+\.\d+)\s+(\d+)/i', $header_line, $matches)) {
$this->_http_version = $matches[1];
$this->_response_code = $matches[2];
$this->http_version = $matches[1];
$this->response_code = $matches[2];
}
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)) {
$this->_location = trim($matches[1]);
$this->location = trim($matches[1]);
}
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)) {
$this->_authentication = $matches[1];
$this->_realm = trim($matches[2]);
$this->authentication = $matches[1];
$this->realm = trim($matches[2]);
}
}
/**
* Parse the Set-cookie content.
* @param string $cookie_line Text after "Set-cookie:"
* @return SimpleCookie New cookie object.
* @access private
*/
function _parseCookie($cookie_line) {
protected function parseCookie($cookie_line) {
$parts = explode(";", $cookie_line);
$cookie = array();
preg_match('/\s*(.*?)\s*=(.*)/', array_shift($parts), $cookie);
@ -479,12 +480,12 @@ class SimpleHttpHeaders {
* @subpackage WebTester
*/
class SimpleHttpResponse extends SimpleStickyError {
var $_url;
var $_encoding;
var $_sent;
var $_content;
var $_headers;
private $url;
private $encoding;
private $sent;
private $content;
private $headers;
/**
* Constructor. Reads and parses the incoming
* content and headers.
@ -494,74 +495,77 @@ class SimpleHttpResponse extends SimpleStickyError {
* @param mixed $encoding Record of content sent.
* @access public
*/
function SimpleHttpResponse(&$socket, $url, $encoding) {
$this->SimpleStickyError();
$this->_url = $url;
$this->_encoding = $encoding;
$this->_sent = $socket->getSent();
$this->_content = false;
$raw = $this->_readAll($socket);
function __construct($socket, $url, $encoding) {
parent::__construct();
$this->url = $url;
$this->encoding = $encoding;
$this->sent = $socket->getSent();
$this->content = false;
$raw = $this->readAll($socket);
if ($socket->isError()) {
$this->_setError('Error reading socket [' . $socket->getError() . ']');
$this->setError('Error reading socket [' . $socket->getError() . ']');
return;
}
$this->_parse($raw);
$this->parse($raw);
}
/**
* Splits up the headers and the rest of the content.
* @param string $raw Content to parse.
* @access private
*/
function _parse($raw) {
protected function parse($raw) {
if (! $raw) {
$this->_setError('Nothing fetched');
$this->_headers = &new SimpleHttpHeaders('');
$this->setError('Nothing fetched');
$this->headers = new SimpleHttpHeaders('');
} elseif ('file' == $this->url->getScheme()) {
$this->headers = new SimpleHttpHeaders('');
$this->content = $raw;
} elseif (! strstr($raw, "\r\n\r\n")) {
$this->_setError('Could not split headers from content');
$this->_headers = &new SimpleHttpHeaders($raw);
$this->setError('Could not split headers from content');
$this->headers = new SimpleHttpHeaders($raw);
} else {
list($headers, $this->_content) = explode("\r\n\r\n", $raw, 2);
$this->_headers = &new SimpleHttpHeaders($headers);
list($headers, $this->content) = explode("\r\n\r\n", $raw, 2);
$this->headers = new SimpleHttpHeaders($headers);
}
}
/**
* Original request method.
* @return string GET, POST or HEAD.
* @access public
*/
function getMethod() {
return $this->_encoding->getMethod();
return $this->encoding->getMethod();
}
/**
* Resource name.
* @return SimpleUrl Current url.
* @access public
*/
function getUrl() {
return $this->_url;
return $this->url;
}
/**
* Original request data.
* @return mixed Sent content.
* @access public
*/
function getRequestData() {
return $this->_encoding;
return $this->encoding;
}
/**
* Raw request that was sent down the wire.
* @return string Bytes actually sent.
* @access public
*/
function getSent() {
return $this->_sent;
return $this->sent;
}
/**
* Accessor for the content after the last
* header line.
@ -569,9 +573,9 @@ class SimpleHttpResponse extends SimpleStickyError {
* @access public
*/
function getContent() {
return $this->_content;
return $this->content;
}
/**
* Accessor for header block. The response is the
* combination of this and the content.
@ -579,18 +583,18 @@ class SimpleHttpResponse extends SimpleStickyError {
* @access public
*/
function getHeaders() {
return $this->_headers;
return $this->headers;
}
/**
* Accessor for any new cookies.
* @return array List of new cookies.
* @access public
*/
function getNewCookies() {
return $this->_headers->getNewCookies();
return $this->headers->getNewCookies();
}
/**
* Reads the whole of the socket output into a
* single string.
@ -599,14 +603,14 @@ class SimpleHttpResponse extends SimpleStickyError {
* else false.
* @access private
*/
function _readAll(&$socket) {
protected function readAll($socket) {
$all = '';
while (! $this->_isLastPacket($next = $socket->read())) {
while (! $this->isLastPacket($next = $socket->read())) {
$all .= $next;
}
return $all;
}
/**
* Test to see if the packet from the socket is the
* last one.
@ -614,11 +618,11 @@ class SimpleHttpResponse extends SimpleStickyError {
* @return boolean True if empty or EOF.
* @access private
*/
function _isLastPacket($packet) {
protected function isLastPacket($packet) {
if (is_string($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
* @package SimpleTest
* @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
*/
class SimpleInvoker {
var $_test_case;
private $test_case;
/**
* Stashes the test case for later.
* @param SimpleTestCase $test_case Test case to run.
*/
function SimpleInvoker(&$test_case) {
$this->_test_case = &$test_case;
function __construct($test_case) {
$this->test_case = $test_case;
}
/**
@ -43,8 +43,8 @@ class SimpleInvoker {
* @return SimpleTestCase Test case.
* @access public
*/
function &getTestCase() {
return $this->_test_case;
function getTestCase() {
return $this->test_case;
}
/**
@ -54,7 +54,7 @@ class SimpleInvoker {
* @access public
*/
function before($method) {
$this->_test_case->before($method);
$this->test_case->before($method);
}
/**
@ -64,9 +64,9 @@ class SimpleInvoker {
* @access public
*/
function invoke($method) {
$this->_test_case->setUp();
$this->_test_case->$method();
$this->_test_case->tearDown();
$this->test_case->setUp();
$this->test_case->$method();
$this->test_case->tearDown();
}
/**
@ -76,7 +76,7 @@ class SimpleInvoker {
* @access public
*/
function after($method) {
$this->_test_case->after($method);
$this->test_case->after($method);
}
}
@ -87,14 +87,14 @@ class SimpleInvoker {
* @subpackage UnitTester
*/
class SimpleInvokerDecorator {
var $_invoker;
private $invoker;
/**
* Stores the invoker to wrap.
* @param SimpleInvoker $invoker Test method runner.
*/
function SimpleInvokerDecorator(&$invoker) {
$this->_invoker = &$invoker;
function __construct($invoker) {
$this->invoker = $invoker;
}
/**
@ -102,8 +102,8 @@ class SimpleInvokerDecorator {
* @return SimpleTestCase Test case.
* @access public
*/
function &getTestCase() {
return $this->_invoker->getTestCase();
function getTestCase() {
return $this->invoker->getTestCase();
}
/**
@ -113,7 +113,7 @@ class SimpleInvokerDecorator {
* @access public
*/
function before($method) {
$this->_invoker->before($method);
$this->invoker->before($method);
}
/**
@ -123,7 +123,7 @@ class SimpleInvokerDecorator {
* @access public
*/
function invoke($method) {
$this->_invoker->invoke($method);
$this->invoker->invoke($method);
}
/**
@ -133,7 +133,7 @@ class SimpleInvokerDecorator {
* @access public
*/
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
* @package SimpleTest
* @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
*/
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__) . '/form.php');
require_once(dirname(__FILE__) . '/selector.php');
/**#@-*/
/**
* Creates tags and widgets given HTML tag
* attributes.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleTagBuilder {
/**
* Factory for the tag objects. Creates the
* appropriate tag object for the incoming tag name
* and attributes.
* @param string $name HTML tag name.
* @param hash $attributes Element attributes.
* @return SimpleTag Tag object.
* @access public
*/
function createTag($name, $attributes) {
static $map = array(
'a' => 'SimpleAnchorTag',
'title' => 'SimpleTitleTag',
'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.
* @package SimpleTest
* @subpackage WebTester
*/
class SimplePage {
var $_links;
var $_title;
var $_last_widget;
var $_label;
var $_left_over_labels;
var $_open_forms;
var $_complete_forms;
var $_frameset;
var $_frames;
var $_frameset_nesting_level;
var $_transport_error;
var $_raw;
var $_text;
var $_sent;
var $_headers;
var $_method;
var $_url;
var $_base = false;
var $_request_data;
private $links = array();
private $title = false;
private $last_widget;
private $label;
private $forms = array();
private $frames = array();
private $transport_error;
private $raw;
private $text = false;
private $sent;
private $headers;
private $method;
private $url;
private $base = false;
private $request_data;
/**
* Parses a page ready to access it's contents.
* @param SimpleHttpResponse $response Result of HTTP fetch.
* @access public
*/
function SimplePage($response = false) {
$this->_links = array();
$this->_title = false;
$this->_left_over_labels = array();
$this->_open_forms = array();
$this->_complete_forms = array();
$this->_frameset = false;
$this->_frames = array();
$this->_frameset_nesting_level = 0;
$this->_text = false;
function __construct($response = false) {
if ($response) {
$this->_extractResponse($response);
$this->extractResponse($response);
} else {
$this->_noResponse();
$this->noResponse();
}
}
@ -379,28 +56,28 @@ class SimplePage {
* @param SimpleHttpResponse $response Response being parsed.
* @access private
*/
function _extractResponse($response) {
$this->_transport_error = $response->getError();
$this->_raw = $response->getContent();
$this->_sent = $response->getSent();
$this->_headers = $response->getHeaders();
$this->_method = $response->getMethod();
$this->_url = $response->getUrl();
$this->_request_data = $response->getRequestData();
protected function extractResponse($response) {
$this->transport_error = $response->getError();
$this->raw = $response->getContent();
$this->sent = $response->getSent();
$this->headers = $response->getHeaders();
$this->method = $response->getMethod();
$this->url = $response->getUrl();
$this->request_data = $response->getRequestData();
}
/**
* Sets up a missing response.
* @access private
*/
function _noResponse() {
$this->_transport_error = 'No page fetched yet';
$this->_raw = false;
$this->_sent = false;
$this->_headers = false;
$this->_method = 'GET';
$this->_url = false;
$this->_request_data = false;
protected function noResponse() {
$this->transport_error = 'No page fetched yet';
$this->raw = false;
$this->sent = false;
$this->headers = false;
$this->method = 'GET';
$this->url = false;
$this->request_data = false;
}
/**
@ -409,7 +86,7 @@ class SimplePage {
* @access public
*/
function getRequest() {
return $this->_sent;
return $this->sent;
}
/**
@ -418,7 +95,7 @@ class SimplePage {
* @access public
*/
function getRaw() {
return $this->_raw;
return $this->raw;
}
/**
@ -428,10 +105,10 @@ class SimplePage {
* @access public
*/
function getText() {
if (! $this->_text) {
$this->_text = SimpleHtmlSaxParser::normalise($this->_raw);
if (! $this->text) {
$this->text = SimplePage::normalise($this->raw);
}
return $this->_text;
return $this->text;
}
/**
@ -440,8 +117,8 @@ class SimplePage {
* @access public
*/
function getHeaders() {
if ($this->_headers) {
return $this->_headers->getRaw();
if ($this->headers) {
return $this->headers->getRaw();
}
return false;
}
@ -452,7 +129,7 @@ class SimplePage {
* @access public
*/
function getMethod() {
return $this->_method;
return $this->method;
}
/**
@ -461,7 +138,7 @@ class SimplePage {
* @access public
*/
function getUrl() {
return $this->_url;
return $this->url;
}
/**
@ -470,7 +147,7 @@ class SimplePage {
* @access public
*/
function getBaseUrl() {
return $this->_base;
return $this->base;
}
/**
@ -479,7 +156,7 @@ class SimplePage {
* @access public
*/
function getRequestData() {
return $this->_request_data;
return $this->request_data;
}
/**
@ -488,7 +165,7 @@ class SimplePage {
* @access public
*/
function getTransportError() {
return $this->_transport_error;
return $this->transport_error;
}
/**
@ -497,8 +174,8 @@ class SimplePage {
* @access public
*/
function getMimeType() {
if ($this->_headers) {
return $this->_headers->getMimeType();
if ($this->headers) {
return $this->headers->getMimeType();
}
return false;
}
@ -509,8 +186,8 @@ class SimplePage {
* @access public
*/
function getResponseCode() {
if ($this->_headers) {
return $this->_headers->getResponseCode();
if ($this->headers) {
return $this->headers->getResponseCode();
}
return false;
}
@ -522,8 +199,8 @@ class SimplePage {
* @access public
*/
function getAuthentication() {
if ($this->_headers) {
return $this->_headers->getAuthentication();
if ($this->headers) {
return $this->headers->getAuthentication();
}
return false;
}
@ -535,8 +212,8 @@ class SimplePage {
* @access public
*/
function getRealm() {
if ($this->_headers) {
return $this->_headers->getRealm();
if ($this->headers) {
return $this->headers->getRealm();
}
return false;
}
@ -579,129 +256,10 @@ class SimplePage {
}
/**
* Adds a tag to the page.
* @param SimpleTag $tag Tag to accept.
* @access public
* TODO: write docs
*/
function acceptTag(&$tag) {
if ($tag->getTagName() == "a") {
$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);
function setFrames($frames) {
$this->frames = $frames;
}
/**
@ -710,7 +268,7 @@ class SimplePage {
* @return boolean True if absolute.
* @access protected
*/
function _linkIsAbsolute($url) {
protected function linkIsAbsolute($url) {
$parsed = new SimpleUrl($url);
return (boolean)($parsed->getScheme() && $parsed->getHost());
}
@ -718,28 +276,17 @@ class SimplePage {
/**
* Adds a link to the page.
* @param SimpleAnchorTag $tag Link to accept.
* @access protected
*/
function _addLink($tag) {
$this->_links[] = $tag;
function addLink($tag) {
$this->links[] = $tag;
}
/**
* Marker for end of complete page. Any work in
* progress can now be closed.
* @access public
* Set the forms
* @param array $forms An array of SimpleForm objects
*/
function acceptPageEnd() {
while (count($this->_open_forms)) {
$this->_complete_forms[] = array_pop($this->_open_forms);
}
foreach ($this->_left_over_labels as $label) {
for ($i = 0, $count = count($this->_complete_forms); $i < $count; $i++) {
$this->_complete_forms[$i]->attachLabelBySelector(
new SimpleById($label->getFor()),
$label->getText());
}
}
function setForms($forms) {
$this->forms = $forms;
}
/**
@ -748,7 +295,7 @@ class SimplePage {
* @access public
*/
function hasFrames() {
return (boolean)$this->_frameset;
return count($this->frames) > 0;
}
/**
@ -761,13 +308,13 @@ class SimplePage {
* @access public
*/
function getFrameset() {
if (! $this->_frameset) {
if (! $this->hasFrames()) {
return false;
}
$urls = array();
for ($i = 0; $i < count($this->_frames); $i++) {
$name = $this->_frames[$i]->getAttribute('name');
$url = new SimpleUrl($this->_frames[$i]->getAttribute('src'));
for ($i = 0; $i < count($this->frames); $i++) {
$name = $this->frames[$i]->getAttribute('name');
$url = new SimpleUrl($this->frames[$i]->getAttribute('src'));
$urls[$name ? $name : $i + 1] = $this->expandUrl($url);
}
return $urls;
@ -791,8 +338,8 @@ class SimplePage {
*/
function getUrls() {
$all = array();
foreach ($this->_links as $link) {
$url = $this->_getUrlFromLink($link);
foreach ($this->links as $link) {
$url = $this->getUrlFromLink($link);
$all[] = $url->asString();
}
return $all;
@ -807,9 +354,9 @@ class SimplePage {
*/
function getUrlsByLabel($label) {
$matches = array();
foreach ($this->_links as $link) {
foreach ($this->links as $link) {
if ($link->getText() == $label) {
$matches[] = $this->_getUrlFromLink($link);
$matches[] = $this->getUrlFromLink($link);
}
}
return $matches;
@ -822,9 +369,9 @@ class SimplePage {
* @access public
*/
function getUrlById($id) {
foreach ($this->_links as $link) {
foreach ($this->links as $link) {
if ($link->getAttribute('id') === (string)$id) {
return $this->_getUrlFromLink($link);
return $this->getUrlFromLink($link);
}
}
return false;
@ -836,7 +383,7 @@ class SimplePage {
* @return SimpleUrl URL with frame target if any.
* @access private
*/
function _getUrlFromLink($link) {
protected function getUrlFromLink($link) {
$url = $this->expandUrl($link->getHref());
if ($link->getAttribute('target')) {
$url->setTarget($link->getAttribute('target'));
@ -861,21 +408,18 @@ class SimplePage {
/**
* Sets the base url for the page.
* @param SimpleTag $tag Base URL for page.
* @access protected
* @param string $url Base URL for page.
*/
function _setBase(&$tag) {
$url = $tag->getAttribute('href');
$this->_base = new SimpleUrl($url);
function setBase($url) {
$this->base = new SimpleUrl($url);
}
/**
* Sets the title tag contents.
* @param SimpleTitleTag $tag Title of page.
* @access protected
*/
function _setTitle(&$tag) {
$this->_title = &$tag;
function setTitle($tag) {
$this->title = $tag;
}
/**
@ -884,8 +428,8 @@ class SimplePage {
* @access public
*/
function getTitle() {
if ($this->_title) {
return $this->_title->getText();
if ($this->title) {
return $this->title->getText();
}
return false;
}
@ -898,14 +442,13 @@ class SimplePage {
* the button.
* @access public
*/
function &getFormBySubmit($selector) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->hasSubmit($selector)) {
return $this->_complete_forms[$i];
function getFormBySubmit($selector) {
for ($i = 0; $i < count($this->forms); $i++) {
if ($this->forms[$i]->hasSubmit($selector)) {
return $this->forms[$i];
}
}
$null = null;
return $null;
return null;
}
/**
@ -916,14 +459,13 @@ class SimplePage {
* the image.
* @access public
*/
function &getFormByImage($selector) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->hasImage($selector)) {
return $this->_complete_forms[$i];
function getFormByImage($selector) {
for ($i = 0; $i < count($this->forms); $i++) {
if ($this->forms[$i]->hasImage($selector)) {
return $this->forms[$i];
}
}
$null = null;
return $null;
return null;
}
/**
@ -934,14 +476,13 @@ class SimplePage {
* @return SimpleForm Form object containing the matching ID.
* @access public
*/
function &getFormById($id) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->getId() == $id) {
return $this->_complete_forms[$i];
function getFormById($id) {
for ($i = 0; $i < count($this->forms); $i++) {
if ($this->forms[$i]->getId() == $id) {
return $this->forms[$i];
}
}
$null = null;
return $null;
return null;
}
/**
@ -954,8 +495,8 @@ class SimplePage {
*/
function setField($selector, $value, $position=false) {
$is_set = false;
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->setField($selector, $value, $position)) {
for ($i = 0; $i < count($this->forms); $i++) {
if ($this->forms[$i]->setField($selector, $value, $position)) {
$is_set = true;
}
}
@ -971,13 +512,31 @@ class SimplePage {
* @access public
*/
function getField($selector) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
$value = $this->_complete_forms[$i]->getValue($selector);
for ($i = 0; $i < count($this->forms); $i++) {
$value = $this->forms[$i]->getValue($selector);
if (isset($value)) {
return $value;
}
}
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
* @package SimpleTest
* @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() {
return false;
}
/**
* Scans for final methods, but as it's PHP 4 there
* aren't any.

View File

@ -3,7 +3,7 @@
* base include file for SimpleTest
* @package SimpleTest
* @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
*/
class SimpleReflection {
var $_interface;
private $interface;
/**
* Stashes the class/interface.
* @param string $interface Class or interface
* to inspect.
*/
function SimpleReflection($interface) {
$this->_interface = $interface;
function __construct($interface) {
$this->interface = $interface;
}
/**
@ -31,10 +31,10 @@ class SimpleReflection {
* @access public
*/
function classExists() {
if (! class_exists($this->_interface)) {
if (! class_exists($this->interface)) {
return false;
}
$reflection = new ReflectionClass($this->_interface);
$reflection = new ReflectionClass($this->interface);
return ! $reflection->isInterface();
}
@ -45,7 +45,7 @@ class SimpleReflection {
* @access public
*/
function classExistsSansAutoload() {
return class_exists($this->_interface, false);
return class_exists($this->interface, false);
}
/**
@ -55,7 +55,7 @@ class SimpleReflection {
* @access public
*/
function classOrInterfaceExists() {
return $this->_classOrInterfaceExistsWithAutoload($this->_interface, true);
return $this->classOrInterfaceExistsWithAutoload($this->interface, true);
}
/**
@ -65,7 +65,7 @@ class SimpleReflection {
* @access public
*/
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.
* @access private
*/
function _classOrInterfaceExistsWithAutoload($interface, $autoload) {
protected function classOrInterfaceExistsWithAutoload($interface, $autoload) {
if (function_exists('interface_exists')) {
if (interface_exists($this->_interface, $autoload)) {
if (interface_exists($this->interface, $autoload)) {
return true;
}
}
return class_exists($this->_interface, $autoload);
return class_exists($this->interface, $autoload);
}
/**
@ -92,7 +92,7 @@ class SimpleReflection {
* @access public
*/
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
*/
function getInterfaces() {
$reflection = new ReflectionClass($this->_interface);
$reflection = new ReflectionClass($this->interface);
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.
* @access private
*/
function _isInterfaceMethod($method) {
protected function isInterfaceMethod($method) {
return in_array($method, $this->getInterfaceMethods());
}
@ -141,7 +141,7 @@ class SimpleReflection {
* @access public
*/
function getParent() {
$reflection = new ReflectionClass($this->_interface);
$reflection = new ReflectionClass($this->interface);
$parent = $reflection->getParentClass();
if ($parent) {
return $parent->getName();
@ -155,7 +155,7 @@ class SimpleReflection {
* @access public
*/
function isAbstract() {
$reflection = new ReflectionClass($this->_interface);
$reflection = new ReflectionClass($this->interface);
return $reflection->isAbstract();
}
@ -165,7 +165,7 @@ class SimpleReflection {
* @access public
*/
function isInterface() {
$reflection = new ReflectionClass($this->_interface);
$reflection = new ReflectionClass($this->interface);
return $reflection->isInterface();
}
@ -176,7 +176,7 @@ class SimpleReflection {
* @access public
*/
function hasFinal() {
$reflection = new ReflectionClass($this->_interface);
$reflection = new ReflectionClass($this->interface);
foreach ($reflection->getMethods() as $method) {
if ($method->isFinal()) {
return true;
@ -193,7 +193,7 @@ class SimpleReflection {
* @returns array List of parent interface names.
* @access private
*/
function _onlyParents($interfaces) {
protected function onlyParents($interfaces) {
$parents = array();
$blacklist = array();
foreach ($interfaces as $interface) {
@ -218,8 +218,8 @@ class SimpleReflection {
* @return bool true if method is abstract, else false
* @access private
*/
function _isAbstractMethod($name) {
$interface = new ReflectionClass($this->_interface);
protected function isAbstractMethod($name) {
$interface = new ReflectionClass($this->interface);
if (! $interface->hasMethod($name)) {
return false;
}
@ -232,8 +232,8 @@ class SimpleReflection {
* @return bool true if method is the constructor
* @access private
*/
function _isConstructor($name) {
return ($name == '__construct') || ($name == $this->_interface);
protected function isConstructor($name) {
return ($name == '__construct') || ($name == $this->interface);
}
/**
@ -242,8 +242,8 @@ class SimpleReflection {
* @return bool true if method is abstract in parent, else false
* @access private
*/
function _isAbstractMethodInParents($name) {
$interface = new ReflectionClass($this->_interface);
protected function isAbstractMethodInParents($name) {
$interface = new ReflectionClass($this->interface);
$parent = $interface->getParentClass();
while($parent) {
if (! $parent->hasMethod($name)) {
@ -263,8 +263,8 @@ class SimpleReflection {
* @return bool true if method is static, else false
* @access private
*/
function _isStaticMethod($name) {
$interface = new ReflectionClass($this->_interface);
protected function isStaticMethod($name) {
$interface = new ReflectionClass($this->interface);
if (! $interface->hasMethod($name)) {
return false;
}
@ -294,13 +294,19 @@ class SimpleReflection {
if ($name == '__toString') {
return "function $name()";
}
if ($this->_isInterfaceMethod($name) ||
$this->_isAbstractMethod($name) ||
$this->_isAbstractMethodInParents($name) ||
$this->_isStaticMethod($name)) {
return $this->_getFullSignature($name);
// This wonky try-catch is a work around for a faulty method_exists()
// in early versions of PHP 5 which would return false for static
// methods. The Reflection classes work fine, but hasMethod()
// 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.
* @access private
*/
function _getFullSignature($name) {
$interface = new ReflectionClass($this->_interface);
protected function getFullSignature($name) {
$interface = new ReflectionClass($this->interface);
$method = $interface->getMethod($name);
$reference = $method->returnsReference() ? '&' : '';
$static = $method->isStatic() ? 'static ' : '';
return "{$static}function $reference$name(" .
implode(', ', $this->_getParameterSignatures($method)) .
implode(', ', $this->getParameterSignatures($method)) .
")";
}
@ -329,7 +335,7 @@ class SimpleReflection {
* a snippet of code.
* @access private
*/
function _getParameterSignatures($method) {
protected function getParameterSignatures($method) {
$signatures = array();
foreach ($method->getParameters() as $parameter) {
$signature = '';
@ -342,8 +348,8 @@ class SimpleReflection {
if ($parameter->isPassedByReference()) {
$signature .= '&';
}
$signature .= '$' . $this->_suppressSpurious($parameter->getName());
if ($this->_isOptional($parameter)) {
$signature .= '$' . $this->suppressSpurious($parameter->getName());
if ($this->isOptional($parameter)) {
$signature .= ' = null';
}
$signatures[] = $signature;
@ -359,7 +365,7 @@ class SimpleReflection {
* @return string Cleaner name.
* @access private
*/
function _suppressSpurious($name) {
protected function suppressSpurious($name) {
return str_replace(array('[', ']', ' '), '', $name);
}
@ -370,11 +376,11 @@ class SimpleReflection {
* @return boolean True if optional.
* @access private
*/
function _isOptional($parameter) {
protected function isOptional($parameter) {
if (method_exists($parameter, 'isOptional')) {
return $parameter->isOptional();
}
return false;
}
}
?>
?>

View File

@ -3,7 +3,7 @@
* base include file for SimpleTest
* @package SimpleTest
* @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
*/
class RemoteTestCase {
var $_url;
var $_dry_url;
var $_size;
private $url;
private $dry_url;
private $size;
/**
* Sets the location of the remote test.
* @param string $url Test location.
* @param string $dry_url Location for dry run.
* @access public
*/
function RemoteTestCase($url, $dry_url = false) {
$this->_url = $url;
$this->_dry_url = $dry_url ? $dry_url : $url;
$this->_size = false;
function __construct($url, $dry_url = false) {
$this->url = $url;
$this->dry_url = $dry_url ? $dry_url : $url;
$this->size = false;
}
/**
* Accessor for the test name for subclasses.
* @return string Name of the test.
* @access public
*/
function getLabel() {
return $this->_url;
return $this->url;
}
/**
@ -53,65 +53,63 @@ class RemoteTestCase {
* @returns boolean True if no failures.
* @access public
*/
function run(&$reporter) {
$browser = &$this->_createBrowser();
$xml = $browser->get($this->_url);
function run($reporter) {
$browser = $this->createBrowser();
$xml = $browser->get($this->url);
if (! $xml) {
trigger_error('Cannot read remote test URL [' . $this->_url . ']');
trigger_error('Cannot read remote test URL [' . $this->url . ']');
return false;
}
$parser = &$this->_createParser($reporter);
$parser = $this->createParser($reporter);
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 true;
}
/**
* Creates a new web browser object for fetching
* the XML report.
* @return SimpleBrowser New browser.
* @access protected
*/
function &_createBrowser() {
$browser = &new SimpleBrowser();
return $browser;
protected function createBrowser() {
return new SimpleBrowser();
}
/**
* Creates the XML parser.
* @param SimpleReporter $reporter Target of test results.
* @return SimpleTestXmlListener XML reader.
* @access protected
*/
function &_createParser(&$reporter) {
$parser = &new SimpleTestXmlParser($reporter);
return $parser;
protected function createParser($reporter) {
return new SimpleTestXmlParser($reporter);
}
/**
* Accessor for the number of subtests.
* @return integer Number of test cases.
* @access public
*/
function getSize() {
if ($this->_size === false) {
$browser = &$this->_createBrowser();
$xml = $browser->get($this->_dry_url);
if ($this->size === false) {
$browser = $this->createBrowser();
$xml = $browser->get($this->dry_url);
if (! $xml) {
trigger_error('Cannot read remote test URL [' . $this->_dry_url . ']');
trigger_error('Cannot read remote test URL [' . $this->dry_url . ']');
return false;
}
$reporter = &new SimpleReporter();
$parser = &$this->_createParser($reporter);
$reporter = new SimpleReporter();
$parser = $this->createParser($reporter);
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;
}
$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
* @package SimpleTest
* @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
*/
require_once(dirname(__FILE__) . '/scorer.php');
//require_once(dirname(__FILE__) . '/arguments.php');
/**#@-*/
/**
@ -19,7 +20,7 @@ require_once(dirname(__FILE__) . '/scorer.php');
* @subpackage UnitTester
*/
class HtmlReporter extends SimpleReporter {
var $_character_set;
private $character_set;
/**
* Does nothing yet. The first output will
@ -27,9 +28,9 @@ class HtmlReporter extends SimpleReporter {
* by a web browser.
* @access public
*/
function HtmlReporter($character_set = 'ISO-8859-1') {
$this->SimpleReporter();
$this->_character_set = $character_set;
function __construct($character_set = 'ISO-8859-1') {
parent::__construct();
$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 "<html>\n<head>\n<title>$test_name</title>\n";
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 $this->_getCss() . "\n";
print $this->getCss() . "\n";
print "</style>\n";
print "</head>\n<body>\n";
print "<h1>$test_name</h1>\n";
@ -57,9 +58,8 @@ class HtmlReporter extends SimpleReporter {
* reloaded on every request. Otherwise you could be
* scratching your head over out of date test data.
* @access public
* @static
*/
function sendNoCacheHeaders() {
static function sendNoCacheHeaders() {
if (! headers_sent()) {
header("Expires: Mon, 26 Jul 1997 05:00:00 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.
* @access protected
*/
function _getCss() {
protected function getCss() {
return ".fail { background-color: inherit; color: red; }" .
".pass { background-color: inherit; color: green; }" .
" pre { background-color: lightgray; color: inherit; }";
@ -106,7 +106,6 @@ class HtmlReporter extends SimpleReporter {
* top level test.
* @param string $message Failure message displayed in
* the context of the other tests.
* @access public
*/
function paintFail($message) {
parent::paintFail($message);
@ -114,7 +113,7 @@ class HtmlReporter extends SimpleReporter {
$breadcrumb = $this->getTestList();
array_shift($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();
array_shift($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() .
'] in ['. $exception->getFile() .
' 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.
* @param string $message Text of skip condition.
@ -160,16 +159,16 @@ class HtmlReporter extends SimpleReporter {
$breadcrumb = $this->getTestList();
array_shift($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.
* @access public
*/
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.
* @access protected
*/
function _htmlEntities($message) {
return htmlentities($message, ENT_COMPAT, $this->_character_set);
protected function htmlEntities($message) {
return htmlentities($message, ENT_COMPAT, $this->character_set);
}
}
@ -197,10 +196,9 @@ class TextReporter extends SimpleReporter {
/**
* Does nothing yet. The first output will
* be sent on the first test start.
* @access public
*/
function TextReporter() {
$this->SimpleReporter();
function __construct() {
parent::__construct();
}
/**
@ -283,7 +281,7 @@ class TextReporter extends SimpleReporter {
print "\tin " . implode("\n\tin ", array_reverse($breadcrumb));
print "\n";
}
/**
* Prints the message for skipping tests.
* @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.
* @access public
*/
@ -312,10 +310,10 @@ class TextReporter extends SimpleReporter {
* @subpackage UnitTester
*/
class SelectiveReporter extends SimpleReporterDecorator {
var $_just_this_case = false;
var $_just_this_test = false;
var $_on;
private $just_this_case = false;
private $just_this_test = false;
private $on;
/**
* Selects the test case or group to be run,
* 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_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) {
$this->_just_this_case = strtolower($just_this_case);
$this->_off();
$this->just_this_case = strtolower($just_this_case);
$this->off();
} else {
$this->_on();
$this->on();
}
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.
* @access protected
*/
function _matchesTestCase($test_case) {
return $this->_just_this_case == strtolower($test_case);
protected function matchesTestCase($test_case) {
return $this->just_this_case == strtolower($test_case);
}
/**
@ -354,40 +352,40 @@ class SelectiveReporter extends SimpleReporterDecorator {
* @return boolean True if matched.
* @access protected
*/
function _shouldRunTest($test_case, $method) {
if ($this->_isOn() || $this->_matchesTestCase($test_case)) {
if ($this->_just_this_test) {
return $this->_just_this_test == strtolower($method);
protected function shouldRunTest($test_case, $method) {
if ($this->isOn() || $this->matchesTestCase($test_case)) {
if ($this->just_this_test) {
return $this->just_this_test == strtolower($method);
} else {
return true;
}
}
return false;
}
/**
* Switch on testing for the group or subgroup.
* @access private
*/
function _on() {
$this->_on = true;
protected function on() {
$this->on = true;
}
/**
* Switch off testing for the group or subgroup.
* @access private
*/
function _off() {
$this->_on = false;
protected function off() {
$this->on = false;
}
/**
* Is this group actually being tested?
* @return boolean True if the current test group is active.
* @access private
*/
function _isOn() {
return $this->_on;
protected function isOn() {
return $this->on;
}
/**
@ -398,8 +396,8 @@ class SelectiveReporter extends SimpleReporterDecorator {
* @access public
*/
function shouldInvoke($test_case, $method) {
if ($this->_shouldRunTest($test_case, $method)) {
return $this->_reporter->shouldInvoke($test_case, $method);
if ($this->shouldRunTest($test_case, $method)) {
return $this->reporter->shouldInvoke($test_case, $method);
}
return false;
}
@ -411,10 +409,10 @@ class SelectiveReporter extends SimpleReporterDecorator {
* @access public
*/
function paintGroupStart($test_case, $size) {
if ($this->_just_this_case && $this->_matchesTestCase($test_case)) {
$this->_on();
if ($this->just_this_case && $this->matchesTestCase($test_case)) {
$this->on();
}
$this->_reporter->paintGroupStart($test_case, $size);
$this->reporter->paintGroupStart($test_case, $size);
}
/**
@ -423,9 +421,9 @@ class SelectiveReporter extends SimpleReporterDecorator {
* @access public
*/
function paintGroupEnd($test_case) {
$this->_reporter->paintGroupEnd($test_case);
if ($this->_just_this_case && $this->_matchesTestCase($test_case)) {
$this->_off();
$this->reporter->paintGroupEnd($test_case);
if ($this->just_this_case && $this->matchesTestCase($test_case)) {
$this->off();
}
}
}
@ -436,7 +434,7 @@ class SelectiveReporter extends SimpleReporterDecorator {
* @subpackage UnitTester
*/
class NoSkipsReporter extends SimpleReporterDecorator {
/**
* Does nothing.
* @param string $message Text of skip condition.

View File

@ -3,7 +3,7 @@
* base include file for SimpleTest
* @package SimpleTest
* @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
*/
class SimpleScorer {
var $_passes;
var $_fails;
var $_exceptions;
var $_is_dry_run;
private $passes;
private $fails;
private $exceptions;
private $is_dry_run;
/**
* Starts the test run with no results.
* @access public
*/
function SimpleScorer() {
$this->_passes = 0;
$this->_fails = 0;
$this->_exceptions = 0;
$this->_is_dry_run = false;
function __construct() {
$this->passes = 0;
$this->fails = 0;
$this->exceptions = 0;
$this->is_dry_run = false;
}
/**
@ -43,7 +43,7 @@ class SimpleScorer {
* @access public
*/
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
*/
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.
* @access public
*/
function &createInvoker(&$invoker) {
function createInvoker($invoker) {
return $invoker;
}
@ -75,7 +75,7 @@ class SimpleScorer {
* @access public
*/
function getStatus() {
if ($this->_exceptions + $this->_fails > 0) {
if ($this->exceptions + $this->fails > 0) {
return false;
}
return true;
@ -136,7 +136,7 @@ class SimpleScorer {
* @access public
*/
function paintPass($message) {
$this->_passes++;
$this->passes++;
}
/**
@ -145,7 +145,7 @@ class SimpleScorer {
* @access public
*/
function paintFail($message) {
$this->_fails++;
$this->fails++;
}
/**
@ -155,7 +155,7 @@ class SimpleScorer {
* @access public
*/
function paintError($message) {
$this->_exceptions++;
$this->exceptions++;
}
/**
@ -164,9 +164,9 @@ class SimpleScorer {
* @access public
*/
function paintException($exception) {
$this->_exceptions++;
$this->exceptions++;
}
/**
* Prints the message for skipping tests.
* @param string $message Text of skip condition.
@ -181,7 +181,7 @@ class SimpleScorer {
* @access public
*/
function getPassCount() {
return $this->_passes;
return $this->passes;
}
/**
@ -190,7 +190,7 @@ class SimpleScorer {
* @access public
*/
function getFailCount() {
return $this->_fails;
return $this->fails;
}
/**
@ -200,7 +200,7 @@ class SimpleScorer {
* @access public
*/
function getExceptionCount() {
return $this->_exceptions;
return $this->exceptions;
}
/**
@ -213,7 +213,7 @@ class SimpleScorer {
/**
* Paints a formatted ASCII message such as a
* variable dump.
* privateiable dump.
* @param string $message Text to display.
* @access public
*/
@ -239,24 +239,23 @@ class SimpleScorer {
* @subpackage UnitTester
*/
class SimpleReporter extends SimpleScorer {
var $_test_stack;
var $_size;
var $_progress;
private $test_stack;
private $size;
private $progress;
/**
* Starts the display with no results in.
* @access public
*/
function SimpleReporter() {
$this->SimpleScorer();
$this->_test_stack = array();
$this->_size = null;
$this->_progress = 0;
function __construct() {
parent::__construct();
$this->test_stack = array();
$this->size = null;
$this->progress = 0;
}
/**
* Gets the formatter for variables and other small
* generic data items.
* Gets the formatter for small generic data items.
* @return SimpleDumper Formatter.
* @access public
*/
@ -274,13 +273,13 @@ class SimpleReporter extends SimpleScorer {
* @access public
*/
function paintGroupStart($test_name, $size) {
if (! isset($this->_size)) {
$this->_size = $size;
if (! isset($this->size)) {
$this->size = $size;
}
if (count($this->_test_stack) == 0) {
if (count($this->test_stack) == 0) {
$this->paintHeader($test_name);
}
$this->_test_stack[] = $test_name;
$this->test_stack[] = $test_name;
}
/**
@ -291,8 +290,8 @@ class SimpleReporter extends SimpleScorer {
* @access public
*/
function paintGroupEnd($test_name) {
array_pop($this->_test_stack);
if (count($this->_test_stack) == 0) {
array_pop($this->test_stack);
if (count($this->test_stack) == 0) {
$this->paintFooter($test_name);
}
}
@ -306,13 +305,13 @@ class SimpleReporter extends SimpleScorer {
* @access public
*/
function paintCaseStart($test_name) {
if (! isset($this->_size)) {
$this->_size = 1;
if (! isset($this->size)) {
$this->size = 1;
}
if (count($this->_test_stack) == 0) {
if (count($this->test_stack) == 0) {
$this->paintHeader($test_name);
}
$this->_test_stack[] = $test_name;
$this->test_stack[] = $test_name;
}
/**
@ -322,9 +321,9 @@ class SimpleReporter extends SimpleScorer {
* @access public
*/
function paintCaseEnd($test_name) {
$this->_progress++;
array_pop($this->_test_stack);
if (count($this->_test_stack) == 0) {
$this->progress++;
array_pop($this->test_stack);
if (count($this->test_stack) == 0) {
$this->paintFooter($test_name);
}
}
@ -335,7 +334,7 @@ class SimpleReporter extends SimpleScorer {
* @access public
*/
function paintMethodStart($test_name) {
$this->_test_stack[] = $test_name;
$this->test_stack[] = $test_name;
}
/**
@ -345,7 +344,7 @@ class SimpleReporter extends SimpleScorer {
* @access public
*/
function paintMethodEnd($test_name) {
array_pop($this->_test_stack);
array_pop($this->test_stack);
}
/**
@ -375,7 +374,7 @@ class SimpleReporter extends SimpleScorer {
* @access public
*/
function getTestList() {
return $this->_test_stack;
return $this->test_stack;
}
/**
@ -386,7 +385,7 @@ class SimpleReporter extends SimpleScorer {
* @access public
*/
function getTestCaseCount() {
return $this->_size;
return $this->size;
}
/**
@ -396,16 +395,15 @@ class SimpleReporter extends SimpleScorer {
* @access public
*/
function getTestCaseProgress() {
return $this->_progress;
return $this->progress;
}
/**
* Static check for running in the comand line.
* @return boolean True if CLI.
* @access public
* @static
*/
function inCli() {
static function inCli() {
return php_sapi_name() == 'cli';
}
}
@ -416,14 +414,14 @@ class SimpleReporter extends SimpleScorer {
* @subpackage UnitTester
*/
class SimpleReporterDecorator {
var $_reporter;
protected $reporter;
/**
* Mediates between the reporter and the test case.
* @param SimpleScorer $reporter Reporter to receive events.
*/
function SimpleReporterDecorator(&$reporter) {
$this->_reporter = &$reporter;
function __construct($reporter) {
$this->reporter = $reporter;
}
/**
@ -434,7 +432,7 @@ class SimpleReporterDecorator {
* @access public
*/
function makeDry($is_dry = true) {
$this->_reporter->makeDry($is_dry);
$this->reporter->makeDry($is_dry);
}
/**
@ -445,39 +443,53 @@ class SimpleReporterDecorator {
* @access public
*/
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.
* @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.
* @return boolean True if test should be run.
* @access public
*/
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.
* @param SimpleInvoker $invoker Individual test runner.
* @return SimpleInvoker Wrapped test runner.
* @access public
*/
function &createInvoker(&$invoker) {
return $this->_reporter->createInvoker($invoker);
function 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.
* @return SimpleDumper Formatter.
* @access public
*/
function getDumper() {
return $this->_reporter->getDumper();
return $this->reporter->getDumper();
}
/**
@ -487,7 +499,7 @@ class SimpleReporterDecorator {
* @access public
*/
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
*/
function paintGroupEnd($test_name) {
$this->_reporter->paintGroupEnd($test_name);
$this->reporter->paintGroupEnd($test_name);
}
/**
@ -505,7 +517,7 @@ class SimpleReporterDecorator {
* @access public
*/
function paintCaseStart($test_name) {
$this->_reporter->paintCaseStart($test_name);
$this->reporter->paintCaseStart($test_name);
}
/**
@ -514,7 +526,7 @@ class SimpleReporterDecorator {
* @access public
*/
function paintCaseEnd($test_name) {
$this->_reporter->paintCaseEnd($test_name);
$this->reporter->paintCaseEnd($test_name);
}
/**
@ -523,7 +535,7 @@ class SimpleReporterDecorator {
* @access public
*/
function paintMethodStart($test_name) {
$this->_reporter->paintMethodStart($test_name);
$this->reporter->paintMethodStart($test_name);
}
/**
@ -532,7 +544,7 @@ class SimpleReporterDecorator {
* @access public
*/
function paintMethodEnd($test_name) {
$this->_reporter->paintMethodEnd($test_name);
$this->reporter->paintMethodEnd($test_name);
}
/**
@ -541,7 +553,7 @@ class SimpleReporterDecorator {
* @access public
*/
function paintPass($message) {
$this->_reporter->paintPass($message);
$this->reporter->paintPass($message);
}
/**
@ -550,7 +562,7 @@ class SimpleReporterDecorator {
* @access public
*/
function paintFail($message) {
$this->_reporter->paintFail($message);
$this->reporter->paintFail($message);
}
/**
@ -560,7 +572,7 @@ class SimpleReporterDecorator {
* @access public
*/
function paintError($message) {
$this->_reporter->paintError($message);
$this->reporter->paintError($message);
}
/**
@ -569,16 +581,16 @@ class SimpleReporterDecorator {
* @access public
*/
function paintException($exception) {
$this->_reporter->paintException($exception);
$this->reporter->paintException($exception);
}
/**
* Prints the message for skipping tests.
* @param string $message Text of skip condition.
* @access public
*/
function paintSkip($message) {
$this->_reporter->paintSkip($message);
$this->reporter->paintSkip($message);
}
/**
@ -587,7 +599,7 @@ class SimpleReporterDecorator {
* @access public
*/
function paintMessage($message) {
$this->_reporter->paintMessage($message);
$this->reporter->paintMessage($message);
}
/**
@ -596,7 +608,7 @@ class SimpleReporterDecorator {
* @access public
*/
function paintFormattedMessage($message) {
$this->_reporter->paintFormattedMessage($message);
$this->reporter->paintFormattedMessage($message);
}
/**
@ -608,8 +620,8 @@ class SimpleReporterDecorator {
* test suite.
* @access public
*/
function paintSignal($type, &$payload) {
$this->_reporter->paintSignal($type, $payload);
function paintSignal($type, $payload) {
$this->reporter->paintSignal($type, $payload);
}
}
@ -620,15 +632,15 @@ class SimpleReporterDecorator {
* @subpackage UnitTester
*/
class MultipleReporter {
var $_reporters = array();
private $reporters = array();
/**
* Adds a reporter to the subscriber list.
* @param SimpleScorer $reporter Reporter to receive events.
* @access public
*/
function attachReporter(&$reporter) {
$this->_reporters[] = &$reporter;
function attachReporter($reporter) {
$this->reporters[] = $reporter;
}
/**
@ -639,8 +651,8 @@ class MultipleReporter {
* @access public
*/
function makeDry($is_dry = true) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->makeDry($is_dry);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->makeDry($is_dry);
}
}
@ -653,8 +665,8 @@ class MultipleReporter {
* @access public
*/
function getStatus() {
for ($i = 0; $i < count($this->_reporters); $i++) {
if (! $this->_reporters[$i]->getStatus()) {
for ($i = 0; $i < count($this->reporters); $i++) {
if (! $this->reporters[$i]->getStatus()) {
return false;
}
}
@ -669,8 +681,8 @@ class MultipleReporter {
* @access public
*/
function shouldInvoke($test_case_name, $method) {
for ($i = 0; $i < count($this->_reporters); $i++) {
if (! $this->_reporters[$i]->shouldInvoke($test_case_name, $method)) {
for ($i = 0; $i < count($this->reporters); $i++) {
if (! $this->reporters[$i]->shouldInvoke($test_case_name, $method)) {
return false;
}
}
@ -683,15 +695,15 @@ class MultipleReporter {
* @return SimpleInvoker Wrapped test runner.
* @access public
*/
function &createInvoker(&$invoker) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$invoker = &$this->_reporters[$i]->createInvoker($invoker);
function createInvoker($invoker) {
for ($i = 0; $i < count($this->reporters); $i++) {
$invoker = $this->reporters[$i]->createInvoker($invoker);
}
return $invoker;
}
/**
* Gets the formatter for variables and other small
* Gets the formatter for privateiables and other small
* generic data items.
* @return SimpleDumper Formatter.
* @access public
@ -707,8 +719,8 @@ class MultipleReporter {
* @access public
*/
function paintGroupStart($test_name, $size) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintGroupStart($test_name, $size);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintGroupStart($test_name, $size);
}
}
@ -718,8 +730,8 @@ class MultipleReporter {
* @access public
*/
function paintGroupEnd($test_name) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintGroupEnd($test_name);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintGroupEnd($test_name);
}
}
@ -729,8 +741,8 @@ class MultipleReporter {
* @access public
*/
function paintCaseStart($test_name) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintCaseStart($test_name);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintCaseStart($test_name);
}
}
@ -740,8 +752,8 @@ class MultipleReporter {
* @access public
*/
function paintCaseEnd($test_name) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintCaseEnd($test_name);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintCaseEnd($test_name);
}
}
@ -751,8 +763,8 @@ class MultipleReporter {
* @access public
*/
function paintMethodStart($test_name) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintMethodStart($test_name);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintMethodStart($test_name);
}
}
@ -762,8 +774,8 @@ class MultipleReporter {
* @access public
*/
function paintMethodEnd($test_name) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintMethodEnd($test_name);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintMethodEnd($test_name);
}
}
@ -773,8 +785,8 @@ class MultipleReporter {
* @access public
*/
function paintPass($message) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintPass($message);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintPass($message);
}
}
@ -784,8 +796,8 @@ class MultipleReporter {
* @access public
*/
function paintFail($message) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintFail($message);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintFail($message);
}
}
@ -796,19 +808,19 @@ class MultipleReporter {
* @access public
*/
function paintError($message) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintError($message);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintError($message);
}
}
/**
* Chains to the wrapped reporter.
* @param Exception $exception Exception to display.
* @access public
*/
function paintException($exception) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintException($exception);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintException($exception);
}
}
@ -818,8 +830,8 @@ class MultipleReporter {
* @access public
*/
function paintSkip($message) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintSkip($message);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintSkip($message);
}
}
@ -829,8 +841,8 @@ class MultipleReporter {
* @access public
*/
function paintMessage($message) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintMessage($message);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintMessage($message);
}
}
@ -840,8 +852,8 @@ class MultipleReporter {
* @access public
*/
function paintFormattedMessage($message) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintFormattedMessage($message);
for ($i = 0; $i < count($this->reporters); $i++) {
$this->reporters[$i]->paintFormattedMessage($message);
}
}
@ -854,9 +866,9 @@ class MultipleReporter {
* test suite.
* @access public
*/
function paintSignal($type, &$payload) {
for ($i = 0; $i < count($this->_reporters); $i++) {
$this->_reporters[$i]->paintSignal($type, $payload);
function paintSignal($type, $payload) {
for ($i = 0; $i < count($this->reporters); $i++) {
$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.
* @package SimpleTest
* @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
*/
class SimpleByName {
var $_name;
private $name;
/**
* Stashes the name for later comparison.
* @param string $name Name attribute to match.
*/
function SimpleByName($name) {
$this->_name = $name;
function __construct($name) {
$this->name = $name;
}
/**
* Accessor for name.
* @returns string $name Name to match.
*/
function getName() {
return $this->_name;
return $this->name;
}
/**
@ -40,7 +44,7 @@ class SimpleByName {
* @access public
*/
function isMatch($widget) {
return ($widget->getName() == $this->_name);
return ($widget->getName() == $this->name);
}
}
@ -51,14 +55,14 @@ class SimpleByName {
* @subpackage WebTester
*/
class SimpleByLabel {
var $_label;
private $label;
/**
* Stashes the name for later comparison.
* @param string $label Visible text to match.
*/
function SimpleByLabel($label) {
$this->_label = $label;
function __construct($label) {
$this->label = $label;
}
/**
@ -71,7 +75,7 @@ class SimpleByLabel {
if (! method_exists($widget, 'isLabel')) {
return false;
}
return $widget->isLabel($this->_label);
return $widget->isLabel($this->label);
}
}
@ -82,14 +86,14 @@ class SimpleByLabel {
* @subpackage WebTester
*/
class SimpleById {
var $_id;
private $id;
/**
* Stashes the name for later comparison.
* @param string $id ID atribute to match.
*/
function SimpleById($id) {
$this->_id = $id;
function __construct($id) {
$this->id = $id;
}
/**
@ -98,7 +102,7 @@ class SimpleById {
* @access public
*/
function isMatch($widget) {
return $widget->isId($this->_id);
return $widget->isId($this->id);
}
}
@ -109,14 +113,14 @@ class SimpleById {
* @subpackage WebTester
*/
class SimpleByLabelOrName {
var $_label;
private $label;
/**
* Stashes the name/label for later comparison.
* @param string $label Visible text to match.
*/
function SimpleByLabelOrName($label) {
$this->_label = $label;
function __construct($label) {
$this->label = $label;
}
/**
@ -127,11 +131,11 @@ class SimpleByLabelOrName {
*/
function isMatch($widget) {
if (method_exists($widget, 'isLabel')) {
if ($widget->isLabel($this->_label)) {
if ($widget->isLabel($this->label)) {
return true;
}
}
return ($widget->getName() == $this->_label);
return ($widget->getName() == $this->label);
}
}
?>

View File

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

View File

@ -3,17 +3,13 @@
* Global state for SimpleTest and kicker script in future versions.
* @package SimpleTest
* @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
*/
if (version_compare(phpversion(), '5') >= 0) {
require_once(dirname(__FILE__) . '/reflection_php5.php');
} else {
require_once(dirname(__FILE__) . '/reflection_php4.php');
}
require_once(dirname(__FILE__) . '/reflection_php5.php');
require_once(dirname(__FILE__) . '/default_reporter.php');
require_once(dirname(__FILE__) . '/compatibility.php');
/**#@-*/
@ -29,10 +25,8 @@ class SimpleTest {
/**
* Reads the SimpleTest version from the release file.
* @return string Version string.
* @static
* @access public
*/
function getVersion() {
static function getVersion() {
$content = file(dirname(__FILE__) . '/VERSION');
return trim($content[0]);
}
@ -40,14 +34,10 @@ class SimpleTest {
/**
* Sets the name of a test case to ignore, usually
* 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.
* @static
* @access public
*/
function ignore($class) {
$registry = &SimpleTest::_getRegistry();
static function ignore($class) {
$registry = &SimpleTest::getRegistry();
$registry['IgnoreList'][strtolower($class)] = true;
}
@ -63,11 +53,9 @@ class SimpleTest {
* the ignore() calls. It's just nice to have the ignore()
* calls at the top of the file before the actual declarations.
* @param array $classes Class names of interest.
* @static
* @access public
*/
function ignoreParentsIfIgnored($classes) {
$registry = &SimpleTest::_getRegistry();
static function ignoreParentsIfIgnored($classes) {
$registry = &SimpleTest::getRegistry();
foreach ($classes as $class) {
if (SimpleTest::isIgnored($class)) {
$reflection = new SimpleReflection($class);
@ -83,13 +71,11 @@ class SimpleTest {
* which can be retrieved with SimpleTest :: preferred() method.
* Instances of the same class are overwritten.
* @param object $object Preferred object
* @static
* @access public
* @see preferred()
*/
function prefer(&$object) {
$registry = &SimpleTest::_getRegistry();
$registry['Preferred'][] = &$object;
static function prefer($object) {
$registry = &SimpleTest::getRegistry();
$registry['Preferred'][] = $object;
}
/**
@ -97,16 +83,14 @@ class SimpleTest {
* can be applied in order to retrieve the object of the specific
* class
* @param array|string $classes Allowed classes or interfaces.
* @static
* @access public
* @return array|object|null
* @see prefer()
*/
function &preferred($classes) {
static function preferred($classes) {
if (! is_array($classes)) {
$classes = array($classes);
}
$registry = &SimpleTest::_getRegistry();
$registry = &SimpleTest::getRegistry();
for ($i = count($registry['Preferred']) - 1; $i >= 0; $i--) {
foreach ($classes as $class) {
if (SimpleTestCompatibility::isA($registry['Preferred'][$i], $class)) {
@ -125,30 +109,12 @@ class SimpleTest {
* use it.
* @param string $class Class name to test.
* @return boolean True if should not be run.
* @access public
* @static
*/
function isIgnored($class) {
$registry = &SimpleTest::_getRegistry();
static function isIgnored($class) {
$registry = &SimpleTest::getRegistry();
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
* testing from behind a firewall. Set host
@ -157,10 +123,9 @@ class SimpleTest {
* @param string $proxy Proxy host as URL.
* @param string $username Proxy username for authentication.
* @param string $password Proxy password for authentication.
* @access public
*/
function useProxy($proxy, $username = false, $password = false) {
$registry = &SimpleTest::_getRegistry();
static function useProxy($proxy, $username = false, $password = false) {
$registry = &SimpleTest::getRegistry();
$registry['DefaultProxy'] = $proxy;
$registry['DefaultProxyUsername'] = $username;
$registry['DefaultProxyPassword'] = $password;
@ -169,43 +134,60 @@ class SimpleTest {
/**
* Accessor for default proxy host.
* @return string Proxy URL.
* @access public
*/
function getDefaultProxy() {
$registry = &SimpleTest::_getRegistry();
static function getDefaultProxy() {
$registry = &SimpleTest::getRegistry();
return $registry['DefaultProxy'];
}
/**
* Accessor for default proxy username.
* @return string Proxy username for authentication.
* @access public
*/
function getDefaultProxyUsername() {
$registry = &SimpleTest::_getRegistry();
static function getDefaultProxyUsername() {
$registry = &SimpleTest::getRegistry();
return $registry['DefaultProxyUsername'];
}
/**
* Accessor for default proxy password.
* @return string Proxy password for authentication.
* @access public
*/
function getDefaultProxyPassword() {
$registry = &SimpleTest::_getRegistry();
static function getDefaultProxyPassword() {
$registry = &SimpleTest::getRegistry();
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.
* @return hash All stored values.
* @access private
* @static
*/
function &_getRegistry() {
protected static function &getRegistry() {
static $registry = false;
if (! $registry) {
$registry = SimpleTest::_getDefaults();
$registry = SimpleTest::getDefaults();
}
return $registry;
}
@ -214,10 +196,8 @@ class SimpleTest {
* Accessor for the context of the current
* test run.
* @return SimpleTestContext Current test run.
* @access public
* @static
*/
function &getContext() {
static function getContext() {
static $context = false;
if (! $context) {
$context = new SimpleTestContext();
@ -228,12 +208,10 @@ class SimpleTest {
/**
* Constant default values.
* @return hash All registry defaults.
* @access private
* @static
*/
function _getDefaults() {
protected static function getDefaults() {
return array(
'StubBaseClass' => 'SimpleStub',
'Parsers' => false,
'MockBaseClass' => 'SimpleMock',
'IgnoreList' => array(),
'DefaultProxy' => false,
@ -241,6 +219,22 @@ class SimpleTest {
'DefaultProxyPassword' => false,
'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
*/
class SimpleTestContext {
var $_test;
var $_reporter;
var $_resources;
private $test;
private $reporter;
private $resources;
/**
* Clears down the current context.
* @access public
*/
function clear() {
$this->_resources = array();
$this->resources = array();
}
/**
@ -269,20 +263,18 @@ class SimpleTestContext {
* global instance can be used by the mock objects
* to send message to the test cases.
* @param SimpleTestCase $test Test case to register.
* @access public
*/
function setTest(&$test) {
function setTest($test) {
$this->clear();
$this->_test = &$test;
$this->test = $test;
}
/**
* Accessor for currently running test case.
* @return SimpleTestCase Current test.
* @access public
*/
function &getTest() {
return $this->_test;
function getTest() {
return $this->test;
}
/**
@ -290,33 +282,29 @@ class SimpleTestContext {
* global instance can be used by the mock objects
* to send messages.
* @param SimpleReporter $reporter Reporter to register.
* @access public
*/
function setReporter(&$reporter) {
function setReporter($reporter) {
$this->clear();
$this->_reporter = &$reporter;
$this->reporter = $reporter;
}
/**
* Accessor for current reporter.
* @return SimpleReporter Current reporter.
* @access public
*/
function &getReporter() {
return $this->_reporter;
function getReporter() {
return $this->reporter;
}
/**
* Accessor for the Singleton resource.
* @return object Global resource.
* @access public
* @static
*/
function &get($resource) {
if (! isset($this->_resources[$resource])) {
$this->_resources[$resource] = &new $resource();
function get($resource) {
if (! isset($this->resources[$resource])) {
$this->resources[$resource] = new $resource();
}
return $this->_resources[$resource];
return $this->resources[$resource];
}
}
@ -327,15 +315,15 @@ class SimpleTestContext {
* @subpackage UnitTester
*/
class SimpleStackTrace {
var $_prefixes;
private $prefixes;
/**
* Stashes the list of target prefixes.
* @param array $prefixes List of method prefixes
* to search for.
*/
function SimpleStackTrace($prefixes) {
$this->_prefixes = $prefixes;
function __construct($prefixes) {
$this->prefixes = $prefixes;
}
/**
@ -344,15 +332,14 @@ class SimpleStackTrace {
* @param array $stack List of stack frames.
* @return string Snippet of test report with line
* number and file.
* @access public
*/
function traceMethod($stack = false) {
$stack = $stack ? $stack : $this->_captureTrace();
$stack = $stack ? $stack : $this->captureTrace();
foreach ($stack as $frame) {
if ($this->_frameLiesWithinSimpleTestFolder($frame)) {
if ($this->frameLiesWithinSimpleTestFolder($frame)) {
continue;
}
if ($this->_frameMatchesPrefix($frame)) {
if ($this->frameMatchesPrefix($frame)) {
return ' at [' . $frame['file'] . ' line ' . $frame['line'] . ']';
}
}
@ -363,9 +350,8 @@ class SimpleStackTrace {
* Test to see if error is generated by SimpleTest itself.
* @param array $frame PHP stack frame.
* @return boolean True if a SimpleTest file.
* @access private
*/
function _frameLiesWithinSimpleTestFolder($frame) {
protected function frameLiesWithinSimpleTestFolder($frame) {
if (isset($frame['file'])) {
$path = substr(SIMPLE_TEST, 0, -1);
if (strpos($frame['file'], $path) === 0) {
@ -381,10 +367,9 @@ class SimpleStackTrace {
* Tries to determine if the method call is an assert, etc.
* @param array $frame PHP stack frame.
* @return boolean True if matches a target.
* @access private
*/
function _frameMatchesPrefix($frame) {
foreach ($this->_prefixes as $prefix) {
protected function frameMatchesPrefix($frame) {
foreach ($this->prefixes as $prefix) {
if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) {
return true;
}
@ -395,84 +380,12 @@ class SimpleStackTrace {
/**
* Grabs a current stack trace.
* @return array Fulle trace.
* @access private
*/
function _captureTrace() {
protected function captureTrace() {
if (function_exists('debug_backtrace')) {
return array_reverse(debug_backtrace());
}
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
* @package SimpleTest
* @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
*/
class SimpleStickyError {
var $_error = 'Constructor not chained';
private $error = 'Constructor not chained';
/**
* Sets the error to empty.
* @access public
*/
function SimpleStickyError() {
$this->_clearError();
function __construct() {
$this->clearError();
}
/**
@ -35,7 +35,7 @@ class SimpleStickyError {
* @access public
*/
function isError() {
return ($this->_error != '');
return ($this->error != '');
}
/**
@ -45,7 +45,7 @@ class SimpleStickyError {
* @access public
*/
function getError() {
return $this->_error;
return $this->error;
}
/**
@ -53,16 +53,112 @@ class SimpleStickyError {
* @param string Error message to stash.
* @access protected
*/
function _setError($error) {
$this->_error = $error;
function setError($error) {
$this->error = $error;
}
/**
* Resets the error state to no error.
* @access protected
*/
function _clearError() {
$this->_setError('');
function clearError() {
$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
*/
class SimpleSocket extends SimpleStickyError {
var $_handle;
var $_is_open = false;
var $_sent = '';
var $lock_size;
private $handle;
private $is_open = false;
private $sent = '';
private $lock_size;
/**
* Opens a socket for reading and writing.
@ -85,15 +181,15 @@ class SimpleSocket extends SimpleStickyError {
* @param integer $block_size Size of chunk to read.
* @access public
*/
function SimpleSocket($host, $port, $timeout, $block_size = 255) {
$this->SimpleStickyError();
if (! ($this->_handle = $this->_openSocket($host, $port, $error_number, $error, $timeout))) {
$this->_setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds");
function __construct($host, $port, $timeout, $block_size = 255) {
parent::__construct();
if (! ($this->handle = $this->openSocket($host, $port, $error_number, $error, $timeout))) {
$this->setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds");
return;
}
$this->_is_open = true;
$this->_block_size = $block_size;
SimpleTestCompatibility::setTimeout($this->_handle, $timeout);
$this->is_open = true;
$this->block_size = $block_size;
SimpleTestCompatibility::setTimeout($this->handle, $timeout);
}
/**
@ -106,16 +202,16 @@ class SimpleSocket extends SimpleStickyError {
if ($this->isError() || ! $this->isOpen()) {
return false;
}
$count = fwrite($this->_handle, $message);
$count = fwrite($this->handle, $message);
if (! $count) {
if ($count === false) {
$this->_setError('Cannot write to socket');
$this->setError('Cannot write to socket');
$this->close();
}
return false;
}
fflush($this->_handle);
$this->_sent .= $message;
fflush($this->handle);
$this->sent .= $message;
return true;
}
@ -131,9 +227,9 @@ class SimpleSocket extends SimpleStickyError {
if ($this->isError() || ! $this->isOpen()) {
return false;
}
$raw = @fread($this->_handle, $this->_block_size);
$raw = @fread($this->handle, $this->block_size);
if ($raw === false) {
$this->_setError('Cannot read from socket');
$this->setError('Cannot read from socket');
$this->close();
}
return $raw;
@ -145,7 +241,7 @@ class SimpleSocket extends SimpleStickyError {
* @access public
*/
function isOpen() {
return $this->_is_open;
return $this->is_open;
}
/**
@ -155,8 +251,8 @@ class SimpleSocket extends SimpleStickyError {
* @access public
*/
function close() {
$this->_is_open = false;
return fclose($this->_handle);
$this->is_open = false;
return fclose($this->handle);
}
/**
@ -165,7 +261,7 @@ class SimpleSocket extends SimpleStickyError {
* @access public
*/
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.
* @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);
}
}
@ -196,8 +292,8 @@ class SimpleSecureSocket extends SimpleSocket {
* @param integer $timeout Connection timeout in seconds.
* @access public
*/
function SimpleSecureSocket($host, $port, $timeout) {
$this->SimpleSocket($host, $port, $timeout);
function __construct($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.
* @access protected
*/
function _openSocket($host, $port, &$error_number, &$error, $timeout) {
return parent::_openSocket("tls://$host", $port, $error_number, $error, $timeout);
function openSocket($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
* @package SimpleTest
* @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__) . '/dumper.php');
require_once(dirname(__FILE__) . '/simpletest.php');
if (version_compare(phpversion(), '5') >= 0) {
require_once(dirname(__FILE__) . '/exceptions.php');
require_once(dirname(__FILE__) . '/reflection_php5.php');
} else {
require_once(dirname(__FILE__) . '/reflection_php4.php');
}
require_once(dirname(__FILE__) . '/exceptions.php');
require_once(dirname(__FILE__) . '/reflection_php5.php');
/**#@-*/
if (! defined('SIMPLE_TEST')) {
/**
* @ignore
*/
define('SIMPLE_TEST', dirname(__FILE__) . DIRECTORY_SEPARATOR);
}
/**#@-*/
/**
* Basic test case. This is the smallest unit of a test
@ -40,10 +36,10 @@ if (! defined('SIMPLE_TEST')) {
* @subpackage UnitTester
*/
class SimpleTestCase {
var $_label = false;
var $_reporter;
var $_observers;
var $_should_skip = false;
private $label = false;
protected $reporter;
private $observers;
private $should_skip = false;
/**
* Sets up the test with no display.
@ -51,9 +47,9 @@ class SimpleTestCase {
* the class name is used.
* @access public
*/
function SimpleTestCase($label = false) {
function __construct($label = false) {
if ($label) {
$this->_label = $label;
$this->label = $label;
}
}
@ -63,7 +59,7 @@ class SimpleTestCase {
* @access public
*/
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
*/
function skipIf($should_skip, $message = '%s') {
if ($should_skip && ! $this->_should_skip) {
$this->_should_skip = true;
if ($should_skip && ! $this->should_skip) {
$this->should_skip = true;
$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
* case to skip if the incoming flag is false.
@ -106,12 +110,9 @@ class SimpleTestCase {
* @return SimpleInvoker Individual test runner.
* @access public
*/
function &createInvoker() {
$invoker = &new SimpleErrorTrappingInvoker(new SimpleInvoker($this));
if (version_compare(phpversion(), '5') >= 0) {
$invoker = &new SimpleExceptionTrappingInvoker($invoker);
}
return $invoker;
function createInvoker() {
return new SimpleErrorTrappingInvoker(
new SimpleExceptionTrappingInvoker(new SimpleInvoker($this)));
}
/**
@ -122,23 +123,23 @@ class SimpleTestCase {
* @return boolean True if all tests passed.
* @access public
*/
function run(&$reporter) {
$context = &SimpleTest::getContext();
function run($reporter) {
$context = SimpleTest::getContext();
$context->setTest($this);
$context->setReporter($reporter);
$this->_reporter = &$reporter;
$this->reporter = $reporter;
$started = false;
foreach ($this->getTests() as $method) {
if ($reporter->shouldInvoke($this->getLabel(), $method)) {
$this->skip();
if ($this->_should_skip) {
if ($this->should_skip) {
break;
}
if (! $started) {
$reporter->paintCaseStart($this->getLabel());
$started = true;
}
$invoker = &$this->_reporter->createInvoker($this->createInvoker());
$invoker = $this->reporter->createInvoker($this->createInvoker());
$invoker->before($method);
$invoker->invoke($method);
$invoker->after($method);
@ -147,7 +148,8 @@ class SimpleTestCase {
if ($started) {
$reporter->paintCaseEnd($this->getLabel());
}
unset($this->_reporter);
unset($this->reporter);
$context->setTest(null);
return $reporter->getStatus();
}
@ -162,7 +164,7 @@ class SimpleTestCase {
function getTests() {
$methods = array();
foreach (get_class_methods(get_class($this)) as $method) {
if ($this->_isTest($method)) {
if ($this->isTest($method)) {
$methods[] = $method;
}
}
@ -177,7 +179,7 @@ class SimpleTestCase {
* @return boolean True if test method.
* @access protected
*/
function _isTest($method) {
protected function isTest($method) {
if (strtolower(substr($method, 0, 4)) == 'test') {
return ! SimpleTestCompatibility::isA($this, strtolower($method));
}
@ -190,8 +192,8 @@ class SimpleTestCase {
* @access public
*/
function before($method) {
$this->_reporter->paintMethodStart($method);
$this->_observers = array();
$this->reporter->paintMethodStart($method);
$this->observers = array();
}
/**
@ -217,10 +219,10 @@ class SimpleTestCase {
* @access public
*/
function after($method) {
for ($i = 0; $i < count($this->_observers); $i++) {
$this->_observers[$i]->atTestEnd($method, $this);
for ($i = 0; $i < count($this->observers); $i++) {
$this->observers[$i]->atTestEnd($method, $this);
}
$this->_reporter->paintMethodEnd($method);
$this->reporter->paintMethodEnd($method);
}
/**
@ -229,18 +231,18 @@ class SimpleTestCase {
* method.
* @access public
*/
function tell(&$observer) {
$this->_observers[] = &$observer;
function tell($observer) {
$this->observers[] = &$observer;
}
/**
* @deprecated
*/
function pass($message = "Pass") {
if (! isset($this->_reporter)) {
if (! isset($this->reporter)) {
trigger_error('Can only make assertions within test methods');
}
$this->_reporter->paintPass(
$this->reporter->paintPass(
$message . $this->getAssertionLine());
return true;
}
@ -251,10 +253,10 @@ class SimpleTestCase {
* @access public
*/
function fail($message = "Fail") {
if (! isset($this->_reporter)) {
if (! isset($this->reporter)) {
trigger_error('Can only make assertions within test methods');
}
$this->_reporter->paintFail(
$this->reporter->paintFail(
$message . $this->getAssertionLine());
return false;
}
@ -269,10 +271,10 @@ class SimpleTestCase {
* @access public
*/
function error($severity, $message, $file, $line) {
if (! isset($this->_reporter)) {
if (! isset($this->reporter)) {
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]");
}
@ -283,17 +285,19 @@ class SimpleTestCase {
* @access public
*/
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) {
if (! isset($this->_reporter)) {
function signal($type, $payload) {
if (! isset($this->reporter)) {
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
* @access public
*/
function assert(&$expectation, $compare, $message = '%s') {
function assert($expectation, $compare, $message = '%s') {
if ($expectation->test($compare)) {
return $this->pass(sprintf(
$message,
$expectation->overlayMessage($compare, $this->_reporter->getDumper())));
$expectation->overlayMessage($compare, $this->reporter->getDumper())));
} else {
return $this->fail(sprintf(
$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.
* @return string Line number of first assert*
@ -345,27 +342,19 @@ class SimpleTestCase {
* @access public
*/
function dump($variable, $message = false) {
$dumper = $this->_reporter->getDumper();
$dumper = $this->reporter->getDumper();
$formatted = $dumper->dump($variable);
if ($message) {
$formatted = $message . "\n" . $formatted;
}
$this->_reporter->paintFormattedMessage($formatted);
$this->reporter->paintFormattedMessage($formatted);
return $variable;
}
/**
* @deprecated
*/
function sendMessage($message) {
$this->_reporter->PaintMessage($message);
}
/**
* Accessor for the number of subtests including myelf.
* @return integer Number of test cases.
* @access public
* @static
*/
function getSize() {
return 1;
@ -374,6 +363,8 @@ class SimpleTestCase {
/**
* Helps to extract test cases automatically from a file.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleFileLoader {
@ -385,34 +376,33 @@ class SimpleFileLoader {
* @return TestSuite The new test suite.
* @access public
*/
function &load($test_file) {
function load($test_file) {
$existing_classes = get_declared_classes();
$existing_globals = get_defined_vars();
include_once($test_file);
$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);
if (empty($new_classes)) {
$new_classes = $this->_scrapeClassesFromFile($test_file);
$new_classes = $this->scrapeClassesFromFile($test_file);
}
$classes = $this->selectRunnableTests($new_classes);
$suite = &$this->createSuiteFromClasses($test_file, $classes);
return $suite;
return $this->createSuiteFromClasses($test_file, $classes);
}
/**
* Imports new variables into the global namespace.
* @param hash $existing Variables before the file was loaded.
* @param hash $new Variables after the file was loaded.
* @access private
*/
function _makeFileVariablesGlobal($existing, $new) {
protected function makeFileVariablesGlobal($existing, $new) {
$globals = array_diff(array_keys($new), array_keys($existing));
foreach ($globals as $global) {
$_GLOBALS[$global] = $new[$global];
$GLOBALS[$global] = $new[$global];
}
}
/**
* Lookup classnames from file contents, in case the
* file may have been included before.
@ -423,7 +413,7 @@ class SimpleFileLoader {
* @param string $test_file File name with classes.
* @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',
file_get_contents($test_file),
$matches );
@ -461,16 +451,16 @@ class SimpleFileLoader {
* test cases.
* @access public
*/
function &createSuiteFromClasses($title, $classes) {
function createSuiteFromClasses($title, $classes) {
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;
}
SimpleTest::ignoreParentsIfIgnored($classes);
$suite = &new TestSuite($title);
$suite = new TestSuite($title);
foreach ($classes as $class) {
if (! SimpleTest::isIgnored($class)) {
$suite->addTestClass($class);
$suite->add($class);
}
}
return $suite;
@ -485,8 +475,8 @@ class SimpleFileLoader {
* @subpackage UnitTester
*/
class TestSuite {
var $_label;
var $_test_cases;
private $label;
private $test_cases;
/**
* Sets the name of the test suite.
@ -495,8 +485,8 @@ class TestSuite {
* @access public
*/
function TestSuite($label = false) {
$this->_label = $label;
$this->_test_cases = array();
$this->label = $label;
$this->test_cases = array();
}
/**
@ -506,29 +496,11 @@ class TestSuite {
* @access public
*/
function getLabel() {
if (! $this->_label) {
if (! $this->label) {
return ($this->getSize() == 1) ?
get_class($this->_test_cases[0]) : get_class($this);
get_class($this->test_cases[0]) : get_class($this);
} else {
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;
return $this->label;
}
}
@ -540,23 +512,16 @@ class TestSuite {
* runnable test interface.
* @access public
*/
function add(&$test_case) {
function add($test_case) {
if (! is_string($test_case)) {
$this->_test_cases[] = &$test_case;
} elseif (TestSuite::getBaseTestCase($class) == 'testsuite') {
$this->_test_cases[] = &new $class();
$this->test_cases[] = $test_case;
} elseif (TestSuite::getBaseTestCase($test_case) == 'testsuite') {
$this->test_cases[] = new $test_case();
} 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.
* The new suite is composed into this one.
@ -576,7 +541,7 @@ class TestSuite {
* @param SimpleCollector $collector Directory scanner.
* @access public
*/
function collect($path, &$collector) {
function collect($path, $collector) {
$collector->collect($this, $path);
}
@ -586,16 +551,16 @@ class TestSuite {
* @param SimpleReporter $reporter Current test reporter.
* @access public
*/
function run(&$reporter) {
function run($reporter) {
$reporter->paintGroupStart($this->getLabel(), $this->getSize());
for ($i = 0, $count = count($this->_test_cases); $i < $count; $i++) {
if (is_string($this->_test_cases[$i])) {
$class = $this->_test_cases[$i];
$test = &new $class();
for ($i = 0, $count = count($this->test_cases); $i < $count; $i++) {
if (is_string($this->test_cases[$i])) {
$class = $this->test_cases[$i];
$test = new $class();
$test->run($reporter);
unset($test);
} else {
$this->_test_cases[$i]->run($reporter);
$this->test_cases[$i]->run($reporter);
}
}
$reporter->paintGroupEnd($this->getLabel());
@ -609,7 +574,7 @@ class TestSuite {
*/
function getSize() {
$count = 0;
foreach ($this->_test_cases as $case) {
foreach ($this->test_cases as $case) {
if (is_string($case)) {
if (! SimpleTest::isIgnored($case)) {
$count++;
@ -626,9 +591,8 @@ class TestSuite {
* SimpleTestCase class.
* @param string $class Class name.
* @access public
* @static
*/
function getBaseTestCase($class) {
static function getBaseTestCase($class) {
while ($class = get_parent_class($class)) {
$class = strtolower($class);
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
* loaded properly.
@ -653,8 +610,8 @@ class GroupTest extends TestSuite { }
* @subpackage UnitTester
*/
class BadTestSuite {
var $_label;
var $_error;
private $label;
private $error;
/**
* Sets the name of the test suite and error message.
@ -663,8 +620,8 @@ class BadTestSuite {
* @access public
*/
function BadTestSuite($label, $error) {
$this->_label = $label;
$this->_error = $error;
$this->label = $label;
$this->error = $error;
}
/**
@ -673,7 +630,7 @@ class BadTestSuite {
* @access public
*/
function getLabel() {
return $this->_label;
return $this->label;
}
/**
@ -681,10 +638,10 @@ class BadTestSuite {
* @param SimpleReporter $reporter Current test reporter.
* @access public
*/
function run(&$reporter) {
function run($reporter) {
$reporter->paintGroupStart($this->getLabel(), $this->getSize());
$reporter->paintFail('Bad TestSuite [' . $this->getLabel() .
'] with error [' . $this->_error . ']');
'] with error [' . $this->error . ']');
$reporter->paintGroupEnd($this->getLabel());
return $reporter->getStatus();
}
@ -698,11 +655,4 @@ class BadTestSuite {
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
* @package SimpleTest
* @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.
* @access public
*/
function UnitTestCase($label = false) {
function __construct($label = false) {
if (! $label) {
$label = get_class($this);
}
$this->SimpleTestCase($label);
parent::__construct($label);
}
/**
@ -45,7 +45,7 @@ class UnitTestCase extends SimpleTestCase {
* @return boolean True on pass
* @access public
*/
function assertTrue($result, $message = false) {
function assertTrue($result, $message = '%s') {
return $this->assert(new TrueExpectation(), $result, $message);
}
@ -71,7 +71,7 @@ class UnitTestCase extends SimpleTestCase {
* @access public
*/
function assertNull($value, $message = '%s') {
$dumper = &new SimpleDumper();
$dumper = new SimpleDumper();
$message = sprintf(
$message,
'[' . $dumper->describeValue($value) . '] should be null');
@ -86,7 +86,7 @@ class UnitTestCase extends SimpleTestCase {
* @access public
*/
function assertNotNull($value, $message = '%s') {
$dumper = &new SimpleDumper();
$dumper = new SimpleDumper();
$message = sprintf(
$message,
'[' . $dumper->describeValue($value) . '] should not be null');
@ -227,15 +227,18 @@ class UnitTestCase extends SimpleTestCase {
/**
* Will trigger a pass if both parameters refer
* to the same object. Fail otherwise.
* @param mixed $first Object reference to check.
* @param mixed $second Hopefully the same object.
* to the same object or value. Fail otherwise.
* This will cause problems testing objects under
* 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.
* @return boolean True on pass
* @access public
*/
function assertReference(&$first, &$second, $message = '%s') {
$dumper = &new SimpleDumper();
$dumper = new SimpleDumper();
$message = sprintf(
$message,
'[' . $dumper->describeValue($first) .
@ -246,6 +249,29 @@ class UnitTestCase extends SimpleTestCase {
$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
* to different objects. Fail otherwise. The objects
@ -256,25 +282,33 @@ class UnitTestCase extends SimpleTestCase {
* @return boolean True on pass
* @access public
*/
function assertClone(&$first, &$second, $message = '%s') {
$dumper = &new SimpleDumper();
function assertClone($first, $second, $message = '%s') {
$dumper = new SimpleDumper();
$message = sprintf(
$message,
'[' . $dumper->describeValue($first) .
'] and [' . $dumper->describeValue($second) .
'] should not be the same object');
$identical = &new IdenticalExpectation($first);
$identical = new IdenticalExpectation($first);
return $this->assertTrue(
$identical->test($second) &&
! SimpleTestCompatibility::isReference($first, $second),
$identical->test($second) && ! ($first === $second),
$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") {
$dumper = &new SimpleDumper();
$dumper = new SimpleDumper();
$message = sprintf(
$message,
"[" . $dumper->describeValue($first) .
@ -302,13 +336,6 @@ class UnitTestCase extends SimpleTestCase {
$message);
}
/**
* @deprecated
*/
function assertWantedPattern($pattern, $subject, $message = '%s') {
return $this->assertPattern($pattern, $subject, $message);
}
/**
* Will trigger a pass if the perl regex pattern
* is not present in subject. Fail if found.
@ -326,40 +353,6 @@ class UnitTestCase extends SimpleTestCase {
$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
* passes through, otherwise it is swallowed. Any
@ -369,9 +362,8 @@ class UnitTestCase extends SimpleTestCase {
* @access public
*/
function expectError($expected = false, $message = '%s') {
$context = &SimpleTest::getContext();
$queue = &$context->get('SimpleErrorQueue');
$queue->expectError($this->_coerceExpectation($expected), $message);
$queue = SimpleTest::getContext()->get('SimpleErrorQueue');
$queue->expectError($this->coerceExpectation($expected), $message);
}
/**
@ -383,14 +375,22 @@ class UnitTestCase extends SimpleTestCase {
* @access public
*/
function expectException($expected = false, $message = '%s') {
$context = &SimpleTest::getContext();
$queue = &$context->get('SimpleExceptionTrap');
// :HACK: Directly substituting in seems to cause a segfault with
// Zend Optimizer on some systems
$queue = SimpleTest::getContext()->get('SimpleExceptionTrap');
$line = $this->getAssertionLine();
$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
* object/value is not already some type
@ -399,7 +399,7 @@ class UnitTestCase extends SimpleTestCase {
* @return SimpleExpectation Expectation object.
* @access private
*/
function _coerceExpectation($expected) {
protected function coerceExpectation($expected) {
if ($expected == false) {
return new TrueExpectation();
}
@ -409,12 +409,5 @@ class UnitTestCase extends SimpleTestCase {
return new EqualExpectation(
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
* @package SimpleTest
* @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
*/
class SimpleUrl {
var $_scheme;
var $_username;
var $_password;
var $_host;
var $_port;
var $_path;
var $_request;
var $_fragment;
var $_x;
var $_y;
var $_target;
var $_raw = false;
private $scheme;
private $username;
private $password;
private $host;
private $port;
public $path;
private $request;
private $fragment;
private $x;
private $y;
private $target;
private $raw = false;
/**
* Constructor. Parses URL into sections.
* @param string $url Incoming URL.
* @access public
*/
function SimpleUrl($url = '') {
list($x, $y) = $this->_chompCoordinates($url);
function __construct($url = '') {
list($x, $y) = $this->chompCoordinates($url);
$this->setCoordinates($x, $y);
$this->_scheme = $this->_chompScheme($url);
list($this->_username, $this->_password) = $this->_chompLogin($url);
$this->_host = $this->_chompHost($url);
$this->_port = false;
if (preg_match('/(.*?):(.*)/', $this->_host, $host_parts)) {
$this->_host = $host_parts[1];
$this->_port = (integer)$host_parts[2];
$this->scheme = $this->chompScheme($url);
if ($this->scheme === 'file') {
// Unescaped backslashes not used in directory separator context
// will get caught by this, but they should have been urlencoded
// anyway so we don't care. If this ends up being a problem, the
// host regexp must be modified to match for backslashes when
// the scheme is file.
$url = str_replace('\\', '/', $url);
}
$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;
list($this->username, $this->password) = $this->chompLogin($url);
$this->host = $this->chompHost($url);
$this->port = 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.
* @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.
* @access private
*/
function _chompCoordinates(&$url) {
protected function chompCoordinates(&$url) {
if (preg_match('/(.*)\?(\d+),(\d+)$/', $url, $matches)) {
$url = $matches[1];
return array((integer)$matches[2], (integer)$matches[3]);
}
return array(false, false);
}
/**
* Extracts the scheme part of an incoming URL.
* @param string $url URL so far. The scheme will be
@ -80,14 +94,14 @@ class SimpleUrl {
* @return string Scheme part or false.
* @access private
*/
function _chompScheme(&$url) {
if (preg_match('/^([^\/:]*):(\/\/)(.*)/', $url, $matches)) {
protected function chompScheme(&$url) {
if (preg_match('#^([^/:]*):(//)(.*)#', $url, $matches)) {
$url = $matches[2] . $matches[3];
return $matches[1];
}
return false;
}
/**
* Extracts the username and password from the
* incoming URL. The // prefix will be reattached
@ -98,13 +112,13 @@ class SimpleUrl {
* password. Will urldecode() them.
* @access private
*/
function _chompLogin(&$url) {
protected function chompLogin(&$url) {
$prefix = '';
if (preg_match('/^(\/\/)(.*)/', $url, $matches)) {
if (preg_match('#^(//)(.*)#', $url, $matches)) {
$prefix = $matches[1];
$url = $matches[2];
}
if (preg_match('/^([^\/]*)@(.*)/', $url, $matches)) {
if (preg_match('#^([^/]*)@(.*)#', $url, $matches)) {
$url = $prefix . $matches[2];
$parts = explode(":", $matches[1]);
return array(
@ -114,7 +128,7 @@ class SimpleUrl {
$url = $prefix . $url;
return array(false, false);
}
/**
* Extracts the host part of an incoming URL.
* Includes the port number part. Will extract
@ -126,12 +140,12 @@ class SimpleUrl {
* @return string Host part guess or false.
* @access private
*/
function _chompHost(&$url) {
if (preg_match('/^(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) {
protected function chompHost(&$url) {
if (preg_match('!^(//)(.*?)(/.*|\?.*|#.*|$)!', $url, $matches)) {
$url = $matches[3];
return $matches[2];
}
if (preg_match('/(.*?)(\.\.\/|\.\/|\/|\?|#|$)(.*)/', $url, $matches)) {
if (preg_match('!(.*?)(\.\./|\./|/|\?|#|$)(.*)!', $url, $matches)) {
$tlds = SimpleUrl::getAllTopLevelDomains();
if (preg_match('/[a-z0-9\-]+\.(' . $tlds . ')/i', $matches[1])) {
$url = $matches[2] . $matches[3];
@ -143,7 +157,7 @@ class SimpleUrl {
}
return false;
}
/**
* Extracts the path information from the incoming
* URL. Strips this path from the URL.
@ -152,14 +166,14 @@ class SimpleUrl {
* @return string Path part or '/'.
* @access private
*/
function _chompPath(&$url) {
protected function chompPath(&$url) {
if (preg_match('/(.*?)(\?|#|$)(.*)/', $url, $matches)) {
$url = $matches[2] . $matches[3];
return ($matches[1] ? $matches[1] : '');
}
return '';
}
/**
* Strips off the request data.
* @param string $url URL so far. The request will be
@ -167,33 +181,33 @@ class SimpleUrl {
* @return string Raw request part.
* @access private
*/
function _chompRequest(&$url) {
protected function chompRequest(&$url) {
if (preg_match('/\?(.*?)(#|$)(.*)/', $url, $matches)) {
$url = $matches[2] . $matches[3];
return $matches[1];
}
return '';
}
/**
* Breaks the request down into an object.
* @param string $raw Raw request.
* @return SimpleFormEncoding Parsed data.
* @access private
*/
function _parseRequest($raw) {
$this->_raw = $raw;
protected function parseRequest($raw) {
$this->raw = $raw;
$request = new SimpleGetEncoding();
foreach (explode("&", $raw) as $pair) {
if (preg_match('/(.*?)=(.*)/', $pair, $matches)) {
$request->add($matches[1], urldecode($matches[2]));
$request->add(urldecode($matches[1]), urldecode($matches[2]));
} elseif ($pair) {
$request->add($pair, '');
$request->add(urldecode($pair), '');
}
}
return $request;
}
/**
* Accessor for protocol part.
* @param string $default Value to use if not present.
@ -201,27 +215,27 @@ class SimpleUrl {
* @access public
*/
function getScheme($default = false) {
return $this->_scheme ? $this->_scheme : $default;
return $this->scheme ? $this->scheme : $default;
}
/**
* Accessor for user name.
* @return string Username preceding host.
* @access public
*/
function getUsername() {
return $this->_username;
return $this->username;
}
/**
* Accessor for password.
* @return string Password preceding host.
* @access public
*/
function getPassword() {
return $this->_password;
return $this->password;
}
/**
* Accessor for hostname and port.
* @param string $default Value to use if not present.
@ -229,9 +243,9 @@ class SimpleUrl {
* @access public
*/
function getHost($default = false) {
return $this->_host ? $this->_host : $default;
return $this->host ? $this->host : $default;
}
/**
* Accessor for top level domain.
* @return string Last part of host.
@ -241,28 +255,28 @@ class SimpleUrl {
$path_parts = pathinfo($this->getHost());
return (isset($path_parts['extension']) ? $path_parts['extension'] : false);
}
/**
* Accessor for port number.
* @return integer TCP/IP port number.
* @access public
*/
function getPort() {
return $this->_port;
}
return $this->port;
}
/**
* Accessor for path.
* @return string Full path including leading slash if implied.
* @access public
*/
function getPath() {
if (! $this->_path && $this->_host) {
if (! $this->path && $this->host) {
return '/';
}
return $this->_path;
return $this->path;
}
/**
* Accessor for page if any. This may be a
* directory name if ambiguious.
@ -275,7 +289,7 @@ class SimpleUrl {
}
return $matches[1];
}
/**
* Gets the path to the page.
* @return string Path less the page.
@ -287,16 +301,16 @@ class SimpleUrl {
}
return $matches[1];
}
/**
* Accessor for fragment at end of URL after the "#".
* @return string Part after "#".
* @access public
*/
function getFragment() {
return $this->_fragment;
return $this->fragment;
}
/**
* Sets image coordinates. Set to false to clear
* them.
@ -306,31 +320,31 @@ class SimpleUrl {
*/
function setCoordinates($x = false, $y = false) {
if (($x === false) || ($y === false)) {
$this->_x = $this->_y = false;
$this->x = $this->y = false;
return;
}
$this->_x = (integer)$x;
$this->_y = (integer)$y;
$this->x = (integer)$x;
$this->y = (integer)$y;
}
/**
* Accessor for horizontal image coordinate.
* @return integer X value.
* @access public
*/
function getX() {
return $this->_x;
return $this->x;
}
/**
* Accessor for vertical image coordinate.
* @return integer Y value.
* @access public
*/
function getY() {
return $this->_y;
return $this->y;
}
/**
* Accessor for current request parameters
* in URL string form. Will return teh original request
@ -340,17 +354,17 @@ class SimpleUrl {
* @access public
*/
function getEncodedRequest() {
if ($this->_raw) {
$encoded = $this->_raw;
if ($this->raw) {
$encoded = $this->raw;
} else {
$encoded = $this->_request->asUrlRequest();
$encoded = $this->request->asUrlRequest();
}
if ($encoded) {
return '?' . preg_replace('/^\?/', '', $encoded);
}
return '';
}
/**
* Adds an additional parameter to the request.
* @param string $key Name of parameter.
@ -358,10 +372,10 @@ class SimpleUrl {
* @access public
*/
function addRequestParameter($key, $value) {
$this->_raw = false;
$this->_request->add($key, $value);
$this->raw = false;
$this->request->add($key, $value);
}
/**
* Adds additional parameters to the request.
* @param hash/SimpleFormEncoding $parameters Additional
@ -369,19 +383,19 @@ class SimpleUrl {
* @access public
*/
function addRequestParameters($parameters) {
$this->_raw = false;
$this->_request->merge($parameters);
$this->raw = false;
$this->request->merge($parameters);
}
/**
* Clears down all parameters.
* @access public
*/
function clearRequest() {
$this->_raw = false;
$this->_request = &new SimpleGetEncoding();
$this->raw = false;
$this->request = new SimpleGetEncoding();
}
/**
* Gets the frame target if present. Although
* not strictly part of the URL specification it
@ -390,44 +404,53 @@ class SimpleUrl {
* @access public
*/
function getTarget() {
return $this->_target;
return $this->target;
}
/**
* Attaches a frame target.
* @param string $frame Name of frame.
* @access public
*/
function setTarget($frame) {
$this->_raw = false;
$this->_target = $frame;
$this->raw = false;
$this->target = $frame;
}
/**
* Renders the URL back into a string.
* @return string URL in canonical form.
* @access public
*/
function asString() {
$path = $this->_path;
$scheme = $identity = $host = $encoded = $fragment = '';
if ($this->_username && $this->_password) {
$identity = $this->_username . ':' . $this->_password . '@';
$path = $this->path;
$scheme = $identity = $host = $port = $encoded = $fragment = '';
if ($this->username && $this->password) {
$identity = $this->username . ':' . $this->password . '@';
}
if ($this->getHost()) {
$scheme = $this->getScheme() ? $this->getScheme() : 'http';
$scheme .= "://";
$scheme .= '://';
$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) == '/') {
$path = $this->normalisePath($this->_path);
if ($this->getPort() && $this->getPort() != 80 ) {
$port = ':'.$this->getPort();
}
if (substr($this->path, 0, 1) == '/') {
$path = $this->normalisePath($this->path);
}
$encoded = $this->getEncodedRequest();
$fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
$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
* URL into an absolute one. The base URL can
@ -453,13 +476,13 @@ class SimpleUrl {
$port = $base->getPort() ? ':' . $base->getPort() : '';
$identity = $base->getIdentity() ? $base->getIdentity() . '@' : '';
}
$path = $this->normalisePath($this->_extractAbsolutePath($base));
$path = $this->normalisePath($this->extractAbsolutePath($base));
$encoded = $this->getEncodedRequest();
$fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
$coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords");
}
/**
* Replaces unknown sections of the path with base parts
* to return a complete absolute one.
@ -467,29 +490,29 @@ class SimpleUrl {
* @param string Absolute path.
* @access private
*/
function _extractAbsolutePath($base) {
protected function extractAbsolutePath($base) {
if ($this->getHost()) {
return $this->_path;
return $this->path;
}
if (! $this->_isRelativePath($this->_path)) {
return $this->_path;
if (! $this->isRelativePath($this->path)) {
return $this->path;
}
if ($this->_path) {
return $base->getBasePath() . $this->_path;
if ($this->path) {
return $base->getBasePath() . $this->path;
}
return $base->getPath();
}
/**
* Simple test to see if a path part is relative.
* @param string $path Path to test.
* @return boolean True if starts with a "/".
* @access private
*/
function _isRelativePath($path) {
protected function isRelativePath($path) {
return (substr($path, 0, 1) != '/');
}
/**
* Extracts the username and password for use in rendering
* a URL.
@ -497,12 +520,12 @@ class SimpleUrl {
* @access public
*/
function getIdentity() {
if ($this->_username && $this->_password) {
return $this->_username . ':' . $this->_password;
if ($this->username && $this->password) {
return $this->username . ':' . $this->password;
}
return false;
}
/**
* Replaces . and .. sections of the path.
* @param string $path Unoptimised path.
@ -513,16 +536,15 @@ class SimpleUrl {
$path = preg_replace('|/\./|', '/', $path);
return preg_replace('|/[^/]+/\.\./|', '/', $path);
}
/**
* A pipe seperated list of all TLDs that result in two part
* domain names.
* @return string Pipe separated list.
* @access public
* @static
*/
function getAllTopLevelDomains() {
static function getAllTopLevelDomains() {
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
* @package SimpleTest
* @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
*/
class SimpleUserAgent {
var $_cookie_jar;
var $_cookies_enabled = true;
var $_authenticator;
var $_max_redirects = DEFAULT_MAX_REDIRECTS;
var $_proxy = false;
var $_proxy_username = false;
var $_proxy_password = false;
var $_connection_timeout = DEFAULT_CONNECTION_TIMEOUT;
var $_additional_headers = array();
private $cookie_jar;
private $cookies_enabled = true;
private $authenticator;
private $max_redirects = DEFAULT_MAX_REDIRECTS;
private $proxy = false;
private $proxy_username = false;
private $proxy_password = false;
private $connection_timeout = DEFAULT_CONNECTION_TIMEOUT;
private $additional_headers = array();
/**
* Starts with no cookies, realms or proxies.
* @access public
*/
function SimpleUserAgent() {
$this->_cookie_jar = &new SimpleCookieJar();
$this->_authenticator = &new SimpleAuthenticator();
function __construct() {
$this->cookie_jar = new SimpleCookieJar();
$this->authenticator = new SimpleAuthenticator();
}
/**
* Removes expired and temporary cookies as if
* the browser was closed and re-opened. Authorisation
@ -58,10 +58,10 @@ class SimpleUserAgent {
* @access public
*/
function restart($date = false) {
$this->_cookie_jar->restartSession($date);
$this->_authenticator->restartSession();
$this->cookie_jar->restartSession($date);
$this->authenticator->restartSession();
}
/**
* Adds a header to every fetch.
* @param string $header Header line to add to every
@ -69,18 +69,18 @@ class SimpleUserAgent {
* @access public
*/
function addHeader($header) {
$this->_additional_headers[] = $header;
$this->additional_headers[] = $header;
}
/**
* Ages the cookies by the specified time.
* @param integer $interval Amount in seconds.
* @access public
*/
function ageCookies($interval) {
$this->_cookie_jar->agePrematurely($interval);
$this->cookie_jar->agePrematurely($interval);
}
/**
* Sets an additional cookie. If a cookie has
* the same name and path it is replaced.
@ -92,9 +92,9 @@ class SimpleUserAgent {
* @access public
*/
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
* browser cookies.
@ -106,9 +106,9 @@ class SimpleUserAgent {
* @access public
*/
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.
* @param string $name Key of cookie to find.
@ -123,32 +123,32 @@ class SimpleUserAgent {
}
return $this->getCookieValue($base->getHost(), $base->getPath(), $name);
}
/**
* Switches off cookie sending and recieving.
* @access public
*/
function ignoreCookies() {
$this->_cookies_enabled = false;
$this->cookies_enabled = false;
}
/**
* Switches back on the cookie sending and recieving.
* @access public
*/
function useCookies() {
$this->_cookies_enabled = true;
$this->cookies_enabled = true;
}
/**
* Sets the socket timeout for opening a connection.
* @param integer $timeout Maximum time in seconds.
* @access public
*/
function setConnectionTimeout($timeout) {
$this->_connection_timeout = $timeout;
$this->connection_timeout = $timeout;
}
/**
* Sets the maximum number of redirects before
* a page will be loaded anyway.
@ -156,9 +156,9 @@ class SimpleUserAgent {
* @access public
*/
function setMaximumRedirects($max) {
$this->_max_redirects = $max;
$this->max_redirects = $max;
}
/**
* Sets proxy to use on all requests for when
* testing from behind a firewall. Set URL
@ -170,27 +170,27 @@ class SimpleUserAgent {
*/
function useProxy($proxy, $username, $password) {
if (! $proxy) {
$this->_proxy = false;
$this->proxy = false;
return;
}
if ((strncmp($proxy, 'http://', 7) != 0) && (strncmp($proxy, 'https://', 8) != 0)) {
$proxy = 'http://'. $proxy;
}
$this->_proxy = &new SimpleUrl($proxy);
$this->_proxy_username = $username;
$this->_proxy_password = $password;
$this->proxy = new SimpleUrl($proxy);
$this->proxy_username = $username;
$this->proxy_password = $password;
}
/**
* Test to see if the redirect limit is passed.
* @param integer $redirects Count so far.
* @return boolean True if over.
* @access private
*/
function _isTooManyRedirects($redirects) {
return ($redirects > $this->_max_redirects);
protected function isTooManyRedirects($redirects) {
return ($redirects > $this->max_redirects);
}
/**
* Sets the identity for the current realm.
* @param string $host Host to which realm applies.
@ -200,9 +200,9 @@ class SimpleUserAgent {
* @access public
*/
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.
* It will also collect authentication realm information.
@ -211,15 +211,15 @@ class SimpleUserAgent {
* @return SimpleHttpResponse Hopefully the target page.
* @access public
*/
function &fetchResponse($url, $encoding) {
function fetchResponse($url, $encoding) {
if ($encoding->getMethod() != 'POST') {
$url->addRequestParameters($encoding);
$encoding->clear();
}
$response = &$this->_fetchWhileRedirected($url, $encoding);
$response = $this->fetchWhileRedirected($url, $encoding);
if ($headers = $response->getHeaders()) {
if ($headers->isChallenge()) {
$this->_authenticator->addRealm(
$this->authenticator->addRealm(
$url,
$headers->getAuthentication(),
$headers->getRealm());
@ -227,7 +227,7 @@ class SimpleUserAgent {
}
return $response;
}
/**
* Fetches the page until no longer redirected or
* until the redirect limit runs out.
@ -236,27 +236,27 @@ class SimpleUserAgent {
* @return SimpleHttpResponse Hopefully the target page.
* @access private
*/
function &_fetchWhileRedirected($url, $encoding) {
protected function fetchWhileRedirected($url, $encoding) {
$redirects = 0;
do {
$response = &$this->_fetch($url, $encoding);
$response = $this->fetch($url, $encoding);
if ($response->isError()) {
return $response;
}
$headers = $response->getHeaders();
$location = new SimpleUrl($headers->getLocation());
$url = $location->makeAbsolute($url);
if ($this->_cookies_enabled) {
$headers->writeCookiesToJar($this->_cookie_jar, $url);
if ($this->cookies_enabled) {
$headers->writeCookiesToJar($this->cookie_jar, $url);
}
if (! $headers->isRedirect()) {
break;
}
$location = new SimpleUrl($headers->getLocation());
$url = $location->makeAbsolute($url);
$encoding = new SimpleGetEncoding();
} while (! $this->_isTooManyRedirects(++$redirects));
} while (! $this->isTooManyRedirects(++$redirects));
return $response;
}
/**
* Actually make the web request.
* @param SimpleUrl $url Target to fetch.
@ -264,12 +264,11 @@ class SimpleUserAgent {
* @return SimpleHttpResponse Headers and hopefully content.
* @access protected
*/
function &_fetch($url, $encoding) {
$request = &$this->_createRequest($url, $encoding);
$response = &$request->fetch($this->_connection_timeout);
return $response;
protected function fetch($url, $encoding) {
$request = $this->createRequest($url, $encoding);
return $request->fetch($this->connection_timeout);
}
/**
* Creates a full page request.
* @param SimpleUrl $url Target to fetch as url object.
@ -277,16 +276,16 @@ class SimpleUserAgent {
* @return SimpleHttpRequest New request.
* @access private
*/
function &_createRequest($url, $encoding) {
$request = &$this->_createHttpRequest($url, $encoding);
$this->_addAdditionalHeaders($request);
if ($this->_cookies_enabled) {
$request->readCookiesFromJar($this->_cookie_jar, $url);
protected function createRequest($url, $encoding) {
$request = $this->createHttpRequest($url, $encoding);
$this->addAdditionalHeaders($request);
if ($this->cookies_enabled) {
$request->readCookiesFromJar($this->cookie_jar, $url);
}
$this->_authenticator->addHeaders($request, $url);
$this->authenticator->addHeaders($request, $url);
return $request;
}
/**
* Builds the appropriate HTTP request object.
* @param SimpleUrl $url Target to fetch as url object.
@ -294,37 +293,34 @@ class SimpleUserAgent {
* @return SimpleHttpRequest New request object.
* @access protected
*/
function &_createHttpRequest($url, $encoding) {
$request = &new SimpleHttpRequest($this->_createRoute($url), $encoding);
return $request;
protected function createHttpRequest($url, $encoding) {
return new SimpleHttpRequest($this->createRoute($url), $encoding);
}
/**
* Sets up either a direct route or via a proxy.
* @param SimpleUrl $url Target to fetch as url object.
* @return SimpleRoute Route to take to fetch URL.
* @access protected
*/
function &_createRoute($url) {
if ($this->_proxy) {
$route = &new SimpleProxyRoute(
protected function createRoute($url) {
if ($this->proxy) {
return new SimpleProxyRoute(
$url,
$this->_proxy,
$this->_proxy_username,
$this->_proxy_password);
} else {
$route = &new SimpleRoute($url);
$this->proxy,
$this->proxy_username,
$this->proxy_password);
}
return $route;
return new SimpleRoute($url);
}
/**
* Adds additional manual headers.
* @param SimpleHttpRequest $request Outgoing request.
* @access private
*/
function _addAdditionalHeaders(&$request) {
foreach ($this->_additional_headers as $header) {
protected function addAdditionalHeaders(&$request) {
foreach ($this->additional_headers as $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
* @package SimpleTest
* @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
*/
class XmlReporter extends SimpleReporter {
var $_indent;
var $_namespace;
private $indent;
private $namespace;
/**
* Sets up indentation and namespace.
@ -28,10 +28,10 @@ class XmlReporter extends SimpleReporter {
* @param string $indent Indenting to add on each nesting.
* @access public
*/
function XmlReporter($namespace = false, $indent = ' ') {
$this->SimpleReporter();
$this->_namespace = ($namespace ? $namespace . ':' : '');
$this->_indent = $indent;
function __construct($namespace = false, $indent = ' ') {
parent::__construct();
$this->namespace = ($namespace ? $namespace . ':' : '');
$this->indent = $indent;
}
/**
@ -41,9 +41,9 @@ class XmlReporter extends SimpleReporter {
* @return string Leading space.
* @access protected
*/
function _getIndent($offset = 0) {
protected function getIndent($offset = 0) {
return str_repeat(
$this->_indent,
$this->indent,
count($this->getTestList()) + $offset);
}
@ -69,12 +69,12 @@ class XmlReporter extends SimpleReporter {
*/
function paintGroupStart($test_name, $size) {
parent::paintGroupStart($test_name, $size);
print $this->_getIndent();
print "<" . $this->_namespace . "group size=\"$size\">\n";
print $this->_getIndent(1);
print "<" . $this->_namespace . "name>" .
print $this->getIndent();
print "<" . $this->namespace . "group size=\"$size\">\n";
print $this->getIndent(1);
print "<" . $this->namespace . "name>" .
$this->toParsedXml($test_name) .
"</" . $this->_namespace . "name>\n";
"</" . $this->namespace . "name>\n";
}
/**
@ -83,8 +83,8 @@ class XmlReporter extends SimpleReporter {
* @access public
*/
function paintGroupEnd($test_name) {
print $this->_getIndent();
print "</" . $this->_namespace . "group>\n";
print $this->getIndent();
print "</" . $this->namespace . "group>\n";
parent::paintGroupEnd($test_name);
}
@ -95,12 +95,12 @@ class XmlReporter extends SimpleReporter {
*/
function paintCaseStart($test_name) {
parent::paintCaseStart($test_name);
print $this->_getIndent();
print "<" . $this->_namespace . "case>\n";
print $this->_getIndent(1);
print "<" . $this->_namespace . "name>" .
print $this->getIndent();
print "<" . $this->namespace . "case>\n";
print $this->getIndent(1);
print "<" . $this->namespace . "name>" .
$this->toParsedXml($test_name) .
"</" . $this->_namespace . "name>\n";
"</" . $this->namespace . "name>\n";
}
/**
@ -109,8 +109,8 @@ class XmlReporter extends SimpleReporter {
* @access public
*/
function paintCaseEnd($test_name) {
print $this->_getIndent();
print "</" . $this->_namespace . "case>\n";
print $this->getIndent();
print "</" . $this->namespace . "case>\n";
parent::paintCaseEnd($test_name);
}
@ -121,12 +121,12 @@ class XmlReporter extends SimpleReporter {
*/
function paintMethodStart($test_name) {
parent::paintMethodStart($test_name);
print $this->_getIndent();
print "<" . $this->_namespace . "test>\n";
print $this->_getIndent(1);
print "<" . $this->_namespace . "name>" .
print $this->getIndent();
print "<" . $this->namespace . "test>\n";
print $this->getIndent(1);
print "<" . $this->namespace . "name>" .
$this->toParsedXml($test_name) .
"</" . $this->_namespace . "name>\n";
"</" . $this->namespace . "name>\n";
}
/**
@ -136,8 +136,8 @@ class XmlReporter extends SimpleReporter {
* @access public
*/
function paintMethodEnd($test_name) {
print $this->_getIndent();
print "</" . $this->_namespace . "test>\n";
print $this->getIndent();
print "</" . $this->namespace . "test>\n";
parent::paintMethodEnd($test_name);
}
@ -148,10 +148,10 @@ class XmlReporter extends SimpleReporter {
*/
function paintPass($message) {
parent::paintPass($message);
print $this->_getIndent(1);
print "<" . $this->_namespace . "pass>";
print $this->getIndent(1);
print "<" . $this->namespace . "pass>";
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) {
parent::paintFail($message);
print $this->_getIndent(1);
print "<" . $this->_namespace . "fail>";
print $this->getIndent(1);
print "<" . $this->namespace . "fail>";
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) {
parent::paintError($message);
print $this->_getIndent(1);
print "<" . $this->_namespace . "exception>";
print $this->getIndent(1);
print "<" . $this->namespace . "exception>";
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) {
parent::paintException($exception);
print $this->_getIndent(1);
print "<" . $this->_namespace . "exception>";
print $this->getIndent(1);
print "<" . $this->namespace . "exception>";
$message = 'Unexpected exception of type [' . get_class($exception) .
'] with message ['. $exception->getMessage() .
'] in ['. $exception->getFile() .
' line ' . $exception->getLine() . ']';
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) {
parent::paintSkip($message);
print $this->_getIndent(1);
print "<" . $this->_namespace . "skip>";
print $this->getIndent(1);
print "<" . $this->namespace . "skip>";
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) {
parent::paintMessage($message);
print $this->_getIndent(1);
print "<" . $this->_namespace . "message>";
print $this->getIndent(1);
print "<" . $this->namespace . "message>";
print $this->toParsedXml($message);
print "</" . $this->_namespace . "message>\n";
print "</" . $this->namespace . "message>\n";
}
/**
* Paints a formatted ASCII message such as a
* variable dump.
* privateiable dump.
* @param string $message Text to display.
* @access public
*/
function paintFormattedMessage($message) {
parent::paintFormattedMessage($message);
print $this->_getIndent(1);
print "<" . $this->_namespace . "formatted>";
print $this->getIndent(1);
print "<" . $this->namespace . "formatted>";
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) {
parent::paintSignal($type, $payload);
print $this->_getIndent(1);
print "<" . $this->_namespace . "signal type=\"$type\">";
print $this->getIndent(1);
print "<" . $this->namespace . "signal type=\"$type\">";
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');
}
print "<?xml version=\"1.0\"";
if ($this->_namespace) {
print " xmlns:" . $this->_namespace .
if ($this->namespace) {
print " xmlns:" . $this->namespace .
"=\"www.lastcraft.com/SimpleTest/Beta3/Report\"";
}
print "?>\n";
print "<" . $this->_namespace . "run>\n";
print "<" . $this->namespace . "run>\n";
}
/**
@ -278,7 +278,7 @@ class XmlReporter extends SimpleReporter {
* @abstract
*/
function paintFooter($test_name) {
print "</" . $this->_namespace . "run>\n";
print "</" . $this->namespace . "run>\n";
}
}
@ -290,8 +290,8 @@ class XmlReporter extends SimpleReporter {
* @subpackage UnitTester
*/
class NestingXmlTag {
var $_name;
var $_attributes;
private $name;
private $attributes;
/**
* Sets the basic test information except
@ -300,8 +300,8 @@ class NestingXmlTag {
* @access public
*/
function NestingXmlTag($attributes) {
$this->_name = false;
$this->_attributes = $attributes;
$this->name = false;
$this->attributes = $attributes;
}
/**
@ -310,7 +310,7 @@ class NestingXmlTag {
* @access public
*/
function setName($name) {
$this->_name = $name;
$this->name = $name;
}
/**
@ -319,7 +319,7 @@ class NestingXmlTag {
* @access public
*/
function getName() {
return $this->_name;
return $this->name;
}
/**
@ -327,8 +327,8 @@ class NestingXmlTag {
* @return hash All attributes.
* @access protected
*/
function _getAttributes() {
return $this->_attributes;
protected function getAttributes() {
return $this->attributes;
}
}
@ -457,7 +457,7 @@ class NestingGroupTag extends NestingXmlTag {
* @access public
*/
function getSize() {
$attributes = $this->_getAttributes();
$attributes = $this->getAttributes();
if (isset($attributes['SIZE'])) {
return (integer)$attributes['SIZE'];
}
@ -472,12 +472,12 @@ class NestingGroupTag extends NestingXmlTag {
* @subpackage UnitTester
*/
class SimpleTestXmlParser {
var $_listener;
var $_expat;
var $_tag_stack;
var $_in_content_tag;
var $_content;
var $_attributes;
private $listener;
private $expat;
private $tag_stack;
private $in_content_tag;
private $content;
private $attributes;
/**
* Loads a listener with the SimpleReporter
@ -486,12 +486,12 @@ class SimpleTestXmlParser {
* @access public
*/
function SimpleTestXmlParser(&$listener) {
$this->_listener = &$listener;
$this->_expat = &$this->_createParser();
$this->_tag_stack = array();
$this->_in_content_tag = false;
$this->_content = '';
$this->_attributes = array();
$this->listener = &$listener;
$this->expat = &$this->createParser();
$this->tag_stack = array();
$this->in_content_tag = false;
$this->content = '';
$this->attributes = array();
}
/**
@ -502,9 +502,9 @@ class SimpleTestXmlParser {
* @access public
*/
function parse($chunk) {
if (! xml_parse($this->_expat, $chunk)) {
if (! xml_parse($this->expat, $chunk)) {
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 true;
@ -515,12 +515,12 @@ class SimpleTestXmlParser {
* @return resource Expat handle.
* @access protected
*/
function &_createParser() {
protected function &createParser() {
$expat = xml_parser_create();
xml_set_object($expat, $this);
xml_set_element_handler($expat, '_startElement', '_endElement');
xml_set_character_data_handler($expat, '_addContent');
xml_set_default_handler($expat, '_default');
xml_set_element_handler($expat, 'startElement', 'endElement');
xml_set_character_data_handler($expat, 'addContent');
xml_set_default_handler($expat, 'defaultContent');
return $expat;
}
@ -530,8 +530,8 @@ class SimpleTestXmlParser {
* to start.
* @access private
*/
function _pushNestingTag($nested) {
array_unshift($this->_tag_stack, $nested);
protected function pushNestingTag($nested) {
array_unshift($this->tag_stack, $nested);
}
/**
@ -540,8 +540,8 @@ class SimpleTestXmlParser {
* being parsed.
* @access private
*/
function &_getCurrentNestingTag() {
return $this->_tag_stack[0];
protected function &getCurrentNestingTag() {
return $this->tag_stack[0];
}
/**
@ -550,8 +550,8 @@ class SimpleTestXmlParser {
* just finished.
* @access private
*/
function _popNestingTag() {
return array_shift($this->_tag_stack);
protected function popNestingTag() {
return array_shift($this->tag_stack);
}
/**
@ -560,7 +560,7 @@ class SimpleTestXmlParser {
* @return @boolean True if leaf, false if nesting.
* @private
*/
function _isLeaf($tag) {
protected function isLeaf($tag) {
return in_array($tag, array(
'NAME', 'PASS', 'FAIL', 'EXCEPTION', 'SKIP', 'MESSAGE', 'FORMATTED', 'SIGNAL'));
}
@ -574,17 +574,17 @@ class SimpleTestXmlParser {
* are marked as true.
* @access protected
*/
function _startElement($expat, $tag, $attributes) {
$this->_attributes = $attributes;
protected function startElement($expat, $tag, $attributes) {
$this->attributes = $attributes;
if ($tag == 'GROUP') {
$this->_pushNestingTag(new NestingGroupTag($attributes));
$this->pushNestingTag(new NestingGroupTag($attributes));
} elseif ($tag == 'CASE') {
$this->_pushNestingTag(new NestingCaseTag($attributes));
$this->pushNestingTag(new NestingCaseTag($attributes));
} elseif ($tag == 'TEST') {
$this->_pushNestingTag(new NestingMethodTag($attributes));
} elseif ($this->_isLeaf($tag)) {
$this->_in_content_tag = true;
$this->_content = '';
$this->pushNestingTag(new NestingMethodTag($attributes));
} elseif ($this->isLeaf($tag)) {
$this->in_content_tag = true;
$this->content = '';
}
}
@ -594,31 +594,31 @@ class SimpleTestXmlParser {
* @param string $tag Element name.
* @access protected
*/
function _endElement($expat, $tag) {
$this->_in_content_tag = false;
protected function endElement($expat, $tag) {
$this->in_content_tag = false;
if (in_array($tag, array('GROUP', 'CASE', 'TEST'))) {
$nesting_tag = $this->_popNestingTag();
$nesting_tag->paintEnd($this->_listener);
$nesting_tag = $this->popNestingTag();
$nesting_tag->paintEnd($this->listener);
} elseif ($tag == 'NAME') {
$nesting_tag = &$this->_getCurrentNestingTag();
$nesting_tag->setName($this->_content);
$nesting_tag->paintStart($this->_listener);
$nesting_tag = &$this->getCurrentNestingTag();
$nesting_tag->setName($this->content);
$nesting_tag->paintStart($this->listener);
} elseif ($tag == 'PASS') {
$this->_listener->paintPass($this->_content);
$this->listener->paintPass($this->content);
} elseif ($tag == 'FAIL') {
$this->_listener->paintFail($this->_content);
$this->listener->paintFail($this->content);
} elseif ($tag == 'EXCEPTION') {
$this->_listener->paintError($this->_content);
$this->listener->paintError($this->content);
} elseif ($tag == 'SKIP') {
$this->_listener->paintSkip($this->_content);
$this->listener->paintSkip($this->content);
} elseif ($tag == 'SIGNAL') {
$this->_listener->paintSignal(
$this->_attributes['TYPE'],
unserialize($this->_content));
$this->listener->paintSignal(
$this->attributes['TYPE'],
unserialize($this->content));
} elseif ($tag == 'MESSAGE') {
$this->_listener->paintMessage($this->_content);
$this->listener->paintMessage($this->content);
} 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.
* @access protected
*/
function _addContent($expat, $text) {
if ($this->_in_content_tag) {
$this->_content .= $text;
protected function addContent($expat, $text) {
if ($this->in_content_tag) {
$this->content .= $text;
}
return true;
}
@ -641,7 +641,7 @@ class SimpleTestXmlParser {
* @param string $default Text of default content.
* @access protected
*/
function _default($expat, $default) {
protected function defaultContent($expat, $default) {
}
}
?>