merging changes from [428]

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

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

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

View file

@ -1,201 +1,241 @@
Simple Test interface changes
=============================
Because the SimpleTest tool set is still evolving it is likely that tests
written with earlier versions will fail with the newest ones. The most
dramatic changes are in the alpha releases. Here is a list of possible
problems...
No HTML when matching page elements
-----------------------------------
This behaviour has been switched to using plain text as if it
were seen by the user of the browser. This means that HTML tags
are suppressed, entities are converted and whitespace is
normalised. This should make it easier to match items in forms.
Also images are replaced with their "alt" text so that they
can be matched as well.
No method SimpleRunner::_getTestCase()
--------------------------------------
This was made public as getTestCase() in 1.0RC2.
No method restartSession()
--------------------------
This was renamed to restart() in the WebTestCase, SimpleBrowser
and the underlying SimpleUserAgent in 1.0RC2. Because it was
undocumented anyway, no attempt was made at backward
compatibility.
My custom test case ignored by tally()
--------------------------------------
The _assertTrue method has had it's signature changed due to a bug
in the PHP 5.0.1 release. You must now use getTest() from within
that method to get the test case.
Broken code extending SimpleRunner
----------------------------------
This was replaced with SimpleScorer so that I could use the runner
name in another class. This happened in RC1 development and there
is no easy backward compatibility fix. The solution is simply to
extend SimpleScorer instead.
Missing method getBaseCookieValue()
-----------------------------------
This was renamed getCurrentCookieValue() in RC1.
Missing files from the SimpleTest suite
---------------------------------------
Versions of SimpleTest prior to Beta6 required a SIMPLE_TEST constant
to point at the SimpleTest folder location before any of the toolset
was loaded. This is no longer documented as it is now unnecessary
for later versions. If you are using an earlier version you may
need this constant. Consult the documentation that was bundled with
the release that you are using or upgrade to Beta6 or later.
No method SimpleBrowser::getCurrentUrl()
--------------------------------------
This is replaced with the more versatile showRequest() for
debugging. It only existed in this context for version Beta5.
Later versions will have SimpleBrowser::getHistory() for tracking
paths through pages. It is renamed as getUrl() since 1.0RC1.
No method Stub::setStubBaseClass()
----------------------------------
This method has finally been removed in 1.0RC1. Use
SimpleTestOptions::setStubBaseClass() instead.
No class CommandLineReporter
----------------------------
This was renamed to TextReporter in Beta3 and the deprecated version
was removed in 1.0RC1.
No method requireReturn()
-------------------------
This was deprecated in Beta3 and is now removed.
No method expectCookie()
------------------------
This method was abruptly removed in Beta4 so as to simplify the internals
until another mechanism can replace it. As a workaround it is necessary
to assert that the cookie has changed by setting it before the page
fetch and then assert the desired value.
No method clickSubmitByFormId()
-------------------------------
This method had an incorrect name as no button was involved. It was
renamed to submitByFormId() in Beta4 and the old version deprecated.
Now removed.
No method paintStart() or paintEnd()
------------------------------------
You should only get this error if you have subclassed the lower level
reporting and test runner machinery. These methods have been broken
down into events for test methods, events for test cases and events
for group tests. The new methods are...
paintStart() --> paintMethodStart(), paintCaseStart(), paintGroupStart()
paintEnd() --> paintMethodEnd(), paintCaseEnd(), paintGroupEnd()
This change was made in Beta3, ironically to make it easier to subclass
the inner machinery. Simply duplicating the code you had in the previous
methods should provide a temporary fix.
No class TestDisplay
--------------------
This has been folded into SimpleReporter in Beta3 and is now deprecated.
It was removed in RC1.
No method WebTestCase::fetch()
------------------------------
This was renamed get() in Alpha8. It is removed in Beta3.
No method submit()
------------------
This has been renamed clickSubmit() in Beta1. The old method was
removed in Beta2.
No method clearHistory()
------------------------
This method is deprecated in Beta2 and removed in RC1.
No method getCallCount()
------------------------
This method has been deprecated since Beta1 and has now been
removed. There are now more ways to set expectations on counts
and so this method should be unecessery. Removed in RC1.
Cannot find file *
------------------
The following public name changes have occoured...
simple_html_test.php --> reporter.php
simple_mock.php --> mock_objects.php
simple_unit.php --> unit_tester.php
simple_web.php --> web_tester.php
The old names were deprecated in Alpha8 and removed in Beta1.
No method attachObserver()
--------------------------
Prior to the Alpha8 release the old internal observer pattern was
gutted and replaced with a visitor. This is to trade flexibility of
test case expansion against the ease of writing user interfaces.
Code such as...
$test = &new MyTestCase();
$test->attachObserver(new TestHtmlDisplay());
$test->run();
...should be rewritten as...
$test = &new MyTestCase();
$test->run(new HtmlReporter());
If you previously attached multiple observers then the workaround
is to run the tests twice, once with each, until they can be combined.
For one observer the old method is simulated in Alpha 8, but is
removed in Beta1.
No class TestHtmlDisplay
------------------------
This class has been renamed to HtmlReporter in Alpha8. It is supported,
but deprecated in Beta1 and removed in Beta2. If you have subclassed
the display for your own design, then you will have to extend this
class (HtmlReporter) instead.
If you have accessed the event queue by overriding the notify() method
then I am afraid you are in big trouble :(. The reporter is now
carried around the test suite by the runner classes and the methods
called directly. In the unlikely event that this is a problem and
you don't want to upgrade the test tool then simplest is to write your
own runner class and invoke the tests with...
$test->accept(new MyRunner(new MyReporter()));
...rather than the run method. This should be easier to extend
anyway and gives much more control. Even this method is overhauled
in Beta3 where the runner class can be set within the test case. Really
the best thing to do is to upgrade to this version as whatever you were
trying to achieve before should now be very much easier.
Missing set options method
--------------------------
All test suite options are now in one class called SimpleTestOptions.
This means that options are set differently...
GroupTest::ignore() --> SimpleTestOptions::ignore()
Mock::setMockBaseClass() --> SimpleTestOptions::setMockBaseClass()
These changed in Alpha8 and the old versions are now removed in RC1.
No method setExpected*()
------------------------
The mock expectations changed their names in Alpha4 and the old names
ceased to be supported in Alpha8. The changes are...
setExpectedArguments() --> expectArguments()
setExpectedArgumentsSequence() --> expectArgumentsAt()
setExpectedCallCount() --> expectCallCount()
setMaximumCallCount() --> expectMaximumCallCount()
The parameters remained the same.
Simple Test interface changes
=============================
Because the SimpleTest tool set is still evolving it is likely that tests
written with earlier versions will fail with the newest ones. The most
dramatic changes are in the alpha releases. Here is a list of possible
problems and their fixes...
No class WantedPatternExpectation
---------------------------------
This was deprecated in 1.0.1alpha in favour of the simpler
name PatternExpectation.
No class NoUnwantedPatternExpectation
-------------------------------------
This was deprecated in 1.0.1alpha in favour of the simpler
name NoPatternExpectation.
No method assertNoUnwantedPattern()
-----------------------------------
This has been renamed to assertNoPattern() in 1.0.1alpha and
the old form is deprecated.
No method assertWantedPattern()
-------------------------------
This has been renamed to assertPattern() in 1.0.1alpha and
the old form is deprecated.
No method assertExpectation()
-----------------------------
This was renamed as assert() in 1.0.1alpha and the old form
has been deprecated.
No class WildcardExpectation
----------------------------
This was a mostly internal class for the mock objects. It was
renamed AnythingExpectation to bring it closer to JMock and
NMock in version 1.0.1alpha.
Missing UnitTestCase::assertErrorPattern()
------------------------------------------
This method is deprecated for version 1.0.1 onwards.
This method has been subsumed by assertError() that can now
take an expectation. Simply pass a PatternExpectation
into assertError() to simulate the old behaviour.
No HTML when matching page elements
-----------------------------------
This behaviour has been switched to using plain text as if it
were seen by the user of the browser. This means that HTML tags
are suppressed, entities are converted and whitespace is
normalised. This should make it easier to match items in forms.
Also images are replaced with their "alt" text so that they
can be matched as well.
No method SimpleRunner::_getTestCase()
--------------------------------------
This was made public as getTestCase() in 1.0RC2.
No method restartSession()
--------------------------
This was renamed to restart() in the WebTestCase, SimpleBrowser
and the underlying SimpleUserAgent in 1.0RC2. Because it was
undocumented anyway, no attempt was made at backward
compatibility.
My custom test case ignored by tally()
--------------------------------------
The _assertTrue method has had it's signature changed due to a bug
in the PHP 5.0.1 release. You must now use getTest() from within
that method to get the test case. Mock compatibility with other
unit testers is now deprecated as of 1.0.1alpha as PEAR::PHUnit2
should soon have mock support of it's own.
Broken code extending SimpleRunner
----------------------------------
This was replaced with SimpleScorer so that I could use the runner
name in another class. This happened in RC1 development and there
is no easy backward compatibility fix. The solution is simply to
extend SimpleScorer instead.
Missing method getBaseCookieValue()
-----------------------------------
This was renamed getCurrentCookieValue() in RC1.
Missing files from the SimpleTest suite
---------------------------------------
Versions of SimpleTest prior to Beta6 required a SIMPLE_TEST constant
to point at the SimpleTest folder location before any of the toolset
was loaded. This is no longer documented as it is now unnecessary
for later versions. If you are using an earlier version you may
need this constant. Consult the documentation that was bundled with
the release that you are using or upgrade to Beta6 or later.
No method SimpleBrowser::getCurrentUrl()
--------------------------------------
This is replaced with the more versatile showRequest() for
debugging. It only existed in this context for version Beta5.
Later versions will have SimpleBrowser::getHistory() for tracking
paths through pages. It is renamed as getUrl() since 1.0RC1.
No method Stub::setStubBaseClass()
----------------------------------
This method has finally been removed in 1.0RC1. Use
SimpleTestOptions::setStubBaseClass() instead.
No class CommandLineReporter
----------------------------
This was renamed to TextReporter in Beta3 and the deprecated version
was removed in 1.0RC1.
No method requireReturn()
-------------------------
This was deprecated in Beta3 and is now removed.
No method expectCookie()
------------------------
This method was abruptly removed in Beta4 so as to simplify the internals
until another mechanism can replace it. As a workaround it is necessary
to assert that the cookie has changed by setting it before the page
fetch and then assert the desired value.
No method clickSubmitByFormId()
-------------------------------
This method had an incorrect name as no button was involved. It was
renamed to submitByFormId() in Beta4 and the old version deprecated.
Now removed.
No method paintStart() or paintEnd()
------------------------------------
You should only get this error if you have subclassed the lower level
reporting and test runner machinery. These methods have been broken
down into events for test methods, events for test cases and events
for group tests. The new methods are...
paintStart() --> paintMethodStart(), paintCaseStart(), paintGroupStart()
paintEnd() --> paintMethodEnd(), paintCaseEnd(), paintGroupEnd()
This change was made in Beta3, ironically to make it easier to subclass
the inner machinery. Simply duplicating the code you had in the previous
methods should provide a temporary fix.
No class TestDisplay
--------------------
This has been folded into SimpleReporter in Beta3 and is now deprecated.
It was removed in RC1.
No method WebTestCase::fetch()
------------------------------
This was renamed get() in Alpha8. It is removed in Beta3.
No method submit()
------------------
This has been renamed clickSubmit() in Beta1. The old method was
removed in Beta2.
No method clearHistory()
------------------------
This method is deprecated in Beta2 and removed in RC1.
No method getCallCount()
------------------------
This method has been deprecated since Beta1 and has now been
removed. There are now more ways to set expectations on counts
and so this method should be unecessery. Removed in RC1.
Cannot find file *
------------------
The following public name changes have occoured...
simple_html_test.php --> reporter.php
simple_mock.php --> mock_objects.php
simple_unit.php --> unit_tester.php
simple_web.php --> web_tester.php
The old names were deprecated in Alpha8 and removed in Beta1.
No method attachObserver()
--------------------------
Prior to the Alpha8 release the old internal observer pattern was
gutted and replaced with a visitor. This is to trade flexibility of
test case expansion against the ease of writing user interfaces.
Code such as...
$test = &new MyTestCase();
$test->attachObserver(new TestHtmlDisplay());
$test->run();
...should be rewritten as...
$test = &new MyTestCase();
$test->run(new HtmlReporter());
If you previously attached multiple observers then the workaround
is to run the tests twice, once with each, until they can be combined.
For one observer the old method is simulated in Alpha 8, but is
removed in Beta1.
No class TestHtmlDisplay
------------------------
This class has been renamed to HtmlReporter in Alpha8. It is supported,
but deprecated in Beta1 and removed in Beta2. If you have subclassed
the display for your own design, then you will have to extend this
class (HtmlReporter) instead.
If you have accessed the event queue by overriding the notify() method
then I am afraid you are in big trouble :(. The reporter is now
carried around the test suite by the runner classes and the methods
called directly. In the unlikely event that this is a problem and
you don't want to upgrade the test tool then simplest is to write your
own runner class and invoke the tests with...
$test->accept(new MyRunner(new MyReporter()));
...rather than the run method. This should be easier to extend
anyway and gives much more control. Even this method is overhauled
in Beta3 where the runner class can be set within the test case. Really
the best thing to do is to upgrade to this version as whatever you were
trying to achieve before should now be very much easier.
Missing set options method
--------------------------
All test suite options are now in one class called SimpleTestOptions.
This means that options are set differently...
GroupTest::ignore() --> SimpleTestOptions::ignore()
Mock::setMockBaseClass() --> SimpleTestOptions::setMockBaseClass()
These changed in Alpha8 and the old versions are now removed in RC1.
No method setExpected*()
------------------------
The mock expectations changed their names in Alpha4 and the old names
ceased to be supported in Alpha8. The changes are...
setExpectedArguments() --> expectArguments()
setExpectedArgumentsSequence() --> expectArgumentsAt()
setExpectedCallCount() --> expectCallCount()
setMaximumCallCount() --> expectMaximumCallCount()
The parameters remained the same.

View file

@ -18,10 +18,10 @@ If you find a bug in one of the standards mode test cases, please let us know so
Definitions:
* "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification.
* "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder.
* "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package.
* "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.)
* "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification.
* "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder.
* "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package.
* "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.)
* "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it.
1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers.
@ -46,4 +46,4 @@ accompany any non-standard executables and testcases with their corresponding St
9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
The End
The End

View file

@ -107,4 +107,4 @@ Feucks. Early adopters are always an inspiration.
yours Marcus Baker, Jason Sweat and Perrick Penet.
--
marcus@lastcraft.com
marcus@lastcraft.com

View file

@ -1 +1 @@
1.0
1.0.1alpha

View file

@ -1,34 +1,34 @@
<?php
/**
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
* @version $Id$
*/
/**
* include http class
*/
/**
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
* @version $Id$
*/
/**
* include http class
*/
require_once(dirname(__FILE__) . '/http.php');
/**
* Represents a single security realm's identity.
* @package SimpleTest
* @subpackage WebTester
*/
/**
* Represents a single security realm's identity.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleRealm {
var $_type;
var $_root;
var $_username;
var $_password;
/**
* Starts with the initial entry directory.
* @param string $type Authentication type for this
* realm. Only Basic authentication
* is currently supported.
* @param SimpleUrl $url Somewhere in realm.
* @access public
*/
/**
* Starts with the initial entry directory.
* @param string $type Authentication type for this
* realm. Only Basic authentication
* is currently supported.
* @param SimpleUrl $url Somewhere in realm.
* @access public
*/
function SimpleRealm($type, $url) {
$this->_type = $type;
$this->_root = $url->getBasePath();
@ -36,22 +36,22 @@
$this->_password = false;
}
/**
* Adds another location to the realm.
* @param SimpleUrl $url Somewhere in realm.
* @access public
*/
/**
* 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());
}
/**
* Finds the common starting path.
* @param string $first Path to compare.
* @param string $second Path to compare.
* @return string Common directories.
* @access private
*/
/**
* Finds the common starting path.
* @param string $first Path to compare.
* @param string $second Path to compare.
* @return string Common directories.
* @access private
*/
function _getCommonPath($first, $second) {
$first = explode('/', $first);
$second = explode('/', $second);
@ -63,112 +63,131 @@
return implode('/', $first) . '/';
}
/**
* Sets the identity to try within this realm.
* @param string $username Username in authentication dialog.
* @param string $username Password in authentication dialog.
* @access public
*/
/**
* Sets the identity to try within this realm.
* @param string $username Username in authentication dialog.
* @param string $username Password in authentication dialog.
* @access public
*/
function setIdentity($username, $password) {
$this->_username = $username;
$this->_password = $password;
}
/**
* Accessor for current identity.
* @return string Last succesful username.
* @access public
*/
/**
* Accessor for current identity.
* @return string Last succesful username.
* @access public
*/
function getUsername() {
return $this->_username;
}
/**
* Accessor for current identity.
* @return string Last succesful password.
* @access public
*/
/**
* Accessor for current identity.
* @return string Last succesful password.
* @access public
*/
function getPassword() {
return $this->_password;
}
/**
* Test to see if the URL is within the directory
* tree of the realm.
* @param SimpleUrl $url URL to test.
* @return boolean True if subpath.
* @access public
*/
/**
* Test to see if the URL is within the directory
* tree of the realm.
* @param SimpleUrl $url URL to test.
* @return boolean True if subpath.
* @access public
*/
function isWithin($url) {
return (strpos($url->getBasePath(), $this->_root) === 0);
if ($this->_isIn($this->_root, $url->getBasePath())) {
return true;
}
if ($this->_isIn($this->_root, $url->getBasePath() . $url->getPage() . '/')) {
return true;
}
return false;
}
/**
* Tests to see if one string is a substring of
* another.
* @param string $part Small bit.
* @param string $whole Big bit.
* @return boolean True if the small bit is
* in the big bit.
* @access private
*/
function _isIn($part, $whole) {
return strpos($whole, $part) === 0;
}
}
/**
* Manages security realms.
* @package SimpleTest
* @subpackage WebTester
*/
/**
* Manages security realms.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleAuthenticator {
var $_realms;
/**
* Clears the realms.
* @access public
*/
/**
* Clears the realms.
* @access public
*/
function SimpleAuthenticator() {
$this->restartSession();
}
/**
* Starts with no realms set up.
* @access public
*/
/**
* Starts with no realms set up.
* @access public
*/
function restartSession() {
$this->_realms = array();
}
/**
* Adds a new realm centered the current URL.
* Browsers vary 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
* occours. SimpleTest tries to follow the spirit of
* the original standards committee and treats the
* base URL as the root of a file tree shaped realm.
* @param SimpleUrl $url Base of realm.
* @param string $type Authentication type for this
* realm. Only Basic authentication
* is currently supported.
* @param string $realm Name of realm.
* @access public
*/
/**
* Adds a new realm centered the current URL.
* Browsers vary 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
* occours. SimpleTest tries to follow the spirit of
* the original standards committee and treats the
* base URL as the root of a file tree shaped realm.
* @param SimpleUrl $url Base of realm.
* @param string $type Authentication type for this
* realm. Only Basic authentication
* is currently supported.
* @param string $realm Name of realm.
* @access public
*/
function addRealm($url, $type, $realm) {
$this->_realms[$url->getHost()][$realm] = new SimpleRealm($type, $url);
}
/**
* Sets the current identity to be presented
* against that realm.
* @param string $host Server hosting realm.
* @param string $realm Name of realm.
* @param string $username Username for realm.
* @param string $password Password for realm.
* @access public
*/
/**
* Sets the current identity to be presented
* against that realm.
* @param string $host Server hosting realm.
* @param string $realm Name of realm.
* @param string $username Username for realm.
* @param string $password Password for realm.
* @access public
*/
function setIdentityForRealm($host, $realm, $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
*/
/**
* 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()])) {
return false;
@ -181,12 +200,12 @@
return false;
}
/**
* Presents the appropriate headers for this location.
* @param SimpleHttpRequest $request Request to modify.
* @param SimpleUrl $url Base of realm.
* @access public
*/
/**
* Presents the appropriate headers for this location.
* @param SimpleHttpRequest $request Request to modify.
* @param SimpleUrl $url Base of realm.
* @access public
*/
function addHeaders(&$request, $url) {
if ($url->getUsername() && $url->getPassword()) {
$username = $url->getUsername();
@ -200,15 +219,15 @@
$this->addBasicHeaders($request, $username, $password);
}
/**
* Presents the appropriate headers for this
* location for basic authentication.
* @param SimpleHttpRequest $request Request to modify.
* @param string $username Username for realm.
* @param string $password Password for realm.
* @access public
* @static
*/
/**
* Presents the appropriate headers for this
* location for basic authentication.
* @param SimpleHttpRequest $request Request to modify.
* @param string $username Username for realm.
* @param string $password Password for realm.
* @access public
* @static
*/
function addBasicHeaders(&$request, $username, $password) {
if ($username && $password) {
$request->addHeaderLine(

File diff suppressed because it is too large Load diff

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

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

View file

@ -195,11 +195,11 @@ $test-&gt;run(new HtmlReporter());</strong>
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
<strong>2</strong> passes and <strong>0</strong> fails.</div>
</div>
And if you get this...
And if you get this...
<div class="demo">
<b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b>
</div>
it means you're missing the <em>classes/Log.php</em> file that could look like...
it means you're missing the <em>classes/Log.php</em> file that could look like...
<pre>
&lt;?php
class Log {
@ -207,8 +207,8 @@ class Log {
function Log($file_path) {
}
function message() {
}
function message() {
}
}
?&gt;;
</pre>

View file

@ -375,7 +375,7 @@ Test cases run: 1/1, Failures: 0, Exceptions: 0
<pre class="shell">
File test
1) True assertion failed.
in createnewfile
in createnewfile
FAILURES!!!
Test cases run: 1/1, Failures: 1, Exceptions: 0
</pre>

View file

@ -283,9 +283,9 @@ class TestOfLastcraft extends WebTestCase {
<pre class="shell">
Web site tests
1) Expecting response in [200] got [302]
in testhomepage
in testoflastcraft
in lastcraft_test.php
in testhomepage
in testoflastcraft
in lastcraft_test.php
FAILURES!!!
Test cases run: 1/1, Failures: 1, Exceptions: 0
</pre>

View file

@ -219,15 +219,15 @@
?&gt;
</pre>
Comme les sc&eacute;narios de test normaux, un <span class="new_code">GroupTest</span> peut &ecirc;tre charg&eacute; avec la m&eacute;thode <span class="new_code">GroupTest::addTestFile()</span>.
<pre>
&lt;?php
define('RUNNER', true);
$test = &amp;new BigGroupTest('Big group');<strong>
$test-&gt;addTestFile('file_group_test.php');
$test-&gt;addTestFile(...);</strong>
$test-&gt;run(new HtmlReporter());
?&gt;
<pre>
&lt;?php
define('RUNNER', true);
$test = &amp;new BigGroupTest('Big group');<strong>
$test-&gt;addTestFile('file_group_test.php');
$test-&gt;addTestFile(...);</strong>
$test-&gt;run(new HtmlReporter());
?&gt;
</pre>
</p>

View file

@ -149,11 +149,11 @@ $test-&gt;run(new HtmlReporter());</strong>
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
<strong>2</strong> passes and <strong>0</strong> fails.</div>
</div>
Et si vous obtenez &ccedil;a...
Et si vous obtenez &ccedil;a...
<div class="demo">
<b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b>
</div>
c'est qu'il vous manque le fichier <em>classes/Log.php</em> qui pourrait ressembler &agrave; :
c'est qu'il vous manque le fichier <em>classes/Log.php</em> qui pourrait ressembler &agrave; :
<pre>
&lt;?php
class Log {

View file

@ -282,7 +282,7 @@ Test cases run: 1/1, Failures: 0, Exceptions: 0
<pre class="shell">
File test
1) True assertion failed.
in createnewfile
in createnewfile
FAILURES!!!
Test cases run: 1/1, Failures: 1, Exceptions: 0
</pre>

View file

@ -218,9 +218,9 @@ class TestOfLastcraft extends WebTestCase {
<pre class="shell">
Web site tests
1) Expecting response in [200] got [302]
in testhomepage
in testoflastcraft
in lastcraft_test.php
in testhomepage
in testoflastcraft
in lastcraft_test.php
FAILURES!!!
Test cases run: 1/1, Failures: 1, Exceptions: 0
</pre>

View file

@ -1,28 +1,30 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**
* does type matter
*/
define('TYPE_MATTERS', true);
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**
* does type matter
*/
if (!defined('TYPE_MATTERS')) {
define('TYPE_MATTERS', true);
}
/**
* Displays variables as text and does diffs.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Displays variables as text and does diffs.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleDumper {
/**
* Renders a variable in a shorter form than print_r().
* @param mixed $value Variable to render as a string.
* @return string Human readable string form.
* @access public
*/
/**
* Renders a variable in a shorter form than print_r().
* @param mixed $value Variable to render as a string.
* @return string Human readable string form.
* @access public
*/
function describeValue($value) {
$type = $this->getType($value);
switch($type) {
@ -42,12 +44,12 @@
return "Unknown";
}
/**
* Gets the string representation of a type.
* @param mixed $value Variable to check against.
* @return string Type.
* @access public
*/
/**
* Gets the string representation of a type.
* @param mixed $value Variable to check against.
* @return string Type.
* @access public
*/
function getType($value) {
if (! isset($value)) {
return "Null";
@ -69,16 +71,16 @@
return "Unknown";
}
/**
* Creates a human readable description of the
* difference between two variables. Uses a
* dynamic call.
* @param mixed $first First variable.
* @param mixed $second Value to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Description of difference.
* @access public
*/
/**
* Creates a human readable description of the
* difference between two variables. Uses a
* dynamic call.
* @param mixed $first First variable.
* @param mixed $second Value to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Description of difference.
* @access public
*/
function describeDifference($first, $second, $identical = false) {
if ($identical) {
if (! $this->_isTypeMatch($first, $second)) {
@ -94,25 +96,25 @@
return $this->$method($first, $second, $identical);
}
/**
* Tests to see if types match.
* @param mixed $first First variable.
* @param mixed $second Value to compare with.
* @return boolean True if matches.
* @access private
*/
/**
* Tests to see if types match.
* @param mixed $first First variable.
* @param mixed $second Value to compare with.
* @return boolean True if matches.
* @access private
*/
function _isTypeMatch($first, $second) {
return ($this->getType($first) == $this->getType($second));
}
/**
* Clips a string to a maximum length.
* @param string $value String to truncate.
* @param integer $size Minimum string size to show.
* @param integer $position Centre of string section.
* @return string Shortened version.
* @access public
*/
/**
* Clips a string to a maximum length.
* @param string $value String to truncate.
* @param integer $size Minimum string size to show.
* @param integer $position Centre of string section.
* @return string Shortened version.
* @access public
*/
function clipString($value, $size, $position = 0) {
$length = strlen($value);
if ($length <= $size) {
@ -127,56 +129,56 @@
return ($start > 0 ? "..." : "") . $value . ($start + $size < $length ? "..." : "");
}
/**
* Creates a human readable description of the
* difference between two variables. The minimal
* version.
* @param null $first First value.
* @param mixed $second Value to compare with.
* @return string Human readable description.
* @access private
*/
/**
* Creates a human readable description of the
* difference between two variables. The minimal
* version.
* @param null $first First value.
* @param mixed $second Value to compare with.
* @return string Human readable description.
* @access private
*/
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.
* @param null $first First null.
* @param mixed $second Null to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
/**
* Creates a human readable description of the
* difference between a null and another variable.
* @param null $first First null.
* @param mixed $second Null to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
function _describeNullDifference($first, $second, $identical) {
return $this->_describeGenericDifference($first, $second);
}
/**
* Creates a human readable description of the
* difference between a boolean and another variable.
* @param boolean $first First boolean.
* @param mixed $second Boolean to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
/**
* Creates a human readable description of the
* difference between a boolean and another variable.
* @param boolean $first First boolean.
* @param mixed $second Boolean to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
function _describeBooleanDifference($first, $second, $identical) {
return $this->_describeGenericDifference($first, $second);
}
/**
* Creates a human readable description of the
* difference between a string and another variable.
* @param string $first First string.
* @param mixed $second String to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
/**
* Creates a human readable description of the
* difference between a string and another variable.
* @param string $first First string.
* @param mixed $second String to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
function _describeStringDifference($first, $second, $identical) {
if (is_object($second) || is_array($second)) {
return $this->_describeGenericDifference($first, $second);
@ -189,15 +191,15 @@
return $message;
}
/**
* Creates a human readable description of the
* difference between an integer and another variable.
* @param integer $first First number.
* @param mixed $second Number to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
/**
* Creates a human readable description of the
* difference between an integer and another variable.
* @param integer $first First number.
* @param mixed $second Number to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
function _describeIntegerDifference($first, $second, $identical) {
if (is_object($second) || is_array($second)) {
return $this->_describeGenericDifference($first, $second);
@ -208,33 +210,34 @@
abs($first - $second);
}
/**
* Creates a human readable description of the
* difference between two floating point numbers.
* @param float $first First float.
* @param mixed $second Float to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
/**
* Creates a human readable description of the
* difference between two floating point numbers.
* @param float $first First float.
* @param mixed $second Float to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
function _describeFloatDifference($first, $second, $identical) {
if (is_object($second) || is_array($second)) {
return $this->_describeGenericDifference($first, $second);
}
return "because " . $this->describeValue($first) .
return "because [" . $this->describeValue($first) .
"] differs from [" .
$this->describeValue($second) . "]";
$this->describeValue($second) . "] by " .
abs($first - $second);
}
/**
* Creates a human readable description of the
* difference between two arrays.
* @param array $first First array.
* @param mixed $second Array to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
/**
* Creates a human readable description of the
* difference between two arrays.
* @param array $first First array.
* @param mixed $second Array to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
function _describeArrayDifference($first, $second, $identical) {
if (! is_array($second)) {
return $this->_describeGenericDifference($first, $second);
@ -259,16 +262,16 @@
return "";
}
/**
* Compares two arrays to see if their key lists match.
* For an identical match, the ordering and types of the keys
* is significant.
* @param array $first First array.
* @param array $second Array to compare with.
* @param boolean $identical If true then type anomolies count.
* @return boolean True if matching.
* @access private
*/
/**
* Compares two arrays to see if their key lists match.
* For an identical match, the ordering and types of the keys
* is significant.
* @param array $first First array.
* @param array $second Array to compare with.
* @param boolean $identical If true then type anomolies count.
* @return boolean True if matching.
* @access private
*/
function _isMatchingKeys($first, $second, $identical) {
$first_keys = array_keys($first);
$second_keys = array_keys($second);
@ -280,28 +283,28 @@
return ($first_keys == $second_keys);
}
/**
* Creates a human readable description of the
* difference between a resource and another variable.
* @param resource $first First resource.
* @param mixed $second Resource to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
/**
* Creates a human readable description of the
* difference between a resource and another variable.
* @param resource $first First resource.
* @param mixed $second Resource to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
function _describeResourceDifference($first, $second, $identical) {
return $this->_describeGenericDifference($first, $second);
}
/**
* Creates a human readable description of the
* difference between two objects.
* @param object $first First object.
* @param mixed $second Object to compare with.
* @param boolean $identical If true then type anomolies count.
* @return string Human readable description.
* @access private
*/
/**
* Creates a human readable description of the
* difference between two objects.
* @param object $first First object.
* @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) {
if (! is_object($second)) {
return $this->_describeGenericDifference($first, $second);
@ -312,15 +315,15 @@
$identical);
}
/**
* Find the first character position that differs
* in two strings by binary chop.
* @param string $first First string.
* @param string $second String to compare with.
* @return integer Position of first differing
* character.
* @access private
*/
/**
* Find the first character position that differs
* in two strings by binary chop.
* @param string $first First string.
* @param string $second String to compare with.
* @return integer Position of first differing
* character.
* @access private
*/
function _stringDiffersAt($first, $second) {
if (! $first || ! $second) {
return 0;
@ -339,13 +342,13 @@
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
*/
/**
* 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();
print_r($variable);
@ -354,15 +357,15 @@
return $formatted;
}
/**
* Extracts the last assertion that was not within
* Simpletest itself. The name must start with "assert".
* @param array $stack List of stack frames.
* @param string $format String formatting.
* @param string $prefix Prefix of method to search for.
* @access public
* @static
*/
/**
* Extracts the last assertion that was not within
* Simpletest itself. The name must start with "assert".
* @param array $stack List of stack frames.
* @param string $format String formatting.
* @param string $prefix Prefix of method to search for.
* @access public
* @static
*/
function getFormattedAssertionLine($stack, $format = '%d', $prefix = 'assert') {
foreach ($stack as $frame) {
if (isset($frame['file']) && strpos($frame['file'], 'simpletest') !== false) { // dirname() is a bit slow.

View file

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

View file

@ -1,56 +1,56 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/** @ignore - PHP5 compatibility fix. */
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/** @ignore - PHP5 compatibility fix. */
if (! defined('E_STRICT')) {
define('E_STRICT', 2048);
}
/**
* Singleton error queue used to record trapped
* errors.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Singleton error queue used to record trapped
* errors.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleErrorQueue {
var $_queue;
/**
* Starts with an empty queue.
* @access public
*/
/**
* Starts with an empty queue.
* @access public
*/
function SimpleErrorQueue() {
$this->clear();
}
/**
* Adds an error to the front of the queue.
* @param $severity PHP error code.
* @param $message Text of error.
* @param $filename File error occoured in.
* @param $line Line number of error.
* @param $super_globals Hash of PHP super global arrays.
* @access public
*/
/**
* Adds an error to the front of the queue.
* @param $severity PHP error code.
* @param $message Text of error.
* @param $filename File error occoured in.
* @param $line Line number of error.
* @param $super_globals Hash of PHP super global arrays.
* @access public
*/
function add($severity, $message, $filename, $line, $super_globals) {
array_push(
$this->_queue,
array($severity, $message, $filename, $line, $super_globals));
}
/**
* Pulls the earliest error from the queue.
* @return False if none, or a list of error
* information. Elements are: severity
* as the PHP error code, the error message,
* the file with the error, the line number
* and a list of PHP super global arrays.
* @access public
*/
/**
* Pulls the earliest error from the queue.
* @return False if none, or a list of error
* information. Elements are: severity
* as the PHP error code, the error message,
* the file with the error, the line number
* and a list of PHP super global arrays.
* @access public
*/
function extract() {
if (count($this->_queue)) {
return array_shift($this->_queue);
@ -58,28 +58,28 @@
return false;
}
/**
* Discards the contents of the error queue.
* @access public
*/
/**
* Discards the contents of the error queue.
* @access public
*/
function clear() {
$this->_queue = array();
}
/**
* Tests to see if the queue is empty.
* @return True if empty.
*/
/**
* Tests to see if the queue is empty.
* @return True if empty.
*/
function isEmpty() {
return (count($this->_queue) == 0);
}
/**
* Global access to a single error queue.
* @return Global error queue object.
* @access public
* @static
*/
/**
* Global access to a single error queue.
* @return Global error queue object.
* @access public
* @static
*/
function &instance() {
static $queue = false;
if (! $queue) {
@ -88,14 +88,14 @@
return $queue;
}
/**
* Converst an error code into it's string
* representation.
* @param $severity PHP integer error code.
* @return String version of error code.
* @access public
* @static
*/
/**
* Converst 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 $map = array(
E_STRICT => 'E_STRICT',
@ -114,18 +114,18 @@
}
}
/**
* Error handler that simply stashes any errors into the global
* error queue. Simulates the existing behaviour with respect to
* logging errors, but this feature may be removed in future.
* @param $severity PHP error code.
* @param $message Text of error.
* @param $filename File error occoured in.
* @param $line Line number of error.
* @param $super_globals Hash of PHP super global arrays.
* @static
* @access public
*/
/**
* Error handler that simply stashes any errors into the global
* error queue. Simulates the existing behaviour with respect to
* logging errors, but this feature may be removed in future.
* @param $severity PHP error code.
* @param $message Text of error.
* @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, $line, $super_globals) {
if ($severity = $severity & error_reporting()) {
restore_error_handler();

View file

@ -1,119 +1,119 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**#@+
* include other SimpleTest class files
*/
/**#@+
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/dumper.php');
require_once(dirname(__FILE__) . '/options.php');
/**#@-*/
/**#@-*/
/**
* Assertion that can display failure information.
* Also includes various helper methods.
* @package SimpleTest
* @subpackage UnitTester
* @abstract
*/
/**
* Assertion that can display failure information.
* Also includes various helper methods.
* @package SimpleTest
* @subpackage UnitTester
* @abstract
*/
class SimpleExpectation {
var $_dumper;
var $_message;
/**
* Creates a dumper for displaying values and sets
* the test message.
* @param string $message Customised message on failure.
*/
/**
* Creates a dumper for displaying values and sets
* the test message.
* @param string $message Customised message on failure.
*/
function SimpleExpectation($message = '%s') {
$this->_dumper = &new SimpleDumper();
$this->_message = $message;
}
/**
* Tests the expectation. True if correct.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
* @abstract
*/
/**
* Tests the expectation. True if correct.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
* @abstract
*/
function test($compare) {
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
* @abstract
*/
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
* @abstract
*/
function testMessage($compare) {
}
/**
* Overlays the generated message onto the stored user
* message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
/**
* Overlays the generated message onto the stored user
* message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function overlayMessage($compare) {
return sprintf($this->_message, $this->testMessage($compare));
}
/**
* Accessor for the dumper.
* @return SimpleDumper Current value dumper.
* @access protected
*/
/**
* Accessor for the dumper.
* @return SimpleDumper Current value dumper.
* @access protected
*/
function &_getDumper() {
return $this->_dumper;
}
}
/**
* Test for equality.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Test for equality.
* @package SimpleTest
* @subpackage UnitTester
*/
class EqualExpectation extends SimpleExpectation {
var $_value;
/**
* Sets the value to compare against.
* @param mixed $value Test value to match.
* @param string $message Customised message on failure.
* @access public
*/
/**
* Sets the value to compare against.
* @param mixed $value Test value to match.
* @param string $message Customised message on failure.
* @access public
*/
function EqualExpectation($value, $message = '%s') {
$this->SimpleExpectation($message);
$this->_value = $value;
}
/**
* Tests the expectation. True if it matches the
* held value.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
function test($compare, $nasty = false) {
/**
* Tests the expectation. True if it matches the
* held value.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
function test($compare) {
return (($this->_value == $compare) && ($compare == $this->_value));
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
if ($this->test($compare)) {
return "Equal expectation [" . $this->_dumper->describeValue($this->_value) . "]";
@ -123,51 +123,51 @@
}
}
/**
* Accessor for comparison value.
* @return mixed Held value to compare with.
* @access protected
*/
/**
* Accessor for comparison value.
* @return mixed Held value to compare with.
* @access protected
*/
function _getValue() {
return $this->_value;
}
}
/**
* Test for inequality.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Test for inequality.
* @package SimpleTest
* @subpackage UnitTester
*/
class NotEqualExpectation extends EqualExpectation {
/**
* Sets the value to compare against.
* @param mixed $value Test value to match.
* @param string $message Customised message on failure.
* @access public
*/
/**
* Sets the value to compare against.
* @param mixed $value Test value to match.
* @param string $message Customised message on failure.
* @access public
*/
function NotEqualExpectation($value, $message = '%s') {
$this->EqualExpectation($value, $message);
}
/**
* Tests the expectation. True if it differs from the
* held value.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
/**
* Tests the expectation. True if it differs from the
* held value.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
function test($compare) {
return ! parent::test($compare);
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
if ($this->test($compare)) {
@ -181,41 +181,162 @@
}
}
/**
* Test for identity.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Test for being within a range.
* @package SimpleTest
* @subpackage UnitTester
*/
class WithinMarginExpectation extends SimpleExpectation {
var $_upper;
var $_lower;
/**
* Sets the value to compare against and the fuzziness of
* the match. Used for comparing floating point values.
* @param mixed $value Test value to match.
* @param mixed $margin Fuzziness of match.
* @param string $message Customised message on failure.
* @access public
*/
function WithinMarginExpectation($value, $margin, $message = '%s') {
$this->SimpleExpectation($message);
$this->_upper = $value + $margin;
$this->_lower = $value - $margin;
}
/**
* Tests the expectation. True if it matches the
* held value.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
function test($compare) {
return (($compare <= $this->_upper) && ($compare >= $this->_lower));
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
if ($this->test($compare)) {
return $this->_withinMessage($compare);
} else {
return $this->_outsideMessage($compare);
}
}
/**
* Creates a the message for being within the range.
* @param mixed $compare Value being tested.
* @access private
*/
function _withinMessage($compare) {
return "Within expectation [" . $this->_dumper->describeValue($this->_lower) . "] and [" .
$this->_dumper->describeValue($this->_upper) . "]";
}
/**
* Creates a the message for being within the range.
* @param mixed $compare Value being tested.
* @access private
*/
function _outsideMessage($compare) {
if ($compare > $this->_upper) {
return "Outside expectation " .
$this->_dumper->describeDifference($compare, $this->_upper);
} else {
return "Outside expectation " .
$this->_dumper->describeDifference($compare, $this->_lower);
}
}
}
/**
* Test for being outside of a range.
* @package SimpleTest
* @subpackage UnitTester
*/
class OutsideMarginExpectation extends WithinMarginExpectation {
/**
* Sets the value to compare against and the fuzziness of
* the match. Used for comparing floating point values.
* @param mixed $value Test value to not match.
* @param mixed $margin Fuzziness of match.
* @param string $message Customised message on failure.
* @access public
*/
function OutsideMarginExpectation($value, $margin, $message = '%s') {
$this->WithinMarginExpectation($value, $margin, $message);
}
/**
* Tests the expectation. True if it matches the
* held value.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
function test($compare) {
return ! parent::test($compare);
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
if (! $this->test($compare)) {
return $this->_withinMessage($compare);
} else {
return $this->_outsideMessage($compare);
}
}
}
/**
* Test for identity.
* @package SimpleTest
* @subpackage UnitTester
*/
class IdenticalExpectation extends EqualExpectation {
/**
* Sets the value to compare against.
* @param mixed $value Test value to match.
* @param string $message Customised message on failure.
* @access public
*/
/**
* Sets the value to compare against.
* @param mixed $value Test value to match.
* @param string $message Customised message on failure.
* @access public
*/
function IdenticalExpectation($value, $message = '%s') {
$this->EqualExpectation($value, $message);
}
/**
* Tests the expectation. True if it exactly
* matches the held value.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
/**
* Tests the expectation. True if it exactly
* matches the held value.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
function test($compare) {
return SimpleTestCompatibility::isIdentical($this->_getValue(), $compare);
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
if ($this->test($compare)) {
@ -229,41 +350,41 @@
}
}
/**
* Test for non-identity.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Test for non-identity.
* @package SimpleTest
* @subpackage UnitTester
*/
class NotIdenticalExpectation extends IdenticalExpectation {
/**
* Sets the value to compare against.
* @param mixed $value Test value to match.
* @param string $message Customised message on failure.
* @access public
*/
/**
* Sets the value to compare against.
* @param mixed $value Test value to match.
* @param string $message Customised message on failure.
* @access public
*/
function NotIdenticalExpectation($value, $message = '%s') {
$this->IdenticalExpectation($value, $message);
}
/**
* Tests the expectation. True if it differs from the
* held value.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
/**
* Tests the expectation. True if it differs from the
* held value.
* @param mixed $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
function test($compare) {
return ! parent::test($compare);
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
if ($this->test($compare)) {
@ -275,52 +396,52 @@
}
}
/**
* Test for a pattern using Perl regex rules.
* @package SimpleTest
* @subpackage UnitTester
*/
class WantedPatternExpectation extends SimpleExpectation {
/**
* Test for a pattern using Perl regex rules.
* @package SimpleTest
* @subpackage UnitTester
*/
class PatternExpectation extends SimpleExpectation {
var $_pattern;
/**
* Sets the value to compare against.
* @param string $pattern Pattern to search for.
* @param string $message Customised message on failure.
* @access public
*/
function WantedPatternExpectation($pattern, $message = '%s') {
/**
* Sets the value to compare against.
* @param string $pattern Pattern to search for.
* @param string $message Customised message on failure.
* @access public
*/
function PatternExpectation($pattern, $message = '%s') {
$this->SimpleExpectation($message);
$this->_pattern = $pattern;
}
/**
* Accessor for the pattern.
* @return string Perl regex as string.
* @access protected
*/
/**
* Accessor for the pattern.
* @return string Perl regex as string.
* @access protected
*/
function _getPattern() {
return $this->_pattern;
}
/**
* Tests the expectation. True if the Perl regex
* matches the comparison value.
* @param string $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
/**
* Tests the expectation. True if the Perl regex
* matches the comparison value.
* @param string $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
function test($compare) {
return (boolean)preg_match($this->_getPattern(), $compare);
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
if ($this->test($compare)) {
return $this->_describePatternMatch($this->_getPattern(), $compare);
@ -332,13 +453,13 @@
}
}
/**
* Describes a pattern match including the string
* found and it's position.
* @param string $pattern Regex to match against.
* @param string $subject Subject to search.
* @access protected
*/
/**
* Describes a pattern match including the string
* found and it's position.
* @param string $pattern Regex to match against.
* @param string $subject Subject to search.
* @access protected
*/
function _describePatternMatch($pattern, $subject) {
preg_match($pattern, $subject, $matches);
$position = strpos($subject, $matches[0]);
@ -350,42 +471,48 @@
}
}
/**
* Fail if a pattern is detected within the
* comparison.
* @package SimpleTest
* @subpackage UnitTester
*/
class UnwantedPatternExpectation extends WantedPatternExpectation {
/**
* @deprecated
*/
class WantedPatternExpectation extends PatternExpectation {
}
/**
* Fail if a pattern is detected within the
* comparison.
* @package SimpleTest
* @subpackage UnitTester
*/
class NoPatternExpectation extends PatternExpectation {
/**
* Sets the reject pattern
* @param string $pattern Pattern to search for.
* @param string $message Customised message on failure.
* @access public
*/
function UnwantedPatternExpectation($pattern, $message = '%s') {
$this->WantedPatternExpectation($pattern, $message);
/**
* Sets the reject pattern
* @param string $pattern Pattern to search for.
* @param string $message Customised message on failure.
* @access public
*/
function NoPatternExpectation($pattern, $message = '%s') {
$this->PatternExpectation($pattern, $message);
}
/**
* Tests the expectation. False if the Perl regex
* matches the comparison value.
* @param string $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
/**
* Tests the expectation. False if the Perl regex
* matches the comparison value.
* @param string $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
function test($compare) {
return ! parent::test($compare);
}
/**
* Returns a human readable test message.
* @param string $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
/**
* Returns a human readable test message.
* @param string $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
if ($this->test($compare)) {
$dumper = &$this->_getDumper();
@ -398,41 +525,47 @@
}
}
/**
* Tests either type or class name if it's an object.
* @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;
/**
* Sets the type to compare with.
* @param string $type Type or class name.
* @param string $message Customised message on failure.
* @access public
*/
/**
* Sets the type to compare with.
* @param string $type Type or class name.
* @param string $message Customised message on failure.
* @access public
*/
function IsAExpectation($type, $message = '%s') {
$this->SimpleExpectation($message);
$this->_type = $type;
}
/**
* Accessor for type to check against.
* @return string Type or class name.
* @access protected
*/
/**
* Accessor for type to check against.
* @return string Type or class name.
* @access protected
*/
function _getType() {
return $this->_type;
}
/**
* Tests the expectation. True if the type or
* class matches the string value.
* @param string $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
/**
* Tests the expectation. True if the type or
* class matches the string value.
* @param string $compare Comparison value.
* @return boolean True if correct.
* @access public
*/
function test($compare) {
if (is_object($compare)) {
return SimpleTestCompatibility::isA($compare, $this->_type);
@ -441,12 +574,12 @@
}
}
/**
* Coerces type name into a gettype() match.
* @param string $type User type.
* @return string Simpler type.
* @access private
*/
/**
* Coerces type name into a gettype() match.
* @param string $type User type.
* @return string Simpler type.
* @access private
*/
function _canonicalType($type) {
$type = strtolower($type);
$map = array(
@ -460,13 +593,13 @@
return $type;
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
return "Value [" . $dumper->describeValue($compare) .
@ -474,43 +607,43 @@
}
}
/**
* Tests either type or class name if it's an object.
* Will succeed if the type does not match.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Tests either type or class name if it's an object.
* Will succeed if the type does not match.
* @package SimpleTest
* @subpackage UnitTester
*/
class NotAExpectation extends IsAExpectation {
var $_type;
/**
* Sets the type to compare with.
* @param string $type Type or class name.
* @param string $message Customised message on failure.
* @access public
*/
/**
* Sets the type to compare with.
* @param string $type Type or class name.
* @param string $message Customised message on failure.
* @access public
*/
function NotAExpectation($type, $message = '%s') {
$this->IsAExpectation($type, $message);
}
/**
* Tests the expectation. False if the type or
* class matches the string value.
* @param string $compare Comparison value.
* @return boolean True if different.
* @access public
*/
/**
* Tests the expectation. False if the type or
* class matches the string value.
* @param string $compare Comparison value.
* @return boolean True if different.
* @access public
*/
function test($compare) {
return ! parent::test($compare);
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
return "Value [" . $dumper->describeValue($compare) .
@ -518,51 +651,51 @@
}
}
/**
* Tests for existance of a method in an object
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Tests for existance of a method in an object
* @package SimpleTest
* @subpackage UnitTester
*/
class MethodExistsExpectation extends SimpleExpectation {
var $_method;
/**
* Sets the value to compare against.
* @param string $method Method to check.
* @param string $message Customised message on failure.
* @access public
* @return void
*/
/**
* 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;
}
/**
* 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
*/
/**
* 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));
}
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
* @access public
*/
function testMessage($compare) {
$dumper = &$this->_getDumper();
if (! is_object($compare)) {
return 'No method on non-object [' . $dumper->describeValue($compare) . ']';
}
$method = $this->_method;
return "Object [" . $dumper->describeValue($compare) .
"] should contain method [$method]";
$dumper = &$this->_getDumper();
if (! is_object($compare)) {
return 'No method on non-object [' . $dumper->describeValue($compare) . ']';
}
$method = $this->_method;
return "Object [" . $dumper->describeValue($compare) .
"] should contain method [$method]";
}
}
?>

View file

@ -1,84 +1,84 @@
<?php
/**
* adapter for SimpleTest to use PEAR PHPUnit test cases
* @package SimpleTest
* @subpackage Extensions
* @version $Id$
*/
/**
* adapter for SimpleTest to use PEAR PHPUnit test cases
* @package SimpleTest
* @subpackage Extensions
* @version $Id$
*/
/**#@+
* include SimpleTest files
*/
require_once dirname(__FILE__) . '/../dumper.php';
require_once dirname(__FILE__) . '/../options.php';
require_once dirname(__FILE__) . '/../simple_test.php';
require_once dirname(__FILE__) . '/../expectation.php';
/**#@-*/
/**#@+
* include SimpleTest files
*/
require_once(dirname(__FILE__) . '/../dumper.php');
require_once(dirname(__FILE__) . '/../options.php');
require_once(dirname(__FILE__) . '/../simple_test.php');
require_once(dirname(__FILE__) . '/../expectation.php');
/**#@-*/
/**
* Adapter for PEAR PHPUnit test case to allow
* legacy PEAR test cases to be used with SimpleTest.
* @package SimpleTest
* @subpackage Extensions
*/
/**
* Adapter for PEAR PHPUnit test case to allow
* legacy PEAR test cases to be used with SimpleTest.
* @package SimpleTest
* @subpackage Extensions
*/
class PHPUnit_TestCase extends SimpleTestCase {
var $_loosely_typed;
/**
* Constructor. Sets the test name.
* @param $label Test name to display.
* @public
*/
/**
* Constructor. Sets the test name.
* @param $label Test name to display.
* @public
*/
function PHPUnit_TestCase($label = false) {
$this->SimpleTestCase($label);
$this->_loosely_typed = false;
}
/**
* 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
*/
/**
* 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 = "%s", $delta = 0) {
if ($this->_loosely_typed) {
$expectation = &new EqualExpectation($first);
} else {
$expectation = &new IdenticalExpectation($first);
}
$this->assertExpectation($expectation, $second, $message);
$this->assert($expectation, $second, $message);
}
/**
* Passes if the value tested is not null.
* @param $value Value to test against.
* @param $message Message to display.
* @public
*/
/**
* Passes if the value tested is not null.
* @param $value Value to test against.
* @param $message Message to display.
* @public
*/
function assertNotNull($value, $message = "%s") {
parent::assertTrue(isset($value), $message);
}
/**
* Passes if the value tested is null.
* @param $value Value to test against.
* @param $message Message to display.
* @public
*/
/**
* Passes if the value tested is null.
* @param $value Value to test against.
* @param $message Message to display.
* @public
*/
function assertNull($value, $message = "%s") {
parent::assertTrue(!isset($value), $message);
}
/**
* In PHP5 the identity test tests for the same
* object. This is a reference test in PHP4.
* @param $first First object handle.
* @param $second Hopefully the same handle.
* @param $message Message to display.
* @public
*/
/**
* In PHP5 the identity test tests for the same
* object. This is a reference test in PHP4.
* @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();
$message = sprintf(
@ -91,14 +91,14 @@
$message);
}
/**
* In PHP5 the identity test tests for the same
* object. This is a reference test in PHP4.
* @param $first First object handle.
* @param $second Hopefully a different handle.
* @param $message Message to display.
* @public
*/
/**
* In PHP5 the identity test tests for the same
* object. This is a reference test in PHP4.
* @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();
$message = sprintf(
@ -111,88 +111,85 @@
$message);
}
/**
* Sends pass if the test condition resolves true,
* a fail otherwise.
* @param $condition Condition to test true.
* @param $message Message to display.
* @public
*/
/**
* Sends pass if the test condition resolves true,
* a fail otherwise.
* @param $condition Condition to test true.
* @param $message Message to display.
* @public
*/
function assertTrue($condition, $message = "%s") {
parent::assertTrue($condition, $message);
}
/**
* Sends pass if the test condition resolves false,
* a fail otherwise.
* @param $condition Condition to test false.
* @param $message Message to display.
* @public
*/
/**
* Sends pass if the test condition resolves false,
* a fail otherwise.
* @param $condition Condition to test false.
* @param $message Message to display.
* @public
*/
function assertFalse($condition, $message = "%s") {
parent::assertTrue(!$condition, $message);
}
/**
* Tests a regex match. Needs refactoring.
* @param $pattern Regex to match.
* @param $subject String to search in.
* @param $message Message to display.
* @public
*/
/**
* Tests a regex match. Needs refactoring.
* @param $pattern Regex to match.
* @param $subject String to search in.
* @param $message Message to display.
* @public
*/
function assertRegExp($pattern, $subject, $message = "%s") {
$this->assertExpectation(
new WantedPatternExpectation($pattern),
$subject,
$message);
$this->assert(new PatternExpectation($pattern), $subject, $message);
}
/**
* Tests the type of a value.
* @param $value Value to take type of.
* @param $type Hoped for type.
* @param $message Message to display.
* @public
*/
/**
* Tests the type of a value.
* @param $value Value to take type of.
* @param $type Hoped for type.
* @param $message Message to display.
* @public
*/
function assertType($value, $type, $message = "%s") {
parent::assertTrue(gettype($value) == strtolower($type), $message);
}
/**
* Sets equality operation to act as a simple equal
* comparison only, allowing a broader range of
* matches.
* @param $loosely_typed True for broader comparison.
* @public
*/
/**
* Sets equality operation to act as a simple equal
* comparison only, allowing a broader range of
* matches.
* @param $loosely_typed True for broader comparison.
* @public
*/
function setLooselyTyped($loosely_typed) {
$this->_loosely_typed = $loosely_typed;
}
/**
* For progress indication during
* a test amongst other things.
* @return Usually one.
* @public
*/
/**
* For progress indication during
* a test amongst other things.
* @return Usually one.
* @public
*/
function countTestCases() {
return $this->getSize();
}
/**
* Accessor for name, normally just the class
* name.
* @public
*/
/**
* Accessor for name, normally just the class
* name.
* @public
*/
function getName() {
return $this->getLabel();
}
/**
* Does nothing. For compatibility only.
* @param $name Dummy
* @public
*/
/**
* Does nothing. For compatibility only.
* @param $name Dummy
* @public
*/
function setName($name) {
}
}

View file

@ -1,106 +1,94 @@
<?php
/**
* adapter for SimpleTest to use PHPUnit test cases
* @package SimpleTest
* @subpackage Extensions
* @version $Id$
*/
/**
* adapter for SimpleTest to use PHPUnit test cases
* @package SimpleTest
* @subpackage Extensions
* @version $Id$
*/
/**#@+
* include SimpleTest files
*/
require_once dirname(__FILE__).DIRECTORY_SEPARATOR
.'..'.DIRECTORY_SEPARATOR . 'unit_tester.php';
require_once dirname(__FILE__).DIRECTORY_SEPARATOR
.'..'.DIRECTORY_SEPARATOR . 'expectation.php';
/**#@-*/
/**#@+
* 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
*/
/**
* 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
*/
/**
* Constructor. Sets the test name.
* @param $label Test name to display.
* @public
*/
function TestCase($label) {
$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
*/
/**
* 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::assertTrue($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
*/
/**
* 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) {
$this->assertExpectation(
new EqualExpectation($first),
$second,
$message);
parent::assert(new EqualExpectation($first), $second, $message);
}
/**
* Will test straight equality if set to loose
* typing, or identity if not.
* @param $first First value.
* @param $second Comparison value.
* @param $message Message to display.
* @public
*/
/**
* Simple string equality.
* @param $first First value.
* @param $second Comparison value.
* @param $message Message to display.
* @public
*/
function assertEqualsMultilineStrings($first, $second, $message = false) {
$this->assertExpectation(
new EqualExpectation($first),
$second,
$message);
parent::assert(new EqualExpectation($first), $second, $message);
}
/**
* Tests a regex match.
* @param $pattern Regex to match.
* @param $subject String to search in.
* @param $message Message to display.
* @public
*/
/**
* 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) {
$this->assertExpectation(
new WantedPatternExpectation($pattern),
$subject,
$message);
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
*/
/**
* 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::assertTrue(false, "Error triggered [$message]");
parent::fail("Error triggered [$message]");
}
/**
* Accessor for name.
* @public
*/
/**
* Accessor for name.
* @public
*/
function name() {
return $this->getLabel();
}

View file

@ -1,108 +1,28 @@
<?php
/**
* Base include file for SimpleTest.
* @package SimpleTest
* @subpackage WebTester
* @version $Id$
*/
/**
* Base include file for SimpleTest.
* @package SimpleTest
* @subpackage WebTester
* @version $Id$
*/
/**#@+
* include SimpleTest files
*/
/**#@+
* include SimpleTest files
*/
require_once(dirname(__FILE__) . '/tag.php');
require_once(dirname(__FILE__) . '/encoding.php');
/**#@-*/
require_once(dirname(__FILE__) . '/selector.php');
/**#@-*/
/**
* Used to extract form elements for testing against.
* Searches by name attribute.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleNameSelector {
var $_name;
/**
* Stashes the name for later comparison.
* @param string $name Name attribute to match.
*/
function SimpleNameSelector($name) {
$this->_name = $name;
}
/**
* Comparison. Compares with name attribute of
* widget.
* @param SimpleWidget $widget Control to compare.
* @access public
*/
function isMatch($widget) {
return ($widget->getName() == $this->_name);
}
}
/**
* Used to extract form elements for testing against.
* Searches by visible label or alt text.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleLabelSelector {
var $_label;
/**
* Stashes the name for later comparison.
* @param string $label Visible text to match.
*/
function SimpleLabelSelector($label) {
$this->_label = $label;
}
/**
* Comparison. Compares visible text of widget.
* @param SimpleWidget $widget Control to compare.
* @access public
*/
function isMatch($widget) {
return (trim($widget->getLabel()) == trim($this->_label));
}
}
/**
* Used to extract form elements for testing against.
* Searches dy id attribute.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleIdSelector {
var $_id;
/**
* Stashes the name for later comparison.
* @param string $id ID atribute to match.
*/
function SimpleIdSelector($id) {
$this->_id = $id;
}
/**
* Comparison. Compares id attribute of widget.
* @param SimpleWidget $widget Control to compare.
* @access public
*/
function isMatch($widget) {
return $widget->isId($this->_id);
}
}
/**
* Form tag class to hold widget values.
* @package SimpleTest
* @subpackage WebTester
*/
/**
* Form tag class to hold widget values.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleForm {
var $_method;
var $_action;
var $_encoding;
var $_default_target;
var $_id;
var $_buttons;
@ -111,14 +31,15 @@
var $_radios;
var $_checkboxes;
/**
* Starts with no held controls/widgets.
* @param SimpleTag $tag Form tag to read.
* @param SimpleUrl $url Location of holding page.
*/
/**
* Starts with no held controls/widgets.
* @param SimpleTag $tag Form tag to read.
* @param SimpleUrl $url Location of holding page.
*/
function SimpleForm($tag, $url) {
$this->_method = $tag->getAttribute('method');
$this->_action = $this->_createAction($tag->getAttribute('action'), $url);
$this->_encoding = $this->_setEncodingClass($tag);
$this->_default_target = false;
$this->_id = $tag->getAttribute('id');
$this->_buttons = array();
@ -128,48 +49,60 @@
$this->_checkboxes = array();
}
/**
* Sets the frame target within a frameset.
* @param string $frame Name of frame.
* @access public
*/
/**
* Creates the request packet to be sent by the form.
* @param SimpleTag $tag Form tag to read.
* @return string Packet class.
* @access private
*/
function _setEncodingClass($tag) {
if (strtolower($tag->getAttribute('method')) == 'post') {
if (strtolower($tag->getAttribute('enctype')) == 'multipart/form-data') {
return 'SimpleMultipartEncoding';
}
return 'SimplePostEncoding';
}
return 'SimpleGetEncoding';
}
/**
* Sets the frame target within a frameset.
* @param string $frame Name of frame.
* @access public
*/
function setDefaultTarget($frame) {
$this->_default_target = $frame;
}
/**
* Accessor for form action.
* @return string Either get or post.
* @access public
*/
/**
* Accessor for form action.
* @return string Either get or post.
* @access public
*/
function getMethod() {
return ($this->_method ? strtolower($this->_method) : 'get');
}
/**
* Combined action attribute with current location
* to get an absolute form target.
* @param string $action Action attribute from form tag.
* @param SimpleUrl $base Page location.
* @return SimpleUrl Absolute form target.
*/
/**
* Combined action attribute with current location
* to get an absolute form target.
* @param string $action Action attribute from form tag.
* @param SimpleUrl $base Page location.
* @return SimpleUrl Absolute form target.
*/
function _createAction($action, $base) {
if ($action === false) {
if (is_bool($action)) {
return $base;
}
if ($action === true) {
$url = new SimpleUrl('');
} else {
$url = new SimpleUrl($action);
}
$url = new SimpleUrl($action);
return $url->makeAbsolute($base);
}
/**
* Absolute URL of the target.
* @return SimpleUrl URL target.
* @access public
*/
/**
* Absolute URL of the target.
* @return SimpleUrl URL target.
* @access public
*/
function getAction() {
$url = $this->_action;
if ($this->_default_target && ! $url->getTarget()) {
@ -177,22 +110,37 @@
}
return $url;
}
/**
* ID field of form for unique identification.
* @return string Unique tag ID.
* @access public
*/
/**
* Creates the encoding for the current values in the
* form.
* @return SimpleFormEncoding Request to submit.
* @access private
*/
function _encode() {
$class = $this->_encoding;
$encoding = new $class();
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
$this->_widgets[$i]->write($encoding);
}
return $encoding;
}
/**
* ID field of form for unique identification.
* @return string Unique tag ID.
* @access public
*/
function getId() {
return $this->_id;
}
/**
* Adds a tag contents to the form.
* @param SimpleWidget $tag Input tag to add.
* @access public
*/
function addWidget($tag) {
/**
* Adds a tag contents to the form.
* @param SimpleWidget $tag Input tag to add.
* @access public
*/
function addWidget(&$tag) {
if (strtolower($tag->getAttribute('type')) == 'submit') {
$this->_buttons[] = &$tag;
} elseif (strtolower($tag->getAttribute('type')) == 'image') {
@ -202,13 +150,13 @@
}
}
/**
* Sets the widget into the form, grouping radio
* buttons if any.
* @param SimpleWidget $tag Incoming form control.
* @access private
*/
function _setWidget($tag) {
/**
* Sets the widget into the form, grouping radio
* buttons if any.
* @param SimpleWidget $tag Incoming form control.
* @access private
*/
function _setWidget(&$tag) {
if (strtolower($tag->getAttribute('type')) == 'radio') {
$this->_addRadioButton($tag);
} elseif (strtolower($tag->getAttribute('type')) == 'checkbox') {
@ -218,12 +166,12 @@
}
}
/**
* Adds a radio button, building a group if necessary.
* @param SimpleRadioButtonTag $tag Incoming form control.
* @access private
*/
function _addRadioButton($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;
@ -231,12 +179,12 @@
$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) {
/**
* 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;
@ -251,14 +199,14 @@
}
}
/**
* Extracts current value from form.
* @param SimpleSelector $selector Criteria to apply.
* @return string/array Value(s) as string or null
* if not set.
* @access public
*/
function _getValueBySelector($selector) {
/**
* Extracts current value from form.
* @param SimpleSelector $selector Criteria to apply.
* @return string/array Value(s) as string or null
* if not set.
* @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();
@ -272,38 +220,16 @@
return null;
}
/**
* Extracts current value from form.
* @param string $name Keyed by widget name.
* @return string/array Value(s) or null
* if not set.
* @access public
*/
function getValue($name) {
return $this->_getValueBySelector(new SimpleNameSelector($name));
}
/**
* Extracts current value from form by the ID.
* @param string/integer $id Keyed by widget ID attribute.
* @return string/array Value(s) or null
* if not set.
* @access public
*/
function getValueById($id) {
return $this->_getValueBySelector(new SimpleIdSelector($id));
}
/**
* Sets a widget value within the form.
* @param SimpleSelector $selector Criteria to apply.
* @param string $value Value to input into the widget.
* @return boolean True if value is legal, false
* otherwise. If the field is not
* present, nothing will be set.
* @access public
*/
function _setFieldBySelector($selector, $value) {
/**
* Sets a widget value within the form.
* @param SimpleSelector $selector Criteria to apply.
* @param string $value Value to input into the widget.
* @return boolean True if value is legal, false
* otherwise. If the field is not
* present, nothing will be set.
* @access public
*/
function setField($selector, $value) {
$success = false;
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($selector->isMatch($this->_widgets[$i])) {
@ -315,55 +241,31 @@
return $success;
}
/**
* Sets a widget value within the form.
* @param string $name Name of widget tag.
* @param string $value Value to input into the widget.
* @return boolean True if value is legal, false
* otherwise. If the field is not
* present, nothing will be set.
* @access public
*/
function setField($name, $value) {
return $this->_setFieldBySelector(new SimpleNameSelector($name), $value);
}
/**
* Sets a widget value within the form by using the ID.
* @param string/integer $id Name of widget tag.
* @param string $value Value to input into the widget.
* @return boolean True if value is legal, false
* otherwise. If the field is not
* present, nothing will be set.
* @access public
*/
function setFieldById($id, $value) {
return $this->_setFieldBySelector(new SimpleIdSelector($id), $value);
}
/**
* Creates the encoding for the current values in the
* form.
* @return SimpleFormEncoding Request to submit.
* @access private
*/
function _getEncoding() {
$encoding = new SimpleFormEncoding();
/**
* Used by the page object to set widgets labels to
* external label tags.
* @param SimpleSelector $selector Criteria to apply.
* @access public
*/
function attachLabelBySelector($selector, $label) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
$encoding->add(
$this->_widgets[$i]->getName(),
$this->_widgets[$i]->getValue());
if ($selector->isMatch($this->_widgets[$i])) {
if (method_exists($this->_widgets[$i], 'setLabel')) {
$this->_widgets[$i]->setLabel($label);
return;
}
}
}
return $encoding;
}
/**
* Test to see if a form has a submit button.
* @param SimpleSelector $selector Criteria to apply.
* @return boolean True if present.
* @access private
*/
function _hasSubmitBySelector($selector) {
/**
* Test to see if a form has a submit button.
* @param SimpleSelector $selector Criteria to apply.
* @return boolean True if present.
* @access private
* @access public
*/
function hasSubmit($selector) {
foreach ($this->_buttons as $button) {
if ($selector->isMatch($button)) {
return true;
@ -372,46 +274,13 @@
return false;
}
/**
* Test to see if a form has a submit button with this
* name attribute.
* @param string $name Name to look for.
* @return boolean True if present.
* @access public
*/
function hasSubmitName($name) {
return $this->_hasSubmitBySelector(new SimpleNameSelector($name));
}
/**
* Test to see if a form has a submit button with this
* value attribute.
* @param string $label Button label to search for.
* @return boolean True if present.
* @access public
*/
function hasSubmitLabel($label) {
return $this->_hasSubmitBySelector(new SimpleLabelSelector($label));
}
/**
* Test to see if a form has a submit button with this
* ID attribute.
* @param string $id Button ID attribute to search for.
* @return boolean True if present.
* @access public
*/
function hasSubmitId($id) {
return $this->_hasSubmitBySelector(new SimpleIdSelector($id));
}
/**
* Test to see if a form has an image control.
* @param SimpleSelector $selector Criteria to apply.
* @return boolean True if present.
* @access public
*/
function _hasImageBySelector($selector) {
/**
* Test to see if a form has an image control.
* @param SimpleSelector $selector Criteria to apply.
* @return boolean True if present.
* @access public
*/
function hasImage($selector) {
foreach ($this->_images as $image) {
if ($selector->isMatch($image)) {
return true;
@ -419,54 +288,21 @@
}
return false;
}
/**
* Test to see if a form has a submit button with this
* name attribute.
* @param string $label Button alt attribute to search for
* or nearest equivalent.
* @return boolean True if present.
* @access public
*/
function hasImageLabel($label) {
return $this->_hasImageBySelector(new SimpleLabelSelector($label));
}
/**
* Test to see if a form has a submittable image with this
* field name.
* @param string $name Image name to search for.
* @return boolean True if present.
* @access public
*/
function hasImageName($name) {
return $this->_hasImageBySelector(new SimpleNameSelector($name));
}
/**
* Test to see if a form has a submittable image with this
* ID attribute.
* @param string $id Button ID attribute to search for.
* @return boolean True if present.
* @access public
*/
function hasImageId($id) {
return $this->_hasImageBySelector(new SimpleIdSelector($id));
}
/**
* Gets the submit values for a selected button.
* @param SimpleSelector $selector Criteria to apply.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button
* in the form.
* @access public
*/
function _submitButtonBySelector($selector, $additional) {
/**
* Gets the submit values for a selected button.
* @param SimpleSelector $selector Criteria to apply.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button
* in the form.
* @access public
*/
function submitButton($selector, $additional = false) {
$additional = $additional ? $additional : array();
foreach ($this->_buttons as $button) {
if ($selector->isMatch($button)) {
$encoding = $this->_getEncoding();
$encoding = $this->_encode();
$encoding->merge($button->getSubmitValues());
if ($additional) {
$encoding->merge($additional);
@ -476,67 +312,23 @@
}
return false;
}
/**
* Gets the submit values for a named button.
* @param string $name Button label to search for.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitButtonByName($name, $additional = false) {
return $this->_submitButtonBySelector(
new SimpleNameSelector($name),
$additional);
}
/**
* Gets the submit values for a named button.
* @param string $label Button label to search for.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitButtonByLabel($label, $additional = false) {
return $this->_submitButtonBySelector(
new SimpleLabelSelector($label),
$additional);
}
/**
* Gets the submit values for a button identified by the ID.
* @param string $id Button ID attribute to search for.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitButtonById($id, $additional = false) {
return $this->_submitButtonBySelector(
new SimpleIdSelector($id),
$additional);
}
/**
* Gets the submit values for an image.
* @param SimpleSelector $selector Criteria to apply.
* @param integer $x X-coordinate of click.
* @param integer $y Y-coordinate of click.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function _submitImageBySelector($selector, $x, $y, $additional) {
/**
* Gets the submit values for an image.
* @param SimpleSelector $selector Criteria to apply.
* @param integer $x X-coordinate of click.
* @param integer $y Y-coordinate of click.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitImage($selector, $x, $y, $additional = false) {
$additional = $additional ? $additional : array();
foreach ($this->_images as $image) {
if ($selector->isMatch($image)) {
$encoding = $this->_getEncoding();
$encoding = $this->_encode();
$encoding->merge($image->getSubmitValues($x, $y));
if ($additional) {
$encoding->merge($additional);
@ -546,74 +338,16 @@
}
return false;
}
/**
* Gets the submit values for an image identified by the alt
* tag or nearest equivalent.
* @param string $label Button label to search for.
* @param integer $x X-coordinate of click.
* @param integer $y Y-coordinate of click.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitImageByLabel($label, $x, $y, $additional = false) {
return $this->_submitImageBySelector(
new SimpleLabelSelector($label),
$x,
$y,
$additional);
}
/**
* Gets the submit values for an image identified by the ID.
* @param string $name Image name to search for.
* @param integer $x X-coordinate of click.
* @param integer $y Y-coordinate of click.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitImageByName($name, $x, $y, $additional = false) {
return $this->_submitImageBySelector(
new SimpleNameSelector($name),
$x,
$y,
$additional);
}
/**
* Gets the submit values for an image identified by the ID.
* @param string/integer $id Button ID attribute to search for.
* @param integer $x X-coordinate of click.
* @param integer $y Y-coordinate of click.
* @param hash $additional Additional data for the form.
* @return SimpleEncoding Submitted values or false
* if there is no such button in the
* form.
* @access public
*/
function submitImageById($id, $x, $y, $additional = false) {
return $this->_submitImageBySelector(
new SimpleIdSelector($id),
$x,
$y,
$additional);
}
/**
* Simply submits the form without the submit button
* value. Used when there is only one button or it
* is unimportant.
* @return hash Submitted values.
* @access public
*/
/**
* Simply submits the form without the submit button
* value. Used when there is only one button or it
* is unimportant.
* @return hash Submitted values.
* @access public
*/
function submit() {
return $this->_getEncoding();
return $this->_encode();
}
}
?>

View file

@ -1,37 +1,37 @@
<?php
/**
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
* @version $Id$
*/
/**
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
* @version $Id$
*/
/**#@+
* include other SimpleTest class files
*/
/**#@+
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/page.php');
require_once(dirname(__FILE__) . '/user_agent.php');
/**#@-*/
/**#@-*/
/**
* A composite page. Wraps a frameset page and
* adds subframes. The original page will be
* mostly ignored. Implements the SimplePage
* interface so as to be interchangeable.
* @package SimpleTest
* @subpackage WebTester
*/
/**
* A composite page. Wraps a frameset page and
* adds subframes. The original page will be
* mostly ignored. Implements the SimplePage
* interface so as to be interchangeable.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleFrameset {
var $_frameset;
var $_frames;
var $_focus;
var $_names;
/**
* Stashes the frameset page. Will make use of the
* browser to fetch the sub frames recursively.
* @param SimplePage $page Frameset page.
*/
/**
* 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();
@ -39,12 +39,12 @@
$this->_names = array();
}
/**
* Adds a parsed page to the frameset.
* @param SimplePage $page Frame page.
* @param string $name Name of frame in frameset.
* @access public
*/
/**
* Adds a parsed page to the frameset.
* @param SimplePage $page Frame page.
* @param string $name Name of frame in frameset.
* @access public
*/
function addFrame(&$page, $name = false) {
$this->_frames[] = &$page;
if ($name) {
@ -52,14 +52,14 @@
}
}
/**
* Replaces existing frame with another. If the
* frame is nested, then the call is passed down
* one level.
* @param array $path Path of frame in frameset.
* @param SimplePage $page Frame source.
* @access public
*/
/**
* Replaces existing frame with another. If the
* frame is nested, then the call is passed down
* one level.
* @param array $path Path of frame in frameset.
* @param SimplePage $page Frame source.
* @access public
*/
function setFrame($path, &$page) {
$name = array_shift($path);
if (isset($this->_names[$name])) {
@ -74,13 +74,13 @@
$this->_frames[$index]->setFrame($path, $page);
}
/**
* Accessor for current frame focus. Will be
* false if no frame has focus. Will have the nested
* frame focus if any.
* @return array Labels or indexes of nested frames.
* @access public
*/
/**
* Accessor for current frame focus. Will be
* false if no frame has focus. Will have the nested
* frame focus if any.
* @return array Labels or indexes of nested frames.
* @access public
*/
function getFrameFocus() {
if ($this->_focus === false) {
return array();
@ -90,14 +90,14 @@
$this->_frames[$this->_focus]->getFrameFocus());
}
/**
* Turns an internal array index into the frames list
* into a public name, or if none, then a one offset
* index.
* @param integer $subject Internal index.
* @return integer/string Public name.
* @access private
*/
/**
* Turns an internal array index into the frames list
* into a public name, or if none, then a one offset
* index.
* @param integer $subject Internal index.
* @return integer/string Public name.
* @access private
*/
function _getPublicNameFromIndex($subject) {
foreach ($this->_names as $name => $index) {
if ($subject == $index) {
@ -107,14 +107,14 @@
return $subject + 1;
}
/**
* Sets the focus by index. The integer index starts from 1.
* If already focused and the target frame also has frames,
* then the nested frame will be focused.
* @param integer $choice Chosen frame.
* @return boolean True if frame exists.
* @access public
*/
/**
* Sets the focus by index. The integer index starts from 1.
* If already focused and the target frame also has frames,
* then the nested frame will be focused.
* @param integer $choice Chosen frame.
* @return boolean True if frame exists.
* @access public
*/
function setFrameFocusByIndex($choice) {
if (is_integer($this->_focus)) {
if ($this->_frames[$this->_focus]->hasFrames()) {
@ -128,14 +128,14 @@
return true;
}
/**
* Sets the focus by name. If already focused and the
* target frame also has frames, then the nested frame
* will be focused.
* @param string $name Chosen frame.
* @return boolean True if frame exists.
* @access public
*/
/**
* Sets the focus by name. If already focused and the
* target frame also has frames, then the nested frame
* will be focused.
* @param string $name Chosen frame.
* @return boolean True if frame exists.
* @access public
*/
function setFrameFocus($name) {
if (is_integer($this->_focus)) {
if ($this->_frames[$this->_focus]->hasFrames()) {
@ -149,41 +149,41 @@
return false;
}
/**
* Clears the frame focus.
* @access public
*/
/**
* Clears the frame focus.
* @access public
*/
function clearFrameFocus() {
$this->_focus = false;
$this->_clearNestedFramesFocus();
}
/**
* Clears the frame focus for any nested frames.
* @access private
*/
/**
* Clears the frame focus for any nested frames.
* @access private
*/
function _clearNestedFramesFocus() {
for ($i = 0; $i < count($this->_frames); $i++) {
$this->_frames[$i]->clearFrameFocus();
}
}
/**
* Test for the presence of a frameset.
* @return boolean Always true.
* @access public
*/
/**
* Test for the presence of a frameset.
* @return boolean Always true.
* @access public
*/
function hasFrames() {
return true;
}
/**
* Accessor for frames information.
* @return array/string Recursive hash of frame URL strings.
* The key is either a numerical
* index or the name attribute.
* @access public
*/
/**
* Accessor for frames information.
* @return array/string Recursive hash of frame URL strings.
* The key is either a numerical
* index or the name attribute.
* @access public
*/
function getFrames() {
$report = array();
for ($i = 0; $i < count($this->_frames); $i++) {
@ -193,12 +193,12 @@
return $report;
}
/**
* Accessor for raw text of either all the pages or
* the frame in focus.
* @return string Raw unparsed content.
* @access public
*/
/**
* Accessor for raw text of either all the pages or
* the frame in focus.
* @return string Raw unparsed content.
* @access public
*/
function getRaw() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getRaw();
@ -210,12 +210,12 @@
return $raw;
}
/**
* Accessor for plain text of either all the pages or
* the frame in focus.
* @return string Plain text content.
* @access public
*/
/**
* Accessor for plain text of either all the pages or
* the frame in focus.
* @return string Plain text content.
* @access public
*/
function getText() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getText();
@ -227,11 +227,11 @@
return trim($raw);
}
/**
* Accessor for last error.
* @return string Error from last response.
* @access public
*/
/**
* Accessor for last error.
* @return string Error from last response.
* @access public
*/
function getTransportError() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getTransportError();
@ -239,11 +239,11 @@
return $this->_frameset->getTransportError();
}
/**
* Request method used to fetch this frame.
* @return string GET, POST or HEAD.
* @access public
*/
/**
* Request method used to fetch this frame.
* @return string GET, POST or HEAD.
* @access public
*/
function getMethod() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getMethod();
@ -251,11 +251,11 @@
return $this->_frameset->getMethod();
}
/**
* Original resource name.
* @return SimpleUrl Current url.
* @access public
*/
/**
* Original resource name.
* @return SimpleUrl Current url.
* @access public
*/
function getUrl() {
if (is_integer($this->_focus)) {
$url = $this->_frames[$this->_focus]->getUrl();
@ -266,11 +266,11 @@
return $url;
}
/**
* Original request data.
* @return mixed Sent content.
* @access public
*/
/**
* Original request data.
* @return mixed Sent content.
* @access public
*/
function getRequestData() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getRequestData();
@ -278,11 +278,11 @@
return $this->_frameset->getRequestData();
}
/**
* Accessor for current MIME type.
* @return string MIME type as string; e.g. 'text/html'
* @access public
*/
/**
* Accessor for current MIME type.
* @return string MIME type as string; e.g. 'text/html'
* @access public
*/
function getMimeType() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getMimeType();
@ -290,11 +290,11 @@
return $this->_frameset->getMimeType();
}
/**
* Accessor for last response code.
* @return integer Last HTTP response code received.
* @access public
*/
/**
* Accessor for last response code.
* @return integer Last HTTP response code received.
* @access public
*/
function getResponseCode() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getResponseCode();
@ -302,12 +302,12 @@
return $this->_frameset->getResponseCode();
}
/**
* Accessor for last Authentication type. Only valid
* straight after a challenge (401).
* @return string Description of challenge type.
* @access public
*/
/**
* Accessor for last Authentication type. Only valid
* straight after a challenge (401).
* @return string Description of challenge type.
* @access public
*/
function getAuthentication() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getAuthentication();
@ -315,12 +315,12 @@
return $this->_frameset->getAuthentication();
}
/**
* Accessor for last Authentication realm. Only valid
* straight after a challenge (401).
* @return string Name of security realm.
* @access public
*/
/**
* Accessor for last Authentication realm. Only valid
* straight after a challenge (401).
* @return string Name of security realm.
* @access public
*/
function getRealm() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getRealm();
@ -328,11 +328,11 @@
return $this->_frameset->getRealm();
}
/**
* Accessor for outgoing header information.
* @return string Header block.
* @access public
*/
/**
* Accessor for outgoing header information.
* @return string Header block.
* @access public
*/
function getRequest() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getRequest();
@ -340,11 +340,11 @@
return $this->_frameset->getRequest();
}
/**
* Accessor for raw header information.
* @return string Header block.
* @access public
*/
/**
* Accessor for raw header information.
* @return string Header block.
* @access public
*/
function getHeaders() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getHeaders();
@ -352,21 +352,21 @@
return $this->_frameset->getHeaders();
}
/**
* Accessor for parsed title.
* @return string Title or false if no title is present.
* @access public
*/
/**
* Accessor for parsed title.
* @return string Title or false if no title is present.
* @access public
*/
function getTitle() {
return $this->_frameset->getTitle();
}
/**
* Accessor for a list of all fixed links.
* @return array List of urls with scheme of
* http or https and hostname.
* @access public
*/
/**
* Accessor for a list of all fixed links.
* @return array List of urls with scheme of
* http or https and hostname.
* @access public
*/
function getAbsoluteUrls() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getAbsoluteUrls();
@ -378,11 +378,11 @@
return array_values(array_unique($urls));
}
/**
* Accessor for a list of all relative links.
* @return array List of urls without hostname.
* @access public
*/
/**
* Accessor for a list of all relative links.
* @return array List of urls without hostname.
* @access public
*/
function getRelativeUrls() {
if (is_integer($this->_focus)) {
return $this->_frames[$this->_focus]->getRelativeUrls();
@ -394,13 +394,13 @@
return array_values(array_unique($urls));
}
/**
* Accessor for URLs by the link label. Label will match
* regardess of whitespace issues and case.
* @param string $label Text of link.
* @return array List of links with that label.
* @access public
*/
/**
* Accessor for URLs by the link label. Label will match
* regardess of whitespace issues and case.
* @param string $label Text of link.
* @return array List of links with that label.
* @access public
*/
function getUrlsByLabel($label) {
if (is_integer($this->_focus)) {
return $this->_tagUrlsWithFrame(
@ -418,15 +418,15 @@
return $urls;
}
/**
* Accessor for a URL by the id attribute. If in a frameset
* then the first link found with that ID attribute is
* returned only. Focus on a frame if you want one from
* a specific part of the frameset.
* @param string $id Id attribute of link.
* @return string URL with that id.
* @access public
*/
/**
* Accessor for a URL by the id attribute. If in a frameset
* then the first link found with that ID attribute is
* returned only. Focus on a frame if you want one from
* a specific part of the frameset.
* @param string $id Id attribute of link.
* @return string URL with that id.
* @access public
*/
function getUrlById($id) {
foreach ($this->_frames as $index => $frame) {
if ($url = $frame->getUrlById($id)) {
@ -439,13 +439,13 @@
return false;
}
/**
* Attaches the intended frame index to a list of URLs.
* @param array $urls List of SimpleUrls.
* @param string $frame Name of frame or index.
* @return array List of tagged URLs.
* @access private
*/
/**
* Attaches the intended frame index to a list of URLs.
* @param array $urls List of SimpleUrls.
* @param string $frame Name of frame or index.
* @return array List of tagged URLs.
* @access private
*/
function _tagUrlsWithFrame($urls, $frame) {
$tagged = array();
foreach ($urls as $url) {
@ -457,113 +457,121 @@
return $tagged;
}
/**
* Finds a held form by button label. Will only
* search correctly built forms. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $label Button label, default 'Submit'.
* @return SimpleForm Form object containing the button.
* @access public
*/
/**
* Finds a held form by button label. Will only
* search correctly built forms. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $label Button label, default 'Submit'.
* @return SimpleForm Form object containing the button.
* @access public
*/
function &getFormBySubmitLabel($label) {
return $this->_findForm('getFormBySubmitLabel', $label);
$form = &$this->_findForm('getFormBySubmitLabel', $label);
return $form;
}
/**
* Finds a held form by button label. Will only
* search correctly built forms. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $name Button name attribute.
* @return SimpleForm Form object containing the button.
* @access public
*/
/**
* Finds a held form by button label. Will only
* search correctly built forms. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $name Button name attribute.
* @return SimpleForm Form object containing the button.
* @access public
*/
function &getFormBySubmitName($name) {
return $this->_findForm('getFormBySubmitName', $name);
$form = &$this->_findForm('getFormBySubmitName', $name);
return $form;
}
/**
* Finds a held form by button id. Will only
* search correctly built forms. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $id Button ID attribute.
* @return SimpleForm Form object containing the button.
* @access public
*/
/**
* Finds a held form by button id. Will only
* search correctly built forms. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $id Button ID attribute.
* @return SimpleForm Form object containing the button.
* @access public
*/
function &getFormBySubmitId($id) {
return $this->_findForm('getFormBySubmitId', $id);
$form = &$this->_findForm('getFormBySubmitId', $id);
return $form;
}
/**
* Finds a held form by image label. Will only
* search correctly built forms. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $label Usually the alt attribute.
* @return SimpleForm Form object containing the image.
* @access public
*/
/**
* Finds a held form by image label. Will only
* search correctly built forms. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $label Usually the alt attribute.
* @return SimpleForm Form object containing the image.
* @access public
*/
function &getFormByImageLabel($label) {
return $this->_findForm('getFormByImageLabel', $label);
$form = &$this->_findForm('getFormByImageLabel', $label);
return $form;
}
/**
* Finds a held form by image button id. Will only
* search correctly built forms. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $name Image name.
* @return SimpleForm Form object containing the image.
* @access public
*/
/**
* Finds a held form by image button id. Will only
* search correctly built forms. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $name Image name.
* @return SimpleForm Form object containing the image.
* @access public
*/
function &getFormByImageName($name) {
return $this->_findForm('getFormByImageName', $name);
$form = &$this->_findForm('getFormByImageName', $name);
return $form;
}
/**
* Finds a held form by image button id. Will only
* search correctly built forms. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $id Image ID attribute.
* @return SimpleForm Form object containing the image.
* @access public
*/
/**
* Finds a held form by image button id. Will only
* search correctly built forms. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $id Image ID attribute.
* @return SimpleForm Form object containing the image.
* @access public
*/
function &getFormByImageId($id) {
return $this->_findForm('getFormByImageId', $id);
$form = &$this->_findForm('getFormByImageId', $id);
return $form;
}
/**
* Finds a held form by the form ID. A way of
* identifying a specific form when we have control
* of the HTML code. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $id Form label.
* @return SimpleForm Form object containing the matching ID.
* @access public
*/
/**
* Finds a held form by the form ID. A way of
* identifying a specific form when we have control
* of the HTML code. The first form found
* either within the focused frame, or across frames,
* will be the one returned.
* @param string $id Form label.
* @return SimpleForm Form object containing the matching ID.
* @access public
*/
function &getFormById($id) {
return $this->_findForm('getFormById', $id);
$form = &$this->_findForm('getFormById', $id);
return $form;
}
/**
* General form finder. Will search all the frames or
* just the one in focus.
* @param string $method Method to use to find in a page.
* @param string $attribute Label, name or ID.
* @return SimpleForm Form object containing the matching ID.
* @access private
*/
/**
* General form finder. Will search all the frames or
* just the one in focus.
* @param string $method Method to use to find in a page.
* @param string $attribute Label, name or ID.
* @return SimpleForm Form object containing the matching ID.
* @access private
*/
function &_findForm($method, $attribute) {
if (is_integer($this->_focus)) {
return $this->_findFormInFrame(
$form = &$this->_findFormInFrame(
$this->_frames[$this->_focus],
$this->_focus,
$method,
$attribute);
return $form;
}
for ($i = 0; $i < count($this->_frames); $i++) {
$form = &$this->_findFormInFrame(
@ -575,19 +583,20 @@
return $form;
}
}
return null;
$null = null;
return $null;
}
/**
* Finds a form in a page using a form finding method. Will
* also tag the form with the frame name it belongs in.
* @param SimplePage $page Page content of frame.
* @param integer $index Internal frame representation.
* @param string $method Method to use to find in a page.
* @param string $attribute Label, name or ID.
* @return SimpleForm Form object containing the matching ID.
* @access private
*/
/**
* Finds a form in a page using a form finding method. Will
* also tag the form with the frame name it belongs in.
* @param SimplePage $page Page content of frame.
* @param integer $index Internal frame representation.
* @param string $method Method to use to find in a page.
* @param string $attribute Label, name or ID.
* @return SimpleForm Form object containing the matching ID.
* @access private
*/
function &_findFormInFrame(&$page, $index, $method, $attribute) {
$form = &$this->_frames[$index]->$method($attribute);
if (isset($form)) {
@ -596,32 +605,51 @@
return $form;
}
/**
* Sets a field on each form in which the field is
* available.
* @param string $name Field name.
* @param string $value Value to set field to.
* @return boolean True if value is valid.
* @access public
*/
function setField($name, $value) {
/**
* Sets a field on each form in which the field is
* available by label and then name. labels are not
* yet implemented.
* @param string $label Field name.
* @param string $value Value to set field to.
* @return boolean True if value is valid.
* @access public
*/
function setField($label, $value) {
if (is_integer($this->_focus)) {
$this->_frames[$this->_focus]->setField($name, $value);
$this->_frames[$this->_focus]->setField($label, $value);
} else {
for ($i = 0; $i < count($this->_frames); $i++) {
$this->_frames[$i]->setField($name, $value);
$this->_frames[$i]->setField($label, $value);
}
}
}
/**
* Sets a field on each form in which the field is
* available.
* @param string $name Field name.
* @param string $value Value to set field to.
* @return boolean True if value is valid.
* @access public
*/
function setFieldByName($name, $value) {
if (is_integer($this->_focus)) {
$this->_frames[$this->_focus]->setFieldByName($name, $value);
} else {
for ($i = 0; $i < count($this->_frames); $i++) {
$this->_frames[$i]->setFieldByName($name, $value);
}
}
}
/**
* Sets a field on the form in which the unique field is
* available.
* @param string/integer $id Field ID attribute.
* @param string $value Value to set field to.
* @return boolean True if value is valid.
* @access public
*/
/**
* Sets a field on the form in which the unique field is
* available.
* @param string/integer $id Field ID attribute.
* @param string $value Value to set field to.
* @return boolean True if value is valid.
* @access public
*/
function setFieldById($id, $value) {
if (is_integer($this->_focus)) {
$this->_frames[$this->_focus]->setFieldById($id, $value);
@ -632,18 +660,37 @@
}
}
/**
* Accessor for a form element value within a frameset.
* Finds the first match amongst the frames.
* @param string $name Field name.
* @return string/boolean A string if the field is
* present, false if unchecked
* and null if missing.
* @access public
*/
function getField($name) {
/**
* Accessor for a form element value within a frameset.
* Finds the first match amongst the frames.
* @param string $label Field label.
* @return string/boolean A string if the field is
* present, false if unchecked
* and null if missing.
* @access public
*/
function getField($label) {
for ($i = 0; $i < count($this->_frames); $i++) {
$value = $this->_frames[$i]->getField($name);
$value = $this->_frames[$i]->getField($label);
if (isset($value)) {
return $value;
}
}
return null;
}
/**
* Accessor for a form element value within a frameset.
* Finds the first match amongst the frames.
* @param string $name Field name.
* @return string/boolean A string if the field is
* present, false if unchecked
* and null if missing.
* @access public
*/
function getFieldByName($name) {
for ($i = 0; $i < count($this->_frames); $i++) {
$value = $this->_frames[$i]->getFieldByName($name);
if (isset($value)) {
return $value;
}
@ -651,15 +698,15 @@
return null;
}
/**
* Accessor for a form element value within a page.
* Finds the first match.
* @param string/integer $id Field ID attribute.
* @return string/boolean A string if the field is
* present, false if unchecked
* and null if missing.
* @access public
*/
/**
* Accessor for a form element value within a page.
* Finds the first match.
* @param string/integer $id Field ID attribute.
* @return string/boolean A string if the field is
* present, false if unchecked
* and null if missing.
* @access public
*/
function getFieldById($id) {
for ($i = 0; $i < count($this->_frames); $i++) {
$value = $this->_frames[$i]->getFieldById($id);

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,139 +1,131 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @version $Id$
*/
/**
* base include file for SimpleTest
* @package SimpleTest
* @version $Id$
*/
/**
* Static global directives and options.
* @package SimpleTest
*/
/**
* Static global directives and options.
* @package SimpleTest
*/
class SimpleTestOptions {
/**
* Reads the SimpleTest version from the release file.
* @return string Version string.
* @static
* @access public
*/
/**
* Reads the SimpleTest version from the release file.
* @return string Version string.
* @static
* @access public
*/
function getVersion() {
$content = file(dirname(__FILE__) . '/VERSION');
return trim($content[0]);
}
/**
* Sets the name of a test case to ignore, usually
* because the class is an abstract case that should
* not be run.
* @param string $class Add a class to ignore.
* @static
* @access public
*/
/**
* Sets the name of a test case to ignore, usually
* because the class is an abstract case that should
* not be run.
* @param string $class Add a class to ignore.
* @static
* @access public
*/
function ignore($class) {
$registry = &SimpleTestOptions::_getRegistry();
$registry['IgnoreList'][] = strtolower($class);
}
/**
* Test to see if a test case is in the ignore
* list.
* @param string $class Class name to test.
* @return boolean True if should not be run.
* @access public
* @static
*/
/**
* Test to see if a test case is in the ignore
* list.
* @param string $class Class name to test.
* @return boolean True if should not be run.
* @access public
* @static
*/
function isIgnored($class) {
$registry = &SimpleTestOptions::_getRegistry();
return in_array(strtolower($class), $registry['IgnoreList']);
}
/**
* The base class name is settable here. This is the
* class that a new stub will inherited from.
* To modify the generated stubs simply extend the
* SimpleStub class and set it's name
* with this method before any stubs are generated.
* @param string $stub_base Server stub class to use.
* @static
* @access public
*/
/**
* The base class name is settable here. This is the
* class that a new stub will inherited from.
* To modify the generated stubs simply extend the
* SimpleStub class and set it's name
* with this method before any stubs are generated.
* @param string $stub_base Server stub class to use.
* @static
* @access public
*/
function setStubBaseClass($stub_base) {
$registry = &SimpleTestOptions::_getRegistry();
$registry['StubBaseClass'] = $stub_base;
}
/**
* Accessor for the currently set stub base class.
* @return string Class name to inherit from.
* @static
* @access public
*/
/**
* Accessor for the currently set stub base class.
* @return string Class name to inherit from.
* @static
* @access public
*/
function getStubBaseClass() {
$registry = &SimpleTestOptions::_getRegistry();
return $registry['StubBaseClass'];
}
/**
* The base class name is settable here. This is the
* class that a new mock will inherited from.
* To modify the generated mocks simply extend the
* SimpleMock class and set it's name
* with this method before any mocks are generated.
* @param string $mock_base Mock base class to use.
* @static
* @access public
*/
/**
* The base class name is settable here. This is the
* class that a new mock will inherited from.
* To modify the generated mocks simply extend the
* SimpleMock class and set it's name
* with this method before any mocks are generated.
* @param string $mock_base Mock base class to use.
* @static
* @access public
*/
function setMockBaseClass($mock_base) {
$registry = &SimpleTestOptions::_getRegistry();
$registry['MockBaseClass'] = $mock_base;
}
/**
* Accessor for the currently set mock base class.
* @return string Class name to inherit from.
* @static
* @access public
*/
/**
* Accessor for the currently set mock base class.
* @return string Class name to inherit from.
* @static
* @access public
*/
function getMockBaseClass() {
$registry = &SimpleTestOptions::_getRegistry();
return $registry['MockBaseClass'];
}
/**
* Adds additional mock code.
* @param string $code Extra code that can be added
* to the partial mocks for
* extra functionality. Useful
* when a test tool has overridden
* the mock base classes.
* @access public
*/
/**
* @deprecated
*/
function addPartialMockCode($code = '') {
$registry = &SimpleTestOptions::_getRegistry();
$registry['AdditionalPartialMockCode'] = $code;
}
/**
* Accessor for additional partial mock code.
* @return string Extra code.
* @access public
*/
/**
* @deprecated
*/
function getPartialMockCode() {
$registry = &SimpleTestOptions::_getRegistry();
return $registry['AdditionalPartialMockCode'];
}
/**
* Sets proxy to use on all requests for when
* testing from behind a firewall. Set host
* to false to disable. This will take effect
* if there are no other proxy settings.
* @param string $proxy Proxy host as URL.
* @param string $username Proxy username for authentication.
* @param string $password Proxy password for authentication.
* @access public
*/
/**
* Sets proxy to use on all requests for when
* testing from behind a firewall. Set host
* to false to disable. This will take effect
* if there are no other proxy settings.
* @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 = &SimpleTestOptions::_getRegistry();
$registry['DefaultProxy'] = $proxy;
@ -141,42 +133,42 @@
$registry['DefaultProxyPassword'] = $password;
}
/**
* Accessor for default proxy host.
* @return string Proxy URL.
* @access public
*/
/**
* Accessor for default proxy host.
* @return string Proxy URL.
* @access public
*/
function getDefaultProxy() {
$registry = &SimpleTestOptions::_getRegistry();
return $registry['DefaultProxy'];
}
/**
* Accessor for default proxy username.
* @return string Proxy username for authentication.
* @access public
*/
/**
* Accessor for default proxy username.
* @return string Proxy username for authentication.
* @access public
*/
function getDefaultProxyUsername() {
$registry = &SimpleTestOptions::_getRegistry();
return $registry['DefaultProxyUsername'];
}
/**
* Accessor for default proxy password.
* @return string Proxy password for authentication.
* @access public
*/
/**
* Accessor for default proxy password.
* @return string Proxy password for authentication.
* @access public
*/
function getDefaultProxyPassword() {
$registry = &SimpleTestOptions::_getRegistry();
return $registry['DefaultProxyPassword'];
}
/**
* Accessor for global registry of options.
* @return hash All stored values.
* @access private
* @static
*/
/**
* Accessor for global registry of options.
* @return hash All stored values.
* @access private
* @static
*/
function &_getRegistry() {
static $registry = false;
if (! $registry) {
@ -185,12 +177,12 @@
return $registry;
}
/**
* Constant default values.
* @return hash All registry defaults.
* @access private
* @static
*/
/**
* Constant default values.
* @return hash All registry defaults.
* @access private
* @static
*/
function _getDefaults() {
return array(
'StubBaseClass' => 'SimpleStub',
@ -203,22 +195,38 @@
}
}
/**
* Static methods for compatibility between different
* PHP versions.
* @package SimpleTest
*/
/**
* Static methods for compatibility between different
* PHP versions.
* @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) {
if (version_compare(phpversion(), '5') >= 0) {
eval('$copy = clone $object;');
return $copy;
}
return $object;
}
/**
* Identity test. Drops back to equality + types for PHP5
* objects as the === operator counts as the
* stronger reference constraint.
* @param mixed $first Test subject.
* @param mixed $second Comparison object.
* @access public
* @static
*/
/**
* Identity test. Drops back to equality + types for PHP5
* objects as the === operator counts as the
* stronger reference constraint.
* @param mixed $first Test subject.
* @param mixed $second Comparison object.
* @return boolean True if identical.
* @access public
* @static
*/
function isIdentical($first, $second) {
if ($first != $second) {
return false;
@ -229,13 +237,14 @@
return ($first === $second);
}
/**
* Recursive type test.
* @param mixed $first Test subject.
* @param mixed $second Comparison object.
* @access private
* @static
*/
/**
* 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) {
if (gettype($first) != gettype($second)) {
return false;
@ -254,13 +263,14 @@
return true;
}
/**
* Recursive type test for each element of an array.
* @param mixed $first Test subject.
* @param mixed $second Comparison object.
* @access private
* @static
*/
/**
* 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) {
if (array_keys($first) != array_keys($second)) {
return false;
@ -276,33 +286,42 @@
return true;
}
/**
* Test for two variables being aliases.
* @param mixed $first Test subject.
* @param mixed $second Comparison object.
* @access public
* @static
*/
/**
* 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) {
if (version_compare(phpversion(), '5', '>=')
&& is_object($first)) {
return ($first === $second);
}
$temp = $first;
&& is_object($first)) {
return ($first === $second);
}
if (is_object($first) && is_object($second)) {
$id = uniqid("test");
$first->$id = true;
$is_ref = isset($second->$id);
unset($first->$id);
return $is_ref;
}
$temp = $first;
$first = uniqid("test");
$is_ref = ($first === $second);
$first = $temp;
return $is_ref;
}
/**
* Test to see if an object is a member of a
* class hiearchy.
* @param object $object Object to test.
* @param string $class Root name of hiearchy.
* @access public
* @static
*/
/**
* Test to see if an object is a member of a
* class hiearchy.
* @param object $object Object to test.
* @param string $class Root name of hiearchy.
* @return boolean True if class in hiearchy.
* @access public
* @static
*/
function isA($object, $class) {
if (version_compare(phpversion(), '5') >= 0) {
if (! class_exists($class, false)) {
@ -318,28 +337,13 @@
or (is_subclass_of($object, $class)));
}
/**
* Autoload safe version of class_exists().
* @param string $class Name of class to look for.
* @return boolean True if class is defined.
* @access public
* @static
*/
function classExists($class) {
if (version_compare(phpversion(), '5') >= 0) {
return class_exists($class, false);
} else {
return class_exists($class);
}
}
/**
* Sets a socket timeout for each chunk.
* @param resource $handle Socket handle.
* @param integer $timeout Limit in seconds.
* @access public
* @static
*/
/**
* 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) {
if (function_exists('stream_set_timeout')) {
stream_set_timeout($handle, $timeout, 0);
@ -350,12 +354,12 @@
}
}
/**
* Gets the current stack trace topmost first.
* @return array List of stack frames.
* @access public
* @static
*/
/**
* Gets the current stack trace topmost first.
* @return array List of stack frames.
* @access public
* @static
*/
function getStackTrace() {
if (function_exists('debug_backtrace')) {
return array_reverse(debug_backtrace());

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,58 +1,58 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**#@+
* include other SimpleTest class files
*/
/**#@+
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/browser.php');
require_once(dirname(__FILE__) . '/xml.php');
require_once(dirname(__FILE__) . '/simple_test.php');
/**#@-*/
/**#@-*/
/**
* Runs an XML formated test on a remote server.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Runs an XML formated test on a remote server.
* @package SimpleTest
* @subpackage UnitTester
*/
class RemoteTestCase {
var $_url;
var $_dry_url;
var $_size;
/**
* Sets the location of the remote test.
* @param string $url Test location.
* @param string $dry_url Location for dry run.
* @access public
*/
/**
* 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;
}
/**
* Accessor for the test name for subclasses.
* @return string Name of the test.
* @access public
*/
/**
* Accessor for the test name for subclasses.
* @return string Name of the test.
* @access public
*/
function getLabel() {
return $this->_url;
}
/**
* Runs the top level test for this class. Currently
* reads the data as a single chunk. I'll fix this
* once I have added iteration to the browser.
* @param SimpleReporter $reporter Target of test results.
* @returns boolean True if no failures.
* @access public
*/
/**
* Runs the top level test for this class. Currently
* reads the data as a single chunk. I'll fix this
* once I have added iteration to the browser.
* @param SimpleReporter $reporter Target of test results.
* @returns boolean True if no failures.
* @access public
*/
function run(&$reporter) {
$browser = &$this->_createBrowser();
$xml = $browser->get($this->_url);
@ -68,31 +68,31 @@
return true;
}
/**
* Creates a new web browser object for fetching
* the XML report.
* @return SimpleBrowser New browser.
* @access protected
*/
/**
* Creates a new web browser object for fetching
* the XML report.
* @return SimpleBrowser New browser.
* @access protected
*/
function &_createBrowser() {
return new SimpleBrowser();
}
/**
* Creates the XML parser.
* @param SimpleReporter $reporter Target of test results.
* @return SimpleTestXmlListener XML reader.
* @access protected
*/
/**
* Creates the XML parser.
* @param SimpleReporter $reporter Target of test results.
* @return SimpleTestXmlListener XML reader.
* @access protected
*/
function &_createParser(&$reporter) {
return new SimpleTestXmlParser($reporter);
}
/**
* Accessor for the number of subtests.
* @return integer Number of test cases.
* @access public
*/
/**
* Accessor for the number of subtests.
* @return integer Number of test cases.
* @access public
*/
function getSize() {
if ($this->_size === false) {
$browser = &$this->_createBrowser();

View file

@ -1,43 +1,43 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**#@+
* include other SimpleTest class files
*/
/**#@+
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/scorer.php');
/**#@-*/
/**#@-*/
/**
* Sample minimal test displayer. Generates only
* failure messages and a pass count.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Sample minimal test displayer. Generates only
* failure messages and a pass count.
* @package SimpleTest
* @subpackage UnitTester
*/
class HtmlReporter extends SimpleReporter {
var $_character_set;
/**
* Does nothing yet. The first output will
* be sent on the first test start. For use
* by a web browser.
* @access public
*/
/**
* Does nothing yet. The first output will
* be sent on the first test start. For use
* by a web browser.
* @access public
*/
function HtmlReporter($character_set = 'ISO-8859-1') {
$this->SimpleReporter();
$this->_character_set = $character_set;
}
/**
* Paints the top of the web page setting the
* title to the name of the starting test.
* @param string $test_name Name class of test.
* @access public
*/
/**
* Paints the top of the web page setting the
* title to the name of the starting test.
* @param string $test_name Name class of test.
* @access public
*/
function paintHeader($test_name) {
$this->sendNoCacheHeaders();
print "<html>\n<head>\n<title>$test_name</title>\n";
@ -51,13 +51,13 @@
flush();
}
/**
* Send the headers necessary to ensure the page is
* reloaded on every request. Otherwise you could be
* scratching your head over out of date test data.
* @access public
* @static
*/
/**
* Send the headers necessary to ensure the page is
* reloaded on every request. Otherwise you could be
* scratching your head over out of date test data.
* @access public
* @static
*/
function sendNoCacheHeaders() {
if (! headers_sent()) {
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
@ -68,21 +68,21 @@
}
}
/**
* Paints the CSS. Add additional styles here.
* @return string CSS code as text.
* @access protected
*/
/**
* Paints the CSS. Add additional styles here.
* @return string CSS code as text.
* @access protected
*/
function _getCss() {
return ".fail { color: red; } pre { background-color: lightgray; }";
}
/**
* Paints the end of the test with a summary of
* the passes and failures.
* @param string $test_name Name class of test.
* @access public
*/
/**
* Paints the end of the test with a summary of
* the passes and failures.
* @param string $test_name Name class of test.
* @access public
*/
function paintFooter($test_name) {
$colour = ($this->getFailCount() + $this->getExceptionCount() > 0 ? "red" : "green");
print "<div style=\"";
@ -97,14 +97,14 @@
print "</body>\n</html>\n";
}
/**
* Paints the test failure with a breadcrumbs
* trail of the nesting test suites below the
* top level test.
* @param string $message Failure message displayed in
* the context of the other tests.
* @access public
*/
/**
* Paints the test failure with a breadcrumbs
* trail of the nesting test suites below the
* top level test.
* @param string $message Failure message displayed in
* the context of the other tests.
* @access public
*/
function paintFail($message) {
parent::paintFail($message);
print "<span class=\"fail\">Fail</span>: ";
@ -114,12 +114,12 @@
print " -&gt; " . $this->_htmlEntities($message) . "<br />\n";
}
/**
* Paints a PHP error or exception.
* @param string $message Message is ignored.
* @access public
* @abstract
*/
/**
* Paints a PHP error or exception.
* @param string $message Message is ignored.
* @access public
* @abstract
*/
function paintException($message) {
parent::paintException($message);
print "<span class=\"fail\">Exception</span>: ";
@ -129,51 +129,51 @@
print " -&gt; <strong>" . $this->_htmlEntities($message) . "</strong><br />\n";
}
/**
* Paints formatted text such as dumped variables.
* @param string $message Text to show.
* @access public
*/
/**
* Paints formatted text such as dumped variables.
* @param string $message Text to show.
* @access public
*/
function paintFormattedMessage($message) {
print '<pre>' . $this->_htmlEntities($message) . '</pre>';
}
/**
* Character set adjusted entity conversion.
* @param string $message Plain text or Unicode message.
* @return string Browser readable message.
* @access protected
*/
/**
* Character set adjusted entity conversion.
* @param string $message Plain text or Unicode message.
* @return string Browser readable message.
* @access protected
*/
function _htmlEntities($message) {
return htmlentities($message, ENT_COMPAT, $this->_character_set);
}
}
/**
* Sample minimal test displayer. Generates only
* failure messages and a pass count. For command
* line use. I've tried to make it look like JUnit,
* but I wanted to output the errors as they arrived
* which meant dropping the dots.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Sample minimal test displayer. Generates only
* failure messages and a pass count. For command
* line use. I've tried to make it look like JUnit,
* but I wanted to output the errors as they arrived
* which meant dropping the dots.
* @package SimpleTest
* @subpackage UnitTester
*/
class TextReporter extends SimpleReporter {
/**
* Does nothing yet. The first output will
* be sent on the first test start.
* @access public
*/
/**
* Does nothing yet. The first output will
* be sent on the first test start.
* @access public
*/
function TextReporter() {
$this->SimpleReporter();
}
/**
* Paints the title only.
* @param string $test_name Name class of test.
* @access public
*/
/**
* Paints the title only.
* @param string $test_name Name class of test.
* @access public
*/
function paintHeader($test_name) {
if (! SimpleReporter::inCli()) {
header('Content-type: text/plain');
@ -182,12 +182,12 @@
flush();
}
/**
* Paints the end of the test with a summary of
* the passes and failures.
* @param string $test_name Name class of test.
* @access public
*/
/**
* Paints the end of the test with a summary of
* the passes and failures.
* @param string $test_name Name class of test.
* @access public
*/
function paintFooter($test_name) {
if ($this->getFailCount() + $this->getExceptionCount() == 0) {
print "OK\n";
@ -202,12 +202,12 @@
}
/**
* Paints the test failure as a stack trace.
* @param string $message Failure message displayed in
* the context of the other tests.
* @access public
*/
/**
* Paints the test failure as a stack trace.
* @param string $message Failure message displayed in
* the context of the other tests.
* @access public
*/
function paintFail($message) {
parent::paintFail($message);
print $this->getFailCount() . ") $message\n";
@ -217,22 +217,22 @@
print "\n";
}
/**
* Paints a PHP error or exception.
* @param string $message Message is ignored.
* @access public
* @abstract
*/
/**
* Paints a PHP error or exception.
* @param string $message Message is ignored.
* @access public
* @abstract
*/
function paintException($message) {
parent::paintException($message);
print "Exception " . $this->getExceptionCount() . "!\n$message\n";
}
/**
* Paints formatted text such as dumped variables.
* @param string $message Text to show.
* @access public
*/
/**
* Paints formatted text such as dumped variables.
* @param string $message Text to show.
* @access public
*/
function paintFormattedMessage($message) {
print "$message\n";
flush();

View file

@ -1,15 +1,15 @@
<?php
/**
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**#@+
* Includes SimpleTest files and defined the root constant
* for dependent libraries.
*/
/**#@+
* Includes SimpleTest files and defined the root constant
* for dependent libraries.
*/
require_once(dirname(__FILE__) . '/errors.php');
require_once(dirname(__FILE__) . '/options.php');
require_once(dirname(__FILE__) . '/scorer.php');
@ -18,41 +18,41 @@
if (! defined('SIMPLE_TEST')) {
define('SIMPLE_TEST', dirname(__FILE__) . '/');
}
/**#@-*/
/**#@-*/
/**
* This is called by the class runner to run a
* single test method. Will also run the setUp()
* and tearDown() methods.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* This is called by the class runner to run a
* single test method. Will also run the setUp()
* and tearDown() methods.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleInvoker {
var $_test_case;
/**
* Stashes the test case for later.
* @param SimpleTestCase $test_case Test case to run.
*/
/**
* Stashes the test case for later.
* @param SimpleTestCase $test_case Test case to run.
*/
function SimpleInvoker(&$test_case) {
$this->_test_case = &$test_case;
}
/**
* Accessor for test case being run.
* @return SimpleTestCase Test case.
* @access public
*/
/**
* Accessor for test case being run.
* @return SimpleTestCase Test case.
* @access public
*/
function &getTestCase() {
return $this->_test_case;
}
/**
* Invokes a test method and buffered with setUp()
* and tearDown() calls.
* @param string $method Test method to call.
* @access public
*/
/**
* Invokes a test method and buffered with setUp()
* and tearDown() calls.
* @param string $method Test method to call.
* @access public
*/
function invoke($method) {
$this->_test_case->setUp();
$this->_test_case->$method();
@ -60,66 +60,66 @@
}
}
/**
* Do nothing decorator. Just passes the invocation
* straight through.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Do nothing decorator. Just passes the invocation
* straight through.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleInvokerDecorator {
var $_invoker;
/**
* Stores the invoker to wrap.
* @param SimpleInvoker $invoker Test method runner.
*/
/**
* Stores the invoker to wrap.
* @param SimpleInvoker $invoker Test method runner.
*/
function SimpleInvokerDecorator(&$invoker) {
$this->_invoker = &$invoker;
}
/**
* Accessor for test case being run.
* @return SimpleTestCase Test case.
* @access public
*/
/**
* Accessor for test case being run.
* @return SimpleTestCase Test case.
* @access public
*/
function &getTestCase() {
return $this->_invoker->getTestCase();
}
/**
* Invokes a test method and buffered with setUp()
* and tearDown() calls.
* @param string $method Test method to call.
* @access public
*/
/**
* Invokes a test method and buffered with setUp()
* and tearDown() calls.
* @param string $method Test method to call.
* @access public
*/
function invoke($method) {
$this->_invoker->invoke($method);
}
}
/**
* Extension that traps errors into an error queue.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Extension that traps errors into an error queue.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleErrorTrappingInvoker extends SimpleInvokerDecorator {
/**
/**
* Stores the invoker to wrap.
* @param SimpleInvoker $invoker Test method runner.
*/
/**
/**
* Stores the invoker to wrap.
* @param SimpleInvoker $invoker Test method runner.
*/
function SimpleErrorTrappingInvoker(&$invoker) {
$this->SimpleInvokerDecorator($invoker);
}
/**
* Invokes a test method and dispatches any
* untrapped errors. Called back from
* the visiting runner.
* @param string $method Test method to call.
* @access public
*/
/**
* Invokes a test method and dispatches any
* untrapped errors. Called back from
* the visiting runner.
* @param string $method Test method to call.
* @access public
*/
function invoke($method) {
set_error_handler('simpleTestErrorHandler');
parent::invoke($method);
@ -132,42 +132,42 @@
}
}
/**
* The standard runner. Will run every method starting
* with test Basically the
* Mediator pattern.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* The standard runner. Will run every method starting
* with test Basically the
* Mediator pattern.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleRunner {
var $_test_case;
var $_scorer;
/**
* Takes in the test case and reporter to mediate between.
* @param SimpleTestCase $test_case Test case to run.
* @param SimpleScorer $scorer Reporter to receive events.
*/
/**
* Takes in the test case and reporter to mediate between.
* @param SimpleTestCase $test_case Test case to run.
* @param SimpleScorer $scorer Reporter to receive events.
*/
function SimpleRunner(&$test_case, &$scorer) {
$this->_test_case = &$test_case;
$this->_scorer = &$scorer;
}
/**
* Accessor for test case being run.
* @return SimpleTestCase Test case.
* @access public
*/
/**
* Accessor for test case being run.
* @return SimpleTestCase Test case.
* @access public
*/
function &getTestCase() {
return $this->_test_case;
}
/**
* Runs the test methods in the test case.
* @param SimpleTest $test_case Test case to run test on.
* @param string $method Name of test method.
* @access public
*/
/**
* Runs the test methods in the test case.
* @param SimpleTest $test_case Test case to run test on.
* @param string $method Name of test method.
* @access public
*/
function run() {
$methods = get_class_methods(get_class($this->_test_case));
$invoker = &$this->_test_case->createInvoker();
@ -186,113 +186,113 @@
}
}
/**
* Tests to see if the method is the constructor and
* so should be ignored.
* @param string $method Method name to try.
* @return boolean True if constructor.
* @access protected
*/
/**
* Tests to see if the method is the constructor and
* so should be ignored.
* @param string $method Method name to try.
* @return boolean True if constructor.
* @access protected
*/
function _isConstructor($method) {
return SimpleTestCompatibility::isA(
$this->_test_case,
strtolower($method));
}
/**
* Tests to see if the method is a test that should
* be run. Currently any method that starts with 'test'
* is a candidate.
* @param string $method Method name to try.
* @return boolean True if test method.
* @access protected
*/
/**
* Tests to see if the method is a test that should
* be run. Currently any method that starts with 'test'
* is a candidate.
* @param string $method Method name to try.
* @return boolean True if test method.
* @access protected
*/
function _isTest($method) {
return strtolower(substr($method, 0, 4)) == 'test';
}
/**
* Paints the start of a test method.
* @param string $test_name Name of test or other label.
* @access public
*/
/**
* Paints the start of a test method.
* @param string $test_name Name of test or other label.
* @access public
*/
function paintMethodStart($test_name) {
$this->_scorer->paintMethodStart($test_name);
}
/**
* Paints the end of a test method.
* @param string $test_name Name of test or other label.
* @access public
*/
/**
* Paints the end of a test method.
* @param string $test_name Name of test or other label.
* @access public
*/
function paintMethodEnd($test_name) {
$this->_scorer->paintMethodEnd($test_name);
}
/**
* Chains to the wrapped reporter.
* @param string $message Message is ignored.
* @access public
*/
/**
* Chains to the wrapped reporter.
* @param string $message Message is ignored.
* @access public
*/
function paintPass($message) {
$this->_scorer->paintPass($message);
}
/**
* Chains to the wrapped reporter.
* @param string $message Message is ignored.
* @access public
*/
/**
* Chains to the wrapped reporter.
* @param string $message Message is ignored.
* @access public
*/
function paintFail($message) {
$this->_scorer->paintFail($message);
}
/**
* Chains to the wrapped reporter.
* @param string $message Text of error formatted by
* the test case.
* @access public
*/
/**
* Chains to the wrapped reporter.
* @param string $message Text of error formatted by
* the test case.
* @access public
*/
function paintError($message) {
$this->_scorer->paintError($message);
}
/**
* Chains to the wrapped reporter.
* @param Exception $exception Object thrown.
* @access public
*/
/**
* Chains to the wrapped reporter.
* @param Exception $exception Object thrown.
* @access public
*/
function paintException($exception) {
$this->_scorer->paintException($exception);
}
/**
* Chains to the wrapped reporter.
* @param string $message Text to display.
* @access public
*/
/**
* Chains to the wrapped reporter.
* @param string $message Text to display.
* @access public
*/
function paintMessage($message) {
$this->_scorer->paintMessage($message);
}
/**
* Chains to the wrapped reporter.
* @param string $message Text to display.
* @access public
*/
/**
* Chains to the wrapped reporter.
* @param string $message Text to display.
* @access public
*/
function paintFormattedMessage($message) {
$this->_scorer->paintFormattedMessage($message);
}
/**
* Chains to the wrapped reporter.
* @param string $type Event type as text.
* @param mixed $payload Message or object.
* @return boolean Should return false if this
* type of signal should fail the
* test suite.
* @access public
*/
/**
* Chains to the wrapped reporter.
* @param string $type Event type as text.
* @param mixed $payload Message or object.
* @return boolean Should return false if this
* type of signal should fail the
* test suite.
* @access public
*/
function paintSignal($type, &$payload) {
$this->_scorer->paintSignal($type, $payload);
}

View file

@ -1,29 +1,29 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**
* Can recieve test events and display them. Display
* is achieved by making display methods available
* and visiting the incoming event.
* @package SimpleTest
* @subpackage UnitTester
* @abstract
*/
/**
* Can recieve test events and display them. Display
* is achieved by making display methods available
* and visiting the incoming event.
* @package SimpleTest
* @subpackage UnitTester
* @abstract
*/
class SimpleScorer {
var $_passes;
var $_fails;
var $_exceptions;
var $_is_dry_run;
/**
* Starts the test run with no results.
* @access public
*/
/**
* Starts the test run with no results.
* @access public
*/
function SimpleScorer() {
$this->_passes = 0;
$this->_fails = 0;
@ -31,32 +31,32 @@
$this->_is_dry_run = false;
}
/**
* Signals that the next evaluation will be a dry
* run. That is, the structure events will be
* recorded, but no tests will be run.
*/
/**
* Signals that the next evaluation will be a dry
* run. That is, the structure events will be
* recorded, but no tests will be run.
*/
function makeDry($is_dry = true) {
$this->_is_dry_run = $is_dry;
}
/**
* The reporter has a veto on what should be run.
* @param string $test_case_name name of test case.
* @param string $method Name of test method.
* @access public
*/
/**
* The reporter has a veto on what should be run.
* @param string $test_case_name name of test case.
* @param string $method Name of test method.
* @access public
*/
function shouldInvoke($test_case_name, $method) {
return ! $this->_is_dry_run;
}
/**
* Accessor for current status. Will be false
* if there have been any failures or exceptions.
* Used for command line tools.
* @return boolean True if no failures.
* @access public
*/
/**
* Accessor for current status. Will be false
* if there have been any failures or exceptions.
* Used for command line tools.
* @return boolean True if no failures.
* @access public
*/
function getStatus() {
if ($this->_exceptions + $this->_fails > 0) {
return false;
@ -64,165 +64,165 @@
return true;
}
/**
* Paints the start of a test method.
* @param string $test_name Name of test or other label.
* @access public
*/
/**
* Paints the start of a test method.
* @param string $test_name Name of test or other label.
* @access public
*/
function paintMethodStart($test_name) {
}
/**
* Paints the end of a test method.
* @param string $test_name Name of test or other label.
* @access public
*/
/**
* Paints the end of a test method.
* @param string $test_name Name of test or other label.
* @access public
*/
function paintMethodEnd($test_name) {
}
/**
* Paints the start of a test case.
* @param string $test_name Name of test or other label.
* @access public
*/
/**
* Paints the start of a test case.
* @param string $test_name Name of test or other label.
* @access public
*/
function paintCaseStart($test_name) {
}
/**
* Paints the end of a test case.
* @param string $test_name Name of test or other label.
* @access public
*/
/**
* Paints the end of a test case.
* @param string $test_name Name of test or other label.
* @access public
*/
function paintCaseEnd($test_name) {
}
/**
* Paints the start of a group test.
* @param string $test_name Name of test or other label.
* @param integer $size Number of test cases starting.
* @access public
*/
/**
* Paints the start of a group test.
* @param string $test_name Name of test or other label.
* @param integer $size Number of test cases starting.
* @access public
*/
function paintGroupStart($test_name, $size) {
}
/**
* Paints the end of a group test.
* @param string $test_name Name of test or other label.
* @access public
*/
/**
* Paints the end of a group test.
* @param string $test_name Name of test or other label.
* @access public
*/
function paintGroupEnd($test_name) {
}
/**
* Increments the pass count.
* @param string $message Message is ignored.
* @access public
*/
/**
* Increments the pass count.
* @param string $message Message is ignored.
* @access public
*/
function paintPass($message) {
$this->_passes++;
}
/**
* Increments the fail count.
* @param string $message Message is ignored.
* @access public
*/
/**
* Increments the fail count.
* @param string $message Message is ignored.
* @access public
*/
function paintFail($message) {
$this->_fails++;
}
/**
* Deals with PHP 4 throwing an error.
* @param string $message Text of error formatted by
* the test case.
* @access public
*/
/**
* Deals with PHP 4 throwing an error.
* @param string $message Text of error formatted by
* the test case.
* @access public
*/
function paintError($message) {
$this->paintException($message);
}
/**
* Deals with PHP 5 throwing an exception
* This isn't really implemented yet.
* @param Exception $exception Object thrown.
* @access public
*/
/**
* Deals with PHP 5 throwing an exception
* This isn't really implemented yet.
* @param Exception $exception Object thrown.
* @access public
*/
function paintException($exception) {
$this->_exceptions++;
}
/**
* Accessor for the number of passes so far.
* @return integer Number of passes.
* @access public
*/
/**
* Accessor for the number of passes so far.
* @return integer Number of passes.
* @access public
*/
function getPassCount() {
return $this->_passes;
}
/**
* Accessor for the number of fails so far.
* @return integer Number of fails.
* @access public
*/
/**
* Accessor for the number of fails so far.
* @return integer Number of fails.
* @access public
*/
function getFailCount() {
return $this->_fails;
}
/**
* Accessor for the number of untrapped errors
* so far.
* @return integer Number of exceptions.
* @access public
*/
/**
* Accessor for the number of untrapped errors
* so far.
* @return integer Number of exceptions.
* @access public
*/
function getExceptionCount() {
return $this->_exceptions;
}
/**
* Paints a simple supplementary message.
* @param string $message Text to display.
* @access public
*/
/**
* Paints a simple supplementary message.
* @param string $message Text to display.
* @access public
*/
function paintMessage($message) {
}
/**
* Paints a formatted ASCII message such as a
* variable dump.
* @param string $message Text to display.
* @access public
*/
/**
* Paints a formatted ASCII message such as a
* variable dump.
* @param string $message Text to display.
* @access public
*/
function paintFormattedMessage($message) {
}
/**
* By default just ignores user generated events.
* @param string $type Event type as text.
* @param mixed $payload Message or object.
* @access public
*/
function paintSignal($type, &$payload) {
/**
* By default just ignores user generated events.
* @param string $type Event type as text.
* @param mixed $payload Message or object.
* @access public
*/
function paintSignal($type, $payload) {
}
}
/**
* Recipient of generated test messages that can display
* page footers and headers. Also keeps track of the
* test nesting. This is the main base class on which
* to build the finished test (page based) displays.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Recipient of generated test messages that can display
* page footers and headers. Also keeps track of the
* test nesting. This is the main base class on which
* to build the finished test (page based) displays.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleReporter extends SimpleScorer {
var $_test_stack;
var $_size;
var $_progress;
/**
* Starts the display with no results in.
* @access public
*/
/**
* Starts the display with no results in.
* @access public
*/
function SimpleReporter() {
$this->SimpleScorer();
$this->_test_stack = array();
@ -230,15 +230,15 @@
$this->_progress = 0;
}
/**
* Paints the start of a group test. Will also paint
* the page header and footer if this is the
* first test. Will stash the size if the first
* start.
* @param string $test_name Name of test that is starting.
* @param integer $size Number of test cases starting.
* @access public
*/
/**
* Paints the start of a group test. Will also paint
* the page header and footer if this is the
* first test. Will stash the size if the first
* start.
* @param string $test_name Name of test that is starting.
* @param integer $size Number of test cases starting.
* @access public
*/
function paintGroupStart($test_name, $size) {
if (! isset($this->_size)) {
$this->_size = $size;
@ -249,13 +249,13 @@
$this->_test_stack[] = $test_name;
}
/**
* Paints the end of a group test. Will paint the page
* footer if the stack of tests has unwound.
* @param string $test_name Name of test that is ending.
* @param integer $progress Number of test cases ending.
* @access public
*/
/**
* Paints the end of a group test. Will paint the page
* footer if the stack of tests has unwound.
* @param string $test_name Name of test that is ending.
* @param integer $progress Number of test cases ending.
* @access public
*/
function paintGroupEnd($test_name) {
array_pop($this->_test_stack);
if (count($this->_test_stack) == 0) {
@ -263,14 +263,14 @@
}
}
/**
* Paints the start of a test case. Will also paint
* the page header and footer if this is the
* first test. Will stash the size if the first
* start.
* @param string $test_name Name of test that is starting.
* @access public
*/
/**
* Paints the start of a test case. Will also paint
* the page header and footer if this is the
* first test. Will stash the size if the first
* start.
* @param string $test_name Name of test that is starting.
* @access public
*/
function paintCaseStart($test_name) {
if (! isset($this->_size)) {
$this->_size = 1;
@ -281,12 +281,12 @@
$this->_test_stack[] = $test_name;
}
/**
* Paints the end of a test case. Will paint the page
* footer if the stack of tests has unwound.
* @param string $test_name Name of test that is ending.
* @access public
*/
/**
* Paints the end of a test case. Will paint the page
* footer if the stack of tests has unwound.
* @param string $test_name Name of test that is ending.
* @access public
*/
function paintCaseEnd($test_name) {
$this->_progress++;
array_pop($this->_test_stack);
@ -295,86 +295,84 @@
}
}
/**
* Paints the start of a test method.
* @param string $test_name Name of test that is starting.
* @access public
*/
/**
* Paints the start of a test method.
* @param string $test_name Name of test that is starting.
* @access public
*/
function paintMethodStart($test_name) {
$this->_test_stack[] = $test_name;
}
/**
* Paints the end of a test method. Will paint the page
* footer if the stack of tests has unwound.
* @param string $test_name Name of test that is ending.
* @access public
*/
/**
* Paints the end of a test method. Will paint the page
* footer if the stack of tests has unwound.
* @param string $test_name Name of test that is ending.
* @access public
*/
function paintMethodEnd($test_name) {
array_pop($this->_test_stack);
}
/**
* Paints the test document header.
* @param string $test_name First test top level
* to start.
* @access public
* @abstract
*/
/**
* Paints the test document header.
* @param string $test_name First test top level
* to start.
* @access public
* @abstract
*/
function paintHeader($test_name) {
}
/**
* Paints the test document footer.
* @param string $test_name The top level test.
* @access public
* @abstract
*/
/**
* Paints the test document footer.
* @param string $test_name The top level test.
* @access public
* @abstract
*/
function paintFooter($test_name) {
}
/**
* Accessor for internal test stack. For
* subclasses that need to see the whole test
* history for display purposes.
* @return array List of methods in nesting order.
* @access public
*/
/**
* Accessor for internal test stack. For
* subclasses that need to see the whole test
* history for display purposes.
* @return array List of methods in nesting order.
* @access public
*/
function getTestList() {
return $this->_test_stack;
}
/**
* Accessor for total test size in number
* of test cases. Null until the first
* test is started.
* @return integer Total number of cases at start.
* @access public
*/
/**
* Accessor for total test size in number
* of test cases. Null until the first
* test is started.
* @return integer Total number of cases at start.
* @access public
*/
function getTestCaseCount() {
return $this->_size;
}
/**
* Accessor for the number of test cases
* completed so far.
* @return integer Number of ended cases.
* @access public
*/
/**
* Accessor for the number of test cases
* completed so far.
* @return integer Number of ended cases.
* @access public
*/
function getTestCaseProgress() {
return $this->_progress;
}
/**
* Static check for running in the comand line.
* @return boolean True if CLI.
* @access public
* @static
*/
/**
* Static check for running in the comand line.
* @return boolean True if CLI.
* @access public
* @static
*/
function inCli() {
$method = getenv('REQUEST_METHOD');
return empty($method);
// return php_sapi_name() == 'cli';
return php_sapi_name() == 'cli';
}
}
?>

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

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

View file

@ -1,85 +1,85 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**#@+
* include other SimpleTest class files
*/
/**#@+
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/simple_test.php');
/**#@-*/
/**#@-*/
/**
* Wrapper for exec() functionality.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Wrapper for exec() functionality.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleShell {
var $_output;
/**
* Executes the shell comand and stashes the output.
* @access public
*/
/**
* Executes the shell comand and stashes the output.
* @access public
*/
function SimpleShell() {
$this->_output = false;
}
/**
* Actually runs the command. Does not trap the
* error stream output as this need PHP 4.3+.
* @param string $command The actual command line
* to run.
* @return integer Exit code.
* @access public
*/
/**
* Actually runs the command. Does not trap the
* error stream output as this need PHP 4.3+.
* @param string $command The actual command line
* to run.
* @return integer Exit code.
* @access public
*/
function execute($command) {
$this->_output = false;
exec($command, $this->_output, $ret);
return $ret;
}
/**
* Accessor for the last output.
* @return string Output as text.
* @access public
*/
/**
* Accessor for the last output.
* @return string Output as text.
* @access public
*/
function getOutput() {
return implode("\n", $this->_output);
}
/**
* Accessor for the last output.
* @return array Output as array of lines.
* @access public
*/
function getOutputAsList() {
return $this->_output;
}
/**
* Accessor for the last output.
* @return array Output as array of lines.
* @access public
*/
function getOutputAsList() {
return $this->_output;
}
}
/**
* Test case for testing of command line scripts and
* utilities. Usually scripts taht are external to the
* PHP code, but support it in some way.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Test case for testing of command line scripts and
* utilities. Usually scripts taht are external to the
* PHP code, but support it in some way.
* @package SimpleTest
* @subpackage UnitTester
*/
class ShellTestCase extends SimpleTestCase {
var $_current_shell;
var $_last_status;
var $_last_command;
/**
* Creates an empty test case. Should be subclassed
* with test methods for a functional test case.
* @param string $label Name of test case. Will use
* the class name if none specified.
* @access public
*/
/**
* Creates an empty test case. Should be subclassed
* with test methods for a functional test case.
* @param string $label Name of test case. Will use
* the class name if none specified.
* @access public
*/
function ShellTestCase($label = false) {
$this->SimpleTestCase($label);
$this->_current_shell = &$this->_createShell();
@ -87,12 +87,12 @@
$this->_last_command = '';
}
/**
* Executes a command and buffers the results.
* @param string $command Command to run.
* @return boolean True if zero exit code.
* @access public
*/
/**
* Executes a command and buffers the results.
* @param string $command Command to run.
* @return boolean True if zero exit code.
* @access public
*/
function execute($command) {
$shell = &$this->_getShell();
$this->_last_status = $shell->execute($command);
@ -100,42 +100,76 @@
return ($this->_last_status === 0);
}
/**
* Dumps the output of the last command.
* @access public
*/
/**
* Dumps the output of the last command.
* @access public
*/
function dumpOutput() {
$this->dump($this->getOutput());
}
/**
* Accessor for the last output.
* @return string Output as text.
* @access public
*/
function getOutput() {
/**
* Accessor for the last output.
* @return string Output as text.
* @access public
*/
function getOutput() {
$shell = &$this->_getShell();
return $shell->getOutput();
}
}
/**
* Accessor for the last output.
* @return array Output as array of lines.
* @access public
*/
function getOutputAsList() {
/**
* Accessor for the last output.
* @return array Output as array of lines.
* @access public
*/
function getOutputAsList() {
$shell = &$this->_getShell();
return $shell->getOutputAsList();
}
}
/**
* Will trigger a pass if the two parameters have
* the same value only. Otherwise a fail. This
* is for testing hand extracted text, etc.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertEqual($first, $second, $message = "%s") {
return $this->assert(
new EqualExpectation($first),
$second,
$message);
}
/**
* Will trigger a pass if the two parameters have
* a different value. Otherwise a fail. This
* is for testing hand extracted text, etc.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertNotEqual($first, $second, $message = "%s") {
return $this->assert(
new NotEqualExpectation($first),
$second,
$message);
}
/**
* Tests the last status code from the shell.
* @param integer $status Expected status of last
* command.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
/**
* Tests the last status code from the shell.
* @param integer $status Expected status of last
* command.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertExitCode($status, $message = "%s") {
$message = sprintf($message, "Expected status code of [$status] from [" .
$this->_last_command . "], but got [" .
@ -143,129 +177,130 @@
return $this->assertTrue($status === $this->_last_status, $message);
}
/**
* Attempt to exactly match the combined STDERR and
* STDOUT output.
* @param string $expected Expected output.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
/**
* Attempt to exactly match the combined STDERR and
* STDOUT output.
* @param string $expected Expected output.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertOutput($expected, $message = "%s") {
$shell = &$this->_getShell();
return $this->assertExpectation(
return $this->assert(
new EqualExpectation($expected),
$shell->getOutput(),
$message);
}
/**
* Scans the output for a Perl regex. If found
* anywhere it passes, else it fails.
* @param string $pattern Regex to search for.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
/**
* Scans the output for a Perl regex. If found
* anywhere it passes, else it fails.
* @param string $pattern Regex to search for.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertOutputPattern($pattern, $message = "%s") {
$shell = &$this->_getShell();
return $this->assertExpectation(
new WantedPatternExpectation($pattern),
return $this->assert(
new PatternExpectation($pattern),
$shell->getOutput(),
$message);
}
/**
* If a Perl regex is found anywhere in the current
* output then a failure is generated, else a pass.
* @param string $pattern Regex to search for.
* @param $message Message to display.
* @return boolean True if pass.
* @access public
*/
/**
* If a Perl regex is found anywhere in the current
* output then a failure is generated, else a pass.
* @param string $pattern Regex to search for.
* @param $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertNoOutputPattern($pattern, $message = "%s") {
$shell = &$this->_getShell();
return $this->assertExpectation(
new UnwantedPatternExpectation($pattern),
return $this->assert(
new NoPatternExpectation($pattern),
$shell->getOutput(),
$message);
}
/**
* File existence check.
* @param string $path Full filename and path.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
/**
* File existence check.
* @param string $path Full filename and path.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertFileExists($path, $message = "%s") {
$message = sprintf($message, "File [$path] should exist");
return $this->assertTrue(file_exists($path), $message);
}
/**
* File non-existence check.
* @param string $path Full filename and path.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
/**
* File non-existence check.
* @param string $path Full filename and path.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertFileNotExists($path, $message = "%s") {
$message = sprintf($message, "File [$path] should not exist");
return $this->assertFalse(file_exists($path), $message);
}
/**
* Scans a file for a Perl regex. If found
* anywhere it passes, else it fails.
* @param string $pattern Regex to search for.
* @param string $path Full filename and path.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
/**
* Scans a file for a Perl regex. If found
* anywhere it passes, else it fails.
* @param string $pattern Regex to search for.
* @param string $path Full filename and path.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertFilePattern($pattern, $path, $message = "%s") {
$shell = &$this->_getShell();
return $this->assertExpectation(
new WantedPatternExpectation($pattern),
return $this->assert(
new PatternExpectation($pattern),
implode('', file($path)),
$message);
}
/**
* If a Perl regex is found anywhere in the named
* file then a failure is generated, else a pass.
* @param string $pattern Regex to search for.
* @param string $path Full filename and path.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
/**
* If a Perl regex is found anywhere in the named
* file then a failure is generated, else a pass.
* @param string $pattern Regex to search for.
* @param string $path Full filename and path.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertNoFilePattern($pattern, $path, $message = "%s") {
$shell = &$this->_getShell();
return $this->assertExpectation(
new UnwantedPatternExpectation($pattern),
return $this->assert(
new NoPatternExpectation($pattern),
implode('', file($path)),
$message);
}
/**
* Accessor for current shell. Used for testing the
* the tester itself.
* @return Shell Current shell.
* @access protected
*/
/**
* Accessor for current shell. Used for testing the
* the tester itself.
* @return Shell Current shell.
* @access protected
*/
function &_getShell() {
return $this->_current_shell;
}
/**
* Factory for the shell to run the command on.
* @return Shell New shell object.
* @access protected
*/
/**
* Factory for the shell to run the command on.
* @return Shell New shell object.
* @access protected
*/
function &_createShell() {
return new SimpleShell();
$shell = &new SimpleShell();
return $shell;
}
}
?>

View file

@ -1,15 +1,15 @@
<?php
/**
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**#@+
* Includes SimpleTest files and defined the root constant
* for dependent libraries.
*/
/**#@+
* Includes SimpleTest files and defined the root constant
* for dependent libraries.
*/
require_once(dirname(__FILE__) . '/errors.php');
require_once(dirname(__FILE__) . '/options.php');
require_once(dirname(__FILE__) . '/runner.php');
@ -19,68 +19,71 @@
if (! defined('SIMPLE_TEST')) {
define('SIMPLE_TEST', dirname(__FILE__) . '/');
}
/**#@-*/
/**#@-*/
/**
* Basic test case. This is the smallest unit of a test
* suite. It searches for
* all methods that start with the the string "test" and
* runs them. Working test cases extend this class.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Basic test case. This is the smallest unit of a test
* suite. It searches for
* all methods that start with the the string "test" and
* runs them. Working test cases extend this class.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleTestCase {
var $_label;
var $_runner;
var $_label = false;
var $_runner = false;
/**
* Sets up the test with no display.
* @param string $label If no test name is given then
* the class name is used.
* @access public
*/
/**
* Sets up the test with no display.
* @param string $label If no test name is given then
* the class name is used.
* @access public
*/
function SimpleTestCase($label = false) {
$this->_label = $label ? $label : get_class($this);
$this->_runner = false;
if ($label) {
$this->_label = $label;
}
}
/**
* Accessor for the test name for subclasses.
* @return string Name of the test.
* @access public
*/
/**
* Accessor for the test name for subclasses.
* @return string Name of the test.
* @access public
*/
function getLabel() {
return $this->_label;
return $this->_label ? $this->_label : get_class($this);
}
/**
* Used to invoke the single tests.
* @return SimpleInvoker Individual test runner.
* @access public
*/
/**
* Used to invoke the single tests.
* @return SimpleInvoker Individual test runner.
* @access public
*/
function &createInvoker() {
return new SimpleErrorTrappingInvoker(new SimpleInvoker($this));
$invoker = &new SimpleErrorTrappingInvoker(new SimpleInvoker($this));
return $invoker;
}
/**
* Can modify the incoming reporter so as to run
* the tests differently. This version simply
* passes it straight through.
* @param SimpleReporter $reporter Incoming observer.
* @return SimpleReporter
* @access protected
*/
/**
* Can modify the incoming reporter so as to run
* the tests differently. This version simply
* passes it straight through.
* @param SimpleReporter $reporter Incoming observer.
* @return SimpleReporter
* @access protected
*/
function &_createRunner(&$reporter) {
return new SimpleRunner($this, $reporter);
$runner = &new SimpleRunner($this, $reporter);
return $runner;
}
/**
* Uses reflection to run every method within itself
* starting with the string "test" unless a method
* is specified.
* @param SimpleReporter $reporter Current test reporter.
* @access public
*/
/**
* Uses reflection to run every method within itself
* starting with the string "test" unless a method
* is specified.
* @param SimpleReporter $reporter Current test reporter.
* @access public
*/
function run(&$reporter) {
$reporter->paintCaseStart($this->getLabel());
$this->_runner = &$this->_createRunner($reporter);
@ -89,126 +92,133 @@
return $reporter->getStatus();
}
/**
* Sets up unit test wide variables at the start
* of each test method. To be overridden in
* actual user test cases.
* @access public
*/
/**
* Sets up unit test wide variables at the start
* of each test method. To be overridden in
* actual user test cases.
* @access public
*/
function setUp() {
}
/**
* Clears the data set in the setUp() method call.
* To be overridden by the user in actual user test cases.
* @access public
*/
/**
* Clears the data set in the setUp() method call.
* To be overridden by the user in actual user test cases.
* @access public
*/
function tearDown() {
}
/**
* Sends a pass event with a message.
* @param string $message Message to send.
* @access public
*/
/**
* Sends a pass event with a message.
* @param string $message Message to send.
* @access public
*/
function pass($message = "Pass") {
$this->_runner->paintPass($message . $this->getAssertionLine(' at line [%d]'));
return true;
}
/**
* Sends a fail event with a message.
* @param string $message Message to send.
* @access public
*/
/**
* Sends a fail event with a message.
* @param string $message Message to send.
* @access public
*/
function fail($message = "Fail") {
$this->_runner->paintFail($message . $this->getAssertionLine(' at line [%d]'));
return false;
}
/**
* Formats a PHP error and dispatches it to the
* runner.
* @param integer $severity PHP error code.
* @param string $message Text of error.
* @param string $file File error occoured in.
* @param integer $line Line number of error.
* @param hash $globals PHP super global arrays.
* @access public
*/
/**
* Formats a PHP error and dispatches it to the
* runner.
* @param integer $severity PHP error code.
* @param string $message Text of error.
* @param string $file File error occoured in.
* @param integer $line Line number of error.
* @param hash $globals PHP super global arrays.
* @access public
*/
function error($severity, $message, $file, $line, $globals) {
$severity = SimpleErrorQueue::getSeverityAsString($severity);
$this->_runner->paintError(
"Unexpected PHP error [$message] severity [$severity] in [$file] line [$line]");
}
/**
* Sends a user defined event to the test runner.
* This is for small scale extension where
* both the test case and either the runner or
* display are subclassed.
* @param string $type Type of event.
* @param mixed $payload Object or message to deliver.
* @access public
*/
/**
* Sends a user defined event to the test runner.
* This is for small scale extension where
* both the test case and either the runner or
* display are subclassed.
* @param string $type Type of event.
* @param mixed $payload Object or message to deliver.
* @access public
*/
function signal($type, &$payload) {
$this->_runner->paintSignal($type, $payload);
}
/**
* Cancels any outstanding errors.
* @access public
*/
/**
* Cancels any outstanding errors.
* @access public
*/
function swallowErrors() {
$queue = &SimpleErrorQueue::instance();
$queue->clear();
}
/**
* Runs an expectation directly, for extending the
* tests with new expectation classes.
* @param SimpleExpectation $expectation Expectation subclass.
* @param mixed $test_value Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertExpectation(&$expectation, $test_value, $message = '%s') {
/**
* Runs an expectation directly, for extending the
* tests with new expectation classes.
* @param SimpleExpectation $expectation Expectation subclass.
* @param mixed $compare Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assert(&$expectation, $compare, $message = '%s') {
return $this->assertTrue(
$expectation->test($test_value),
sprintf($message, $expectation->overlayMessage($test_value)));
$expectation->test($compare),
sprintf($message, $expectation->overlayMessage($compare)));
}
/**
* @deprecated
*/
function assertExpectation(&$expectation, $compare, $message = '%s') {
return $this->assert($expectation, $compare, $message);
}
/**
* Called from within the test methods to register
* passes and failures.
* @param boolean $result Pass on true.
* @param string $message Message to display describing
* the test state.
* @return boolean True on pass
* @access public
*/
/**
* Called from within the test methods to register
* passes and failures.
* @param boolean $result Pass on true.
* @param string $message Message to display describing
* the test state.
* @return boolean True on pass
* @access public
*/
function assertTrue($result, $message = false) {
if (! $message) {
$message = 'True assertion got ' . ($result ? 'True' : 'False');
}
if ($result) {
$this->pass($message);
return true;
return $this->pass($message);
} else {
$this->fail($message);
return false;
return $this->fail($message);
}
}
/**
* Will be true on false and vice versa. False
* is the PHP definition of false, so that null,
* empty strings, zero and an empty array all count
* as false.
* @param boolean $result Pass on false.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
/**
* Will be true on false and vice versa. False
* is the PHP definition of false, so that null,
* empty strings, zero and an empty array all count
* as false.
* @param boolean $result Pass on false.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertFalse($result, $message = false) {
if (! $message) {
$message = 'False assertion got ' . ($result ? 'True' : 'False');
@ -216,16 +226,16 @@
return $this->assertTrue(! $result, $message);
}
/**
* Uses a stack trace to find the line of an assertion.
* @param string $format String formatting.
* @param array $stack Stack frames top most first. Only
* needed if not using the PHP
* backtrace function.
* @return string Line number of first assert*
* method embedded in format string.
* @access public
*/
/**
* Uses a stack trace to find the line of an assertion.
* @param string $format String formatting.
* @param array $stack Stack frames top most first. Only
* needed if not using the PHP
* backtrace function.
* @return string Line number of first assert*
* method embedded in format string.
* @access public
*/
function getAssertionLine($format = '%d', $stack = false) {
if ($stack === false) {
$stack = SimpleTestCompatibility::getStackTrace();
@ -233,15 +243,15 @@
return SimpleDumper::getFormattedAssertionLine($stack, $format);
}
/**
* Sends a formatted dump of a variable to the
* test suite for those emergency debugging
* situations.
* @param mixed $variable Variable to display.
* @param string $message Message to display.
* @return mixed The original variable.
* @access public
*/
/**
* Sends a formatted dump of a variable to the
* test suite for those emergency debugging
* situations.
* @param mixed $variable Variable to display.
* @param string $message Message to display.
* @return mixed The original variable.
* @access public
*/
function dump($variable, $message = false) {
$formatted = SimpleDumper::dump($variable);
if ($message) {
@ -251,94 +261,98 @@
return $variable;
}
/**
* Dispatches a text message straight to the
* test suite. Useful for status bar displays.
* @param string $message Message to show.
* @access public
*/
/**
* Dispatches a text message straight to the
* test suite. Useful for status bar displays.
* @param string $message Message to show.
* @access public
*/
function sendMessage($message) {
$this->_runner->PaintMessage($message);
}
/**
* Accessor for the number of subtests.
* @return integer Number of test cases.
* @access public
* @static
*/
/**
* Accessor for the number of subtests.
* @return integer Number of test cases.
* @access public
* @static
*/
function getSize() {
return 1;
}
}
/**
* This is a composite test class for combining
* test cases and other RunnableTest classes into
* a group test.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* This is a composite test class for combining
* test cases and other RunnableTest classes into
* a group test.
* @package SimpleTest
* @subpackage UnitTester
*/
class GroupTest {
var $_label;
var $_test_cases;
var $_old_track_errors;
var $_xdebug_is_enabled;
/**
* Sets the name of the test suite.
* @param string $label Name sent at the start and end
* of the test.
* @access public
*/
function GroupTest($label) {
$this->_label = $label;
/**
* Sets the name of the test suite.
* @param string $label Name sent at the start and end
* of the test.
* @access public
*/
function GroupTest($label = false) {
$this->_label = $label ? $label : get_class($this);
$this->_test_cases = array();
$this->_old_track_errors = ini_get('track_errors');
$this->_xdebug_is_enabled = function_exists('xdebug_is_enabled') ?
xdebug_is_enabled() : false;
}
/**
* Accessor for the test name for subclasses.
* @return string Name of the test.
* @access public
*/
/**
* Accessor for the test name for subclasses.
* @return string Name of the test.
* @access public
*/
function getLabel() {
return $this->_label;
}
/**
* Adds a test into the suite. Can be either a group
* test or some other unit test.
* @param SimpleTestCase $test_case Suite or individual test
* case implementing the
* runnable test interface.
* @access public
*/
/**
* Adds a test into the suite. Can be either a group
* test or some other unit test.
* @param SimpleTestCase $test_case Suite or individual test
* case implementing the
* runnable test interface.
* @access public
*/
function addTestCase(&$test_case) {
$this->_test_cases[] = &$test_case;
}
/**
* Adds a test into the suite by class name. The class will
* be instantiated as needed.
* @param SimpleTestCase $test_case Suite or individual test
* case implementing the
* runnable test interface.
* @access public
*/
/**
* Adds a test into the suite by class name. The class will
* be instantiated as needed.
* @param SimpleTestCase $test_case Suite or individual test
* case implementing the
* runnable test interface.
* @access public
*/
function addTestClass($class) {
$this->_test_cases[] = $class;
if ($this->_getBaseTestCase($class) == 'grouptest') {
$this->_test_cases[] = &new $class();
} else {
$this->_test_cases[] = $class;
}
}
/**
* Builds a group test from a library of test cases.
* The new group is composed into this one.
* @param string $test_file File name of library with
* test case classes.
* @access public
*/
/**
* Builds a group test from a library of test cases.
* The new group is composed into this one.
* @param string $test_file File name of library with
* test case classes.
* @access public
*/
function addTestFile($test_file) {
$existing_classes = get_declared_classes();
if ($error = $this->_requireWithError($test_file)) {
@ -353,34 +367,34 @@
$this->addTestCase($this->_createGroupFromClasses($test_file, $classes));
}
/**
* Requires a source file recording any syntax errors.
* @param string $file File name to require in.
* @return string/boolean An error message on failure or false
* if no errors.
* @access private
*/
/**
* Requires a source file recording any syntax errors.
* @param string $file File name to require in.
* @return string/boolean An error message on failure or false
* if no errors.
* @access private
*/
function _requireWithError($file) {
$this->_enableErrorReporting();
include($file);
$error = isset($php_errormsg) ? $php_errormsg : false;
$this->_disableErrorReporting();
$self_inflicted = array(
$self_inflicted_errors = array(
'Assigning the return value of new by reference is deprecated',
'var: Deprecated. Please use the public/private/protected modifiers');
if (in_array($error, $self_inflicted)) {
if (in_array($error, $self_inflicted_errors)) {
return false;
}
return $error;
}
/**
* Sets up detection of parse errors. Note that XDebug
* interferes with this and has to be disabled. This is
* to make sure the correct error code is returned
* from unattended scripts.
* @access private
*/
/**
* Sets up detection of parse errors. Note that XDebug
* interferes with this and has to be disabled. This is
* to make sure the correct error code is returned
* from unattended scripts.
* @access private
*/
function _enableErrorReporting() {
if ($this->_xdebug_is_enabled) {
xdebug_disable();
@ -388,12 +402,12 @@
ini_set('track_errors', true);
}
/**
* Resets detection of parse errors to their old values.
* This is to make sure the correct error code is returned
* from unattended scripts.
* @access private
*/
/**
* Resets detection of parse errors to their old values.
* This is to make sure the correct error code is returned
* from unattended scripts.
* @access private
*/
function _disableErrorReporting() {
ini_set('track_errors', $this->_old_track_errors);
if ($this->_xdebug_is_enabled) {
@ -401,37 +415,36 @@
}
}
/**
* Calculates the incoming test cases from a before
* and after list of loaded classes.
* @param array $existing_classes Classes before require().
* @param array $new_classes Classes after require().
* @return array New classes which are test
* cases that shouldn't be ignored.
* @access private
*/
/**
* Calculates the incoming test cases from a before
* and after list of loaded classes.
* @param array $existing_classes Classes before require().
* @param array $new_classes Classes after require().
* @return array New classes which are test
* cases that shouldn't be ignored.
* @access private
*/
function _selectRunnableTests($existing_classes, $new_classes) {
$classes = array();
foreach ($new_classes as $class) {
if (in_array($class, $existing_classes)) {
continue;
}
if (! $this->_isTestCase($class)) {
continue;
if ($this->_getBaseTestCase($class)) {
$classes[] = $class;
}
$classes[] = $class;
}
return $classes;
}
/**
* Builds a group test from a class list.
* @param string $title Title of new group.
* @param array $classes Test classes.
* @return GroupTest Group loaded with the new
* test cases.
* @access private
*/
/**
* Builds a group test from a class list.
* @param string $title Title of new group.
* @param array $classes Test classes.
* @return GroupTest Group loaded with the new
* test cases.
* @access private
*/
function _createGroupFromClasses($title, $classes) {
$group = new GroupTest($title);
foreach ($classes as $class) {
@ -443,28 +456,39 @@
return $group;
}
/**
* Test to see if a class is derived from the
* TestCase class.
* @param string $class Class name.
* @access private
*/
function _isTestCase($class) {
/**
* Test to see if a class is derived from the
* SimpleTestCase class.
* @param string $class Class name.
* @access private
*/
function _getBaseTestCase($class) {
while ($class = get_parent_class($class)) {
$class = strtolower($class);
if ($class == "simpletestcase" || $class == "grouptest") {
return true;
return $class;
}
}
return false;
}
/**
* Delegates to a visiting collector to add test
* files.
* @param string $path Path to scan from.
* @param SimpleCollector $collector Directory scanner.
* @access public
*/
function collect($path, &$collector) {
$collector->collect($this, $path);
}
/**
* Invokes run() on all of the held test cases, instantiating
* them if necessary.
* @param SimpleReporter $reporter Current test reporter.
* @access public
*/
/**
* Invokes run() on all of the held test cases, instantiating
* them if necessary.
* @param SimpleReporter $reporter Current test reporter.
* @access public
*/
function run(&$reporter) {
$reporter->paintGroupStart($this->getLabel(), $this->getSize());
for ($i = 0, $count = count($this->_test_cases); $i < $count; $i++) {
@ -480,11 +504,11 @@
return $reporter->getStatus();
}
/**
* Number of contained test cases.
* @return integer Total count of cases in the group.
* @access public
*/
/**
* Number of contained test cases.
* @return integer Total count of cases in the group.
* @access public
*/
function getSize() {
$count = 0;
foreach ($this->_test_cases as $case) {
@ -498,41 +522,41 @@
}
}
/**
* This is a failing group test for when a test suite hasn't
* loaded properly.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* This is a failing group test for when a test suite hasn't
* loaded properly.
* @package SimpleTest
* @subpackage UnitTester
*/
class BadGroupTest {
var $_label;
var $_error;
/**
* Sets the name of the test suite and error message.
* @param string $label Name sent at the start and end
* of the test.
* @access public
*/
/**
* Sets the name of the test suite and error message.
* @param string $label Name sent at the start and end
* of the test.
* @access public
*/
function BadGroupTest($label, $error) {
$this->_label = $label;
$this->_error = $error;
}
/**
* Accessor for the test name for subclasses.
* @return string Name of the test.
* @access public
*/
/**
* Accessor for the test name for subclasses.
* @return string Name of the test.
* @access public
*/
function getLabel() {
return $this->_label;
}
/**
* Sends a single error to the reporter.
* @param SimpleReporter $reporter Current test reporter.
* @access public
*/
/**
* Sends a single error to the reporter.
* @param SimpleReporter $reporter Current test reporter.
* @access public
*/
function run(&$reporter) {
$reporter->paintGroupStart($this->getLabel(), $this->getSize());
$reporter->paintFail('Bad GroupTest [' . $this->getLabel() .
@ -541,11 +565,11 @@
return $reporter->getStatus();
}
/**
* Number of contained test cases. Always zero.
* @return integer Total count of cases in the group.
* @access public
*/
/**
* Number of contained test cases. Always zero.
* @return integer Total count of cases in the group.
* @access public
*/
function getSize() {
return 0;
}

View file

@ -1,88 +1,88 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage MockObjects
* @version $Id$
*/
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage MockObjects
* @version $Id$
*/
/**#@+
* include SimpleTest files
*/
/**#@+
* include SimpleTest files
*/
require_once(dirname(__FILE__) . '/options.php');
/**#@-*/
/**#@-*/
/**
* Stashes an error for later. Useful for constructors
* until PHP gets exceptions.
* @package SimpleTest
* @subpackage WebTester
*/
/**
* Stashes an error for later. Useful for constructors
* until PHP gets exceptions.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleStickyError {
var $_error = 'Constructor not chained';
/**
* Sets the error to empty.
* @access public
*/
/**
* Sets the error to empty.
* @access public
*/
function SimpleStickyError() {
$this->_clearError();
}
/**
* Test for an outstanding error.
* @return boolean True if there is an error.
* @access public
*/
/**
* Test for an outstanding error.
* @return boolean True if there is an error.
* @access public
*/
function isError() {
return ($this->_error != '');
}
/**
* Accessor for an outstanding error.
* @return string Empty string if no error otherwise
* the error message.
* @access public
*/
/**
* Accessor for an outstanding error.
* @return string Empty string if no error otherwise
* the error message.
* @access public
*/
function getError() {
return $this->_error;
}
/**
* Sets the internal error.
* @param string Error message to stash.
* @access protected
*/
/**
* Sets the internal error.
* @param string Error message to stash.
* @access protected
*/
function _setError($error) {
$this->_error = $error;
}
/**
* Resets the error state to no error.
* @access protected
*/
/**
* Resets the error state to no error.
* @access protected
*/
function _clearError() {
$this->_setError('');
}
}
/**
* Wrapper for TCP/IP socket.
* @package SimpleTest
* @subpackage WebTester
*/
/**
* Wrapper for TCP/IP socket.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleSocket extends SimpleStickyError {
var $_handle;
var $_is_open;
var $_sent;
/**
* Opens a socket for reading and writing.
* @param string $host Hostname to send request to.
* @param integer $port Port on remote machine to open.
* @param integer $timeout Connection timeout in seconds.
* @access public
*/
/**
* Opens a socket for reading and writing.
* @param string $host Hostname to send request to.
* @param integer $port Port on remote machine to open.
* @param integer $timeout Connection timeout in seconds.
* @access public
*/
function SimpleSocket($host, $port, $timeout) {
$this->SimpleStickyError();
$this->_is_open = false;
@ -95,12 +95,12 @@
SimpleTestCompatibility::setTimeout($this->_handle, $timeout);
}
/**
* 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
*/
/**
* 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) {
if ($this->isError() || ! $this->isOpen()) {
return false;
@ -118,15 +118,15 @@
return true;
}
/**
* Reads data from the socket. The error suppresion
* is a workaround for PHP4 always throwing a warning
* with a secure socket.
* @param integer $block_size Size of chunk to read.
* @return integer Incoming bytes. False
* on error.
* @access public
*/
/**
* Reads data from the socket. The error suppresion
* is a workaround for PHP4 always throwing a warning
* with a secure socket.
* @param integer $block_size Size of chunk to read.
* @return string/boolean Incoming bytes. False
* on error.
* @access public
*/
function read($block_size = 255) {
if ($this->isError() || ! $this->isOpen()) {
return false;
@ -139,76 +139,76 @@
return $raw;
}
/**
* Accessor for socket open state.
* @return boolean True if open.
* @access public
*/
/**
* 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
*/
/**
* Closes the socket preventing further reads.
* Cannot be reopened once closed.
* @return boolean True if successful.
* @access public
*/
function close() {
$this->_is_open = false;
return fclose($this->_handle);
}
/**
* Accessor for content so far.
* @return string Bytes sent only.
* @access public
*/
/**
* Accessor for content so far.
* @return string Bytes sent only.
* @access public
*/
function getSent() {
return $this->_sent;
}
/**
* Actually opens the low level socket.
* @param string $host Host to connect to.
* @param integer $port Port on host.
* @param integer $error_number Recipient of error code.
* @param string $error Recipoent of error message.
* @param integer $timeout Maximum time to wait for connection.
* @access protected
*/
/**
* Actually opens the low level socket.
* @param string $host Host to connect to.
* @param integer $port Port on host.
* @param integer $error_number Recipient of error code.
* @param string $error Recipoent of error message.
* @param integer $timeout Maximum time to wait for connection.
* @access protected
*/
function _openSocket($host, $port, &$error_number, &$error, $timeout) {
return @fsockopen($host, $port, $error_number, $error, $timeout);
}
}
/**
* Wrapper for TCP/IP socket over TLS.
* @package SimpleTest
* @subpackage WebTester
*/
/**
* Wrapper for TCP/IP socket over TLS.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleSecureSocket extends SimpleSocket {
/**
* Opens a secure socket for reading and writing.
* @param string $host Hostname to send request to.
* @param integer $port Port on remote machine to open.
* @param integer $timeout Connection timeout in seconds.
* @access public
*/
/**
* Opens a secure socket for reading and writing.
* @param string $host Hostname to send request to.
* @param integer $port Port on remote machine to open.
* @param integer $timeout Connection timeout in seconds.
* @access public
*/
function SimpleSecureSocket($host, $port, $timeout) {
$this->SimpleSocket($host, $port, $timeout);
}
/**
* Actually opens the low level socket.
* @param string $host Host to connect to.
* @param integer $port Port on host.
* @param integer $error_number Recipient of error code.
* @param string $error Recipient of error message.
* @param integer $timeout Maximum time to wait for connection.
* @access protected
*/
/**
* Actually opens the low level socket.
* @param string $host Host to connect to.
* @param integer $port Port on host.
* @param integer $error_number Recipient of error code.
* @param string $error Recipient of error message.
* @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);
}

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,35 +1,35 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**#@+
* include other SimpleTest class files
*/
/**#@+
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/simple_test.php');
require_once(dirname(__FILE__) . '/errors.php');
require_once(dirname(__FILE__) . '/dumper.php');
/**#@-*/
/**#@-*/
/**
* Standard unit test class for day to day testing
* of PHP code XP style. Adds some useful standard
* assertions.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Standard unit test class for day to day testing
* of PHP code XP style. Adds some useful standard
* assertions.
* @package SimpleTest
* @subpackage UnitTester
*/
class UnitTestCase extends SimpleTestCase {
/**
* Creates an empty test case. Should be subclassed
* with test methods for a functional test case.
* @param string $label Name of test case. Will use
* the class name if none specified.
* @access public
*/
/**
* Creates an empty test case. Should be subclassed
* with test methods for a functional test case.
* @param string $label Name of test case. Will use
* the class name if none specified.
* @access public
*/
function UnitTestCase($label = false) {
if (! $label) {
$label = get_class($this);
@ -37,13 +37,13 @@
$this->SimpleTestCase($label);
}
/**
* Will be true if the value is null.
* @param null $value Supposedly null value.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
/**
* Will be true if the value is null.
* @param null $value Supposedly null value.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertNull($value, $message = "%s") {
$dumper = &new SimpleDumper();
$message = sprintf(
@ -52,13 +52,13 @@
return $this->assertTrue(! isset($value), $message);
}
/**
* Will be true if the value is set.
* @param mixed $value Supposedly set value.
* @param string $message Message to display.
* @return boolean True on pass.
* @access public
*/
/**
* Will be true if the value is set.
* @param mixed $value Supposedly set value.
* @param string $message Message to display.
* @return boolean True on pass.
* @access public
*/
function assertNotNull($value, $message = "%s") {
$dumper = &new SimpleDumper();
$message = sprintf(
@ -67,113 +67,147 @@
return $this->assertTrue(isset($value), $message);
}
/**
* Type and class test. Will pass if class
* matches the type name or is a subclass or
* if not an object, but the type is correct.
* @param mixed $object Object to test.
* @param string $type Type name as string.
* @param string $message Message to display.
* @return boolean True on pass.
* @access public
*/
/**
* Type and class test. Will pass if class
* matches the type name or is a subclass or
* if not an object, but the type is correct.
* @param mixed $object Object to test.
* @param string $type Type name as string.
* @param string $message Message to display.
* @return boolean True on pass.
* @access public
*/
function assertIsA($object, $type, $message = "%s") {
return $this->assertExpectation(
return $this->assert(
new IsAExpectation($type),
$object,
$message);
}
/**
* Type and class mismatch test. Will pass if class
* name or underling type does not match the one
* specified.
* @param mixed $object Object to test.
* @param string $type Type name as string.
* @param string $message Message to display.
* @return boolean True on pass.
* @access public
*/
/**
* Type and class mismatch test. Will pass if class
* name or underling type does not match the one
* specified.
* @param mixed $object Object to test.
* @param string $type Type name as string.
* @param string $message Message to display.
* @return boolean True on pass.
* @access public
*/
function assertNotA($object, $type, $message = "%s") {
return $this->assertExpectation(
return $this->assert(
new NotAExpectation($type),
$object,
$message);
}
/**
* Will trigger a pass if the two parameters have
* the same value only. Otherwise a fail.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
/**
* Will trigger a pass if the two parameters have
* the same value only. Otherwise a fail.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertEqual($first, $second, $message = "%s") {
return $this->assertExpectation(
return $this->assert(
new EqualExpectation($first),
$second,
$message);
}
/**
* Will trigger a pass if the two parameters have
* a different value. Otherwise a fail.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
/**
* Will trigger a pass if the two parameters have
* a different value. Otherwise a fail.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertNotEqual($first, $second, $message = "%s") {
return $this->assertExpectation(
return $this->assert(
new NotEqualExpectation($first),
$second,
$message);
}
/**
* Will trigger a pass if the two parameters have
* the same value and same type. Otherwise a fail.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
/**
* Will trigger a pass if the if the first parameter
* is near enough to the second by the margin.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param mixed $margin Fuzziness of match.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertWithinMargin($first, $second, $margin, $message = "%s") {
return $this->assert(
new WithinMarginExpectation($first, $margin),
$second,
$message);
}
/**
* Will trigger a pass if the two parameters differ
* by more than the margin.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param mixed $margin Fuzziness of match.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertOutsideMargin($first, $second, $margin, $message = "%s") {
return $this->assert(
new OutsideMarginExpectation($first, $margin),
$second,
$message);
}
/**
* Will trigger a pass if the two parameters have
* the same value and same type. Otherwise a fail.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertIdentical($first, $second, $message = "%s") {
return $this->assertExpectation(
return $this->assert(
new IdenticalExpectation($first),
$second,
$message);
}
/**
* Will trigger a pass if the two parameters have
* the different value or different type.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
/**
* Will trigger a pass if the two parameters have
* the different value or different type.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertNotIdentical($first, $second, $message = "%s") {
return $this->assertExpectation(
return $this->assert(
new NotIdenticalExpectation($first),
$second,
$message);
}
/**
* 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.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
/**
* 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.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertReference(&$first, &$second, $message = "%s") {
$dumper = &new SimpleDumper();
$message = sprintf(
@ -186,15 +220,15 @@
$message);
}
/**
* Will trigger a pass if both parameters refer
* to different objects. Fail otherwise.
* @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
*/
/**
* Will trigger a pass if both parameters refer
* to different objects. Fail otherwise.
* @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();
$message = sprintf(
@ -207,47 +241,61 @@
$message);
}
/**
* Will trigger a pass if the Perl regex pattern
* is found in the subject. Fail otherwise.
* @param string $pattern Perl regex to look for including
* the regex delimiters.
* @param string $subject String to search in.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
/**
* Will trigger a pass if the Perl regex pattern
* is found in the subject. Fail otherwise.
* @param string $pattern Perl regex to look for including
* the regex delimiters.
* @param string $subject String to search in.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertPattern($pattern, $subject, $message = "%s") {
return $this->assert(
new PatternExpectation($pattern),
$subject,
$message);
}
/**
* @deprecated
*/
function assertWantedPattern($pattern, $subject, $message = "%s") {
return $this->assertExpectation(
new WantedPatternExpectation($pattern),
return $this->assertPattern($pattern, $subject, $message);
}
/**
* Will trigger a pass if the perl regex pattern
* is not present in subject. Fail if found.
* @param string $pattern Perl regex to look for including
* the regex delimiters.
* @param string $subject String to search in.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertNoPattern($pattern, $subject, $message = "%s") {
return $this->assert(
new NoPatternExpectation($pattern),
$subject,
$message);
}
/**
* Will trigger a pass if the perl regex pattern
* is not present in subject. Fail if found.
* @param string $pattern Perl regex to look for including
* the regex delimiters.
* @param string $subject String to search in.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
/**
* @deprecated
*/
function assertNoUnwantedPattern($pattern, $subject, $message = "%s") {
return $this->assertExpectation(
new UnwantedPatternExpectation($pattern),
$subject,
$message);
return $this->assertNoPattern($pattern, $subject, $message);
}
/**
* Confirms that no errors have occoured so
* far in the test method.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
/**
* Confirms that no errors have occoured so
* far in the test method.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertNoErrors($message = "%s") {
$queue = &SimpleErrorQueue::instance();
return $this->assertTrue(
@ -255,15 +303,15 @@
sprintf($message, "Should be no errors"));
}
/**
* Confirms that an error has occoured and
* optionally that the error text matches exactly.
* @param string $expected Expected error text or
* false for no check.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
/**
* Confirms that an error has occoured and
* optionally that the error text matches exactly.
* @param string $expected Expected error text or
* false for no check.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertError($expected = false, $message = "%s") {
$queue = &SimpleErrorQueue::instance();
if ($queue->isEmpty()) {
@ -272,32 +320,37 @@
}
list($severity, $content, $file, $line, $globals) = $queue->extract();
$severity = SimpleErrorQueue::getSeverityAsString($severity);
return $this->assertTrue(
! $expected || ($expected == $content),
"Expected [$expected] in PHP error [$content] severity [$severity] in [$file] line [$line]");
if (! $expected) {
return $this->pass(
"Captured a PHP error of [$content] severity [$severity] in [$file] line [$line] -> %s");
}
$expected = $this->_coerceToExpectation($expected);
return $this->assert(
$expected,
$content,
"Expected PHP error [$content] severity [$severity] in [$file] line [$line] -> %s");
}
/**
* Confirms that an error has occoured and
* that the error text matches a Perl regular
* expression.
* @param string $pattern Perl regular expresion to
* match against.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertErrorPattern($pattern, $message = "%s") {
$queue = &SimpleErrorQueue::instance();
if ($queue->isEmpty()) {
$this->fail(sprintf($message, "Expected error not found"));
return;
/**
* Creates an equality expectation if the
* object/value is not already some type
* of expectation.
* @param mixed $expected Expected value.
* @return SimpleExpectation Expectation object.
* @access private
*/
function _coerceToExpectation($expected) {
if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) {
return $expected;
}
list($severity, $content, $file, $line, $globals) = $queue->extract();
$severity = SimpleErrorQueue::getSeverityAsString($severity);
return $this->assertTrue(
(boolean)preg_match($pattern, $content),
"Expected pattern match [$pattern] in PHP error [$content] severity [$severity] in [$file] line [$line]");
return new EqualExpectation($expected);
}
/**
* @deprecated
*/
function assertErrorPattern($pattern, $message = "%s") {
return $this->assertError(new PatternExpectation($pattern), $message);
}
}
?>

View file

@ -1,26 +1,27 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
* @version $Id$
*/
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
* @version $Id$
*/
/**#@+
* include other SimpleTest class files
*/
/**#@+
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/encoding.php');
/**#@-*/
/**#@-*/
/**
* URL parser to replace parse_url() PHP function which
* got broken in PHP 4.3.0. Adds some browser specific
* functionality such as expandomatics.
* Guesses a bit trying to separate the host from
* the path.
* @package SimpleTest
* @subpackage WebTester
*/
/**
* URL parser to replace parse_url() PHP function which
* got broken in PHP 4.3.0. Adds some browser specific
* functionality such as expandomatics.
* Guesses a bit trying to separate the host from
* the path and tries to keep a raw, possibly unparsable,
* request string as long as possible.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleUrl {
var $_scheme;
var $_username;
@ -30,15 +31,19 @@
var $_path;
var $_request;
var $_fragment;
var $_x;
var $_y;
var $_target;
var $_raw = false;
/**
* Constructor. Parses URL into sections.
* @param string $url Incoming URL.
* @access public
*/
/**
* Constructor. Parses URL into sections.
* @param string $url Incoming URL.
* @access public
*/
function SimpleUrl($url) {
list($x, $y) = $this->_chompCoordinates($url);
$this->setCoordinates($x, $y);
$this->_scheme = $this->_chompScheme($url);
list($this->_username, $this->_password) = $this->_chompLogin($url);
$this->_host = $this->_chompHost($url);
@ -49,18 +54,17 @@
}
$this->_path = $this->_chompPath($url);
$this->_request = $this->_parseRequest($this->_chompRequest($url));
$this->_request->setCoordinates($x, $y);
$this->_fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false);
$this->_target = false;
}
/**
* Extracts the X, Y coordinate pair from an image map.
* @param string $url URL so far. The coordinates will be
* removed.
* @return array X, Y as a pair of integers.
* @access private
*/
/**
* Extracts the X, Y coordinate pair from an image map.
* @param string $url URL so far. The coordinates will be
* removed.
* @return array X, Y as a pair of integers.
* @access private
*/
function _chompCoordinates(&$url) {
if (preg_match('/(.*)\?(\d+),(\d+)$/', $url, $matches)) {
$url = $matches[1];
@ -69,13 +73,13 @@
return array(false, false);
}
/**
* Extracts the scheme part of an incoming URL.
* @param string $url URL so far. The scheme will be
* removed.
* @return string Scheme part or false.
* @access private
*/
/**
* Extracts the scheme part of an incoming URL.
* @param string $url URL so far. The scheme will be
* removed.
* @return string Scheme part or false.
* @access private
*/
function _chompScheme(&$url) {
if (preg_match('/(.*?):(\/\/)(.*)/', $url, $matches)) {
$url = $matches[2] . $matches[3];
@ -84,19 +88,19 @@
return false;
}
/**
* Extracts the username and password from the
* incoming URL. The // prefix will be reattached
* to the URL after the doublet is extracted.
* @param string $url URL so far. The username and
* password are removed.
* @return array Two item list of username and
* password. Will urldecode() them.
* @access private
*/
/**
* Extracts the username and password from the
* incoming URL. The // prefix will be reattached
* to the URL after the doublet is extracted.
* @param string $url URL so far. The username and
* password are removed.
* @return array Two item list of username and
* password. Will urldecode() them.
* @access private
*/
function _chompLogin(&$url) {
$prefix = '';
if (preg_match('/(\/\/)(.*)/', $url, $matches)) {
if (preg_match('/^(\/\/)(.*)/', $url, $matches)) {
$prefix = $matches[1];
$url = $matches[2];
}
@ -111,19 +115,19 @@
return array(false, false);
}
/**
* Extracts the host part of an incoming URL.
* Includes the port number part. Will extract
* the host if it starts with // or it has
* a top level domain or it has at least two
* dots.
* @param string $url URL so far. The host will be
* removed.
* @return string Host part guess or false.
* @access private
*/
/**
* Extracts the host part of an incoming URL.
* Includes the port number part. Will extract
* the host if it starts with // or it has
* a top level domain or it has at least two
* dots.
* @param string $url URL so far. The host will be
* removed.
* @return string Host part guess or false.
* @access private
*/
function _chompHost(&$url) {
if (preg_match('/(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) {
if (preg_match('/^(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) {
$url = $matches[3];
return $matches[2];
}
@ -140,14 +144,14 @@
return false;
}
/**
* Extracts the path information from the incoming
* URL. Strips this path from the URL.
* @param string $url URL so far. The host will be
* removed.
* @return string Path part or '/'.
* @access private
*/
/**
* Extracts the path information from the incoming
* URL. Strips this path from the URL.
* @param string $url URL so far. The host will be
* removed.
* @return string Path part or '/'.
* @access private
*/
function _chompPath(&$url) {
if (preg_match('/(.*?)(\?|#|$)(.*)/', $url, $matches)) {
$url = $matches[2] . $matches[3];
@ -156,13 +160,13 @@
return '';
}
/**
* Strips off the request data.
* @param string $url URL so far. The request will be
* removed.
* @return string Raw request part.
* @access private
*/
/**
* Strips off the request data.
* @param string $url URL so far. The request will be
* removed.
* @return string Raw request part.
* @access private
*/
function _chompRequest(&$url) {
if (preg_match('/\?(.*?)(#|$)(.*)/', $url, $matches)) {
$url = $matches[2] . $matches[3];
@ -171,14 +175,15 @@
return '';
}
/**
* Breaks the request down into an object.
* @param string $raw Raw request.
* @return SimpleFormEncoding Parsed data.
* @access private
*/
/**
* Breaks the request down into an object.
* @param string $raw Raw request.
* @return SimpleFormEncoding Parsed data.
* @access private
*/
function _parseRequest($raw) {
$request = new SimpleFormEncoding();
$this->_raw = $raw;
$request = new SimpleGetEncoding();
foreach (split("&", $raw) as $pair) {
if (preg_match('/(.*?)=(.*)/', $pair, $matches)) {
$request->add($matches[1], urldecode($matches[2]));
@ -189,68 +194,68 @@
return $request;
}
/**
* Accessor for protocol part.
* @param string $default Value to use if not present.
* @return string Scheme name, e.g "http".
* @access public
*/
/**
* Accessor for protocol part.
* @param string $default Value to use if not present.
* @return string Scheme name, e.g "http".
* @access public
*/
function getScheme($default = false) {
return $this->_scheme ? $this->_scheme : $default;
}
/**
* Accessor for user name.
* @return string Username preceding host.
* @access public
*/
/**
* Accessor for user name.
* @return string Username preceding host.
* @access public
*/
function getUsername() {
return $this->_username;
}
/**
* Accessor for password.
* @return string Password preceding host.
* @access public
*/
/**
* Accessor for password.
* @return string Password preceding host.
* @access public
*/
function getPassword() {
return $this->_password;
}
/**
* Accessor for hostname and port.
* @param string $default Value to use if not present.
* @return string Hostname only.
* @access public
*/
/**
* Accessor for hostname and port.
* @param string $default Value to use if not present.
* @return string Hostname only.
* @access public
*/
function getHost($default = false) {
return $this->_host ? $this->_host : $default;
}
/**
* Accessor for top level domain.
* @return string Last part of host.
* @access public
*/
/**
* Accessor for top level domain.
* @return string Last part of host.
* @access public
*/
function getTld() {
$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
*/
/**
* Accessor for port number.
* @return integer TCP/IP port number.
* @access public
*/
function getPort() {
return $this->_port;
}
/**
* Accessor for path.
* @return string Full path including leading slash if implied.
* @access public
*/
/**
* Accessor for path.
* @return string Full path including leading slash if implied.
* @access public
*/
function getPath() {
if (! $this->_path && $this->_host) {
return '/';
@ -258,12 +263,12 @@
return $this->_path;
}
/**
* Accessor for page if any. This may be a
* directory name if ambiguious.
* @return Page name.
* @access public
*/
/**
* Accessor for page if any. This may be a
* directory name if ambiguious.
* @return Page name.
* @access public
*/
function getPage() {
if (! preg_match('/([^\/]*?)$/', $this->getPath(), $matches)) {
return false;
@ -271,11 +276,11 @@
return $matches[1];
}
/**
* Gets the path to the page.
* @return string Path less the page.
* @access public
*/
/**
* Gets the path to the page.
* @return string Path less the page.
* @access public
*/
function getBasePath() {
if (! preg_match('/(.*\/)[^\/]*?$/', $this->getPath(), $matches)) {
return false;
@ -283,111 +288,126 @@
return $matches[1];
}
/**
* Accessor for fragment at end of URL after the "#".
* @return string Part after "#".
* @access public
*/
/**
* Accessor for fragment at end of URL after the "#".
* @return string Part after "#".
* @access public
*/
function getFragment() {
return $this->_fragment;
}
/**
* Accessor for horizontal image coordinate.
* @return integer X value.
* @access public
*/
/**
* Sets image coordinates. Set to false to clear
* them.
* @param integer $x Horizontal position.
* @param integer $y Vertical position.
* @access public
*/
function setCoordinates($x = false, $y = false) {
if (($x === false) || ($y === false)) {
$this->_x = $this->_y = false;
return;
}
$this->_x = (integer)$x;
$this->_y = (integer)$y;
}
/**
* Accessor for horizontal image coordinate.
* @return integer X value.
* @access public
*/
function getX() {
return $this->_request->getX();
return $this->_x;
}
/**
* Accessor for vertical image coordinate.
* @return integer Y value.
* @access public
*/
/**
* Accessor for vertical image coordinate.
* @return integer Y value.
* @access public
*/
function getY() {
return $this->_request->getY();
return $this->_y;
}
/**
* Accessor for current request parameters
* in URL string form
* @return string Form is string "?a=1&b=2", etc.
* @access public
*/
/**
* Accessor for current request parameters
* in URL string form. Will return teh original request
* if at all possible even if it doesn't make much
* sense.
* @return string Form is string "?a=1&b=2", etc.
* @access public
*/
function getEncodedRequest() {
$encoded = $this->_request->asString();
if ($this->_raw) {
$encoded = $this->_raw;
} else {
$encoded = $this->_request->asUrlRequest();
}
if ($encoded) {
return '?' . preg_replace('/^\?/', '', $encoded);
}
return '';
}
/**
* Adds an additional parameter to the request.
* @param string $key Name of parameter.
* @param string $value Value as string.
* @access public
*/
/**
* Adds an additional parameter to the request.
* @param string $key Name of parameter.
* @param string $value Value as string.
* @access public
*/
function addRequestParameter($key, $value) {
$this->_raw = false;
$this->_request->add($key, $value);
}
/**
* Adds additional parameters to the request.
* @param hash/SimpleFormEncoding $parameters Additional
* parameters.
* @access public
*/
/**
* Adds additional parameters to the request.
* @param hash/SimpleFormEncoding $parameters Additional
* parameters.
* @access public
*/
function addRequestParameters($parameters) {
$this->_raw = false;
$this->_request->merge($parameters);
}
/**
* Clears down all parameters.
* @access public
*/
/**
* Clears down all parameters.
* @access public
*/
function clearRequest() {
$this->_request = &new SimpleFormEncoding();
$this->_raw = false;
$this->_request = &new SimpleGetEncoding();
}
/**
* Sets image coordinates. Set to flase to clear
* them.
* @param integer $x Horizontal position.
* @param integer $y Vertical position.
* @access public
*/
function setCoordinates($x = false, $y = false) {
$this->_request->setCoordinates($x, $y);
}
/**
* Gets the frame target if present. Although
* not strictly part of the URL specification it
* acts as similarily to the browser.
* @return boolean/string Frame name or false if none.
* @access public
*/
/**
* Gets the frame target if present. Although
* not strictly part of the URL specification it
* acts as similarily to the browser.
* @return boolean/string Frame name or false if none.
* @access public
*/
function getTarget() {
return $this->_target;
}
/**
* Attaches a frame target.
* @param string $frame Name of frame.
* @access public
*/
/**
* Attaches a frame target.
* @param string $frame Name of frame.
* @access public
*/
function setTarget($frame) {
$this->_raw = false;
$this->_target = $frame;
}
/**
* Renders the URL back into a string.
* @return string URL in canonical form.
* @access public
*/
/**
* Renders the URL back into a string.
* @return string URL in canonical form.
* @access public
*/
function asString() {
$scheme = $identity = $host = $path = $encoded = $fragment = '';
if ($this->_username && $this->_password) {
@ -402,51 +422,48 @@
}
$encoded = $this->getEncodedRequest();
$fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
return "$scheme://$identity$host$path$encoded$fragment";
$coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
return "$scheme://$identity$host$path$encoded$fragment$coords";
}
/**
* Replaces unknown sections to turn a relative
* URL into an absolute one. The base URL can
* be either a string or a SimpleUrl object.
* @param string/SimpleUrl $base Base URL.
* @access public
*/
/**
* Replaces unknown sections to turn a relative
* URL into an absolute one. The base URL can
* be either a string or a SimpleUrl object.
* @param string/SimpleUrl $base Base URL.
* @access public
*/
function makeAbsolute($base) {
if (! is_object($base)) {
$base = new SimpleUrl($base);
}
$scheme = $this->getScheme() ? $this->getScheme() : $base->getScheme();
$host = $this->getHost() ? $this->getHost() : $base->getHost();
$port = $this->_extractAbsolutePort($base);
if ($this->getHost()) {
$host = $this->getHost();
$port = $this->getPort() ? ':' . $this->getPort() : '';
$identity = $this->getIdentity() ? $this->getIdentity() . '@' : '';
if (! $identity) {
$identity = $base->getIdentity() ? $base->getIdentity() . '@' : '';
}
} else {
$host = $base->getHost();
$port = $base->getPort() ? ':' . $base->getPort() : '';
$identity = $base->getIdentity() ? $base->getIdentity() . '@' : '';
}
$path = $this->normalisePath($this->_extractAbsolutePath($base));
$identity = $this->_getIdentity() ? $this->_getIdentity() . '@' : '';
$encoded = $this->getEncodedRequest();
$fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment");
$coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords");
}
/**
* Extracts the port from the base URL if it's needed, but
* not present, in the current URL.
* @param string/SimpleUrl $base Base URL.
* @param string Absolute port number.
* @access private
*/
function _extractAbsolutePort($base) {
if ($this->getHost()) {
return ($this->getPort() ? ':' . $this->getPort() : '');
}
return ($base->getPort() ? ':' . $base->getPort() : '');
}
/**
* Replaces unknown sections of the path with base parts
* to return a complete absolute one.
* @param string/SimpleUrl $base Base URL.
* @param string Absolute path.
* @access private
*/
/**
* Replaces unknown sections of the path with base parts
* to return a complete absolute one.
* @param string/SimpleUrl $base Base URL.
* @param string Absolute path.
* @access private
*/
function _extractAbsolutePath($base) {
if ($this->getHost()) {
return $this->_path;
@ -460,47 +477,47 @@
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
*/
/**
* 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) {
return (substr($path, 0, 1) != '/');
}
/**
* Extracts the username and password for use in rendering
* a URL.
* @return string/boolean Form of username:password@ or false.
* @access private
*/
function _getIdentity() {
/**
* Extracts the username and password for use in rendering
* a URL.
* @return string/boolean Form of username:password@ or false.
* @access public
*/
function getIdentity() {
if ($this->_username && $this->_password) {
return $this->_username . ':' . $this->_password;
}
return false;
}
/**
* Replaces . and .. sections of the path.
* @param string $path Unoptimised path.
* @return string Path with dots removed if possible.
* @access public
*/
/**
* Replaces . and .. sections of the path.
* @param string $path Unoptimised path.
* @return string Path with dots removed if possible.
* @access public
*/
function normalisePath($path) {
$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
*/
/**
* A pipe seperated list of all TLDs that result in two part
* domain names.
* @return string Pipe separated list.
* @access public
* @static
*/
function getAllTopLevelDomains() {
return 'com|edu|net|org|gov|mil|int|biz|info|name|pro|aero|coop|museum';
}

View file

@ -1,45 +1,50 @@
<?php
/**
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
* @version $Id$
*/
/**
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
* @version $Id$
*/
/**#@+
* include other SimpleTest class files
*/
/**#@+
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/http.php');
require_once(dirname(__FILE__) . '/encoding.php');
require_once(dirname(__FILE__) . '/authentication.php');
/**#@-*/
/**#@-*/
define('DEFAULT_MAX_REDIRECTS', 3);
define('DEFAULT_CONNECTION_TIMEOUT', 15);
if (!defined('DEFAULT_MAX_REDIRECTS')) {
define('DEFAULT_MAX_REDIRECTS', 3);
}
/**
* Repository for cookies. This stuff is a
* tiny bit browser dependent.
* @package SimpleTest
* @subpackage WebTester
*/
if (!defined('DEFAULT_CONNECTION_TIMEOUT')) {
define('DEFAULT_CONNECTION_TIMEOUT', 15);
}
/**
* Repository for cookies. This stuff is a
* tiny bit browser dependent.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleCookieJar {
var $_cookies;
/**
* Constructor. Jar starts empty.
* @access public
*/
/**
* Constructor. Jar starts empty.
* @access public
*/
function SimpleCookieJar() {
$this->_cookies = array();
}
/**
* Removes expired and temporary cookies as if
* the browser was closed and re-opened.
* @param string/integer $now Time to test expiry against.
* @access public
*/
/**
* Removes expired and temporary cookies as if
* the browser was closed and re-opened.
* @param string/integer $now Time to test expiry against.
* @access public
*/
function restartSession($date = false) {
$surviving_cookies = array();
for ($i = 0; $i < count($this->_cookies); $i++) {
@ -57,26 +62,26 @@
$this->_cookies = $surviving_cookies;
}
/**
* Ages all cookies in the cookie jar.
* @param integer $interval The old session is moved
* into the past by this number
* of seconds. Cookies now over
* age will be removed.
* @access public
*/
/**
* Ages all cookies in the cookie jar.
* @param integer $interval The old session is moved
* into the past by this number
* of seconds. Cookies now over
* age will be removed.
* @access public
*/
function agePrematurely($interval) {
for ($i = 0; $i < count($this->_cookies); $i++) {
$this->_cookies[$i]->agePrematurely($interval);
}
}
/**
* Adds a cookie to the jar. This will overwrite
* cookies with matching host, paths and keys.
* @param SimpleCookie $cookie New cookie.
* @access public
*/
/**
* Adds a cookie to the jar. This will overwrite
* cookies with matching host, paths and keys.
* @param SimpleCookie $cookie New cookie.
* @access public
*/
function setCookie($cookie) {
for ($i = 0; $i < count($this->_cookies); $i++) {
$is_match = $this->_isMatch(
@ -92,18 +97,18 @@
$this->_cookies[] = $cookie;
}
/**
* Fetches a hash of all valid cookies filtered
* by host, path and keyed by name
* Any cookies with missing categories will not
* be filtered out by that category. Expired
* cookies must be cleared by restarting the session.
* @param string $host Host name requirement.
* @param string $path Path encompassing cookies.
* @return hash Valid cookie objects keyed
* on the cookie name.
* @access public
*/
/**
* Fetches a hash of all valid cookies filtered
* by host, path and keyed by name
* Any cookies with missing categories will not
* be filtered out by that category. Expired
* cookies must be cleared by restarting the session.
* @param string $host Host name requirement.
* @param string $path Path encompassing cookies.
* @return hash Valid cookie objects keyed
* on the cookie name.
* @access public
*/
function getValidCookies($host = false, $path = "/") {
$valid_cookies = array();
foreach ($this->_cookies as $cookie) {
@ -114,17 +119,17 @@
return $valid_cookies;
}
/**
* Tests cookie for matching against search
* criteria.
* @param SimpleTest $cookie Cookie to test.
* @param string $host Host must match.
* @param string $path Cookie path must be shorter than
* this path.
* @param string $name Name must match.
* @return boolean True if matched.
* @access private
*/
/**
* Tests cookie for matching against search
* criteria.
* @param SimpleTest $cookie Cookie to test.
* @param string $host Host must match.
* @param string $path Cookie path must be shorter than
* this path.
* @param string $name Name must match.
* @return boolean True if matched.
* @access private
*/
function _isMatch($cookie, $host, $path, $name) {
if ($cookie->getName() != $name) {
return false;
@ -138,12 +143,12 @@
return true;
}
/**
* Adds the current cookies to a request.
* @param SimpleHttpRequest $request Request to modify.
* @param SimpleUrl $url Cookie selector.
* @access private
*/
/**
* Adds the current cookies to a request.
* @param SimpleHttpRequest $request Request to modify.
* @param SimpleUrl $url Cookie selector.
* @access private
*/
function addHeaders(&$request, $url) {
$cookies = $this->getValidCookies($url->getHost(), $url->getPath());
foreach ($cookies as $cookie) {
@ -152,12 +157,12 @@
}
}
/**
* Fetches web pages whilst keeping track of
* cookies and authentication.
* @package SimpleTest
* @subpackage WebTester
*/
/**
* Fetches web pages whilst keeping track of
* cookies and authentication.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleUserAgent {
var $_cookie_jar;
var $_authenticator;
@ -168,10 +173,10 @@
var $_connection_timeout;
var $_additional_headers;
/**
* Starts with no cookies, realms or proxies.
* @access public
*/
/**
* Starts with no cookies, realms or proxies.
* @access public
*/
function SimpleUserAgent() {
$this->_cookie_jar = &new SimpleCookieJar();
$this->_authenticator = &new SimpleAuthenticator();
@ -183,49 +188,49 @@
$this->_additional_headers = array();
}
/**
* Removes expired and temporary cookies as if
* the browser was closed and re-opened. Authorisation
* has to be obtained again as well.
* @param string/integer $date Time when session restarted.
* If omitted then all persistent
* cookies are kept.
* @access public
*/
/**
* Removes expired and temporary cookies as if
* the browser was closed and re-opened. Authorisation
* has to be obtained again as well.
* @param string/integer $date Time when session restarted.
* If omitted then all persistent
* cookies are kept.
* @access public
*/
function restart($date = false) {
$this->_cookie_jar->restartSession($date);
$this->_authenticator->restartSession();
}
/**
* Adds a header to every fetch.
* @param string $header Header line to add to every
* request until cleared.
* @access public
*/
/**
* Adds a header to every fetch.
* @param string $header Header line to add to every
* request until cleared.
* @access public
*/
function addHeader($header) {
$this->_additional_headers[] = $header;
}
/**
* Ages the cookies by the specified time.
* @param integer $interval Amount in seconds.
* @access public
*/
/**
* Ages the cookies by the specified time.
* @param integer $interval Amount in seconds.
* @access public
*/
function ageCookies($interval) {
$this->_cookie_jar->agePrematurely($interval);
}
/**
* Sets an additional cookie. If a cookie has
* the same name and path it is replaced.
* @param string $name Cookie key.
* @param string $value Value of cookie.
* @param string $host Host upon which the cookie is valid.
* @param string $path Cookie path if not host wide.
* @param string $expiry Expiry date.
* @access public
*/
/**
* Sets an additional cookie. If a cookie has
* the same name and path it is replaced.
* @param string $name Cookie key.
* @param string $value Value of cookie.
* @param string $host Host upon which the cookie is valid.
* @param string $path Cookie path if not host wide.
* @param string $expiry Expiry date.
* @access public
*/
function setCookie($name, $value, $host = false, $path = '/', $expiry = false) {
$cookie = new SimpleCookie($name, $value, $path, $expiry);
if ($host) {
@ -234,16 +239,16 @@
$this->_cookie_jar->setCookie($cookie);
}
/**
* Reads the most specific cookie value from the
* browser cookies.
* @param string $host Host to search.
* @param string $path Applicable path.
* @param string $name Name of cookie to read.
* @return string False if not present, else the
* value as a string.
* @access public
*/
/**
* Reads the most specific cookie value from the
* browser cookies.
* @param string $host Host to search.
* @param string $path Applicable path.
* @param string $name Name of cookie to read.
* @return string False if not present, else the
* value as a string.
* @access public
*/
function getCookieValue($host, $path, $name) {
$longest_path = '';
foreach ($this->_cookie_jar->getValidCookies($host, $path) as $cookie) {
@ -257,14 +262,14 @@
return (isset($value) ? $value : false);
}
/**
* Reads the current cookies within the base URL.
* @param string $name Key of cookie to find.
* @param SimpleUrl $base Base URL to search from.
* @return string Null if there is no base URL, false
* if the cookie is not set.
* @access public
*/
/**
* Reads the current cookies within the base URL.
* @param string $name Key of cookie to find.
* @param SimpleUrl $base Base URL to search from.
* @return string Null if there is no base URL, false
* if the cookie is not set.
* @access public
*/
function getBaseCookieValue($name, $base) {
if (! $base) {
return null;
@ -272,34 +277,34 @@
return $this->getCookieValue($base->getHost(), $base->getPath(), $name);
}
/**
* Sets the socket timeout for opening a connection.
* @param integer $timeout Maximum time in seconds.
* @access public
*/
/**
* Sets the socket timeout for opening a connection.
* @param integer $timeout Maximum time in seconds.
* @access public
*/
function setConnectionTimeout($timeout) {
$this->_connection_timeout = $timeout;
}
/**
* Sets the maximum number of redirects before
* a page will be loaded anyway.
* @param integer $max Most hops allowed.
* @access public
*/
/**
* Sets the maximum number of redirects before
* a page will be loaded anyway.
* @param integer $max Most hops allowed.
* @access public
*/
function setMaximumRedirects($max) {
$this->_max_redirects = $max;
}
/**
* Sets proxy to use on all requests for when
* testing from behind a firewall. Set URL
* to false to disable.
* @param string $proxy Proxy URL.
* @param string $username Proxy username for authentication.
* @param string $password Proxy password for authentication.
* @access public
*/
/**
* Sets proxy to use on all requests for when
* testing from behind a firewall. Set URL
* to false to disable.
* @param string $proxy Proxy URL.
* @param string $username Proxy username for authentication.
* @param string $password Proxy password for authentication.
* @access public
*/
function useProxy($proxy, $username, $password) {
if (! $proxy) {
$this->_proxy = false;
@ -313,43 +318,42 @@
$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
*/
/**
* 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);
}
/**
* Sets the identity for the current realm.
* @param string $host Host to which realm applies.
* @param string $realm Full name of realm.
* @param string $username Username for realm.
* @param string $password Password for realm.
* @access public
*/
/**
* Sets the identity for the current realm.
* @param string $host Host to which realm applies.
* @param string $realm Full name of realm.
* @param string $username Username for realm.
* @param string $password Password for realm.
* @access public
*/
function setIdentity($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.
* @param string $method GET, POST, etc.
* @param string/SimpleUrl $url Target to fetch.
* @param SimpleFormEncoding $parameters Additional parameters for request.
* @return SimpleHttpResponse Hopefully the target page.
* @access public
*/
function &fetchResponse($method, $url, $parameters = false) {
if ($method != 'POST') {
$url->addRequestParameters($parameters);
$parameters = false;
/**
* Fetches a URL as a response object. Will keep trying if redirected.
* It will also collect authentication realm information.
* @param string/SimpleUrl $url Target to fetch.
* @param SimpleEncoding $encoding Additional parameters for request.
* @return SimpleHttpResponse Hopefully the target page.
* @access public
*/
function &fetchResponse($url, $encoding) {
if ($encoding->getMethod() != 'POST') {
$url->addRequestParameters($encoding);
$encoding->clear();
}
$response = &$this->_fetchWhileRedirected($method, $url, $parameters);
$response = &$this->_fetchWhileRedirected($url, $encoding);
if ($headers = $response->getHeaders()) {
if ($headers->isChallenge()) {
$this->_authenticator->addRealm(
@ -361,19 +365,18 @@
return $response;
}
/**
* Fetches the page until no longer redirected or
* until the redirect limit runs out.
* @param string $method GET, POST, etc.
* @param SimpleUrl $url Target to fetch.
* @param SimpelFormEncoding $parameters Additional parameters for request.
* @return SimpleHttpResponse Hopefully the target page.
* @access private
*/
function &_fetchWhileRedirected($method, $url, $parameters) {
/**
* Fetches the page until no longer redirected or
* until the redirect limit runs out.
* @param SimpleUrl $url Target to fetch.
* @param SimpelFormEncoding $encoding Additional parameters for request.
* @return SimpleHttpResponse Hopefully the target page.
* @access private
*/
function &_fetchWhileRedirected($url, $encoding) {
$redirects = 0;
do {
$response = &$this->_fetch($method, $url, $parameters);
$response = &$this->_fetch($url, $encoding);
if ($response->isError()) {
return $response;
}
@ -384,100 +387,87 @@
if (! $headers->isRedirect()) {
break;
}
$method = 'GET';
$parameters = false;
$encoding = new SimpleGetEncoding();
} while (! $this->_isTooManyRedirects(++$redirects));
return $response;
}
/**
* Actually make the web request.
* @param string $method GET, POST, etc.
* @param SimpleUrl $url Target to fetch.
* @param SimpleFormEncoding $parameters Additional parameters for request.
* @return SimpleHttpResponse Headers and hopefully content.
* @access protected
*/
function &_fetch($method, $url, $parameters) {
if (! $parameters) {
$parameters = new SimpleFormEncoding();
}
$request = &$this->_createRequest($method, $url, $parameters);
return $request->fetch($this->_connection_timeout);
/**
* Actually make the web request.
* @param SimpleUrl $url Target to fetch.
* @param SimpleFormEncoding $encoding Additional parameters for request.
* @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;
}
/**
* Creates a full page request.
* @param string $method Fetching method.
* @param SimpleUrl $url Target to fetch as url object.
* @param SimpleFormEncoding $parameters POST/GET parameters.
* @return SimpleHttpRequest New request.
* @access private
*/
function &_createRequest($method, $url, $parameters) {
$request = &$this->_createHttpRequest($method, $url, $parameters);
/**
* Creates a full page request.
* @param SimpleUrl $url Target to fetch as url object.
* @param SimpleFormEncoding $encoding POST/GET parameters.
* @return SimpleHttpRequest New request.
* @access private
*/
function &_createRequest($url, $encoding) {
$request = &$this->_createHttpRequest($url, $encoding);
$this->_addAdditionalHeaders($request);
$this->_cookie_jar->addHeaders($request, $url);
$this->_authenticator->addHeaders($request, $url);
return $request;
}
/**
* Builds the appropriate HTTP request object.
* @param string $method Fetching method.
* @param SimpleUrl $url Target to fetch as url object.
* @param SimpleFormEncoding $parameters POST/GET parameters.
* @return SimpleHttpRequest New request object.
* @access protected
*/
function &_createHttpRequest($method, $url, $parameters) {
if ($method == 'POST') {
$request = &new SimpleHttpRequest(
$this->_createRoute($url),
'POST',
$parameters);
return $request;
}
if ($parameters) {
$url->addRequestParameters($parameters);
}
return new SimpleHttpRequest($this->_createRoute($url), $method);
/**
* Builds the appropriate HTTP request object.
* @param SimpleUrl $url Target to fetch as url object.
* @param SimpleFormEncoding $parameters POST/GET parameters.
* @return SimpleHttpRequest New request object.
* @access protected
*/
function &_createHttpRequest($url, $encoding) {
$request = &new SimpleHttpRequest($this->_createRoute($url), $encoding);
return $request;
}
/**
* 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
*/
/**
* 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) {
return new SimpleProxyRoute(
$route = &new SimpleProxyRoute(
$url,
$this->_proxy,
$this->_proxy_username,
$this->_proxy_password);
} else {
$route = &new SimpleRoute($url);
}
return new SimpleRoute($url);
return $route;
}
/**
* Adds additional manual headers.
* @param SimpleHttpRequest $request Outgoing request.
* @access private
*/
/**
* Adds additional manual headers.
* @param SimpleHttpRequest $request Outgoing request.
* @access private
*/
function _addAdditionalHeaders(&$request) {
foreach ($this->_additional_headers as $header) {
$request->addHeaderLine($header);
}
}
/**
* Extracts new cookies into the cookie jar.
* @param SimpleUrl $url Target to fetch as url object.
* @param array $cookies New cookies.
* @access private
*/
/**
* Extracts new cookies into the cookie jar.
* @param SimpleUrl $url Target to fetch as url object.
* @param array $cookies New cookies.
* @access private
*/
function _addCookiesToJar($url, $cookies) {
foreach ($cookies as $cookie) {
if ($url->getHost()) {

File diff suppressed because it is too large Load diff

View file

@ -1,57 +1,57 @@
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**#@+
* include other SimpleTest class files
*/
/**#@+
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/scorer.php');
/**#@-*/
/**#@-*/
/**
* Creates the XML needed for remote communication
* by SimpleTest.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Creates the XML needed for remote communication
* by SimpleTest.
* @package SimpleTest
* @subpackage UnitTester
*/
class XmlReporter extends SimpleReporter {
var $_indent;
var $_namespace;
/**
* Does nothing yet.
* @access public
*/
/**
* Does nothing yet.
* @access public
*/
function XmlReporter($namespace = false, $indent = ' ') {
$this->SimpleReporter();
$this->_namespace = ($namespace ? $namespace . ':' : '');
$this->_indent = $indent;
}
/**
* Calculates the pretty printing indent level
* from the current level of nesting.
* @param integer $offset Extra indenting level.
* @return string Leading space.
* @access protected
*/
/**
* Calculates the pretty printing indent level
* from the current level of nesting.
* @param integer $offset Extra indenting level.
* @return string Leading space.
* @access protected
*/
function _getIndent($offset = 0) {
return str_repeat(
$this->_indent,
count($this->getTestList()) + $offset);
}
/**
* Converts character string to parsed XML
* entities string.
* @param string text Unparsed character data.
* @return string Parsed character data.
* @access public
*/
/**
* Converts character string to parsed XML
* entities string.
* @param string text Unparsed character data.
* @return string Parsed character data.
* @access public
*/
function toParsedXml($text) {
return str_replace(
array('&', '<', '>', '"', '\''),
@ -59,12 +59,12 @@
$text);
}
/**
* Paints the start of a group test.
* @param string $test_name Name of test that is starting.
* @param integer $size Number of test cases starting.
* @access public
*/
/**
* Paints the start of a group test.
* @param string $test_name Name of test that is starting.
* @param integer $size Number of test cases starting.
* @access public
*/
function paintGroupStart($test_name, $size) {
parent::paintGroupStart($test_name, $size);
print $this->_getIndent();
@ -75,22 +75,22 @@
"</" . $this->_namespace . "name>\n";
}
/**
* Paints the end of a group test.
* @param string $test_name Name of test that is ending.
* @access public
*/
/**
* Paints the end of a group test.
* @param string $test_name Name of test that is ending.
* @access public
*/
function paintGroupEnd($test_name) {
print $this->_getIndent();
print "</" . $this->_namespace . "group>\n";
parent::paintGroupEnd($test_name);
}
/**
* Paints the start of a test case.
* @param string $test_name Name of test that is starting.
* @access public
*/
/**
* Paints the start of a test case.
* @param string $test_name Name of test that is starting.
* @access public
*/
function paintCaseStart($test_name) {
parent::paintCaseStart($test_name);
print $this->_getIndent();
@ -101,22 +101,22 @@
"</" . $this->_namespace . "name>\n";
}
/**
* Paints the end of a test case.
* @param string $test_name Name of test that is ending.
* @access public
*/
/**
* Paints the end of a test case.
* @param string $test_name Name of test that is ending.
* @access public
*/
function paintCaseEnd($test_name) {
print $this->_getIndent();
print "</" . $this->_namespace . "case>\n";
parent::paintCaseEnd($test_name);
}
/**
* Paints the start of a test method.
* @param string $test_name Name of test that is starting.
* @access public
*/
/**
* Paints the start of a test method.
* @param string $test_name Name of test that is starting.
* @access public
*/
function paintMethodStart($test_name) {
parent::paintMethodStart($test_name);
print $this->_getIndent();
@ -127,23 +127,23 @@
"</" . $this->_namespace . "name>\n";
}
/**
* Paints the end of a test method.
* @param string $test_name Name of test that is ending.
* @param integer $progress Number of test cases ending.
* @access public
*/
/**
* Paints the end of a test method.
* @param string $test_name Name of test that is ending.
* @param integer $progress Number of test cases ending.
* @access public
*/
function paintMethodEnd($test_name) {
print $this->_getIndent();
print "</" . $this->_namespace . "test>\n";
parent::paintMethodEnd($test_name);
}
/**
* Increments the pass count.
* @param string $message Message is ignored.
* @access public
*/
/**
* Increments the pass count.
* @param string $message Message is ignored.
* @access public
*/
function paintPass($message) {
parent::paintPass($message);
print $this->_getIndent(1);
@ -152,11 +152,11 @@
print "</" . $this->_namespace . "pass>\n";
}
/**
* Increments the fail count.
* @param string $message Message is ignored.
* @access public
*/
/**
* Increments the fail count.
* @param string $message Message is ignored.
* @access public
*/
function paintFail($message) {
parent::paintFail($message);
print $this->_getIndent(1);
@ -165,12 +165,12 @@
print "</" . $this->_namespace . "fail>\n";
}
/**
* Paints a PHP error or exception.
* @param string $message Message is ignored.
* @access public
* @abstract
*/
/**
* Paints a PHP error or exception.
* @param string $message Message is ignored.
* @access public
* @abstract
*/
function paintException($message) {
parent::paintException($message);
print $this->_getIndent(1);
@ -179,11 +179,11 @@
print "</" . $this->_namespace . "exception>\n";
}
/**
* Paints a simple supplementary message.
* @param string $message Text to display.
* @access public
*/
/**
* Paints a simple supplementary message.
* @param string $message Text to display.
* @access public
*/
function paintMessage($message) {
parent::paintMessage($message);
print $this->_getIndent(1);
@ -192,12 +192,12 @@
print "</" . $this->_namespace . "message>\n";
}
/**
* Paints a formatted ASCII message such as a
* variable dump.
* @param string $message Text to display.
* @access public
*/
/**
* Paints a formatted ASCII message such as a
* variable dump.
* @param string $message Text to display.
* @access public
*/
function paintFormattedMessage($message) {
parent::paintFormattedMessage($message);
print $this->_getIndent(1);
@ -206,12 +206,12 @@
print "</" . $this->_namespace . "formatted>\n";
}
/**
* Serialises the event object.
* @param string $type Event type as text.
* @param mixed $payload Message or object.
* @access public
*/
/**
* Serialises the event object.
* @param string $type Event type as text.
* @param mixed $payload Message or object.
* @access public
*/
function paintSignal($type, &$payload) {
parent::paintSignal($type, $payload);
print $this->_getIndent(1);
@ -220,13 +220,13 @@
print "</" . $this->_namespace . "signal>\n";
}
/**
* Paints the test document header.
* @param string $test_name First test top level
* to start.
* @access public
* @abstract
*/
/**
* Paints the test document header.
* @param string $test_name First test top level
* to start.
* @access public
* @abstract
*/
function paintHeader($test_name) {
if (! SimpleReporter::inCli()) {
header('Content-type: text/xml');
@ -240,191 +240,191 @@
print "<" . $this->_namespace . "run>\n";
}
/**
* Paints the test document footer.
* @param string $test_name The top level test.
* @access public
* @abstract
*/
/**
* Paints the test document footer.
* @param string $test_name The top level test.
* @access public
* @abstract
*/
function paintFooter($test_name) {
print "</" . $this->_namespace . "run>\n";
}
}
/**
* Accumulator for incoming tag. Holds the
* incoming test structure information for
* later dispatch to the reporter.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Accumulator for incoming tag. Holds the
* incoming test structure information for
* later dispatch to the reporter.
* @package SimpleTest
* @subpackage UnitTester
*/
class NestingXmlTag {
var $_name;
var $_attributes;
/**
* Sets the basic test information except
* the name.
* @param hash $attributes Name value pairs.
* @access public
*/
/**
* Sets the basic test information except
* the name.
* @param hash $attributes Name value pairs.
* @access public
*/
function NestingXmlTag($attributes) {
$this->_name = false;
$this->_attributes = $attributes;
}
/**
* Sets the test case/method name.
* @param string $name Name of test.
* @access public
*/
/**
* Sets the test case/method name.
* @param string $name Name of test.
* @access public
*/
function setName($name) {
$this->_name = $name;
}
/**
* Accessor for name.
* @return string Name of test.
* @access public
*/
/**
* Accessor for name.
* @return string Name of test.
* @access public
*/
function getName() {
return $this->_name;
}
/**
* Accessor for attributes.
* @return hash All attributes.
* @access protected
*/
/**
* Accessor for attributes.
* @return hash All attributes.
* @access protected
*/
function _getAttributes() {
return $this->_attributes;
}
}
/**
* Accumulator for incoming method tag. Holds the
* incoming test structure information for
* later dispatch to the reporter.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Accumulator for incoming method tag. Holds the
* incoming test structure information for
* later dispatch to the reporter.
* @package SimpleTest
* @subpackage UnitTester
*/
class NestingMethodTag extends NestingXmlTag {
/**
* Sets the basic test information except
* the name.
* @param hash $attributes Name value pairs.
* @access public
*/
/**
* Sets the basic test information except
* the name.
* @param hash $attributes Name value pairs.
* @access public
*/
function NestingMethodTag($attributes) {
$this->NestingXmlTag($attributes);
}
/**
* Signals the appropriate start event on the
* listener.
* @param SimpleReporter $listener Target for events.
* @access public
*/
/**
* Signals the appropriate start event on the
* listener.
* @param SimpleReporter $listener Target for events.
* @access public
*/
function paintStart(&$listener) {
$listener->paintMethodStart($this->getName());
}
/**
* Signals the appropriate end event on the
* listener.
* @param SimpleReporter $listener Target for events.
* @access public
*/
/**
* Signals the appropriate end event on the
* listener.
* @param SimpleReporter $listener Target for events.
* @access public
*/
function paintEnd(&$listener) {
$listener->paintMethodEnd($this->getName());
}
}
/**
* Accumulator for incoming case tag. Holds the
* incoming test structure information for
* later dispatch to the reporter.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Accumulator for incoming case tag. Holds the
* incoming test structure information for
* later dispatch to the reporter.
* @package SimpleTest
* @subpackage UnitTester
*/
class NestingCaseTag extends NestingXmlTag {
/**
* Sets the basic test information except
* the name.
* @param hash $attributes Name value pairs.
* @access public
*/
/**
* Sets the basic test information except
* the name.
* @param hash $attributes Name value pairs.
* @access public
*/
function NestingCaseTag($attributes) {
$this->NestingXmlTag($attributes);
}
/**
* Signals the appropriate start event on the
* listener.
* @param SimpleReporter $listener Target for events.
* @access public
*/
/**
* Signals the appropriate start event on the
* listener.
* @param SimpleReporter $listener Target for events.
* @access public
*/
function paintStart(&$listener) {
$listener->paintCaseStart($this->getName());
}
/**
* Signals the appropriate end event on the
* listener.
* @param SimpleReporter $listener Target for events.
* @access public
*/
/**
* Signals the appropriate end event on the
* listener.
* @param SimpleReporter $listener Target for events.
* @access public
*/
function paintEnd(&$listener) {
$listener->paintCaseEnd($this->getName());
}
}
/**
* Accumulator for incoming group tag. Holds the
* incoming test structure information for
* later dispatch to the reporter.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Accumulator for incoming group tag. Holds the
* incoming test structure information for
* later dispatch to the reporter.
* @package SimpleTest
* @subpackage UnitTester
*/
class NestingGroupTag extends NestingXmlTag {
/**
* Sets the basic test information except
* the name.
* @param hash $attributes Name value pairs.
* @access public
*/
/**
* Sets the basic test information except
* the name.
* @param hash $attributes Name value pairs.
* @access public
*/
function NestingGroupTag($attributes) {
$this->NestingXmlTag($attributes);
}
/**
* Signals the appropriate start event on the
* listener.
* @param SimpleReporter $listener Target for events.
* @access public
*/
/**
* Signals the appropriate start event on the
* listener.
* @param SimpleReporter $listener Target for events.
* @access public
*/
function paintStart(&$listener) {
$listener->paintGroupStart($this->getName(), $this->getSize());
}
/**
* Signals the appropriate end event on the
* listener.
* @param SimpleReporter $listener Target for events.
* @access public
*/
/**
* Signals the appropriate end event on the
* listener.
* @param SimpleReporter $listener Target for events.
* @access public
*/
function paintEnd(&$listener) {
$listener->paintGroupEnd($this->getName());
}
/**
* The size in the attributes.
* @return integer Value of size attribute or zero.
* @access public
*/
/**
* The size in the attributes.
* @return integer Value of size attribute or zero.
* @access public
*/
function getSize() {
$attributes = $this->_getAttributes();
if (isset($attributes['SIZE'])) {
@ -434,12 +434,12 @@
}
}
/**
* Parser for importing the output of the XmlReporter.
* Dispatches that output to another reporter.
* @package SimpleTest
* @subpackage UnitTester
*/
/**
* Parser for importing the output of the XmlReporter.
* Dispatches that output to another reporter.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleTestXmlParser {
var $_listener;
var $_expat;
@ -448,12 +448,12 @@
var $_content;
var $_attributes;
/**
* Loads a listener with the SimpleReporter
* interface.
* @param SimpleReporter $listener Listener of tag events.
* @access public
*/
/**
* Loads a listener with the SimpleReporter
* interface.
* @param SimpleReporter $listener Listener of tag events.
* @access public
*/
function SimpleTestXmlParser(&$listener) {
$this->_listener = &$listener;
$this->_expat = &$this->_createParser();
@ -463,13 +463,13 @@
$this->_attributes = array();
}
/**
* Parses a block of XML sending the results to
* the listener.
* @param string $chunk Block of text to read.
* @return boolean True if valid XML.
* @access public
*/
/**
* Parses a block of XML sending the results to
* the listener.
* @param string $chunk Block of text to read.
* @return boolean True if valid XML.
* @access public
*/
function parse($chunk) {
if (! xml_parse($this->_expat, $chunk)) {
trigger_error('XML parse error with ' .
@ -479,11 +479,11 @@
return true;
}
/**
* Sets up expat as the XML parser.
* @return resource Expat handle.
* @access protected
*/
/**
* Sets up expat as the XML parser.
* @return resource Expat handle.
* @access protected
*/
function &_createParser() {
$expat = xml_parser_create();
xml_set_object($expat, $this);
@ -493,57 +493,56 @@
return $expat;
}
/**
* Opens a new test nesting level.
* @return NestedXmlTag The group, case or method tag
* to start.
* @access private
*/
/**
* Opens a new test nesting level.
* @return NestedXmlTag The group, case or method tag
* to start.
* @access private
*/
function _pushNestingTag($nested) {
array_unshift($this->_tag_stack, $nested);
}
/**
* Accessor for current test structure tag.
* @return NestedXmlTag The group, case or method tag
* being parsed.
* @access private
*/
/**
* Accessor for current test structure tag.
* @return NestedXmlTag The group, case or method tag
* being parsed.
* @access private
*/
function &_getCurrentNestingTag() {
return $this->_tag_stack[0];
}
/**
* Ends a nesting tag.
* @return NestedXmlTag The group, case or method tag
* just finished.
* @access private
*/
/**
* Ends a nesting tag.
* @return NestedXmlTag The group, case or method tag
* just finished.
* @access private
*/
function _popNestingTag() {
return array_shift($this->_tag_stack);
}
/**
* Test if tag is a leaf node with only text content.
* @param string $tag XML tag name.
* @return @boolean True if leaf, false if nesting.
* @private
*/
/**
* Test if tag is a leaf node with only text content.
* @param string $tag XML tag name.
* @return @boolean True if leaf, false if nesting.
* @private
*/
function _isLeaf($tag) {
return in_array(
$tag,
array('NAME', 'PASS', 'FAIL', 'EXCEPTION', 'MESSAGE', 'FORMATTED', 'SIGNAL'));
return in_array($tag, array(
'NAME', 'PASS', 'FAIL', 'EXCEPTION', 'MESSAGE', 'FORMATTED', 'SIGNAL'));
}
/**
* Handler for start of event element.
* @param resource $expat Parser handle.
* @param string $tag Element name.
* @param hash $attributes Name value pairs.
* Attributes without content
* are marked as true.
* @access protected
*/
/**
* Handler for start of event element.
* @param resource $expat Parser handle.
* @param string $tag Element name.
* @param hash $attributes Name value pairs.
* Attributes without content
* are marked as true.
* @access protected
*/
function _startElement($expat, $tag, $attributes) {
$this->_attributes = $attributes;
if ($tag == 'GROUP') {
@ -558,12 +557,12 @@
}
}
/**
* End of element event.
* @param resource $expat Parser handle.
* @param string $tag Element name.
* @access protected
*/
/**
* End of element event.
* @param resource $expat Parser handle.
* @param string $tag Element name.
* @access protected
*/
function _endElement($expat, $tag) {
$this->_in_content_tag = false;
if (in_array($tag, array('GROUP', 'CASE', 'TEST'))) {
@ -590,12 +589,12 @@
}
}
/**
* Content between start and end elements.
* @param resource $expat Parser handle.
* @param string $text Usually output messages.
* @access protected
*/
/**
* Content between start and end elements.
* @param resource $expat Parser handle.
* @param string $text Usually output messages.
* @access protected
*/
function _addContent($expat, $text) {
if ($this->_in_content_tag) {
$this->_content .= $text;
@ -603,12 +602,12 @@
return true;
}
/**
* XML and Doctype handler. Discards all such content.
* @param resource $expat Parser handle.
* @param string $default Text of default content.
* @access protected
*/
/**
* XML and Doctype handler. Discards all such content.
* @param resource $expat Parser handle.
* @param string $default Text of default content.
* @access protected
*/
function _default($expat, $default) {
}
}