+";
+ $root=new TestFolder($rootPath,$rootPath,$rootUri);
+ echo $root->getHtml();
+ echo "\n";
+}
+
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/framework/utApplication.php b/tests/UnitTests/framework/utApplication.php
new file mode 100644
index 00000000..603f9fc3
--- /dev/null
+++ b/tests/UnitTests/framework/utApplication.php
@@ -0,0 +1,25 @@
+pass();
+ }
+ chdir($dir);
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/framework/utComponent.php b/tests/UnitTests/framework/utComponent.php
new file mode 100644
index 00000000..2683652a
--- /dev/null
+++ b/tests/UnitTests/framework/utComponent.php
@@ -0,0 +1,224 @@
+_text;
+ }
+
+ public function setText($value)
+ {
+ $this->_text=$value;
+ }
+
+ public function getObject()
+ {
+ if(!$this->_object)
+ {
+ $this->_object=new NewComponent;
+ $this->_object->_text='object text';
+ }
+ return $this->_object;
+ }
+
+ public function onMyEvent($param)
+ {
+ $this->raiseEvent('MyEvent',$this,$param);
+ }
+
+ public function myEventHandler($sender,$param)
+ {
+ $this->_eventHandled=true;
+ }
+
+ public function isEventHandled()
+ {
+ return $this->_eventHandled;
+ }
+}
+
+class utComponent extends UnitTestCase
+{
+ protected $component;
+
+ public function setUp()
+ {
+ $this->component=new NewComponent;
+ }
+
+ public function tearDown()
+ {
+ $this->component=null;
+ }
+
+ public function testHasProperty()
+ {
+ $this->assertTrue($this->component->hasProperty('Text'));
+ $this->assertTrue($this->component->hasProperty('text'));
+ $this->assertFalse($this->component->hasProperty('Caption'));
+ }
+
+ public function testCanGetProperty()
+ {
+ $this->assertTrue($this->component->canGetProperty('Text'));
+ $this->assertTrue($this->component->canGetProperty('text'));
+ $this->assertFalse($this->component->canGetProperty('Caption'));
+ }
+
+ public function testCanSetProperty()
+ {
+ $this->assertTrue($this->component->canSetProperty('Text'));
+ $this->assertTrue($this->component->canSetProperty('text'));
+ $this->assertFalse($this->component->canSetProperty('Caption'));
+ }
+
+ public function testGetProperty()
+ {
+ $this->assertTrue('default'===$this->component->Text);
+ try
+ {
+ $value2=$this->component->Caption;
+ $this->fail('exception not raised when getting undefined property');
+ }
+ catch(TInvalidOperationException $e)
+ {
+ $this->pass();
+ }
+ }
+
+ public function testSetProperty()
+ {
+ $value='new value';
+ $this->component->Text=$value;
+ $text=$this->component->Text;
+ $this->assertTrue($value===$this->component->Text);
+ try
+ {
+ $this->component->NewMember=$value;
+ $this->fail('exception not raised when setting undefined property');
+ }
+ catch(TInvalidOperationException $e)
+ {
+ $this->pass();
+ }
+ }
+
+ public function testGetPropertyByPath()
+ {
+ $this->assertTrue('object text'===$this->component->getPropertyByPath('Object.Text'));
+ }
+
+ public function testSetPropertyByPath()
+ {
+ $this->component->setPropertyByPath('Object.Text','new object text');
+ $this->assertEqual('new object text',$this->component->getPropertyByPath('Object.Text'));
+ }
+
+ public function testHasEvent()
+ {
+ $this->assertTrue($this->component->hasEvent('MyEvent'));
+ $this->assertTrue($this->component->hasEvent('myevent'));
+ $this->assertFalse($this->component->hasEvent('YourEvent'));
+ }
+
+ public function testHasEventHandler()
+ {
+ $this->assertFalse($this->component->hasEventHandler('MyEvent'));
+ $this->component->attachEventHandler('MyEvent','foo');
+ $this->assertTrue($this->component->hasEventHandler('MyEvent'));
+ }
+
+ public function testGetEventHandlers()
+ {
+ $list=$this->component->getEventHandlers('MyEvent');
+ $this->assertTrue(($list instanceof TList) && ($list->getCount()===0));
+ $this->component->attachEventHandler('MyEvent','foo');
+ $this->assertTrue(($list instanceof TList) && ($list->getCount()===1));
+ try
+ {
+ $list=$this->component->getEventHandlers('YourEvent');
+ $this->fail('exception not raised when getting event handlers for undefined event');
+ }
+ catch(TInvalidOperationException $e)
+ {
+ $this->pass();
+ }
+ }
+
+ public function testAttachEventHandler()
+ {
+ $this->component->attachEventHandler('MyEvent','foo');
+ $this->assertTrue($this->component->getEventHandlers('MyEvent')->getCount()===1);
+ try
+ {
+ $this->component->attachEventHandler('YourEvent','foo');
+ $this->fail('exception not raised when attaching event handlers for undefined event');
+ }
+ catch(TInvalidOperationException $e)
+ {
+ $this->pass();
+ }
+ $this->component->MyEvent[]='foo2';
+ $this->assertTrue($this->component->getEventHandlers('MyEvent')->getCount()===2);
+ $this->component->getEventHandlers('MyEvent')->add('foo3');
+ $this->assertTrue($this->component->getEventHandlers('MyEvent')->getCount()===3);
+ $this->component->MyEvent[0]='foo4';
+ $this->assertTrue($this->component->getEventHandlers('MyEvent')->getCount()===3);
+ $this->component->getEventHandlers('MyEvent')->addAt(0,'foo5');
+ $this->assertTrue($this->component->MyEvent->Count===4 && $this->component->MyEvent[0]==='foo5');
+ $this->component->MyEvent='foo6';
+ $this->assertTrue($this->component->MyEvent->Count===5 && $this->component->MyEvent[4]==='foo6');
+ }
+
+ public function testRaiseEvent()
+ {
+ $this->component->attachEventHandler('MyEvent',array($this->component,'myEventHandler'));
+ $this->assertFalse($this->component->isEventHandled());
+ $this->component->raiseEvent('MyEvent',$this,null);
+ $this->assertTrue($this->component->isEventHandled());
+ $this->component->attachEventHandler('MyEvent',array($this->component,'Object.myEventHandler'));
+ $this->assertFalse($this->component->Object->isEventHandled());
+ $this->component->raiseEvent('MyEvent',$this,null);
+ $this->assertTrue($this->component->Object->isEventHandled());
+ }
+
+ public function testEvaluateExpression()
+ {
+ $expression="1+2";
+ $this->assertTrue(3===$this->component->evaluateExpression($expression));
+ try
+ {
+ $button=$this->component->evaluateExpression('$this->button');
+ $this->fail('exception not raised when evaluating an invalid exception');
+ }
+ catch(Exception $e)
+ {
+ $this->pass();
+ }
+ }
+
+ public function testEvaluateStatements()
+ {
+ $statements='$a="test string"; echo $a;';
+ $this->assertEqual('test string',$this->component->evaluateStatements($statements));
+ try
+ {
+ $statements='$a=new NewComponent; echo $a->button;';
+ $button=$this->component->evaluateStatements($statements);
+ $this->fail('exception not raised when evaluating an invalid statement');
+ }
+ catch(Exception $e)
+ {
+ $this->pass();
+ }
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/framework/utPradoBase.php b/tests/UnitTests/framework/utPradoBase.php
new file mode 100644
index 00000000..f7861c57
--- /dev/null
+++ b/tests/UnitTests/framework/utPradoBase.php
@@ -0,0 +1,111 @@
+data=$data;
+ }
+}
+
+class utPradoBase extends UnitTestCase
+{
+ public function testFrameworkPath()
+ {
+ $this->assertTrue(FRAMEWORK_DIR===Prado::getFrameworkPath());
+ }
+
+ public function testSerialization()
+ {
+ $object=new TComponent;
+ $number=12345.123;
+ $string='12345\'"';
+ $array=array('123'=>123,'abc'=>'def');
+ $this->assertFalse($object===Prado::unserialize(Prado::serialize($object)));
+ $this->assertTrue(Prado::unserialize(Prado::serialize($object)) instanceof TComponent);
+ $this->assertTrue($number===Prado::unserialize(Prado::serialize($number)));
+ $this->assertTrue($string===Prado::unserialize(Prado::serialize($string)));
+ $this->assertTrue($array===Prado::unserialize(Prado::serialize($array)));
+
+ // test complex object reference structure grandparent <-> parent <-> child
+ $grandp=new testNode('grandp');
+ $parent=new testNode('parent');
+ $child=new testNode('child');
+ $grandp->child=$parent;
+ $parent->child=$child;
+ $child->parent=$parent;
+ $parent->parent=$grandp;
+
+ $newGrandp=Prado::unserialize(Prado::serialize($grandp));
+ $this->assertTrue($newGrandp!==$grandp);
+ $this->assertTrue($newGrandp instanceof testNode);
+ $this->assertTrue($newGrandp->parent===null);
+ $this->assertTrue($newGrandp->data==='grandp');
+
+ $newParent=$newGrandp->child;
+ $this->assertTrue($newParent!==$parent);
+ $this->assertTrue($newParent instanceof testNode);
+ $this->assertTrue($newParent->parent===$newGrandp);
+ $this->assertTrue($newParent->data==='parent');
+
+ $newChild=$newParent->child;
+ $this->assertTrue($newChild!==$child);
+ $this->assertTrue($newChild instanceof testNode);
+ $this->assertTrue($newChild->parent===$newParent);
+ $this->assertTrue($newChild->child===null);
+ $this->assertTrue($newChild->data==='child');
+ }
+
+ public function testCreateComponent()
+ {
+ $this->assertTrue(Prado::createComponent('TComponent') instanceof TComponent);
+ $this->assertTrue(Prado::createComponent('System.TComponent') instanceof TComponent);
+ try
+ {
+ Prado::createComponent('System2.TComponent');
+ $this->fail('exception not raised when creating a nonexistent component');
+ }
+ catch(TInvalidDataValueException $e)
+ {
+ $this->pass();
+ }
+ }
+
+ public function testNamespace()
+ {
+ $this->assertTrue(FRAMEWORK_DIR===Prado::getPathOfAlias('System'));
+ $this->assertTrue(Prado::getPathOfAlias('System2')===null);
+ $testSystem=dirname(__FILE__).'/TestSystem';
+
+ Prado::setPathOfAlias('TestSystem',$testSystem);
+ $this->assertTrue(realpath($testSystem)===Prado::getPathOfAlias('TestSystem'));
+
+ $this->assertTrue(Prado::getPathOfNamespace('TestSystem.*')===realpath($testSystem));
+ $this->assertTrue(Prado::getPathOfNamespace('TestSystem.protected.*')===realpath($testSystem).'/protected');
+ $this->assertTrue(Prado::getPathOfNamespace('TestSystem')===null);
+
+ // test repeatedly using the same namespaces
+ Prado::using('System.*');
+ Prado::using('System.*');
+ Prado::using('System.TComponent');
+ Prado::using('System.TComponent');
+
+ try
+ {
+ Prado::using('System');
+ $this->fail('no exception raised when using an invalid namespace for a directory');
+ }
+ catch(TInvalidDataValueException $e)
+ {
+ $this->pass();
+ }
+ // TODO: using new namespaces to see if classes can be automatically loaded or found
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/CHANGELOG b/tests/UnitTests/simpletest/CHANGELOG
new file mode 100644
index 00000000..e416f9a6
--- /dev/null
+++ b/tests/UnitTests/simpletest/CHANGELOG
@@ -0,0 +1,6 @@
+June 7, 2005, by Qiang Xue (qiang.xue@gmail.com)
+------------------------------------------------
+- changed all class memeber declarations from 'var $varname' to 'private $varname'.
+- removed all reference usages, including creating new objects, returning and passing objects.
+- modified expectation.php line 106 from 'function test($compare, &$nasty=false) {' to 'function test($compare) {'.
+- added HtmlReporterWithCoverage.php
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE b/tests/UnitTests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE
new file mode 100644
index 00000000..357ff092
--- /dev/null
+++ b/tests/UnitTests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE
@@ -0,0 +1,201 @@
+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.
diff --git a/tests/UnitTests/simpletest/HtmlReporterWithCoverage.php b/tests/UnitTests/simpletest/HtmlReporterWithCoverage.php
new file mode 100644
index 00000000..dd900051
--- /dev/null
+++ b/tests/UnitTests/simpletest/HtmlReporterWithCoverage.php
@@ -0,0 +1,268 @@
+painter = $painter;
+ $this->base_dir = $base_dir;
+ }
+
+ function paintHeader($test_name, $charset="UTF-8")
+ {
+ $this->sendNoCacheHeaders();
+ header('Content-Type: text/html; Charset='.$charset);
+ print "\n\n$test_name\n";
+ print "";
+ print "\n";
+ print "\n\n";
+ print "
Total code lines: {$total} Total lines executed: {$executed} ({$percentage}%)
";
+ flush();
+ }
+
+ function paintFooter($test_name)
+ {
+ print "\n\n";
+ }
+
+ static function codelines($file)
+ {
+ $source = file_get_contents($file);
+ $tokens = @token_get_all($source);
+
+ $lines = '';
+
+ foreach ($tokens as $token)
+ {
+ if (is_string($token))
+ {
+ // simple 1-character token
+ $lines .= $token;
+ }
+ else
+ {
+ // token array
+ list($id, $text) = $token;
+
+ switch ($id)
+ {
+ case T_COMMENT:
+ case T_ML_COMMENT: // we've defined this
+ case T_DOC_COMMENT: // and this
+ // no action on comments
+ break;
+
+ default:
+ // anything else -> output "as is"
+ //echo $text;
+ $lines .= $text;
+ break;
+ }
+ }
+ }
+
+ $lines = preg_replace('/\\n\s*$/m',"",$lines);
+ $codelines = explode("\n",$lines);
+ $count = 0;
+ $patterns[] = '^\s*{\s*$';
+ $patterns[] = '<\?';
+ $patterns[] = '^\s*(private|protected|public)\s+\$';
+ $pattern = '/'.implode('|', $patterns).'/';
+ foreach($codelines as $line)
+ {
+ if(!preg_match($pattern, $line))
+ $count++;
+ }
+ return $count;
+ //var_dump($codelines);
+ //return count($codelines);
+ }
+}
+
+?>
diff --git a/tests/UnitTests/simpletest/LICENSE b/tests/UnitTests/simpletest/LICENSE
new file mode 100644
index 00000000..78d032ad
--- /dev/null
+++ b/tests/UnitTests/simpletest/LICENSE
@@ -0,0 +1,49 @@
+The Open Group Test Suite License
+
+Preamble
+
+The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications.
+
+Testing is essential for proper development and maintenance of standards-based products.
+
+For buyers: adequate conformance testing leads to reduced integration costs and protection of investments in applications, software and people.
+
+For software developers: conformance testing of platforms and middleware greatly reduces the cost of developing and maintaining multi-platform application software.
+
+For suppliers: In-depth testing increases customer satisfaction and keeps development and support costs in check. API conformance is highly measurable and suppliers who claim it must be able to substantiate that claim.
+
+As such, since these are benchmark measures of conformance, we feel the integrity of test tools is of importance. In order to preserve the integrity of the existing conformance modes of this test package and to permit recipients of modified versions of this package to run the original test modes, this license requires that the original test modes be preserved.
+
+If you find a bug in one of the standards mode test cases, please let us know so we can feed this back into the original, and also raise any specification issues with the appropriate bodies (for example the POSIX committees).
+
+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.)
+* "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.
+
+2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version.
+
+3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least the following:
+
+rename any non-standard executables and testcases so the names do not conflict with standard executables and testcases, which must also be provided, and provide a separate manual page for each non-standard executable and testcase that clearly documents how it differs from the Standard Version.
+
+4. You may distribute the programs of this Package in object code or executable form, provided that you do at least the following:
+
+accompany any non-standard executables and testcases with their corresponding Standard Version executables and testcases, giving the non-standard executables and testcases non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version.
+
+5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own.
+
+6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package.
+
+7.Subroutines supplied by you and linked into this Package shall not be considered part of this Package.
+
+8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission.
+
+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
diff --git a/tests/UnitTests/simpletest/README b/tests/UnitTests/simpletest/README
new file mode 100644
index 00000000..b8dd6d1a
--- /dev/null
+++ b/tests/UnitTests/simpletest/README
@@ -0,0 +1,110 @@
+SimpleTest
+==========
+You probably got this package from...
+http://sourceforge.net/projects/simpletest/
+
+If there is no licence agreement with this package please download
+a version from the location above. You must read and accept that
+licence to use this software. The file is titled simply LICENSE.
+
+What is it? It's a framework for unit testing, web site testing and
+mock objects for PHP 4.2.0+.
+
+If you have used JUnit you will find this PHP unit testing version very
+similar. Also included is a mock objects and server stubs generator.
+The stubs can have return values set for different arguments, can have
+sequences set also by arguments and can return items by reference.
+The mocks inherit all of this functionality and can also have
+expectations set, again in sequences and for different arguments.
+
+A web tester similar in concept to JWebUnit is also included. There is no
+JavaScript or tables support, but forms, authentication, cookies and
+frames are handled.
+
+You are not tied to just using SimpleTest, though. The mocks and stubs
+will work with other test frameworks and SimpleTest can use other
+framework's (PHPUnit, PEAR::PhpUnit) test cases as it's own. The
+web browser part of the web tester can also be used independently either
+in other testers or as part of a scripting solution.
+
+You can see a release schedule at http://www.lastcraft.com/overview.php
+which is also copied to the documentation folder with this release.
+A full PHPDocumenter API documentation exists at
+http://simpletest.sourceforge.net/.
+
+The user interface is minimal
+in the extreme, but a lot of information flows from the test suite.
+After version 1.0 we will release a better web UI, but we are leaving XUL
+and GTk versions to volunteers as everybody has their own opinion
+on a good GUI, and we don't want to discourage development by shipping
+one with the toolkit.
+
+You are looking at a first full release. The unit tests for SimpleTest
+itself can be run here...
+
+simpletest/test/unit_tests.php
+
+And tests involving live network connections as well are here...
+
+simpletest/test/all_tests.php
+
+The full tests will typically overrun the 8Mb limit usually allowed
+to a PHP process. A workaround is to run the tests on the command
+with a custom php.ini file if you do not have access to your server
+version.
+
+You will have to edit the all_tests.php file if you are accesssing
+the internet through a proxy server. See the comments in all_tests.php
+for instructions.
+
+The full tests read some test data from the LastCraft site. If the site
+is down or has been modified for a later version then you will get
+spurious errors. A unit_tests.php failure on the other hand would be
+very serious. As far as we know we haven't yet managed to check in any
+test failures so please correct us if you find one.
+
+Even if all of the tests run please verify that your existing test suites
+also function as expected. If they don't see the file...
+
+HELP_MY_TESTS_DONT_WORK_ANYMORE
+
+This contains information on interface changes. It also points out
+deprecated interfaces so you should read this even if all of
+your current tests appear to run.
+
+There is a documentation folder which contains the core reference information
+in English and French, although this information is fairly basic.
+You can find a tutorial on http://www.lastcraft.com/first_test_tutorial.php
+to get you started and this material will eventually become included
+with the project documentation. A French translation exists at
+http://www.onpk.net/index.php/2005/01/12/254-tutoriel-simpletest-decouvrir-les-tests-unitaires.
+
+If you download and use and possibly even extend this tool, please let us
+know. Any feedback, even bad, is always welcome and we will work to get
+your suggestions into the version one release. Ideally please send your
+comments to...
+
+simpletest-support@lists.sourceforge.net
+
+...so that others can read them too. We usually try to respond within 48
+hours.
+
+There is no change log as yet except at Sourceforge. You can visit the
+release notes to see the completed TODO list after each cycle and also the
+status of any bugs, but if the bug is recent then it will be fixed in CVS only.
+The CVS check-ins always have all the tests passing and so CVS snapshots should
+be pretty usable, although the code may not look so good internally.
+
+Oh, yes. It is called "Simple" because it should be simple to
+use. We intend to add a complete set of tools for a test first
+and "test as you code" type of development. "Simple" does not
+mean "Lite" in this context.
+
+Thanks to everyone who has sent comments and offered suggestions. They
+really are invaluable, but sadly you are too many to mention in full.
+Thanks to all on the advanced PHP forum on SitePoint, especially Harry
+Feucks. Early adopters are always an inspiration.
+
+yours Marcus Baker, Jason Sweat and Perrick Penet.
+--
+marcus@lastcraft.com
diff --git a/tests/UnitTests/simpletest/VERSION b/tests/UnitTests/simpletest/VERSION
new file mode 100644
index 00000000..d69d4fac
--- /dev/null
+++ b/tests/UnitTests/simpletest/VERSION
@@ -0,0 +1 @@
+1.0
diff --git a/tests/UnitTests/simpletest/authentication.php b/tests/UnitTests/simpletest/authentication.php
new file mode 100644
index 00000000..6ec7bc0c
--- /dev/null
+++ b/tests/UnitTests/simpletest/authentication.php
@@ -0,0 +1,219 @@
+_type = $type;
+ $this->_root = $url->getBasePath();
+ $this->_username = false;
+ $this->_password = false;
+ }
+
+ /**
+ * Adds another location to the realm.
+ * @param SimpleUrl $url Somewhere in realm.
+ * @access public
+ */
+ function stretch($url) {
+ $this->_root = $this->_getCommonPath($this->_root, $url->getPath());
+ }
+
+ /**
+ * 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);
+ for ($i = 0; $i < min(count($first), count($second)); $i++) {
+ if ($first[$i] != $second[$i]) {
+ return implode('/', array_slice($first, 0, $i)) . '/';
+ }
+ }
+ 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
+ */
+ function setIdentity($username, $password) {
+ $this->_username = $username;
+ $this->_password = $password;
+ }
+
+ /**
+ * 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
+ */
+ 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
+ */
+ function isWithin($url) {
+ return (strpos($url->getBasePath(), $this->_root) === 0);
+ }
+ }
+
+ /**
+ * Manages security realms.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleAuthenticator {
+ protected $_realms;
+
+ /**
+ * Clears the realms.
+ * @access public
+ */
+ function SimpleAuthenticator() {
+ $this->restartSession();
+ }
+
+ /**
+ * 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
+ */
+ 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
+ */
+ 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
+ */
+ function _findRealmFromUrl($url) {
+ if (! isset($this->_realms[$url->getHost()])) {
+ return false;
+ }
+ foreach ($this->_realms[$url->getHost()] as $name => $realm) {
+ if ($realm->isWithin($url)) {
+ return $realm;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Presents the appropriate headers for this location.
+ * @param SimpleHttpRequest $request Request to modify.
+ * @param SimpleUrl $url Base of realm.
+ * @access public
+ */
+ function addHeaders($request, $url) {
+ if ($url->getUsername() && $url->getPassword()) {
+ $username = $url->getUsername();
+ $password = $url->getPassword();
+ } elseif ($realm = $this->_findRealmFromUrl($url)) {
+ $username = $realm->getUsername();
+ $password = $realm->getPassword();
+ } else {
+ return;
+ }
+ $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
+ */
+ function addBasicHeaders($request, $username, $password) {
+ if ($username && $password) {
+ $request->addHeaderLine(
+ 'Authorization: Basic ' . base64_encode("$username:$password"));
+ }
+ }
+ }
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/browser.php b/tests/UnitTests/simpletest/browser.php
new file mode 100644
index 00000000..0e281e5a
--- /dev/null
+++ b/tests/UnitTests/simpletest/browser.php
@@ -0,0 +1,1016 @@
+_sequence = array();
+ $this->_position = -1;
+ }
+
+ /**
+ * Test for no entries yet.
+ * @return boolean True if empty.
+ * @access private
+ */
+ function _isEmpty() {
+ return ($this->_position == -1);
+ }
+
+ /**
+ * Test for being at the beginning.
+ * @return boolean True if first.
+ * @access private
+ */
+ function _atBeginning() {
+ return ($this->_position == 0) && ! $this->_isEmpty();
+ }
+
+ /**
+ * Test for being at the last entry.
+ * @return boolean True if last.
+ * @access private
+ */
+ function _atEnd() {
+ return ($this->_position + 1 >= count($this->_sequence)) && ! $this->_isEmpty();
+ }
+
+ /**
+ * Adds a successfully fetched page to the history.
+ * @param string $method GET or POST.
+ * @param SimpleUrl $url URL of fetch.
+ * @param SimpleFormEncoding $parameters Any post data with the fetch.
+ * @access public
+ */
+ function recordEntry($method, $url, $parameters) {
+ $this->_dropFuture();
+ array_push(
+ $this->_sequence,
+ array('method' => $method, 'url' => $url, 'parameters' => $parameters));
+ $this->_position++;
+ }
+
+ /**
+ * Last fetching method for current history
+ * position.
+ * @return string GET or POST for this point in
+ * the history.
+ * @access public
+ */
+ function getMethod() {
+ if ($this->_isEmpty()) {
+ return false;
+ }
+ return $this->_sequence[$this->_position]['method'];
+ }
+
+ /**
+ * Last fully qualified URL for current history
+ * position.
+ * @return SimpleUrl URL for this position.
+ * @access public
+ */
+ function getUrl() {
+ if ($this->_isEmpty()) {
+ return false;
+ }
+ return $this->_sequence[$this->_position]['url'];
+ }
+
+ /**
+ * Parameters of last fetch from current history
+ * position.
+ * @return SimpleFormEncoding Post parameters.
+ * @access public
+ */
+ function getParameters() {
+ if ($this->_isEmpty()) {
+ return false;
+ }
+ return $this->_sequence[$this->_position]['parameters'];
+ }
+
+ /**
+ * Step back one place in the history. Stops at
+ * the first page.
+ * @return boolean True if any previous entries.
+ * @access public
+ */
+ function back() {
+ if ($this->_isEmpty() || $this->_atBeginning()) {
+ return false;
+ }
+ $this->_position--;
+ return true;
+ }
+
+ /**
+ * Step forward one place. If already at the
+ * latest entry then nothing will happen.
+ * @return boolean True if any future entries.
+ * @access public
+ */
+ function forward() {
+ if ($this->_isEmpty() || $this->_atEnd()) {
+ return false;
+ }
+ $this->_position++;
+ return true;
+ }
+
+ /**
+ * Ditches all future entries beyond the current
+ * point.
+ * @access private
+ */
+ function _dropFuture() {
+ if ($this->_isEmpty()) {
+ return;
+ }
+ while (! $this->_atEnd()) {
+ array_pop($this->_sequence);
+ }
+ }
+ }
+
+ /**
+ * Simulated web browser. This is an aggregate of
+ * the user agent, the HTML parsing, request history
+ * and the last header set.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleBrowser {
+ protected $_user_agent;
+ protected $_page;
+ protected $_history;
+ protected $_ignore_frames;
+ protected $_maximum_nested_frames;
+
+ /**
+ * Starts with a fresh browser with no
+ * cookie or any other state information. The
+ * exception is that a default proxy will be
+ * set up if specified in the options.
+ * @access public
+ */
+ function SimpleBrowser() {
+ $this->_user_agent = $this->_createUserAgent();
+ $this->_user_agent->useProxy(
+ SimpleTestOptions::getDefaultProxy(),
+ SimpleTestOptions::getDefaultProxyUsername(),
+ SimpleTestOptions::getDefaultProxyPassword());
+ $this->_page = new SimplePage();
+ $this->_history = $this->_createHistory();
+ $this->_ignore_frames = false;
+ $this->_maximum_nested_frames = DEFAULT_MAX_NESTED_FRAMES;
+ }
+
+ /**
+ * Creates the underlying user agent.
+ * @return SimpleFetcher Content fetcher.
+ * @access protected
+ */
+ function _createUserAgent() {
+ return new SimpleUserAgent();
+ }
+
+ /**
+ * Creates a new empty history list.
+ * @return SimpleBrowserHistory New list.
+ * @access protected
+ */
+ function _createHistory() {
+ return new SimpleBrowserHistory();
+ }
+
+ /**
+ * Disables frames support. Frames will not be fetched
+ * and the frameset page will be used instead.
+ * @access public
+ */
+ function ignoreFrames() {
+ $this->_ignore_frames = true;
+ }
+
+ /**
+ * Enables frames support. Frames will be fetched from
+ * now on.
+ * @access public
+ */
+ function useFrames() {
+ $this->_ignore_frames = false;
+ }
+
+ /**
+ * Parses the raw content into a page. Will load further
+ * frame pages unless frames are disabled.
+ * @param SimpleHttpResponse $response Response from fetch.
+ * @param integer $depth Nested frameset depth.
+ * @return SimplePage Parsed HTML.
+ * @access protected
+ */
+ function _parse($response, $depth = 0) {
+ $builder = new SimplePageBuilder();
+ $page = $builder->parse($response);
+ if ($this->_ignore_frames || ! $page->hasFrames() || ($depth > $this->_maximum_nested_frames)) {
+ return $page;
+ }
+ $frameset = new SimpleFrameset($page);
+ foreach ($page->getFrameset() as $key => $url) {
+ $frame = $this->_fetch('GET', $url, array(), $depth + 1);
+ $frameset->addFrame($frame, $key);
+ }
+ return $frameset;
+ }
+
+ /**
+ * Fetches a page.
+ * @param string $method GET or POST.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param SimpleFormEncoding $parameters POST parameters.
+ * @param integer $depth Nested frameset depth protection.
+ * @return SimplePage Parsed page.
+ * @access private
+ */
+ function _fetch($method, $url, $parameters, $depth = 0) {
+ $response = $this->_user_agent->fetchResponse($method, $url, $parameters);
+ if ($response->isError()) {
+ return new SimplePage($response);
+ }
+ return $this->_parse($response, $depth);
+ }
+
+ /**
+ * Fetches a page or a single frame if that is the current
+ * focus.
+ * @param string $method GET or POST.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param SimpleFormEncoding $parameters POST parameters.
+ * @return string Raw content of page.
+ * @access private
+ */
+ function _load($method, $url, $parameters = false) {
+ $frame = $url->getTarget();
+ if (! $frame || ! $this->_page->hasFrames() || (strtolower($frame) == '_top')) {
+ return $this->_loadPage($method, $url, $parameters);
+ }
+ return $this->_loadFrame(array($frame), $method, $url, $parameters);
+ }
+
+ /**
+ * Fetches a page and makes it the current page/frame.
+ * @param string $method GET or POST.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param SimpleFormEncoding $parameters POST parameters.
+ * @return string Raw content of page.
+ * @access private
+ */
+ function _loadPage($method, $url, $parameters = false) {
+ $this->_page = $this->_fetch(strtoupper($method), $url, $parameters);
+ $this->_history->recordEntry(
+ $this->_page->getMethod(),
+ $this->_page->getUrl(),
+ $this->_page->getRequestData());
+ return $this->_page->getRaw();
+ }
+
+ /**
+ * Fetches a frame into the existing frameset replacing the
+ * original.
+ * @param array $frames List of names to drill down.
+ * @param string $method GET or POST.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param SimpleFormEncoding $parameters POST parameters.
+ * @return string Raw content of page.
+ * @access private
+ */
+ function _loadFrame($frames, $method, $url, $parameters = false) {
+ $page = $this->_fetch(strtoupper($method), $url, $parameters);
+ $this->_page->setFrame($frames, $page);
+ }
+
+ /**
+ * Removes expired and temporary cookies as if
+ * the browser was closed and re-opened.
+ * @param string/integer $date Time when session restarted.
+ * If omitted then all persistent
+ * cookies are kept.
+ * @access public
+ */
+ function restart($date = false) {
+ $this->_user_agent->restart($date);
+ }
+
+ /**
+ * Adds a header to every fetch.
+ * @param string $header Header line to add to every
+ * request until cleared.
+ * @access public
+ */
+ function addHeader($header) {
+ $this->_user_agent->addHeader($header);
+ }
+
+ /**
+ * Ages the cookies by the specified time.
+ * @param integer $interval Amount in seconds.
+ * @access public
+ */
+ function ageCookies($interval) {
+ $this->_user_agent->ageCookies($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
+ */
+ function setCookie($name, $value, $host = false, $path = '/', $expiry = false) {
+ $this->_user_agent->setCookie($name, $value, $host, $path, $expiry);
+ }
+
+ /**
+ * 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) {
+ return $this->_user_agent->getCookieValue($host, $path, $name);
+ }
+
+ /**
+ * Reads the current cookies for the current URL.
+ * @param string $name Key of cookie to find.
+ * @return string Null if there is no current URL, false
+ * if the cookie is not set.
+ * @access public
+ */
+ function getCurrentCookieValue($name) {
+ return $this->_user_agent->getBaseCookieValue($name, $this->_page->getUrl());
+ }
+
+ /**
+ * 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->_user_agent->setMaximumRedirects($max);
+ }
+
+ /**
+ * Sets the maximum number of nesting of framed pages
+ * within a framed page to prevent loops.
+ * @param integer $max Highest depth allowed.
+ * @access public
+ */
+ function setMaximumNestedFrames($max) {
+ $this->_maximum_nested_frames = $max;
+ }
+
+ /**
+ * Sets the socket timeout for opening a connection.
+ * @param integer $timeout Maximum time in seconds.
+ * @access public
+ */
+ function setConnectionTimeout($timeout) {
+ $this->_user_agent->setConnectionTimeout($timeout);
+ }
+
+ /**
+ * 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 = false, $password = false) {
+ $this->_user_agent->useProxy($proxy, $username, $password);
+ }
+
+ /**
+ * Fetches the page content with a HEAD request.
+ * Will affect cookies, but will not change the base URL.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param hash/SimpleFormEncoding $parameters Additional parameters for
+ * HEAD request.
+ * @return boolean True if successful.
+ * @access public
+ */
+ function head($url, $parameters = false) {
+ if (! is_object($url)) {
+ $url = new SimpleUrl($url);
+ }
+ if (is_array($parameters)) {
+ $parameters = new SimpleFormEncoding($parameters);
+ }
+ if ($this->getUrl()) {
+ $url = $url->makeAbsolute($this->getUrl());
+ }
+ $response = $this->_user_agent->fetchResponse(
+ 'HEAD',
+ $url,
+ $parameters);
+ return ! $response->isError();
+ }
+
+ /**
+ * Fetches the page content with a simple GET request.
+ * @param string/SimpleUrl $url Target to fetch.
+ * @param hash/SimpleFormEncoding $parameters Additional parameters for
+ * GET request.
+ * @return string Content of page or false.
+ * @access public
+ */
+ function get($url, $parameters = false) {
+ if (! is_object($url)) {
+ $url = new SimpleUrl($url);
+ }
+ if (is_array($parameters)) {
+ $parameters = new SimpleFormEncoding($parameters);
+ }
+ if ($this->getUrl()) {
+ $url = $url->makeAbsolute($this->getUrl());
+ }
+ return $this->_load('GET', $url, $parameters);
+ }
+
+ /**
+ * Fetches the page content with a POST request.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param hash/SimpleFormEncoding $parameters POST parameters.
+ * @return string Content of page.
+ * @access public
+ */
+ function post($url, $parameters = false) {
+ if (! is_object($url)) {
+ $url = new SimpleUrl($url);
+ }
+ if (is_array($parameters)) {
+ $parameters = new SimpleFormEncoding($parameters);
+ }
+ if ($this->getUrl()) {
+ $url = $url->makeAbsolute($this->getUrl());
+ }
+ return $this->_load('POST', $url, $parameters);
+ }
+
+ /**
+ * Equivalent to hitting the retry button on the
+ * browser. Will attempt to repeat the page fetch. If
+ * there is no history to repeat it will give false.
+ * @return string/boolean Content if fetch succeeded
+ * else false.
+ * @access public
+ */
+ function retry() {
+ $frames = $this->_page->getFrameFocus();
+ if (count($frames) > 0) {
+ $this->_loadFrame(
+ $frames,
+ $this->_page->getMethod(),
+ $this->_page->getUrl(),
+ $this->_page->getRequestData());
+ return $this->_page->getRaw();
+ }
+ if ($method = $this->_history->getMethod()) {
+ $this->_page = $this->_fetch(
+ $method,
+ $this->_history->getUrl(),
+ $this->_history->getParameters());
+ return $this->_page->getRaw();
+ }
+ return false;
+ }
+
+ /**
+ * Equivalent to hitting the back button on the
+ * browser. The browser history is unchanged on
+ * failure.
+ * @return boolean True if history entry and
+ * fetch succeeded
+ * @access public
+ */
+ function back() {
+ if (! $this->_history->back()) {
+ return false;
+ }
+ $content = $this->retry();
+ if (! $content) {
+ $this->_history->forward();
+ }
+ return $content;
+ }
+
+ /**
+ * Equivalent to hitting the forward button on the
+ * browser. The browser history is unchanged on
+ * failure.
+ * @return boolean True if history entry and
+ * fetch succeeded
+ * @access public
+ */
+ function forward() {
+ if (! $this->_history->forward()) {
+ return false;
+ }
+ $content = $this->retry();
+ if (! $content) {
+ $this->_history->back();
+ }
+ return $content;
+ }
+
+ /**
+ * Retries a request after setting the authentication
+ * for the current realm.
+ * @param string $username Username for realm.
+ * @param string $password Password for realm.
+ * @return boolean True if successful fetch. Note
+ * that authentication may still have
+ * failed.
+ * @access public
+ */
+ function authenticate($username, $password) {
+ if (! $this->_page->getRealm()) {
+ return false;
+ }
+ $url = $this->_page->getUrl();
+ if (! $url) {
+ return false;
+ }
+ $this->_user_agent->setIdentity(
+ $url->getHost(),
+ $this->_page->getRealm(),
+ $username,
+ $password);
+ return $this->retry();
+ }
+
+ /**
+ * Accessor for a breakdown of the frameset.
+ * @return array Hash tree of frames by name
+ * or index if no name.
+ * @access public
+ */
+ function getFrames() {
+ return $this->_page->getFrames();
+ }
+
+ /**
+ * Accessor for current frame focus. Will be
+ * false if no frame has focus.
+ * @return integer/string/boolean Label if any, otherwise
+ * the position in the frameset
+ * or false if none.
+ * @access public
+ */
+ function getFrameFocus() {
+ return $this->_page->getFrameFocus();
+ }
+
+ /**
+ * Sets the focus by index. The integer index starts from 1.
+ * @param integer $choice Chosen frame.
+ * @return boolean True if frame exists.
+ * @access public
+ */
+ function setFrameFocusByIndex($choice) {
+ return $this->_page->setFrameFocusByIndex($choice);
+ }
+
+ /**
+ * Sets the focus by name.
+ * @param string $name Chosen frame.
+ * @return boolean True if frame exists.
+ * @access public
+ */
+ function setFrameFocus($name) {
+ return $this->_page->setFrameFocus($name);
+ }
+
+ /**
+ * Clears the frame focus. All frames will be searched
+ * for content.
+ * @access public
+ */
+ function clearFrameFocus() {
+ return $this->_page->clearFrameFocus();
+ }
+
+ /**
+ * Accessor for last error.
+ * @return string Error from last response.
+ * @access public
+ */
+ function getTransportError() {
+ return $this->_page->getTransportError();
+ }
+
+ /**
+ * Accessor for current MIME type.
+ * @return string MIME type as string; e.g. 'text/html'
+ * @access public
+ */
+ function getMimeType() {
+ return $this->_page->getMimeType();
+ }
+
+ /**
+ * Accessor for last response code.
+ * @return integer Last HTTP response code received.
+ * @access public
+ */
+ function getResponseCode() {
+ return $this->_page->getResponseCode();
+ }
+
+ /**
+ * Accessor for last Authentication type. Only valid
+ * straight after a challenge (401).
+ * @return string Description of challenge type.
+ * @access public
+ */
+ function getAuthentication() {
+ return $this->_page->getAuthentication();
+ }
+
+ /**
+ * Accessor for last Authentication realm. Only valid
+ * straight after a challenge (401).
+ * @return string Name of security realm.
+ * @access public
+ */
+ function getRealm() {
+ return $this->_page->getRealm();
+ }
+
+ /**
+ * Accessor for current URL of page or frame if
+ * focused.
+ * @return string Location of current page or frame as
+ * a string.
+ */
+ function getUrl() {
+ $url = $this->_page->getUrl();
+ return $url ? $url->asString() : false;
+ }
+
+ /**
+ * Accessor for raw bytes sent down the wire.
+ * @return string Original text sent.
+ * @access public
+ */
+ function getRequest() {
+ return $this->_page->getRequest();
+ }
+
+ /**
+ * Accessor for raw header information.
+ * @return string Header block.
+ * @access public
+ */
+ function getHeaders() {
+ return $this->_page->getHeaders();
+ }
+
+ /**
+ * Accessor for raw page information.
+ * @return string Original text content of web page.
+ * @access public
+ */
+ function getContent() {
+ return $this->_page->getRaw();
+ }
+
+ /**
+ * Accessor for plain text version of the page.
+ * @return string Normalised text representation.
+ * @access public
+ */
+ function getContentAsText() {
+ return $this->_page->getText();
+ }
+
+ /**
+ * Accessor for parsed title.
+ * @return string Title or false if no title is present.
+ * @access public
+ */
+ function getTitle() {
+ return $this->_page->getTitle();
+ }
+
+ /**
+ * Accessor for a list of all fixed links in current page.
+ * @return array List of urls with scheme of
+ * http or https and hostname.
+ * @access public
+ */
+ function getAbsoluteUrls() {
+ return $this->_page->getAbsoluteUrls();
+ }
+
+ /**
+ * Accessor for a list of all relative links.
+ * @return array List of urls without hostname.
+ * @access public
+ */
+ function getRelativeUrls() {
+ return $this->_page->getRelativeUrls();
+ }
+
+ /**
+ * Sets all form fields with that name.
+ * @param string $name Name of field in forms.
+ * @param string $value New value of field.
+ * @return boolean True if field exists, otherwise false.
+ * @access public
+ */
+ function setField($name, $value) {
+ return $this->_page->setField($name, $value);
+ }
+
+ /**
+ * Sets all form fields with that id attribute.
+ * @param string/integer $id Id of field in forms.
+ * @param string $value New value of field.
+ * @return boolean True if field exists, otherwise false.
+ * @access public
+ */
+ function setFieldById($id, $value) {
+ return $this->_page->setFieldById($id, $value);
+ }
+
+ /**
+ * Accessor for a form element value within the page.
+ * Finds the first match.
+ * @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) {
+ return $this->_page->getField($name);
+ }
+
+ /**
+ * Accessor for a form element value within the page.
+ * @param string/integer $id Id of field in forms.
+ * @return string/boolean A string if the field is
+ * present, false if unchecked
+ * and null if missing.
+ * @access public
+ */
+ function getFieldById($id) {
+ return $this->_page->getFieldById($id);
+ }
+
+ /**
+ * Clicks the submit button by label. The owning
+ * form will be submitted by this.
+ * @param string $label Button label. An unlabeled
+ * button can be triggered by 'Submit'.
+ * @param hash $additional Additional form data.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickSubmit($label = 'Submit', $additional = false) {
+ if (! ($form = $this->_page->getFormBySubmitLabel($label))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submitButtonByLabel($label, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Clicks the submit button by name attribute. The owning
+ * form will be submitted by this.
+ * @param string $name Button name.
+ * @param hash $additional Additional form data.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickSubmitByName($name, $additional = false) {
+ if (! ($form = $this->_page->getFormBySubmitName($name))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submitButtonByName($name, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Clicks the submit button by ID attribute of the button
+ * itself. The owning form will be submitted by this.
+ * @param string $id Button ID.
+ * @param hash $additional Additional form data.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickSubmitById($id, $additional = false) {
+ if (! ($form = $this->_page->getFormBySubmitId($id))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submitButtonById($id, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Clicks the submit image by some kind of label. Usually
+ * the alt tag or the nearest equivalent. The owning
+ * form will be submitted by this. Clicking outside of
+ * the boundary of the coordinates will result in
+ * a failure.
+ * @param string $label ID attribute of button.
+ * @param integer $x X-coordinate of imaginary click.
+ * @param integer $y Y-coordinate of imaginary click.
+ * @param hash $additional Additional form data.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickImage($label, $x = 1, $y = 1, $additional = false) {
+ if (! ($form = $this->_page->getFormByImageLabel($label))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submitImageByLabel($label, $x, $y, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Clicks the submit image by the name. Usually
+ * the alt tag or the nearest equivalent. The owning
+ * form will be submitted by this. Clicking outside of
+ * the boundary of the coordinates will result in
+ * a failure.
+ * @param string $name Name attribute of button.
+ * @param integer $x X-coordinate of imaginary click.
+ * @param integer $y Y-coordinate of imaginary click.
+ * @param hash $additional Additional form data.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickImageByName($name, $x = 1, $y = 1, $additional = false) {
+ if (! ($form = $this->_page->getFormByImageName($name))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submitImageByName($name, $x, $y, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Clicks the submit image by ID attribute. The owning
+ * form will be submitted by this. Clicking outside of
+ * the boundary of the coordinates will result in
+ * a failure.
+ * @param integer/string $id ID attribute of button.
+ * @param integer $x X-coordinate of imaginary click.
+ * @param integer $y Y-coordinate of imaginary click.
+ * @param hash $additional Additional form data.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickImageById($id, $x = 1, $y = 1, $additional = false) {
+ if (! ($form = $this->_page->getFormByImageId($id))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submitImageById($id, $x, $y, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Submits a form by the ID.
+ * @param string $id The form ID. No submit button value
+ * will be sent.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function submitFormById($id) {
+ if (! ($form = $this->_page->getFormById($id))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submit());
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Follows a link by label. Will click the first link
+ * found with this link text by default, or a later
+ * one if an index is given. The match ignores case and
+ * white space issues.
+ * @param string $label Text between the anchor tags.
+ * @param integer $index Link position counting from zero.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickLink($label, $index = 0) {
+ $urls = $this->_page->getUrlsByLabel($label);
+ if (count($urls) == 0) {
+ return false;
+ }
+ if (count($urls) < $index + 1) {
+ return false;
+ }
+ $this->_load('GET', $urls[$index]);
+ return $this->getContent();
+ }
+
+ /**
+ * Tests to see if a link is present by label.
+ * @param string $label Text of value attribute.
+ * @return boolean True if link present.
+ * @access public
+ */
+ function isLink($label) {
+ return (count($this->_page->getUrlsByLabel($label)) > 0);
+ }
+
+ /**
+ * Follows a link by id attribute.
+ * @param string $id ID attribute value.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickLinkById($id) {
+ if (! ($url = $this->_page->getUrlById($id))) {
+ return false;
+ }
+ $this->_load('GET', $url);
+ return $this->getContent();
+ }
+
+ /**
+ * Tests to see if a link is present by ID attribute.
+ * @param string $id Text of id attribute.
+ * @return boolean True if link present.
+ * @access public
+ */
+ function isLinkById($id) {
+ return (boolean)$this->_page->getUrlById($id);
+ }
+ }
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/docs/en/authentication_documentation.html b/tests/UnitTests/simpletest/docs/en/authentication_documentation.html
new file mode 100644
index 00000000..a83f448b
--- /dev/null
+++ b/tests/UnitTests/simpletest/docs/en/authentication_documentation.html
@@ -0,0 +1,320 @@
+
+
+
+SimpleTest documentation for testing log-in and authentication
+
+
+
+
+ One of the trickiest, and yet most important, areas
+ of testing web sites is the security.
+ Testing these schemes is one of the core goals of
+ the SimpleTest web tester.
+
+ If you fetch a page protected by basic authentication then
+ rather than receiving content, you will instead get a 401
+ header.
+ We can illustrate this with this test...
+
1/1 test cases complete.
+ 0 passes, 0 fails and 0 exceptions.
+
+ We are trying to get away from visual inspection though, and so SimpleTest
+ allows to make automated assertions against the challenge.
+ Here is a thorough test of our header...
+
+ Any one of these tests would normally do on it's own depending
+ on the amount of detail you want to see.
+
+
+ Most of the time we are not interested in testing the
+ authentication itself, but want to get past it to test
+ the pages underneath.
+ As soon as the challenge has been issued we can reply with
+ an authentication response...
+
+ The username and password will now be sent with every
+ subsequent request to that directory and subdirectories.
+ You will have to authenticate again if you step outside
+ the authenticated directory, but SimpleTest is smart enough
+ to merge subdirectories into a common realm.
+
+
+ You can shortcut this step further by encoding the log in
+ details straight into the URL...
+
+ If your username or password has special characters, then you
+ will have to URL encode them or the request will not be parsed
+ correctly.
+ Also this header will not be sent on subsequent requests if
+ you request a page with a fully qualified URL.
+ If you navigate with relative URLs though, the authentication
+ information will be preserved.
+
+
+ Only basic authentication is currently supported and this is
+ only really secure in tandem with HTTPS connections.
+ This is usually enough to protect test server from prying eyes,
+ however.
+ Digest authentication and NTLM authentication may be added
+ in the future.
+
+ Basic authentication doesn't give enough control over the
+ user interface for web developers.
+ More likely this functionality will be coded directly into
+ the web architecture using cookies and complicated timeouts.
+
+ Let's suppose that in fetching this page a cookie has been
+ set with a session ID.
+ We are not going to fill the form in yet, just test that
+ we are tracking the user.
+ Here is the test...
+
+ All we are doing is confirming that the cookie is set.
+ As the value is likely to be rather cryptic it's not
+ really worth testing this.
+
+
+ The rest of the test would be the same as any other form,
+ but we might want to confirm that we still have the same
+ cookie after log-in as before we entered.
+ We wouldn't want to lose track of this after all.
+ Here is a possible test for this...
+
+ If you are testing an authentication system a critical piece
+ of behaviour is what happens when a user logs back in.
+ We would like to simulate closing and reopening a browser...
+
+ The WebTestCase::restart() method will
+ preserve cookies that have unexpired timeouts, but throw away
+ those that are temporary or expired.
+ You can optionally specify the time and date that the restart
+ happened.
+
+
+ Expiring cookies can be a problem.
+ After all, if you have a cookie that expires after an hour,
+ you don't want to stall the test for an hour while the
+ cookie passes it's timeout.
+
+
+ To push the cookies over the hour limit you can age them
+ before you restart the session...
+
+ SimpleTest's web browser component can be used not just
+ outside of the WebTestCase class, but also
+ independently of the SimpleTest framework itself.
+
+ You can use the web browser in PHP scripts to confirm
+ services are up and running, or to extract information
+ from them at a regular basis.
+ For example, here is a small script to extract the current number of
+ open PHP 5 bugs from the PHP web site...
+
+ There are simpler methods to do this particular example in PHP
+ of course.
+ For example you can just use the PHP file()
+ command against what here is a pretty fixed page.
+ However, using the web browser for scripts allows authentication,
+ correct handling of cookies, automatic loading of frames, redirects,
+ form submission and the ability to examine the page headers.
+ Such methods are fragile against a site that is constantly
+ evolving and you would want a more direct way of accessing
+ data in a permanent set up, but for simple tasks this can provide
+ a very rapid solution.
+
+
+ All of the navigation methods used in the
+ WebTestCase
+ are present in the SimpleBrowser class, but
+ the assertions are replaced with simpler accessors.
+ Here is a full list of the page navigation methods...
+
+
+
+
addHeader($header)
Adds a header to every fetch
+
+
+
useProxy($proxy, $username, $password)
Use this proxy from now on
+
+
+
head($url, $parameters)
Perform a HEAD request
+
+
+
get($url, $parameters)
Fetch a page with GET
+
+
+
post($url, $parameters)
Fetch a page with POST
+
+
+
clickLink($label)
Follows a link by label
+
+
+
isLink($label)
See if a link is present by label
+
+
+
clickLinkById($id)
Follows a link by attribute
+
+
+
isLinkById($id)
See if a link is present by attribut
+
+
+
getUrl()
Current URL of page or frame
+
+
+
getTitle()
Page title
+
+
+
getContent()
Raw page or frame
+
+
+
getContentAsText()
HTML removed except for alt text
+
+
+
retry()
Repeat the last request
+
+
+
back()
Use the browser back button
+
+
+
forward()
Use the browser forward button
+
+
+
authenticate($username, $password)
Retry page or frame after a 401 response
+
+
+
restart($date)
Restarts the browser for a new session
+
+
+
ageCookies($interval)
Ages the cookies by the specified time
+
+
+
setCookie($name, $value)
Sets an additional cookie
+
+
+
getCookieValue($host, $path, $name)
Reads the most specific cookie
+
+
+
getCurrentCookieValue($name)
Reads cookie for the current context
+
+
+
+ The methods SimpleBrowser::useProxy() and
+ SimpleBrowser::addHeader() are special.
+ Once called they continue to apply to all subsequent fetches.
+
+
+ At the moment there aren't any methods to list available forms
+ and fields.
+ This will probably be added to later versions of SimpleTest.
+
+
+ Within a page, individual frames can be selected.
+ If no selection is made then all the frames are merged together
+ in one large conceptual page.
+ The content of the current page will be a concatenation of all of the
+ frames in the order that they were specified in the "frameset"
+ tags.
+
+
+
+
getFrames()
A dump of the current frame structure
+
+
+
getFrameFocus()
Current frame label or index
+
+
+
setFrameFocusByIndex($choice)
Select a frame numbered from 1
+
+
+
setFrameFocus($name)
Select frame by label
+
+
+
clearFrameFocus()
Treat all the frames as a single page
+
+
+
+ When focused on a single frame, the content will come from
+ that frame only.
+ This includes links to click and forms to submit.
+
+
+
+ All of this functionality is great when we actually manage to fetch pages,
+ but that doesn't always happen.
+ To help figure out what went wrong, the browser has some methods to
+ aid in debugging...
+
+
+
+
setConnectionTimeout($timeout)
Close the socket on overrun
+
+
+
getRequest()
Raw request header of page or frame
+
+
+
getHeaders()
Raw response header of page or frame
+
+
+
getTransportError()
Any socket level errors in the last fetch
+
+
+
getResponseCode()
HTTP response of page or frame
+
+
+
getMimeType()
Mime type of page or frame
+
+
+
getAuthentication()
Authentication type in 401 challenge header
+
+
+
getRealm()
Authentication realm in 401 challenge header
+
+
+
setMaximumRedirects($max)
Number of redirects before page is loaded anyway
+
+
+
setMaximumNestedFrames($max)
Protection against recursive framesets
+
+
+
ignoreFrames()
Disables frames support
+
+
+
useFrames()
Enables frames support
+
+
+
+ The methods SimpleBrowser::setConnectionTimeout()
+ SimpleBrowser::setMaximumRedirects(),
+ SimpleBrowser::setMaximumNestedFrames(),
+ SimpleBrowser::ignoreFrames() and
+ SimpleBrowser::useFrames() continue to apply
+ to every subsequent request.
+ The other methods are frames aware.
+ This means that if you have an individual frame that is not
+ loading, navigate to it using SimpleBrowser::setFrameFocus()
+ and you can then use SimpleBrowser::getRequest(), etc to
+ see what happened.
+
+
+
+ Anything that could be done in a
+ WebTestCase can
+ now be done in a UnitTestCase.
+ This means that we can freely mix domain object testing with the
+ web interface...
+
+ While this may be a useful temporary expediency, I am not a fan
+ of this type of testing.
+ The testing has cut across application layers, make it twice as
+ likely it will need refactoring when the code changes.
+
+
+ A more useful case of where using the browser directly can be helpful
+ is where the WebTestCase cannot cope.
+ An example is where two browsers are needed at the same time.
+
+
+ For example, say we want to disallow multiple simultaneous
+ usage of a site with the same username.
+ This test case will do the job...
+
+ The default behaviour of the
+ mock objects
+ in
+ SimpleTest
+ is either an identical match on the argument or to allow any argument at all.
+ For almost all tests this is sufficient.
+ Sometimes, though, you want to weaken a test case.
+
+
+ One place where a test can be too tightly coupled is with
+ text matching.
+ Suppose we have a component that outputs a helpful error
+ message when something goes wrong.
+ You want to test that the correct error was sent, but the actual
+ text may be rather long.
+ If you test for the text exactly, then every time the exact wording
+ of the message changes, you will have to go back and edit the test suite.
+
+
+ For example, suppose we have a news service that has failed
+ to connect to its remote source.
+
+class NewsService {
+ ...
+ function publish(&$writer) {
+ if (! $this->isConnected()) {
+ $writer->write('Cannot connect to news service "' .
+ $this->_name . '" at this time. ' .
+ 'Please try again later.');
+ }
+ ...
+ }
+}
+
+ Here it is sending its content to a
+ Writer class.
+ We could test this behaviour with a
+ MockWriter like so...
+
+class TestOfNewsService extends UnitTestCase {
+ ...
+ function testConnectionFailure() {
+ $writer = &new MockWriter($this);
+ $writer->expectOnce('write', array(
+ 'Cannot connect to news service ' .
+ '"BBC News" at this time. ' .
+ 'Please try again later.'));
+
+ $service = &new NewsService('BBC News');
+ $service->publish($writer);
+
+ $writer->tally();
+ }
+}
+
+ This is a good example of a brittle test.
+ If we decide to add additional instructions, such as
+ suggesting an alternative news source, we will break
+ our tests even though no underlying functionality
+ has been altered.
+
+
+ To get around this, we would like to do a regular expression
+ test rather than an exact match.
+ We can actually do this with...
+
+ Instead of passing in the expected parameter to the
+ MockWriter we pass an
+ expectation class called
+ WantedPatternExpectation.
+ The mock object is smart enough to recognise this as special
+ and to treat it differently.
+ Rather than simply comparing the incoming argument to this
+ object, it uses the expectation object itself to
+ perform the test.
+
+
+ The WantedPatternExpectation takes
+ the regular expression to match in its constructor.
+ Whenever a comparison is made by the MockWriter
+ against this expectation class, it will do a
+ preg_match() with this pattern.
+ With our test case above, as long as "cannot connect"
+ appears in the text of the string, the mock will issue a pass
+ to the unit tester.
+ The rest of the text does not matter.
+
+
+ The possible expectation classes are...
+
+
+
+
EqualExpectation
An equality, rather than the stronger identity comparison
+
+
+
NotEqualExpectation
An inequality comparison
+
+
+
IndenticalExpectation
The default mock object check which must match exactly
+
+
+
NotIndenticalExpectation
Inverts the mock object logic
+
+
+
WantedPatternExpectation
Uses a Perl Regex to match a string
+
+
+
NoUnwantedPatternExpectation
Passes only if failing a Perl Regex
+
+
+
IsAExpectation
Checks the type or class name only
+
+
+
NotAExpectation
Opposite of the IsAExpectation
+
+
+
MethodExistsExpectation
Checks a method is available on an object
+
+
+
+ Most take the expected value in the constructor.
+ The exceptions are the pattern matchers, which take a regular expression,
+ and the IsAExpectation and NotAExpectation which takes a type
+ or class name as a string.
+
+
+
+ The expectation classes can be used not just for sending assertions
+ from mock objects, but also for selecting behaviour for either
+ the
+ mock objects
+ or the
+ server stubs.
+ Anywhere a list of arguments is given, a list of expectation objects
+ can be inserted instead.
+
+
+ Suppose we want an authorisation server stub to simulate a successful login
+ only if it receives a valid session object.
+ We can do this as follows...
+
+Stub::generate('Authorisation');
+
+$authorisation = new StubAuthorisation();
+$authorisation->setReturnValue(
+ 'isAllowed',
+ true,
+ array(new IsAExpectation('Session', 'Must be a session')));
+$authorisation->setReturnValue('isAllowed', false);
+
+ We have set the default stub behaviour to return false when
+ isAllowed is called.
+ When we call the method with a single parameter that
+ is a Session object, it will return true.
+ We have also added a second parameter as a message.
+ This will be displayed as part of the mock object
+ failure message if this expectation is the cause of
+ a failure.
+
+
+ This kind of sophistication is rarely useful, but is included for
+ completeness.
+
+ The expectation classes have a very simple structure.
+ So simple that it is easy to create your own versions for
+ commonly used test logic.
+
+
+ As an example here is the creation of a class to test for
+ valid IP addresses.
+ In order to work correctly with the stubs and mocks the new
+ expectation class should extend
+ SimpleExpectation...
+
+class ValidIp extends SimpleExpectation {
+
+ function test($ip) {
+ return (ip2long($ip) != -1);
+ }
+
+ function testMessage($ip) {
+ return "Address [$ip] should be a valid IP address";
+ }
+}
+
+ There are only two methods to implement.
+ The test() method should
+ evaluate to true if the expectation is to pass, and
+ false otherwise.
+ The testMessage() method
+ should simply return some helpful text explaining the test
+ that was carried out.
+
+
+ This class can now be used in place of the earlier expectation
+ classes.
+
+ The SimpleTest unit testing framework
+ also uses the expectation classes internally for the
+ UnitTestCase class.
+ We can also take advantage of these mechanisms to reuse our
+ homebrew expectation classes within the test suites directly.
+
+
+ The most crude way of doing this is to use the
+ SimpleTest::assertExpectation() method to
+ test against it directly...
+
+ This is a little untidy compared with our usual
+ assert...() syntax.
+
+
+ For such a simple case we would normally create a
+ separate assertion method on our test case rather
+ than bother using the expectation class.
+ If we pretend that our expectation is a little more
+ complicated for a moment, so that we want to reuse it,
+ we get...
+
+ It is unlikely we would ever need this degree of control
+ over the testing machinery.
+ It is rare to need the expectations for more than pattern
+ matching.
+ Also, complex expectation classes could make the tests
+ harder to read and debug.
+ These mechanisms are really of most use to authors of systems
+ that will extend the test framework to create their own tool set.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+
+
diff --git a/tests/UnitTests/simpletest/docs/en/form_testing_documentation.html b/tests/UnitTests/simpletest/docs/en/form_testing_documentation.html
new file mode 100644
index 00000000..597db3b0
--- /dev/null
+++ b/tests/UnitTests/simpletest/docs/en/form_testing_documentation.html
@@ -0,0 +1,277 @@
+
+
+
+Simple Test documentation for testing HTML forms
+
+
+
+
+ When a page is fetched by the WebTestCase
+ using get() or
+ post() the page content is
+ automatically parsed.
+ This results in any form controls that are inside <form> tags
+ being available from within the test case.
+ For example, if we have this snippet of HTML...
+
+ We can navigate to this code, via the
+ LastCraft
+ site, with the following test...
+
+class SimpleFormTests extends WebTestCase {
+
+ function testDefaultValue() {
+ $this->get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this->assertField('a', 'A default');
+ }
+}
+
+ Immediately after loading the page all of the HTML controls are set at
+ their default values just as they would appear in the web browser.
+ The assertion tests that a HTML widget exists in the page with the
+ name "a" and that it is currently set to the value
+ "A default"
+
+
+ We could submit the form straight away, but first we'll change
+ the value of the text field and only then submit it...
+
+ Because we didn't specify a method attribute on the form tag, and
+ didn't specify an action either, the test case will follow
+ the usual browser behaviour of submitting the form data as a GET
+ request back to the same location.
+ SimpleTest tries to emulate typical browser behaviour as much as possible,
+ rather than attempting to catch missing attributes on tags.
+ This is because the target of the testing framework is the PHP application
+ logic, not syntax or other errors in the HTML code.
+ For HTML errors, other tools such as
+ HTMLTidy should be used.
+
+
+ If a field is not present in any form, or if an option is unavailable,
+ then WebTestCase::setField() will return
+ false.
+ For example, suppose we wish to verify that a "Superuser"
+ option is not present in this form...
+
+<strong>Select type of user to add:</strong>
+<select name="type">
+ <option>Subscriber</option>
+ <option>Author</option>
+ <option>Administrator</option>
+</select>
+
+ The selection will not be changed on a failure to set
+ a widget value.
+
+
+ Here is the full list of widgets currently supported...
+
+
Text fields, including hidden and password fields.
+
Submit buttons including the button tag, although not yet reset buttons
+
Text area. This includes text wrapping behaviour.
+
Checkboxes, including multiple checkboxes in the same form.
+
Drop down selections, including multiple selects.
+
Radio buttons.
+
Images.
+
+
+
+ Although most standard HTML widgets are catered for by SimpleTest's
+ built in parser, it is unlikely that JavaScript will be implemented
+ anytime soon.
+
+ SimpleTest can cope with two types of multivalue controls: Multiple
+ selection drop downs, and multiple checkboxes with the same name
+ within a form.
+ The multivalue nature of these means that setting and testing
+ are slightly different.
+ Using checkboxes as an example...
+
+ Instead of setting the field to a single value, we give it a list
+ of values.
+ We do the same when testing expected values.
+ We can then write other test code to confirm the effect of this, perhaps
+ by logging in as that user and attempting an update.
+
+
+ If you want to test a form handler, but have not yet written
+ or do not have access to the form itself, you can create a
+ form submission by hand.
+
+ As many cases as needed can appear in a single file.
+ They should include any code they need, such as the library
+ being tested, but none of the simple test libraries.
+
+
+ If you have extended any test cases, you can include them
+ as well.
+
+ The FileTester class does
+ not contain any actual tests, but is a base class for other
+ test cases.
+ For this reason we use the
+ SimpleTestOptions::ignore() directive
+ to tell the upcoming group test to ignore it.
+ This directive can appear anywhere in the file and works
+ when a whole file of test cases is loaded (see below).
+ We will call this sample file_test.php.
+
+
+ Next we create a group test file, called say group_test.php.
+ You will think of a better name I am sure.
+ We will add the test file using a safe method...
+
+ This instantiates the test case before the test suite is
+ run.
+ This could get a little expensive with a large number of test
+ cases, so another method is provided that will only
+ instantiate the class when it is needed...
+
+ The problem with this method is that for every test case
+ that we add we will have
+ to require_once() the test code
+ file and manually instantiate each and every test case.
+ We can save a lot of typing with...
+
+ What happens here is that the GroupTest
+ class has done the require_once()
+ for us.
+ It then checks to see if any new test case classes
+ have been created by the new file and automatically adds
+ them to the group test.
+ Now all we have to do is add each new file.
+
+
+ There are two things that could go wrong and which require care...
+
+
+ The file could already have been parsed by PHP and so no
+ new classes will have been added. You should make
+ sure that the test cases are only included in this file
+ and no others.
+
+
+ New test case extension classes that get included will be
+ placed in the group test and run also.
+ You will need to add a SimpleTestOptions::ignore()
+ directive for these classes or make sure that they are included
+ before the GroupTest::addTestFile()
+ line.
+
+ The above method places all of the test cases into one large group.
+ For larger projects though this may not be flexible enough; you
+ may want to group the tests in all sorts of ways.
+
+
+ To get a more flexible group test we can subclass
+ GroupTest and then instantiate it as needed...
+
+ This effectively names the test in the constructor and then
+ adds our test cases and a single group below.
+ Of course we can add more than one group at this point.
+ We can now invoke the tests from a separate runner file...
+
+ If we still wish to run the original group test and we
+ don't want all of these little runner files, we can
+ put the test runner code around guard bars when we create
+ each group.
+
+ This approach requires the guard to be set when including
+ the group test file, but this is still less hassle than
+ lots of separate runner files.
+ You include the same guard on the top level tests to make sure
+ that run() will run once only
+ from the top level script that has been invoked.
+
+ If you already have unit tests for your code or are extending external
+ classes that have tests, it is unlikely that all of the test cases
+ are in SimpleTest format.
+ Fortunately it is possible to incorporate test cases from other
+ unit testers directly into SimpleTest group tests.
+
+
+ Say we have the following
+ PhpUnit
+ test case in the file config_test.php...
+
+ The PEAR test cases can be freely mixed with SimpleTest
+ ones even in the same test file,
+ but you cannot use SimpleTest assertions in the legacy
+ test case versions.
+ This is done as a check that you are not accidently making
+ your test cases completely dependent on SimpleTest.
+ You may want to do a PEAR release of your library for example
+ which would mean shipping it with valid PEAR::PhpUnit test
+ cases.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+
+
diff --git a/tests/UnitTests/simpletest/docs/en/index.html b/tests/UnitTests/simpletest/docs/en/index.html
new file mode 100644
index 00000000..d5a30d31
--- /dev/null
+++ b/tests/UnitTests/simpletest/docs/en/index.html
@@ -0,0 +1,467 @@
+
+
+
+
+ Download the Simple Test testing framework -
+ Unit tests and mock objects for PHP
+
+
+
+
+
+ The following assumes that you are familiar with the concept
+ of unit testing as well as the PHP web development language.
+ It is a guide for the impatient new user of
+ SimpleTest.
+ For fuller documentation, especially if you are new
+ to unit testing see the ongoing
+ documentation, and for
+ example test cases see the
+ unit testing tutorial.
+
+ Amongst software testing tools, a unit tester is the one
+ closest to the developer.
+ In the context of agile development the test code sits right
+ next to the source code as both are written simultaneously.
+ In this context SimpleTest aims to be a complete PHP developer
+ test solution and is called "Simple" because it
+ should be easy to use and extend.
+ It wasn't a good choice of name really.
+ It includes all of the typical functions you would expect from
+ JUnit and the
+ PHPUnit
+ ports, but also adds
+ mock objects.
+ It has some JWebUnit
+ functionality as well.
+ This includes web page navigation, cookie testing and form submission.
+
+
+ The quickest way to demonstrate is with an example.
+
+
+ Let us suppose we are testing a simple file logging class called
+ Log in classes/log.php.
+ We start by creating a test script which we will call
+ tests/log_test.php and populate it as follows...
+
+ Here the simpletest folder is either local or in the path.
+ You would have to edit these locations depending on where you
+ placed the toolset.
+ Next we create a test case...
+
+ Now we have five lines of scaffolding code and still no tests.
+ However from this part on we get return on our investment very quickly.
+ We'll assume that the Log class
+ takes the file name to write to in the constructor and we have
+ a temporary folder in which to place this file...
+
+<?php
+require_once('simpletest/unit_tester.php');
+require_once('simpletest/reporter.php');
+require_once('../classes/log.php');
+
+class TestOfLogging extends UnitTestCase {
+
+ function testCreatingNewFile() {
+ @unlink('/temp/test.log');
+ $log = new Log('/temp/test.log');
+ $this->assertFalse(file_exists('/temp/test.log'));
+ $log->message('Should write this to a file');
+ $this->assertTrue(file_exists('/temp/test.log'));
+ }
+}
+?>
+
+ When a test case runs it will search for any method that
+ starts with the string test
+ and execute that method.
+ We would normally have more than one test method of course.
+ Assertions within the test methods trigger messages to the
+ test framework which displays the result immediately.
+ This immediate response is important, not just in the event
+ of the code causing a crash, but also so that
+ print statements can display
+ their content right next to the test case concerned.
+
+
+ To see these results we have to actually run the tests.
+ If this is the only test case we wish to run we can achieve
+ it with...
+
+<?php
+require_once('simpletest/unit_tester.php');
+require_once('simpletest/reporter.php');
+require_once('../classes/log.php');
+
+class TestOfLogging extends UnitTestCase {
+
+ function testCreatingNewFile() {
+ @unlink('/temp/test.log');
+ $log = new Log('/temp/test.log');
+ $this->assertFalse(file_exists('/temp/test.log'));
+ $log->message('Should write this to a file');
+ $this->assertTrue(file_exists('/temp/test.log'));
+ }
+}
+
+$test = &new TestOfLogging();
+$test->run(new HtmlReporter());
+?>
+
+ Fatal error: Failed opening required '../classes/log.php' (include_path='') in /home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php on line 7
+
+ it means you're missing the classes/Log.php file that could look like...
+
+ It is unlikely in a real application that we will only ever run
+ one test case.
+ This means that we need a way of grouping cases into a test
+ script that can, if need be, run every test in the application.
+
+
+ Our first step is to strip the includes and to undo our
+ previous hack...
+
+<?php
+require_once('../classes/log.php');
+
+class TestOfLogging extends UnitTestCase {
+
+ function testCreatingNewFile() {
+ @unlink('/temp/test.log');
+ $log = new Log('/temp/test.log');
+ $this->assertFalse(file_exists('/temp/test.log'));
+ $log->message('Should write this to a file');
+ $this->assertTrue(file_exists('/temp/test.log'));
+ }
+}
+?>
+
+ Next we create a new file called tests/all_tests.php
+ and insert the following code...
+
+ The method GroupTest::addTestFile()
+ will include the test case file and read any new classes created
+ that are descended from SimpleTestCase, of which
+ UnitTestCase is one example.
+ Just the class names are stored for now, so that the test runner
+ can instantiate the class when it works its way
+ through your test suite.
+
+
+ For this to work properly the test case file should not blindly include
+ any other test case extensions that do not actually run tests.
+ This could result in extra test cases being counted during the test
+ run.
+ Hardly a major problem, but to avoid this inconvenience simply add
+ a SimpleTestOptions::ignore() directive
+ somewhere in the test case file.
+ Also the test case file should not have been included
+ elsewhere or no cases will be added to this group test.
+ This would be a more serious error as if the test case classes are
+ already loaded by PHP the GroupTest::addTestFile()
+ method will not detect them.
+
+
+ To display the results it is necessary only to invoke
+ tests/all_tests.php from the web server.
+
+ Assume that our logging class is tested and completed.
+ Assume also that we are testing another class that is
+ required to write log messages, say a
+ SessionPool.
+ We want to test a method that will probably end up looking
+ like this...
+
+ This test case design is not all bad, but it could be improved.
+ We are spending time fiddling with log files which are
+ not part of our test. Worse, we have created close ties
+ with the Log class and
+ this test.
+ What if we don't use files any more, but use ths
+ syslog library instead?
+ Did you notice the extra carriage return in the message?
+ Was that added by the logger?
+ What if it also added a time stamp or other data?
+
+
+ The only part that we really want to test is that a particular
+ message was sent to the logger.
+ We reduce coupling if we can pass in a fake logging class
+ that simply records the message calls for testing, but
+ takes no action.
+ It would have to look exactly like our original though.
+
+
+ If the fake object doesn't write to a file then we save on deleting
+ the file before and after each test. We could save even more
+ test code if the fake object would kindly run the assertion for us.
+
+
+ Too good to be true?
+ Luckily we can create such an object easily...
+
+ The tally() call is needed to
+ tell the mock object that time is up for the expected call
+ count.
+ Without it the mock would wait forever for the method
+ call to come in without ever actually notifying the test case.
+ The other test will be triggered when the call to
+ message() is invoked on the
+ MockLog object.
+ The mock call will trigger a parameter comparison and then send the
+ resulting pass or fail event to the test display.
+ Wildcards can be included here too so as to prevent tests
+ becoming too specific.
+
+
+ The mock objects in the SimpleTest suite can have arbitrary
+ return values set, sequences of returns, return values
+ selected according to the incoming arguments, sequences of
+ parameter expectations and limits on the number of times
+ a method is to be invoked.
+
+
+ For this test to run the mock objects library must have been
+ included in the test suite, say in all_tests.php.
+
+ One of the requirements of web sites is that they produce web
+ pages.
+ If you are building a project top-down and you want to fully
+ integrate testing along the way then you will want a way of
+ automatically navigating a site and examining output for
+ correctness.
+ This is the job of a web tester.
+
+
+ The web testing in SimpleTest is fairly primitive, there is
+ no JavaScript for example.
+ To give an idea here is a trivial example where a home
+ page is fetched, from which we navigate to an "about"
+ page and then test some client determined content.
+
+<?php
+require_once('simpletest/web_tester.php');
+require_once('simpletest/reporter.php');
+
+class TestOfAbout extends WebTestCase {
+
+ function setUp() {
+ $this->get('http://test-server/index.php');
+ $this->clickLink('About');
+ }
+
+ function testSearchEngineOptimisations() {
+ $this->assertTitle('A long title about us for search engines');
+ $this->assertWantedPattern('/a popular keyphrase/i');
+ }
+}
+$test = &new TestOfAbout();
+$test->run(new HtmlReporter());
+?>
+
+ With this code as an acceptance test you can ensure that
+ the content always meets the specifications of both the
+ developers and the other project stakeholders.
+
+
+
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+ Mock objects have two roles during a test case: actor and critic.
+
+
+ The actor behaviour is to simulate objects that are difficult to
+ set up or time consuming to set up for a test.
+ The classic example is a database connection.
+ Setting up a test database at the start of each test would slow
+ testing to a crawl and would require the installation of the
+ database engine and test data on the test machine.
+ If we can simulate the connection and return data of our
+ choosing we not only win on the pragmatics of testing, but can
+ also feed our code spurious data to see how it responds.
+ We can simulate databases being down or other extremes
+ without having to create a broken database for real.
+ In other words, we get greater control of the test environment.
+
+
+ If mock objects only behaved as actors they would simply be
+ known as server stubs.
+
+
+ However, the mock objects not only play a part (by supplying chosen
+ return values on demand) they are also sensitive to the
+ messages sent to them (via expectations).
+ By setting expected parameters for a method call they act
+ as a guard that the calls upon them are made correctly.
+ If expectations are not met they save us the effort of
+ writing a failed test assertion by performing that duty on our
+ behalf.
+ In the case of an imaginary database connection they can
+ test that the query, say SQL, was correctly formed by
+ the object that is using the connection.
+ Set them up with fairly tight expectations and you will
+ hardly need manual assertions at all.
+
+ In the same way that we create server stubs, all we need is an
+ existing class, say a database connection that looks like this...
+
+class DatabaseConnection {
+ function DatabaseConnection() {
+ }
+
+ function query() {
+ }
+
+ function selectQuery() {
+ }
+}
+
+ The class does not need to have been implemented yet.
+ To create a mock version of the class we need to include the
+ mock object library and run the generator...
+
+ Unlike the generated stubs the mock constructor needs a reference
+ to the test case so that it can dispatch passes and failures while
+ checking its expectations.
+ This means that mock objects can only be used within test cases.
+ Despite this their extra power means that stubs are hardly ever used
+ if mocks are available.
+
+
+ The mock version of a class has all the methods of the original
+ so that operations like
+ $connection->query() are still
+ legal.
+ As with stubs we can replace the default null return values...
+
+$connection->setReturnValue('query', 37);
+
+ Now every time we call
+ $connection->query() we get
+ the result of 37.
+ As with the stubs we can set wildcards and we can overload the
+ wildcard parameter.
+ We can also add extra methods to the mock when generating it
+ and choose our own class name...
+
+ Here the mock will behave as if the setOptions()
+ existed in the original class.
+ This is handy if a class has used the PHP overload()
+ mechanism to add dynamic methods.
+ You can create a special mock to simulate this situation.
+
+
+ All of the patterns available with server stubs are available
+ to mock objects...
+
+class Iterator {
+ function Iterator() {
+ }
+
+ function next() {
+ }
+}
+
+ Again, assuming that this iterator only returns text until it
+ reaches the end, when it returns false, we can simulate it
+ with...
+
+ When next() is called on the
+ mock iterator it will first return "First string",
+ on the second call "Second string" will be returned
+ and on any other call false will
+ be returned.
+ The sequenced return values take precedence over the constant
+ return value.
+ The constant one is a kind of default if you like.
+
+
+ A repeat of the stubbed information holder with name/value pairs...
+
+class Configuration {
+ function Configuration() {
+ }
+
+ function getValue($key) {
+ }
+}
+
+ This is a classic situation for using mock objects as
+ actual configuration will vary from machine to machine,
+ hardly helping the reliability of our tests if we use it
+ directly.
+ The problem though is that all the data comes through the
+ getValue() method and yet
+ we want different results for different keys.
+ Luckily the mocks have a filter system...
+
+ The extra parameter is a list of arguments to attempt
+ to match.
+ In this case we are trying to match only one argument which
+ is the look up key.
+ Now when the mock object has the
+ getValue() method invoked
+ like this...
+
+$config->getValue('db_user')
+
+ ...it will return "admin".
+ It finds this by attempting to match the calling arguments
+ to its list of returns one after another until
+ a complete match is found.
+
+
+ There are times when you want a specific object to be
+ dished out by the mock rather than a copy.
+ Again this is identical to the server stubs mechanism...
+
+ Although the server stubs approach insulates your tests from
+ real world disruption, it is only half the benefit.
+ You can have the class under test receiving the required
+ messages, but is your new class sending correct ones?
+ Testing this can get messy without a mock objects library.
+
+
+ By way of example, suppose we have a
+ SessionPool class that we
+ want to add logging to.
+ Rather than grow the original class into something more
+ complicated, we want to add this behaviour with a decorator (GOF).
+ The SessionPool code currently looks
+ like this...
+
+ Out of all of this, the only class we want to test here
+ is the LoggingSessionPool.
+ In particular we would like to check that the
+ findSession() method is
+ called with the correct session ID in the cookie and that
+ it sent the message "Starting session $cookie"
+ to the logger.
+
+
+ Despite the fact that we are testing only a few lines of
+ production code, here is what we would have to do in a
+ conventional test case:
+
+
Create a log object.
+
Set a directory to place the log file.
+
Set the directory permissions so we can write the log.
+
Create a SessionPool object.
+
Hand start a session, which probably does lot's of things.
+
Invoke findSession().
+
Read the new Session ID (hope there is an accessor!).
+
Raise a test assertion to confirm that the ID matches the cookie.
+
Read the last line of the log file.
+
Pattern match out the extra logging timestamps, etc.
+
Assert that the session message is contained in the text.
+
+ It is hardly surprising that developers hate writing tests
+ when they are this much drudgery.
+ To make things worse, every time the logging format changes or
+ the method of creating new sessions changes, we have to rewrite
+ parts of this test even though this test does not officially
+ test those parts of the system.
+ We are creating headaches for the writers of these other classes.
+
+
+ Instead, here is the complete test method using mock object magic...
+
+ We start by creating a dummy session.
+ We don't have to be too fussy about this as the check
+ for which session we want is done elsewhere.
+ We only need to check that it was the same one that came
+ from the session pool.
+
+
+ findSession() is a factory
+ method the simulation of which is described above.
+ The point of departure comes with the first
+ expectOnce() call.
+ This line states that whenever
+ findSession() is invoked on the
+ mock, it will test the incoming arguments.
+ If it receives the single argument of a string "abc"
+ then a test pass is sent to the unit tester, otherwise a fail is
+ generated.
+ This was the part where we checked that the right session was asked for.
+ The argument list follows the same format as the one for setting
+ return values.
+ You can have wildcards and sequences and the order of
+ evaluation is the same.
+
+
+ If the call is never made then neither a pass nor a failure will
+ generated.
+ To get around this we must tell the mock when the test is over
+ so that the object can decide if the expectation has been met.
+ The unit tester assertion for this is triggered by the
+ tally() call at the end of
+ the test.
+
+
+ We use the same pattern to set up the mock logger.
+ We tell it that it should have
+ message() invoked
+ once only with the argument "Starting session abc".
+ By testing the calling arguments, rather than the logger output,
+ we insulate the test from any display changes in the logger.
+
+
+ We start to run our tests when we create the new
+ LoggingSessionPool and feed
+ it our preset mock objects.
+ Everything is now under our control.
+ Finally we confirm that the
+ $session we gave our decorator
+ is the one that we get back and tell the mocks to run their
+ internal call count tests with the
+ tally() calls.
+
+
+ This is still quite a bit of test code, but the code is very
+ strict.
+ If it still seems rather daunting there is a lot less of it
+ than if we tried this without mocks and this particular test,
+ interactions rather than output, is always more work to set
+ up.
+ More often you will be testing more complex situations without
+ needing this level or precision.
+ Also some of this can be refactored into a test case
+ setUp() method.
+
+
+ Here is the full list of expectations you can set on a mock object
+ in SimpleTest...
+
+
+
+
Expectation
Needs tally()
+
+
+
+
+
expectArguments($method, $args)
+
No
+
+
+
expectArgumentsAt($timing, $method, $args)
+
No
+
+
+
expectCallCount($method, $count)
+
Yes
+
+
+
expectMaximumCallCount($method, $count)
+
No
+
+
+
expectMinimumCallCount($method, $count)
+
Yes
+
+
+
expectNever($method)
+
No
+
+
+
expectOnce($method, $args)
+
Yes
+
+
+
expectAtLeastOnce($method, $args)
+
Yes
+
+
+
+ Where the parameters are...
+
+
$method
+
The method name, as a string, to apply the condition to.
+
$args
+
+ The arguments as a list. Wildcards can be included in the same
+ manner as for setReturn().
+ This argument is optional for expectOnce()
+ and expectAtLeastOnce().
+
+
$timing
+
+ The only point in time to test the condition.
+ The first call starts at zero.
+
+
$count
+
The number of calls expected.
+
+ The method expectMaximumCallCount()
+ is slightly different in that it will only ever generate a failure.
+ It is silent if the limit is never reached.
+
+
+ Like the assertions within test cases, all of the expectations
+ can take a message override as an extra parameter.
+ Also the original failure message can be embedded in the output
+ as "%s".
+
+ There are three approaches to creating mocks including the one
+ that SimpleTest employs.
+ Coding them by hand using a base class, generating them to
+ a file and dynamically generating them on the fly.
+
+
+ Mock objects generated with SimpleTest
+ are dynamic.
+ They are created at run time in memory, using
+ eval(), rather than written
+ out to a file.
+ This makes the mocks easy to create, a one liner,
+ especially compared with hand
+ crafting them in a parallel class hierarchy.
+ The problem is that the behaviour is usually set up in the tests
+ themselves.
+ If the original objects change the mock versions
+ that the tests rely on can get out of sync.
+ This can happen with the parallel hierarchy approach as well,
+ but is far more quickly detected.
+
+
+ The solution, of course, is to add some real integration
+ tests.
+ You don't need very many and the convenience gained
+ from the mocks more than outweighs the small amount of
+ extra testing.
+ You cannot trust code that was only tested with mocks.
+
+
+ If you are still determined to build static libraries of mocks
+ because you want to simulate very specific behaviour, you can
+ achieve the same effect using the SimpleTest class generator.
+ In your library file, say mocks/connection.php for a
+ database connection, create a mock and inherit to override
+ special methods or add presets...
+
+ The generate call tells the class generator to create
+ a class called BasicMockConnection
+ rather than the usual MockConnection.
+ We then inherit from this to get our version of
+ MockConnection.
+ By intercepting in this way we can add behaviour, here setting
+ the default value of query() to be false.
+ By using the default name we make sure that the mock class
+ generator will not recreate a different one when invoked elsewhere in the
+ tests.
+ It never creates a class if it already exists.
+ As long as the above file is included first then all tests
+ that generated MockConnection should
+ now be using our one instead.
+ If we don't get the order right and the mock library
+ creates one first then the class creation will simply fail.
+
+
+ Use this trick if you find you have a lot of common mock behaviour
+ or you are getting frequent integration problems at later
+ stages of testing.
+
+ But at the time of writing it is the only one with mock objects,
+ so are you stuck with it?
+
+
+ No, not at all.
+ SimpleTest is a toolkit and one of those
+ tools is the mock objects which can be employed independently.
+ Suppose you have your own favourite unit tester and all your current
+ test cases are written using it.
+ Pretend that you have called your unit tester PHPUnit (everyone else has)
+ and the core test class looks like this...
+
+ All the assertion() method does
+ is print some fancy output and the boolean assertion parameter determines
+ whether to print a pass or a failure.
+ Let's say that it is used like this...
+
+$unit_test = new PHPUnit();
+$unit_test>assertion('I hope this file exists', file_exists('my_file'));
+
+ How do you use mocks with this?
+
+
+ There is a protected method on the base mock class
+ SimpleMock called
+ _assertTrue() and
+ by overriding this method we can use our own assertion format.
+ We start with a subclass, in say my_mock.php...
+
+ Now instantiating MyMock will create
+ an object that speaks the same language as your tester.
+ The catch is of course that we never create such an object, the
+ code generator does.
+ We need just one more line of code to tell the generator to use
+ your mock instead...
+
+ From now on you just include my_mock.php instead of the
+ default mock_objects.php version and you can introduce
+ mock objects into your existing test suite.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+
+
diff --git a/tests/UnitTests/simpletest/docs/en/overview.html b/tests/UnitTests/simpletest/docs/en/overview.html
new file mode 100644
index 00000000..5047598d
--- /dev/null
+++ b/tests/UnitTests/simpletest/docs/en/overview.html
@@ -0,0 +1,422 @@
+
+
+
+
+ Overview and feature list for the SimpleTest PHP unit tester and web tester
+
+
+
+
+
+ The heart of SimpleTest is a testing framework built around
+ test case classes.
+ These are written as extensions of base test case classes,
+ each extended with methods that actually contain test code.
+ Top level test scripts then invoke the run()
+ methods on every one of these test cases in order.
+ Each test method is written to invoke various assertions that
+ the developer expects to be true such as
+ assertEqual().
+ If the expectation is correct, then a successful result is dispatched to the
+ observing test reporter, but any failure triggers an alert
+ and a description of the mismatch.
+
+ These tools are designed for the developer.
+ Tests are written in the PHP language itself more or less
+ as the application itself is built.
+ The advantage of using PHP itself as the testing language is that
+ there are no new languages to learn, testing can start straight away,
+ and the developer can test any part of the code.
+ Basically, all parts that can be accessed by the application code can also be
+ accessed by the test code if they are in the same language.
+
+
+ The simplest type of test case is the
+ UnitTestCase.
+ This class of test case includes standard tests for equality,
+ references and pattern matching.
+ All these test the typical expectations of what you would
+ expect the result of a function or method to be.
+ This is by far the most common type of test in the daily
+ routine of development, making up about 95% of test cases.
+
+
+ The top level task of a web application though is not to
+ produce correct output from its methods and objects, but
+ to generate web pages.
+ The WebTestCase class tests web
+ pages.
+ It simulates a web browser requesting a page, complete with
+ cookies, proxies, secure connections, authentication, forms, frames and most
+ navigation elements.
+ With this type of test case, the developer can assert that
+ information is present in the page and that forms and
+ sessions are handled correctly.
+
+ The following is a very rough outline of past and future features
+ and their expected point of release.
+ I am afraid it is liable to change without warning as meeting the
+ milestones rather depends on time available.
+ Green stuff has been coded, but not necessarily released yet.
+ If you have a pressing need for a green but unreleased feature
+ then you should check-out the code from sourceforge CVS directly.
+ A released feature is marked as "Done".
+
+
+
+
Feature
Description
Release
+
+
+
+
+
Unit test case
+
Core test case class and assertions
+
Done
+
+
+
Html display
+
Simplest possible display
+
Done
+
+
+
Autoloading of test cases
+
+ Reading a file with test cases and loading them into a
+ group test automatically
+
+
Done
+
+
+
Mock objects code generator
+
+ Objects capable of simulating other objects removing
+ test dependencies
+
+
Done
+
+
+
Server stubs
+
+ Mocks without expectations to be used outside of test cases,
+ e.g. for prototyping
+
+
Done
+
+
+
Integration of other unit testers
+
+ The ability to read and simulate test cases from PHPUnit
+ and PEAR::PhpUnit
+
+
Done
+
+
+
Web test case
+
Basic pattern matching of fetched pages
+
Done
+
+
+
HTML parsing of pages
+
Allows link following and title tag matching
+
Done
+
+
+
Partial mocks
+
+ Mocking parts of a class for testing less than a class
+ or for complex simulations
+
+
Done
+
+
+
Web cookie handling
+
Correct handling of cookies when fetching pages
+
Done
+
+
+
Following redirects
+
Page fetching automatically follows 300 redirects
+
Done
+
+
+
Form parsing
+
Ability to submit simple forms and read default form values
+
Done
+
+
+
Command line interface
+
Test display without the need of a web browser
+
Done
+
+
+
Exposure of expectation classes
+
Can create precise tests with mocks as well as test cases
+
Done
+
+
+
XML output and parsing
+
+ Allows multi host testing and the integration of acceptance
+ testing extensions
+
+
Done
+
+
+
Command line test case
+
Allows testing of utilities and file handling
+
Done
+
+
+
PHP Documentor compatibility
+
Fully generated class level documentation
+
Done
+
+
+
Browser interface
+
+ Exposure of lower level web browser interface for more
+ detailed test cases
+
+
Done
+
+
+
HTTP authentication
+
+ Fetching protected web pages with basic authentication
+ only
+
+
Done
+
+
+
Browser navigation buttons
+
Back, forward and retry
+
Done
+
+
+
SSL support
+
Can connect to https: pages
+
Done
+
+
+
Proxy support
+
Can connect via. common proxies
+
Done
+
+
+
Frames support
+
Handling of frames in web test cases
+
Done
+
+
+
Improved display
+
Better web GUI with tree display of test cases
+
1.1
+
+
+
Localisation
+
Messages abstracted and code generated from XML
+
1.1
+
+
+
File upload testing
+
Can simulate the input type file tag
+
1.1
+
+
+
Mocking interfaces
+
Can generate mock objects to interfaces as well as classes
+
2.0
+
+
+
Testing exceptions
+
Similar to testing PHP errors
+
2.0
+
+
+
XPath searching of elements
+
Can make use of HTML tidy for faster and more flexible content matching
+
2.0
+
+
+
+ PHP5 migraton will start straight after the version 1.1 series,
+ whereupon PHP4 will no longer be supported.
+ SimpleTest is currently compatible with PHP5, but will not
+ make use of all of the new features until version 2.
+
+
+
+ Process is at least as important as tools.
+ The type of process that makes the heaviest use of a developer's
+ testing tool is of course
+ Extreme Programming.
+ This is one of the
+ Agile Methodologies
+ which combine various practices to "flatten the cost curve" of software development.
+ More extreme still is Test Driven Development,
+ where you very strictly adhere to the rule of no coding until you have a test.
+ If you're more of a planner or believe that experience trumps evolution,
+ you may prefer the
+ RUP approach.
+ I haven't tried it, but even I can see that you will need test tools (see figure 9).
+
+
+ Most unit testers clone JUnit to some degree,
+ as far as the interface at least. There is a wealth of information on the
+ JUnit site including the
+ FAQ
+ which contains plenty of general advice on testing.
+ Once you get bitten by the bug you will certainly appreciate the phrase
+ test infected
+ coined by Eric Gamma.
+ If you are still reviewing which unit tester to use the main choices
+ are PHPUnit
+ and Pear PHP::PHPUnit.
+ They currently lack a lot of features found in
+ SimpleTest, but the PEAR
+ version at least has been upgraded for PHP5 and is recommended if you are porting
+ existing JUnit test cases.
+
+
+ Library writers don't seem to ship tests with their code very often
+ which is a shame.
+ Library code that includes tests can be more safely refactored and
+ the test code can act as additional documentation in a fairly standard
+ form.
+ This can save trawling the source code for clues when problems occour,
+ especially when upgrading such a library.
+ Libraries using SimpleTest for their unit testing include
+ WACT and
+ PEAR::XML_HTMLSax.
+
+
+ There is currently a sad lack of material on mock objects, which is a shame
+ as unit testing without them is a lot more work.
+ The original mock objects paper
+ is very Java focused, but still worth a read.
+ As a new technology there are plenty of discussions and debate on how to use mocks,
+ often on Wikis such as
+ Extreme Tuesday
+ or www.mockobjects.com
+ or the original C2 Wiki.
+ Injecting mocks into a class is the main area of debate for which this
+ paper on IBM
+ makes a good starting point.
+
+
+ There are plenty of web testing tools, but most are written in Java and
+ tutorials and advice are rather thin on the ground.
+ The only hope is to look at the documentation for
+ HTTPUnit,
+ HTMLUnit
+ or JWebUnit and hope for clues.
+ There are some XML driven test frameworks, but again most
+ require Java to run.
+ As SimpleTest does not support JavaScript you would probably
+ have to look at these tools anyway if you have highly dynamic
+ pages.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+ A partial mock is simply a pattern to alleviate a specific problem
+ in testing with mock objects,
+ that of getting mock objects into tight corners.
+ It's quite a limited tool and possibly not even a good idea.
+ It is included with SimpleTest because I have found it useful
+ on more than one occasion and has saved a lot of work at that point.
+
+ When one object uses another it is very simple to just pass a mock
+ version in already set up with its expectations.
+ Things are rather tricker if one object creates another and the
+ creator is the one you want to test.
+ This means that the created object should be mocked, but we can
+ hardly tell our class under test to create a mock instead.
+ The tested class doesn't even know it is running inside a test
+ after all.
+
+
+ For example, suppose we are building a telnet client and it
+ needs to create a network socket to pass its messages.
+ The connection method might look something like...
+
+ We would really like to have a mock object version of the socket
+ here, what can we do?
+
+
+ The first solution is to pass the socket in as a parameter,
+ forcing the creation up a level.
+ Having the client handle this is actually a very good approach
+ if you can manage it and should lead to factoring the creation from
+ the doing.
+ In fact, this is one way in which testing with mock objects actually
+ forces you to code more tightly focused solutions.
+ They improve your programming.
+
+ It is pretty obvious though that one level is all you can go.
+ You would hardly want your top level application creating
+ every low level file, socket and database connection ever
+ needed.
+ It wouldn't know the constructor parameters anyway.
+
+
+ The next simplest compromise is to have the created object passed
+ in as an optional parameter...
+
+ The problem with this approach is its untidiness.
+ There is test code in the main class and parameters passed
+ in the test case that are never used.
+ This is a quick and dirty approach, but nevertheless effective
+ in most situations.
+
+
+ The next method is to pass in a factory object to do the creation...
+
+ This is probably the most highly factored answer as creation
+ is now moved into a small specialist class.
+ The networking factory can now be tested separately, but mocked
+ easily when we are testing the telnet class...
+
+ The downside is that we are adding a lot more classes to the
+ library.
+ Also we are passing a lot of factories around which will
+ make the code a little less intuitive.
+ The most flexible solution, but the most complex.
+
+
+ There is a way we can circumvent the problem without creating
+ any new application classes, but it involves creating a subclass
+ when we do the actual testing.
+ Firstly we move the socket creation into its own method...
+
+ Here I have passed the mock in the constructor, but a
+ setter would have done just as well.
+ Note that the mock was set into the object variable
+ before the constructor was chained.
+ This is necessary in case the constructor calls
+ connect().
+ Otherwise it could get a null value from
+ _createSocket().
+
+
+ After the completion of all of this extra work the
+ actual test case is fairly easy.
+ We just test our new class instead...
+
+ The new class is very simple of course.
+ It just sets up a return value, rather like a mock.
+ It would be nice if it also checked the incoming parameters
+ as well.
+ Just like a mock.
+ It seems we are likely to do this often, can
+ we automate the subclass creation?
+
+
+
+ Of course the answer is "yes" or I would have stopped writing
+ this by now!
+ The previous test case was a lot of work, but we can
+ generate the subclass using a similar approach to the mock objects.
+
+
+ Here is the partial mock version of the test...
+
+ The partial mock is a subclass of the original with
+ selected methods "knocked out" with test
+ versions.
+ The generatePartial() call
+ takes three parameters: the class to be subclassed,
+ the new test class name and a list of methods to mock.
+
+
+ Instantiating the resulting objects is slightly tricky.
+ The only constructor parameter of a partial mock is
+ the unit tester reference.
+ As with the normal mock objects this is needed for sending
+ test results in response to checked expectations.
+
+
+ The original constructor is not run yet.
+ This is necessary in case the constructor is going to
+ make use of the as yet unset mocked methods.
+ We set any return values at this point and then run the
+ constructor with its normal parameters.
+ This three step construction of "new", followed
+ by setting up the methods, followed by running the constructor
+ proper is what distinguishes the partial mock code.
+
+
+ Apart from construction, all of the mocked methods have
+ the same features as mock objects and all of the unmocked
+ methods behave as before.
+ We can set expectations very easily...
+
+ The mocked out methods don't have to be factory methods,
+ they could be any sort of method.
+ In this way partial mocks allow us to take control of any part of
+ a class except the constructor.
+ We could even go as far as to mock every method
+ except one we actually want to test.
+
+
+ This last situation is all rather hypothetical, as I haven't
+ tried it.
+ I am open to the possibility, but a little worried that
+ forcing object granularity may be better for the code quality.
+ I personally use partial mocks as a way of overriding creation
+ or for occasional testing of the TemplateMethod pattern.
+
+
+ It's all going to come down to the coding standards of your
+ project to decide which mechanism you use.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+
+
diff --git a/tests/UnitTests/simpletest/docs/en/reporter_documentation.html b/tests/UnitTests/simpletest/docs/en/reporter_documentation.html
new file mode 100644
index 00000000..2794c5ab
--- /dev/null
+++ b/tests/UnitTests/simpletest/docs/en/reporter_documentation.html
@@ -0,0 +1,515 @@
+
+
+
+SimpleTest for PHP test runner and display documentation
+
+
+
+
+ SimpleTest pretty much follows the MVC pattern
+ (Model-View-Controller).
+ The reporter classes are the view and the model is your
+ test cases and their hiearchy.
+ The controller is mostly hidden from the user of
+ SimpleTest unless you want to change how the test cases
+ are actually run, in which case it is possible to
+ override the runner objects from within the test case.
+ As usual with MVC, the controller is mostly undefined
+ and there are other places to control the test run.
+
+ The default test display is minimal in the extreme.
+ It reports success and failure with the conventional red and
+ green bars and shows a breadcrumb trail of test groups
+ for every failed assertion.
+ Here's a fail...
+
+
File test
+ Fail: createnewfile->True assertion failed.
+
1/1 test cases complete.
+ 0 passes, 1 fails and 0 exceptions.
+
+ And here all tests passed...
+
+
File test
+
1/1 test cases complete.
+ 1 passes, 0 fails and 0 exceptions.
+
+ The good news is that there are several points in the display
+ hiearchy for subclassing.
+
+
+ For web page based displays there is the
+ HtmlReporter class with the following
+ signature...
+
+class HtmlReporter extends SimpleReporter {
+ public HtmlReporter($encoding) { ... }
+ public makeDry(boolean $is_dry) { ... }
+ public void paintHeader(string $test_name) { ... }
+ public void sendNoCacheHeaders() { ... }
+ public void paintFooter(string $test_name) { ... }
+ public void paintGroupStart(string $test_name, integer $size) { ... }
+ public void paintGroupEnd(string $test_name) { ... }
+ public void paintCaseStart(string $test_name) { ... }
+ public void paintCaseEnd(string $test_name) { ... }
+ public void paintMethodStart(string $test_name) { ... }
+ public void paintMethodEnd(string $test_name) { ... }
+ public void paintFail(string $message) { ... }
+ public void paintPass(string $message) { ... }
+ public void paintError(string $message) { ... }
+ public void paintException(string $message) { ... }
+ public void paintMessage(string $message) { ... }
+ public void paintFormattedMessage(string $message) { ... }
+ protected string _getCss() { ... }
+ public array getTestList() { ... }
+ public integer getPassCount() { ... }
+ public integer getFailCount() { ... }
+ public integer getExceptionCount() { ... }
+ public integer getTestCaseCount() { ... }
+ public integer getTestCaseProgress() { ... }
+}
+
+ Here is what some of these methods mean. First the display methods
+ that you will probably want to override...
+
+
+ HtmlReporter(string $encoding)
+
+ is the constructor.
+ Note that the unit test sets up the link to the display
+ rather than the other way around.
+ The display is a mostly passive receiver of test events.
+ This allows easy adaption of the display for other test
+ systems beside unit tests, such as monitoring servers.
+ The encoding is the character encoding you wish to
+ display the test output in.
+ In order to correctly render debug output when
+ using the web tester, this should match the encoding
+ of the site you are trying to test.
+ The available character set strings are described in
+ the PHP html_entities()
+ function.
+
+
+ void paintHeader(string $test_name)
+
+ is called once at the very start of the test when the first
+ start event arrives.
+ The first start event is usually delivered by the top level group
+ test and so this is where $test_name
+ comes from.
+ It paints the page titles, CSS, body tag, etc.
+ It returns nothing (void).
+
+
+ void paintFooter(string $test_name)
+
+ Called at the very end of the test to close any tags opened
+ by the page header.
+ By default it also displays the red/green bar and the final
+ count of results.
+ Actually the end of the test happens when a test end event
+ comes in with the same name as the one that started it all
+ at the same level.
+ The tests nest you see.
+ Closing the last test finishes the display.
+
+
+ void paintMethodStart(string $test_name)
+
+ is called at the start of each test method.
+ The name normally comes from method name.
+ The other test start events behave the same way except
+ that the group test one tells the reporter how large
+ it is in number of held test cases.
+ This is so that the reporter can display a progress bar
+ as the runner churns through the test cases.
+
+
+ void paintMethodEnd(string $test_name)
+
+ backs out of the test started with the same name.
+
+
+ void paintFail(string $message)
+
+ paints a failure.
+ By default it just displays the word fail, a breadcrumbs trail
+ showing the current test nesting and the message issued by
+ the assertion.
+
+
+ void paintPass(string $message)
+
+ by default does nothing.
+
+
+ string _getCss()
+
+ Returns the CSS styles as a string for the page header
+ method.
+ Additional styles have to be appended here if you are
+ not overriding the page header.
+ You will want to use this method in an overriden page header
+ if you want to include the original CSS.
+
+
+ There are also some accessors to get information on the current
+ state of the test suite.
+ Use these to enrich the display...
+
+
+ array getTestList()
+
+ is the first convenience method for subclasses.
+ Lists the current nesting of the tests as a list
+ of test names.
+ The first, most deeply nested test, is first in the
+ list and the current test method will be last.
+
+
+ integer getPassCount()
+
+ returns the number of passes chalked up so far.
+ Needed for the display at the end.
+
+
+ integer getFailCount()
+
+ is likewise the number of fails so far.
+
+
+ integer getExceptionCount()
+
+ is likewise the number of errors so far.
+
+
+ integer getTestCaseCount()
+
+ is the total number of test cases in the test run.
+ This includes the grouping tests themselves.
+
+
+ integer getTestCaseProgress()
+
+ is the number of test cases completed so far.
+
+
+ One simple modification is to get the HtmlReporter to display
+ the passes as well as the failures and errors...
+
+ One method that was glossed over was the makeDry()
+ method.
+ If you run this method, with no parameters, on the reporter
+ before the test suite is run no actual test methods
+ will be called.
+ You will still get the events of entering and leaving the
+ test methods and test cases, but no passes or failures etc,
+ because the test code will not actually be executed.
+
+
+ The reason for this is to allow for more sophistcated
+ GUI displays that allow the selection of individual test
+ cases.
+ In order to build a list of possible tests they need a
+ report on the test structure for drawing, say a tree view
+ of the test suite.
+ With a reporter set to dry run that just sends drawing events
+ this is easily accomplished.
+
+ Rather than simply modifying the existing display, you might want to
+ produce a whole new HTML look, or even generate text or XML.
+ Rather than override every method in
+ HtmlReporter we can take one
+ step up the class hiearchy to SimpleReporter
+ in the simple_test.php source file.
+
+
+ A do nothing display, a blank canvas for your own creation, would
+ be...
+
+ SimpleTest also ships with a minimal command line reporter.
+ The interface mimics JUnit to some extent, but paints the
+ failure messages as they arrive.
+ To use the command line reporter simply substitute it
+ for the HTML version...
+
+File test
+1) True assertion failed.
+ in createnewfile
+FAILURES!!!
+Test cases run: 1/1, Failures: 1, Exceptions: 0
+
+
+
+ One of the main reasons for using a command line driven
+ test suite is of using the tester as part of some automated
+ process.
+ To function properly in shell scripts the test script should
+ return a non-zero exit code on failure.
+ If a test suite fails the value false
+ is returned from the SimpleTest::run()
+ method.
+ We can use that result to exit the script with the desired return
+ code...
+
+ Of course we don't really want to create two test scripts,
+ a command line one and a web browser one, for each test suite.
+ The command line reporter includes a method to sniff out the
+ run time environment...
+
+ You can make use of this format with the parser
+ supplied as part of SimpleTest itself.
+ This is called SimpleTestXmlParser and
+ resides in xml.php within the SimpleTest package...
+
+ The $test_output should be the XML format
+ from the XML reporter, and could come from say a command
+ line run of a test case.
+ The parser sends events to the reporter just like any
+ other test run.
+ There are some odd occasions where this is actually useful.
+
+
+ A problem with large test suites is thet they can exhaust
+ the default 8Mb memory limit on a PHP process.
+ By having the test groups output in XML and run in
+ separate processes, the output can be reparsed to
+ aggregate the results into a much smaller footprint top level
+ test.
+
+
+ Because the XML output can come from anywhere, this opens
+ up the possibility of aggregating test runs from remote
+ servers.
+ A test case already exists to do this within the SimpleTest
+ framework, but it is currently experimental...
+
+ The RemoteTestCase takes the actual location
+ of the test runner, basically a web page in XML format.
+ It also takes the URL of a reporter set to do a dry run.
+ This is so that progress can be reported upward correctly.
+ The RemoteTestCase can be added to test suites
+ just like any other group test.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+
+
diff --git a/tests/UnitTests/simpletest/docs/en/server_stubs_documentation.html b/tests/UnitTests/simpletest/docs/en/server_stubs_documentation.html
new file mode 100644
index 00000000..445ba63e
--- /dev/null
+++ b/tests/UnitTests/simpletest/docs/en/server_stubs_documentation.html
@@ -0,0 +1,388 @@
+
+
+
+SimpleTest for PHP server stubs documentation
+
+
+
+
+ This was originally a pattern named by Robert Binder (Testing
+ object-oriented systems: models, patterns, and tools,
+ Addison-Wesley) in 1999.
+ A server stub is a simulation of an object or component.
+ It should exactly replace a component in a system for test
+ or prototyping purposes, but remain lightweight.
+ This allows tests to run more quickly, or if the simulated
+ class has not been written, to run at all.
+
+ All we need is an existing class, say a database connection
+ that looks like this...
+
+class DatabaseConnection {
+ function DatabaseConnection() {
+ }
+
+ function query() {
+ }
+
+ function selectQuery() {
+ }
+}
+
+ The class does not need to have been implemented yet.
+ To create a stub version of the class we need to include the
+ server stub library and run the generator...
+
+ This generates a clone class called
+ StubDatabaseConnection.
+ We can now create instances of the new class within
+ our prototype script...
+
+require_once('simpletest/mock_objects.php');
+require_once('database_connection.php');
+Stub::generate('DatabaseConnection');
+
+$connection = new StubDatabaseConnection();
+
+
+ The stub version of a class has all the methods of the original
+ so that operations like
+ $connection->query() are still
+ legal.
+ The return value will be null,
+ but we can change that with...
+
+$connection->setReturnValue('query', 37)
+
+ Now every time we call
+ $connection->query() we get
+ the result of 37.
+ We can set the return value to anything, say a hash of
+ imaginary database results or a list of persistent objects.
+ Parameters are irrelevant here, we always get the same
+ values back each time once they have been set up this way.
+ That may not sound like a convincing replica of a
+ database connection, but for the half a dozen lines of
+ a test method it is usually all you need.
+
+
+
+ Things aren't always that simple though.
+ One common problem is iterators, where constantly returning
+ the same value could cause an endless loop in the object
+ being tested.
+ For these we need to set up sequences of values.
+ Let's say we have a simple iterator that looks like this...
+
+class Iterator {
+ function Iterator() {
+ }
+
+ function next() {
+ }
+}
+
+ This is about the simplest iterator you could have.
+ Assuming that this iterator only returns text until it
+ reaches the end, when it returns false, we can simulate it
+ with...
+
+ When next() is called on the
+ stub iterator it will first return "First string",
+ on the second call "Second string" will be returned
+ and on any other call false will
+ be returned.
+ The sequenced return values take precedence over the constant
+ return value.
+ The constant one is a kind of default if you like.
+
+
+ Another tricky situation is an overloaded
+ get() operation.
+ An example of this is an information holder with name/value pairs.
+ Say we have a configuration class like...
+
+class Configuration {
+ function Configuration() {
+ }
+
+ function getValue($key) {
+ }
+}
+
+ This is a classic situation for using stub objects as
+ actual configuration will vary from machine to machine,
+ hardly helping the reliability of our tests if we use it
+ directly.
+ The problem though is that all the data comes through the
+ getValue() method and yet
+ we want different results for different keys.
+ Luckily the stubs have a filter system...
+
+ The extra parameter is a list of arguments to attempt
+ to match.
+ In this case we are trying to match only one argument which
+ is the look up key.
+ Now when the server stub has the
+ getValue() method invoked
+ like this...
+
+$config->getValue('db_user');
+
+ ...it will return "admin".
+ It finds this by attempting to match the calling arguments
+ to its list of returns one after another until
+ a complete match is found.
+
+
+ You can set a default argument argument like so...
+
+ This is not the same as setting the return value without
+ any argument requirements like this...
+
+
+$config->setReturnValue('getValue', false);
+
+ In the first case it will accept any single argument,
+ but exactly one is required.
+ In the second case any number of arguments will do and
+ it acts as a catchall after all other matches.
+ Note that if we add further single parameter options after
+ the wildcard in the first case, they will be ignored as the wildcard
+ will match first.
+ With complex parameter lists the ordering could be important
+ or else desired matches could be masked by earlier wildcard
+ ones.
+ Declare the most specific matches first if you are not sure.
+
+
+ There are times when you want a specific object to be
+ dished out by the stub rather than just a copy.
+ The PHP copy semantics force us to use a different method
+ for this.
+ You might be simulating a container for example...
+
+ This will return the $stuff only on the third
+ call and only if two parameters were set the second of
+ which must be the integer 1.
+ That should cover most simple prototyping situations.
+
+
+ A final tricky case is one object creating another, known
+ as a factory pattern.
+ Suppose that on a successful query to our imaginary
+ database, a result set is returned as an iterator with
+ each call to next() giving
+ one row until false.
+ This sounds like a simulation nightmare, but in fact it can all
+ be stubbed using the mechanics above.
+
+ Now only if our
+ $connection is called with the correct
+ query() will the
+ $result be returned that is
+ itself exhausted after the third call to next().
+ This should be enough
+ information for our UserFinder class,
+ the class actually
+ being tested here, to come up with goods.
+ A very precise test and not a real database in sight.
+
+
+
+ This is not very useful in itself as there would be no difference
+ in this class and the default except for the name.
+ However we can also add additional methods not found in the
+ original interface...
+
+ The core system is a regression testing framework built around
+ test cases.
+ A sample test case looks like this...
+
+class FileTestCase extends UnitTestCase {
+}
+
+ If no test name is supplied when chaining the constructor then
+ the class name will be taken instead.
+ This will be the name displayed in the test results.
+
+
+ Actual tests are added as methods in the test case whose names
+ by default start with the string "test" and
+ when the test case is invoked all such methods are run in
+ the order that PHP introspection finds them.
+ As many test methods can be added as needed.
+ For example...
+
+ The constructor is optional and usually omitted.
+ Without a name, the class name is taken as the name of the test case.
+
+
+ Our only test method at the moment is testCreation()
+ where we check that a file has been created by our
+ Writer object.
+ We could have put the unlink()
+ code into this method as well, but by placing it in
+ setUp() and
+ tearDown() we can use it with
+ other test methods that we add.
+
+
+ The setUp() method is run
+ just before each and every test method.
+ tearDown() is run just after
+ each and every test method.
+
+
+ You can place some test case set up into the constructor to
+ be run once for all the methods in the test case, but
+ you risk test inteference that way.
+ This way is slightly slower, but it is safer.
+ Note that if you come from a JUnit background this will not
+ be the behaviour you are used to.
+ JUnit surprisingly reinstantiates the test case for each test
+ method to prevent such interference.
+ SimpleTest requires the end user to use setUp(), but
+ supplies additional hooks for library writers.
+
+
+ The means of reporting test results (see below) are by a
+ visiting display class
+ that is notified by various assert...()
+ methods.
+ Here is the full list for the UnitTestCase
+ class, the default for SimpleTest...
+
+
+
+
assertTrue($x)
Fail if $x is false
+
+
+
assertFalse($x)
Fail if $x is true
+
+
+
assertNull($x)
Fail if $x is set
+
+
+
assertNotNull($x)
Fail if $x not set
+
+
+
assertIsA($x, $t)
Fail if $x is not the class or type $t
+
+
+
assertNotA($x, $t)
Fail if $x is of the class or type $t
+
+
+
assertEqual($x, $y)
Fail if $x == $y is false
+
+
+
assertNotEqual($x, $y)
Fail if $x == $y is true
+
+
+
assertIdentical($x, $y)
Fail if $x == $y is false or a type mismatch
+
+
+
assertNotIdentical($x, $y)
Fail if $x == $y is true and types match
+
+
+
assertReference($x, $y)
Fail unless $x and $y are the same variable
+
+
+
assertCopy($x, $y)
Fail if $x and $y are the same variable
+
+
+
assertWantedPattern($p, $x)
Fail unless the regex $p matches $x
+
+
+
assertNoUnwantedPattern($p, $x)
Fail if the regex $p matches $x
+
+
+
assertNoErrors()
Fail if any PHP error occoured
+
+
+
assertError($x)
Fail if no PHP error or incorrect message
+
+
+
assertErrorPattern($p)
Fail unless the error matches the regex $p
+
+
+
+ All assertion methods can take an optional description to
+ label the displayed result with.
+ If omitted a default message is sent instead which is usually
+ sufficient.
+ This default message can still be embedded in your own message
+ if you include "%s" within the string.
+ All the assertions return true on a pass or false on failure.
+
+
+ Some examples...
+
+$variable = null;
+$this->assertNull($variable, 'Should be cleared');
+
+ ...will pass and normally show no message.
+ If you have
+ set up the tester to display passes
+ as well then the message will be displayed as is.
+
+$this->assertIdentical(0, false, 'Zero is not false [%s]');
+
+ This will fail as it performs a type
+ check as well as a comparison between the two values.
+ The "%s" part is replaced by the default
+ error message that would have been shown if we had not
+ supplied our own.
+ This also allows us to nest test messages.
+
+ This one takes some explanation as in fact they all pass!
+
+
+ PHP errors in SimpleTest are trapped and placed in a queue.
+ Here the first error check catches the "Disaster"
+ message without checking the text and passes.
+ This removes the error from the queue.
+ The next error check tests not only the existence of the error,
+ but also the text which here matches so another pass.
+ With the queue now empty the last test will pass as well.
+ If any unchecked errors are left at the end of a test method then
+ an exception will be reported in the test.
+ Note that SimpleTest cannot catch compile time PHP errors.
+
+
+ The test cases also have some convenience methods for debugging
+ code or extending the suite...
+
+
+
+
setUp()
Runs this before each test method
+
+
+
tearDown()
Runs this after each test method
+
+
+
pass()
Sends a test pass
+
+
+
fail()
Sends a test failure
+
+
+
error()
Sends an exception event
+
+
+
sendMessage()
Sends a status message to those displays that support it
+
+
+
signal($type, $payload)
Sends a user defined message to the test reporter
+
+
+
dump($var)
Does a formatted print_r() for quick and dirty debugging
+ If you want a test case that does not have all of the
+ UnitTestCase assertions,
+ only your own and assertTrue(),
+ you need to extend the SimpleTestCase
+ class instead.
+ It is found in simple_test.php rather than
+ unit_tester.php.
+ See later if you
+ want to incorporate other unit tester's
+ test cases in your test suites.
+
+ You won't often run single test cases except when bashing
+ away at a module that is having difficulty and you don't
+ want to upset the main test suite.
+ Here is the scaffolding needed to run the a lone test case...
+
+ Testing classes is all very well, but PHP is predominately
+ a language for creating functionality within web pages.
+ How do we test the front end presentation role of our PHP
+ applications?
+ Well the web pages are just text, so we should be able to
+ examine them just like any other test data.
+
+
+ This leads to a tricky issue.
+ If we test at too low a level, testing for matching tags
+ in the page with pattern matching for example, our tests will
+ be brittle.
+ The slightest change in layout could break a large number of
+ tests.
+ If we test at too high a level, say using mock versions of a
+ template engine, then we lose the ability to automate some classes
+ of test.
+ For example, the interaction of forms and navigation will
+ have to be tested manually.
+ These types of test are extremely repetitive and error prone.
+
+
+ SimpleTest includes a special form of test case for the testing
+ of web page actions.
+ The WebTestCase includes facilities
+ for navigation, content and cookie checks and form handling.
+ Usage of these test cases is similar to the
+ UnitTestCase...
+
+class TestOfLastcraft extends WebTestCase {
+}
+
+ Here we are about to test the
+ Last Craft site itself.
+ If this test case is in a file called lastcraft_test.php
+ then it can be loaded in a runner script just like unit tests...
+
+ The get() method will
+ return true only if page content was successfully
+ loaded.
+ It is a simple, but crude way to check that a web page
+ was actually delivered by the web server.
+ However that content may be a 404 response and yet
+ our get() method will still return true.
+
+
+ Assuming that the web server for the Last Craft site is up
+ (sadly not always the case), we should see...
+
+ To confirm that the page we think we are on is actually the
+ page we are on, we need to verify the page content.
+
+class TestOfLastcraft extends WebTestCase {
+
+ function testHomepage() {
+ $this->get('http://www.lastcraft.com/');
+ $this->assertWantedPattern('/why the last craft/i');
+ }
+}
+
+ The page from the last fetch is held in a buffer in
+ the test case, so there is no need to refer to it directly.
+ The pattern match is always made against the buffer.
+
+
+ Here is the list of possible content assertions...
+
+
+
+
assertTitle($title)
Pass if title is an exact match
+
+
+
assertWantedPattern($pattern)
A Perl pattern match against the page content
+
+
+
assertNoUnwantedPattern($pattern)
A Perl pattern match to not find content
+
+
+
assertWantedText($text)
Pass if matches visible and "alt" text
+
+
+
assertNoUnwantedText($text)
Pass if doesn't match visible and "alt" text
+
+
+
assertLink($label)
Pass if a link with this text is present
+
+
+
assertNoLink($label)
Pass if no link with this text is present
+
+
+
assertLinkById($id)
Pass if a link with this id attribute is present
+
+
+
assertNoLinkById($id)
Pass if no link with this id attribute is present
+
+
+
assertField($name, $value)
Pass if an input tag with this name has this value
+
+
+
assertFieldById($id, $value)
Pass if an input tag with this id has this value
+
+
+
assertResponse($codes)
Pass if HTTP response matches this list
+
+
+
assertMime($types)
Pass if MIME type is in this list
+
+
+
assertAuthentication($protocol)
Pass if the current challenge is this protocol
+
+
+
assertNoAuthentication()
Pass if there is no current challenge
+
+
+
assertRealm($name)
Pass if the current challenge realm matches
+
+
+
assertHeader($header, $content)
Pass if a header was fetched matching this value
+
+
+
assertNoUnwantedHeader($header)
Pass if a header was not fetched
+
+
+
assertHeaderPattern($header, $pattern)
Pass if a header was fetched matching this Perl regex
+
+
+
assertCookie($name, $value)
Pass if there is currently a matching cookie
+
+
+
assertNoCookie($name)
Pass if there is currently no cookie of this name
+
+
+
+ As usual with the SimpleTest assertions, they all return
+ false on failure and true on pass.
+ They also allow an optional test message and you can embed
+ the original test message inside using "%s" inside
+ your custom message.
+
+
+ So now we could instead test against the title tag with...
+
+$this->assertTitle('The Last Craft? Web developer tutorials on PHP, Extreme programming and Object Oriented development');
+
+ As well as the simple HTML content checks we can check
+ that the MIME type is in a list of allowed types with...
+
+ More interesting is checking the HTTP response code.
+ Like the MIME type, we can assert that the response code
+ is in a list of allowed values...
+
+ Here we are checking that the fetch is successful by
+ allowing only a 200 HTTP response.
+ This test will pass, but it is not actually correct to do so.
+ There is no page, instead the server issues a redirect.
+ The WebTestCase will
+ automatically follow up to three such redirects.
+ The tests are more robust this way and we are usually
+ interested in the interaction with the pages rather
+ than their delivery.
+ If the redirects are of interest then this ability must
+ be disabled...
+
+ Users don't often navigate sites by typing in URLs, but by
+ clicking links and buttons.
+ Here we confirm that the contact details can be reached
+ from the home page...
+
+ If the target is a button rather than an anchor tag, then
+ clickSubmit() should be used
+ with the button title...
+
+$this->clickSubmit('Go!');
+
+
+
+ The list of navigation methods is...
+
+
+
+
getUrl()
The current location
+
+
+
get($url, $parameters)
Send a GET request with these parameters
+
+
+
post($url, $parameters)
Send a POST request with these parameters
+
+
+
head($url, $parameters)
Send a HEAD request without replacing the page content
+
+
+
retry()
Reload the last request
+
+
+
back()
Like the browser back button
+
+
+
forward()
Like the browser forward button
+
+
+
authenticate($name, $password)
Retry after a challenge
+
+
+
restart()
Restarts the browser as if a new session
+
+
+
getCookie($name)
Gets the cookie value for the current context
+
+
+
ageCookies($interval)
Ages current cookies prior to a restart
+
+
+
clearFrameFocus()
Go back to treating all frames as one page
+
+
+
clickSubmit($label)
Click the first button with this label
+
+
+
clickSubmitByName($name)
Click the button with this name attribute
+
+
+
clickSubmitById($id)
Click the button with this ID attribute
+
+
+
clickImage($label, $x, $y)
Click an input tag of type image by title or alt text
+
+
+
clickImageByName($name, $x, $y)
Click an input tag of type image by name
+
+
+
clickImageById($id, $x, $y)
Click an input tag of type image by ID attribute
+
+
+
submitFormById($id)
Submit a form without the submit value
+
+
+
clickLink($label, $index)
Click an anchor by the visible label text
+
+
+
clickLinkById($id)
Click an anchor by the ID attribute
+
+
+
getFrameFocus()
The name of the currently selected frame
+
+
+
setFrameFocusByIndex($choice)
Focus on a frame counting from 1
+
+
+
setFrameFocus($name)
Focus on a frame by name
+
+
+
+
+
+ The parameters in the get(), post() or
+ head() methods are optional.
+ The HTTP HEAD fetch does not change the browser context, only loads
+ cookies.
+ This can be useful for when an image or stylesheet sets a cookie
+ for crafty robot blocking.
+
+
+ The retry(), back() and
+ forward() commands work as they would on
+ your web browser.
+ They use the history to retry pages.
+ This can be handy for checking the effect of hitting the
+ back button on your forms.
+
+
+ The frame methods need a little explanation.
+ By default a framed page is treated just like any other.
+ Content will be searced for throughout the entire frameset,
+ so clicking a link will work no matter which frame
+ the anchor tag is in.
+ You can override this behaviour by focusing on a single
+ frame.
+ If you do that, all searches and actions will apply to that
+ frame alone, such as authentication and retries.
+ If a link or button is not in a focused frame then it cannot
+ be clicked.
+
+
+ Testing navigation on fixed pages only tells you when you
+ have broken an entire script.
+ For highly dynamic pages, such as for bulletin boards, this can
+ be crucial for verifying the correctness of the application.
+ For most applications though, the really tricky logic is usually in
+ the handling of forms and sessions.
+ Fortunately SimpleTest includes
+ tools for testing web forms
+ as well.
+
+ Although SimpleTest does not have the goal of testing networking
+ problems, it does include some methods to modify and debug
+ the requests it makes.
+ Here is another method list...
+
+
+
+
getTransportError()
The last socket error
+
+
+
showRequest()
Dump the outgoing request
+
+
+
showHeaders()
Dump the incoming headers
+
+
+
showSource()
Dump the raw HTML page content
+
+
+
ignoreFrames()
Do not load framesets
+
+
+
setCookie($name, $value)
Set a cookie from now on
+
+
+
addHeader($header)
Always add this header to the request
+
+
+
setMaximumRedirects($max)
Stop after this many redirects
+
+
+
setConnectionTimeout($timeout)
Kill the connection after this time between bytes
+
+
+
useProxy($proxy, $name, $password)
Make requests via this proxy URL
+
+
+
+ These methods are principally for debugging.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+ Un des secteurs à la fois délicat et important lors d'un test de site web reste la sécurité. Tester ces schémas est au coeur des objectifs du testeur web de SimpleTest.
+
+ Si vous allez chercher une page web protégée par une authentification basique, vous hériterez d'une entête 401. Nous pouvons représenter ceci par ce test...
+
1/1 test cases complete.
+ 0 passes, 0 fails and 0 exceptions.
+
+ Sauf que nous voulons éviter l'inspection visuelle, on souhaite que SimpleTest puisse nous dire si oui ou non la page est protégée. Voici un test en profondeur sur nos entêtes...
+
+ N'importe laquelle de ces assertions suffirait, tout dépend de la masse de détails que vous souhaitez voir.
+
+
+ La plupart du temps, nous ne souhaitons pas tester l'authentification en elle-même, mais plutôt les pages protégées par cette authentification. Dès que la tentative d'authentification est reçue, nous pouvons y répondre à l'aide d'une réponse d'authentification :
+
+ Le nom d'utilisateur et le mot de passe seront désormais envoyés à chaque requête vers ce répertoire et ses sous répertoires. En revanche vous devrez vous authentifier à nouveau si vous sortez de ce répertoire.
+
+
+ Vous pouvez gagner une ligne en définissant l'authentification au niveau de l'URL...
+
+ Si votre nom d'utilisateur ou mot de passe comporte des caractères spéciaux, alors n'oubliez pas de les encoder, sinon la requête ne sera pas analysée correctement. De plus cette entête ne sera pas envoyée aux sous requêtes si vous la définissez avec une URL absolue. Par contre si vous naviguez avec des URL relatives, l'information d'authentification sera préservée.
+
+
+ Pour l'instant, seule l'authentification de base est implémentée et elle n'est réellement fiable qu'en tandem avec une connexion HTTPS. C'est généralement suffisant pour protéger le serveur testé des regards malveillants. Les authentifications Digest et NTLM pourraient être ajoutées prochainement.
+
+ L'authentification de base ne donne pas assez de contrôle au développeur Web sur l'interface utilisateur. Il y a de forte chance pour que cette fonctionnalité soit codée directement dans l'architecture web à grand renfort de cookies et de timeouts compliqués.
+
+
+ Commençons par un simple formulaire de connexion...
+
+ Supposons que, durant le chargement de la page, un cookie ait été inscrit avec un numéro d'identifiant de session. Nous n'allons pas encore remplir le formulaire, juste tester que nous pistons bien l'utilisateur. Voici le test...
+
+ Nous nous contentons ici de vérifier que le cookie a bien été défini. Etant donné que sa valeur est plutôt énigmatique, elle ne vaut pas la peine d'être testée.
+
+
+ Le reste du test est le même que dans n'importe quel autre formulaire, mais nous pourrions souhaiter nous assurer que le cookie n'a pas été modifié depuis la phase de connexion. Voici comment cela pourrait être testé :
+
+ Si vous testez un système d'authentification, la reconnexion par un utilisateur est un point sensible. Essayons de simuler ce qui se passe dans ce cas :
+
+ La méthode WebTestCase::restart() préserve les cookies dont le timeout a expiré, mais conserve les cookies temporaires ou expirés. Vous pouvez spécifier l'heure et la date de leur réactivation.
+
+
+ L'expiration des cookies peut être un problème. Si vous avez un cookie qui doit expirer au bout d'une heure, nous n'allons pas mettre le test en veille en attendant que le cookie expire...
+
+
+ Afin de provoquer leur expiration, vous pouvez dater manuellement les cookies, avant le début de la session.
+
+ Le composant de navigation web de SimpleTest peut être utilisé non seulement à l'extérieur de la classe WebTestCase, mais aussi indépendamment du frameword SimpleTest lui-même.
+
+ Vous pouvez utiliser le navigateur web dans des scripts PHP pour confirmer que des services marchent bien comme il faut ou pour extraire des informations à partir de ceux-ci de façon régulière.
+ Par exemple, voici un petit script pour extraire le nombre de bogues ouverts dans PHP 5 à partir du site web PHP...
+
+ Bien sûr Il y a des méthodes plus simple pour réaliser cet exemple en PHP. Par exemple, vous pourriez juste utiliser la commande PHP file() sur ce qui est ici une page fixe. Cependant, en utilisant des scripts avec le navigateur web vous vous autorisez l'authentification, la gestion des cookies, le chargement automatique des fenêtres, les redirections, la transmission de formulaire et la capacité d'examiner les entêtes. De telles méthodes sont fragiles dans un site en constante évolution et vous voudrez employer une méthode plus directe pour accéder aux données de façon permanente, mais pour des tâches simples cette technique peut s'avérer une solution très rapide.
+
+
+ Toutes les méthode de navigation utilisées dans WebTestCase sont présente dans la classe SimpleBrowser, mais les assertions sont remplacées par de simples accesseurs. Voici une liste complète des méthodes de navigation de page à page...
+
+
+
+
addHeader($header)
Ajouter une entête à chaque téléchargement
+
+
+
useProxy($proxy, $username, $password)
Utilise ce proxy à partir de maintenant
+
+
+
head($url, $parameters)
Effectue une requête HEAD
+
+
+
get($url, $parameters)
Télécharge une page avec un GET
+
+
+
post($url, $parameters)
Télécharge une page avec un POST
+
+
+
clickLink($label)
Suit un lien par son étiquette
+
+
+
isLink($label)
Vérifie si un lien avec cette étiquette existe
+
+
+
clickLinkById($id)
Suit un lien par son attribut d'identification
+
+
+
isLinkById($id)
Vérifie si un lien avec cet attribut d'identification existe
+
+
+
getUrl()
La page ou la fenêtre URL en cours
+
+
+
getTitle()
Le titre de la page
+
+
+
getContent()
Le page ou la fenêtre brute
+
+
+
getContentAsText()
Sans code HTML à l'exception du text "alt"
+
+
+
retry()
Répète la dernière requête
+
+
+
back()
Utilise le bouton "précédent" du navigateur
+
+
+
forward()
Utilise le bouton "suivant" du navigateur
+
+
+
authenticate($username, $password)
Retente la page ou la fenêtre après une réponse 401
+
+
+
restart($date)
Relance le navigateur pour une nouvelle session
+
+
+
ageCookies($interval)
Change la date des cookies
+
+
+
setCookie($name, $value)
Lance un nouveau cookie
+
+
+
getCookieValue($host, $path, $name)
Lit le cookie le plus spécifique
+
+
+
getCurrentCookieValue($name)
Lit le contenue du cookie en cours
+
+
+
+ Les méthode SimpleBrowser::useProxy() et SimpleBrowser::addHeader() sont spéciales. Une fois appellées, elles continuent à s'appliquer sur les téléchargements suivants.
+
+
Accesseur de la valeur de l'élément de formulaire avec cet identifiant
+
+
+
clickSubmit($label)
Transmet le formulaire avec l'étiquette de son bouton
+
+
+
clickSubmitByName($name)
Transmet le formulaire avec l'attribut de son bouton
+
+
+
clickSubmitById($id)
Transmet le formulaire avec l'identifiant de son bouton
+
+
+
clickImage($label, $x, $y)
Clique sur l'image par son texte alternatif
+
+
+
clickImageByName($name, $x, $y)
Clique sur l'image par son attribut
+
+
+
clickImageById($id, $x, $y)
Clique sur l'image par son identifiant
+
+
+
submitFormById($id)
Transmet le formulaire par son identifiant propre
+
+
+
+ A aujourd'hui il n'existe aucune méthode pour lister les formulaires et les champs disponibles : ce sera probablement ajouté dans des versions successives de SimpleTest.
+
+
+ A l'intérieur d'une page, les fenêtres individuelles peuvent être sélectionnées. Si aucune sélection n'est réalisée alors toutes les fenêtres sont fusionnées ensemble dans un unique et grande page. Le contenu de la page en cours sera une concaténation des toutes les fenêtres dans l'ordre spécifié par les balises "frameset".
+
+
+
+
getFrames()
Un déchargement de la structure de la fenêtre courante
+
+
+
getFrameFocus()
L'index ou l'étiquette de la fenêtre en courante
+
+
+
setFrameFocusByIndex($choice)
Sélectionne la fenêtre numérotée à partir de 1
+
+
+
setFrameFocus($name)
Sélectionne une fenêtre par son étiquette
+
+
+
clearFrameFocus()
Traite toutes les fenêtres comme une seule page
+
+
+
+ Lorsqu'on est focalisé sur une fenêtre unique, le contenu viendra de celle-ci uniquement. Cela comprend les liens à cliquer et les formulaires à transmettre.
+
+
+
+ Toute cette masse de fonctionnalités est géniale lorsqu'on arrive à bien télécharger les pages, mais ce n'est pas toujours évident. Pour aider à découvrir les erreurs, le navigateur a aussi des méthodes pour aider au débogage.
+
+
+
+
setConnectionTimeout($timeout)
Ferme la socket avec un délai trop long
+
+
+
getRequest()
L'entête de la requête brute de la page ou de la fenêtre
+
+
+
getHeaders()
L'entête de réponse de la page ou de la fenêtre
+
+
+
getTransportError()
N'importe quel erreur au niveau de la socket dans le dernier téléchargement
+
+
+
getResponseCode()
La réponse HTTP de la page ou de la fenêtre
+
+
+
getMimeType()
Le type Mime de la page our de la fenêtre
+
+
+
getAuthentication()
Le type d'authenficiation dans l'entête d'une provocation 401
+
+
+
getRealm()
Le realm d'authentification dans l'entête d'une provocation 401
+
+
+
setMaximumRedirects($max)
Nombre de redirection avant que la page ne soit chargée automatiquement
+
+
+
setMaximumNestedFrames($max)
Protection contre des framesets récursifs
+
+
+
ignoreFrames()
Neutralise le support des fenêtres
+
+
+
useFrames()
Autorise le support des fenêtres
+
+
+
+ Les méthodes SimpleBrowser::setConnectionTimeout(), SimpleBrowser::setMaximumRedirects(),SimpleBrowser::setMaximumNestedFrames(), SimpleBrowser::ignoreFrames() et SimpleBrowser::useFrames() continuent à s'appliquer sur toutes les requêtes suivantes. Les autres méthodes tiennent compte des fenêtres. Cela veut dire que si une fenêtre individuel ne se charge pas, il suffit de se diriger vers elle avec SimpleBrowser::setFrameFocus() : ensuite on utilisera SimpleBrowser::getRequest(), etc. pour voir ce qui se passe.
+
+
+
+ Tout ce qui peut être fait dans WebTestCase peut maintenant être fait dans un UnitTestCase. Ce qui revient à dire que nous pouvons librement mélanger des tests sur des objets de domaine avec l'interface web...
+
+ Bien que ça puisse être utile par convenance temporaire, je ne suis pas fan de ce genre de test. Ce test s'applique à sur plusieurs couches de l'application, ça implique qu'il est plus que probable qu'il faudra le remanier lorsque le code change.
+
+
+ Un cas plus utile d'utilisation directe du navigateur est le moment où le WebTestCase ne peut plus suivre. Un exemple ? Quand deux navigateurs doivent être utilisés en même temps.
+
+
+ Par exemple, supposons que nous voulions interdire des usages simultanés d'un site avec le même login d'identification. Ce scénario de test le vérifie...
+
+ Vous pouvez aussi utiliser la classe SimpleBrowser quand vous souhaitez écrire des scénarios de test en utilisant un autre outil que SimpleTest.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+ Le comportement par défaut des objets fantaisie dans SimpleTest est soit une correspondance identique sur l'argument, soit l'acceptation de n'importe quel argument. Pour la plupart des tests, c'est suffisant. Cependant il est parfois nécessaire de ramollir un scénario de test.
+
+
+ Un des endroits où un test peut être trop serré est la reconnaissance textuelle. Prenons l'exemple d'un composant qui produirait un message d'erreur utile lorsque quelque chose plante. Il serait utile de tester que l'erreur correcte est renvoyée, mais le texte proprement dit risque d'être plutôt long. Si vous testez le texte dans son ensemble alors à chaque modification de ce même message -- même un point ou une virgule -- vous aurez à revenir sur la suite de test pour la modifier.
+
+
+ Voici un cas concret, nous avons un service d'actualités qui a échoué dans sa tentative de connexion à sa source distante.
+
+class NewsService {
+ ...
+ function publish(&$writer) {
+ if (! $this->isConnected()) {
+ $writer->write('Cannot connect to news service "' .
+ $this->_name . '" at this time. ' .
+ 'Please try again later.');
+ }
+ ...
+ }
+}
+
+ Là il envoie son contenu vers un classe Writer. Nous pourrions tester ce comportement avec un MockWriter...
+
+class TestOfNewsService extends UnitTestCase {
+ ...
+ function testConnectionFailure() {
+ $writer = &new MockWriter($this);
+ $writer->expectOnce('write', array(
+ 'Cannot connect to news service ' .
+ '"BBC News" at this time. ' .
+ 'Please try again later.'));
+
+ $service = &new NewsService('BBC News');
+ $service->publish($writer);
+
+ $writer->tally();
+ }
+}
+
+ C'est un bon exemple d'un test fragile. Si nous décidons d'ajouter des instructions complémentaires, par exemple proposer une source d'actualités alternative, nous casserons nos tests par la même occasion sans pourtant avoir modifié une seule fonctionnalité.
+
+
+ Pour contourner ce problème, nous voudrions utiliser un test avec une expression rationnelle plutôt qu'une correspondance exacte. Nous pouvons y parvenir avec...
+
+ Plutôt que de transmettre le paramètre attendu au MockWriter, nous envoyons une classe d'attente appelée WantedPatternExpectation. L'objet fantaisie est suffisamment élégant pour reconnaître qu'il s'agit d'un truc spécial et pour le traiter différemment. Plutôt que de comparer l'argument entrant à cet objet, il utilise l'objet attente lui-même pour exécuter le test.
+
+
+ WantedPatternExpectation utilise l'expression rationnelle pour la comparaison avec son constructeur. A chaque fois q'une comparaison est fait à travers MockWriter par rapport à cette classe attente, elle fera un preg_match() avec ce motif. Dans notre scénario de test ci-dessus, aussi longtemps que la chaîne "cannot connect" apparaît dans le texte, la fantaisie transmettra un succès au testeur unitaire. Peu importe le reste du texte.
+
+
+ Les classes attente possibles sont...
+
+
+
+
EqualExpectation
Une égalité, plutôt que la plus forte comparaison à l'identique
+
+
+
NotEqualExpectation
Une comparaison sur la non-égalité
+
+
+
IndenticalExpectation
La vérification par défaut de l'objet fantaisie qui doit correspondre exactement
+
+
+
NotIndenticalExpectation
Inverse la logique de l'objet fantaisie
+
+
+
WantedPatternExpectation
Utilise une expression rationnelle Perl pour comparer une chaîne
+
+
+
NoUnwantedPatternExpectation
Passe seulement si l'expression rationnelle Perl échoue
+
+
+
IsAExpectation
Vérifie le type ou le nom de la classe uniquement
+
+
+
NotAExpectation
L'opposé de IsAExpectation
+
+
+
MethodExistsExpectation
Vérifie si la méthode est disponible sur un objet
+
+
+
+ La plupart utilisent la valeur attendue dans le constructeur. Les exceptions sont les vérifications sur motif, qui utilisent une expression rationnelle, ainsi que IsAExpectation et NotAExpectation, qui prennent un type ou un nom de classe comme chaîne.
+
+
+
+ Les classes attente peuvent servir à autre chose que l'envoi d'assertions depuis les objets fantaisie, afin de choisir le comportement d'un objet fantaisie our celui d'un bouchon serveur. A chaque fois qu'une liste d'arguments est donnée, une liste d'objets attente peut être insérée à la place.
+
+
+ Mettons que nous voulons qu'un bouchon serveur d'autorisation simule une connexion réussie seulement si il reçoit un objet de session valide. Nous pouvons y arriver avec ce qui suit...
+
+Stub::generate('Authorisation');
+
+$authorisation = new StubAuthorisation();
+$authorisation->setReturnValue(
+ 'isAllowed',
+ true,
+ array(new IsAExpectation('Session', 'Must be a session')));
+$authorisation->setReturnValue('isAllowed', false);
+
+ Le comportement par défaut du bouchon serveur est défini pour renvoyer false quand isAllowed est appelé. Lorsque nous appelons cette méthode avec un unique paramètre qui est un objet Session, il renverra true. Nous avons aussi ajouté un deuxième paramètre comme message. Il sera affiché dans le message d'erreur de l'objet fantaisie si l'attente est la cause de l'échec.
+
+
+ Ce niveau de sophistication est rarement utile : il n'est inclut que pour être complet.
+
+ Les classes d'attentes ont une structure très simple. Tellement simple qu'il devient très simple de créer vos propres version de logique pour des tests utilisés couramment.
+
+
+ Par exemple voici la création d'une classe pour tester la validité d'adresses IP. Pour fonctionner correctement avec les bouchons serveurs et les objets fantaisie, cette nouvelle classe d'attente devrait étendre SimpleExpectation...
+
+class ValidIp extends SimpleExpectation {
+
+ function test($ip) {
+ return (ip2long($ip) != -1);
+ }
+
+ function testMessage($ip) {
+ return "Address [$ip] should be a valid IP address";
+ }
+}
+
+ Il n'y a véritablement que deux méthodes à mettre en place. La méthode test() devrait renvoyer un true si l'attente doit passer, et une erreur false dans le cas contraire. La méthode testMessage() ne devrait renvoyer que du texte utile à la compréhension du test en lui-même.
+
+
+ Cette classe peut désormais être employée à la place des classes d'attente précédentes.
+
+ Le frameworkd de test unitaire SimpleTest utilise aussi dans son coeur des classes d'attente pour la classe UnitTestCase. Nous pouvons aussi tirer parti de ces mécanismes pour réutiliser nos propres classes attente à l'intérieur même des suites de test.
+
+
+ La méthode la plus directe est d'utiliser la méthode SimpleTest::assertExpectation() pour effectuer le test...
+
+ C'est plutôt sale par rapport à notre syntaxe habituelle du type assert...().
+
+
+ Pour un cas aussi simple, nous créons d'ordinaire une méthode d'assertion distincte en utilisant la classe d'attente. Supposons un instant que notre attente soit un peu plus compliquée et que par conséquent nous souhaitions la réutiliser, nous obtenons...
+
+ Il est peu probable que nous ayons besoin de ce niveau de contrôle sur la machinerie de test. Il est assez rare que le besoin d'une attente dépasse le stade de la reconnaissance d'un motif. De plus, les classes d'attente complexes peuvent rendre les tests difficiles à lire et à déboguer. Ces mécanismes sont véritablement là pour les auteurs de système qui étendront le framework de test pour leurs propres outils de test.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+
+
diff --git a/tests/UnitTests/simpletest/docs/fr/form_testing_documentation.html b/tests/UnitTests/simpletest/docs/fr/form_testing_documentation.html
new file mode 100644
index 00000000..39ec01ce
--- /dev/null
+++ b/tests/UnitTests/simpletest/docs/fr/form_testing_documentation.html
@@ -0,0 +1,235 @@
+
+
+
+Documentation SimpleTest : tester des formulaires HTML
+
+
+
+
+ Lorsqu'une page est téléchargée par WebTestCase en utilisant get() ou post() le contenu de la page est automatiquement analysé. De cette analyse découle le fait que toutes les commandes à l'intérieur de la balise <form> sont disponibles depuis l'intérieur du scénario de test. Prenons pas exemple cet extrait de code HTML...
+
+ Nous pouvons naviguer vers ce code, via le site LastCraft, avec le test suivant...
+
+class SimpleFormTests extends WebTestCase {
+
+ function testDefaultValue() {
+ $this->get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this->assertField('a', 'A default');
+ }
+}
+
+ Directement après le chargement de la page toutes les commandes HTML sont initiées avec leur valeur par défaut, comme elles apparaîtraient dans un navigateur web. L'assertion teste qu'un objet HTML avec le nom "a" existe dans la page et qu'il contient la valeur "A default".
+
+
+ Nous pourrions retourner le formulaire tout de suite, mais d'abord nous allons changer la valeur du champ texte. Ce n'est qu'après que nous le transmettre...
+
+ Parce que nous n'avons spécifié ni attribut "method" sur la balise form, ni attribut "action", le scénario de test suivra le comportement classique d'un navigateur : transmission des données avec une requête GET vers la même page. SimpleTest essaie d'émuler le comportement typique d'un navigateur autant que possible, plutôt que d'essayer d'attraper des attributs manquants sur les balises. La raison est simple : la cible d'un framework de test est la logique d'une application PHP, pas les erreurs -- de syntaxe ou autres -- du code HTML. Pour les erreurs HTML, d'autres outils tel HTMLTidy devraient être employés.
+
+
+ Si un champ manque dans n'importe que formulaire ou si une option est indisponible alors WebTestCase::setField() renverra false. Par exemple, supposons que nous souhaitons vérifier qu'une option "Superuser" n'est pas présente dans ce formulaire...
+
+<strong>Select type of user to add:</strong>
+<select name="type">
+ <option>Subscriber</option>
+ <option>Author</option>
+ <option>Administrator</option>
+</select>
+
+ La sélection ne sera pas changée suite à un échec d'initialisation d'une valeur sur un objet.
+
+
+ Voici la liste complète des objets supportés à aujourd'hui...
+
+
Champs texte, y compris les champs masqués (hidden) ou cryptés (password).
+
Boutons submit, en incluant aussi la balise button, mais pas encore les boutons reset
+
Aires texte (textarea) avec leur gestion des retours à la ligne (wrap).
+
Cases à cocher, y compris les cases à cocher multiples dans un même formulaire.
+
Listes à menu déroulant, y compris celles à sélections multiples.
+
Boutons radio.
+
Images.
+
+
+
+ Bien que la plupart des objets HTML standards soient couvert par le parseur de SimpleTest, il est peu probable que JavaScript soit implémenté dans un futur proche.
+
+ SimpleTest peut gérer deux types de commandes à valeur multiple : les menus déroulants à sélection multiple et les cases à cocher avec le même nom à l'intérieur même d'un formulaire. La nature de ceux-ci implique que leur initialisation et leur test sont légèrement différents. Voici un exemple avec des cases à cocher...
+
+ Si nous souhaitons désactiver tous les privilèges sauf ceux de téléchargement (Retrieve) et transmettre cette information, nous pouvons y arriver par...
+
+ Plutôt que d'initier le champ à une valeur unique, nous lui donnons une liste de valeurs. Nous faisons la même chose pour tester les valeurs attendues. Nous pouvons écrire d'autre code de test pour confirmer cet effet, peut-être en nous connectant comme utilisateur et en essayant d'effectuer une mise à jour.
+
+
+ Si vous souhaitez tester un gestionnaire de formulaire mais que vous ne l'avez pas écrit ou que vous n'y avez pas encore accès, vous pouvez créer un envoi de formulaire à la main.
+
+ Autant de scénarios que nécessaires peuvent être mis dans un fichier unique. Ils doivent contenir tout le code nécessaire, entre autres la bibliothèque testée, mais aucune des bibliothèques de SimpleTest.
+
+
+ Si vous avez étendu l'un ou l'autre des scénarios de test, vous pouvez aussi les inclure.
+
+ La classe FileTester ne contient aucun test véritable, il s'agit d'une classe de base pour d'autres scénarios de test. Pour cette raison nous utilisons la directive SimpleTestOptions::ignore() pour indiquer au prochain groupe de test de l'ignorer. Cette directive peut se placer n'importe où dans le fichier et fonctionne quand un fichier complet des scénarios de test est chargé (cf. ci-dessous). Nous l'appelons file_test.php.
+
+
+ Ensuite nous créons un fichier de groupe de test, disons group_test.php. Vous penserez à un nom plus convaincant, j'en suis sûr. Nous lui ajoutons le fichier de test avec une méthode sans risque...
+
+ Ceci instancie le scénario de test avant que la suite de test ne soit lancée. Ça pourrait devenir assez onéreux avec un grand nombre de scénarios de test : il existe donc une autre méthode qui instancie la classe uniquement quand elle devient nécessaire...
+
+ Le problème de cette technique est que pour chaque scénario de test supplémentaire nous aurons à require_once() le fichier de code de test et à manuellement instancier chaque scénario de test. Nous pouvons nous épargner beaucoup de dactylographie avec...
+
+ Voici ce qui vient de se passer : la classe GroupTest a réalisé le require_once() pour nous. Ensuite elle vérifie si de nouvelles classes de scénario de test ont été créées par ce nouveau fichier et les ajoute automatiquement au groupe de test. Désormais tout ce qu'il nous reste à faire, c'est d'ajouter chaque nouveau fichier.
+
+
+ Il y a deux choses qui peuvent planter et qui demandent un minimum d'attention...
+
+
+ Le fichier peut déjà avoir été analysé par PHP et dans ce cas aucune classe ne sera ajoutée. Pensez à bien vérifier que les scénarios de test ne sont inclus que dans ce fichier et dans aucun autre.
+
+
+ Les nouvelles classes d'extension de scénario de test qui sont incluses seront placées dans le groupe de test et exécutées par la même occasion. Vous aurez à ajouter une directive SimpleTestOptions::ignore() pour ces classes ou alors pensez à les ajouter avant la ligne GroupTest::addTestFile().
+
+ La technique ci-dessus place tous les scénarios de test dans un unique et grand groupe. Sauf que pour des projets plus conséquents, ce n'est probablement pas assez souple ; vous voudriez peut-être grouper les tests tout à fait différemment.
+
+
+ Pour obtenir un groupe de test plus souple nous pouvons sous classer GroupTest et ensuite l'instancier au cas par cas...
+
+ Ceci nomme le test dans le constructeur et ensuite ajoute à la fois nos scénarios de test et un unique groupe en dessous. Bien sûr nous pouvons ajouter plus d'un groupe à cet instant. Nous pouvons maintenant invoquer les tests à partir d'un autre fichier d'exécution...
+
+ Si nous souhaitons lancer le groupe de test original sans utiliser ses petits fichiers d'exécution, nous pouvons mettre le code du lanceur de test derrière des barreaux quand nous créons chaque groupe.
+
+ Cette approche exige aux barrières d'être activées à l'inclusion du fichier de groupe de test, mais c'est quand même moins de tracas que beaucoup de fichiers de lancement éparpillés. Reste à inclure des barreaux identiques au niveau supérieur afin de s'assurer que le run() ne sera lancé qu'une seule fois à partir du script de haut niveau qui l'a invoqué.
+
+ Si vous avez déjà des tests unitaires pour votre code ou alors si vous étendez des classes externes qui ont déjà leurs propres tests, il y a peu de chances pour que ceux-ci soient déjà au format SimpleTest. Heureusement il est possible d'incorporer ces scénarios de test en provenance d'autres testeurs unitaires directement dans des groupes de test SimpleTest.
+
+
+ Par exemple, supposons que nous ayons ce scénario de test prévu pour PhpUnitdans le fichier config_test.php...
+
+ Les scénarios de test de PEAR peuvent être librement mélangés avec ceux de SimpleTest mais vous ne pouvez pas utiliser les assertions de SimpleTest au sein des versions héritées des scénarios de test. La raison ? Une simple vérification que vous ne rendez pas par accident vos scénarios de test complètement dépendants de SimpleTest. Peut-être que vous souhaitez publier votre bibliothèque sur PEAR par exemple : ça voudrait dire la livrer avec des scénarios de test compatibles avec PEAR::PhpUnit.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+
+
diff --git a/tests/UnitTests/simpletest/docs/fr/index.html b/tests/UnitTests/simpletest/docs/fr/index.html
new file mode 100644
index 00000000..c0db74ae
--- /dev/null
+++ b/tests/UnitTests/simpletest/docs/fr/index.html
@@ -0,0 +1,343 @@
+
+
+
+
+ Télécharger le framework de tests Simple Test - Tests unitaire et objets fantaisie pour PHP
+
+
+
+
+
+ Le présent article présuppose que vous soyez familier avec le concept de tests unitaires ainsi que celui de développement web avec le langage PHP. Il s'agit d'un guide pour le nouvel et impatient utilisateur de SimpleTest. Pour une documentation plus complète, particulièrement si vous découvrez les tests unitaires, consultez la documentation en cours, et pour des exemples de scénarios de test, consultez le tutorial sur les tests unitaires.
+
+ Parmi les outils de test pour logiciel, le testeur unitaire est le plus proche du développeur. Dans un contexte de développement agile, le code de test se place juste à côté du code source étant donné que tous les deux sont écrits simultanément. Dans ce contexte, SimpleTest aspire à être une solution complète de test pour un développeur PHP et s'appelle "Simple" parce qu'elle devrait être simple à utiliser et à étendre. Ce nom n'était pas vraiment un bon choix. Non seulement cette solution inclut toutes les fonctions classiques qu'on est en droit d'attendre de la part des portages de JUnit et des PHPUnit, mais elle inclut aussi les objets fantaisie ou "mock objects". Sans compter quelques fonctionnalités de JWebUnit : parmi celles-ci la navigation sur des pages web, les tests sur les cookies et l'envoi de formulaire.
+
+
+ La démonstration la plus rapide : l'exemple
+
+
+ Supposons que nous sommes en train de tester une simple classe de log dans un fichier : elle s'appelle Log dans classes/Log.php. Commençons par créer un script de test, appelé tests/log_test.php. Son contenu est le suivant...
+
+ Ici le répertoire simpletest est soit dans le dossier courant, soit dans les dossiers pour fichiers inclus. Vous auriez à éditer ces arborescences suivant l'endroit où vous avez installé SimpleTest. Ensuite créons un scénario de test...
+
+ A présent il y a 5 lignes de code d'échafaudage et toujours pas de test. Cependant à partir de cet instant le retour sur investissement arrive très rapidement. Supposons que la classe Log prenne le nom du fichier à écrire dans le constructeur et que nous ayons un répertoire temporaire dans lequel placer ce fichier...
+
+<?php
+require_once('simpletest/unit_tester.php');
+require_once('simpletest/reporter.php');
+require_once('../classes/log.php');
+
+class TestOfLogging extends UnitTestCase {
+
+ function testCreatingNewFile() {
+ @unlink('/temp/test.log');
+ $log = new Log('/temp/test.log');
+ $this->assertFalse(file_exists('/temp/test.log'));
+ $log->message('Should write this to a file');
+ $this->assertTrue(file_exists('/temp/test.log'));
+ }
+}
+?>
+
+ Au lancement du scénario de test, toutes les méthodes qui commencent avec la chaîne test sont identifiées puis exécutées. D'ordinaire nous avons bien plusieurs méthodes de tests. Les assertions dans les méthodes de test envoient des messages vers le framework de test qui affiche immédiatement le résultat. Cette réponse immédiate est importante, non seulement lors d'un crash causé par le code, mais aussi de manière à rapprocher l'affichage de l'erreur au plus près du scénario de test concerné.
+
+
+ Pour voir ces résultats lançons effectivement les tests. S'il s'agit de l'unique scénario de test à lancer, on peut y arriver avec...
+
+<?php
+require_once('simpletest/unit_tester.php');
+require_once('simpletest/reporter.php');
+require_once('../classes/log.php');
+
+class TestOfLogging extends UnitTestCase {
+
+ function testCreatingNewFile() {
+ @unlink('/temp/test.log');
+ $log = new Log('/temp/test.log');
+ $this->assertFalse(file_exists('/temp/test.log'));
+ $log->message('Should write this to a file');
+ $this->assertTrue(file_exists('/temp/test.log'));
+ }
+}
+
+$test = &new TestOfLogging();
+$test->run(new HtmlReporter());
+?>
+
+ Fatal error: Failed opening required '../classes/log.php' (include_path='') in /home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php on line 7
+
+ c'est qu'il vous manque le fichier classes/Log.php qui pourrait ressembler à :
+
+ Il est peu probable que dans une véritable application on ait uniquement besoin de passer un seul scénario de test. Cela veut dire que nous avons besoin de grouper les scénarios dans un script de test qui peut, si nécessaire, lancer tous les tests de l'application.
+
+
+ Notre première étape est de supprimer les includes et de défaire notre hack précédent...
+
+<?php
+require_once('../classes/log.php');
+
+class TestOfLogging extends UnitTestCase {
+
+ function testCreatingNewFile() {
+ @unlink('/temp/test.log');
+ $log = new Log('/temp/test.log');
+ $this->assertFalse(file_exists('/temp/test.log'));
+ $log->message('Should write this to a file');
+ $this->assertTrue(file_exists('/temp/test.log'));
+ }
+}
+?>
+
+ Ensuite nous créons un nouveau fichier appelé tests/all_tests.php. On y insert le code suivant...
+
+ Cette méthode GroupTest::addTestFile() va inclure le fichier de scénarios de test et lire parmi toutes les nouvelles classes créées celles qui sont issues de TestCase. Dans un premier temps, seuls les noms sont stockés, de la sorte le lanceur de test peut instancier la classe au fur et à mesure qu'il exécute votre suite de tests.
+
+
+ Pour que ça puisse marcher proprement le fichier de suite de tests ne devrait pas inclure aveuglement d'autres extensions de scénarios de test qui n'exécuteraient pas effectivement de test. Le résultat pourrait être que des tests supplémentaires soient alors être comptabilisés pendant l'exécution des tests. Ce n'est pas un problème grave mais pour éviter ce désagrément, il suffit d'ajouter la commande SimpleTestOptions::ignore() quelque part dans le fichier de scénario de test. Par ailleurs le scénario de test ne devrait pas avoir été inclus ailleurs ou alors aucun scénario ne sera ajouté aux groupes de test. Il s'agirait là d'une erreur autrement sérieuse : si tous les classes de scénario de test sont chargées par PHP, alors la méthode GroupTest::addTestFile() ne pourra pas les détecter.
+
+
+ Pour afficher les résultats, il est seulement nécessaire d'invoquer tests/all_tests.php à partir du serveur web.
+
+ Supposons que notre class logging soit testée et terminée. Supposons aussi que nous testons une autre classe qui ait besoin d'écrire des messages de log, disons SessionPool. Nous voulons tester une méthode qui ressemblera probablement à quelque chose comme...
+
+ Avec le concept de "réutilisation de code" comme fil conducteur, nous utilisons notre class Log. Un scénario de test classique ressemblera peut-être à...
+
+ Le design de ce scénario de test n'est pas complètement mauvais, mais on peut l'améliorer. Nous passons du temps à tripoter les fichiers de log qui ne font pas partie de notre test. Pire, nous avons créé des liens de proximité entre la classe Log et ce test. Que se passerait-il si nous n'utilisions plus de fichiers, mais la bibliothèque syslog à la place ? Avez-vous remarqué le retour chariot supplémentaire à la fin du message ? A-t-il été ajouté par le loggueur ? Et si il ajoutait aussi un timestamp ou d'autres données ?
+
+
+ L'unique partie à tester réellement est l'envoi d'un message précis au loggueur. Nous réduisons le couplage en créant une fausse classe de logging : elle ne fait qu'enregistrer le message pour le test, mais ne produit aucun résultat. Sauf qu'elle doit ressembler exactement à l'original.
+
+
+ Si l'objet fantaisie n'écrit pas dans un fichier alors nous nous épargnons la suppression du fichier avant et après le test. Nous pourrions même nous épargner quelques lignes de code supplémentaires si l'objet fantaisie pouvait exécuter l'assertion.
+
+
+ Trop beau pour être vrai ? Par chance on peut créer un tel objet très facilement...
+
+ L'appel tally() est nécessaire pour annoncer à l'objet fantaisie qu'il n'y aura plus d'appels ultérieurs. Sans ça l'objet fantaisie pourrait attendre pendant une éternité l'appel de la méthode sans jamais prévenir le scénario de test. Les autres tests sont déclenchés automatiquement quand l'appel à message() est invoqué sur l'objet MockLog. L'appel mock va déclencher une comparaison des paramètres et ensuite envoyer le message "pass" ou "fail" au test pour l'affichage. Des jokers peuvent être inclus ici aussi afin d'empêcher que les tests ne deviennent trop spécifiques.
+
+
+ Les objets fantaisie dans la suite SimpleTest peuvent avoir un ensemble de valeurs de sortie arbitraires, des séquences de sorties, des valeurs de sortie sélectionnées à partir des arguments d'entrée, des séquences de paramètres attendus et des limites sur le nombre de fois qu'une méthode peut être invoquée.
+
+
+ Pour que ce test fonctionne la librairie avec les objets fantaisie doit être incluse dans la suite de tests, par exemple dans all_tests.php.
+
+ Une des exigences des sites web, c'est qu'ils produisent des pages web. Si vous construisez un projet de A à Z et que vous voulez intégrer des tests au fur et à mesure alors vous voulez un outil qui puisse effectuer une navigation automatique et en examiner le résultat. C'est le boulot d'un testeur web.
+
+
+ Effectuer un test web via SimpleTest reste assez primitif : il n'y a pas de javascript par exemple. Pour vous donner une idée, voici un exemple assez trivial : aller chercher une page web, à partir de là naviguer vers la page "about" et finalement tester un contenu déterminé par le client.
+
+<?php
+require_once('simpletest/web_tester.php');
+require_once('simpletest/reporter.php');
+
+class TestOfAbout extends WebTestCase {
+
+ function setUp() {
+ $this->get('http://test-server/index.php');
+ $this->clickLink('About');
+ }
+
+ function testSearchEngineOptimisations() {
+ $this->assertTitle('A long title about us for search engines');
+ $this->assertWantedPattern('/a popular keyphrase/i');
+ }
+}
+$test = &new TestOfAbout();
+$test->run(new HtmlReporter());
+?>
+
+ Avec ce code comme test de recette, vous pouvez vous assurer que le contenu corresponde toujours aux spécifications à la fois des développeurs et des autres parties prenantes au projet.
+
+
+
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+ Les objets fantaisie - ou "mock objects" en anglais - ont deux rôles pendant un scénario de test : acteur et critique.
+
+
+ Le comportement d'acteur est celui de simuler des objets difficiles à initialiser ou trop consommateurs en temps pendant un test. Le cas classique est celui de la connexion à une base de données. Mettre sur pied une base de données de test au lancement de chaque test ralentirait considérablement les tests et en plus exigerait l'installation d'un moteur de base de données ainsi que des données sur la machine de test. Si nous pouvons simuler la connexion et renvoyer des données à notre guise alors non seulement nous gagnons en pragmatisme sur les tests mais en sus nous pouvons nourrir notre base avec des données falsifiées et voir comment il répond. Nous pouvons simuler une base de données en suspens ou d'autres cas extrêmes sans avoir à créer une véritable panne de base de données. En d'autres termes nous pouvons gagner en contrôle sur l'environnement de test.
+
+
+ Si les objets fantaisie ne se comportaient que comme des acteurs alors on les connaîtrait sous le nom de bouchons serveur.
+
+
+ Cependant non seulement les objets fantaisie jouent un rôle (en fournissant à la demande les valeurs requises) mais en plus ils sont aussi sensibles aux messages qui leur sont envoyés (par le biais d'attentes). En posant les paramètres attendus d'une méthode ils agissent comme des gardiens : un appel sur eux doit être réalisé correctement. Si les attentes ne sont pas atteintes ils nous épargnent l'effort de l'écriture d'une assertion de test avec échec en réalisant cette tâche à notre place. Dans le cas d'une connexion à une base de données imaginaire ils peuvent tester si la requête, disons SQL, a bien été formé par l'objet qui utilise cette connexion. Mettez-les sur pied avec des attentes assez précises et vous verrez que vous n'aurez presque plus d'assertion à écrire manuellement.
+
+ Comme pour la création des bouchons serveur, tout ce dont nous avons besoin c'est d'un classe existante. La fameuse connexion à une base de données qui ressemblerait à...
+
+class DatabaseConnection {
+ function DatabaseConnection() {
+ }
+
+ function query() {
+ }
+
+ function selectQuery() {
+ }
+}
+
+ Cette classe n'a pas encore besoin d'être implémentée. Pour en créer sa version fantaisie nous devons juste inclure la librairie d'objet fantaisie puis lancer le générateur...
+
+ Ceci génère une classe clone appelée MockDatabaseConnection. Nous pouvons désormais créer des instances de cette nouvelle classe à l'intérieur même de notre scénario de test...
+
+ Contrairement aux bouchons, le constructeur d'une classe fantaisie a besoin d'une référence au scénario de test pour pouvoir transmettre les succès et les échecs pendant qu'il vérifie les attentes. Concrètement ça veut dire que les objets fantaisie ne peuvent être utilisés qu'au sein d'un scénario de test. Malgré tout, cette puissance supplémentaire implique que les bouchons ne sont que rarement utilisés si des objets fantaisie sont disponibles.
+
+
+ La version fantaisie d'une classe contient toutes les méthodes de l'originale. De la sorte une opération comme $connection->query() est encore possible. Tout comme avec les bouchons, nous pouvons remplacer la valeur nulle renvoyée par défaut...
+
+$connection->setReturnValue('query', 37);
+
+ Désormais à chaque appel de $connection->query() nous recevons comme résultat 37. Tout comme avec les bouchons nous pouvons utiliser des jokers et surcharger le paramètre joker. Nous pouvons aussi ajouter des méthodes supplémentaires à l'objet fantaisie lors de sa génération et lui choisir un nom de classe qui lui soit propre...
+
+ Ici l'objet fantaisie se comportera comme si setOptions() existait dans la classe originale. C'est pratique si une classe a utilisé le mécanisme overload() de PHP pour ajouter des méthodes dynamiques. Vous pouvez créer des fantaisies spéciales pour simuler cette situation.
+
+
+ Tous les modèles disponibles avec les bouchons serveur le sont également avec les objets fantaisie...
+
+class Iterator {
+ function Iterator() {
+ }
+
+ function next() {
+ }
+}
+
+ Une nouvelle fois, supposons que cet itérateur ne retourne que du texte jusqu'au moment où il atteint son terme, quand il renvoie false. Nous pouvons le simuler avec...
+
+ Au moment du premier appel à next() sur l'itérateur fantaisie il renverra tout d'abord "First string", puis ce sera au tour de "Second string" au deuxième appel et ensuite pour tout appel suivant false sera renvoyé. Ces valeurs renvoyées successivement sont prioritaires sur la valeur constante retournée. Cette dernière est un genre de valeur par défaut si vous voulez.
+
+
+ Reprenons aussi le conteneur d'information bouchonné avec des pairs clef / valeur...
+
+class Configuration {
+ function Configuration() {
+ }
+
+ function getValue($key) {
+ }
+}
+
+ Il s'agit là d'une situation classique d'utilisation d'objets fantaisie étant donné que la configuration peut varier grandement de machine à machine : ça contraint fortement la fiabilité de nos tests si nous l'utilisons directement. Le problème est que toutes les données nous parviennent à travers la méthode getValue() et que nous voulons des résultats différents pour des clefs différentes. Heureusement les objets fantaisie ont un système de filtrage...
+
+ Le paramètre en plus est une liste d'arguments à faire correspondre. Dans ce cas nous essayons de faire correspondre un unique argument : en l'occurrence la clef recherchée. Maintenant que la méthode getValue() est invoquée sur l'objet fantaisie...
+
+$config->getValue('db_user')
+
+ ...elle renverra "admin". Elle le trouve en essayant de faire correspondre les arguments entrants dans sa liste d'arguments sortants les uns après les autres jusqu'au moment où une correspondance exacte est atteinte.
+
+
+ Il y a des fois où vous souhaitez qu'un objet spécifique soit servi par la fantaisie plutôt qu'une copie. De nouveau c'est identique au mécanisme des bouchons serveur...
+
+ Même si les bouchons serveur vous isolent du désordre du monde réel, il ne s'agit là que de la moitié du bénéfice potentiel. Vous pouvez avoir une classe de test recevant les messages ad hoc, mais est-ce que votre nouvelle classe renvoie bien les bons ? Le tester peut devenir cafouillis sans une librairie d'objets fantaisie.
+
+
+ Pour l'exemple, prenons une classe SessionPool à laquelle nous allons ajouter une fonction de log. Plutôt que de complexifier la classe originale, nous souhaitons ajouter ce comportement avec un décorateur (GOF). Pour l'instant le code de SessionPool ressemble à...
+
+ Dans tout ceci, la seule classe à tester est LoggingSessionPool. En particulier, nous voulons vérifier que la méthode findSession() est appelée avec le bon identifiant de session au sein du cookie et qu'elle renvoie bien le message "Starting session $cookie" au loggueur.
+
+
+ Bien que nous ne testions que quelques lignes de code de production, voici la liste des choses à faire dans un scénario de test conventionnel :
+
+
Créer un objet de log.
+
Indiquer le répertoire d'écriture du fichier de log.
+
Modifier les droits sur le répertoire pour pouvoir y écrire le fichier.
+
Créer un objet SessionPool.
+
Lancer une session, ce qui demande probablement pas mal de choses.
+
Invoquer findSession().
+
Lire le nouvel identifiant de sessions (en espérant qu'il existe un accesseur !).
+
Lever une assertion de test pour vérifier que cet identifiant correspond bien au cookie.
+
Lire la dernière ligne du fichier de log.
+
Supprimer avec une (ou plusieurs) expression rationnelle les timestamps de log en trop, etc.
+
Vérifier que le message de session est bien dans le texte.
+
+ Pas étonnant que les développeurs détestent écrire des tests quand ils sont aussi ingrats. Pour rendre les choses encore pire, à chaque fois que le format de log change ou bien que la méthode de création des sessions change, nous devons réécrire une partie des tests alors même qu'ils ne testent pas ces parties du système. Nous sommes en train de préparer le cauchemar pour les développeurs de ces autres classes.
+
+
+ A la place, voici la méthode complète pour le test avec un peu de magie via les objets fantaisie...
+
+ Commençons par écrire une session simulacre. Pas la peine d'être trop pointilleux avec celle-ci puisque la vérification de la session désirée est effectuée ailleurs. Nous avons juste besoin de vérifier qu'il s'agit de la même que celle qui vient du groupe commun des sessions.
+
+
+ findSession() est un méthode fabrique dont la simulation est décrite plus haut. Le point de départ vient avec le premier appel expectOnce(). Cette ligne indique qu'à chaque fois que findSession() est invoqué sur l'objet fantaisie, il vérifiera les arguments entrant. S'il ne reçoit que la chaîne "abc" en tant qu'argument alors un succès est envoyé au testeur unitaire, sinon c'est un échec qui est généré. Il s'agit là de la partie qui teste si nous avons bien la bonne session. La liste des arguments suit une format identique à celui qui précise les valeurs renvoyées. Vous pouvez avoir des jokers et des séquences et l'ordre de l'évaluation restera le même.
+
+
+ Si l'appel n'est jamais effectué alors n'est généré ni le succès, ni l'échec. Pour contourner cette limitation, nous devons dire à l'objet fantaisie que le test est terminé : il pourra alors décider si les attentes ont été répondues. L'assertion du testeur unitaire de ceci est déclenchée par l'appel tally() à la fin du test.
+
+
+ Nous utilisons le même modèle pour mettre sur pied le loggueur fantaisie. Nous lui indiquons que message() devrait être invoqué une fois et une fois seulement avec l'argument "Starting session abc". En testant les arguments d'appel, plutôt que ceux de sorite du loggueur, nous isolons le test de tout modification dans le loggueur.
+
+
+ Nous commençons le lancement nos tests à la création du nouveau LoggingSessionPool et nous l'alimentons avec nos objets fantaisie juste créés. Désormais tout est sous contrôle. Au final nous confirmons que le $session donné au décorateur est bien celui reçu et prions les objets fantaisie de lancer leurs tests de comptage d'appel interne avec les appels tally().
+
+
+ Il y a encore pas mal de code de test, mais ce code est très strict. S'il vous semble encore terrifiant il l'est bien moins que si nous avions essayé sans les objets fantaisie et ce test en particulier, interactions plutôt que résultat, est toujours plus difficile à mettre en place. Le plus souvent vous aurez besoin de tester des situations plus complexes sans ce niveau ni cette précision. En outre une partie peut être remaniée avec la méthode de scénario de test setUp().
+
+
+ Voici la liste complète des attentes que vous pouvez placer sur un objet fantaisie avec SimpleTest...
+
+
+
+
Attente
Nécessite tally()
+
+
+
+
+
expectArguments($method, $args)
+
Non
+
+
+
expectArgumentsAt($timing, $method, $args)
+
Non
+
+
+
expectCallCount($method, $count)
+
Oui
+
+
+
expectMaximumCallCount($method, $count)
+
Non
+
+
+
expectMinimumCallCount($method, $count)
+
Oui
+
+
+
expectNever($method)
+
Non
+
+
+
expectOnce($method, $args)
+
Oui
+
+
+
expectAtLeastOnce($method, $args)
+
Oui
+
+
+
+ Où les paramètres sont...
+
+
$method
+
Le nom de la méthode, sous la forme d'une chaîne, à laquelle la condition doit être appliquée.
+
$args
+
+ Les arguments sous la forme d'une liste. Les jokers peuvent être inclus de la même manière qu'avec setReturn(). Cet argument est optionel pour expectOnce() et expectAtLeastOnce().
+
+
$timing
+
+ Le seul point dans le temps pour tester la condition. Le premier appel commence à zéro.
+
+
$count
+
Le nombre d'appels attendu.
+
+ La méthode expectMaximumCallCount() est légèrement différente dans le sens où elle ne pourra générer qu'un échec. Elle reste silencieuse si la limite n'est jamais atteinte.
+
+
+ Comme avec les assertions dans les scénarios de test, toutes ces attentes peuvent accepter une surcharge de message sous la forme d'un paramètre supplémentaire. Par ailleurs le message d'échec original peut être inclus dans le résultat avec "%s".
+
+ Il existe trois approches pour créer des objets fantaisie en comprenant celle utiliser par SimpleTest. Les coder à la main en utilisant une classe de base, les générer dans un fichier ou les générer dynamiquement à la volée.
+
+
+ Les objets fantaisie générés avec SimpleTest sont dynamiques. Ils sont créés à l'exécution dans la mémoire, grâce à eval(), plutôt qu'écrit dans un fichier. Cette opération les rend facile à créer, en une seule ligne, surtout par rapport à leur création à la main dans une hiérarchie de classe parallèle. Le problème avec ce comportement tient généralement dans la mise en place des tests proprement dits. Si les objets originaux changent les versions fantaisie sur lesquels reposent les tests, une désynchronisation peut subvenir. Cela peut aussi arriver avec l'approche en hiérarchie parallèle, mais c'est détecté beaucoup plus vite.
+
+
+ Bien sûr, la solution est d'ajouter de véritables tests d'intégration. Vous n'en avez pas besoin de beaucoup et le côté pratique des objets fantaisie fait plus que compenser la petite dose de test supplémentaire. Vous ne pouvez pas avoir confiance dans du code qui ne serait testé que par des objets fantaisie.
+
+
+ Si vous restez déterminé de construire des librairies statiques d'objets fantaisie parce que vous souhaitez émuler un comportement très spécifique, vous pouvez y parvenir grâce au générateur de classe de SimpleTest. Dans votre fichier librairie, par exemple mocks/connection.php pour une connexion à une base de données, créer un objet fantaisie et provoquer m'héritage pour hériter pour surcharger des méthodes spéciales ou ajouter des préréglages...
+
+ L'appel generate dit au générateur de classe d'en créer une appelée BasicMockConnection plutôt que la plus courante MockConnection. Ensuite nous héritons à partir de celle-ci pour obtenir notre version de MockConnection. En interceptant de cette manière nous pouvons ajouter un comportement, ici transformer la valeur par défaut de query() en "false".
+ En utilisant le nom par défaut nous garantissons que le générateur de classe fantaisie n'en recréera pas une autre différente si il est invoqué ailleurs dans les tests. Il ne créera jamais de classe si elle existe déjà. Aussi longtemps que le fichier ci-dessus est inclus avant alors tous les tests qui généraient MockConnection devraient utiliser notre version à présent. Par contre si nous avons une erreur dans l'ordre et que la librairie de fantaisie en crée une d'abord alors la création de la classe échouera tout simplement.
+
+
+ Utiliser cette astuce si vous vous trouvez avec beaucoup de comportement en commun sur les objets fantaisie ou si vous avez de fréquents problèmes d'intégration plus tard dans les étapes de test.
+
+ Mais au moment d'écrire ces lignes c'est le seul à gérer les objets fantaisie, donc vous êtes bloqué avec lui ?
+
+
+ Non, pas du tout.
+ SimpleTest est une boîte à outils et parmi ceux-ci on trouve les objets fantaisie qui peuvent être utilisés indépendamment. Supposons que vous avez votre propre testeur unitaire favori et que tous vos tests actuels l'utilisent. Prétendez que vous avez appelé votre tester unitaire PHPUnit (c'est ce que tout le monde a fait) et que la classe principale de test ressemble à...
+
+ La seule chose que la méthode assertion() réalise, c'est de préparer une sortie embellie alors le paramètre boolien de l'assertion sert à déterminer s'il s'agit d'une erreur ou d'un succès. Supposons qu'elle est utilisée de la manière suivante...
+
+$unit_test = new PHPUnit();
+$unit_test>assertion('I hope this file exists', file_exists('my_file'));
+
+ Comment utiliser les objets fantaisie avec ceci ?
+
+
+ Il y a une méthode protégée sur la classe de base des objets fantaisie : elle s'appelle _assertTrue(). En surchargeant cette méthode nous pouvons utiliser notre propre format d'assertion. Nous commençons avec une sous-classe, dans my_mock.php...
+
+ Maintenant une instance de MyMock créera un objet qui parle le même langage que votre testeur. Bien sûr le truc c'est que nous créons jamais un tel objet : le générateur s'en chargera. Nous avons juste besoin d'une ligne de code supplémentaire pour dire au générateur d'utiliser vos nouveaux objets fantaisie...
+
+ A partir de maintenant vous avez juste à inclure my_mock.php à la place de la version par défaut simple_mock.php et vous pouvez introduire des objets fantaisie dans votre suite de tests existants.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+
+
diff --git a/tests/UnitTests/simpletest/docs/fr/overview.html b/tests/UnitTests/simpletest/docs/fr/overview.html
new file mode 100644
index 00000000..3d6663a0
--- /dev/null
+++ b/tests/UnitTests/simpletest/docs/fr/overview.html
@@ -0,0 +1,294 @@
+
+
+
+
+ Aperçu et liste des fonctionnalités des testeurs unitaires PHP et web de SimpleTest PHP
+
+
+
+
+
+ Le coeur de SimpleTest est un framework de test construit autour de classes de scénarios de test. Celles-ci sont écrites comme des extensions des classes premières de scénarios de test, chacune élargie avec des méthodes qui contiennent le code de test effectif. Les scripts de test de haut niveau invoque la méthode run() à chaque scénario de test successivement. Chaque méthode de test est écrite pour appeler des assertions diverses que le développeur suppose être vraies, assertEqual() par exemple. Si l'assertion est correcte, alors un succès est expédié au rapporteur observant le test, mais toute erreur déclenche une alerte et une description de la dissension.
+
+ Ces outils sont conçus pour le développeur. Les tests sont écrits en PHP directement, plus ou moins simultanément avec la construction de l'application elle-même. L'avantage d'utiliser PHP lui-même comme langage de test est qu'il n'y a pas de nouveau langage à apprendre, les tests peuvent commencer directement et le développeur peut tester n'importe quelle partie du code. Plus simplement, toutes les parties qui peuvent être accédées par le code de l'application peuvent aussi être accédées par le code de test si ils sont tous les deux dans le même langage.
+
+
+ Le type de scénario de test le plus simple est le UnitTestCase. Cette classe de scénario de test inclut les tests standards pour l'égalité, les références et l'appariement de motifs (via les expressions rationnelles). Ceux-ci testent ce que vous seriez en droit d'attendre du résultat d'une fonction ou d'une méthode. Il s'agit du type de test le plus commun pendant le quotidien du développeur, peut-être 95% des scénarios de test.
+
+
+ La tâche ultime d'une application web n'est cependant pas de produire une sortie correcte à partir de méthodes ou d'objets, mais plutôt de produire des pages web. La classe WebTestCase teste des pages web. Elle simule un navigateur web demandant une page, de façon exhaustive : cookies, proxies, connexions sécurisées, authentification, formulaires, cadres et la plupart des éléments de navigation. Avec ce type de scénario de test, le développeur peut garantir que telle ou telle information est présente dans la page et que les formulaires ainsi que les sessions sont gérés comme il faut.
+
+ Ci-dessous vous trouverez un canevas assez brut des fonctionnalités à aujourd'hui et pour demain, sans oublier leur date approximative de publication. J'ai bien peur qu'il soit modifiable sans pré-avis étant donné que les jalons dépendent beaucoup sur le temps disponible. Les trucs en vert ont été codés, mais pas forcément déjà rendus public. Si vous avez une besoin pressant pour une fonctionnalité verte mais pas encore publique alors vous devriez retirer le code directement sur le CVS chez SourceFourge. Une fonctionnalitée publiée est indiqué par "Fini".
+
+
+
+
Fonctionnalité
Description
Publication
+
+
+
+
+
Scénariot de test unitaire
+
Les classes de test et assertions de base
+
Fini
+
+
+
Affichage HTML
+
L'affichage le plus simple possible
+
Fini
+
+
+
Autochargement des scénarios de test
+
Lire un fichier avec des scénarios de test et les charger dans un groupe de test automatiquement
+
Fini
+
+
+
Générateur de code d'objets fantaisie
+
Des objets capable de simuler d'autres objets, supprimant les dépendances dans les tests
+
Fini
+
+
+
Bouchons serveur
+
Des objets fantaisie sans résultat attendu à utiliser à l'extérieur des scénarios de test, pour le prototypage par exemple.
+
Fini
+
+
+
Intégration d'autres testeurs unitaires
+
+ La capacité de lire et simuler d'autres scénarios de test en provenance de PHPUnit et de PEAR::Phpunit.
+
Fini
+
+
+
Scénario de test web
+
Appariement basique de motifs dans une page téléchargée.
+
Fini
+
+
+
Analyse de page HTML
+
Permet de suivre les liens et de trouver la balise de titre
+
Fini
+
+
+
Simulacre partiel
+
Simuler des parties d'une classe pour tester moins qu'une classe ou dans des cas complexes.
+
Fini
+
+
+
Gestion des cookies Web
+
Gestion correcte des cookies au téléchargement d'une page.
+
Fini
+
+
+
Suivi des redirections
+
Le téléchargement d'une page suit automatiquement une redirection 300.
+
Fini
+
+
+
Analyse d'un formulaire
+
La capacité de valider un formulaire simple et d'en lire les valeurs par défaut.
+
Fini
+
+
+
Interface en ligne de commande
+
Affiche le résultat des tests sans navigateur web.
+
Fini
+
+
+
Mise à nu des attentes d'une classe
+
Peut créer des tests précis avec des simulacres ainsi que des scénarios de test.
+
Fini
+
+
+
Sortie et analyse XML
+
Permet de tester sur plusieurs hôtes et d'intégrer des extensions d'acceptation de test.
+
Fini
+
+
+
Scénario de test en ligne de commande
+
Permet de tester des outils ou scripts en ligne de commande et de manier des fichiers.
+
Fini
+
+
+
Compatibilité avec PHP Documentor
+
Génération automatique et complète de la documentation au niveau des classes.
+
Fini
+
+
+
Interface navigateur
+
Mise à nu des niveaux bas de l'interface du navigateur web pour des scénarios de test plus précis.
+
Fini
+
+
+
Authentification HTTP
+
Téléchargement des pages web protégées avec une authentification basique seulement.
+
Fini
+
+
+
Boutons de navigation d'un navigateur
+
Arrière, avant et recommencer
+
Fini
+
+
+
Support de SSL
+
Peut se connecter à des pages de type https.
+
Fini
+
+
+
Support de proxy
+
Peut se connecter via des proxys communs
+
Fini
+
+
+
Support des cadres
+
Gère les cadres dans les scénarios de test web.
+
Fini
+
+
+
Amélioration de l'affichage des tests
+
Une meilleure interface graphique web, avec un arbre des scénarios de test.
+
1.1
+
+
+
Localisation
+
Abstraction des messages et génration du code à partir de fichiers XML.
+
1.1
+
+
+
Simulation d'interface
+
Peut générer des objets fantaisie tant vers des interfaces que vers des classes.
+
2.0
+
+
+
Test sur es exceptions
+
Dans le même esprit que sur les tests des erreurs PHP.
+
2.0
+
+
+
Rercherche d'éléments avec XPath
+
Peut utiliser Tidy HTML pour un appariement plus rapide et plus souple.
+
2.0
+
+
+
Test de l'upload de fichier
+
Peut simuler la balise input de type file
+
2.0
+
+
+
+ La migration vers PHP5 commencera juste après la série des 1.0, à partir de là PHP4 ne sera plus supporté. SimpleTest est actuellement compatible avec PHP5 mais n'utilisera aucune des nouvelles fonctionnalités avant la version 2.
+
+
+
+ Le processus est au moins aussi important que les outils. Le type de procédure que fait un usage le plus intensif des outils de test pour développeur est bien sûr l'Extreme Programming. Il s'agit là d'une des méthodes agiles qui combinent plusieurs pratiques pour "lisser la courbe de coût" du développement logiciel. La plus extrème reste le développement piloté par les tests, où vous devez adhérer à la règle du pas de code avant d'avoir un test. Si vous êtes plutôt du genre planninficateur ou que vous estimez que l'expérience compte plus que l'évolution, vous préférerez peut-être l'approche RUP. Je ne l'ai pas testé mais je peux voir où vous aurez besoin d'outils de test (cf. illustration 9).
+
+
+ La plupart des testeurs unitaires sont dans une certaine mesure un clone de JUnit, au moins dans l'interface. Il y a énormément d'information sur le site de JUnit, à commencer par la FAQ quie contient pas mal de conseils généraux sur les tests. Une fois mordu par le bogue vous apprécierez sûrement la phrase infecté par les tests trouvée par Eric Gamma. Si vous êtes encore en train de tergiverser sur un testeur unitaire, sachez que les choix principaux sont PHPUnit et Pear PHP::PHPUnit. De nombreuses fonctionnalités de SimpleTest leurs font défaut, mais la version PEAR a d'ores et déjà été mise à jour pour PHP5. Elle est aussi recommandée si vous portez des scénarios de test existant depuis JUnit.
+
+
+ Les développeurs de bibliothèque n'ont pas l'air de livrer très souvent des tests avec leur code : c'est bien dommage. Le code d'une bibliothèque qui inclut des tests peut être remanié avec plus de sécurité et le code de test sert de documentation additionnelle dans un format assez standard. Ceci peut épargner la pêche aux indices dans le code source lorsque qu'un problème survient, en particulier lors de la mise à jour d'une telle bibliothèque. Parmi les bibliothèques utilisant SimpleTest comme testeur unitaire on retrouve WACT et PEAR::XML_HTMLSax.
+
+
+ Au jour d'aujourd'hui il manque tristement beaucoup de matière sur les objets fantaisie : dommage, surtout que tester unitairement sans eux représente pas mal de travail en plus. L'article original sur les objets fantaisie est très orienté Java, mais reste intéressant à lire. Etant donné qu'il s'agit d'une nouvelle technologie il y a beaucoup de discussions et de débats sur comment les utiliser, souvent sur des wikis comme Extreme Tuesday ou www.mockobjects.comou the original C2 Wiki. Injecter des objets fantaisie dans une classe est un des champs principaux du débat : cet article chez IBM en est un bon point de départ.
+
+
+ Il y a énormement d'outils de test web mais la plupart sont écrits en Java. De plus les tutoriels et autres conseils sont plutôt rares. Votre seul espoir est de regarder directement la documentation pour HTTPUnit, HTMLUnit ou JWebUnit et d'espérer y trouver pour des indices. Il y a aussi des frameworks basés sur XML, mais de nouveau la plupart ont besoin de Java pour tourner.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+ Un objet fantaisie partiel n'est ni plus ni moins qu'un modèle de conception pour soulager un problème spécifique du test avec des objets fantaisie, celui de placer des objets fantaisie dans des coins serrés. Il s'agit d'un outil assez limité et peut-être même une idée pas si bonne que ça. Elle est incluse dans SimpleTest pour la simple raison que je l'ai trouvée utile à plus d'une occasion et qu'elle m'a épargnée pas mal de travail dans ces moments-là.
+
+ Quand un objet en utilise un autre il est très simple d'y faire circuler une version fantaisie déjà prête avec ses attentes. Les choses deviennent un peu plus délicates si un objet en crée un autre et que le créateur est celui que l'on souhaite tester. Cela revient à dire que l'objet créé devrait être une fantaisie, mais nous pouvons difficilement dire à notre classe sous test de créer un objet fantaisie plutôt qu'un "vrai" objet. La classe testée ne sait même pas qu'elle travaille dans un environnement de test.
+
+
+ Par exemple, supposons que nous sommes en train de construire un client telnet et qu'il a besoin de créer une socket réseau pour envoyer ses messages. La méthode de connexion pourrait ressemble à quelque chose comme...
+
+ Nous voudrions vraiment avoir une version fantaisie de l'objet socket, que pouvons nous faire ?
+
+
+ La première solution est de passer la socket en tant que paramètre, ce qui force la création au niveau inférieur. Charger le client de cette tâche est effectivement une bonne approche si c'est possible et devrait conduire à un remaniement -- de la création à partir de l'action. En fait, c'est là une des manières avec lesquels tester en s'appuyant sur des objets fantaisie vous force à coder des solutions plus resserrées sur leur objectif. Ils améliorent votre programmation.
+
+ C'est assez évident que vous ne pouvez descendre que d'un niveau. Vous ne voudriez pas que votre application de haut niveau crée tous les fichiers de bas niveau, sockets et autres connexions à la base de données dont elle aurait besoin. Elle ne connaîtrait pas les paramètres du constructeur de toute façon.
+
+
+ La solution suivante est de passer l'objet créé sous la forme d'un paramètre optionnel...
+
+ Le problème de cette approche tient dans son manque de netteté. Il y a du code de test dans la classe principale et aussi des paramètres transmis dans le scénario de test qui ne sont jamais utilisés. Il s'agit là d'une approche rapide et sale, mais qui ne reste pas moins efficace dans la plupart des situations.
+
+
+ Une autre solution encore est de laisser un objet fabrique s'occuper de la création...
+
+ Il s'agit là probablement de la réponse la plus travaillée étant donné que la création est maintenant située dans une petite classe spécialisée. La fabrique réseau peut être testée séparément et utilisée en tant que fantaisie quand nous testons la classe telnet...
+
+ Le problème reste que nous ajoutons beaucoup de classes à la bibliothèque. Et aussi que nous utilisons beaucoup de fabriques ce qui rend notre code un peu moins intuitif. La solution la plus flexible, mais aussi la plus complexe.
+
+
+ Il existe une technique pour palier à ce problème sans créer de nouvelle classe dans l'application; par contre elle induit la création d'une sous-classe au moment du test. Premièrement nous déplaçons la création de la socket dans sa propre méthode...
+
+ Ici j'ai déplacé la fantaisie dans le constructeur, mais un setter aurait fonctionné tout aussi bien. Notez bien que la fantaisie est placée dans une variable d'objet avant que le constructeur ne soit attaché. C'est nécessaire dans le cas où le constructeur appelle connect(). Autrement il pourrait donner un valeur nulle à partir de _createSocket().
+
+
+ Après la réalisation de tout ce travail supplémentaire le scénario de test est assez simple. Nous avons juste besoin de tester notre nouvelle classe à la place...
+
+ Cette nouvelle classe est très simple bien sûr. Elle ne fait qu'initier une valeur renvoyée, à la manière d'une fantaisie. Ce serait pas mal non plus si elle pouvait vérifier les paramètres entrants. Exactement comme un objet fantaisie. Il se pourrait bien que nous ayons à réaliser cette astuce régulièrement : serait-il possible d'automatiser la création de cette sous-classe ?
+
+
+
+ Bien sûr la réponse est "oui" ou alors j'aurais arrêté d'écrire depuis quelques temps déjà ! Le test précédent a représenté beaucoup de travail, mais nous pouvons générer la sous-classe en utilisant une approche à celle des objets fantaisie.
+
+
+ Voici donc une version avec objet fantaisie partiel du test...
+
+ La fantaisie partielle est une sous-classe de l'original dont on aurait "remplacé" les méthodes sélectionnées avec des versions de test. L'appel à generatePartial() nécessite trois paramètres : la classe à sous classer, le nom de la nouvelle classe et une liste des méthodes à simuler.
+
+
+ Instancier les objets qui en résultent est plutôt délicat. L'unique paramètre du constructeur d'un objet fantaisie partiel est la référence du testeur unitaire. Comme avec les objets fantaisie classiques c'est nécessaire pour l'envoi des résultats de test en réponse à la vérification des attentes.
+
+
+ Une nouvelle fois le constructeur original n'est pas lancé. Indispensable dans le cas où le constructeur aurait besoin des méthodes fantaisie : elles n'ont pas encore été initiées ! Nous initions les valeurs retournées à cet instant et ensuite lançons le constructeur avec ses paramètres normaux. Cette construction en trois étapes de "new", suivie par la mise en place des méthodes et ensuite par la lancement du constructeur proprement dit est ce qui distingue le code d'un objet fantaisie partiel.
+
+
+ A part pour leur construction, toutes ces méthodes fantaisie ont les mêmes fonctionnalités que dans le cas des objets fantaisie et toutes les méthodes non fantaisie se comportent comme avant. Nous pouvons mettre en place des attentes très facilement...
+
+ Les méthodes issues d'un objet fantaisie n'ont pas besoin d'être des méthodes fabrique, Il peut s'agir de n'importe quelle sorte de méthode. Ainsi les objets fantaisie partiels nous permettent de prendre le contrôle de n'importe quelle partie d'une classe, le constructeur excepté. Nous pourrions même aller jusqu'à créer des fantaisies sur toutes les méthode à part celle que nous voulons effectivement tester.
+
+
+ Cette situation est assez hypothétique, étant donné que je ne l'ai jamais essayée. Je suis ouvert à cette possibilité, mais je crains qu'en forçant la granularité d'un objet on n'obtienne pas forcément un code de meilleur qualité. Personnellement j'utilise les objets fantaisie partiels comme moyen de passer outre la création ou alors de temps en temps pour tester le modèle de conception TemplateMethod.
+
+
+ Pour choisir le mécanisme à utiliser, on en revient toujours aux standards de code de votre projet.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+
+
diff --git a/tests/UnitTests/simpletest/docs/fr/reporter_documentation.html b/tests/UnitTests/simpletest/docs/fr/reporter_documentation.html
new file mode 100644
index 00000000..86c1607c
--- /dev/null
+++ b/tests/UnitTests/simpletest/docs/fr/reporter_documentation.html
@@ -0,0 +1,386 @@
+
+
+
+Documentation SimpleTest : le rapporteur de test
+
+
+
+
+ SimpleTest suit plutôt plus que moins le modèle MVC (Modèle-Vue-Contrôleur). Les classes "reporter" sont les vues et les modèles sont vos scénarios de test et leur hiérarchie. Le contrôleur est le plus souvent masqué à l'utilisateur de SimpleTest à moins de vouloir changer la façon dont les tests sont effectivement exécutés, auquel cas il est possible de surcharger les objets "runner" (ceux de l'exécuteur) depuis l'intérieur d'un scénario de test. Comme d'habitude avec MVC, le contrôleur est plutôt indéfini et il existe d'autres endroits pour contrôler l'exécution des tests.
+
+ L'affichage par défaut est minimal à l'extrême. Il renvoie le succès ou l'échec avec les barres conventionnelles - rouge et verte - et affichent une trace d'arborescence des groupes de test pour chaque assertion erronée. Voici un tel échec...
+
+
File test
+ Fail: createnewfile->True assertion failed.
+
1/1 test cases complete.
+ 0 passes, 1 fails and 0 exceptions.
+
+ Alors qu'ici tous les tests passent...
+
+
File test
+
1/1 test cases complete.
+ 1 passes, 0 fails and 0 exceptions.
+
+ La bonne nouvelle, c'est qu'il existe pas mal de points dans la hiérarchie de l'affichage pour créer des sous-classes.
+
+
+ Pour l'affichage basé sur des pages web, il y a la classe HtmlReporter avec la signature suivante...
+
+class HtmlReporter extends SimpleReporter {
+ public HtmlReporter($encoding) { ... }
+ public makeDry(boolean $is_dry) { ... }
+ public void paintHeader(string $test_name) { ... }
+ public void sendNoCacheHeaders() { ... }
+ public void paintFooter(string $test_name) { ... }
+ public void paintGroupStart(string $test_name, integer $size) { ... }
+ public void paintGroupEnd(string $test_name) { ... }
+ public void paintCaseStart(string $test_name) { ... }
+ public void paintCaseEnd(string $test_name) { ... }
+ public void paintMethodStart(string $test_name) { ... }
+ public void paintMethodEnd(string $test_name) { ... }
+ public void paintFail(string $message) { ... }
+ public void paintPass(string $message) { ... }
+ public void paintError(string $message) { ... }
+ public void paintException(string $message) { ... }
+ public void paintMessage(string $message) { ... }
+ public void paintFormattedMessage(string $message) { ... }
+ protected string _getCss() { ... }
+ public array getTestList() { ... }
+ public integer getPassCount() { ... }
+ public integer getFailCount() { ... }
+ public integer getExceptionCount() { ... }
+ public integer getTestCaseCount() { ... }
+ public integer getTestCaseProgress() { ... }
+}
+
+ Voici ce que certaines de ces méthodes veulent dire. Premièrement les méthodes d'affichage que vous voudrez probablement surcharger...
+
+
+ HtmlReporter(string $encoding)
+
+ est le constructeur. Notez que le test unitaire initie le lien à l'affichage plutôt que l'opposé. L'affichage est principalement un receveur passif des évènements de tests. Cela permet d'adapter facilement l'affichage pour d'autres systèmes en dehors des tests unitaires, tel le suivi de la charge de serveurs. L'"encoding" est le type d'encodage que vous souhaitez utiliser pour l'affichage du test. Pour pouvoir effectuer un rendu correct de la sortie de débogage quand on utilise le testeur web, il doit correspondre à l'encodage du site testé. Les chaînes de caractères disponibles sont indiquées dans la fonction PHP html_entities().
+
+
+ void paintHeader(string $test_name)
+
+ est appelé une fois, au début du test quand l'évènement de démarrage survient. Le premier évènement de démarrage est souvent délivré par le groupe de test du niveau le plus haut et donc c'est de là que le $test_name arrive. Il peint les titres de la page, CSS, la balise "body", etc. Il ne renvoie rien du tout (void).
+
+
+ void paintFooter(string $test_name)
+
+ est appelé à la toute fin du test pour fermer les balises ouvertes par l'entête de la page. Par défaut il affiche aussi la barre rouge ou verte et le décompte final des résultats. En fait la fin des tests arrive quand l'évènement de fin de test arrive avec le même nom que celui qui l'a initié au même niveau. Le nid des tests en quelque sorte. Fermer le dernier test finit l'affichage.
+
+
+ void paintMethodStart(string $test_name)
+
+ est appelé au début de chaque méthode de test. Normalement le nom vient de celui de la méthode. Les autres évènements de départ de test se comportent de la même manière sauf que celui du groupe de test indique au rapporteur le nombre de scénarios de test qu'il contient. De la sorte le rapporteur peut afficher une barre de progrès au fur et à mesure que l'exécuteur passe en revue les scénarios de test.
+
+
+ void paintMethodEnd(string $test_name)
+
+ clôt le test lancé avec le même nom.
+
+
+ void paintFail(string $message)
+
+ peint un échec. Par défait il ne fait qu'afficher le mot "fail", une trace d'arborescence affichant la position du test en cours et le message transmis par l'assertion.
+
+
+ void paintPass(string $message)
+
+ ne fait rien, par défaut.
+
+
+ string _getCss()
+
+ renvoie les styles CSS sous la forme d'une chaîne à l'attention de la méthode d'entêtes d'une page. Des styles additionnels peuvent être ajoutés ici si vous ne surchargez pas les entêtes de la page. Vous ne voudrez pas utiliser cette méthode dans des entêtes d'une page surchargée si vous souhaitez inclure le feuille de style CSS d'origine.
+
+
+ Il y a aussi des accesseurs pour aller chercher l'information sur l'état courant de la suite de test. Vous les utiliserez pour enrichir l'affichage...
+
+
+ array getTestList()
+
+ est la première méthode très commode pour les sous-classes. Elle liste l'arborescence courante des tests sous la forme d'une liste de noms de tests. Le premier test -- celui le plus proche du coeur -- sera le premier dans la liste et la méthode de test en cours sera la dernière.
+
+
+ integer getPassCount()
+
+ renvoie le nombre de succès atteint. Il est nécessaire pour l'affichage à la fin.
+
+
+ integer getFailCount()
+
+ renvoie de la même manière le nombre d'échecs.
+
+
+ integer getExceptionCount()
+
+ renvoie quant à lui le nombre d'erreurs.
+
+
+ integer getTestCaseCount()
+
+ est le nombre total de scénarios lors de l'exécution des tests. Il comprend aussi les tests groupés.
+
+
+ integer getTestCaseProgress()
+
+ est le nombre de scénarios réalisés jusqu'à présent.
+
+
+ Une modification simple : demander à l'HtmlReporter d'afficher aussi bien les succès que les échecs et les erreurs...
+
+ Une méthode qui a beaucoup fait jaser reste la méthode makeDry(). Si vous lancez cette méthode, sans paramètre, sur le rapporteur avant que la suite de test ne soit exécutée alors aucune méthode de test ne sera appelée. Vous continuerez à avoir les évènements entrants et sortants des méthodes et scénarios de test, mais aucun succès ni échec ou erreur, parce que le code de test ne sera pas exécuté.
+
+
+ La raison ? Pour permettre un affichage complexe d'une IHM (ou GUI) qui permettrait la sélection de scénarios de test individuels. Afin de construire une liste de tests possibles, ils ont besoin d'un rapport sur la structure du test pour, par exemple, l'affichage un vue en arbre de la suite de test. Avec un rapporteur lancé sur une exécution sèche qui ne renverrait que les évènements d'affichage, cela devient facilement réalisable.
+
+ Plutôt que de modifier l'affichage existant, vous voudrez peut-être produire une présentation HTML complètement différente, ou même générer une version texte ou XML. Plutôt que de surcharger chaque méthode dans HtmlReporter nous pouvons nous rendre une étape plus haut dans la hiérarchie de classe vers SimpleReporter dans le fichier source simple_test.php.
+
+
+ Un affichage sans rien, un canvas vierge pour votre propre création, serait...
+
+ SimpleTest est aussi livré avec un rapporteur en ligne de commande, minime lui aussi. L'interface imite celle de JUnit, sauf qu'elle envoie les messages d'erreur au fur et à mesure de leur arrivée. Pour utiliser le rapporteur en ligne de commande, il suffit de l'intervertir avec celui de la version HTML...
+
+File test
+1) True assertion failed.
+ in createnewfile
+FAILURES!!!
+Test cases run: 1/1, Failures: 1, Exceptions: 0
+
+
+
+ Une des principales raisons pour utiliser une suite de test en ligne de commande tient dans l'utilisation possible du testeur avec un processus automatisé. Pour fonctionner comme il faut dans des scripts shell le script de test devrait renvoyer un code de sortie non-nul suite à un échec. Si une suite de test échoue la valeur false est renvoyée par la méthode SimpleTest::run(). Nous pouvons utiliser ce résultat pour terminer le script avec la bonne valeur renvoyée...
+
+ Bien sûr l'objectif n'est pas de créer deux scripts de test, l'un en ligne de commande et l'autre pour un navigateur web, pour chaque suite de test. Le rapporteur en ligne de commande inclut une méthode pour déterminer l'environnement d'exécution...
+
+ Vous pouvez utiliser ce format avec le parseur fourni dans SimpleTest lui-même. Il s'agit de SimpleTestXmlParser et se trouve xml.php à l'intérieur du paquet SimpleTest...
+
+ $test_output devrait être au format XML, à partir du rapporteur XML, et pourrait venir d'une exécution en ligne de commande d'un scénario de test. Le parseur envoie des évènements au rapporteur exactement comme tout autre exécution de test. Il y a des occasions bizarres dans lesquelles c'est en fait très utile.
+
+
+ Un problème des suites de test très grandes, c'est qu'elles peuvent venir à bout de la limite de mémoire par défaut d'un process PHP - 8Mb. En plaçant la sortie des groupes de test dans du XML et leur exécution dans des process différents, le résultat peut être parser à nouveau pour agrégrer les résultats avec moins d'impact sur le test au premier niveau.
+
+
+ Parce que la sortie XML peut venir de n'importe où, ça ouvre des possibilités d'agrégation d'exécutions de test depuis des serveur distants. Un scénario de test pour le réaliser existe déjà à l'intérieur du framework SimpleTest, mais il est encore expérimental...
+
+ RemoteTestCase prend la localisation réelle du lanceur de test, tout simplement un page web au format XML. Il prend aussi l'URL d'un rapporteur initié pour effectuer une exécution sèche. Cette technique est employée pour que les progrès soient correctement rapportés vers le haut. RemoteTestCase peut être ajouté à une suite de test comme n'importe quel autre groupe de test.
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+ Au départ il s'agit d'un modèle de conception initié par Robert Binder (Testing object-oriented systems: models, patterns, and tools, Addison-Wesley) in 1999. Un bouchon serveur est une simulation d'un objet ou d'un composant. Il doit remplacer exactement un composant dans un système pour des raisons de testabilité ou de prototypage, tout en restant léger. Il permet aux tests de tourner plus rapidement ou alors, si la classe simulée n'a pas été écrite, juste de fonctionner.
+
+ Nous avons juste besoin d'une classe préexistante, par exemple une connexion vers une base de données qui ressemblerait à...
+
+class DatabaseConnection {
+ function DatabaseConnection() {
+ }
+
+ function query() {
+ }
+
+ function selectQuery() {
+ }
+}
+
+ La classe n'a même pas encore besoin d'avoir été implémentée. Pour créer la version bouchonnée de cette classe, nous incluons la librairie de bouchon serveur et exécutons le générateur...
+
+ Est généré un clone de la classe appelé StubDatabaseConnection. Nous pouvons alors créer des instances de cette nouvelle classe à l'intérieur de notre prototype de script...
+
+require_once('simpletest/mock_objects.php');
+require_once('database_connection.php');
+Stub::generate('DatabaseConnection');
+
+$connection = new StubDatabaseConnection();
+
+
+ La version bouchonnée de la classe contient toutes les méthodes de l'original de telle sorte qu'une opération comme $connection->query() soit encore légale. La valeur retournée sera null, Mais nous pouvons y remédier avec...
+
+$connection->setReturnValue('query', 37)
+
+ Désormais à chaque appel de $connection->query() nous obtenons un résultat de 37. Nous pouvons choisir n'importe quelle valeur pour le résultat, par exemple un hash de résultats provenant d'un base de données imaginaire ou alors une liste d'objets persistants. Peu importe les paramètres, nous obtenons systématiquement les même valeurs chaque fois qu'ils ont été initialisés de la sorte : ça ne ressemble peut-être pas à une réponse convaincante venant d'une connexion vers une base de données. Mais pour la demi-douzaine de lignes d'une méthode de test c'est souvent largement suffisant.
+
+
+
+ Sauf que les choses ne sont que rarement aussi simples. Parmi les problèmes les plus courants on trouve les itérateurs : le renvoi d'une valeur constante peut causer une boucle infini dans l'objet testé. Pour ceux-ci nous avons besoin de mettre sur pied une suite de valeurs. Prenons par exemple un itérateur simple qui ressemble à...
+
+class Iterator {
+ function Iterator() {
+ }
+
+ function next() {
+ }
+}
+
+ C'est probablement le plus simple des itérateurs possibles. Supposons que cet itérateur ne retourne que du texte, jusqu'à la fin - quand il retourne false. Une simulation est possible avec...
+
+ A l'appel de next() sur l'itérateur bouchonné il va d'abord renvoyer "First string", puis au second appel c'est "Second string" qui sera renvoyé. Finalement pour tous les autres appels, il s'agira d'un false. Les valeurs renvoyées successivement ont priorité sur la valeur constante renvoyé. Cette dernière est un genre de valeur par défaut.
+
+
+ Une autre situation délicate est une opération get() surchargée. Un exemple ? Un porteur d'information avec des pairs de clef / valeur. Prenons une classe de configuration...
+
+class Configuration {
+ function Configuration() {
+ }
+
+ function getValue($key) {
+ }
+}
+
+ Il s'agit d'une situation propice à l'utilisation d'objets bouchon, surtout que la configuration en production dépend invariablement de la machine : l'utiliser directement ne va pas nous aider à maintenir notre confiance dans nos tests. Sauf que le problème tient de ce que toutes les données proviennent de la méthode getValue() et que nous voulons des résultats différents suivant la clef. Par chance les bouchons ont un système de filtre...
+
+ Ce paramètre supplémentaire est une liste d'arguments que l'on peut utiliser. Dans ce cas nous essayons d'utiliser un unique argument, à savoir la clef recherchée. Maintenant quand on invoque le bouchon serveur via la méthode getValue() avec...
+
+$config->getValue('db_user');
+
+ ...il renvoie "admin". Il le trouve en essayant d'assortir successivement les arguments d'entrée avec sa liste de ceux de sortie jusqu'au moment où une correspondance exacte est trouvée.
+
+
+ Vous pouvez définir un argument par défaut avec...
+
+ Attention ce n'est pas équivalent à initialiser la valeur retournée sans aucun argument.
+
+
+$config->setReturnValue('getValue', false);
+
+ Dans le premier cas il acceptera n'importe quel argument, mais exactement un -- pas plus -- est nécessaire. Dans le second cas n'importe quel nombre d'arguments fera l'affaire : il agit comme un catchall après tous les correspondances. Prenez garde à l'ordre : si nous ajoutons un autre paramètre après le joker ('*') il sera ignoré puisque le joker aura été trouvé auparavant. Avec des listes de paramètres complexes l'ordre peut devenir crucial, au risque de perdre des correspondances souhaitées, masquées par un joker antérieur. Pensez à mettre d'abord les cas les plus spécifiques si vous n'êtes pas sûr.
+
+
+ Il y a des fois où l'on souhaite qu'un objet spécifique soit servi par le bouchon plutôt qu'une simple copie. La sémantique de la copie en PHP nous force à utiliser une autre méthode pour cela. Vous êtes peut-être en train de simuler un conteneur par exemple...
+
+ Le $stuff ne sera renvoyé qu'au troisième appel et seulement si deux paramètres étaient indiqués, avec la contrainte que le second de ceux-ci soit l'entier 1. N'est-ce pas suffisant pour des situations de prototypage simple ?
+
+
+ Un dernier cas critique reste celle d'un objet en créant un autre, connu sous le nom du modèle factory - fabrique. Supposons qu'après une requête réussie à notre base de données imaginaire, un ensemble de résultats est retourné sous la forme d'un itérateur, chaque appel à next() donnant un ligne et à la fin un false.
+ Au premier abord, ça donne l'impression d'être cauchemardesque à simuler. Alors qu'en fait tout peut être bouchonné en utilisant les mécanismes ci-dessus.
+
+ Désormais ce n'est que si notre $connection est appelé avec la bonne query() que le $result sera renvoyé après le troisième appel à next(). Cela devrait être suffisant pour que notre classe UserFinder, la classe effectivement testée à ce niveau, puisse s'exécuter comme il faut. Un test très précis et pas une seule base de données à l'horizon.
+
+
+
+ Pris tout seul ce n'est pas très utile étant donné qu'il n'y aurait pas de différence entre cette classe et celle par défaut -- à part le nom bien entendu. Par contre nous pouvons aussi lui ajouter d'autres méthodes qui ne se trouveraient pas dans l'interface originale...
+
+ Les méthodes next() et isError() peuvent maintenant renvoyer des ensembles de valeurs exactement comme si elles existaient dans la classe originale.
+
+
+ Un moyen encore plus ésotérique de modifier les bouchons est de changer le joker utiliser par défaut pour la correspondance des paramètres.
+
+ L'unique raison valable pour effectuer cette opération, c'est quand vous souhaitez tester la chaîne "*" sans pour autant l'interpréter comme un "n'importe lequel".
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+
+
diff --git a/tests/UnitTests/simpletest/docs/fr/unit_test_documentation.html b/tests/UnitTests/simpletest/docs/fr/unit_test_documentation.html
new file mode 100644
index 00000000..fbbd728b
--- /dev/null
+++ b/tests/UnitTests/simpletest/docs/fr/unit_test_documentation.html
@@ -0,0 +1,306 @@
+
+
+
+Documenation SimpleTest pour les tests de régression en PHP
+
+
+
+
+ Le coeur du système est un framework de test de régression construit autour des scénarios de test. Un exemple de scénario de test ressemble à...
+
+class FileTestCase extends UnitTestCase {
+}
+
+ Si aucun nom de test n'est fourni au moment de la liaison avec le constructeur alors le nom de la classe sera utilisé. Il s'agit du nom qui sera affiché dans les résultats du test.
+
+
+ Les véritables tests sont ajoutés en tant que méthode dans le scénario de test dont le nom par défaut commence par la chaîne "test" et quand le scénario de test est appelé toutes les méthodes de ce type sont exécutées dans l'ordre utilisé par l'introspection de PHP pour les trouver. Peuvent être ajoutées autant de méthodes de test que nécessaires. Par exemple...
+
+ Le constructeur est optionnel et souvent omis. Sans nom, le nom de la classe est utilisé comme nom pour le scénario de test.
+
+
+ Notre unique méthode de test pour le moment est testCreation() où nous vérifions qu'un fichier a bien été créé par notre objet Writer. Nous pourrions avoir mis le code unlink() dans cette méthode, mais en la plaçant dans setUp() et tearDown() nous pouvons l'utiliser pour nos autres méthodes de test que nous ajouterons.
+
+
+ La méthode setUp() est lancé juste avant chaque méthode de test. tearDown() est lancé après chaque méthode de test.
+
+
+ Vous pouvez placer une initialisation de scénario de test dans le constructeur afin qu'elle soit lancée pour toutes les méthodes dans le scénario de test mais dans un tel cas vous vous exposeriez à des interférences. Cette façon de faire est légèrement moins rapide, mais elle est plus sûre. Notez que si vous arrivez avec des notions de JUnit, il ne s'agit pas du comportement auquel vous êtes habitués. Bizarrement JUnit re-instancie le scénario de test pour chaque méthode de test pour se prévenir d'une telle interférence. SimpleTest demande à l'utilisateur final d'utiliser setUp(), mais fournit aux codeurs de bibliothèque d'autres crochets.
+
+
+ Pour rapporter les résultats de test, le passage par une classe d'affichage - notifiée par les différentes méthodes de type assert...() - est utilisée. En voici la liste complète pour la classe UnitTestCase, celle par défaut dans SimpleTest...
+
+
+
+
assertTrue($x)
Echoue si $x est faux
+
+
+
assertFalse($x)
Echoue si $x est vrai
+
+
+
assertNull($x)
Echoue si $x est initialisé
+
+
+
assertNotNull($x)
Echoue si $x n'est pas initialisé
+
+
+
assertIsA($x, $t)
Echoue si $x n'est pas de la classe ou du type $t
+
+
+
assertEqual($x, $y)
Echoue si $x == $y est faux
+
+
+
assertNotEqual($x, $y)
Echoue si $x == $y est vrai
+
+
+
assertIdentical($x, $y)
Echoue si $x === $y est faux
+
+
+
assertNotIdentical($x, $y)
Echoue si $x === $y est vrai
+
+
+
assertReference($x, $y)
Echoue sauf si $x et $y sont la même variable
+
+
+
assertCopy($x, $y)
Echoue si $x et $y sont la même variable
+
+
+
assertWantedPattern($p, $x)
Echoue sauf si l'expression rationnelle $p capture $x
+
+
+
assertNoUnwantedPattern($p, $x)
Echoue si l'expression rationnelle $p capture $x
+
+
+
assertNoErrors()
Echoue si une erreur PHP arrive
+
+
+
assertError($x)
Echoue si aucune erreur ou message incorrect de PHP n'arrive
+
+
+
+ Toutes les méthodes d'assertion peuvent recevoir une description optionnelle : cette description sert pour étiqueter le résultat.
+ Sans elle, une message par défaut est envoyée à la place : il est généralement suffisant. Ce message par défaut peut encore être encadré dans votre propre message si vous incluez "%s" dans la chaîne. Toutes les assertions renvoient vrai / true en cas de succès et faux / false en cas d'échec.
+
+
+ D'autres exemples...
+
+$variable = null;
+$this->assertNull($variable, 'Should be cleared');
+
+$this->assertIdentical(0, false, 'Zero is not false [%s]');
+
+ Ceci échouera étant donné qu'il effectue une vérification sur le type en plus d'une comparaison sur les deux valeurs. La partie "%s" est remplacée par le message d'erreur par défaut qui aurait été affiché si nous n'avions pas fourni le nôtre. Cela nous permet d'emboîter les messages de test.
+
+ Ici, il y a besoin d'une petite explication : toutes passent !
+
+
+ Les erreurs PHP dans SimpleTest sont piégées et placées dans une queue. Ici la première vérification d'erreur attrape le message "Disaster" sans vérifier le texte et passe. Résultat : l'erreur est supprimée de la queue. La vérification suivante teste non seulement l'existence de l'erreur mais aussi le texte qui correspond : un autre succès. Désormais la queue est vide et le dernier test passe aussi. Si une autre erreur non vérifiée est encore dans la queue à la fin de notre méthode de test alors une exception sera rapportée dans le test. Notez que SimpleTest ne peut pas attraper les erreurs PHP à la compilation.
+
+
+ Les scénarios de test peuvent utiliser des méthodes bien pratiques pour déboguer le code ou pour étendre la suite...
+
+
+
+
setUp()
Est lancée avant chaque méthode de test
+
+
+
tearDown()
Est lancée après chaque méthode de test
+
+
+
pass()
Envoie un succès
+
+
+
fail()
Envoie un échec
+
+
+
error()
Envoi un évènement exception
+
+
+
sendMessage()
Envoie un message d'état aux systèmes d'affichage qui le supporte
+
+
+
signal($type, $payload)
Envoie un message défini par l'utilisateur au rapporteur du test
+
+
+
dump($var)
Effectue un print_r() formaté pour du déboguage rapide et grossier
+ Si vous souhaitez un scénario de test sans toutes les assertions de UnitTestCase mais uniquement avec les vôtres propres, vous aurez besoin d'étendre la classe SimpleTestCase à la place. Elle se trouve dans simple_test.php en lieu et place de unit_tester.php. A consulter plus tard si vous souhaitez incorporer les scénarios d'autres testeurs unitaires dans votre suite de test.
+
+ Ce n'est pas souvent qu'il faille lancer des scénarios avec un unique test. Sauf lorsqu'il s'agit de s'arracher les cheveux sur un module à problème sans pour autant désorganiser la suite de test principale. Voici l'échafaudage nécessaire pour lancer un scénario de test solitaire...
+
+ Tester des classes c'es très bien. Reste que PHP est avant tout un langage pour créer des fonctionnalités à l'intérieur de pages web. Comment pouvons tester la partie de devant -- celle de l'interface -- dans nos applications en PHP ? Etant donné qu'une page web n'est constituée que de texte, nous devrions pouvoir les examiner exactement comme n'importe quelle autre donnée de test.
+
+
+ Cela nous amène à une situation délicate. Si nous testons dans un niveau trop bas, vérifier des balises avec un motif ad hoc par exemple, nos tests seront trop fragiles. Le moindre changement dans la présentation pourrait casser un grand nombre de test. Si nos tests sont situés trop haut, en utilisant une version fantaisie du moteur de template pour donner un cas précis, alors nous perdons complètement la capacité à automatiser certaines classes de test. Par exemple, l'interaction entre des formulaires et la navigation devra être testé manuellement. Ces types de test sont extrêmement fastidieux et plutôt sensibles aux erreurs.
+
+
+ SimpleTest comprend une forme spéciale de scénario de test pour tester les actions d'une page web. WebTestCase inclut des facilités pour la navigation, des vérifications sur le contenu et les cookies ainsi que la gestion des formulaires. Utiliser ces scénarios de test ressemble fortement à UnitTestCase...
+
+class TestOfLastcraft extends WebTestCase {
+}
+
+ Ici nous sommes sur le point de tester le site de Last Craft. Si ce scénario de test est situé dans un fichier appelé lastcraft_test.php alors il peut être chargé dans un script de lancement tout comme des tests unitaires...
+
+ La méthode get() renverra "true" uniquement si le contenu de la page a bien été téléchargé. C'est un moyen simple, mais efficace pour vérifier qu'une page web a bien été délivré par le serveur web. Cependant le contenu peut révéler être une erreur 404 et dans ce cas notre méthode get() renverrait encore un succès.
+
+
+ En supposant que le serveur web pour le site Last Craft soit opérationnel (malheureusement ce n'est pas toujours le cas), nous devrions voir...
+
+ Nous avons vérifié qu'une page, de n'importe quel type, a bien été renvoyée. Nous ne savons pas encore s'il s'agit de celle que nous souhaitions.
+
+
+
+ Pour obtenir la confirmation que la page téléchargée est bien celle que nous attendions, nous devons vérifier son contenu.
+
+class TestOfLastcraft extends WebTestCase {
+
+ function testHomepage() {
+ $this->get('http://www.lastcraft.com/');
+ $this->assertWantedPattern('/why the last craft/i');
+ }
+}
+
+ La page obtenue par le dernier téléchargement est placée dans un buffer au sein même du scénario de test. Il n'est donc pas nécessaire de s'y référer directement. La correspondance du motif est toujours effectuée par rapport à ce buffer.
+
+
+ Voici une liste possible d'assertions sur le contenu...
+
+
+
+
assertWantedPattern($pattern)
Vérifier une correspondance sur le contenu via une expression rationnelle Perl
+
+
+
assertNoUnwantedPattern($pattern)
Une expression rationnelle Perl pour vérifier une absence
+
+
+
assertTitle($title)
Passe si le titre de la page correspond exactement
+
+
+
assertLink($label)
Passe si un lien avec ce texte est présent
+
+
+
assertNoLink($label)
Passe si aucun lien avec ce texte est présent
+
+
+
assertLinkById($id)
Passe si un lien avec cet attribut d'identification est présent
+
+
+
assertField($name, $value)
Passe si une balise input avec ce nom contient cette valeur
+
+
+
assertFieldById($id, $value)
Passe si une balise input avec cet identifiant contient cette valeur
+
+
+
assertResponse($codes)
Passe si la réponse HTTP trouve une correspondance dans la liste
+
+
+
assertMime($types)
Passe si le type MIME se retrouve dans cette liste
+
+
+
assertAuthentication($protocol)
Passe si l'authentification provoquée est de ce type de protocole
+
+
+
assertNoAuthentication()
Passe s'il n'y pas d'authentification provoquée en cours
+
+
+
assertRealm($name)
Passe si le domaine provoqué correspond
+
+
+
assertHeader($header, $content)
Passe si une entête téléchargée correspond à cette valeur
+
+
+
assertNoUnwantedHeader($header)
Passe si une entête n'a pas été téléchargé
+
+
+
assertHeaderPattern($header, $pattern)
Passe si une entête téléchargée correspond à cette expression rationnelle Perl
+
+
+
assertCookie($name, $value)
Passe s'il existe un cookie correspondant
+
+
+
assertNoCookie($name)
Passe s'il n'y a pas de cookie avec un tel nom
+
+
+
+ Comme d'habitude avec les assertions de SimpleTest, elles renvoient toutes "false" en cas d'échec et "true" si c'est un succès. Elles renvoient aussi un message de test optionnel : vous pouvez l'ajouter dans votre propre message en utilisant "%s".
+
+
+ A présent nous pourrions effectué le test sur le titre uniquement...
+
+$this->assertTitle('The Last Craft?');
+
+ En plus d'une simple vérification sur le contenu HTML, nous pouvons aussi vérifier que le type MIME est bien d'un type acceptable...
+
+ Plus intéressant encore est la vérification sur le code de la réponse HTTP. Pareillement au type MIME, nous pouvons nous assurer que le code renvoyé se trouve bien dans un liste de valeurs possibles...
+
+ Ici nous vérifions que le téléchargement s'est bien terminé en ne permettant qu'une réponse HTTP 200. Ce test passera, mais ce n'est pas la meilleure façon de procéder. Il n'existe aucune page sur http://simpletest.sourceforge.net/, à la place le serveur renverra une redirection vers http://www.lastcraft.com/simple_test.php. WebTestCase suit automatiquement trois de ces redirections. Les tests sont quelque peu plus robustes de la sorte. Surtout qu'on est souvent plus intéressé par l'interaction entre les pages que de leur simple livraison. Si les redirections se révèlent être digne d'intérêt, il reste possible de les supprimer...
+
+ Les utilisateurs ne naviguent pas souvent en tapant les URLs, mais surtout en cliquant sur des liens et des boutons. Ici nous confirmons que les informations sur le contact peuvent être atteintes depuis la page d'accueil...
+
+ Il l'objectif est un bouton plutôt qu'une balise ancre, alors clickSubmit() doit être utilisé avec le titre du bouton...
+
+$this->clickSubmit('Go!');
+
+
+
+ La liste des méthodes de navigation est...
+
+
+
+
get($url, $parameters)
Envoie une requête GET avec ces paramètres
+
+
+
post($url, $parameters)
Envoie une requête POST avec ces paramètres
+
+
+
head($url, $parameters)
Envoie une requête HEAD sans remplacer le contenu de la page
+
+
+
retry()
Relance la dernière requête
+
+
+
back()
Identique au bouton "Précédent" du navigateur
+
+
+
forward()
Identique au bouton "Suivant" du navigateur
+
+
+
authenticate($name, $password)
Re-essaye avec une tentative d'authentification
+
+
+
getFrameFocus()
Le nom de la fenêtre en cours d'utilisation
+
+
+
setFrameFocusByIndex($choice)
Change le focus d'une fenêtre en commençant par 1
+
+
+
setFrameFocus($name)
Change le focus d'une fenêtre en utilisant son nom
+
+
+
clearFrameFocus()
Revient à un traitement de toutes les fenêtres comme une seule
+
+
+
clickSubmit($label)
Clique sur le premier bouton avec cette étiquette
+
+
+
clickSubmitByName($name)
Clique sur le bouton avec cet attribut de nom
+
+
+
clickSubmitById($id)
Clique sur le bouton avec cet attribut d'identification
+
+
+
clickImage($label, $x, $y)
Clique sur une balise input de type image avec ce titre ou ce texte dans l'attribut alt
+
+
+
clickImageByName($name, $x, $y)
Clique sur une balise input de type image avec ce nom
+
+
+
clickImageById($id, $x, $y)
Clique sur une balise input de type image avec cet attribut d'identification
+
+
+
submitFormById($id)
Soumet un formulaire sans valeur de soumission
+
+
+
clickLink($label, $index)
Clique sur un ancre avec ce texte d'étiquette visible
+
+
+
clickLinkById($id)
Clique sur une ancre avec cet attribut d'identification
+
+
+
+
+
+ Les paramètres dans les méthodes get(), post() et head() sont optionnels. Le téléchargement via HTTP HEAD ne modifie pas le contexte du navigateur, il se limite au chargement des cookies. Cela peut être utilise lorsqu'une image ou une feuille de style initie un cookie pour bloquer un robot trop entreprenant.
+
+
+ Les commandes retry(), back() et forward() fonctionnent exactement comme dans un navigateur. Elles utilisent l'historique pour relancer les pages. Une technique bien pratique pour vérifier les effets d'un bouton retour sur vos formulaires.
+
+
+ Les méthodes sur les fenêtres méritent une petite explication. Par défaut, une page avec des fenêtres est traitée comme toutes les autres. Le contenu sera vérifié à travers l'ensemble de la "frameset", par conséquent un lien fonctionnera, peu importe la fenêtre qui contient la balise ancre. Vous pouvez outrepassé ce comportement en exigeant le focus sur une unique fenêtre. Si vous réalisez cela, toutes les recherches et toutes les actions se limiteront à cette unique fenêtre, y compris les demandes d'authentification. Si un lien ou un bouton n'est pas dans la fenêtre en focus alors il ne peut pas être cliqué.
+
+
+ Tester la navigation sur des pages fixes ne vous alerte que quand vous avez cassé un script entier. Pour des pages fortement dynamiques, un forum de discussion par exemple, ça peut être crucial pour vérifier l'état de l'application. Pour la plupart des applications cependant, la logique vraiment délicate se situe dans la gestion des formulaires et des sessions. Heureusement SimpleTest aussi inclut des outils pour tester des formulaires web.
+
+ Bien que SimpleTest n'ait pas comme objectif de contrôler des erreurs réseau, il contient quand même des méthodes pour modifier et déboguer les requêtes qu'il lance. Voici une autre liste de méthode...
+
+
+
+
getTransportError()
La dernière erreur de socket
+
+
+
getUrl()
La localisation courante
+
+
+
showRequest()
Déverse la requête sortante
+
+
+
showHeaders()
Déverse les entêtes d'entrée
+
+
+
showSource()
Déverse le contenu brut de la page HTML
+
+
+
ignoreFrames()
Ne recharge pas les framesets
+
+
+
setCookie($name, $value)
Initie un cookie à partir de maintenant
+
+
+
addHeader($header)
Ajoute toujours cette entête à la requête
+
+
+
setMaximumRedirects($max)
S'arrête après autant de redirections
+
+
+
setConnectionTimeout($timeout)
Termine la connexion après autant de temps entre les bytes
+
+
+
useProxy($proxy, $name, $password)
Effectue les requêtes à travers ce proxy d'URL
+
+
+
+
+
+
+
+ Copyright Marcus Baker, Jason Sweat, Perrick Penet 2004
+
+
+
diff --git a/tests/UnitTests/simpletest/dumper.php b/tests/UnitTests/simpletest/dumper.php
new file mode 100644
index 00000000..d6182e36
--- /dev/null
+++ b/tests/UnitTests/simpletest/dumper.php
@@ -0,0 +1,380 @@
+getType($value);
+ switch($type) {
+ case "Null":
+ return "NULL";
+ case "Boolean":
+ return "Boolean: " . ($value ? "true" : "false");
+ case "Array":
+ return "Array: " . count($value) . " items";
+ case "Object":
+ return "Object: of " . get_class($value);
+ case "String":
+ return "String: " . $this->clipString($value, 100);
+ default:
+ return "$type: $value";
+ }
+ return "Unknown";
+ }
+
+ /**
+ * 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";
+ } elseif (is_bool($value)) {
+ return "Boolean";
+ } elseif (is_string($value)) {
+ return "String";
+ } elseif (is_integer($value)) {
+ return "Integer";
+ } elseif (is_float($value)) {
+ return "Float";
+ } elseif (is_array($value)) {
+ return "Array";
+ } elseif (is_resource($value)) {
+ return "Resource";
+ } elseif (is_object($value)) {
+ return "Object";
+ }
+ 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
+ */
+ function describeDifference($first, $second, $identical = false) {
+ if ($identical) {
+ if (! $this->_isTypeMatch($first, $second)) {
+ return "with type mismatch as [" . $this->describeValue($first) .
+ "] does not match [" . $this->describeValue($second) . "]";
+ }
+ }
+ $type = $this->getType($first);
+ if ($type == "Unknown") {
+ return "with unknown type";
+ }
+ $method = '_describe' . $type . 'Difference';
+ 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
+ */
+ 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
+ */
+ function clipString($value, $size, $position = 0) {
+ $length = strlen($value);
+ if ($length <= $size) {
+ return $value;
+ }
+ $position = min($position, $length);
+ $start = ($size/2 > $position ? 0 : $position - $size/2);
+ if ($start + $size > $length) {
+ $start = $length - $size;
+ }
+ $value = substr($value, $start, $size);
+ return ($start > 0 ? "..." : "") . $value . ($start + $size < $length ? "..." : "");
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between two variables. The minimal
+ * 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
+ */
+ 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
+ */
+ 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
+ */
+ function _describeStringDifference($first, $second, $identical) {
+ if (is_object($second) || is_array($second)) {
+ return $this->_describeGenericDifference($first, $second);
+ }
+ $position = $this->_stringDiffersAt($first, $second);
+ $message = "at character $position";
+ $message .= " with [" .
+ $this->clipString($first, 100, $position) . "] and [" .
+ $this->clipString($second, 100, $position) . "]";
+ 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
+ */
+ function _describeIntegerDifference($first, $second, $identical) {
+ if (is_object($second) || is_array($second)) {
+ return $this->_describeGenericDifference($first, $second);
+ }
+ return "because [" . $this->describeValue($first) .
+ "] differs from [" .
+ $this->describeValue($second) . "] by " .
+ abs($first - $second);
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between two floating point numbers.
+ * @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) .
+ "] differs from [" .
+ $this->describeValue($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
+ */
+ function _describeArrayDifference($first, $second, $identical) {
+ if (! is_array($second)) {
+ return $this->_describeGenericDifference($first, $second);
+ }
+ if (! $this->_isMatchingKeys($first, $second, $identical)) {
+ return "as key list [" .
+ implode(", ", array_keys($first)) . "] does not match key list [" .
+ implode(", ", array_keys($second)) . "]";
+ }
+ foreach (array_keys($first) as $key) {
+ if ($identical && ($first[$key] === $second[$key])) {
+ continue;
+ }
+ if (! $identical && ($first[$key] == $second[$key])) {
+ continue;
+ }
+ return "with member [$key] " . $this->describeDifference(
+ $first[$key],
+ $second[$key],
+ $identical);
+ }
+ 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
+ */
+ function _isMatchingKeys($first, $second, $identical) {
+ $first_keys = array_keys($first);
+ $second_keys = array_keys($second);
+ if ($identical) {
+ return ($first_keys === $second_keys);
+ }
+ sort($first_keys);
+ sort($second_keys);
+ 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
+ */
+ 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
+ */
+ function _describeObjectDifference($first, $second, $identical) {
+ if (! is_object($second)) {
+ return $this->_describeGenericDifference($first, $second);
+ }
+ return $this->_describeArrayDifference(
+ get_object_vars($first),
+ get_object_vars($second),
+ $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
+ */
+ function _stringDiffersAt($first, $second) {
+ if (! $first || ! $second) {
+ return 0;
+ }
+ if (strlen($first) < strlen($second)) {
+ list($first, $second) = array($second, $first);
+ }
+ $position = 0;
+ $step = strlen($first);
+ while ($step > 1) {
+ $step = (integer)(($step + 1)/2);
+ if (strncmp($first, $second, $position + $step) == 0) {
+ $position += $step;
+ }
+ }
+ return $position;
+ }
+
+ /**
+ * Sends a formatted dump of a variable to a string.
+ * @param mixed $variable Variable to display.
+ * @return string Output from print_r().
+ * @access public
+ * @static
+ */
+ function dump($variable) {
+ ob_start();
+ print_r($variable);
+ $formatted = ob_get_contents();
+ ob_end_clean();
+ 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
+ */
+ 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.
+ if (substr(dirname($frame['file']), -10) == 'simpletest') {
+ continue;
+ }
+ }
+ if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) {
+ return sprintf($format, $frame['line']);
+ }
+ }
+ return '';
+ }
+ }
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/encoding.php b/tests/UnitTests/simpletest/encoding.php
new file mode 100644
index 00000000..fd2d918a
--- /dev/null
+++ b/tests/UnitTests/simpletest/encoding.php
@@ -0,0 +1,156 @@
+_request = array();
+ $this->setCoordinates();
+ $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
+ */
+ 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;
+ }
+ } else {
+ $this->_request[$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
+ */
+ 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());
+ }
+ } elseif (is_array($query)) {
+ foreach ($query as $key => $value) {
+ $this->add($key, $value);
+ }
+ }
+ }
+
+ /**
+ * 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
+ */
+ 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);
+ }
+ }
+ $coords = ($this->_x !== false) ? '?' . $this->_x . ',' . $this->_y : '';
+ return implode('&', $statements) . $coords;
+ }
+ }
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/errors.php b/tests/UnitTests/simpletest/errors.php
new file mode 100644
index 00000000..a1fbe546
--- /dev/null
+++ b/tests/UnitTests/simpletest/errors.php
@@ -0,0 +1,141 @@
+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
+ */
+ 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
+ */
+ function extract() {
+ if (count($this->_queue)) {
+ return array_shift($this->_queue);
+ }
+ return false;
+ }
+
+ /**
+ * 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.
+ */
+ function isEmpty() {
+ return (count($this->_queue) == 0);
+ }
+
+ /**
+ * Global access to a single error queue.
+ * @return Global error queue object.
+ * @access public
+ * @static
+ */
+ static function instance() {
+ static $queue = false;
+ if (! $queue) {
+ $queue = new SimpleErrorQueue();
+ }
+ 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
+ */
+ static function getSeverityAsString($severity) {
+ static $map = array(
+ E_STRICT => 'E_STRICT',
+ E_ERROR => 'E_ERROR',
+ E_WARNING => 'E_WARNING',
+ E_PARSE => 'E_PARSE',
+ E_NOTICE => 'E_NOTICE',
+ E_CORE_ERROR => 'E_CORE_ERROR',
+ E_CORE_WARNING => 'E_CORE_WARNING',
+ E_COMPILE_ERROR => 'E_COMPILE_ERROR',
+ E_COMPILE_WARNING => 'E_COMPILE_WARNING',
+ E_USER_ERROR => 'E_USER_ERROR',
+ E_USER_WARNING => 'E_USER_WARNING',
+ E_USER_NOTICE => 'E_USER_NOTICE');
+ return $map[$severity];
+ }
+ }
+
+ /**
+ * 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();
+ if (ini_get('log_errors')) {
+ $label = SimpleErrorQueue::getSeverityAsString($severity);
+ error_log("$label: $message in $filename on line $line");
+ }
+ $queue = SimpleErrorQueue::instance();
+ $queue->add($severity, $message, $filename, $line, $super_globals);
+ set_error_handler('simpleTestErrorHandler');
+ }
+ }
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/expectation.php b/tests/UnitTests/simpletest/expectation.php
new file mode 100644
index 00000000..ffc61376
--- /dev/null
+++ b/tests/UnitTests/simpletest/expectation.php
@@ -0,0 +1,568 @@
+_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
+ */
+ function test($compare) {
+ }
+
+ /**
+ * 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
+ */
+ function overlayMessage($compare) {
+ return sprintf($this->_message, $this->testMessage($compare));
+ }
+
+ /**
+ * Accessor for the dumper.
+ * @return SimpleDumper Current value dumper.
+ * @access protected
+ */
+ function _getDumper() {
+ return $this->_dumper;
+ }
+ }
+
+ /**
+ * Test for equality.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class EqualExpectation extends SimpleExpectation {
+ protected $_value;
+
+ /**
+ * 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) {
+ 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
+ */
+ function testMessage($compare) {
+ if ($this->test($compare)) {
+ return "Equal expectation [" . $this->_dumper->describeValue($this->_value) . "]";
+ } else {
+ return "Equal expectation fails " .
+ $this->_dumper->describeDifference($this->_value, $compare);
+ }
+ }
+
+ /**
+ * 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
+ */
+ 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
+ */
+ 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
+ */
+ 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) {
+ $dumper = $this->_getDumper();
+ if ($this->test($compare)) {
+ return "Not equal expectation passes " .
+ $dumper->describeDifference($this->_getValue(), $compare);
+ } else {
+ return "Not equal expectation fails [" .
+ $dumper->describeValue($this->_getValue()) .
+ "] matches";
+ }
+ }
+ }
+
+ /**
+ * 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
+ */
+ 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
+ */
+ 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
+ */
+ function testMessage($compare) {
+ $dumper = $this->_getDumper();
+ if ($this->test($compare)) {
+ return "Identical expectation [" . $dumper->describeValue($this->_getValue()) . "]";
+ } else {
+ return "Identical expectation [" . $dumper->describeValue($this->_getValue()) .
+ "] fails with [" .
+ $dumper->describeValue($compare) . "] " .
+ $dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS);
+ }
+ }
+ }
+
+ /**
+ * 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
+ */
+ 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
+ */
+ 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) {
+ $dumper = $this->_getDumper();
+ if ($this->test($compare)) {
+ return "Not identical expectation passes " .
+ $dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS);
+ } else {
+ return "Not identical expectation [" . $dumper->describeValue($this->_getValue()) . "] matches";
+ }
+ }
+ }
+
+ /**
+ * Test for a pattern using Perl regex rules.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class WantedPatternExpectation extends SimpleExpectation {
+ protected $_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') {
+ $this->SimpleExpectation($message);
+ $this->_pattern = $pattern;
+ }
+
+ /**
+ * 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
+ */
+ 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
+ */
+ function testMessage($compare) {
+ if ($this->test($compare)) {
+ return $this->_describePatternMatch($this->_getPattern(), $compare);
+ } else {
+ $dumper = $this->_getDumper();
+ return "Pattern [" . $this->_getPattern() .
+ "] not detected in [" .
+ $dumper->describeValue($compare) . "]";
+ }
+ }
+
+ /**
+ * 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]);
+ $dumper = $this->_getDumper();
+ return "Pattern [$pattern] detected at character [$position] in [" .
+ $dumper->describeValue($subject) . "] as [" .
+ $matches[0] . "] in region [" .
+ $dumper->clipString($subject, 100, $position) . "]";
+ }
+ }
+
+ /**
+ * Fail if a pattern is detected within the
+ * comparison.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class UnwantedPatternExpectation extends WantedPatternExpectation {
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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
+ */
+ function testMessage($compare) {
+ if ($this->test($compare)) {
+ $dumper = $this->_getDumper();
+ return "Pattern [" . $this->_getPattern() .
+ "] not detected in [" .
+ $dumper->describeValue($compare) . "]";
+ } else {
+ return $this->_describePatternMatch($this->_getPattern(), $compare);
+ }
+ }
+ }
+
+ /**
+ * Tests either type or class name if it's an object.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class IsAExpectation extends SimpleExpectation {
+ protected $_type;
+
+ /**
+ * 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
+ */
+ 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
+ */
+ function test($compare) {
+ if (is_object($compare)) {
+ return SimpleTestCompatibility::isA($compare, $this->_type);
+ } else {
+ return (strtolower(gettype($compare)) == $this->_canonicalType($this->_type));
+ }
+ }
+
+ /**
+ * 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(
+ 'bool' => 'boolean',
+ 'float' => 'double',
+ 'real' => 'double',
+ 'int' => 'integer');
+ if (isset($map[$type])) {
+ $type = $map[$type];
+ }
+ return $type;
+ }
+
+ /**
+ * 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) .
+ "] should be type [" . $this->_type . "]";
+ }
+ }
+
+ /**
+ * 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 {
+ protected $_type;
+
+ /**
+ * 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
+ */
+ 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) {
+ $dumper = $this->_getDumper();
+ return "Value [" . $dumper->describeValue($compare) .
+ "] should not be type [" . $this->_getType() . "]";
+ }
+ }
+
+ /**
+ * Tests for existance of a method in an object
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class MethodExistsExpectation extends SimpleExpectation {
+ protected $_method;
+
+ /**
+ * Sets the value to compare against.
+ * @param string $method Method to check.
+ * @param string $message Customised message on failure.
+ * @access public
+ * @return void
+ */
+ function MethodExistsExpectation($method, $message = '%s') {
+ $this->SimpleExpectation($message);
+ $this->_method = $method;
+ }
+
+ /**
+ * 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
+ */
+ 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]";
+ }
+ }
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/extensions/pear_test_case.php b/tests/UnitTests/simpletest/extensions/pear_test_case.php
new file mode 100644
index 00000000..c9ac0743
--- /dev/null
+++ b/tests/UnitTests/simpletest/extensions/pear_test_case.php
@@ -0,0 +1,199 @@
+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
+ */
+ 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);
+ }
+
+ /**
+ * 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
+ */
+ 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
+ */
+ function assertSame(&$first, &$second, $message = "%s") {
+ $dumper = &new SimpleDumper();
+ $message = sprintf(
+ $message,
+ "[" . $dumper->describeValue($first) .
+ "] and [" . $dumper->describeValue($second) .
+ "] should reference the same object");
+ return $this->assertTrue(
+ SimpleTestCompatibility::isReference($first, $second),
+ $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
+ */
+ function assertNotSame(&$first, &$second, $message = "%s") {
+ $dumper = &new SimpleDumper();
+ $message = sprintf(
+ $message,
+ "[" . $dumper->describeValue($first) .
+ "] and [" . $dumper->describeValue($second) .
+ "] should not be the same object");
+ return $this->assertFalse(
+ SimpleTestCompatibility::isReference($first, $second),
+ $message);
+ }
+
+ /**
+ * 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
+ */
+ 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
+ */
+ function assertRegExp($pattern, $subject, $message = "%s") {
+ $this->assertExpectation(
+ new WantedPatternExpectation($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
+ */
+ 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
+ */
+ function setLooselyTyped($loosely_typed) {
+ $this->_loosely_typed = $loosely_typed;
+ }
+
+ /**
+ * 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
+ */
+ function getName() {
+ return $this->getLabel();
+ }
+
+ /**
+ * Does nothing. For compatibility only.
+ * @param $name Dummy
+ * @public
+ */
+ function setName($name) {
+ }
+ }
+?>
diff --git a/tests/UnitTests/simpletest/extensions/phpunit_test_case.php b/tests/UnitTests/simpletest/extensions/phpunit_test_case.php
new file mode 100644
index 00000000..4c6fa54e
--- /dev/null
+++ b/tests/UnitTests/simpletest/extensions/phpunit_test_case.php
@@ -0,0 +1,108 @@
+SimpleTestCase($label);
+ }
+
+ /**
+ * Sends pass if the test condition resolves true,
+ * a fail otherwise.
+ * @param $condition Condition to test true.
+ * @param $message Message to display.
+ * @public
+ */
+ function assert($condition, $message = false) {
+ parent::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
+ */
+ function assertEquals($first, $second, $message = false) {
+ $this->assertExpectation(
+ 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
+ */
+ function assertEqualsMultilineStrings($first, $second, $message = false) {
+ $this->assertExpectation(
+ new EqualExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Tests a regex match.
+ * @param $pattern Regex to match.
+ * @param $subject String to search in.
+ * @param $message Message to display.
+ * @public
+ */
+ function assertRegexp($pattern, $subject, $message = false) {
+ $this->assertExpectation(
+ new WantedPatternExpectation($pattern),
+ $subject,
+ $message);
+ }
+
+ /**
+ * Sends an error which we interpret as a fail
+ * with a different message for compatibility.
+ * @param $message Message to display.
+ * @public
+ */
+ function error($message) {
+ parent::assertTrue(false, "Error triggered [$message]");
+ }
+
+ /**
+ * Accessor for name.
+ * @public
+ */
+ function name() {
+ return $this->getLabel();
+ }
+ }
+?>
diff --git a/tests/UnitTests/simpletest/form.php b/tests/UnitTests/simpletest/form.php
new file mode 100644
index 00000000..05f5c72a
--- /dev/null
+++ b/tests/UnitTests/simpletest/form.php
@@ -0,0 +1,619 @@
+_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 {
+ protected $_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 {
+ protected $_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
+ */
+ class SimpleForm {
+ protected $_method;
+ protected $_action;
+ protected $_default_target;
+ protected $_id;
+ protected $_buttons;
+ protected $_images;
+ protected $_widgets;
+ protected $_radios;
+ protected $_checkboxes;
+
+ /**
+ * 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->_default_target = false;
+ $this->_id = $tag->getAttribute('id');
+ $this->_buttons = array();
+ $this->_images = array();
+ $this->_widgets = array();
+ $this->_radios = array();
+ $this->_checkboxes = array();
+ }
+
+ /**
+ * 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
+ */
+ 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.
+ */
+ function _createAction($action, $base) {
+ if ($action === false) {
+ return $base;
+ }
+ if ($action === true) {
+ $url = new SimpleUrl('');
+ } else {
+ $url = new SimpleUrl($action);
+ }
+ return $url->makeAbsolute($base);
+ }
+
+ /**
+ * Absolute URL of the target.
+ * @return SimpleUrl URL target.
+ * @access public
+ */
+ function getAction() {
+ $url = $this->_action;
+ if ($this->_default_target && ! $url->getTarget()) {
+ $url->setTarget($this->_default_target);
+ }
+ return $url;
+ }
+
+ /**
+ * 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) {
+ if (strtolower($tag->getAttribute('type')) == 'submit') {
+ $this->_buttons[] = $tag;
+ } elseif (strtolower($tag->getAttribute('type')) == 'image') {
+ $this->_images[] = $tag;
+ } elseif ($tag->getName()) {
+ $this->_setWidget($tag);
+ }
+ }
+
+ /**
+ * Sets the widget into the form, grouping radio
+ * buttons if any.
+ * @param SimpleWidget $tag Incoming form control.
+ * @access private
+ */
+ function _setWidget($tag) {
+ if (strtolower($tag->getAttribute('type')) == 'radio') {
+ $this->_addRadioButton($tag);
+ } elseif (strtolower($tag->getAttribute('type')) == 'checkbox') {
+ $this->_addCheckbox($tag);
+ } else {
+ $this->_widgets[] = $tag;
+ }
+ }
+
+ /**
+ * Adds a radio button, building a group if necessary.
+ * @param SimpleRadioButtonTag $tag Incoming form control.
+ * @access private
+ */
+ function _addRadioButton($tag) {
+ if (! isset($this->_radios[$tag->getName()])) {
+ $this->_widgets[] = new SimpleRadioGroup();
+ $this->_radios[$tag->getName()] = count($this->_widgets) - 1;
+ }
+ $this->_widgets[$this->_radios[$tag->getName()]]->addWidget($tag);
+ }
+
+ /**
+ * Adds a checkbox, making it a group on a repeated name.
+ * @param SimpleCheckboxTag $tag Incoming form control.
+ * @access private
+ */
+ function _addCheckbox($tag) {
+ if (! isset($this->_checkboxes[$tag->getName()])) {
+ $this->_widgets[] = $tag;
+ $this->_checkboxes[$tag->getName()] = count($this->_widgets) - 1;
+ } else {
+ $index = $this->_checkboxes[$tag->getName()];
+ if (! SimpleTestCompatibility::isA($this->_widgets[$index], 'SimpleCheckboxGroup')) {
+ $previous = $this->_widgets[$index];
+ $this->_widgets[$index] = new SimpleCheckboxGroup();
+ $this->_widgets[$index]->addWidget($previous);
+ }
+ $this->_widgets[$index]->addWidget($tag);
+ }
+ }
+
+ /**
+ * 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) {
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if ($selector->isMatch($this->_widgets[$i])) {
+ return $this->_widgets[$i]->getValue();
+ }
+ }
+ foreach ($this->_buttons as $button) {
+ if ($selector->isMatch($button)) {
+ return $button->getValue();
+ }
+ }
+ 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) {
+ $success = false;
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if ($selector->isMatch($this->_widgets[$i])) {
+ if ($this->_widgets[$i]->setValue($value)) {
+ $success = true;
+ }
+ }
+ }
+ 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();
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ $encoding->add(
+ $this->_widgets[$i]->getName(),
+ $this->_widgets[$i]->getValue());
+ }
+ 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) {
+ foreach ($this->_buttons as $button) {
+ if ($selector->isMatch($button)) {
+ return true;
+ }
+ }
+ 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) {
+ foreach ($this->_images as $image) {
+ if ($selector->isMatch($image)) {
+ return true;
+ }
+ }
+ 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) {
+ foreach ($this->_buttons as $button) {
+ if ($selector->isMatch($button)) {
+ $encoding = $this->_getEncoding();
+ $encoding->merge($button->getSubmitValues());
+ if ($additional) {
+ $encoding->merge($additional);
+ }
+ return $encoding;
+ }
+ }
+ 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) {
+ foreach ($this->_images as $image) {
+ if ($selector->isMatch($image)) {
+ $encoding = $this->_getEncoding();
+ $encoding->merge($image->getSubmitValues($x, $y));
+ if ($additional) {
+ $encoding->merge($additional);
+ }
+ return $encoding;
+ }
+ }
+ 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
+ */
+ function submit() {
+ return $this->_getEncoding();
+ }
+ }
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/frames.php b/tests/UnitTests/simpletest/frames.php
new file mode 100644
index 00000000..b18d28fc
--- /dev/null
+++ b/tests/UnitTests/simpletest/frames.php
@@ -0,0 +1,673 @@
+_frameset = $page;
+ $this->_frames = array();
+ $this->_focus = false;
+ $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
+ */
+ function addFrame($page, $name = false) {
+ $this->_frames[] = $page;
+ if ($name) {
+ $this->_names[$name] = count($this->_frames) - 1;
+ }
+ }
+
+ /**
+ * 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])) {
+ $index = $this->_names[$name];
+ } else {
+ $index = $name - 1;
+ }
+ if (count($path) == 0) {
+ $this->_frames[$index] = $page;
+ return;
+ }
+ $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
+ */
+ function getFrameFocus() {
+ if ($this->_focus === false) {
+ return array();
+ }
+ return array_merge(
+ array($this->_getPublicNameFromIndex($this->_focus)),
+ $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
+ */
+ function _getPublicNameFromIndex($subject) {
+ foreach ($this->_names as $name => $index) {
+ if ($subject == $index) {
+ return $name;
+ }
+ }
+ 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
+ */
+ function setFrameFocusByIndex($choice) {
+ if (is_integer($this->_focus)) {
+ if ($this->_frames[$this->_focus]->hasFrames()) {
+ return $this->_frames[$this->_focus]->setFrameFocusByIndex($choice);
+ }
+ }
+ if (($choice < 1) || ($choice > count($this->_frames))) {
+ return false;
+ }
+ $this->_focus = $choice - 1;
+ 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
+ */
+ function setFrameFocus($name) {
+ if (is_integer($this->_focus)) {
+ if ($this->_frames[$this->_focus]->hasFrames()) {
+ return $this->_frames[$this->_focus]->setFrameFocus($name);
+ }
+ }
+ if (in_array($name, array_keys($this->_names))) {
+ $this->_focus = $this->_names[$name];
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Clears the frame focus.
+ * @access public
+ */
+ function clearFrameFocus() {
+ $this->_focus = false;
+ $this->_clearNestedFramesFocus();
+ }
+
+ /**
+ * Clears the frame focus for any nested frames.
+ * @access private
+ */
+ function _clearNestedFramesFocus() {
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $this->_frames[$i]->clearFrameFocus();
+ }
+ }
+
+ /**
+ * 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
+ */
+ function getFrames() {
+ $report = array();
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $report[$this->_getPublicNameFromIndex($i)] =
+ $this->_frames[$i]->getFrames();
+ }
+ return $report;
+ }
+
+ /**
+ * 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();
+ }
+ $raw = '';
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $raw .= $this->_frames[$i]->getRaw();
+ }
+ return $raw;
+ }
+
+ /**
+ * 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();
+ }
+ $raw = '';
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $raw .= ' ' . $this->_frames[$i]->getText();
+ }
+ return trim($raw);
+ }
+
+ /**
+ * 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();
+ }
+ return $this->_frameset->getTransportError();
+ }
+
+ /**
+ * 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();
+ }
+ return $this->_frameset->getMethod();
+ }
+
+ /**
+ * Original resource name.
+ * @return SimpleUrl Current url.
+ * @access public
+ */
+ function getUrl() {
+ if (is_integer($this->_focus)) {
+ $url = $this->_frames[$this->_focus]->getUrl();
+ $url->setTarget($this->_getPublicNameFromIndex($this->_focus));
+ } else {
+ $url = $this->_frameset->getUrl();
+ }
+ return $url;
+ }
+
+ /**
+ * Original request data.
+ * @return mixed Sent content.
+ * @access public
+ */
+ function getRequestData() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getRequestData();
+ }
+ return $this->_frameset->getRequestData();
+ }
+
+ /**
+ * 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();
+ }
+ return $this->_frameset->getMimeType();
+ }
+
+ /**
+ * 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();
+ }
+ return $this->_frameset->getResponseCode();
+ }
+
+ /**
+ * 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();
+ }
+ return $this->_frameset->getAuthentication();
+ }
+
+ /**
+ * 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();
+ }
+ return $this->_frameset->getRealm();
+ }
+
+ /**
+ * Accessor for outgoing header information.
+ * @return string Header block.
+ * @access public
+ */
+ function getRequest() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getRequest();
+ }
+ return $this->_frameset->getRequest();
+ }
+
+ /**
+ * Accessor for raw header information.
+ * @return string Header block.
+ * @access public
+ */
+ function getHeaders() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getHeaders();
+ }
+ return $this->_frameset->getHeaders();
+ }
+
+ /**
+ * 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
+ */
+ function getAbsoluteUrls() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getAbsoluteUrls();
+ }
+ $urls = array();
+ foreach ($this->_frames as $frame) {
+ $urls = array_merge($urls, $frame->getAbsoluteUrls());
+ }
+ return array_values(array_unique($urls));
+ }
+
+ /**
+ * 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();
+ }
+ $urls = array();
+ foreach ($this->_frames as $frame) {
+ $urls = array_merge($urls, $frame->getRelativeUrls());
+ }
+ 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
+ */
+ function getUrlsByLabel($label) {
+ if (is_integer($this->_focus)) {
+ return $this->_tagUrlsWithFrame(
+ $this->_frames[$this->_focus]->getUrlsByLabel($label),
+ $this->_focus);
+ }
+ $urls = array();
+ foreach ($this->_frames as $index => $frame) {
+ $urls = array_merge(
+ $urls,
+ $this->_tagUrlsWithFrame(
+ $frame->getUrlsByLabel($label),
+ $index));
+ }
+ 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
+ */
+ function getUrlById($id) {
+ foreach ($this->_frames as $index => $frame) {
+ if ($url = $frame->getUrlById($id)) {
+ if (! $url->gettarget()) {
+ $url->setTarget($this->_getPublicNameFromIndex($index));
+ }
+ return $url;
+ }
+ }
+ 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
+ */
+ function _tagUrlsWithFrame($urls, $frame) {
+ $tagged = array();
+ foreach ($urls as $url) {
+ if (! $url->getTarget()) {
+ $url->setTarget($this->_getPublicNameFromIndex($frame));
+ }
+ $tagged[] = $url;
+ }
+ 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
+ */
+ function getFormBySubmitLabel($label) {
+ return $this->_findForm('getFormBySubmitLabel', $label);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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 protected
+ */
+ function _findForm($method, $attribute) {
+ if (is_integer($this->_focus)) {
+ return $this->_findFormInFrame(
+ $this->_frames[$this->_focus],
+ $this->_focus,
+ $method,
+ $attribute);
+ }
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $form = $this->_findFormInFrame(
+ $this->_frames[$i],
+ $i,
+ $method,
+ $attribute);
+ if ($form) {
+ return $form;
+ }
+ }
+ 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 protected
+ */
+ function _findFormInFrame($page, $index, $method, $attribute) {
+ $form = $this->_frames[$index]->$method($attribute);
+ if (isset($form)) {
+ $form->setDefaultTarget($this->_getPublicNameFromIndex($index));
+ }
+ 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) {
+ if (is_integer($this->_focus)) {
+ $this->_frames[$this->_focus]->setField($name, $value);
+ } else {
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $this->_frames[$i]->setField($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
+ */
+ function setFieldById($id, $value) {
+ if (is_integer($this->_focus)) {
+ $this->_frames[$this->_focus]->setFieldById($id, $value);
+ } else {
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $this->_frames[$i]->setFieldById($id, $value);
+ }
+ }
+ }
+
+ /**
+ * 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) {
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $value = $this->_frames[$i]->getField($name);
+ if (isset($value)) {
+ return $value;
+ }
+ }
+ 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
+ */
+ function getFieldById($id) {
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $value = $this->_frames[$i]->getFieldById($id);
+ if (isset($value)) {
+ return $value;
+ }
+ }
+ return null;
+ }
+ }
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/http.php b/tests/UnitTests/simpletest/http.php
new file mode 100644
index 00000000..36cb395f
--- /dev/null
+++ b/tests/UnitTests/simpletest/http.php
@@ -0,0 +1,853 @@
+_host = false;
+ $this->_name = $name;
+ $this->_value = $value;
+ $this->_path = ($path ? $this->_fixPath($path) : "/");
+ $this->_expiry = false;
+ if (is_string($expiry)) {
+ $this->_expiry = strtotime($expiry);
+ } elseif (is_integer($expiry)) {
+ $this->_expiry = $expiry;
+ }
+ $this->_is_secure = $is_secure;
+ }
+
+ /**
+ * Sets the host. The cookie rules determine
+ * that the first two parts are taken for
+ * certain TLDs and three for others. If the
+ * new host does not match these rules then the
+ * call will fail.
+ * @param string $host New hostname.
+ * @return boolean True if hostname is valid.
+ * @access public
+ */
+ function setHost($host) {
+ if ($host = $this->_truncateHost($host)) {
+ $this->_host = $host;
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for the truncated host to which this
+ * cookie applies.
+ * @return string Truncated hostname.
+ * @access public
+ */
+ function getHost() {
+ return $this->_host;
+ }
+
+ /**
+ * Test for a cookie being valid for a host name.
+ * @param string $host Host to test against.
+ * @return boolean True if the cookie would be valid
+ * here.
+ */
+ function isValidHost($host) {
+ return ($this->_truncateHost($host) === $this->getHost());
+ }
+
+ /**
+ * Extracts just the domain part that determines a
+ * cookie's host validity.
+ * @param string $host Host name to truncate.
+ * @return string Domain or false on a bad host.
+ * @access private
+ */
+ function _truncateHost($host) {
+ $tlds = SimpleUrl::getAllTopLevelDomains();
+ if (preg_match('/[a-z\-]+\.(' . $tlds . ')$/i', $host, $matches)) {
+ return $matches[0];
+ } elseif (preg_match('/[a-z\-]+\.[a-z\-]+\.[a-z\-]+$/i', $host, $matches)) {
+ return $matches[0];
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for name.
+ * @return string Cookie key.
+ * @access public
+ */
+ function getName() {
+ return $this->_name;
+ }
+
+ /**
+ * Accessor for value. A deleted cookie will
+ * have an empty string for this.
+ * @return string Cookie value.
+ * @access public
+ */
+ function getValue() {
+ return $this->_value;
+ }
+
+ /**
+ * Accessor for path.
+ * @return string Valid cookie path.
+ * @access public
+ */
+ function getPath() {
+ return $this->_path;
+ }
+
+ /**
+ * Tests a path to see if the cookie applies
+ * there. The test path must be longer or
+ * equal to the cookie path.
+ * @param string $path Path to test against.
+ * @return boolean True if cookie valid here.
+ * @access public
+ */
+ function isValidPath($path) {
+ return (strncmp(
+ $this->_fixPath($path),
+ $this->getPath(),
+ strlen($this->getPath())) == 0);
+ }
+
+ /**
+ * Accessor for expiry.
+ * @return string Expiry string.
+ * @access public
+ */
+ function getExpiry() {
+ if (! $this->_expiry) {
+ return false;
+ }
+ return gmdate("D, d M Y H:i:s", $this->_expiry) . " GMT";
+ }
+
+ /**
+ * Test to see if cookie is expired against
+ * the cookie format time or timestamp.
+ * Will give true for a session cookie.
+ * @param integer/string $now Time to test against. Result
+ * will be false if this time
+ * is later than the cookie expiry.
+ * Can be either a timestamp integer
+ * or a cookie format date.
+ * @access public
+ */
+ function isExpired($now) {
+ if (! $this->_expiry) {
+ return true;
+ }
+ if (is_string($now)) {
+ $now = strtotime($now);
+ }
+ return ($this->_expiry < $now);
+ }
+
+ /**
+ * Ages the cookie by the specified number of
+ * seconds.
+ * @param integer $interval In seconds.
+ * @public
+ */
+ function agePrematurely($interval) {
+ if ($this->_expiry) {
+ $this->_expiry -= $interval;
+ }
+ }
+
+ /**
+ * Accessor for the secure flag.
+ * @return boolean True if cookie needs SSL.
+ * @access public
+ */
+ function isSecure() {
+ return $this->_is_secure;
+ }
+
+ /**
+ * Adds a trailing and leading slash to the path
+ * if missing.
+ * @param string $path Path to fix.
+ * @access private
+ */
+ function _fixPath($path) {
+ if (substr($path, 0, 1) != '/') {
+ $path = '/' . $path;
+ }
+ if (substr($path, -1, 1) != '/') {
+ $path .= '/';
+ }
+ return $path;
+ }
+ }
+
+ /**
+ * Creates HTTP headers for the end point of
+ * a HTTP request.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleRoute {
+ protected $_url;
+
+ /**
+ * Sets the target URL.
+ * @param SimpleUrl $url URL as object.
+ * @access public
+ */
+ function SimpleRoute($url) {
+ $this->_url = $url;
+ }
+
+ /**
+ * Resource name.
+ * @return SimpleUrl Current url.
+ * @access protected
+ */
+ function getUrl() {
+ return $this->_url;
+ }
+
+ /**
+ * Creates the first line which is the actual request.
+ * @param string $method HTTP request method, usually GET.
+ * @return string Request line content.
+ * @access protected
+ */
+ function _getRequestLine($method) {
+ return $method . ' ' . $this->_url->getPath() .
+ $this->_url->getEncodedRequest() . ' HTTP/1.0';
+ }
+
+ /**
+ * Creates the host part of the request.
+ * @return string Host line content.
+ * @access protected
+ */
+ function _getHostLine() {
+ $line = 'Host: ' . $this->_url->getHost();
+ if ($this->_url->getPort()) {
+ $line .= ':' . $this->_url->getPort();
+ }
+ return $line;
+ }
+
+ /**
+ * Opens a socket to the route.
+ * @param string $method HTTP request method, usually GET.
+ * @param integer $timeout Connection timeout.
+ * @return SimpleSocket New socket.
+ * @access public
+ */
+ function createConnection($method, $timeout) {
+ $default_port = ('https' == $this->_url->getScheme()) ? 443 : 80;
+ $socket = $this->_createSocket(
+ $this->_url->getScheme() ? $this->_url->getScheme() : 'http',
+ $this->_url->getHost(),
+ $this->_url->getPort() ? $this->_url->getPort() : $default_port,
+ $timeout);
+ if (! $socket->isError()) {
+ $socket->write($this->_getRequestLine($method) . "\r\n");
+ $socket->write($this->_getHostLine() . "\r\n");
+ $socket->write("Connection: close\r\n");
+ }
+ return $socket;
+ }
+
+ /**
+ * Factory for socket.
+ * @param string $scheme Protocol to use.
+ * @param string $host Hostname to connect to.
+ * @param integer $port Remote port.
+ * @param integer $timeout Connection timeout.
+ * @return SimpleSocket/SimpleSecureSocket New socket.
+ * @access protected
+ */
+ function _createSocket($scheme, $host, $port, $timeout) {
+ if (in_array($scheme, array('https'))) {
+ return new SimpleSecureSocket($host, $port, $timeout);
+ }
+ return new SimpleSocket($host, $port, $timeout);
+ }
+ }
+
+ /**
+ * Creates HTTP headers for the end point of
+ * a HTTP request via a proxy server.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleProxyRoute extends SimpleRoute {
+ protected $_proxy;
+ protected $_username;
+ protected $_password;
+
+ /**
+ * Stashes the proxy address.
+ * @param SimpleUrl $url URL as object.
+ * @param string $proxy Proxy URL.
+ * @param string $username Username for autentication.
+ * @param string $password Password for autentication.
+ * @access public
+ */
+ function SimpleProxyRoute($url, $proxy, $username = false, $password = false) {
+ $this->SimpleRoute($url);
+ $this->_proxy = $proxy;
+ $this->_username = $username;
+ $this->_password = $password;
+ }
+
+ /**
+ * Creates the first line which is the actual request.
+ * @param string $method HTTP request method, usually GET.
+ * @param SimpleUrl $url URL as object.
+ * @return string Request line content.
+ * @access protected
+ */
+ function _getRequestLine($method) {
+ $url = $this->getUrl();
+ $scheme = $url->getScheme() ? $url->getScheme() : 'http';
+ $port = $url->getPort() ? ':' . $url->getPort() : '';
+ return $method . ' ' . $scheme . '://' . $url->getHost() . $port .
+ $url->getPath() . $url->getEncodedRequest() . ' HTTP/1.0';
+ }
+
+ /**
+ * Creates the host part of the request.
+ * @param SimpleUrl $url URL as object.
+ * @return string Host line content.
+ * @access protected
+ */
+ function _getHostLine() {
+ $host = 'Host: ' . $this->_proxy->getHost();
+ $port = $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080;
+ return "$host:$port";
+ }
+
+ /**
+ * Opens a socket to the route.
+ * @param string $method HTTP request method, usually GET.
+ * @param integer $timeout Connection timeout.
+ * @return SimpleSocket New socket.
+ * @access public
+ */
+ function createConnection($method, $timeout) {
+ $socket = $this->_createSocket(
+ $this->_proxy->getScheme() ? $this->_proxy->getScheme() : 'http',
+ $this->_proxy->getHost(),
+ $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080,
+ $timeout);
+ if (! $socket->isError()) {
+ $socket->write($this->_getRequestLine($method) . "\r\n");
+ $socket->write($this->_getHostLine() . "\r\n");
+ if ($this->_username && $this->_password) {
+ $socket->write('Proxy-Authorization: Basic ' .
+ base64_encode($this->_username . ':' . $this->_password) .
+ "\r\n");
+ }
+ $socket->write("Connection: close\r\n");
+ }
+ return $socket;
+ }
+ }
+
+ /**
+ * HTTP request for a web page. Factory for
+ * HttpResponse object.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleHttpRequest {
+ protected $_route;
+ protected $_method;
+ protected $_encoding;
+ protected $_headers;
+ protected $_cookies;
+
+ /**
+ * Saves the URL ready for fetching.
+ * @param SimpleRoute $route Request route.
+ * @param string $method HTTP request method,
+ * usually GET.
+ * @param SimpleFormEncoding $encoding Content to send with
+ * request or false.
+ * @access public
+ */
+ function SimpleHttpRequest($route, $method, $encoding = false) {
+ $this->_route = $route;
+ $this->_method = $method;
+ $this->_encoding = $encoding;
+ $this->_headers = array();
+ $this->_cookies = array();
+ }
+
+ /**
+ * Fetches the content and parses the headers.
+ * @param integer $timeout Connection timeout.
+ * @return SimpleHttpResponse A response which may only have
+ * an error.
+ * @access public
+ */
+ function fetch($timeout) {
+ $socket = $this->_route->createConnection($this->_method, $timeout);
+ if ($socket->isError()) {
+ return $this->_createResponse($socket);
+ }
+ $this->_dispatchRequest($socket, $this->_method, $this->_encoding);
+ return $this->_createResponse($socket);
+ }
+
+ /**
+ * Sends the headers.
+ * @param SimpleSocket $socket Open socket.
+ * @param string $method HTTP request method,
+ * usually GET.
+ * @param SimpleFormEncoding $encoding Content to send with request.
+ * @access private
+ */
+ function _dispatchRequest($socket, $method, $encoding) {
+ if ($encoding || ($method == 'POST')) {
+ $socket->write("Content-Length: " . $this->_getContentLength($encoding) . "\r\n");
+ $socket->write("Content-Type: application/x-www-form-urlencoded\r\n");
+ }
+ foreach ($this->_headers as $header_line) {
+ $socket->write($header_line . "\r\n");
+ }
+ if (count($this->_cookies) > 0) {
+ $socket->write("Cookie: " . $this->_marshallCookies($this->_cookies) . "\r\n");
+ }
+ $socket->write("\r\n");
+ if ($encoding) {
+ $socket->write($encoding->asString());
+ }
+ }
+
+ /**
+ * Calculates the length of the encoded content.
+ * @param SimpleFormEncoding $encoding Content to send with
+ * request or false.
+ */
+ function _getContentLength($encoding) {
+ if (! $encoding) {
+ return 0;
+ }
+ return (integer)strlen($encoding->asString());
+ }
+
+ /**
+ * Adds a header line to the request.
+ * @param string $header_line Text of header line.
+ * @access public
+ */
+ function addHeaderLine($header_line) {
+ $this->_headers[] = $header_line;
+ }
+
+ /**
+ * Adds a cookie to the request.
+ * @param SimpleCookie $cookie Additional cookie.
+ * @access public
+ */
+ function setCookie($cookie) {
+ $this->_cookies[] = $cookie;
+ }
+
+ /**
+ * Serialises the cookie hash ready for
+ * transmission.
+ * @param hash $cookies Parsed cookies.
+ * @return array Cookies in header form.
+ * @access private
+ */
+ function _marshallCookies($cookies) {
+ $cookie_pairs = array();
+ foreach ($cookies as $cookie) {
+ $cookie_pairs[] = $cookie->getName() . "=" . $cookie->getValue();
+ }
+ return implode(";", $cookie_pairs);
+ }
+
+ /**
+ * Wraps the socket in a response parser.
+ * @param SimpleSocket $socket Responding socket.
+ * @return SimpleHttpResponse Parsed response object.
+ * @access protected
+ */
+ function _createResponse($socket) {
+ return new SimpleHttpResponse(
+ $socket,
+ $this->_method,
+ $this->_route->getUrl(),
+ $this->_encoding);
+ }
+ }
+
+ /**
+ * Collection of header lines in the response.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleHttpHeaders {
+ protected $_raw_headers;
+ protected $_response_code;
+ protected $_http_version;
+ protected $_mime_type;
+ protected $_location;
+ protected $_cookies;
+ protected $_authentication;
+ protected $_realm;
+
+ /**
+ * Parses the incoming header block.
+ * @param string $headers Header block.
+ * @access public
+ */
+ function SimpleHttpHeaders($headers) {
+ $this->_raw_headers = $headers;
+ $this->_response_code = false;
+ $this->_http_version = false;
+ $this->_mime_type = '';
+ $this->_location = false;
+ $this->_cookies = array();
+ $this->_authentication = false;
+ $this->_realm = false;
+ foreach (split("\r\n", $headers) as $header_line) {
+ $this->_parseHeaderLine($header_line);
+ }
+ }
+
+ /**
+ * Accessor for parsed HTTP protocol version.
+ * @return integer HTTP error code.
+ * @access public
+ */
+ function getHttpVersion() {
+ return $this->_http_version;
+ }
+
+ /**
+ * Accessor for raw header block.
+ * @return string All headers as raw string.
+ * @access public
+ */
+ function getRaw() {
+ return $this->_raw_headers;
+ }
+
+ /**
+ * Accessor for parsed HTTP error code.
+ * @return integer HTTP error code.
+ * @access public
+ */
+ function getResponseCode() {
+ return (integer)$this->_response_code;
+ }
+
+ /**
+ * Returns the redirected URL or false if
+ * no redirection.
+ * @return string URL or false for none.
+ * @access public
+ */
+ function getLocation() {
+ return $this->_location;
+ }
+
+ /**
+ * Test to see if the response is a valid redirect.
+ * @return boolean True if valid redirect.
+ * @access public
+ */
+ function isRedirect() {
+ return in_array($this->_response_code, array(301, 302, 303, 307)) &&
+ (boolean)$this->getLocation();
+ }
+
+ /**
+ * Test to see if the response is an authentication
+ * challenge.
+ * @return boolean True if challenge.
+ * @access public
+ */
+ function isChallenge() {
+ return ($this->_response_code == 401) &&
+ (boolean)$this->_authentication &&
+ (boolean)$this->_realm;
+ }
+
+ /**
+ * Accessor for MIME type header information.
+ * @return string MIME type.
+ * @access public
+ */
+ function getMimeType() {
+ return $this->_mime_type;
+ }
+
+ /**
+ * Accessor for authentication type.
+ * @return string Type.
+ * @access public
+ */
+ function getAuthentication() {
+ return $this->_authentication;
+ }
+
+ /**
+ * Accessor for security realm.
+ * @return string Realm.
+ * @access public
+ */
+ function getRealm() {
+ return $this->_realm;
+ }
+
+ /**
+ * Accessor for any new cookies.
+ * @return array List of new cookies.
+ * @access public
+ */
+ function getNewCookies() {
+ return $this->_cookies;
+ }
+
+ /**
+ * Called on each header line to accumulate the held
+ * data within the class.
+ * @param string $header_line One line of header.
+ * @access protected
+ */
+ function _parseHeaderLine($header_line) {
+ if (preg_match('/HTTP\/(\d+\.\d+)\s+(.*?)\s/i', $header_line, $matches)) {
+ $this->_http_version = $matches[1];
+ $this->_response_code = $matches[2];
+ }
+ if (preg_match('/Content-type:\s*(.*)/i', $header_line, $matches)) {
+ $this->_mime_type = trim($matches[1]);
+ }
+ if (preg_match('/Location:\s*(.*)/i', $header_line, $matches)) {
+ $this->_location = trim($matches[1]);
+ }
+ if (preg_match('/Set-cookie:(.*)/i', $header_line, $matches)) {
+ $this->_cookies[] = $this->_parseCookie($matches[1]);
+ }
+ if (preg_match('/WWW-Authenticate:\s+(\S+)\s+realm=\"(.*?)\"/i', $header_line, $matches)) {
+ $this->_authentication = $matches[1];
+ $this->_realm = trim($matches[2]);
+ }
+ }
+
+ /**
+ * Parse the Set-cookie content.
+ * @param string $cookie_line Text after "Set-cookie:"
+ * @return SimpleCookie New cookie object.
+ * @access private
+ */
+ function _parseCookie($cookie_line) {
+ $parts = split(";", $cookie_line);
+ $cookie = array();
+ preg_match('/\s*(.*?)\s*=(.*)/', array_shift($parts), $cookie);
+ foreach ($parts as $part) {
+ if (preg_match('/\s*(.*?)\s*=(.*)/', $part, $matches)) {
+ $cookie[$matches[1]] = trim($matches[2]);
+ }
+ }
+ return new SimpleCookie(
+ $cookie[1],
+ trim($cookie[2]),
+ isset($cookie["path"]) ? $cookie["path"] : "",
+ isset($cookie["expires"]) ? $cookie["expires"] : false);
+ }
+ }
+
+ /**
+ * Basic HTTP response.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleHttpResponse extends SimpleStickyError {
+ protected $_method;
+ protected $_url;
+ protected $_request_data;
+ protected $_sent;
+ protected $_content;
+ protected $_headers;
+
+ /**
+ * Constructor. Reads and parses the incoming
+ * content and headers.
+ * @param SimpleSocket $socket Network connection to fetch
+ * response text from.
+ * @param string $method HTTP request method.
+ * @param SimpleUrl $url Resource name.
+ * @param mixed $request_data Record of content sent.
+ * @access public
+ */
+ function SimpleHttpResponse($socket, $method, $url, $request_data = '') {
+ $this->SimpleStickyError();
+ $this->_method = $method;
+ $this->_url = $url;
+ $this->_request_data = $request_data;
+ $this->_sent = $socket->getSent();
+ $this->_content = false;
+ $raw = $this->_readAll($socket);
+ if ($socket->isError()) {
+ $this->_setError('Error reading socket [' . $socket->getError() . ']');
+ return;
+ }
+ $this->_parse($raw);
+ }
+
+ /**
+ * Splits up the headers and the rest of the content.
+ * @param string $raw Content to parse.
+ * @access private
+ */
+ function _parse($raw) {
+ if (! $raw) {
+ $this->_setError('Nothing fetched');
+ $this->_headers = new SimpleHttpHeaders('');
+ } elseif (! strstr($raw, "\r\n\r\n")) {
+ $this->_setError('Could not parse headers');
+ $this->_headers = new SimpleHttpHeaders($raw);
+ } else {
+ list($headers, $this->_content) = split("\r\n\r\n", $raw, 2);
+ $this->_headers = new SimpleHttpHeaders($headers);
+ }
+ }
+
+ /**
+ * Original request method.
+ * @return string GET, POST or HEAD.
+ * @access public
+ */
+ function getMethod() {
+ return $this->_method;
+ }
+
+ /**
+ * Resource name.
+ * @return SimpleUrl Current url.
+ * @access public
+ */
+ function getUrl() {
+ return $this->_url;
+ }
+
+ /**
+ * Original request data.
+ * @return mixed Sent content.
+ * @access public
+ */
+ function getRequestData() {
+ return $this->_request_data;
+ }
+
+ /**
+ * Raw request that was sent down the wire.
+ * @return string Bytes actually sent.
+ * @access public
+ */
+ function getSent() {
+ return $this->_sent;
+ }
+
+ /**
+ * Accessor for the content after the last
+ * header line.
+ * @return string All content.
+ * @access public
+ */
+ function getContent() {
+ return $this->_content;
+ }
+
+ /**
+ * Accessor for header block. The response is the
+ * combination of this and the content.
+ * @return SimpleHeaders Wrapped header block.
+ * @access public
+ */
+ function getHeaders() {
+ return $this->_headers;
+ }
+
+ /**
+ * Accessor for any new cookies.
+ * @return array List of new cookies.
+ * @access public
+ */
+ function getNewCookies() {
+ return $this->_headers->getNewCookies();
+ }
+
+ /**
+ * Reads the whole of the socket output into a
+ * single string.
+ * @param SimpleSocket $socket Unread socket.
+ * @return string Raw output if successful
+ * else false.
+ * @access private
+ */
+ function _readAll($socket) {
+ $all = '';
+ while (! $this->_isLastPacket($next = $socket->read())) {
+ $all .= $next;
+ }
+ return $all;
+ }
+
+ /**
+ * Test to see if the packet from the socket is the
+ * last one.
+ * @param string $packet Chunk to interpret.
+ * @return boolean True if empty or EOF.
+ * @access private
+ */
+ function _isLastPacket($packet) {
+ if (is_string($packet)) {
+ return $packet === '';
+ }
+ return ! $packet;
+ }
+ }
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/mock_objects.php b/tests/UnitTests/simpletest/mock_objects.php
new file mode 100644
index 00000000..6d7db4ce
--- /dev/null
+++ b/tests/UnitTests/simpletest/mock_objects.php
@@ -0,0 +1,1323 @@
+SimpleExpectation();
+ }
+
+ /**
+ * Tests the expectation. Always true.
+ * @param mixed $compare Ignored.
+ * @return boolean True.
+ * @access public
+ */
+ function test($compare) {
+ return true;
+ }
+
+ /**
+ * 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 'Wildcard always matches [' . $dumper->describeValue($compare) . ']';
+ }
+ }
+
+ /**
+ * Parameter comparison assertion.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class ParametersExpectation extends SimpleExpectation {
+ protected $_expected;
+
+ /**
+ * Sets the expected parameter list.
+ * @param array $parameters Array of parameters including
+ * those that are wildcarded.
+ * If the value is not an array
+ * then it is considered to match any.
+ * @param mixed $wildcard Any parameter matching this
+ * will always match.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function ParametersExpectation($expected = false, $message = '%s') {
+ $this->SimpleExpectation($message);
+ $this->_expected = $expected;
+ }
+
+ /**
+ * Tests the assertion. True if correct.
+ * @param array $parameters Comparison values.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($parameters) {
+ if (! is_array($this->_expected)) {
+ return true;
+ }
+ if (count($this->_expected) != count($parameters)) {
+ return false;
+ }
+ for ($i = 0; $i < count($this->_expected); $i++) {
+ if (! $this->_testParameter($parameters[$i], $this->_expected[$i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Tests an individual parameter.
+ * @param mixed $parameter Value to test.
+ * @param mixed $expected Comparison value.
+ * @return boolean True if expectation
+ * fulfilled.
+ * @access private
+ */
+ function _testParameter($parameter, $expected) {
+ $comparison = $this->_coerceToExpectation($expected);
+ return $comparison->test($parameter);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param array $comparison Incoming parameter list.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($parameters) {
+ if ($this->test($parameters)) {
+ return "Expectation of " . count($this->_expected) .
+ " arguments of [" . $this->_renderArguments($this->_expected) .
+ "] is correct";
+ } else {
+ return $this->_describeDifference($this->_expected, $parameters);
+ }
+ }
+
+ /**
+ * Message to display if expectation differs from
+ * the parameters actually received.
+ * @param array $expected Expected parameters as list.
+ * @param array $parameters Actual parameters received.
+ * @return string Description of difference.
+ * @access private
+ */
+ function _describeDifference($expected, $parameters) {
+ if (count($expected) != count($parameters)) {
+ return "Expected " . count($expected) .
+ " arguments of [" . $this->_renderArguments($expected) .
+ "] but got " . count($parameters) .
+ " arguments of [" . $this->_renderArguments($parameters) . "]";
+ }
+ $messages = array();
+ for ($i = 0; $i < count($expected); $i++) {
+ $comparison = $this->_coerceToExpectation($expected[$i]);
+ if (! $comparison->test($parameters[$i])) {
+ $messages[] = "parameter " . ($i + 1) . " with [" .
+ $comparison->overlayMessage($parameters[$i]) . "]";
+ }
+ }
+ return "Parameter expectation differs at " . implode(" and ", $messages);
+ }
+
+ /**
+ * Creates an identical expectation if the
+ * object/value is not already some type
+ * of expectation.
+ * @param mixed $expected Expected value.
+ * @return SimpleExpectation Expectation object.
+ * @access private
+ */
+ function _coerceToExpectation($expected) {
+ if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) {
+ return $expected;
+ }
+ return new IdenticalExpectation($expected);
+ }
+
+ /**
+ * Renders the argument list as a string for
+ * messages.
+ * @param array $args Incoming arguments.
+ * @return string Simple description of type and value.
+ * @access private
+ */
+ function _renderArguments($args) {
+ $descriptions = array();
+ if (is_array($args)) {
+ foreach ($args as $arg) {
+ $dumper = new SimpleDumper();
+ $descriptions[] = $dumper->describeValue($arg);
+ }
+ }
+ return implode(', ', $descriptions);
+ }
+ }
+
+ /**
+ * Confirms that the number of calls on a method is as expected.
+ */
+ class CallCountExpectation extends SimpleExpectation {
+ protected $_method;
+ protected $_count;
+
+ /**
+ * Stashes the method and expected count for later
+ * reporting.
+ * @param string $method Name of method to confirm against.
+ * @param integer $count Expected number of calls.
+ * @param string $message Custom error message.
+ */
+ function CallCountExpectation($method, $count, $message = '%s') {
+ $this->_method = $method;
+ $this->_count = $count;
+ $this->SimpleExpectation($message);
+ }
+
+ /**
+ * Tests the assertion. True if correct.
+ * @param integer $compare Measured call count.
+ * @return boolean True if expected.
+ * @access public
+ */
+ function test($compare) {
+ return ($this->_count == $compare);
+ }
+
+ /**
+ * Reports the comparison.
+ * @param integer $compare Measured call count.
+ * @return string Message to show.
+ * @access public
+ */
+ function testMessage($compare) {
+ return 'Expected call count for [' . $this->_method .
+ '] was [' . $this->_count .
+ '] got [' . $compare . ']';
+ }
+ }
+
+ /**
+ * Confirms that the number of calls on a method is as expected.
+ */
+ class MinimumCallCountExpectation extends SimpleExpectation {
+ protected $_method;
+ protected $_count;
+
+ /**
+ * Stashes the method and expected count for later
+ * reporting.
+ * @param string $method Name of method to confirm against.
+ * @param integer $count Minimum number of calls.
+ * @param string $message Custom error message.
+ */
+ function MinimumCallCountExpectation($method, $count, $message = '%s') {
+ $this->_method = $method;
+ $this->_count = $count;
+ $this->SimpleExpectation($message);
+ }
+
+ /**
+ * Tests the assertion. True if correct.
+ * @param integer $compare Measured call count.
+ * @return boolean True if enough.
+ * @access public
+ */
+ function test($compare) {
+ return ($this->_count <= $compare);
+ }
+
+ /**
+ * Reports the comparison.
+ * @param integer $compare Measured call count.
+ * @return string Message to show.
+ * @access public
+ */
+ function testMessage($compare) {
+ return 'Minimum call count for [' . $this->_method .
+ '] was [' . $this->_count .
+ '] got [' . $compare . ']';
+ }
+ }
+
+ /**
+ * Confirms that the number of calls on a method is as expected.
+ */
+ class MaximumCallCountExpectation extends SimpleExpectation {
+ protected $_method;
+ protected $_count;
+
+ /**
+ * Stashes the method and expected count for later
+ * reporting.
+ * @param string $method Name of method to confirm against.
+ * @param integer $count Minimum number of calls.
+ * @param string $message Custom error message.
+ */
+ function MaximumCallCountExpectation($method, $count, $message = '%s') {
+ $this->_method = $method;
+ $this->_count = $count;
+ $this->SimpleExpectation($message);
+ }
+
+ /**
+ * Tests the assertion. True if correct.
+ * @param integer $compare Measured call count.
+ * @return boolean True if not over.
+ * @access public
+ */
+ function test($compare) {
+ return ($this->_count >= $compare);
+ }
+
+ /**
+ * Reports the comparison.
+ * @param integer $compare Measured call count.
+ * @return string Message to show.
+ * @access public
+ */
+ function testMessage($compare) {
+ return 'Maximum call count for [' . $this->_method .
+ '] was [' . $this->_count .
+ '] got [' . $compare . ']';
+ }
+ }
+
+ /**
+ * Retrieves values and references by searching the
+ * parameter lists until a match is found.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class CallMap {
+ protected $_map;
+
+ /**
+ * Creates an empty call map.
+ * @access public
+ */
+ function CallMap() {
+ $this->_map = array();
+ }
+
+ /**
+ * Stashes a value against a method call.
+ * @param array $parameters Arguments including wildcards.
+ * @param mixed $value Value copied into the map.
+ * @access public
+ */
+ function addValue($parameters, $value) {
+ $this->addReference($parameters, $value);
+ }
+
+ /**
+ * Stashes a reference against a method call.
+ * @param array $parameters Array of arguments (including wildcards).
+ * @param mixed $reference Array reference placed in the map.
+ * @access public
+ */
+ function addReference($parameters, $reference) {
+ $place = count($this->_map);
+ $this->_map[$place] = array();
+ $this->_map[$place]["params"] = new ParametersExpectation($parameters);
+ $this->_map[$place]["content"] = $reference;
+ }
+
+ /**
+ * Searches the call list for a matching parameter
+ * set. Returned by reference.
+ * @param array $parameters Parameters to search by
+ * without wildcards.
+ * @return object Object held in the first matching
+ * slot, otherwise null.
+ * @access public
+ */
+ function findFirstMatch($parameters) {
+ $slot = $this->_findFirstSlot($parameters);
+ if (!isset($slot)) {
+ return null;
+ }
+ return $slot["content"];
+ }
+
+ /**
+ * Searches the call list for a matching parameter
+ * set. True if successful.
+ * @param array $parameters Parameters to search by
+ * without wildcards.
+ * @return boolean True if a match is present.
+ * @access public
+ */
+ function isMatch($parameters) {
+ return ($this->_findFirstSlot($parameters) != null);
+ }
+
+ /**
+ * Searches the map for a matching item.
+ * @param array $parameters Parameters to search by
+ * without wildcards.
+ * @return array Reference to slot or null.
+ * @access private
+ */
+ function _findFirstSlot($parameters) {
+ $count = count($this->_map);
+ for ($i = 0; $i < $count; $i++) {
+ if ($this->_map[$i]["params"]->test($parameters)) {
+ return $this->_map[$i];
+ }
+ }
+ return null;
+ }
+ }
+
+ /**
+ * An empty collection of methods that can have their
+ * return values set. Used for prototyping.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class SimpleStub {
+ protected $_wildcard;
+ protected $_is_strict;
+ protected $_returns;
+ protected $_return_sequence;
+ protected $_call_counts;
+
+ /**
+ * Sets up the wildcard and everything else empty.
+ * @param mixed $wildcard Parameter matching wildcard.
+ * @param boolean $is_strict Enables method name checks.
+ * @access public
+ */
+ function SimpleStub($wildcard, $is_strict = true) {
+ $this->_wildcard = $wildcard;
+ $this->_is_strict = $is_strict;
+ $this->_returns = array();
+ $this->_return_sequence = array();
+ $this->_call_counts = array();
+ }
+
+ /**
+ * Replaces wildcard matches with wildcard
+ * expectations in the argument list.
+ * @param array $args Raw argument list.
+ * @return array Argument list with
+ * expectations.
+ * @access private
+ */
+ function _replaceWildcards($args) {
+ if ($args === false) {
+ return false;
+ }
+ for ($i = 0; $i < count($args); $i++) {
+ if ($args[$i] === $this->_wildcard) {
+ $args[$i] = new WildcardExpectation();
+ }
+ }
+ return $args;
+ }
+
+ /**
+ * Returns the expected value for the method name.
+ * @param string $method Name of method to simulate.
+ * @param array $args Arguments as an array.
+ * @return mixed Stored return.
+ * @access private
+ */
+ function _invoke($method, $args) {
+ $method = strtolower($method);
+ $step = $this->getCallCount($method);
+ $this->_addCall($method, $args);
+ return $this->_getReturn($method, $args, $step);
+ }
+
+ /**
+ * Triggers a PHP error if the method is not part
+ * of this object.
+ * @param string $method Name of method.
+ * @param string $task Description of task attempt.
+ * @access protected
+ */
+ function _dieOnNoMethod($method, $task) {
+ if ($this->_is_strict && !method_exists($this, $method)) {
+ trigger_error(
+ "Cannot $task as no ${method}() in class " . get_class($this),
+ E_USER_ERROR);
+ }
+ }
+
+ /**
+ * Adds one to the call count of a method.
+ * @param string $method Method called.
+ * @param array $args Arguments as an array.
+ * @access protected
+ */
+ function _addCall($method, $args) {
+ if (!isset($this->_call_counts[$method])) {
+ $this->_call_counts[$method] = 0;
+ }
+ $this->_call_counts[$method]++;
+ }
+
+ /**
+ * Fetches the call count of a method so far.
+ * @param string $method Method name called.
+ * @return Number of calls so far.
+ * @access public
+ */
+ function getCallCount($method) {
+ $this->_dieOnNoMethod($method, "get call count");
+ $method = strtolower($method);
+ if (! isset($this->_call_counts[$method])) {
+ return 0;
+ }
+ return $this->_call_counts[$method];
+ }
+
+ /**
+ * Sets a return for a parameter list that will
+ * be passed by value for all calls to this method.
+ * @param string $method Method name.
+ * @param mixed $value Result of call passed by value.
+ * @param array $args List of parameters to match
+ * including wildcards.
+ * @access public
+ */
+ function setReturnValue($method, $value, $args = false) {
+ $this->_dieOnNoMethod($method, "set return value");
+ $args = $this->_replaceWildcards($args);
+ $method = strtolower($method);
+ if (! isset($this->_returns[$method])) {
+ $this->_returns[$method] = new CallMap();
+ }
+ $this->_returns[$method]->addValue($args, $value);
+ }
+
+ /**
+ * Sets a return for a parameter list that will
+ * be passed by value only when the required call count
+ * is reached.
+ * @param integer $timing Number of calls in the future
+ * to which the result applies. If
+ * not set then all calls will return
+ * the value.
+ * @param string $method Method name.
+ * @param mixed $value Result of call passed by value.
+ * @param array $args List of parameters to match
+ * including wildcards.
+ * @access public
+ */
+ function setReturnValueAt($timing, $method, $value, $args = false) {
+ $this->_dieOnNoMethod($method, "set return value sequence");
+ $args = $this->_replaceWildcards($args);
+ $method = strtolower($method);
+ if (! isset($this->_return_sequence[$method])) {
+ $this->_return_sequence[$method] = array();
+ }
+ if (! isset($this->_return_sequence[$method][$timing])) {
+ $this->_return_sequence[$method][$timing] = new CallMap();
+ }
+ $this->_return_sequence[$method][$timing]->addValue($args, $value);
+ }
+
+ /**
+ * Sets a return for a parameter list that will
+ * be passed by reference for all calls.
+ * @param string $method Method name.
+ * @param mixed $reference Result of the call will be this object.
+ * @param array $args List of parameters to match
+ * including wildcards.
+ * @access public
+ */
+ function setReturnReference($method, $reference, $args = false) {
+ $this->_dieOnNoMethod($method, "set return reference");
+ $args = $this->_replaceWildcards($args);
+ $method = strtolower($method);
+ if (! isset($this->_returns[$method])) {
+ $this->_returns[$method] = new CallMap();
+ }
+ $this->_returns[$method]->addReference($args, $reference);
+ }
+
+ /**
+ * Sets a return for a parameter list that will
+ * be passed by value only when the required call count
+ * is reached.
+ * @param integer $timing Number of calls in the future
+ * to which the result applies. If
+ * not set then all calls will return
+ * the value.
+ * @param string $method Method name.
+ * @param mixed $reference Result of the call will be this object.
+ * @param array $args List of parameters to match
+ * including wildcards.
+ * @access public
+ */
+ function setReturnReferenceAt($timing, $method, $reference, $args = false) {
+ $this->_dieOnNoMethod($method, "set return reference sequence");
+ $args = $this->_replaceWildcards($args);
+ $method = strtolower($method);
+ if (! isset($this->_return_sequence[$method])) {
+ $this->_return_sequence[$method] = array();
+ }
+ if (! isset($this->_return_sequence[$method][$timing])) {
+ $this->_return_sequence[$method][$timing] = new CallMap();
+ }
+ $this->_return_sequence[$method][$timing]->addReference($args, $reference);
+ }
+
+ /**
+ * Finds the return value matching the incoming
+ * arguments. If there is no matching value found
+ * then an error is triggered.
+ * @param string $method Method name.
+ * @param array $args Calling arguments.
+ * @param integer $step Current position in the
+ * call history.
+ * @return mixed Stored return.
+ * @access protected
+ */
+ function _getReturn($method, $args, $step) {
+ if (isset($this->_return_sequence[$method][$step])) {
+ if ($this->_return_sequence[$method][$step]->isMatch($args)) {
+ return $this->_return_sequence[$method][$step]->findFirstMatch($args);
+ }
+ }
+ if (isset($this->_returns[$method])) {
+ return $this->_returns[$method]->findFirstMatch($args);
+ }
+ return null;
+ }
+ }
+
+ /**
+ * An empty collection of methods that can have their
+ * return values set and expectations made of the
+ * calls upon them. The mock will assert the
+ * expectations against it's attached test case in
+ * addition to the server stub behaviour.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class SimpleMock extends SimpleStub {
+ protected $_test;
+ protected $_expected_counts;
+ protected $_max_counts;
+ protected $_expected_args;
+ protected $_expected_args_at;
+
+ /**
+ * Creates an empty return list and expectation list.
+ * All call counts are set to zero.
+ * @param SimpleTestCase $test Test case to test expectations in.
+ * @param mixed $wildcard Parameter matching wildcard.
+ * @param boolean $is_strict Enables method name checks on
+ * expectations.
+ * @access public
+ */
+ function SimpleMock($test, $wildcard, $is_strict = true) {
+ $this->SimpleStub($wildcard, $is_strict);
+ if (! $test) {
+ trigger_error('No unit tester for mock object', E_USER_ERROR);
+ return;
+ }
+ $this->_test = SimpleMock::registerTest($test);
+ $this->_expected_counts = array();
+ $this->_max_counts = array();
+ $this->_expected_args = array();
+ $this->_expected_args_at = array();
+ }
+
+ /**
+ * Accessor for attached unit test so that when
+ * subclassed, new expectations can be added easily.
+ * @return SimpleTestCase Unit test passed in constructor.
+ * @access public
+ */
+ function getTest() {
+ return $this->_test;
+ }
+
+ /**
+ * Die if bad arguments array is passed
+ * @param mixed $args The arguments value to be checked.
+ * @param string $task Description of task attempt.
+ * @return boolean Valid arguments
+ * @access private
+ */
+ function _checkArgumentsIsArray($args, $task) {
+ if (! is_array($args)) {
+ trigger_error(
+ "Cannot $task as \$args parameter is not an array",
+ E_USER_ERROR);
+ }
+ }
+
+ /**
+ * Sets up an expected call with a set of
+ * expected parameters in that call. All
+ * calls will be compared to these expectations
+ * regardless of when the call is made.
+ * @param string $method Method call to test.
+ * @param array $args Expected parameters for the call
+ * including wildcards.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectArguments($method, $args, $message = '%s') {
+ $this->_dieOnNoMethod($method, 'set expected arguments');
+ $this->_checkArgumentsIsArray($args, 'set expected arguments');
+ $args = $this->_replaceWildcards($args);
+ $message .= Mock::getExpectationLine(' at line [%d]');
+ $this->_expected_args[strtolower($method)] =
+ new ParametersExpectation($args, $message);
+ }
+
+ /**
+ * Sets up an expected call with a set of
+ * expected parameters in that call. The
+ * expected call count will be adjusted if it
+ * is set too low to reach this call.
+ * @param integer $timing Number of calls in the future at
+ * which to test. Next call is 0.
+ * @param string $method Method call to test.
+ * @param array $args Expected parameters for the call
+ * including wildcards.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectArgumentsAt($timing, $method, $args, $message = '%s') {
+ $this->_dieOnNoMethod($method, 'set expected arguments at time');
+ $this->_checkArgumentsIsArray($args, 'set expected arguments at time');
+ $args = $this->_replaceWildcards($args);
+ if (! isset($this->_expected_args_at[$timing])) {
+ $this->_expected_args_at[$timing] = array();
+ }
+ $method = strtolower($method);
+ $message .= Mock::getExpectationLine(' at line [%d]');
+ $this->_expected_args_at[$timing][$method] =
+ new ParametersExpectation($args, $message);
+ }
+
+ /**
+ * Sets an expectation for the number of times
+ * a method will be called. The tally method
+ * is used to check this.
+ * @param string $method Method call to test.
+ * @param integer $count Number of times it should
+ * have been called at tally.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectCallCount($method, $count, $message = '%s') {
+ $this->_dieOnNoMethod($method, 'set expected call count');
+ $message .= Mock::getExpectationLine(' at line [%d]');
+ $this->_expected_counts[strtolower($method)] =
+ new CallCountExpectation($method, $count, $message);
+ }
+
+ /**
+ * Sets the number of times a method may be called
+ * before a test failure is triggered.
+ * @param string $method Method call to test.
+ * @param integer $count Most number of times it should
+ * have been called.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectMaximumCallCount($method, $count, $message = '%s') {
+ $this->_dieOnNoMethod($method, 'set maximum call count');
+ $message .= Mock::getExpectationLine(' at line [%d]');
+ $this->_max_counts[strtolower($method)] =
+ new MaximumCallCountExpectation($method, $count, $message);
+ }
+
+ /**
+ * Sets the number of times to call a method to prevent
+ * a failure on the tally.
+ * @param string $method Method call to test.
+ * @param integer $count Least number of times it should
+ * have been called.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectMinimumCallCount($method, $count, $message = '%s') {
+ $this->_dieOnNoMethod($method, 'set minimum call count');
+ $message .= Mock::getExpectationLine(' at line [%d]');
+ $this->_expected_counts[strtolower($method)] =
+ new MinimumCallCountExpectation($method, $count, $message);
+ }
+
+ /**
+ * Convenience method for barring a method
+ * call.
+ * @param string $method Method call to ban.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectNever($method, $message = '%s') {
+ $this->expectMaximumCallCount($method, 0, $message);
+ }
+
+ /**
+ * Convenience method for a single method
+ * call.
+ * @param string $method Method call to track.
+ * @param array $args Expected argument list or
+ * false for any arguments.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectOnce($method, $args = false, $message = '%s') {
+ $this->expectCallCount($method, 1, $message);
+ if ($args !== false) {
+ $this->expectArguments($method, $args, $message);
+ }
+ }
+
+ /**
+ * Convenience method for requiring a method
+ * call.
+ * @param string $method Method call to track.
+ * @param array $args Expected argument list or
+ * false for any arguments.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectAtLeastOnce($method, $args = false, $message = '%s') {
+ $this->expectMinimumCallCount($method, 1, $message);
+ if ($args !== false) {
+ $this->expectArguments($method, $args, $message);
+ }
+ }
+
+ /**
+ * Totals up the call counts and triggers a test
+ * assertion if a test is present for expected
+ * call counts.
+ * This method must be called explicitly for the call
+ * count assertions to be triggered.
+ * @access public
+ */
+ function tally() {
+ foreach ($this->_expected_counts as $method => $expectation) {
+ $this->_assertTrue(
+ $expectation->test($this->getCallCount($method)),
+ $expectation->overlayMessage($this->getCallCount($method)));
+ }
+ foreach ($this->_max_counts as $method => $expectation) {
+ if ($expectation->test($this->getCallCount($method))) {
+ $this->_assertTrue(
+ true,
+ $expectation->overlayMessage($this->getCallCount($method)));
+ }
+ }
+ }
+
+ /**
+ * Returns the expected value for the method name
+ * and checks expectations. Will generate any
+ * test assertions as a result of expectations
+ * if there is a test present.
+ * @param string $method Name of method to simulate.
+ * @param array $args Arguments as an array.
+ * @return mixed Stored return.
+ * @access private
+ */
+ function _invoke($method, $args) {
+ $method = strtolower($method);
+ $step = $this->getCallCount($method);
+ $this->_addCall($method, $args);
+ $this->_checkExpectations($method, $args, $step);
+ return $this->_getReturn($method, $args, $step);
+ }
+
+ /**
+ * Tests the arguments against expectations.
+ * @param string $method Method to check.
+ * @param array $args Argument list to match.
+ * @param integer $timing The position of this call
+ * in the call history.
+ * @access private
+ */
+ function _checkExpectations($method, $args, $timing) {
+ if (isset($this->_max_counts[$method])) {
+ if (! $this->_max_counts[$method]->test($timing + 1)) {
+ $this->_assertTrue(
+ false,
+ $this->_max_counts[$method]->overlayMessage($timing + 1));
+ }
+ }
+ if (isset($this->_expected_args_at[$timing][$method])) {
+ $this->_assertTrue(
+ $this->_expected_args_at[$timing][$method]->test($args),
+ "Mock method [$method] at [$timing] -> " .
+ $this->_expected_args_at[$timing][$method]->overlayMessage($args));
+ } elseif (isset($this->_expected_args[$method])) {
+ $this->_assertTrue(
+ $this->_expected_args[$method]->test($args),
+ "Mock method [$method] -> " . $this->_expected_args[$method]->overlayMessage($args));
+ }
+ }
+
+ /**
+ * Triggers an assertion on the held test case.
+ * Should be overridden when using another test
+ * framework other than the SimpleTest one if the
+ * assertion method has a different name.
+ * @param boolean $assertion True will pass.
+ * @param string $message Message that will go with
+ * the test event.
+ * @access protected
+ */
+ function _assertTrue($assertion, $message) {
+ $test =SimpleMock::injectTest($this->_test);
+ $test->assertTrue($assertion, $message);
+ }
+
+ /**
+ * Stashes the test case for later recovery.
+ * @param SimpleTestCase $test Test case.
+ * @return string Key to find it again.
+ * @access public
+ * @static
+ */
+ function registerTest($test) {
+ $registry =SimpleMock::_getRegistry();
+ $registry[$class = get_class($test)] = $test;
+ return $class;
+ }
+
+ /**
+ * Resolves the dependency on the test case.
+ * @param string $class Key to look up test case in.
+ * @return SimpleTestCase Test case to send results to.
+ * @access public
+ * @static
+ */
+ function injectTest($key) {
+ $registry =SimpleMock::_getRegistry();
+ return $registry[$key];
+ }
+
+ /**
+ * Registry for test cases. The reason for this is
+ * to break the reference between the test cases and
+ * the mocks. It was leading to a fatal error due to
+ * recursive dependencies during comparisons. See
+ * http://bugs.php.net/bug.php?id=31449 for the PHP
+ * bug.
+ * @return array List of references.
+ * @access private
+ * @static
+ */
+ function _getRegistry() {
+ static $registry;
+ if (! isset($registry)) {
+ $registry = array();
+ }
+ return $registry;
+ }
+ }
+
+ /**
+ * Static methods only service class for code generation of
+ * server stubs.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class Stub {
+
+ /**
+ * Factory for server stub classes.
+ */
+ function Stub() {
+ trigger_error('Stub factory methods are class only.');
+ }
+
+ /**
+ * Clones a class' interface and creates a stub version
+ * that can have return values set.
+ * @param string $class Class to clone.
+ * @param string $stub_class New class name. Default is
+ * the old name with "Stub"
+ * prepended.
+ * @param array $methods Additional methods to add beyond
+ * those in the cloned class. Use this
+ * to emulate the dynamic addition of
+ * methods in the cloned class or when
+ * the class hasn't been written yet.
+ * @static
+ * @access public
+ */
+ function generate($class, $stub_class = false, $methods = false) {
+ if (! SimpleTestCompatibility::classExists($class)) {
+ return false;
+ }
+ if (! $stub_class) {
+ $stub_class = "Stub" . $class;
+ }
+ if (SimpleTestCompatibility::classExists($stub_class)) {
+ return false;
+ }
+ return eval(Stub::_createClassCode(
+ $class,
+ $stub_class,
+ $methods ? $methods : array()) . " return true;");
+ }
+
+ /**
+ * The new server stub class code in string form.
+ * @param string $class Class to clone.
+ * @param string $mock_class New class name.
+ * @param array $methods Additional methods.
+ * @static
+ * @access private
+ */
+ function _createClassCode($class, $stub_class, $methods) {
+ $stub_base = SimpleTestOptions::getStubBaseClass();
+ $code = "class $stub_class extends $stub_base {\n";
+ $code .= " function $stub_class(\$wildcard = MOCK_WILDCARD) {\n";
+ $code .= " \$this->$stub_base(\$wildcard);\n";
+ $code .= " }\n";
+ $code .= Stub::_createHandlerCode($class, $stub_base, $methods);
+ $code .= "}\n";
+ return $code;
+ }
+
+ /**
+ * Creates code within a class to generate replaced
+ * methods. All methods call the _invoke() handler
+ * with the method name and the arguments in an
+ * array.
+ * @param string $class Class to clone.
+ * @param string $base Base mock/stub class with methods that
+ * cannot be cloned. Otherwise you
+ * would be stubbing the accessors used
+ * to set the stubs.
+ * @param array $methods Additional methods.
+ * @static
+ * @access private
+ */
+ function _createHandlerCode($class, $base, $methods) {
+ $code = "";
+ $methods = array_merge($methods, get_class_methods($class));
+ foreach ($methods as $method) {
+ if (Stub::_isSpecialMethod($method)) {
+ continue;
+ }
+ if (in_array($method, get_class_methods($base))) {
+ continue;
+ }
+ $code .= " function $method() {\n";
+ $code .= " \$args = func_get_args();\n";
+ $code .= " return \$this->_invoke(\"$method\", \$args);\n";
+ $code .= " }\n";
+ }
+ return $code;
+ }
+
+ /**
+ * Tests to see if a special PHP method is about to
+ * be stubbed by mistake.
+ * @param string $method Method name.
+ * @return boolean True if special.
+ * @access private
+ * @static
+ */
+ function _isSpecialMethod($method) {
+ return in_array(
+ strtolower($method),
+ array('__construct', '__clone', '__get', '__set', '__call'));
+ }
+ }
+
+ /**
+ * Static methods only service class for code generation of
+ * mock objects.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class Mock {
+
+ /**
+ * Factory for mock object classes.
+ * @access public
+ */
+ function Mock() {
+ trigger_error("Mock factory methods are class only.");
+ }
+
+ /**
+ * Clones a class' interface and creates a mock version
+ * that can have return values and expectations set.
+ * @param string $class Class to clone.
+ * @param string $mock_class New class name. Default is
+ * the old name with "Mock"
+ * prepended.
+ * @param array $methods Additional methods to add beyond
+ * those in th cloned class. Use this
+ * to emulate the dynamic addition of
+ * methods in the cloned class or when
+ * the class hasn't been written yet.
+ * @static
+ * @access public
+ */
+ function generate($class, $mock_class = false, $methods = false) {
+ if (! SimpleTestCompatibility::classExists($class)) {
+ return false;
+ }
+ if (! $mock_class) {
+ $mock_class = "Mock" . $class;
+ }
+ if (SimpleTestCompatibility::classExists($mock_class)) {
+ return false;
+ }
+ return eval(Mock::_createClassCode(
+ $class,
+ $mock_class,
+ $methods ? $methods : array()) . " return true;");
+ }
+
+ /**
+ * Generates a version of a class with selected
+ * methods mocked only. Inherits the old class
+ * and chains the mock methods of an aggregated
+ * mock object.
+ * @param string $class Class to clone.
+ * @param string $mock_class New class name.
+ * @param array $methods Methods to be overridden
+ * with mock versions.
+ * @static
+ * @access public
+ */
+ function generatePartial($class, $mock_class, $methods) {
+ if (! SimpleTestCompatibility::classExists($class)) {
+ return false;
+ }
+ if (SimpleTestCompatibility::classExists($mock_class)) {
+ trigger_error("Partial mock class [$mock_class] already exists");
+ return false;
+ }
+ return eval(Mock::_extendClassCode($class, $mock_class, $methods));
+ }
+
+ /**
+ * The new mock class code as a string.
+ * @param string $class Class to clone.
+ * @param string $mock_class New class name.
+ * @param array $methods Additional methods.
+ * @return string Code for new mock class.
+ * @static
+ * @access private
+ */
+ function _createClassCode($class, $mock_class, $methods) {
+ $mock_base = SimpleTestOptions::getMockBaseClass();
+ $code = "class $mock_class extends $mock_base {\n";
+ $code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n";
+ $code .= " \$this->$mock_base(\$test, \$wildcard);\n";
+ $code .= " }\n";
+ $code .= Stub::_createHandlerCode($class, $mock_base, $methods);
+ $code .= "}\n";
+ return $code;
+ }
+
+ /**
+ * The extension class code as a string. The class
+ * composites a mock object and chains mocked methods
+ * to it.
+ * @param string $class Class to extend.
+ * @param string $mock_class New class name.
+ * @param array $methods Mocked methods.
+ * @return string Code for a new class.
+ * @static
+ * @access private
+ */
+ function _extendClassCode($class, $mock_class, $methods) {
+ $mock_base = SimpleTestOptions::getMockBaseClass();
+ $code = "class $mock_class extends $class {\n";
+ $code .= " var \$_mock;\n";
+ $code .= Mock::_addMethodList($methods);
+ $code .= "\n";
+ $code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n";
+ $code .= " \$this->_mock = new $mock_base(\$test, \$wildcard, false);\n";
+ $code .= " }\n";
+ $code .= Mock::_chainMockReturns();
+ $code .= Mock::_chainMockExpectations();
+ $code .= Mock::_overrideMethods($methods);
+ $code .= SimpleTestOptions::getPartialMockCode();
+ $code .= "}\n";
+ return $code;
+ }
+
+ /**
+ * Creates a list of mocked methods for error checking.
+ * @param array $methods Mocked methods.
+ * @return string Code for a method list.
+ * @access private
+ */
+ function _addMethodList($methods) {
+ return " var \$_mocked_methods = array('" . implode("', '", $methods) . "');\n";
+ }
+
+ /**
+ * Creates code to abandon the expectation if not mocked.
+ * @param string $alias Parameter name of method name.
+ * @return string Code for bail out.
+ * @access private
+ */
+ function _bailOutIfNotMocked($alias) {
+ $code = " if (! in_array($alias, \$this->_mocked_methods)) {\n";
+ $code .= " trigger_error(\"Method [$alias] is not mocked\");\n";
+ $code .= " return;\n";
+ $code .= " }\n";
+ return $code;
+ }
+
+ /**
+ * Creates source code for chaining to the composited
+ * mock object.
+ * @return string Code for mock set up.
+ * @access private
+ */
+ function _chainMockReturns() {
+ $code = " function setReturnValue(\$method, \$value, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->setReturnValue(\$method, \$value, \$args);\n";
+ $code .= " }\n";
+ $code .= " function setReturnValueAt(\$timing, \$method, \$value, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n";
+ $code .= " }\n";
+ $code .= " function setReturnReference(\$method, &\$ref, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->setReturnReference(\$method, \$ref, \$args);\n";
+ $code .= " }\n";
+ $code .= " function setReturnReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->setReturnReferenceAt(\$timing, \$method, \$ref, \$args);\n";
+ $code .= " }\n";
+ return $code;
+ }
+
+ /**
+ * Creates source code for chaining to an aggregated
+ * mock object.
+ * @return string Code for expectations.
+ * @access private
+ */
+ function _chainMockExpectations() {
+ $code = " function expectArguments(\$method, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectArguments(\$method, \$args);\n";
+ $code .= " }\n";
+ $code .= " function expectArgumentsAt(\$timing, \$method, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args);\n";
+ $code .= " }\n";
+ $code .= " function expectCallCount(\$method, \$count) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectCallCount(\$method, \$count);\n";
+ $code .= " }\n";
+ $code .= " function expectMaximumCallCount(\$method, \$count) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectMaximumCallCount(\$method, \$count);\n";
+ $code .= " }\n";
+ $code .= " function expectMinimumCallCount(\$method, \$count) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectMinimumCallCount(\$method, \$count);\n";
+ $code .= " }\n";
+ $code .= " function expectNever(\$method) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectNever(\$method);\n";
+ $code .= " }\n";
+ $code .= " function expectOnce(\$method, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectOnce(\$method, \$args);\n";
+ $code .= " }\n";
+ $code .= " function expectAtLeastOnce(\$method, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectAtLeastOnce(\$method, \$args);\n";
+ $code .= " }\n";
+ $code .= " function tally() {\n";
+ $code .= " \$this->_mock->tally();\n";
+ $code .= " }\n";
+ return $code;
+ }
+
+ /**
+ * Creates source code to override a list of methods
+ * with mock versions.
+ * @param array $methods Methods to be overridden
+ * with mock versions.
+ * @return string Code for overridden chains.
+ * @access private
+ */
+ function _overrideMethods($methods) {
+ $code = "";
+ foreach ($methods as $method) {
+ $code .= " function $method() {\n";
+ $code .= " \$args = func_get_args();\n";
+ $code .= " return \$this->_mock->_invoke(\"$method\", \$args);\n";
+ $code .= " }\n";
+ }
+ return $code;
+ }
+
+ /**
+ * 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 expect*
+ * method embedded in format string.
+ * @access public
+ * @static
+ */
+ function getExpectationLine($format = '%d', $stack = false) {
+ if ($stack === false) {
+ $stack = SimpleTestCompatibility::getStackTrace();
+ }
+ return SimpleDumper::getFormattedAssertionLine($stack, $format, 'expect');
+ }
+ }
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/mytests/log_test.php b/tests/UnitTests/simpletest/mytests/log_test.php
new file mode 100644
index 00000000..d1254b7a
--- /dev/null
+++ b/tests/UnitTests/simpletest/mytests/log_test.php
@@ -0,0 +1,18 @@
+assertFalse(false);
+ //$log->message('Should write this to a file');
+ $this->assertTrue(true);
+ }
+}
+
+$test = new TestOfLogging();
+$test->run(new HtmlReporter());
+
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/options.php b/tests/UnitTests/simpletest/options.php
new file mode 100644
index 00000000..63b6b996
--- /dev/null
+++ b/tests/UnitTests/simpletest/options.php
@@ -0,0 +1,366 @@
+ 'SimpleStub',
+ 'MockBaseClass' => 'SimpleMock',
+ 'IgnoreList' => array(),
+ 'AdditionalPartialMockCode' => '',
+ 'DefaultProxy' => false,
+ 'DefaultProxyUsername' => false,
+ 'DefaultProxyPassword' => false);
+ }
+ }
+
+ /**
+ * Static methods for compatibility between different
+ * PHP versions.
+ * @package SimpleTest
+ */
+ class SimpleTestCompatibility {
+
+ /**
+ * 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
+ */
+ function isIdentical($first, $second) {
+ if ($first != $second) {
+ return false;
+ }
+ if (version_compare(phpversion(), '5') >= 0) {
+ return SimpleTestCompatibility::_isIdenticalType($first, $second);
+ }
+ return ($first === $second);
+ }
+
+ /**
+ * Recursive type test.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @access private
+ * @static
+ */
+ function _isIdenticalType($first, $second) {
+ if (gettype($first) != gettype($second)) {
+ return false;
+ }
+ if (is_object($first) && is_object($second)) {
+ if (get_class($first) != get_class($second)) {
+ return false;
+ }
+ return SimpleTestCompatibility::_isArrayOfIdenticalTypes(
+ get_object_vars($first),
+ get_object_vars($second));
+ }
+ if (is_array($first) && is_array($second)) {
+ return SimpleTestCompatibility::_isArrayOfIdenticalTypes($first, $second);
+ }
+ return true;
+ }
+
+ /**
+ * Recursive type test for each element of an array.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @access private
+ * @static
+ */
+ function _isArrayOfIdenticalTypes($first, $second) {
+ if (array_keys($first) != array_keys($second)) {
+ return false;
+ }
+ foreach (array_keys($first) as $key) {
+ $is_identical = SimpleTestCompatibility::_isIdenticalType(
+ $first[$key],
+ $second[$key]);
+ if (! $is_identical) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Test for two variables being aliases.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @access public
+ * @static
+ */
+ function isReference($first, $second) {
+ if (version_compare(phpversion(), '5', '>=')
+ && is_object($first)) {
+ return ($first === $second);
+ }
+ $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
+ */
+ function isA($object, $class) {
+ if (version_compare(phpversion(), '5') >= 0) {
+ if (! class_exists($class, false)) {
+ return false;
+ }
+ eval("\$is_a = \$object instanceof $class;");
+ return $is_a;
+ }
+ if (function_exists('is_a')) {
+ return is_a($object, $class);
+ }
+ return ((strtolower($class) == get_class($object))
+ 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
+ */
+ function setTimeout($handle, $timeout) {
+ if (function_exists('stream_set_timeout')) {
+ stream_set_timeout($handle, $timeout, 0);
+ } elseif (function_exists('socket_set_timeout')) {
+ socket_set_timeout($handle, $timeout, 0);
+ } elseif (function_exists('set_socket_timeout')) {
+ set_socket_timeout($handle, $timeout, 0);
+ }
+ }
+
+ /**
+ * 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());
+ }
+ return array();
+ }
+ }
+?>
diff --git a/tests/UnitTests/simpletest/page.php b/tests/UnitTests/simpletest/page.php
new file mode 100644
index 00000000..03091d3e
--- /dev/null
+++ b/tests/UnitTests/simpletest/page.php
@@ -0,0 +1,961 @@
+SimpleSaxListener();
+ }
+
+ /**
+ * Reads the raw content and send events
+ * into the page to be built.
+ * @param $response SimpleHttpResponse Fetched response.
+ * @return SimplePage Newly parsed page.
+ * @access public
+ */
+ function parse($response) {
+ $this->_tags = array();
+ $this->_page = $this->_createPage($response);
+ $parser = $this->_createParser($this);
+ $parser->parse($response->getContent());
+ $this->_page->acceptPageEnd();
+ return $this->_page;
+ }
+
+ /**
+ * Creates an empty page.
+ * @return SimplePage New unparsed page.
+ * @access protected
+ */
+ function _createPage($response) {
+ return new SimplePage($response);
+ }
+
+ /**
+ * Creates the parser used with the builder.
+ * @param $listener SimpleSaxListener Target of parser.
+ * @return SimpleSaxParser Parser to generate
+ * events for the builder.
+ * @access protected
+ */
+ function _createParser($listener) {
+ return new SimpleSaxParser($listener);
+ }
+
+ /**
+ * Make the keys lower case for case insensitive look-ups.
+ * @param hash $map Hash to convert.
+ * @return hash Unchanged values, but keys lower case.
+ * @access private
+ */
+ function _keysToLowerCase($map) {
+ $lower = array();
+ foreach ($map as $key => $value) {
+ $lower[strtolower($key)] = $value;
+ }
+ return $lower;
+ }
+
+ /**
+ * Start of element event. Opens a new tag.
+ * @param string $name Element name.
+ * @param hash $attributes Attributes without content
+ * are marked as true.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function startElement($name, $attributes) {
+ $tag = $this->_createTag($name, $this->_keysToLowerCase($attributes));
+ if ($name == 'form') {
+ $this->_page->acceptFormStart($tag);
+ return true;
+ }
+ if ($name == 'frameset') {
+ $this->_page->acceptFramesetStart($tag);
+ return true;
+ }
+ if ($name == 'frame') {
+ $this->_page->acceptFrame($tag);
+ return true;
+ }
+ if ($tag->expectEndTag()) {
+ $this->_openTag($tag);
+ return true;
+ }
+ $this->_page->acceptTag($tag);
+ return true;
+ }
+
+ /**
+ * End of element event.
+ * @param string $name Element name.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function endElement($name) {
+ if ($name == 'form') {
+ $this->_page->acceptFormEnd();
+ return true;
+ }
+ if ($name == 'frameset') {
+ $this->_page->acceptFramesetEnd();
+ return true;
+ }
+ if (isset($this->_tags[$name]) && (count($this->_tags[$name]) > 0)) {
+ $tag = array_pop($this->_tags[$name]);
+ $this->_addContentTagToOpenTags($tag);
+ $this->_page->acceptTag($tag);
+ return true;
+ }
+ return true;
+ }
+
+ /**
+ * Unparsed, but relevant data. The data is added
+ * to every open tag.
+ * @param string $text May include unparsed tags.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function addContent($text) {
+ foreach (array_keys($this->_tags) as $name) {
+ for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) {
+ $this->_tags[$name][$i]->addContent($text);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Parsed relevant data. The parsed tag is added
+ * to every open tag.
+ * @param SimpleTag $tag May include unparsed tags.
+ * @access private
+ */
+ function _addContentTagToOpenTags($tag) {
+ if ($tag->getTagName() != 'option') {
+ return;
+ }
+ foreach (array_keys($this->_tags) as $name) {
+ for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) {
+ $this->_tags[$name][$i]->addTag($tag);
+ }
+ }
+ }
+
+ /**
+ * Opens a tag for receiving content. Multiple tags
+ * will be receiving input at the same time.
+ * @param SimpleTag $tag New content tag.
+ * @access private
+ */
+ function _openTag($tag) {
+ $name = $tag->getTagName();
+ if (! in_array($name, array_keys($this->_tags))) {
+ $this->_tags[$name] = array();
+ }
+ array_push($this->_tags[$name], $tag);
+ }
+
+ /**
+ * Factory for the tag objects. Creates the
+ * appropriate tag object for the incoming tag name.
+ * @param string $name HTML tag name.
+ * @param hash $attributes Element attributes.
+ * @return SimpleTag Tag object.
+ * @access protected
+ */
+ function _createTag($name, $attributes) {
+ if ($name == 'a') {
+ return new SimpleAnchorTag($attributes);
+ } elseif ($name == 'title') {
+ return new SimpleTitleTag($attributes);
+ } elseif ($name == 'input') {
+ return $this->_createInputTag($attributes);
+ } elseif ($name == 'button') {
+ return new SimpleButtonTag($attributes);
+ } elseif ($name == 'textarea') {
+ return new SimpleTextAreaTag($attributes);
+ } elseif ($name == 'select') {
+ return $this->_createSelectionTag($attributes);
+ } elseif ($name == 'option') {
+ return new SimpleOptionTag($attributes);
+ } elseif ($name == 'form') {
+ return new SimpleFormTag($attributes);
+ } elseif ($name == 'frame') {
+ return new SimpleFrameTag($attributes);
+ }
+ return new SimpleTag($name, $attributes);
+ }
+
+ /**
+ * Factory for selection fields.
+ * @param hash $attributes Element attributes.
+ * @return SimpleTag Tag object.
+ * @access protected
+ */
+ function _createSelectionTag($attributes) {
+ if (isset($attributes['multiple'])) {
+ return new MultipleSelectionTag($attributes);
+ }
+ return new SimpleSelectionTag($attributes);
+ }
+
+ /**
+ * Factory for input tags.
+ * @param hash $attributes Element attributes.
+ * @return SimpleTag Tag object.
+ * @access protected
+ */
+ function _createInputTag($attributes) {
+ if (! isset($attributes['type'])) {
+ return new SimpleTextTag($attributes);
+ }
+ $type = strtolower($attributes['type']);
+ if ($type == 'submit') {
+ return new SimpleSubmitTag($attributes);
+ } elseif ($type == 'image') {
+ return new SimpleImageSubmitTag($attributes);
+ } elseif ($type == 'checkbox') {
+ return new SimpleCheckboxTag($attributes);
+ } elseif ($type == 'radio') {
+ return new SimpleRadioButtonTag($attributes);
+ } else {
+ return new SimpleTextTag($attributes);
+ }
+ }
+ }
+
+ /**
+ * A wrapper for a web page.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimplePage {
+ protected $_links;
+ protected $_title;
+ protected $_open_forms;
+ protected $_complete_forms;
+ protected $_frameset;
+ protected $_frames;
+ protected $_frameset_nesting_level;
+ protected $_transport_error;
+ protected $_raw;
+ protected $_text;
+ protected $_sent;
+ protected $_headers;
+ protected $_method;
+ protected $_url;
+ protected $_request_data;
+
+ /**
+ * Parses a page ready to access it's contents.
+ * @param SimpleHttpResponse $response Result of HTTP fetch.
+ * @access public
+ */
+ function SimplePage($response = false) {
+ $this->_links = array();
+ $this->_title = false;
+ $this->_open_forms = array();
+ $this->_complete_forms = array();
+ $this->_frameset = false;
+ $this->_frames = array();
+ $this->_frameset_nesting_level = 0;
+ $this->_text = false;
+ if ($response) {
+ $this->_extractResponse($response);
+ } else {
+ $this->_noResponse();
+ }
+ }
+
+ /**
+ * Extracts all of the response information.
+ * @param SimpleHttpResponse $response Response being parsed.
+ * @access private
+ */
+ function _extractResponse($response) {
+ $this->_transport_error = $response->getError();
+ $this->_raw = $response->getContent();
+ $this->_sent = $response->getSent();
+ $this->_headers = $response->getHeaders();
+ $this->_method = $response->getMethod();
+ $this->_url = $response->getUrl();
+ $this->_request_data = $response->getRequestData();
+ }
+
+ /**
+ * Sets up a missing response.
+ * @access private
+ */
+ function _noResponse() {
+ $this->_transport_error = 'No page fetched yet';
+ $this->_raw = false;
+ $this->_sent = false;
+ $this->_headers = false;
+ $this->_method = 'GET';
+ $this->_url = false;
+ $this->_request_data = false;
+ }
+
+ /**
+ * Original request as bytes sent down the wire.
+ * @return mixed Sent content.
+ * @access public
+ */
+ function getRequest() {
+ return $this->_sent;
+ }
+
+ /**
+ * Accessor for raw text of page.
+ * @return string Raw unparsed content.
+ * @access public
+ */
+ function getRaw() {
+ return $this->_raw;
+ }
+
+ /**
+ * Accessor for plain text of page as a text browser
+ * would see it.
+ * @return string Plain text of page.
+ * @access public
+ */
+ function getText() {
+ if (! $this->_text) {
+ $this->_text = SimpleSaxParser::normalise($this->_raw);
+ }
+ return $this->_text;
+ }
+
+ /**
+ * Accessor for raw headers of page.
+ * @return string Header block as text.
+ * @access public
+ */
+ function getHeaders() {
+ if ($this->_headers) {
+ return $this->_headers->getRaw();
+ }
+ return false;
+ }
+
+ /**
+ * Original request method.
+ * @return string GET, POST or HEAD.
+ * @access public
+ */
+ function getMethod() {
+ return $this->_method;
+ }
+
+ /**
+ * Original resource name.
+ * @return SimpleUrl Current url.
+ * @access public
+ */
+ function getUrl() {
+ return $this->_url;
+ }
+
+ /**
+ * Original request data.
+ * @return mixed Sent content.
+ * @access public
+ */
+ function getRequestData() {
+ return $this->_request_data;
+ }
+
+ /**
+ * Accessor for last error.
+ * @return string Error from last response.
+ * @access public
+ */
+ function getTransportError() {
+ return $this->_transport_error;
+ }
+
+ /**
+ * Accessor for current MIME type.
+ * @return string MIME type as string; e.g. 'text/html'
+ * @access public
+ */
+ function getMimeType() {
+ if ($this->_headers) {
+ return $this->_headers->getMimeType();
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for HTTP response code.
+ * @return integer HTTP response code received.
+ * @access public
+ */
+ function getResponseCode() {
+ if ($this->_headers) {
+ return $this->_headers->getResponseCode();
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for last Authentication type. Only valid
+ * straight after a challenge (401).
+ * @return string Description of challenge type.
+ * @access public
+ */
+ function getAuthentication() {
+ if ($this->_headers) {
+ return $this->_headers->getAuthentication();
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for last Authentication realm. Only valid
+ * straight after a challenge (401).
+ * @return string Name of security realm.
+ * @access public
+ */
+ function getRealm() {
+ if ($this->_headers) {
+ return $this->_headers->getRealm();
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for current frame focus. Will be
+ * false as no frames.
+ * @return array Always empty.
+ * @access public
+ */
+ function getFrameFocus() {
+ return array();
+ }
+
+ /**
+ * Sets the focus by index. The integer index starts from 1.
+ * @param integer $choice Chosen frame.
+ * @return boolean Always false.
+ * @access public
+ */
+ function setFrameFocusByIndex($choice) {
+ return false;
+ }
+
+ /**
+ * Sets the focus by name. Always fails for a leaf page.
+ * @param string $name Chosen frame.
+ * @return boolean False as no frames.
+ * @access public
+ */
+ function setFrameFocus($name) {
+ return false;
+ }
+
+ /**
+ * Clears the frame focus. Does nothing for a leaf page.
+ * @access public
+ */
+ function clearFrameFocus() {
+ }
+
+ /**
+ * Adds a tag to the page.
+ * @param SimpleTag $tag Tag to accept.
+ * @access public
+ */
+ function acceptTag($tag) {
+ if ($tag->getTagName() == "a") {
+ $this->_addLink($tag);
+ } elseif ($tag->getTagName() == "title") {
+ $this->_setTitle($tag);
+ } elseif ($this->_isFormElement($tag->getTagName())) {
+ for ($i = 0; $i < count($this->_open_forms); $i++) {
+ $this->_open_forms[$i]->addWidget($tag);
+ }
+ }
+ }
+
+ /**
+ * Tests to see if a tag is a possible form
+ * element.
+ * @param string $name HTML element name.
+ * @return boolean True if form element.
+ * @access private
+ */
+ function _isFormElement($name) {
+ return in_array($name, array('input', 'button', 'textarea', 'select'));
+ }
+
+ /**
+ * Opens a form. New widgets go here.
+ * @param SimpleFormTag $tag Tag to accept.
+ * @access public
+ */
+ function acceptFormStart($tag) {
+ $this->_open_forms[] = new SimpleForm($tag, $this->getUrl());
+ }
+
+ /**
+ * Closes the most recently opened form.
+ * @access public
+ */
+ function acceptFormEnd() {
+ if (count($this->_open_forms)) {
+ $this->_complete_forms[] = array_pop($this->_open_forms);
+ }
+ }
+
+ /**
+ * Opens a frameset. A frameset may contain nested
+ * frameset tags.
+ * @param SimpleFramesetTag $tag Tag to accept.
+ * @access public
+ */
+ function acceptFramesetStart($tag) {
+ if (! $this->_isLoadingFrames()) {
+ $this->_frameset = $tag;
+ }
+ $this->_frameset_nesting_level++;
+ }
+
+ /**
+ * Closes the most recently opened frameset.
+ * @access public
+ */
+ function acceptFramesetEnd() {
+ if ($this->_isLoadingFrames()) {
+ $this->_frameset_nesting_level--;
+ }
+ }
+
+ /**
+ * Takes a single frame tag and stashes it in
+ * the current frame set.
+ * @param SimpleFrameTag $tag Tag to accept.
+ * @access public
+ */
+ function acceptFrame($tag) {
+ if ($this->_isLoadingFrames()) {
+ if ($tag->getAttribute('src')) {
+ $this->_frames[] = $tag;
+ }
+ }
+ }
+
+ /**
+ * Test to see if in the middle of reading
+ * a frameset.
+ * @return boolean True if inframeset.
+ * @access private
+ */
+ function _isLoadingFrames() {
+ if (! $this->_frameset) {
+ return false;
+ }
+ return ($this->_frameset_nesting_level > 0);
+ }
+
+ /**
+ * Test to see if link is an absolute one.
+ * @param string $url Url to test.
+ * @return boolean True if absolute.
+ * @access protected
+ */
+ function _linkIsAbsolute($url) {
+ $parsed = new SimpleUrl($url);
+ return (boolean)($parsed->getScheme() && $parsed->getHost());
+ }
+
+ /**
+ * Adds a link to the page.
+ * @param SimpleAnchorTag $tag Link to accept.
+ * @access protected
+ */
+ function _addLink($tag) {
+ $this->_links[] = $tag;
+ }
+
+ /**
+ * Marker for end of complete page. Any work in
+ * progress can now be closed.
+ * @access public
+ */
+ function acceptPageEnd() {
+ while (count($this->_open_forms)) {
+ $this->_complete_forms[] = array_pop($this->_open_forms);
+ }
+ }
+
+ /**
+ * Test for the presence of a frameset.
+ * @return boolean True if frameset.
+ * @access public
+ */
+ function hasFrames() {
+ return (boolean)$this->_frameset;
+ }
+
+ /**
+ * Accessor for frame name and source URL for every frame that
+ * will need to be loaded. Immediate children only.
+ * @return boolean/array False if no frameset or
+ * otherwise a hash of frame URLs.
+ * The key is either a numerical
+ * base one index or the name attribute.
+ * @access public
+ */
+ function getFrameset() {
+ if (! $this->_frameset) {
+ return false;
+ }
+ $urls = array();
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $name = $this->_frames[$i]->getAttribute('name');
+ $url = new SimpleUrl($this->_frames[$i]->getAttribute('src'));
+ $urls[$name ? $name : $i + 1] = $url->makeAbsolute($this->getUrl());
+ }
+ return $urls;
+ }
+
+ /**
+ * Fetches a list of loaded frames.
+ * @return array/string Just the URL for a single page.
+ * @access public
+ */
+ function getFrames() {
+ $url = $this->getUrl();
+ return $url->asString();
+ }
+
+ /**
+ * 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() {
+ $all = array();
+ foreach ($this->_links as $link) {
+ if ($this->_linkIsAbsolute($link->getHref())) {
+ $all[] = $link->getHref();
+ }
+ }
+ return $all;
+ }
+
+ /**
+ * Accessor for a list of all relative links.
+ * @return array List of urls without hostname.
+ * @access public
+ */
+ function getRelativeUrls() {
+ $all = array();
+ foreach ($this->_links as $link) {
+ if (! $this->_linkIsAbsolute($link->getHref())) {
+ $all[] = $link->getHref();
+ }
+ }
+ return $all;
+ }
+
+ /**
+ * 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) {
+ $matches = array();
+ foreach ($this->_links as $link) {
+ if ($link->getText() == $label) {
+ $matches[] = $this->_getUrlFromLink($link);
+ }
+ }
+ return $matches;
+ }
+
+ /**
+ * Accessor for a URL by the id attribute.
+ * @param string $id Id attribute of link.
+ * @return SimpleUrl URL with that id of false if none.
+ * @access public
+ */
+ function getUrlById($id) {
+ foreach ($this->_links as $link) {
+ if ($link->getAttribute('id') === (string)$id) {
+ return $this->_getUrlFromLink($link);
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Converts a link into a target URL.
+ * @param SimpleAnchor $link Parsed link.
+ * @return SimpleUrl URL with frame target if any.
+ * @access private
+ */
+ function _getUrlFromLink($link) {
+ $url = $this->_makeAbsolute($link->getHref());
+ if ($link->getAttribute('target')) {
+ $url->setTarget($link->getAttribute('target'));
+ }
+ return $url;
+ }
+
+ /**
+ * Expands expandomatic URLs into fully qualified
+ * URLs.
+ * @param SimpleUrl $url Relative URL.
+ * @return SimpleUrl Absolute URL.
+ * @access protected
+ */
+ function _makeAbsolute($url) {
+ if (! is_object($url)) {
+ $url = new SimpleUrl($url);
+ }
+ return $url->makeAbsolute($this->getUrl());
+ }
+
+ /**
+ * Sets the title tag contents.
+ * @param SimpleTitleTag $tag Title of page.
+ * @access protected
+ */
+ function _setTitle($tag) {
+ $this->_title = $tag;
+ }
+
+ /**
+ * Accessor for parsed title.
+ * @return string Title or false if no title is present.
+ * @access public
+ */
+ function getTitle() {
+ if ($this->_title) {
+ return $this->_title->getText();
+ }
+ return false;
+ }
+
+ /**
+ * Finds a held form by button label. Will only
+ * search correctly built forms.
+ * @param string $label Button label, default 'Submit'.
+ * @return SimpleForm Form object containing the button.
+ * @access public
+ */
+ function getFormBySubmitLabel($label) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->hasSubmitLabel($label)) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by button label. Will only
+ * search correctly built forms.
+ * @param string $name Button name attribute.
+ * @return SimpleForm Form object containing the button.
+ * @access public
+ */
+ function getFormBySubmitName($name) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->hasSubmitName($name)) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by button id. Will only
+ * search correctly built forms.
+ * @param string $id Button ID attribute.
+ * @return SimpleForm Form object containing the button.
+ * @access public
+ */
+ function getFormBySubmitId($id) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->hasSubmitId($id)) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by image label. Will only
+ * search correctly built forms.
+ * @param string $label Usually the alt attribute.
+ * @return SimpleForm Form object containing the image.
+ * @access public
+ */
+ function getFormByImageLabel($label) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->hasImageLabel($label)) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by image button id. Will only
+ * search correctly built forms.
+ * @param string $name Image name.
+ * @return SimpleForm Form object containing the image.
+ * @access public
+ */
+ function getFormByImageName($name) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->hasImageName($name)) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by image button id. Will only
+ * search correctly built forms.
+ * @param string $id Image ID attribute.
+ * @return SimpleForm Form object containing the image.
+ * @access public
+ */
+ function getFormByImageId($id) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->hasImageId($id)) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by the form ID. A way of
+ * identifying a specific form when we have control
+ * of the HTML code.
+ * @param string $id Form label.
+ * @return SimpleForm Form object containing the matching ID.
+ * @access public
+ */
+ function getFormById($id) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->getId() == $id) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * 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) {
+ $is_set = false;
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->setField($name, $value)) {
+ $is_set = true;
+ }
+ }
+ return $is_set;
+ }
+
+ /**
+ * 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) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->setFieldById($id, $value)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for a form element value within a page.
+ * Finds the first match.
+ * @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) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ $value = $this->_complete_forms[$i]->getValue($name);
+ if (isset($value)) {
+ return $value;
+ }
+ }
+ 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
+ */
+ function getFieldById($id) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ $value = $this->_complete_forms[$i]->getValueById($id);
+ if (isset($value)) {
+ return $value;
+ }
+ }
+ return null;
+ }
+ }
+?>
diff --git a/tests/UnitTests/simpletest/parser.php b/tests/UnitTests/simpletest/parser.php
new file mode 100644
index 00000000..cb9a3e75
--- /dev/null
+++ b/tests/UnitTests/simpletest/parser.php
@@ -0,0 +1,750 @@
+_case = $case;
+ $this->_patterns = array();
+ $this->_labels = array();
+ $this->_regex = null;
+ }
+
+ /**
+ * Adds a pattern with an optional label.
+ * @param string $pattern Perl style regex, but ( and )
+ * lose the usual meaning.
+ * @param string $label Label of regex to be returned
+ * on a match.
+ * @access public
+ */
+ function addPattern($pattern, $label = true) {
+ $count = count($this->_patterns);
+ $this->_patterns[$count] = $pattern;
+ $this->_labels[$count] = $label;
+ $this->_regex = null;
+ }
+
+ /**
+ * Attempts to match all patterns at once against
+ * a string.
+ * @param string $subject String to match against.
+ * @param string $match First matched portion of
+ * subject.
+ * @return boolean True on success.
+ * @access public
+ */
+ function match($subject, $match) {
+ if (count($this->_patterns) == 0) {
+ return false;
+ }
+ if (! preg_match($this->_getCompoundedRegex(), $subject, $matches)) {
+ $match = '';
+ return false;
+ }
+ $match = $matches[0];
+ for ($i = 1; $i < count($matches); $i++) {
+ if ($matches[$i]) {
+ return $this->_labels[$i - 1];
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Compounds the patterns into a single
+ * regular expression separated with the
+ * "or" operator. Caches the regex.
+ * Will automatically escape (, ) and / tokens.
+ * @param array $patterns List of patterns in order.
+ * @access private
+ */
+ function _getCompoundedRegex() {
+ if ($this->_regex == null) {
+ for ($i = 0, $count = count($this->_patterns); $i < $count; $i++) {
+ $this->_patterns[$i] = '(' . str_replace(
+ array('/', '(', ')'),
+ array('\/', '\(', '\)'),
+ $this->_patterns[$i]) . ')';
+ }
+ $this->_regex = "/" . implode("|", $this->_patterns) . "/" . $this->_getPerlMatchingFlags();
+ }
+ return $this->_regex;
+ }
+
+ /**
+ * Accessor for perl regex mode flags to use.
+ * @return string Perl regex flags.
+ * @access private
+ */
+ function _getPerlMatchingFlags() {
+ return ($this->_case ? "msS" : "msSi");
+ }
+ }
+
+ /**
+ * States for a stack machine.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleStateStack {
+ protected $_stack;
+
+ /**
+ * Constructor. Starts in named state.
+ * @param string $start Starting state name.
+ * @access public
+ */
+ function SimpleStateStack($start) {
+ $this->_stack = array($start);
+ }
+
+ /**
+ * Accessor for current state.
+ * @return string State.
+ * @access public
+ */
+ function getCurrent() {
+ return $this->_stack[count($this->_stack) - 1];
+ }
+
+ /**
+ * Adds a state to the stack and sets it
+ * to be the current state.
+ * @param string $state New state.
+ * @access public
+ */
+ function enter($state) {
+ array_push($this->_stack, $state);
+ }
+
+ /**
+ * Leaves the current state and reverts
+ * to the previous one.
+ * @return boolean False if we drop off
+ * the bottom of the list.
+ * @access public
+ */
+ function leave() {
+ if (count($this->_stack) == 1) {
+ return false;
+ }
+ array_pop($this->_stack);
+ return true;
+ }
+ }
+
+ /**
+ * Accepts text and breaks it into tokens.
+ * Some optimisation to make the sure the
+ * content is only scanned by the PHP regex
+ * parser once. Lexer modes must not start
+ * with leading underscores.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleLexer {
+ protected $_regexes;
+ protected $_parser;
+ protected $_mode;
+ protected $_mode_handlers;
+ protected $_case;
+
+ /**
+ * Sets up the lexer in case insensitive matching
+ * by default.
+ * @param SimpleSaxParser $parser Handling strategy by
+ * reference.
+ * @param string $start Starting handler.
+ * @param boolean $case True for case sensitive.
+ * @access public
+ */
+ function SimpleLexer($parser, $start = "accept", $case = false) {
+ $this->_case = $case;
+ $this->_regexes = array();
+ $this->_parser = $parser;
+ $this->_mode = new SimpleStateStack($start);
+ $this->_mode_handlers = array($start => $start);
+ }
+
+ /**
+ * Adds a token search pattern for a particular
+ * parsing mode. The pattern does not change the
+ * current mode.
+ * @param string $pattern Perl style regex, but ( and )
+ * lose the usual meaning.
+ * @param string $mode Should only apply this
+ * pattern when dealing with
+ * this type of input.
+ * @access public
+ */
+ function addPattern($pattern, $mode = "accept") {
+ if (! isset($this->_regexes[$mode])) {
+ $this->_regexes[$mode] = new ParallelRegex($this->_case);
+ }
+ $this->_regexes[$mode]->addPattern($pattern);
+ if (! isset($this->_mode_handlers[$mode])) {
+ $this->_mode_handlers[$mode] = $mode;
+ }
+ }
+
+ /**
+ * Adds a pattern that will enter a new parsing
+ * mode. Useful for entering parenthesis, strings,
+ * tags, etc.
+ * @param string $pattern Perl style regex, but ( and )
+ * lose the usual meaning.
+ * @param string $mode Should only apply this
+ * pattern when dealing with
+ * this type of input.
+ * @param string $new_mode Change parsing to this new
+ * nested mode.
+ * @access public
+ */
+ function addEntryPattern($pattern, $mode, $new_mode) {
+ if (! isset($this->_regexes[$mode])) {
+ $this->_regexes[$mode] = new ParallelRegex($this->_case);
+ }
+ $this->_regexes[$mode]->addPattern($pattern, $new_mode);
+ if (! isset($this->_mode_handlers[$new_mode])) {
+ $this->_mode_handlers[$new_mode] = $new_mode;
+ }
+ }
+
+ /**
+ * Adds a pattern that will exit the current mode
+ * and re-enter the previous one.
+ * @param string $pattern Perl style regex, but ( and )
+ * lose the usual meaning.
+ * @param string $mode Mode to leave.
+ * @access public
+ */
+ function addExitPattern($pattern, $mode) {
+ if (! isset($this->_regexes[$mode])) {
+ $this->_regexes[$mode] = new ParallelRegex($this->_case);
+ }
+ $this->_regexes[$mode]->addPattern($pattern, "__exit");
+ if (! isset($this->_mode_handlers[$mode])) {
+ $this->_mode_handlers[$mode] = $mode;
+ }
+ }
+
+ /**
+ * Adds a pattern that has a special mode. Acts as an entry
+ * and exit pattern in one go, effectively calling a special
+ * parser handler for this token only.
+ * @param string $pattern Perl style regex, but ( and )
+ * lose the usual meaning.
+ * @param string $mode Should only apply this
+ * pattern when dealing with
+ * this type of input.
+ * @param string $special Use this mode for this one token.
+ * @access public
+ */
+ function addSpecialPattern($pattern, $mode, $special) {
+ if (! isset($this->_regexes[$mode])) {
+ $this->_regexes[$mode] = new ParallelRegex($this->_case);
+ }
+ $this->_regexes[$mode]->addPattern($pattern, "_$special");
+ if (! isset($this->_mode_handlers[$special])) {
+ $this->_mode_handlers[$special] = $special;
+ }
+ }
+
+ /**
+ * Adds a mapping from a mode to another handler.
+ * @param string $mode Mode to be remapped.
+ * @param string $handler New target handler.
+ * @access public
+ */
+ function mapHandler($mode, $handler) {
+ $this->_mode_handlers[$mode] = $handler;
+ }
+
+ /**
+ * Splits the page text into tokens. Will fail
+ * if the handlers report an error or if no
+ * content is consumed. If successful then each
+ * unparsed and parsed token invokes a call to the
+ * held listener.
+ * @param string $raw Raw HTML text.
+ * @return boolean True on success, else false.
+ * @access public
+ */
+ function parse($raw) {
+ if (! isset($this->_parser)) {
+ return false;
+ }
+ $length = strlen($raw);
+ while (is_array($parsed = $this->_reduce($raw))) {
+ list($raw, $unmatched, $matched, $mode) = $parsed;
+ if (! $this->_dispatchTokens($unmatched, $matched, $mode)) {
+ return false;
+ }
+ if ($raw === '') {
+ return true;
+ }
+ if (strlen($raw) == $length) {
+ return false;
+ }
+ $length = strlen($raw);
+ }
+ if (! $parsed) {
+ return false;
+ }
+ return $this->_invokeParser($raw, LEXER_UNMATCHED);
+ }
+
+ /**
+ * Sends the matched token and any leading unmatched
+ * text to the parser changing the lexer to a new
+ * mode if one is listed.
+ * @param string $unmatched Unmatched leading portion.
+ * @param string $matched Actual token match.
+ * @param string $mode Mode after match. A boolean
+ * false mode causes no change.
+ * @return boolean False if there was any error
+ * from the parser.
+ * @access private
+ */
+ function _dispatchTokens($unmatched, $matched, $mode = false) {
+ if (! $this->_invokeParser($unmatched, LEXER_UNMATCHED)) {
+ return false;
+ }
+ if (is_bool($mode)) {
+ return $this->_invokeParser($matched, LEXER_MATCHED);
+ }
+ if ($this->_isModeEnd($mode)) {
+ if (! $this->_invokeParser($matched, LEXER_EXIT)) {
+ return false;
+ }
+ return $this->_mode->leave();
+ }
+ if ($this->_isSpecialMode($mode)) {
+ $this->_mode->enter($this->_decodeSpecial($mode));
+ if (! $this->_invokeParser($matched, LEXER_SPECIAL)) {
+ return false;
+ }
+ return $this->_mode->leave();
+ }
+ $this->_mode->enter($mode);
+ return $this->_invokeParser($matched, LEXER_ENTER);
+ }
+
+ /**
+ * Tests to see if the new mode is actually to leave
+ * the current mode and pop an item from the matching
+ * mode stack.
+ * @param string $mode Mode to test.
+ * @return boolean True if this is the exit mode.
+ * @access private
+ */
+ function _isModeEnd($mode) {
+ return ($mode === "__exit");
+ }
+
+ /**
+ * Test to see if the mode is one where this mode
+ * is entered for this token only and automatically
+ * leaves immediately afterwoods.
+ * @param string $mode Mode to test.
+ * @return boolean True if this is the exit mode.
+ * @access private
+ */
+ function _isSpecialMode($mode) {
+ return (strncmp($mode, "_", 1) == 0);
+ }
+
+ /**
+ * Strips the magic underscore marking single token
+ * modes.
+ * @param string $mode Mode to decode.
+ * @return string Underlying mode name.
+ * @access private
+ */
+ function _decodeSpecial($mode) {
+ return substr($mode, 1);
+ }
+
+ /**
+ * Calls the parser method named after the current
+ * mode. Empty content will be ignored. The lexer
+ * has a parser handler for each mode in the lexer.
+ * @param string $content Text parsed.
+ * @param boolean $is_match Token is recognised rather
+ * than unparsed data.
+ * @access private
+ */
+ function _invokeParser($content, $is_match) {
+ if (($content === '') || ($content === false)) {
+ return true;
+ }
+ $handler = $this->_mode_handlers[$this->_mode->getCurrent()];
+ return $this->_parser->$handler($content, $is_match);
+ }
+
+ /**
+ * Tries to match a chunk of text and if successful
+ * removes the recognised chunk and any leading
+ * unparsed data. Empty strings will not be matched.
+ * @param string $raw The subject to parse. This is the
+ * content that will be eaten.
+ * @return array/boolean Three item list of unparsed
+ * content followed by the
+ * recognised token and finally the
+ * action the parser is to take.
+ * True if no match, false if there
+ * is a parsing error.
+ * @access private
+ */
+ function _reduce($raw) {
+ if ($action = $this->_regexes[$this->_mode->getCurrent()]->match($raw, $match)) {
+ $unparsed_character_count = strpos($raw, $match);
+ $unparsed = substr($raw, 0, $unparsed_character_count);
+ $raw = substr($raw, $unparsed_character_count + strlen($match));
+ return array($raw, $unparsed, $match, $action);
+ }
+ return true;
+ }
+ }
+
+ /**
+ * Converts HTML tokens into selected SAX events.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleSaxParser {
+ protected $_lexer;
+ protected $_listener;
+ protected $_tag;
+ protected $_attributes;
+ protected $_current_attribute;
+
+ /**
+ * Sets the listener.
+ * @param SimpleSaxListener $listener SAX event handler.
+ * @access public
+ */
+ function SimpleSaxParser($listener) {
+ $this->_listener = $listener;
+ $this->_lexer = $this->createLexer($this);
+ $this->_tag = '';
+ $this->_attributes = array();
+ $this->_current_attribute = '';
+ }
+
+ /**
+ * Runs the content through the lexer which
+ * should call back to the acceptors.
+ * @param string $raw Page text to parse.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function parse($raw) {
+ return $this->_lexer->parse($raw);
+ }
+
+ /**
+ * Sets up the matching lexer. Starts in 'text' mode.
+ * @param SimpleSaxParser $parser Event generator, usually $self.
+ * @return SimpleLexer Lexer suitable for this parser.
+ * @access public
+ * @static
+ */
+ function createLexer($parser) {
+ $lexer = new SimpleLexer($parser, 'text');
+ $lexer->mapHandler('text', 'acceptTextToken');
+ SimpleSaxParser::_addSkipping($lexer);
+ foreach (SimpleSaxParser::_getParsedTags() as $tag) {
+ SimpleSaxParser::_addTag($lexer, $tag);
+ }
+ SimpleSaxParser::_addInTagTokens($lexer);
+ return $lexer;
+ }
+
+ /**
+ * List of parsed tags. Others are ignored.
+ * @return array List of searched for tags.
+ * @access private
+ */
+ function _getParsedTags() {
+ return array('a', 'title', 'form', 'input', 'button', 'textarea', 'select',
+ 'option', 'frameset', 'frame');
+ }
+
+ /**
+ * The lexer has to skip certain sections such
+ * as server code, client code and styles.
+ * @param SimpleLexer $lexer Lexer to add patterns to.
+ * @access private
+ * @static
+ */
+ function _addSkipping($lexer) {
+ $lexer->mapHandler('css', 'ignore');
+ $lexer->addEntryPattern('', 'css');
+ $lexer->mapHandler('js', 'ignore');
+ $lexer->addEntryPattern('', 'js');
+ $lexer->mapHandler('comment', 'ignore');
+ $lexer->addEntryPattern('', 'comment');
+ }
+
+ /**
+ * Pattern matches to start and end a tag.
+ * @param SimpleLexer $lexer Lexer to add patterns to.
+ * @param string $tag Name of tag to scan for.
+ * @access private
+ * @static
+ */
+ function _addTag($lexer, $tag) {
+ $lexer->addSpecialPattern("$tag>", 'text', 'acceptEndToken');
+ $lexer->addEntryPattern("<$tag", 'text', 'tag');
+ }
+
+ /**
+ * Pattern matches to parse the inside of a tag
+ * including the attributes and their quoting.
+ * @param SimpleLexer $lexer Lexer to add patterns to.
+ * @access private
+ * @static
+ */
+ function _addInTagTokens($lexer) {
+ $lexer->mapHandler('tag', 'acceptStartToken');
+ $lexer->addSpecialPattern('\s+', 'tag', 'ignore');
+ SimpleSaxParser::_addAttributeTokens($lexer);
+ $lexer->addExitPattern('>', 'tag');
+ }
+
+ /**
+ * Matches attributes that are either single quoted,
+ * double quoted or unquoted.
+ * @param SimpleLexer $lexer Lexer to add patterns to.
+ * @access private
+ * @static
+ */
+ function _addAttributeTokens($lexer) {
+ $lexer->mapHandler('dq_attribute', 'acceptAttributeToken');
+ $lexer->addEntryPattern('=\s*"', 'tag', 'dq_attribute');
+ $lexer->addPattern("\\\\\"", 'dq_attribute');
+ $lexer->addExitPattern('"', 'dq_attribute');
+ $lexer->mapHandler('sq_attribute', 'acceptAttributeToken');
+ $lexer->addEntryPattern("=\s*'", 'tag', 'sq_attribute');
+ $lexer->addPattern("\\\\'", 'sq_attribute');
+ $lexer->addExitPattern("'", 'sq_attribute');
+ $lexer->mapHandler('uq_attribute', 'acceptAttributeToken');
+ $lexer->addSpecialPattern('=\s*[^>\s]*', 'tag', 'uq_attribute');
+ }
+
+ /**
+ * Accepts a token from the tag mode. If the
+ * starting element completes then the element
+ * is dispatched and the current attributes
+ * set back to empty. The element or attribute
+ * name is converted to lower case.
+ * @param string $token Incoming characters.
+ * @param integer $event Lexer event type.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function acceptStartToken($token, $event) {
+ if ($event == LEXER_ENTER) {
+ $this->_tag = strtolower(substr($token, 1));
+ return true;
+ }
+ if ($event == LEXER_EXIT) {
+ $success = $this->_listener->startElement(
+ $this->_tag,
+ $this->_attributes);
+ $this->_tag = "";
+ $this->_attributes = array();
+ return $success;
+ }
+ if ($token != "=") {
+ $this->_current_attribute = strtolower(SimpleSaxParser::decodeHtml($token));
+ $this->_attributes[$this->_current_attribute] = "";
+ }
+ return true;
+ }
+
+ /**
+ * Accepts a token from the end tag mode.
+ * The element name is converted to lower case.
+ * @param string $token Incoming characters.
+ * @param integer $event Lexer event type.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function acceptEndToken($token, $event) {
+ if (! preg_match('/<\/(.*)>/', $token, $matches)) {
+ return false;
+ }
+ return $this->_listener->endElement(strtolower($matches[1]));
+ }
+
+ /**
+ * Part of the tag data.
+ * @param string $token Incoming characters.
+ * @param integer $event Lexer event type.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function acceptAttributeToken($token, $event) {
+ if ($event == LEXER_UNMATCHED) {
+ $this->_attributes[$this->_current_attribute] .=
+ SimpleSaxParser::decodeHtml($token);
+ }
+ if ($event == LEXER_SPECIAL) {
+ $this->_attributes[$this->_current_attribute] .=
+ preg_replace('/^=\s*/' , '', SimpleSaxParser::decodeHtml($token));
+ }
+ return true;
+ }
+
+ /**
+ * A character entity.
+ * @param string $token Incoming characters.
+ * @param integer $event Lexer event type.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function acceptEntityToken($token, $event) {
+ }
+
+ /**
+ * Character data between tags regarded as
+ * important.
+ * @param string $token Incoming characters.
+ * @param integer $event Lexer event type.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function acceptTextToken($token, $event) {
+ return $this->_listener->addContent($token);
+ }
+
+ /**
+ * Incoming data to be ignored.
+ * @param string $token Incoming characters.
+ * @param integer $event Lexer event type.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function ignore($token, $event) {
+ return true;
+ }
+
+ /**
+ * Decodes any HTML entities.
+ * @param string $html Incoming HTML.
+ * @return string Outgoing plain text.
+ * @access public
+ * @static
+ */
+ function decodeHtml($html) {
+ static $translations;
+ if (! isset($translations)) {
+ $translations = array_flip(get_html_translation_table(HTML_ENTITIES));
+ }
+ return strtr($html, $translations);
+ }
+
+ /**
+ * Turns HTML into text browser visible text. Images
+ * are converted to their alt text and tags are supressed.
+ * Entities are converted to their visible representation.
+ * @param string $html HTML to convert.
+ * @return string Plain text.
+ * @access public
+ * @static
+ */
+ function normalise($html) {
+ $text = preg_replace('||', ' \1 ', $html);
+ $text = preg_replace('||', ' \1 ', $text);
+ $text = preg_replace('||', ' \1 ', $text);
+ $text = preg_replace('|<.*?>|', '', $text);
+ $text = SimpleSaxParser::decodeHtml($text);
+ $text = preg_replace('|\s+|', ' ', $text);
+ return trim($text);
+ }
+ }
+
+ /**
+ * SAX event handler.
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @abstract
+ */
+ class SimpleSaxListener {
+
+ /**
+ * Sets the document to write to.
+ * @access public
+ */
+ function SimpleSaxListener() {
+ }
+
+ /**
+ * Start of element event.
+ * @param string $name Element name.
+ * @param hash $attributes Name value pairs.
+ * Attributes without content
+ * are marked as true.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function startElement($name, $attributes) {
+ }
+
+ /**
+ * End of element event.
+ * @param string $name Element name.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function endElement($name) {
+ }
+
+ /**
+ * Unparsed, but relevant data.
+ * @param string $text May include unparsed tags.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function addContent($text) {
+ }
+ }
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/remote.php b/tests/UnitTests/simpletest/remote.php
new file mode 100644
index 00000000..2639ba8c
--- /dev/null
+++ b/tests/UnitTests/simpletest/remote.php
@@ -0,0 +1,115 @@
+_url = $url;
+ $this->_dry_url = $dry_url ? $dry_url : $url;
+ $this->_size = false;
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->_url;
+ }
+
+ /**
+ * 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);
+ if (! $xml) {
+ trigger_error('Cannot read remote test URL [' . $this->_url . ']');
+ return false;
+ }
+ $parser = $this->_createParser($reporter);
+ if (! $parser->parse($xml)) {
+ trigger_error('Cannot parse incoming XML from [' . $this->_url . ']');
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Creates a new web browser object for fetching
+ * the XML report.
+ * @return SimpleBrowser New browser.
+ * @access protected
+ */
+ function _createBrowser() {
+ return new SimpleBrowser();
+ }
+
+ /**
+ * 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
+ */
+ function getSize() {
+ if ($this->_size === false) {
+ $browser = $this->_createBrowser();
+ $xml = $browser->get($this->_dry_url);
+ if (! $xml) {
+ trigger_error('Cannot read remote test URL [' . $this->_dry_url . ']');
+ return false;
+ }
+ $reporter = new SimpleReporter();
+ $parser = $this->_createParser($reporter);
+ if (! $parser->parse($xml)) {
+ trigger_error('Cannot parse incoming XML from [' . $this->_dry_url . ']');
+ return false;
+ }
+ $this->_size = $reporter->getTestCaseCount();
+ }
+ return $this->_size;
+ }
+ }
+?>
\ No newline at end of file
diff --git a/tests/UnitTests/simpletest/reporter.php b/tests/UnitTests/simpletest/reporter.php
new file mode 100644
index 00000000..8abb18fc
--- /dev/null
+++ b/tests/UnitTests/simpletest/reporter.php
@@ -0,0 +1,241 @@
+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
+ */
+ function paintHeader($test_name) {
+ $this->sendNoCacheHeaders();
+ print "\n\n$test_name\n";
+ print "\n";
+ print "\n";
+ print "\n\n";
+ print "
$test_name
\n";
+ 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
+ */
+ function sendNoCacheHeaders() {
+ if (! headers_sent()) {
+ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
+ header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
+ header("Cache-Control: no-store, no-cache, must-revalidate");
+ header("Cache-Control: post-check=0, pre-check=0", false);
+ header("Pragma: no-cache");
+ }
+ }
+
+ /**
+ * 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
+ */
+ function paintFooter($test_name) {
+ $colour = ($this->getFailCount() + $this->getExceptionCount() > 0 ? "red" : "green");
+ print "