summaryrefslogtreecommitdiffstats
path: root/3rdparty/simpletest
diff options
context:
space:
mode:
authorRobin Appelman <icewind@owncloud.com>2012-02-16 09:44:49 +0100
committerRobin Appelman <icewind@owncloud.com>2012-02-16 09:44:49 +0100
commit20553c1afe035b2e020409fd516d0288b748dc7f (patch)
tree9b7cc32ee2560d86315339b9716c1a790a680afc /3rdparty/simpletest
parent19827b8b35de6192d54bf7600e9e29800c93b21b (diff)
downloadnextcloud-server-20553c1afe035b2e020409fd516d0288b748dc7f.tar.gz
nextcloud-server-20553c1afe035b2e020409fd516d0288b748dc7f.zip
Revert "remove the 3rdparty files. everything is now in https://gitorious.org/owncloud/3rdparty"
This reverts commit dccdeca2581f705c69eb4266aa646173f588a9de.
Diffstat (limited to '3rdparty/simpletest')
-rwxr-xr-x3rdparty/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE399
-rwxr-xr-x3rdparty/simpletest/LICENSE502
-rwxr-xr-x3rdparty/simpletest/README102
-rwxr-xr-x3rdparty/simpletest/VERSION1
-rwxr-xr-x3rdparty/simpletest/arguments.php224
-rw-r--r--3rdparty/simpletest/authentication.php237
-rw-r--r--3rdparty/simpletest/autorun.php101
-rw-r--r--3rdparty/simpletest/browser.php1144
-rw-r--r--3rdparty/simpletest/collector.php122
-rwxr-xr-x3rdparty/simpletest/compatibility.php166
-rw-r--r--3rdparty/simpletest/cookies.php380
-rw-r--r--3rdparty/simpletest/default_reporter.php163
-rwxr-xr-x3rdparty/simpletest/detached.php96
-rw-r--r--3rdparty/simpletest/docs/en/authentication_documentation.html378
-rw-r--r--3rdparty/simpletest/docs/en/browser_documentation.html501
-rwxr-xr-x3rdparty/simpletest/docs/en/docs.css121
-rw-r--r--3rdparty/simpletest/docs/en/expectation_documentation.html476
-rw-r--r--3rdparty/simpletest/docs/en/form_testing_documentation.html351
-rw-r--r--3rdparty/simpletest/docs/en/group_test_documentation.html252
-rw-r--r--3rdparty/simpletest/docs/en/index.html542
-rw-r--r--3rdparty/simpletest/docs/en/mock_objects_documentation.html870
-rw-r--r--3rdparty/simpletest/docs/en/overview.html487
-rw-r--r--3rdparty/simpletest/docs/en/partial_mocks_documentation.html457
-rw-r--r--3rdparty/simpletest/docs/en/reporter_documentation.html616
-rw-r--r--3rdparty/simpletest/docs/en/unit_test_documentation.html442
-rw-r--r--3rdparty/simpletest/docs/en/web_tester_documentation.html588
-rw-r--r--3rdparty/simpletest/docs/fr/authentication_documentation.html372
-rw-r--r--3rdparty/simpletest/docs/fr/browser_documentation.html500
-rwxr-xr-x3rdparty/simpletest/docs/fr/docs.css84
-rw-r--r--3rdparty/simpletest/docs/fr/expectation_documentation.html451
-rw-r--r--3rdparty/simpletest/docs/fr/form_testing_documentation.html363
-rw-r--r--3rdparty/simpletest/docs/fr/group_test_documentation.html265
-rw-r--r--3rdparty/simpletest/docs/fr/index.html576
-rw-r--r--3rdparty/simpletest/docs/fr/mock_objects_documentation.html933
-rw-r--r--3rdparty/simpletest/docs/fr/overview.html321
-rw-r--r--3rdparty/simpletest/docs/fr/partial_mocks_documentation.html475
-rw-r--r--3rdparty/simpletest/docs/fr/reporter_documentation.html630
-rw-r--r--3rdparty/simpletest/docs/fr/unit_test_documentation.html447
-rw-r--r--3rdparty/simpletest/docs/fr/web_tester_documentation.html570
-rwxr-xr-x3rdparty/simpletest/dumper.php407
-rw-r--r--3rdparty/simpletest/eclipse.php307
-rw-r--r--3rdparty/simpletest/encoding.php649
-rw-r--r--3rdparty/simpletest/errors.php267
-rwxr-xr-x3rdparty/simpletest/exceptions.php226
-rwxr-xr-x3rdparty/simpletest/expectation.php984
-rwxr-xr-x3rdparty/simpletest/extensions/pear_test_case.php196
-rwxr-xr-x3rdparty/simpletest/extensions/testdox.php53
-rwxr-xr-x3rdparty/simpletest/extensions/testdox/test.php107
-rw-r--r--3rdparty/simpletest/form.php361
-rwxr-xr-x3rdparty/simpletest/frames.php592
-rw-r--r--3rdparty/simpletest/http.php628
-rwxr-xr-x3rdparty/simpletest/invoker.php139
-rwxr-xr-x3rdparty/simpletest/mock_objects.php1641
-rwxr-xr-x3rdparty/simpletest/page.php542
-rwxr-xr-x3rdparty/simpletest/php_parser.php1054
-rw-r--r--3rdparty/simpletest/recorder.php101
-rw-r--r--3rdparty/simpletest/reflection_php4.php136
-rw-r--r--3rdparty/simpletest/reflection_php5.php386
-rw-r--r--3rdparty/simpletest/remote.php115
-rwxr-xr-x3rdparty/simpletest/reporter.php445
-rw-r--r--3rdparty/simpletest/scorer.php875
-rwxr-xr-x3rdparty/simpletest/selector.php141
-rw-r--r--3rdparty/simpletest/shell_tester.php330
-rw-r--r--3rdparty/simpletest/simpletest.php391
-rwxr-xr-x3rdparty/simpletest/socket.php312
-rw-r--r--3rdparty/simpletest/tag.php1527
-rw-r--r--3rdparty/simpletest/test/acceptance_test.php1729
-rwxr-xr-x3rdparty/simpletest/test/adapter_test.php50
-rwxr-xr-x3rdparty/simpletest/test/all_tests.php13
-rwxr-xr-x3rdparty/simpletest/test/arguments_test.php82
-rwxr-xr-x3rdparty/simpletest/test/authentication_test.php145
-rwxr-xr-x3rdparty/simpletest/test/autorun_test.php23
-rwxr-xr-x3rdparty/simpletest/test/bad_test_suite.php10
-rwxr-xr-x3rdparty/simpletest/test/browser_test.php802
-rwxr-xr-x3rdparty/simpletest/test/collector_test.php50
-rwxr-xr-x3rdparty/simpletest/test/command_line_test.php40
-rwxr-xr-x3rdparty/simpletest/test/compatibility_test.php87
-rwxr-xr-x3rdparty/simpletest/test/cookies_test.php227
-rwxr-xr-x3rdparty/simpletest/test/detached_test.php15
-rwxr-xr-x3rdparty/simpletest/test/dumper_test.php88
-rwxr-xr-x3rdparty/simpletest/test/eclipse_test.php32
-rwxr-xr-x3rdparty/simpletest/test/encoding_test.php240
-rwxr-xr-x3rdparty/simpletest/test/errors_test.php229
-rwxr-xr-x3rdparty/simpletest/test/exceptions_test.php183
-rwxr-xr-x3rdparty/simpletest/test/expectation_test.php317
-rwxr-xr-x3rdparty/simpletest/test/form_test.php344
-rwxr-xr-x3rdparty/simpletest/test/frames_test.php549
-rwxr-xr-x3rdparty/simpletest/test/http_test.php492
-rwxr-xr-x3rdparty/simpletest/test/interfaces_test.php137
-rwxr-xr-x3rdparty/simpletest/test/interfaces_test_php5_1.php14
-rwxr-xr-x3rdparty/simpletest/test/live_test.php47
-rwxr-xr-x3rdparty/simpletest/test/mock_objects_test.php985
-rwxr-xr-x3rdparty/simpletest/test/page_test.php166
-rwxr-xr-x3rdparty/simpletest/test/parse_error_test.php9
-rwxr-xr-x3rdparty/simpletest/test/parsing_test.php642
-rwxr-xr-x3rdparty/simpletest/test/php_parser_test.php489
-rwxr-xr-x3rdparty/simpletest/test/recorder_test.php23
-rwxr-xr-x3rdparty/simpletest/test/reflection_php5_test.php263
-rwxr-xr-x3rdparty/simpletest/test/remote_test.php19
-rwxr-xr-x3rdparty/simpletest/test/shell_test.php38
-rwxr-xr-x3rdparty/simpletest/test/shell_tester_test.php42
-rwxr-xr-x3rdparty/simpletest/test/simpletest_test.php58
-rwxr-xr-x3rdparty/simpletest/test/site/file.html6
-rwxr-xr-x3rdparty/simpletest/test/socket_test.php25
-rwxr-xr-x3rdparty/simpletest/test/support/collector/collectable.10
-rwxr-xr-x3rdparty/simpletest/test/support/collector/collectable.20
-rwxr-xr-x3rdparty/simpletest/test/support/empty_test_file.php3
-rwxr-xr-x3rdparty/simpletest/test/support/failing_test.php9
-rwxr-xr-x3rdparty/simpletest/test/support/latin1_sample1
-rwxr-xr-x3rdparty/simpletest/test/support/passing_test.php9
-rwxr-xr-x3rdparty/simpletest/test/support/recorder_sample.php14
-rwxr-xr-x3rdparty/simpletest/test/support/spl_examples.php15
-rwxr-xr-x3rdparty/simpletest/test/support/supplementary_upload_sample.txt1
-rwxr-xr-x3rdparty/simpletest/test/support/test1.php7
-rwxr-xr-x3rdparty/simpletest/test/support/upload_sample.txt1
-rwxr-xr-x3rdparty/simpletest/test/tag_test.php554
-rwxr-xr-x3rdparty/simpletest/test/test_with_parse_error.php8
-rwxr-xr-x3rdparty/simpletest/test/unit_tester_test.php61
-rwxr-xr-x3rdparty/simpletest/test/unit_tests.php49
-rwxr-xr-x3rdparty/simpletest/test/url_test.php515
-rwxr-xr-x3rdparty/simpletest/test/user_agent_test.php348
-rwxr-xr-x3rdparty/simpletest/test/visual_test.php495
-rwxr-xr-x3rdparty/simpletest/test/web_tester_test.php155
-rwxr-xr-x3rdparty/simpletest/test/xml_test.php187
-rw-r--r--3rdparty/simpletest/test_case.php658
-rwxr-xr-x3rdparty/simpletest/tidy_parser.php382
-rwxr-xr-x3rdparty/simpletest/unit_tester.php413
-rw-r--r--3rdparty/simpletest/url.php550
-rw-r--r--3rdparty/simpletest/user_agent.php328
-rw-r--r--3rdparty/simpletest/web_tester.php1532
-rwxr-xr-x3rdparty/simpletest/xml.php647
131 files changed, 44269 insertions, 0 deletions
diff --git a/3rdparty/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE b/3rdparty/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE
new file mode 100755
index 00000000000..a65e83e8762
--- /dev/null
+++ b/3rdparty/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE
@@ -0,0 +1,399 @@
+Simple Test interface changes
+=============================
+Because the SimpleTest tool set is still evolving it is likely that tests
+written with earlier versions will fail with the newest ones. The most
+dramatic changes are in the alpha releases. Here is a list of possible
+problems and their fixes...
+
+assertText() no longer finds a string inside a <script> tag
+-----------------------------------------------------------
+The assertText() method is intended to match only visible,
+human-readable text on the web page. Therefore, the contents of script
+tags should not be matched by this assertion. However there was a bug
+in the text normalisation code of simpletest which meant that <script>
+tags spanning multiple lines would not have their content stripped
+out. If you want to check the content of a <script> tag, use
+assertPattern(), or write a custom expectation.
+
+Overloaded method not working
+-----------------------------
+All protected and private methods had underscores
+removed. This means that any private/protected methods that
+you overloaded with those names need to be updated.
+
+Fatal error: Call to undefined method Classname::classname()
+------------------------------------------------------------
+SimpleTest renamed all of its constructors from
+Classname to __construct; derived classes invoking
+their parent constructors should replace parent::Classname()
+with parent::__construct().
+
+Custom CSS in HtmlReporter not being applied
+--------------------------------------------
+Batch rename of protected and private methods
+means that _getCss() was renamed to getCss().
+Please rename your method and it should work again.
+
+setReturnReference() throws errors in E_STRICT
+----------------------------------------------
+Happens when an object is passed by reference.
+This also happens with setReturnReferenceAt().
+If you want to return objects then replace these
+with calls to returns() and returnsAt() with the
+same arguments. This change was forced in the 1.1
+version for E_STRICT compatibility.
+
+assertReference() throws errors in E_STRICT
+-------------------------------------------
+Due to language restrictions you cannot compare
+both variables and objects in E_STRICT mode. Use
+assertSame() in this mode with objects. This change
+was forced the 1.1 version.
+
+Cannot create GroupTest
+-----------------------
+The GroupTest has been renamed TestSuite (see below).
+It was removed completely in 1.1 in favour of this
+name.
+
+No method getRelativeUrls() or getAbsoluteUrls()
+------------------------------------------------
+These methods were always a bit weird anyway, and
+the new parsing of the base tag makes them more so.
+They have been replaced with getUrls() instead. If
+you want the old functionality then simply chop
+off the current domain from getUrls().
+
+Method setWildcard() removed in mocks
+-------------------------------------
+Even setWildcard() has been removed in 1.0.1beta now.
+If you want to test explicitely for a '*' string, then
+simply pass in new IdenticalExpectation('*') instead.
+
+No method _getTest() on mocks
+-----------------------------
+This has finally been removed. It was a pretty esoteric
+flex point anyway. It was there to allow the mocks to
+work with other test tools, but no one does this.
+
+No method assertError(), assertNoErrors(), swallowErrors()
+----------------------------------------------------------
+These have been deprecated in 1.0.1beta in favour of
+expectError() and expectException(). assertNoErrors() is
+redundant if you use expectError() as failures are now reported
+immediately.
+
+No method TestCase::signal()
+----------------------------
+This has been deprecated in favour of triggering an error or
+throwing an exception. Deprecated as of 1.0.1beta.
+
+No method TestCase::sendMessage()
+---------------------------------
+This has been deprecated as of 1.0.1beta.
+
+Failure to connect now emits failures
+-------------------------------------
+It used to be that you would have to use the
+getTransferError() call on the web tester to see if
+there was a socket level error in a fetch. This check
+is now always carried out by the WebTestCase unless
+the fetch is prefaced with WebTestCase::ignoreErrors().
+The ignore directive only lasts for the next fetching
+action such as get() and click().
+
+No method SimpleTestOptions::ignore()
+-------------------------------------
+This is deprecated in version 1.0.1beta and has been moved
+to SimpleTest::ignore() as that is more readable. In
+addition, parent classes are also ignored automatically.
+If you are using PHP5 you can skip this directive simply
+by marking your test case as abstract.
+
+No method assertCopy()
+----------------------
+This is deprecated in 1.0.1 in favour of assertClone().
+The assertClone() method is slightly different in that
+the objects must be identical, but without being a
+reference. It is thus not a strict inversion of
+assertReference().
+
+Constructor wildcard override has no effect in mocks
+----------------------------------------------------
+As of 1.0.1beta this is now set with setWildcard() instead
+of in the constructor.
+
+No methods setStubBaseClass()/getStubBaseClass()
+------------------------------------------------
+As mocks are now used instead of stubs, these methods
+stopped working and are now removed as of the 1.0.1beta
+release. The mock objects may be freely used instead.
+
+No method addPartialMockCode()
+------------------------------
+The ability to insert arbitrary partial mock code
+has been removed. This was a low value feature
+causing needless complications. It was removed
+in the 1.0.1beta release.
+
+No method setMockBaseClass()
+----------------------------
+The ability to change the mock base class has been
+scheduled for removal and is deprecated since the
+1.0.1beta version. This was a rarely used feature
+except as a workaround for PHP5 limitations. As
+these limitations are being resolved it's hoped
+that the bundled mocks can be used directly.
+
+No class Stub
+-------------
+Server stubs are deprecated from 1.0.1 as the mocks now
+have exactly the same interface. Just use mock objects
+instead.
+
+No class SimpleTestOptions
+--------------------------
+This was replced by the shorter SimpleTest in 1.0.1beta1
+and is since deprecated.
+
+No file simple_test.php
+-----------------------
+This was renamed test_case.php in 1.0.1beta to more accurately
+reflect it's purpose. This file should never be directly
+included in test suites though, as it's part of the
+underlying mechanics and has a tendency to be refactored.
+
+No class WantedPatternExpectation
+---------------------------------
+This was deprecated in 1.0.1alpha in favour of the simpler
+name PatternExpectation.
+
+No class NoUnwantedPatternExpectation
+-------------------------------------
+This was deprecated in 1.0.1alpha in favour of the simpler
+name NoPatternExpectation.
+
+No method assertNoUnwantedPattern()
+-----------------------------------
+This has been renamed to assertNoPattern() in 1.0.1alpha and
+the old form is deprecated.
+
+No method assertWantedPattern()
+-------------------------------
+This has been renamed to assertPattern() in 1.0.1alpha and
+the old form is deprecated.
+
+No method assertExpectation()
+-----------------------------
+This was renamed as assert() in 1.0.1alpha and the old form
+has been deprecated.
+
+No class WildcardExpectation
+----------------------------
+This was a mostly internal class for the mock objects. It was
+renamed AnythingExpectation to bring it closer to JMock and
+NMock in version 1.0.1alpha.
+
+Missing UnitTestCase::assertErrorPattern()
+------------------------------------------
+This method is deprecated for version 1.0.1 onwards.
+This method has been subsumed by assertError() that can now
+take an expectation. Simply pass a PatternExpectation
+into assertError() to simulate the old behaviour.
+
+No HTML when matching page elements
+-----------------------------------
+This behaviour has been switched to using plain text as if it
+were seen by the user of the browser. This means that HTML tags
+are suppressed, entities are converted and whitespace is
+normalised. This should make it easier to match items in forms.
+Also images are replaced with their "alt" text so that they
+can be matched as well.
+
+No method SimpleRunner::_getTestCase()
+--------------------------------------
+This was made public as getTestCase() in 1.0RC2.
+
+No method restartSession()
+--------------------------
+This was renamed to restart() in the WebTestCase, SimpleBrowser
+and the underlying SimpleUserAgent in 1.0RC2. Because it was
+undocumented anyway, no attempt was made at backward
+compatibility.
+
+My custom test case ignored by tally()
+--------------------------------------
+The _assertTrue method has had it's signature changed due to a bug
+in the PHP 5.0.1 release. You must now use getTest() from within
+that method to get the test case. Mock compatibility with other
+unit testers is now deprecated as of 1.0.1alpha as PEAR::PHPUnit2
+should soon have mock support of it's own.
+
+Broken code extending SimpleRunner
+----------------------------------
+This was replaced with SimpleScorer so that I could use the runner
+name in another class. This happened in RC1 development and there
+is no easy backward compatibility fix. The solution is simply to
+extend SimpleScorer instead.
+
+Missing method getBaseCookieValue()
+-----------------------------------
+This was renamed getCurrentCookieValue() in RC1.
+
+Missing files from the SimpleTest suite
+---------------------------------------
+Versions of SimpleTest prior to Beta6 required a SIMPLE_TEST constant
+to point at the SimpleTest folder location before any of the toolset
+was loaded. This is no longer documented as it is now unnecessary
+for later versions. If you are using an earlier version you may
+need this constant. Consult the documentation that was bundled with
+the release that you are using or upgrade to Beta6 or later.
+
+No method SimpleBrowser::getCurrentUrl()
+--------------------------------------
+This is replaced with the more versatile showRequest() for
+debugging. It only existed in this context for version Beta5.
+Later versions will have SimpleBrowser::getHistory() for tracking
+paths through pages. It is renamed as getUrl() since 1.0RC1.
+
+No method Stub::setStubBaseClass()
+----------------------------------
+This method has finally been removed in 1.0RC1. Use
+SimpleTestOptions::setStubBaseClass() instead.
+
+No class CommandLineReporter
+----------------------------
+This was renamed to TextReporter in Beta3 and the deprecated version
+was removed in 1.0RC1.
+
+No method requireReturn()
+-------------------------
+This was deprecated in Beta3 and is now removed.
+
+No method expectCookie()
+------------------------
+This method was abruptly removed in Beta4 so as to simplify the internals
+until another mechanism can replace it. As a workaround it is necessary
+to assert that the cookie has changed by setting it before the page
+fetch and then assert the desired value.
+
+No method clickSubmitByFormId()
+-------------------------------
+This method had an incorrect name as no button was involved. It was
+renamed to submitByFormId() in Beta4 and the old version deprecated.
+Now removed.
+
+No method paintStart() or paintEnd()
+------------------------------------
+You should only get this error if you have subclassed the lower level
+reporting and test runner machinery. These methods have been broken
+down into events for test methods, events for test cases and events
+for group tests. The new methods are...
+
+paintStart() --> paintMethodStart(), paintCaseStart(), paintGroupStart()
+paintEnd() --> paintMethodEnd(), paintCaseEnd(), paintGroupEnd()
+
+This change was made in Beta3, ironically to make it easier to subclass
+the inner machinery. Simply duplicating the code you had in the previous
+methods should provide a temporary fix.
+
+No class TestDisplay
+--------------------
+This has been folded into SimpleReporter in Beta3 and is now deprecated.
+It was removed in RC1.
+
+No method WebTestCase::fetch()
+------------------------------
+This was renamed get() in Alpha8. It is removed in Beta3.
+
+No method submit()
+------------------
+This has been renamed clickSubmit() in Beta1. The old method was
+removed in Beta2.
+
+No method clearHistory()
+------------------------
+This method is deprecated in Beta2 and removed in RC1.
+
+No method getCallCount()
+------------------------
+This method has been deprecated since Beta1 and has now been
+removed. There are now more ways to set expectations on counts
+and so this method should be unecessery. Removed in RC1.
+
+Cannot find file *
+------------------
+The following public name changes have occoured...
+
+simple_html_test.php --> reporter.php
+simple_mock.php --> mock_objects.php
+simple_unit.php --> unit_tester.php
+simple_web.php --> web_tester.php
+
+The old names were deprecated in Alpha8 and removed in Beta1.
+
+No method attachObserver()
+--------------------------
+Prior to the Alpha8 release the old internal observer pattern was
+gutted and replaced with a visitor. This is to trade flexibility of
+test case expansion against the ease of writing user interfaces.
+
+Code such as...
+
+$test = &new MyTestCase();
+$test->attachObserver(new TestHtmlDisplay());
+$test->run();
+
+...should be rewritten as...
+
+$test = &new MyTestCase();
+$test->run(new HtmlReporter());
+
+If you previously attached multiple observers then the workaround
+is to run the tests twice, once with each, until they can be combined.
+For one observer the old method is simulated in Alpha 8, but is
+removed in Beta1.
+
+No class TestHtmlDisplay
+------------------------
+This class has been renamed to HtmlReporter in Alpha8. It is supported,
+but deprecated in Beta1 and removed in Beta2. If you have subclassed
+the display for your own design, then you will have to extend this
+class (HtmlReporter) instead.
+
+If you have accessed the event queue by overriding the notify() method
+then I am afraid you are in big trouble :(. The reporter is now
+carried around the test suite by the runner classes and the methods
+called directly. In the unlikely event that this is a problem and
+you don't want to upgrade the test tool then simplest is to write your
+own runner class and invoke the tests with...
+
+$test->accept(new MyRunner(new MyReporter()));
+
+...rather than the run method. This should be easier to extend
+anyway and gives much more control. Even this method is overhauled
+in Beta3 where the runner class can be set within the test case. Really
+the best thing to do is to upgrade to this version as whatever you were
+trying to achieve before should now be very much easier.
+
+Missing set options method
+--------------------------
+All test suite options are now in one class called SimpleTestOptions.
+This means that options are set differently...
+
+GroupTest::ignore() --> SimpleTestOptions::ignore()
+Mock::setMockBaseClass() --> SimpleTestOptions::setMockBaseClass()
+
+These changed in Alpha8 and the old versions are now removed in RC1.
+
+No method setExpected*()
+------------------------
+The mock expectations changed their names in Alpha4 and the old names
+ceased to be supported in Alpha8. The changes are...
+
+setExpectedArguments() --> expectArguments()
+setExpectedArgumentsSequence() --> expectArgumentsAt()
+setExpectedCallCount() --> expectCallCount()
+setMaximumCallCount() --> expectMaximumCallCount()
+
+The parameters remained the same.
diff --git a/3rdparty/simpletest/LICENSE b/3rdparty/simpletest/LICENSE
new file mode 100755
index 00000000000..09f465ab703
--- /dev/null
+++ b/3rdparty/simpletest/LICENSE
@@ -0,0 +1,502 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/3rdparty/simpletest/README b/3rdparty/simpletest/README
new file mode 100755
index 00000000000..40f41666d40
--- /dev/null
+++ b/3rdparty/simpletest/README
@@ -0,0 +1,102 @@
+SimpleTest
+==========
+
+You probably got this package from:
+
+ http://simpletest.org/en/download.html
+
+If there is no licence agreement with this package please download
+a version from the location above. You must read and accept that
+licence to use this software. The file is titled simply LICENSE.
+
+What is it? It's a framework for unit testing, web site testing and
+mock objects for PHP 5.0.5+.
+
+If you have used JUnit, you will find this PHP unit testing version very
+similar. Also included is a mock objects and server stubs generator.
+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 can see a release schedule at http://simpletest.org/en/overview.html
+which is also copied to the documentation folder with this release.
+A full PHPDocumenter API documentation exists at
+http://simpletest.org/api/.
+
+The user interface is minimal in the extreme, but a lot of information
+flows from the test suite. After version 1.0 we will release a better
+web UI, but we are leaving XUL and GTK versions to volunteers as
+everybody has their own opinion on a good GUI, and we don't want to
+discourage development by shipping one with the toolkit. You can
+download an Eclipse plug-in separately.
+
+The unit tests for SimpleTest itself can be run here:
+
+ test/unit_tests.php
+
+And tests involving live network connections as well are here:
+
+ test/all_tests.php
+
+The full tests will typically overrun the 8Mb limit often allowed
+to a PHP process. A workaround is to run the tests on the command
+with a custom php.ini file or with the switch -dmemory_limit=-1
+if you do not have access to your server version.
+
+The full tests read some test data from simpletest.org. If the site
+is down or has been modified for a later version then you will get
+spurious errors. A unit_tests.php failure on the other hand would be
+very serious. Please notify us if you find one.
+
+Even if all of the tests run please verify that your existing test suites
+also function as expected. The file:
+
+ HELP_MY_TESTS_DONT_WORK_ANYMORE
+
+...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://simpletest.org/en/first_test_tutorial.html
+
+...to get you started and this material will eventually become included
+with the project documentation. A French translation exists at:
+
+ http://simpletest.org/fr/first_test_tutorial.html
+
+If you download and use, and possibly even extend this tool, please let us
+know. Any feedback, even bad, is always welcome and we will work to get
+your suggestions into the next release. Ideally please send your
+comments to:
+
+ 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 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 SVN only.
+The SVN check-ins always have all the tests passing and so SVN snapshots should
+be pretty usable, although the code may not look so good internally.
+
+Oh, and one last thing: SimpleTest is called "Simple" because it should
+be simple to use. We intend to add a complete set of tools for a test
+first and "test as you code" type of development. "Simple" does not mean
+"Lite" in this context.
+
+Thanks to everyone who has sent comments and offered suggestions. They
+really are invaluable, but sadly you are too many to mention in full.
+Thanks to all on the advanced PHP forum on SitePoint, especially Harry
+Fuecks. Early adopters are always an inspiration.
+
+ -- Marcus Baker, Jason Sweat, Travis Swicegood, Perrick Penet and Edward Z. Yang.
diff --git a/3rdparty/simpletest/VERSION b/3rdparty/simpletest/VERSION
new file mode 100755
index 00000000000..9084fa2f716
--- /dev/null
+++ b/3rdparty/simpletest/VERSION
@@ -0,0 +1 @@
+1.1.0
diff --git a/3rdparty/simpletest/arguments.php b/3rdparty/simpletest/arguments.php
new file mode 100755
index 00000000000..89e7f9de6ef
--- /dev/null
+++ b/3rdparty/simpletest/arguments.php
@@ -0,0 +1,224 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: dumper.php 1909 2009-07-29 15:58:11Z dgheath $
+ */
+
+/**
+ * Parses the command line arguments.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleArguments {
+ private $all = array();
+
+ /**
+ * Parses the command line arguments. The usual formats
+ * are supported:
+ * -f value
+ * -f=value
+ * --flag=value
+ * --flag value
+ * -f (true)
+ * --flag (true)
+ * @param array $arguments Normally the PHP $argv.
+ */
+ function __construct($arguments) {
+ array_shift($arguments);
+ while (count($arguments) > 0) {
+ list($key, $value) = $this->parseArgument($arguments);
+ $this->assign($key, $value);
+ }
+ }
+
+ /**
+ * Sets the value in the argments object. If multiple
+ * values are added under the same key, the key will
+ * give an array value in the order they were added.
+ * @param string $key The variable to assign to.
+ * @param string value The value that would norally
+ * be colected on the command line.
+ */
+ function assign($key, $value) {
+ if ($this->$key === false) {
+ $this->all[$key] = $value;
+ } elseif (! is_array($this->$key)) {
+ $this->all[$key] = array($this->$key, $value);
+ } else {
+ $this->all[$key][] = $value;
+ }
+ }
+
+ /**
+ * Extracts the next key and value from the argument list.
+ * @param array $arguments The remaining arguments to be parsed.
+ * The argument list will be reduced.
+ * @return array Two item array of key and value.
+ * If no value can be found it will
+ * have the value true assigned instead.
+ */
+ private function parseArgument(&$arguments) {
+ $argument = array_shift($arguments);
+ if (preg_match('/^-(\w)=(.+)$/', $argument, $matches)) {
+ return array($matches[1], $matches[2]);
+ } elseif (preg_match('/^-(\w)$/', $argument, $matches)) {
+ return array($matches[1], $this->nextNonFlagElseTrue($arguments));
+ } elseif (preg_match('/^--(\w+)=(.+)$/', $argument, $matches)) {
+ return array($matches[1], $matches[2]);
+ } elseif (preg_match('/^--(\w+)$/', $argument, $matches)) {
+ return array($matches[1], $this->nextNonFlagElseTrue($arguments));
+ }
+ }
+
+ /**
+ * Attempts to use the next argument as a value. It
+ * won't use what it thinks is a flag.
+ * @param array $arguments Remaining arguments to be parsed.
+ * This variable is modified if there
+ * is a value to be extracted.
+ * @return string/boolean The next value unless it's a flag.
+ */
+ private function nextNonFlagElseTrue(&$arguments) {
+ return $this->valueIsNext($arguments) ? array_shift($arguments) : true;
+ }
+
+ /**
+ * Test to see if the next available argument is a valid value.
+ * If it starts with "-" or "--" it's a flag and doesn't count.
+ * @param array $arguments Remaining arguments to be parsed.
+ * Not affected by this call.
+ * boolean True if valid value.
+ */
+ function valueIsNext($arguments) {
+ return isset($arguments[0]) && ! $this->isFlag($arguments[0]);
+ }
+
+ /**
+ * It's a flag if it starts with "-" or "--".
+ * @param string $argument Value to be tested.
+ * @return boolean True if it's a flag.
+ */
+ function isFlag($argument) {
+ return strncmp($argument, '-', 1) == 0;
+ }
+
+ /**
+ * The arguments are available as individual member
+ * variables on the object.
+ * @param string $key Argument name.
+ * @return string/array/boolean Either false for no value,
+ * the value as a string or
+ * a list of multiple values if
+ * the flag had been specified more
+ * than once.
+ */
+ function __get($key) {
+ if (isset($this->all[$key])) {
+ return $this->all[$key];
+ }
+ return false;
+ }
+
+ /**
+ * The entire argument set as a hash.
+ * @return hash Each argument and it's value(s).
+ */
+ function all() {
+ return $this->all;
+ }
+}
+
+/**
+ * Renders the help for the command line arguments.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleHelp {
+ private $overview;
+ private $flag_sets = array();
+ private $explanations = array();
+
+ /**
+ * Sets up the top level explanation for the program.
+ * @param string $overview Summary of program.
+ */
+ function __construct($overview = '') {
+ $this->overview = $overview;
+ }
+
+ /**
+ * Adds the explanation for a group of flags that all
+ * have the same function.
+ * @param string/array $flags Flag and alternates. Don't
+ * worry about leading dashes
+ * as these are inserted automatically.
+ * @param string $explanation What that flag group does.
+ */
+ function explainFlag($flags, $explanation) {
+ $flags = is_array($flags) ? $flags : array($flags);
+ $this->flag_sets[] = $flags;
+ $this->explanations[] = $explanation;
+ }
+
+ /**
+ * Generates the help text.
+ * @returns string The complete formatted text.
+ */
+ function render() {
+ $tab_stop = $this->longestFlag($this->flag_sets) + 4;
+ $text = $this->overview . "\n";
+ for ($i = 0; $i < count($this->flag_sets); $i++) {
+ $text .= $this->renderFlagSet($this->flag_sets[$i], $this->explanations[$i], $tab_stop);
+ }
+ return $this->noDuplicateNewLines($text);
+ }
+
+ /**
+ * Works out the longest flag for formatting purposes.
+ * @param array $flag_sets The internal flag set list.
+ */
+ private function longestFlag($flag_sets) {
+ $longest = 0;
+ foreach ($flag_sets as $flags) {
+ foreach ($flags as $flag) {
+ $longest = max($longest, strlen($this->renderFlag($flag)));
+ }
+ }
+ return $longest;
+ }
+
+ /**
+ * Generates the text for a single flag and it's alternate flags.
+ * @returns string Help text for that flag group.
+ */
+ private function renderFlagSet($flags, $explanation, $tab_stop) {
+ $flag = array_shift($flags);
+ $text = str_pad($this->renderFlag($flag), $tab_stop, ' ') . $explanation . "\n";
+ foreach ($flags as $flag) {
+ $text .= ' ' . $this->renderFlag($flag) . "\n";
+ }
+ return $text;
+ }
+
+ /**
+ * Generates the flag name including leading dashes.
+ * @param string $flag Just the name.
+ * @returns Fag with apropriate dashes.
+ */
+ private function renderFlag($flag) {
+ return (strlen($flag) == 1 ? '-' : '--') . $flag;
+ }
+
+ /**
+ * Converts multiple new lines into a single new line.
+ * Just there to trap accidental duplicate new lines.
+ * @param string $text Text to clean up.
+ * @returns string Text with no blank lines.
+ */
+ private function noDuplicateNewLines($text) {
+ return preg_replace('/(\n+)/', "\n", $text);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/authentication.php b/3rdparty/simpletest/authentication.php
new file mode 100644
index 00000000000..fcd4efd3f0a
--- /dev/null
+++ b/3rdparty/simpletest/authentication.php
@@ -0,0 +1,237 @@
+<?php
+/**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: authentication.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+/**
+ * include http class
+ */
+require_once(dirname(__FILE__) . '/http.php');
+
+/**
+ * Represents a single security realm's identity.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleRealm {
+ private $type;
+ private $root;
+ private $username;
+ private $password;
+
+ /**
+ * Starts with the initial entry directory.
+ * @param string $type Authentication type for this
+ * realm. Only Basic authentication
+ * is currently supported.
+ * @param SimpleUrl $url Somewhere in realm.
+ * @access public
+ */
+ function SimpleRealm($type, $url) {
+ $this->type = $type;
+ $this->root = $url->getBasePath();
+ $this->username = false;
+ $this->password = false;
+ }
+
+ /**
+ * Adds another location to the realm.
+ * @param SimpleUrl $url Somewhere in realm.
+ * @access public
+ */
+ function stretch($url) {
+ $this->root = $this->getCommonPath($this->root, $url->getPath());
+ }
+
+ /**
+ * Finds the common starting path.
+ * @param string $first Path to compare.
+ * @param string $second Path to compare.
+ * @return string Common directories.
+ * @access private
+ */
+ protected 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) {
+ if ($this->isIn($this->root, $url->getBasePath())) {
+ return true;
+ }
+ if ($this->isIn($this->root, $url->getBasePath() . $url->getPage() . '/')) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Tests to see if one string is a substring of
+ * another.
+ * @param string $part Small bit.
+ * @param string $whole Big bit.
+ * @return boolean True if the small bit is
+ * in the big bit.
+ * @access private
+ */
+ protected function isIn($part, $whole) {
+ return strpos($whole, $part) === 0;
+ }
+}
+
+/**
+ * Manages security realms.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleAuthenticator {
+ private $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 privatey wildly on their behaviour in this
+ * regard. Mozilla ignores the realm and presents
+ * only when challenged, wasting bandwidth. IE
+ * just carries on presenting until a new challenge
+ * 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
+ */
+ protected 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/3rdparty/simpletest/autorun.php b/3rdparty/simpletest/autorun.php
new file mode 100644
index 00000000000..8faf84d3ceb
--- /dev/null
+++ b/3rdparty/simpletest/autorun.php
@@ -0,0 +1,101 @@
+<?php
+/**
+ * Autorunner which runs all tests cases found in a file
+ * that includes this module.
+ * @package SimpleTest
+ * @version $Id: autorun.php 2037 2011-11-30 17:58:21Z pp11 $
+ */
+
+/**#@+
+ * include simpletest files
+ */
+require_once dirname(__FILE__) . '/unit_tester.php';
+require_once dirname(__FILE__) . '/mock_objects.php';
+require_once dirname(__FILE__) . '/collector.php';
+require_once dirname(__FILE__) . '/default_reporter.php';
+/**#@-*/
+
+$GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_CLASSES'] = get_declared_classes();
+$GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_PATH'] = getcwd();
+register_shutdown_function('simpletest_autorun');
+
+/**
+ * Exit handler to run all recent test cases and exit system if in CLI
+ */
+function simpletest_autorun() {
+ chdir($GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_PATH']);
+ if (tests_have_run()) {
+ return;
+ }
+ $result = run_local_tests();
+ if (SimpleReporter::inCli()) {
+ exit($result ? 0 : 1);
+ }
+}
+
+/**
+ * run all recent test cases if no test has
+ * so far been run. Uses the DefaultReporter which can have
+ * it's output controlled with SimpleTest::prefer().
+ * @return boolean/null false if there were test failures, true if
+ * there were no failures, null if tests are
+ * already running
+ */
+function run_local_tests() {
+ try {
+ if (tests_have_run()) {
+ return;
+ }
+ $candidates = capture_new_classes();
+ $loader = new SimpleFileLoader();
+ $suite = $loader->createSuiteFromClasses(
+ basename(initial_file()),
+ $loader->selectRunnableTests($candidates));
+ return $suite->run(new DefaultReporter());
+ } catch (Exception $stack_frame_fix) {
+ print $stack_frame_fix->getMessage();
+ return false;
+ }
+}
+
+/**
+ * Checks the current test context to see if a test has
+ * ever been run.
+ * @return boolean True if tests have run.
+ */
+function tests_have_run() {
+ if ($context = SimpleTest::getContext()) {
+ return (boolean)$context->getTest();
+ }
+ return false;
+}
+
+/**
+ * The first autorun file.
+ * @return string Filename of first autorun script.
+ */
+function initial_file() {
+ static $file = false;
+ if (! $file) {
+ if (isset($_SERVER, $_SERVER['SCRIPT_FILENAME'])) {
+ $file = $_SERVER['SCRIPT_FILENAME'];
+ } else {
+ $included_files = get_included_files();
+ $file = reset($included_files);
+ }
+ }
+ return $file;
+}
+
+/**
+ * Every class since the first autorun include. This
+ * is safe enough if require_once() is always used.
+ * @return array Class names.
+ */
+function capture_new_classes() {
+ global $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES;
+ return array_map('strtolower', array_diff(get_declared_classes(),
+ $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES ?
+ $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES : array()));
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/browser.php b/3rdparty/simpletest/browser.php
new file mode 100644
index 00000000000..615e738d350
--- /dev/null
+++ b/3rdparty/simpletest/browser.php
@@ -0,0 +1,1144 @@
+<?php
+/**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: browser.php 2013 2011-04-29 09:29:45Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/simpletest.php');
+require_once(dirname(__FILE__) . '/http.php');
+require_once(dirname(__FILE__) . '/encoding.php');
+require_once(dirname(__FILE__) . '/page.php');
+require_once(dirname(__FILE__) . '/php_parser.php');
+require_once(dirname(__FILE__) . '/tidy_parser.php');
+require_once(dirname(__FILE__) . '/selector.php');
+require_once(dirname(__FILE__) . '/frames.php');
+require_once(dirname(__FILE__) . '/user_agent.php');
+if (! SimpleTest::getParsers()) {
+ SimpleTest::setParsers(array(new SimpleTidyPageBuilder(), new SimplePHPPageBuilder()));
+ //SimpleTest::setParsers(array(new SimplePHPPageBuilder()));
+}
+/**#@-*/
+
+if (! defined('DEFAULT_MAX_NESTED_FRAMES')) {
+ define('DEFAULT_MAX_NESTED_FRAMES', 3);
+}
+
+/**
+ * Browser history list.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleBrowserHistory {
+ private $sequence = array();
+ private $position = -1;
+
+ /**
+ * Test for no entries yet.
+ * @return boolean True if empty.
+ * @access private
+ */
+ protected function isEmpty() {
+ return ($this->position == -1);
+ }
+
+ /**
+ * Test for being at the beginning.
+ * @return boolean True if first.
+ * @access private
+ */
+ protected function atBeginning() {
+ return ($this->position == 0) && ! $this->isEmpty();
+ }
+
+ /**
+ * Test for being at the last entry.
+ * @return boolean True if last.
+ * @access private
+ */
+ protected function atEnd() {
+ return ($this->position + 1 >= count($this->sequence)) && ! $this->isEmpty();
+ }
+
+ /**
+ * Adds a successfully fetched page to the history.
+ * @param SimpleUrl $url URL of fetch.
+ * @param SimpleEncoding $parameters Any post data with the fetch.
+ * @access public
+ */
+ function recordEntry($url, $parameters) {
+ $this->dropFuture();
+ array_push(
+ $this->sequence,
+ array('url' => $url, 'parameters' => $parameters));
+ $this->position++;
+ }
+
+ /**
+ * 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
+ */
+ protected 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 {
+ private $user_agent;
+ private $page;
+ private $history;
+ private $ignore_frames;
+ private $maximum_nested_frames;
+ private $parser;
+
+ /**
+ * 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 __construct() {
+ $this->user_agent = $this->createUserAgent();
+ $this->user_agent->useProxy(
+ SimpleTest::getDefaultProxy(),
+ SimpleTest::getDefaultProxyUsername(),
+ SimpleTest::getDefaultProxyPassword());
+ $this->page = new SimplePage();
+ $this->history = $this->createHistory();
+ $this->ignore_frames = false;
+ $this->maximum_nested_frames = DEFAULT_MAX_NESTED_FRAMES;
+ }
+
+ /**
+ * Creates the underlying user agent.
+ * @return SimpleFetcher Content fetcher.
+ * @access protected
+ */
+ protected function createUserAgent() {
+ return new SimpleUserAgent();
+ }
+
+ /**
+ * Creates a new empty history list.
+ * @return SimpleBrowserHistory New list.
+ * @access protected
+ */
+ protected function createHistory() {
+ return new SimpleBrowserHistory();
+ }
+
+ /**
+ * Get the HTML parser to use. Can be overridden by
+ * setParser. Otherwise scans through the available parsers and
+ * uses the first one which is available.
+ * @return object SimplePHPPageBuilder or SimpleTidyPageBuilder
+ */
+ protected function getParser() {
+ if ($this->parser) {
+ return $this->parser;
+ }
+ foreach (SimpleTest::getParsers() as $parser) {
+ if ($parser->can()) {
+ return $parser;
+ }
+ }
+ }
+
+ /**
+ * Override the default HTML parser, allowing parsers to be plugged in.
+ * @param object A parser object instance.
+ */
+ public function setParser($parser) {
+ $this->parser = $parser;
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * Switches off cookie sending and recieving.
+ * @access public
+ */
+ function ignoreCookies() {
+ $this->user_agent->ignoreCookies();
+ }
+
+ /**
+ * Switches back on the cookie sending and recieving.
+ * @access public
+ */
+ function useCookies() {
+ $this->user_agent->useCookies();
+ }
+
+ /**
+ * 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 private
+ */
+ protected function parse($response, $depth = 0) {
+ $page = $this->buildPage($response);
+ if ($this->ignore_frames || ! $page->hasFrames() || ($depth > $this->maximum_nested_frames)) {
+ return $page;
+ }
+ $frameset = new SimpleFrameset($page);
+ foreach ($page->getFrameset() as $key => $url) {
+ $frame = $this->fetch($url, new SimpleGetEncoding(), $depth + 1);
+ $frameset->addFrame($frame, $key);
+ }
+ return $frameset;
+ }
+
+ /**
+ * Assembles the parsing machinery and actually parses
+ * a single page. Frees all of the builder memory and so
+ * unjams the PHP memory management.
+ * @param SimpleHttpResponse $response Response from fetch.
+ * @return SimplePage Parsed top level page.
+ */
+ protected function buildPage($response) {
+ return $this->getParser()->parse($response);
+ }
+
+ /**
+ * Fetches a page. Jointly recursive with the parse()
+ * method as it descends a frameset.
+ * @param string/SimpleUrl $url Target to fetch.
+ * @param SimpleEncoding $encoding GET/POST parameters.
+ * @param integer $depth Nested frameset depth protection.
+ * @return SimplePage Parsed page.
+ * @access private
+ */
+ protected function fetch($url, $encoding, $depth = 0) {
+ $response = $this->user_agent->fetchResponse($url, $encoding);
+ 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 SimpleUrl $url Target to fetch.
+ * @param SimpleEncoding $parameters GET/POST parameters.
+ * @return string Raw content of page.
+ * @access private
+ */
+ protected function load($url, $parameters) {
+ $frame = $url->getTarget();
+ if (! $frame || ! $this->page->hasFrames() || (strtolower($frame) == '_top')) {
+ return $this->loadPage($url, $parameters);
+ }
+ return $this->loadFrame(array($frame), $url, $parameters);
+ }
+
+ /**
+ * Fetches a page and makes it the current page/frame.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param SimplePostEncoding $parameters POST parameters.
+ * @return string Raw content of page.
+ * @access private
+ */
+ protected function loadPage($url, $parameters) {
+ $this->page = $this->fetch($url, $parameters);
+ $this->history->recordEntry(
+ $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/SimpleUrl $url Target to fetch as string.
+ * @param SimpleFormEncoding $parameters POST parameters.
+ * @return string Raw content of page.
+ * @access private
+ */
+ protected function loadFrame($frames, $url, $parameters) {
+ $page = $this->fetch($url, $parameters);
+ $this->page->setFrame($frames, $page);
+ return $page->getRaw();
+ }
+
+ /**
+ * 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/SimpleHeadEncoding $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 ($this->getUrl()) {
+ $url = $url->makeAbsolute($this->getUrl());
+ }
+ $response = $this->user_agent->fetchResponse($url, new SimpleHeadEncoding($parameters));
+ $this->page = new SimplePage($response);
+ 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 ($this->getUrl()) {
+ $url = $url->makeAbsolute($this->getUrl());
+ }
+ return $this->load($url, new SimpleGetEncoding($parameters));
+ }
+
+ /**
+ * Fetches the page content with a POST request.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param hash/SimpleFormEncoding $parameters POST parameters or request body.
+ * @param string $content_type MIME Content-Type of the request body
+ * @return string Content of page.
+ * @access public
+ */
+ function post($url, $parameters = false, $content_type = false) {
+ if (! is_object($url)) {
+ $url = new SimpleUrl($url);
+ }
+ if ($this->getUrl()) {
+ $url = $url->makeAbsolute($this->getUrl());
+ }
+ return $this->load($url, new SimplePostEncoding($parameters, $content_type));
+ }
+
+ /**
+ * Fetches the page content with a PUT request.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param hash/SimpleFormEncoding $parameters PUT request body.
+ * @param string $content_type MIME Content-Type of the request body
+ * @return string Content of page.
+ * @access public
+ */
+ function put($url, $parameters = false, $content_type = false) {
+ if (! is_object($url)) {
+ $url = new SimpleUrl($url);
+ }
+ return $this->load($url, new SimplePutEncoding($parameters, $content_type));
+ }
+
+ /**
+ * Sends a DELETE request and fetches the response.
+ * @param string/SimpleUrl $url Target to fetch.
+ * @param hash/SimpleFormEncoding $parameters Additional parameters for
+ * DELETE request.
+ * @return string Content of page or false.
+ * @access public
+ */
+ function delete($url, $parameters = false) {
+ if (! is_object($url)) {
+ $url = new SimpleUrl($url);
+ }
+ return $this->load($url, new SimpleDeleteEncoding($parameters));
+ }
+
+ /**
+ * 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->getUrl(),
+ $this->page->getRequestData());
+ return $this->page->getRaw();
+ }
+ if ($url = $this->history->getUrl()) {
+ $this->page = $this->fetch($url, $this->history->getParameters());
+ return $this->page->getRaw();
+ }
+ return false;
+ }
+
+ /**
+ * Equivalent to hitting the back button on the
+ * browser. The browser history is unchanged on
+ * failure. The page content is refetched as there
+ * is no concept of content caching in SimpleTest.
+ * @return boolean True if history entry and
+ * fetch succeeded
+ * @access public
+ */
+ 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. The page content is refetched as there
+ * is no concept of content caching in SimpleTest.
+ * @return boolean True if history entry and
+ * fetch succeeded
+ * @access public
+ */
+ 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 base URL of page if set via BASE tag
+ * @return string base URL
+ */
+ function getBaseUrl() {
+ $url = $this->page->getBaseUrl();
+ 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 links in current page.
+ * @return array List of urls with scheme of
+ * http or https and hostname.
+ * @access public
+ */
+ function getUrls() {
+ return $this->page->getUrls();
+ }
+
+ /**
+ * Sets all form fields with that name.
+ * @param string $label Name or label of field in forms.
+ * @param string $value New value of field.
+ * @return boolean True if field exists, otherwise false.
+ * @access public
+ */
+ function setField($label, $value, $position=false) {
+ return $this->page->setField(new SimpleByLabelOrName($label), $value, $position);
+ }
+
+ /**
+ * Sets all form fields with that name. Will use label if
+ * one is available (not yet implemented).
+ * @param string $name Name of field in forms.
+ * @param string $value New value of field.
+ * @return boolean True if field exists, otherwise false.
+ * @access public
+ */
+ function setFieldByName($name, $value, $position=false) {
+ return $this->page->setField(new SimpleByName($name), $value, $position);
+ }
+
+ /**
+ * 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->setField(new SimpleById($id), $value);
+ }
+
+ /**
+ * Accessor for a form element value within the page.
+ * Finds the first match.
+ * @param string $label Field label.
+ * @return string/boolean A value if the field is
+ * present, false if unchecked
+ * and null if missing.
+ * @access public
+ */
+ function getField($label) {
+ return $this->page->getField(new SimpleByLabelOrName($label));
+ }
+
+ /**
+ * 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 getFieldByName($name) {
+ return $this->page->getField(new SimpleByName($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->getField(new SimpleById($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->getFormBySubmit(new SimpleByLabel($label)))) {
+ return false;
+ }
+ $success = $this->load(
+ $form->getAction(),
+ $form->submitButton(new SimpleByLabel($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->getFormBySubmit(new SimpleByName($name)))) {
+ return false;
+ }
+ $success = $this->load(
+ $form->getAction(),
+ $form->submitButton(new SimpleByName($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->getFormBySubmit(new SimpleById($id)))) {
+ return false;
+ }
+ $success = $this->load(
+ $form->getAction(),
+ $form->submitButton(new SimpleById($id), $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Tests to see if a submit button exists with this
+ * label.
+ * @param string $label Button label.
+ * @return boolean True if present.
+ * @access public
+ */
+ function isSubmit($label) {
+ return (boolean)$this->page->getFormBySubmit(new SimpleByLabel($label));
+ }
+
+ /**
+ * 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->getFormByImage(new SimpleByLabel($label)))) {
+ return false;
+ }
+ $success = $this->load(
+ $form->getAction(),
+ $form->submitImage(new SimpleByLabel($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->getFormByImage(new SimpleByName($name)))) {
+ return false;
+ }
+ $success = $this->load(
+ $form->getAction(),
+ $form->submitImage(new SimpleByName($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->getFormByImage(new SimpleById($id)))) {
+ return false;
+ }
+ $success = $this->load(
+ $form->getAction(),
+ $form->submitImage(new SimpleById($id), $x, $y, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Tests to see if an image exists with this
+ * title or alt text.
+ * @param string $label Image text.
+ * @return boolean True if present.
+ * @access public
+ */
+ function isImage($label) {
+ return (boolean)$this->page->getFormByImage(new SimpleByLabel($label));
+ }
+
+ /**
+ * 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, $additional = false) {
+ if (! ($form = $this->page->getFormById($id))) {
+ return false;
+ }
+ $success = $this->load(
+ $form->getAction(),
+ $form->submit($additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Finds a URL by label. Will find 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 URL on success.
+ * @access public
+ */
+ function getLink($label, $index = 0) {
+ $urls = $this->page->getUrlsByLabel($label);
+ if (count($urls) == 0) {
+ return false;
+ }
+ if (count($urls) < $index + 1) {
+ return false;
+ }
+ return $urls[$index];
+ }
+
+ /**
+ * 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) {
+ $url = $this->getLink($label, $index);
+ if ($url === false) {
+ return false;
+ }
+ $this->load($url, new SimpleGetEncoding());
+ return $this->getContent();
+ }
+
+ /**
+ * Finds a link by id attribute.
+ * @param string $id ID attribute value.
+ * @return string/boolean URL on success.
+ * @access public
+ */
+ function getLinkById($id) {
+ return $this->page->getUrlById($id);
+ }
+
+ /**
+ * 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->getLinkById($id))) {
+ return false;
+ }
+ $this->load($url, new SimpleGetEncoding());
+ return $this->getContent();
+ }
+
+ /**
+ * Clicks a visible text item. Will first try buttons,
+ * then links and then images.
+ * @param string $label Visible text or alt text.
+ * @return string/boolean Raw page or false.
+ * @access public
+ */
+ function click($label) {
+ $raw = $this->clickSubmit($label);
+ if (! $raw) {
+ $raw = $this->clickLink($label);
+ }
+ if (! $raw) {
+ $raw = $this->clickImage($label);
+ }
+ return $raw;
+ }
+
+ /**
+ * Tests to see if a click target exists.
+ * @param string $label Visible text or alt text.
+ * @return boolean True if target present.
+ * @access public
+ */
+ function isClickable($label) {
+ return $this->isSubmit($label) || ($this->getLink($label) !== false) || $this->isImage($label);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/collector.php b/3rdparty/simpletest/collector.php
new file mode 100644
index 00000000000..ac49937aada
--- /dev/null
+++ b/3rdparty/simpletest/collector.php
@@ -0,0 +1,122 @@
+<?php
+/**
+ * This file contains the following classes: {@link SimpleCollector},
+ * {@link SimplePatternCollector}.
+ *
+ * @author Travis Swicegood <development@domain51.com>
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: collector.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**
+ * The basic collector for {@link GroupTest}
+ *
+ * @see collect(), GroupTest::collect()
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleCollector {
+
+ /**
+ * Strips off any kind of slash at the end so as to normalise the path.
+ * @param string $path Path to normalise.
+ * @return string Path without trailing slash.
+ */
+ protected function removeTrailingSlash($path) {
+ if (substr($path, -1) == DIRECTORY_SEPARATOR) {
+ return substr($path, 0, -1);
+ } elseif (substr($path, -1) == '/') {
+ return substr($path, 0, -1);
+ } else {
+ return $path;
+ }
+ }
+
+ /**
+ * Scans the directory and adds what it can.
+ * @param object $test Group test with {@link GroupTest::addTestFile()} method.
+ * @param string $path Directory to scan.
+ * @see _attemptToAdd()
+ */
+ function collect(&$test, $path) {
+ $path = $this->removeTrailingSlash($path);
+ if ($handle = opendir($path)) {
+ while (($entry = readdir($handle)) !== false) {
+ if ($this->isHidden($entry)) {
+ continue;
+ }
+ $this->handle($test, $path . DIRECTORY_SEPARATOR . $entry);
+ }
+ closedir($handle);
+ }
+ }
+
+ /**
+ * This method determines what should be done with a given file and adds
+ * it via {@link GroupTest::addTestFile()} if necessary.
+ *
+ * This method should be overriden to provide custom matching criteria,
+ * such as pattern matching, recursive matching, etc. For an example, see
+ * {@link SimplePatternCollector::_handle()}.
+ *
+ * @param object $test Group test with {@link GroupTest::addTestFile()} method.
+ * @param string $filename A filename as generated by {@link collect()}
+ * @see collect()
+ * @access protected
+ */
+ protected function handle(&$test, $file) {
+ if (is_dir($file)) {
+ return;
+ }
+ $test->addFile($file);
+ }
+
+ /**
+ * Tests for hidden files so as to skip them. Currently
+ * only tests for Unix hidden files.
+ * @param string $filename Plain filename.
+ * @return boolean True if hidden file.
+ * @access private
+ */
+ protected function isHidden($filename) {
+ return strncmp($filename, '.', 1) == 0;
+ }
+}
+
+/**
+ * An extension to {@link SimpleCollector} that only adds files matching a
+ * given pattern.
+ *
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @see SimpleCollector
+ */
+class SimplePatternCollector extends SimpleCollector {
+ private $pattern;
+
+ /**
+ *
+ * @param string $pattern Perl compatible regex to test name against
+ * See {@link http://us4.php.net/manual/en/reference.pcre.pattern.syntax.php PHP's PCRE}
+ * for full documentation of valid pattern.s
+ */
+ function __construct($pattern = '/php$/i') {
+ $this->pattern = $pattern;
+ }
+
+ /**
+ * Attempts to add files that match a given pattern.
+ *
+ * @see SimpleCollector::_handle()
+ * @param object $test Group test with {@link GroupTest::addTestFile()} method.
+ * @param string $path Directory to scan.
+ * @access protected
+ */
+ protected function handle(&$test, $filename) {
+ if (preg_match($this->pattern, $filename)) {
+ parent::handle($test, $filename);
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/compatibility.php b/3rdparty/simpletest/compatibility.php
new file mode 100755
index 00000000000..e313db0cb51
--- /dev/null
+++ b/3rdparty/simpletest/compatibility.php
@@ -0,0 +1,166 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @version $Id: compatibility.php 1900 2009-07-29 11:44:37Z lastcraft $
+ */
+
+/**
+ * Static methods for compatibility between different
+ * PHP versions.
+ * @package SimpleTest
+ */
+class SimpleTestCompatibility {
+
+ /**
+ * Creates a copy whether in PHP5 or PHP4.
+ * @param object $object Thing to copy.
+ * @return object A copy.
+ * @access public
+ */
+ static function copy($object) {
+ if (version_compare(phpversion(), '5') >= 0) {
+ eval('$copy = clone $object;');
+ return $copy;
+ }
+ return $object;
+ }
+
+ /**
+ * Identity test. Drops back to equality + types for PHP5
+ * objects as the === operator counts as the
+ * stronger reference constraint.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @return boolean True if identical.
+ * @access public
+ */
+ static function isIdentical($first, $second) {
+ if (version_compare(phpversion(), '5') >= 0) {
+ return SimpleTestCompatibility::isIdenticalType($first, $second);
+ }
+ if ($first != $second) {
+ return false;
+ }
+ return ($first === $second);
+ }
+
+ /**
+ * Recursive type test.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @return boolean True if same type.
+ * @access private
+ */
+ protected 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(
+ (array) $first,
+ (array) $second);
+ }
+ if (is_array($first) && is_array($second)) {
+ return SimpleTestCompatibility::isArrayOfIdenticalTypes($first, $second);
+ }
+ if ($first !== $second) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Recursive type test for each element of an array.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @return boolean True if identical.
+ * @access private
+ */
+ protected static function isArrayOfIdenticalTypes($first, $second) {
+ if (array_keys($first) != array_keys($second)) {
+ return false;
+ }
+ foreach (array_keys($first) as $key) {
+ $is_identical = SimpleTestCompatibility::isIdenticalType(
+ $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.
+ * @return boolean True if same.
+ * @access public
+ */
+ static function isReference(&$first, &$second) {
+ if (version_compare(phpversion(), '5', '>=') && is_object($first)) {
+ return ($first === $second);
+ }
+ if (is_object($first) && is_object($second)) {
+ $id = uniqid("test");
+ $first->$id = true;
+ $is_ref = isset($second->$id);
+ unset($first->$id);
+ return $is_ref;
+ }
+ $temp = $first;
+ $first = uniqid("test");
+ $is_ref = ($first === $second);
+ $first = $temp;
+ return $is_ref;
+ }
+
+ /**
+ * Test to see if an object is a member of a
+ * class hiearchy.
+ * @param object $object Object to test.
+ * @param string $class Root name of hiearchy.
+ * @return boolean True if class in hiearchy.
+ * @access public
+ */
+ static function isA($object, $class) {
+ if (version_compare(phpversion(), '5') >= 0) {
+ if (! class_exists($class, false)) {
+ if (function_exists('interface_exists')) {
+ if (! interface_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)));
+ }
+
+ /**
+ * 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);
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/cookies.php b/3rdparty/simpletest/cookies.php
new file mode 100644
index 00000000000..7a28f4a5bcc
--- /dev/null
+++ b/3rdparty/simpletest/cookies.php
@@ -0,0 +1,380 @@
+<?php
+/**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: cookies.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/url.php');
+/**#@-*/
+
+/**
+ * Cookie data holder. Cookie rules are full of pretty
+ * arbitary stuff. I have used...
+ * http://wp.netscape.com/newsref/std/cookie_spec.html
+ * http://www.cookiecentral.com/faq/
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleCookie {
+ private $host;
+ private $name;
+ private $value;
+ private $path;
+ private $expiry;
+ private $is_secure;
+
+ /**
+ * Constructor. Sets the stored values.
+ * @param string $name Cookie key.
+ * @param string $value Value of cookie.
+ * @param string $path Cookie path if not host wide.
+ * @param string $expiry Expiry date as string.
+ * @param boolean $is_secure Currently ignored.
+ */
+ function __construct($name, $value = false, $path = false, $expiry = false, $is_secure = false) {
+ $this->host = false;
+ $this->name = $name;
+ $this->value = $value;
+ $this->path = ($path ? $this->fixPath($path) : "/");
+ $this->expiry = false;
+ if (is_string($expiry)) {
+ $this->expiry = strtotime($expiry);
+ } 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
+ */
+ protected 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
+ */
+ protected function fixPath($path) {
+ if (substr($path, 0, 1) != '/') {
+ $path = '/' . $path;
+ }
+ if (substr($path, -1, 1) != '/') {
+ $path .= '/';
+ }
+ return $path;
+ }
+}
+
+/**
+ * Repository for cookies. This stuff is a
+ * tiny bit browser dependent.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleCookieJar {
+ private $cookies;
+
+ /**
+ * Constructor. Jar starts empty.
+ * @access public
+ */
+ function __construct() {
+ $this->cookies = array();
+ }
+
+ /**
+ * Removes expired and temporary cookies as if
+ * the browser was closed and re-opened.
+ * @param string/integer $now Time to test expiry against.
+ * @access public
+ */
+ function restartSession($date = false) {
+ $surviving_cookies = array();
+ for ($i = 0; $i < count($this->cookies); $i++) {
+ if (! $this->cookies[$i]->getValue()) {
+ continue;
+ }
+ if (! $this->cookies[$i]->getExpiry()) {
+ continue;
+ }
+ if ($date && $this->cookies[$i]->isExpired($date)) {
+ continue;
+ }
+ $surviving_cookies[] = $this->cookies[$i];
+ }
+ $this->cookies = $surviving_cookies;
+ }
+
+ /**
+ * Ages all cookies in the cookie jar.
+ * @param integer $interval The old session is moved
+ * into the past by this number
+ * of seconds. Cookies now over
+ * age will be removed.
+ * @access public
+ */
+ function agePrematurely($interval) {
+ for ($i = 0; $i < count($this->cookies); $i++) {
+ $this->cookies[$i]->agePrematurely($interval);
+ }
+ }
+
+ /**
+ * Sets an additional cookie. If a cookie has
+ * the same name and path it is replaced.
+ * @param string $name Cookie key.
+ * @param string $value Value of cookie.
+ * @param string $host Host upon which the cookie is valid.
+ * @param string $path Cookie path if not host wide.
+ * @param string $expiry Expiry date.
+ * @access public
+ */
+ function setCookie($name, $value, $host = false, $path = '/', $expiry = false) {
+ $cookie = new SimpleCookie($name, $value, $path, $expiry);
+ if ($host) {
+ $cookie->setHost($host);
+ }
+ $this->cookies[$this->findFirstMatch($cookie)] = $cookie;
+ }
+
+ /**
+ * Finds a matching cookie to write over or the
+ * first empty slot if none.
+ * @param SimpleCookie $cookie Cookie to write into jar.
+ * @return integer Available slot.
+ * @access private
+ */
+ protected function findFirstMatch($cookie) {
+ for ($i = 0; $i < count($this->cookies); $i++) {
+ $is_match = $this->isMatch(
+ $cookie,
+ $this->cookies[$i]->getHost(),
+ $this->cookies[$i]->getPath(),
+ $this->cookies[$i]->getName());
+ if ($is_match) {
+ return $i;
+ }
+ }
+ return count($this->cookies);
+ }
+
+ /**
+ * Reads the most specific cookie value from the
+ * browser cookies. Looks for the longest path that
+ * matches.
+ * @param string $host Host to search.
+ * @param string $path Applicable path.
+ * @param string $name Name of cookie to read.
+ * @return string False if not present, else the
+ * value as a string.
+ * @access public
+ */
+ function getCookieValue($host, $path, $name) {
+ $longest_path = '';
+ foreach ($this->cookies as $cookie) {
+ if ($this->isMatch($cookie, $host, $path, $name)) {
+ if (strlen($cookie->getPath()) > strlen($longest_path)) {
+ $value = $cookie->getValue();
+ $longest_path = $cookie->getPath();
+ }
+ }
+ }
+ return (isset($value) ? $value : false);
+ }
+
+ /**
+ * Tests cookie for matching against search
+ * criteria.
+ * @param SimpleTest $cookie Cookie to test.
+ * @param string $host Host must match.
+ * @param string $path Cookie path must be shorter than
+ * this path.
+ * @param string $name Name must match.
+ * @return boolean True if matched.
+ * @access private
+ */
+ protected function isMatch($cookie, $host, $path, $name) {
+ if ($cookie->getName() != $name) {
+ return false;
+ }
+ if ($host && $cookie->getHost() && ! $cookie->isValidHost($host)) {
+ return false;
+ }
+ if (! $cookie->isValidPath($path)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Uses a URL to sift relevant cookies by host and
+ * path. Results are list of strings of form "name=value".
+ * @param SimpleUrl $url Url to select by.
+ * @return array Valid name and value pairs.
+ * @access public
+ */
+ function selectAsPairs($url) {
+ $pairs = array();
+ foreach ($this->cookies as $cookie) {
+ if ($this->isMatch($cookie, $url->getHost(), $url->getPath(), $cookie->getName())) {
+ $pairs[] = $cookie->getName() . '=' . $cookie->getValue();
+ }
+ }
+ return $pairs;
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/default_reporter.php b/3rdparty/simpletest/default_reporter.php
new file mode 100644
index 00000000000..6feb67a3088
--- /dev/null
+++ b/3rdparty/simpletest/default_reporter.php
@@ -0,0 +1,163 @@
+<?php
+/**
+ * Optional include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: default_reporter.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/simpletest.php');
+require_once(dirname(__FILE__) . '/scorer.php');
+require_once(dirname(__FILE__) . '/reporter.php');
+require_once(dirname(__FILE__) . '/xml.php');
+/**#@-*/
+
+/**
+ * Parser for command line arguments. Extracts
+ * the a specific test to run and engages XML
+ * reporting when necessary.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleCommandLineParser {
+ private $to_property = array(
+ 'case' => 'case', 'c' => 'case',
+ 'test' => 'test', 't' => 'test',
+ );
+ private $case = '';
+ private $test = '';
+ private $xml = false;
+ private $help = false;
+ private $no_skips = false;
+
+ /**
+ * Parses raw command line arguments into object properties.
+ * @param string $arguments Raw commend line arguments.
+ */
+ function __construct($arguments) {
+ if (! is_array($arguments)) {
+ return;
+ }
+ foreach ($arguments as $i => $argument) {
+ if (preg_match('/^--?(test|case|t|c)=(.+)$/', $argument, $matches)) {
+ $property = $this->to_property[$matches[1]];
+ $this->$property = $matches[2];
+ } elseif (preg_match('/^--?(test|case|t|c)$/', $argument, $matches)) {
+ $property = $this->to_property[$matches[1]];
+ if (isset($arguments[$i + 1])) {
+ $this->$property = $arguments[$i + 1];
+ }
+ } elseif (preg_match('/^--?(xml|x)$/', $argument)) {
+ $this->xml = true;
+ } elseif (preg_match('/^--?(no-skip|no-skips|s)$/', $argument)) {
+ $this->no_skips = true;
+ } elseif (preg_match('/^--?(help|h)$/', $argument)) {
+ $this->help = true;
+ }
+ }
+ }
+
+ /**
+ * Run only this test.
+ * @return string Test name to run.
+ */
+ function getTest() {
+ return $this->test;
+ }
+
+ /**
+ * Run only this test suite.
+ * @return string Test class name to run.
+ */
+ function getTestCase() {
+ return $this->case;
+ }
+
+ /**
+ * Output should be XML or not.
+ * @return boolean True if XML desired.
+ */
+ function isXml() {
+ return $this->xml;
+ }
+
+ /**
+ * Output should suppress skip messages.
+ * @return boolean True for no skips.
+ */
+ function noSkips() {
+ return $this->no_skips;
+ }
+
+ /**
+ * Output should be a help message. Disabled during XML mode.
+ * @return boolean True if help message desired.
+ */
+ function help() {
+ return $this->help && ! $this->xml;
+ }
+
+ /**
+ * Returns plain-text help message for command line runner.
+ * @return string String help message
+ */
+ function getHelpText() {
+ return <<<HELP
+SimpleTest command line default reporter (autorun)
+Usage: php <test_file> [args...]
+
+ -c <class> Run only the test-case <class>
+ -t <method> Run only the test method <method>
+ -s Suppress skip messages
+ -x Return test results in XML
+ -h Display this help message
+
+HELP;
+ }
+
+}
+
+/**
+ * The default reporter used by SimpleTest's autorun
+ * feature. The actual reporters used are dependency
+ * injected and can be overridden.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class DefaultReporter extends SimpleReporterDecorator {
+
+ /**
+ * Assembles the appropriate reporter for the environment.
+ */
+ function __construct() {
+ if (SimpleReporter::inCli()) {
+ $parser = new SimpleCommandLineParser($_SERVER['argv']);
+ $interfaces = $parser->isXml() ? array('XmlReporter') : array('TextReporter');
+ if ($parser->help()) {
+ // I'm not sure if we should do the echo'ing here -- ezyang
+ echo $parser->getHelpText();
+ exit(1);
+ }
+ $reporter = new SelectiveReporter(
+ SimpleTest::preferred($interfaces),
+ $parser->getTestCase(),
+ $parser->getTest());
+ if ($parser->noSkips()) {
+ $reporter = new NoSkipsReporter($reporter);
+ }
+ } else {
+ $reporter = new SelectiveReporter(
+ SimpleTest::preferred('HtmlReporter'),
+ @$_GET['c'],
+ @$_GET['t']);
+ if (@$_GET['skips'] == 'no' || @$_GET['show-skips'] == 'no') {
+ $reporter = new NoSkipsReporter($reporter);
+ }
+ }
+ parent::__construct($reporter);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/detached.php b/3rdparty/simpletest/detached.php
new file mode 100755
index 00000000000..a325e140d02
--- /dev/null
+++ b/3rdparty/simpletest/detached.php
@@ -0,0 +1,96 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: detached.php 1784 2008-04-26 13:07:14Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/xml.php');
+require_once(dirname(__FILE__) . '/shell_tester.php');
+/**#@-*/
+
+/**
+ * Runs an XML formated test in a separate process.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class DetachedTestCase {
+ private $command;
+ private $dry_command;
+ private $size;
+
+ /**
+ * Sets the location of the remote test.
+ * @param string $command Test script.
+ * @param string $dry_command Script for dry run.
+ * @access public
+ */
+ function __construct($command, $dry_command = false) {
+ $this->command = $command;
+ $this->dry_command = $dry_command ? $dry_command : $command;
+ $this->size = false;
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->command;
+ }
+
+ /**
+ * 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) {
+ $shell = &new SimpleShell();
+ $shell->execute($this->command);
+ $parser = &$this->createParser($reporter);
+ if (! $parser->parse($shell->getOutput())) {
+ trigger_error('Cannot parse incoming XML from [' . $this->command . ']');
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Accessor for the number of subtests.
+ * @return integer Number of test cases.
+ * @access public
+ */
+ function getSize() {
+ if ($this->size === false) {
+ $shell = &new SimpleShell();
+ $shell->execute($this->dry_command);
+ $reporter = &new SimpleReporter();
+ $parser = &$this->createParser($reporter);
+ if (! $parser->parse($shell->getOutput())) {
+ trigger_error('Cannot parse incoming XML from [' . $this->dry_command . ']');
+ return false;
+ }
+ $this->size = $reporter->getTestCaseCount();
+ }
+ return $this->size;
+ }
+
+ /**
+ * Creates the XML parser.
+ * @param SimpleReporter $reporter Target of test results.
+ * @return SimpleTestXmlListener XML reader.
+ * @access protected
+ */
+ protected function &createParser(&$reporter) {
+ return new SimpleTestXmlParser($reporter);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/docs/en/authentication_documentation.html b/3rdparty/simpletest/docs/en/authentication_documentation.html
new file mode 100644
index 00000000000..e058e19a111
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/authentication_documentation.html
@@ -0,0 +1,378 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest documentation for testing log-in and authentication</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <span class="chosen">Authentication</span>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Authentication documentation</h1>
+ This page...
+ <ul>
+<li>
+ Getting through <a href="#basic">Basic HTTP authentication</a>
+ </li>
+<li>
+ Testing <a href="#cookies">cookie based authentication</a>
+ </li>
+<li>
+ Managing <a href="#session">browser sessions</a> and timeouts
+ </li>
+</ul>
+<div class="content">
+
+ <p>
+ 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.
+ </p>
+
+ <h2>
+<a class="target" name="basic"></a>Basic HTTP authentication</h2>
+ <p>
+ 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...
+<pre>
+class AuthenticationTest extends WebTestCase {<strong>
+ function test401Header() {
+ $this-&gt;get('http://www.lastcraft.com/protected/');
+ $this-&gt;showHeaders();
+ }</strong>
+}
+</pre>
+ This allows us to see the challenge header...
+ <div class="demo">
+ <h1>File test</h1>
+<pre>
+HTTP/1.1 401 Authorization Required
+Date: Sat, 18 Sep 2004 19:25:18 GMT
+Server: Apache/1.3.29 (Unix) PHP/4.3.4
+WWW-Authenticate: Basic realm="SimpleTest basic authentication"
+Connection: close
+Content-Type: text/html; charset=iso-8859-1
+</pre>
+ <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
+ <strong>0</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
+ </div>
+ 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...
+<pre>
+class AuthenticationTest extends WebTestCase {
+ function test401Header() {
+ $this-&gt;get('http://www.lastcraft.com/protected/');<strong>
+ $this-&gt;assertAuthentication('Basic');
+ $this-&gt;assertResponse(401);
+ $this-&gt;assertRealm('SimpleTest basic authentication');</strong>
+ }
+}
+</pre>
+ Any one of these tests would normally do on it's own depending
+ on the amount of detail you want to see.
+ </p>
+ <p>
+ One theme that runs through SimpleTest is the ability to use
+ <span class="new_code">SimpleExpectation</span> objects wherever a simple
+ match is not enough.
+ If you want only an approximate match to the realm for
+ example, you can do this...
+<pre>
+class AuthenticationTest extends WebTestCase {
+ function test401Header() {
+ $this-&gt;get('http://www.lastcraft.com/protected/');
+ $this-&gt;assertRealm(<strong>new PatternExpectation('/simpletest/i')</strong>);
+ }
+}
+</pre>
+ This type of test, testing HTTP responses, is not typical.
+ </p>
+ <p>
+ 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...
+<pre>
+class AuthenticationTest extends WebTestCase {
+ function testCanAuthenticate() {
+ $this-&gt;get('http://www.lastcraft.com/protected/');<strong>
+ $this-&gt;authenticate('Me', 'Secret');</strong>
+ $this-&gt;assertTitle(...);
+ }
+}
+</pre>
+ 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.
+ </p>
+ <p>
+ If you want, you can shortcut this step further by encoding
+ the log in details straight into the URL...
+<pre>
+class AuthenticationTest extends WebTestCase {
+ function testCanReadAuthenticatedPages() {
+ $this-&gt;get('http://<strong>Me:Secret@</strong>www.lastcraft.com/protected/');
+ $this-&gt;assertTitle(...);
+ }
+}
+</pre>
+ If your username or password has special characters, then you
+ will have to URL encode them or the request will not be parsed
+ correctly.
+ I'm afraid we leave this up to you.
+ </p>
+ <p>
+ A problem with encoding the login details directly in the URL is
+ the authentication header will not be sent on subsequent requests.
+ If you navigate with relative URLs though, the authentication
+ information will be preserved along with the domain name.
+ </p>
+ <p>
+ Normally though, you use the <span class="new_code">authenticate()</span> call.
+ SimpleTest will then remember your login information on each request.
+ </p>
+ <p>
+ Only testing with basic authentication is currently supported, and
+ this is only really secure in tandem with HTTPS connections.
+ This is usually good enough to protect test server from prying eyes,
+ however.
+ Digest authentication and NTLM authentication may be added
+ in the future if enough people request this feature.
+ </p>
+
+ <h2>
+<a class="target" name="cookies"></a>Cookies</h2>
+ <p>
+ 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 with complicated timeouts.
+ We need to be able to test this too.
+ </p>
+ <p>
+ Starting with a simple log-in form...
+<pre>
+&lt;form&gt;
+ Username:
+ &lt;input type="text" name="u" value="" /&gt;&lt;br /&gt;
+ Password:
+ &lt;input type="password" name="p" value="" /&gt;&lt;br /&gt;
+ &lt;input type="submit" value="Log in" /&gt;
+&lt;/form&gt;
+</pre>
+ Which looks like...
+ </p>
+ <p>
+ <form class="demo">
+ Username:
+ <input type="text" name="u" value=""><br>
+ Password:
+ <input type="password" name="p" value=""><br>
+ <input type="submit" value="Log in">
+ </form>
+ </p>
+ <p>
+ 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...
+<pre>
+class LogInTest extends WebTestCase {
+ function testSessionCookieSetBeforeForm() {
+ $this-&gt;get('http://www.my-site.com/login.php');<strong>
+ $this-&gt;assertCookie('SID');</strong>
+ }
+}
+</pre>
+ 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 with...
+<pre>
+class LogInTest extends WebTestCase {
+ function testSessionCookieIsCorrectPattern() {
+ $this-&gt;get('http://www.my-site.com/login.php');
+ $this-&gt;assertCookie('SID', <strong>new PatternExpectation('/[a-f0-9]{32}/i')</strong>);
+ }
+}
+</pre>
+ If you are using PHP to handle sessions for you then
+ this test is even more useless, as we are just testing PHP itself.
+ </p>
+ <p>
+ The simplest test of logging in is to visually inspect the
+ next page to see if you are really logged in.
+ Just test the next page with <span class="new_code">WebTestCase::assertText()</span>.
+ </p>
+ <p>
+ The test is similar to any other form test,
+ 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...
+<pre>
+class LogInTest extends WebTestCase {
+ ...
+ function testSessionCookieSameAfterLogIn() {
+ $this-&gt;get('http://www.my-site.com/login.php');<strong>
+ $session = $this-&gt;getCookie('SID');
+ $this-&gt;setField('u', 'Me');
+ $this-&gt;setField('p', 'Secret');
+ $this-&gt;click('Log in');
+ $this-&gt;assertText('Welcome Me');
+ $this-&gt;assertCookie('SID', $session);</strong>
+ }
+}
+</pre>
+ This confirms that the session identifier is maintained
+ afer log-in and we haven't accidently reset it.
+ </p>
+ <p>
+ We could even attempt to hack our own system by setting
+ arbitrary cookies to gain access...
+<pre>
+class LogInTest extends WebTestCase {
+ ...
+ function testSessionCookieSameAfterLogIn() {
+ $this-&gt;get('http://www.my-site.com/login.php');<strong>
+ $this-&gt;setCookie('SID', 'Some other session');
+ $this-&gt;get('http://www.my-site.com/restricted.php');</strong>
+ $this-&gt;assertText('Access denied');
+ }
+}
+</pre>
+ Is your site protected from this attack?
+ </p>
+
+ <h2>
+<a class="target" name="session"></a>Browser sessions</h2>
+ <p>
+ 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...
+<pre>
+class LogInTest extends WebTestCase {
+ ...
+ function testLoseAuthenticationAfterBrowserClose() {
+ $this-&gt;get('http://www.my-site.com/login.php');
+ $this-&gt;setField('u', 'Me');
+ $this-&gt;setField('p', 'Secret');
+ $this-&gt;click('Log in');
+ $this-&gt;assertText('Welcome Me');<strong>
+
+ $this-&gt;restart();
+ $this-&gt;get('http://www.my-site.com/restricted.php');
+ $this-&gt;assertText('Access denied');</strong>
+ }
+}
+</pre>
+ The <span class="new_code">WebTestCase::restart()</span> 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.
+ </p>
+ <p>
+ 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 waiting
+ for the cookie to pass it's timeout.
+ </p>
+ <p>
+ To push the cookies over the hour limit you can age them
+ before you restart the session...
+<pre>
+class LogInTest extends WebTestCase {
+ ...
+ function testLoseAuthenticationAfterOneHour() {
+ $this-&gt;get('http://www.my-site.com/login.php');
+ $this-&gt;setField('u', 'Me');
+ $this-&gt;setField('p', 'Secret');
+ $this-&gt;click('Log in');
+ $this-&gt;assertText('Welcome Me');
+ <strong>
+ $this-&gt;ageCookies(3600);</strong>
+ $this-&gt;restart();
+ $this-&gt;get('http://www.my-site.com/restricted.php');
+ $this-&gt;assertText('Access denied');
+ }
+}
+</pre>
+ After the restart it will appear that cookies are an
+ hour older, and any that pass their expiry will have
+ disappeared.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ The <a href="http://simpletest.org/api/">developer's API for SimpleTest</a>
+ gives full detail on the classes and assertions available.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <span class="chosen">Authentication</span>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/en/browser_documentation.html b/3rdparty/simpletest/docs/en/browser_documentation.html
new file mode 100644
index 00000000000..809c1431137
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/browser_documentation.html
@@ -0,0 +1,501 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest documentation for the scriptable web browser component</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <span class="chosen">Scriptable browser</span>
+</div></div>
+<h1>PHP Scriptable Web Browser</h1>
+ This page...
+ <ul>
+<li>
+ Using the bundled <a href="#scripting">web browser in scripts</a>
+ </li>
+<li>
+ <a href="#debug">Debugging</a> failed pages
+ </li>
+<li>
+ Complex <a href="#unit">tests with multiple web browsers</a>
+ </li>
+</ul>
+<div class="content">
+
+ <p>
+ SimpleTest's web browser component can be used not just
+ outside of the <span class="new_code">WebTestCase</span> class, but also
+ independently of the SimpleTest framework itself.
+ </p>
+
+ <h2>
+<a class="target" name="scripting"></a>The Scriptable Browser</h2>
+ <p>
+ 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 <a href="http://www.php.net/">PHP web site</a>...
+<pre>
+<strong>&lt;?php
+require_once('simpletest/browser.php');
+
+$browser = &amp;new SimpleBrowser();
+$browser-&gt;get('http://php.net/');
+$browser-&gt;click('reporting bugs');
+$browser-&gt;click('statistics');
+$page = $browser-&gt;click('PHP 5 bugs only');
+preg_match('/status=Open.*?by=Any.*?(\d+)&lt;\/a&gt;/', $page, $matches);
+print $matches[1];
+?&gt;</strong>
+</pre>
+ There are simpler methods to do this particular example in PHP
+ of course.
+ For example you can just use the PHP <span class="new_code">file()</span>
+ 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.
+ <p>
+ </p>
+ Methods such as periodic scraping 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.
+ </p>
+ <p>
+ All of the navigation methods used in the
+ <a href="web_tester_documentation.html">WebTestCase</a>
+ are present in the <span class="new_code">SimpleBrowser</span> class, but
+ the assertions are replaced with simpler accessors.
+ Here is a full list of the page navigation methods...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">addHeader($header)</span></td>
+<td>Adds a header to every fetch</td>
+</tr>
+ <tr>
+<td><span class="new_code">useProxy($proxy, $username, $password)</span></td>
+<td>Use this proxy from now on</td>
+</tr>
+ <tr>
+<td><span class="new_code">head($url, $parameters)</span></td>
+<td>Perform a HEAD request</td>
+</tr>
+ <tr>
+<td><span class="new_code">get($url, $parameters)</span></td>
+<td>Fetch a page with GET</td>
+</tr>
+ <tr>
+<td><span class="new_code">post($url, $parameters)</span></td>
+<td>Fetch a page with POST</td>
+</tr>
+ <tr>
+<td><span class="new_code">click($label)</span></td>
+<td>Clicks visible link or button text</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickLink($label)</span></td>
+<td>Follows a link by label</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickLinkById($id)</span></td>
+<td>Follows a link by attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">getUrl()</span></td>
+<td>Current URL of page or frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">getTitle()</span></td>
+<td>Page title</td>
+</tr>
+ <tr>
+<td><span class="new_code">getContent()</span></td>
+<td>Raw page or frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">getContentAsText()</span></td>
+<td>HTML removed except for alt text</td>
+</tr>
+ <tr>
+<td><span class="new_code">retry()</span></td>
+<td>Repeat the last request</td>
+</tr>
+ <tr>
+<td><span class="new_code">back()</span></td>
+<td>Use the browser back button</td>
+</tr>
+ <tr>
+<td><span class="new_code">forward()</span></td>
+<td>Use the browser forward button</td>
+</tr>
+ <tr>
+<td><span class="new_code">authenticate($username, $password)</span></td>
+<td>Retry page or frame after a 401 response</td>
+</tr>
+ <tr>
+<td><span class="new_code">restart($date)</span></td>
+<td>Restarts the browser for a new session</td>
+</tr>
+ <tr>
+<td><span class="new_code">ageCookies($interval)</span></td>
+<td>Ages the cookies by the specified time</td>
+</tr>
+ <tr>
+<td><span class="new_code">setCookie($name, $value)</span></td>
+<td>Sets an additional cookie</td>
+</tr>
+ <tr>
+<td><span class="new_code">getCookieValue($host, $path, $name)</span></td>
+<td>Reads the most specific cookie</td>
+</tr>
+ <tr>
+<td><span class="new_code">getCurrentCookieValue($name)</span></td>
+<td>Reads cookie for the current context</td>
+</tr>
+ </tbody></table>
+ The methods <span class="new_code">SimpleBrowser::useProxy()</span> and
+ <span class="new_code">SimpleBrowser::addHeader()</span> are special.
+ Once called they continue to apply to all subsequent fetches.
+ </p>
+ <p>
+ Navigating forms is similar to the
+ <a href="form_testing_documentation.html">WebTestCase form navigation</a>...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">setField($label, $value)</span></td>
+<td>Sets all form fields with that label or name</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFieldByName($name, $value)</span></td>
+<td>Sets all form fields with that name</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFieldById($id, $value)</span></td>
+<td>Sets all form fields with that id</td>
+</tr>
+ <tr>
+<td><span class="new_code">getField($label)</span></td>
+<td>Accessor for a form element value by label tag and then name</td>
+</tr>
+ <tr>
+<td><span class="new_code">getFieldByName($name)</span></td>
+<td>Accessor for a form element value using name attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">getFieldById($id)</span></td>
+<td>Accessor for a form element value</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmit($label)</span></td>
+<td>Submits form by button label</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmitByName($name)</span></td>
+<td>Submits form by button attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmitById($id)</span></td>
+<td>Submits form by button attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImage($label, $x, $y)</span></td>
+<td>Clicks an input tag of type image by title or alt text</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImageByName($name, $x, $y)</span></td>
+<td>Clicks an input tag of type image by name</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImageById($id, $x, $y)</span></td>
+<td>Clicks an input tag of type image by ID attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">submitFormById($id)</span></td>
+<td>Submits by the form tag attribute</td>
+</tr>
+ </tbody></table>
+ At the moment there aren't many methods to list available links and fields.
+ <table><tbody>
+ <tr>
+<td><span class="new_code">isClickable($label)</span></td>
+<td>Test to see if a click target exists by label or name</td>
+</tr>
+ <tr>
+<td><span class="new_code">isSubmit($label)</span></td>
+<td>Test for the existence of a button with that label or name</td>
+</tr>
+ <tr>
+<td><span class="new_code">isImage($label)</span></td>
+<td>Test for the existence of an image button with that label or name</td>
+</tr>
+ <tr>
+<td><span class="new_code">getLink($label)</span></td>
+<td>Finds a URL from its label</td>
+</tr>
+ <tr>
+<td><span class="new_code">getLinkById($label)</span></td>
+<td>Finds a URL from its ID attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">getUrls()</span></td>
+<td>Lists available links in the current page</td>
+</tr>
+ </tbody></table>
+ This will be expanded in later versions of SimpleTest.
+ </p>
+ <p>
+ Frames are a rather esoteric feature these days, but SimpleTest has
+ retained support for them.
+ </p>
+ <p>
+ 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.
+ <table><tbody>
+ <tr>
+<td><span class="new_code">getFrames()</span></td>
+<td>A dump of the current frame structure</td>
+</tr>
+ <tr>
+<td><span class="new_code">getFrameFocus()</span></td>
+<td>Current frame label or index</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFrameFocusByIndex($choice)</span></td>
+<td>Select a frame numbered from 1</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFrameFocus($name)</span></td>
+<td>Select frame by label</td>
+</tr>
+ <tr>
+<td><span class="new_code">clearFrameFocus()</span></td>
+<td>Treat all the frames as a single page</td>
+</tr>
+ </tbody></table>
+ When focused on a single frame, the content will come from
+ that frame only.
+ This includes links to click and forms to submit.
+ </p>
+
+ <h2>
+<a class="target" name="debug"></a>What went wrong?</h2>
+ <p>
+ 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...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">setConnectionTimeout($timeout)</span></td>
+<td>Close the socket on overrun</td>
+</tr>
+ <tr>
+<td><span class="new_code">getUrl()</span></td>
+<td>Url of most recent page fetched</td>
+</tr>
+ <tr>
+<td><span class="new_code">getRequest()</span></td>
+<td>Raw request header of page or frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">getHeaders()</span></td>
+<td>Raw response header of page or frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">getTransportError()</span></td>
+<td>Any socket level errors in the last fetch</td>
+</tr>
+ <tr>
+<td><span class="new_code">getResponseCode()</span></td>
+<td>HTTP response of page or frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">getMimeType()</span></td>
+<td>Mime type of page or frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">getAuthentication()</span></td>
+<td>Authentication type in 401 challenge header</td>
+</tr>
+ <tr>
+<td><span class="new_code">getRealm()</span></td>
+<td>Authentication realm in 401 challenge header</td>
+</tr>
+ <tr>
+<td><span class="new_code">getBaseUrl()</span></td>
+<td>Base url only of most recent page fetched</td>
+</tr>
+ <tr>
+<td><span class="new_code">setMaximumRedirects($max)</span></td>
+<td>Number of redirects before page is loaded anyway</td>
+</tr>
+ <tr>
+<td><span class="new_code">setMaximumNestedFrames($max)</span></td>
+<td>Protection against recursive framesets</td>
+</tr>
+ <tr>
+<td><span class="new_code">ignoreFrames()</span></td>
+<td>Disables frames support</td>
+</tr>
+ <tr>
+<td><span class="new_code">useFrames()</span></td>
+<td>Enables frames support</td>
+</tr>
+ <tr>
+<td><span class="new_code">ignoreCookies()</span></td>
+<td>Disables sending and receiving of cookies</td>
+</tr>
+ <tr>
+<td><span class="new_code">useCookies()</span></td>
+<td>Enables cookie support</td>
+</tr>
+ </tbody></table>
+ The methods <span class="new_code">SimpleBrowser::setConnectionTimeout()</span>
+ <span class="new_code">SimpleBrowser::setMaximumRedirects()</span>,
+ <span class="new_code">SimpleBrowser::setMaximumNestedFrames()</span>,
+ <span class="new_code">SimpleBrowser::ignoreFrames()</span>,
+ <span class="new_code">SimpleBrowser::useFrames()</span>,
+ <span class="new_code">SimpleBrowser::ignoreCookies()</span> and
+ <span class="new_code">SimpleBrowser::useCokies()</span> 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 <span class="new_code">SimpleBrowser::setFrameFocus()</span>
+ and you can then use <span class="new_code">SimpleBrowser::getRequest()</span>, etc to
+ see what happened.
+ </p>
+
+ <h2>
+<a class="target" name="unit"></a>Complex unit tests with multiple browsers</h2>
+ <p>
+ Anything that could be done in a
+ <a href="web_tester_documentation.html">WebTestCase</a> can
+ now be done in a <a href="unit_tester_documentation.html">UnitTestCase</a>.
+ This means that we could freely mix domain object testing with the
+ web interface...
+<pre>
+<strong>class TestOfRegistration extends UnitTestCase {
+ function testNewUserAddedToAuthenticator() {</strong>
+ $browser = new SimpleBrowser();
+ $browser-&gt;get('http://my-site.com/register.php');
+ $browser-&gt;setField('email', 'me@here');
+ $browser-&gt;setField('password', 'Secret');
+ $browser-&gt;click('Register');
+ <strong>
+ $authenticator = new Authenticator();
+ $member = $authenticator-&gt;findByEmail('me@here');
+ $this-&gt;assertEqual($member-&gt;getPassword(), 'Secret');
+ }
+}</strong>
+</pre>
+ 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.
+ </p>
+ <p>
+ A more useful case of where using the browser directly can be helpful
+ is where the <span class="new_code">WebTestCase</span> cannot cope.
+ An example is where two browsers are needed at the same time.
+ </p>
+ <p>
+ For example, say we want to disallow multiple simultaneous
+ usage of a site with the same username.
+ This test case will do the job...
+<pre>
+class TestOfSecurity extends UnitTestCase {
+ function testNoMultipleLoginsFromSameUser() {<strong>
+ $first_attempt = new SimpleBrowser();
+ $first_attempt-&gt;get('http://my-site.com/login.php');
+ $first_attempt-&gt;setField('name', 'Me');
+ $first_attempt-&gt;setField('password', 'Secret');
+ $first_attempt-&gt;click('Enter');
+ $this-&gt;assertEqual($first_attempt-&gt;getTitle(), 'Welcome');
+
+ $second_attempt = new SimpleBrowser();
+ $second_attempt-&gt;get('http://my-site.com/login.php');
+ $second_attempt-&gt;setField('name', 'Me');
+ $second_attempt-&gt;setField('password', 'Secret');
+ $second_attempt-&gt;click('Enter');
+ $this-&gt;assertEqual($second_attempt-&gt;getTitle(), 'Access Denied');</strong>
+ }
+}
+</pre>
+ You can also use the <span class="new_code">SimpleBrowser</span> class
+ directly when you want to write test cases using a different
+ test tool than SimpleTest, such as PHPUnit.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ The <a href="http://simpletest.org/api/">developer's API for SimpleTest</a>
+ gives full detail on the classes and assertions available.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <span class="chosen">Scriptable browser</span>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/en/docs.css b/3rdparty/simpletest/docs/en/docs.css
new file mode 100755
index 00000000000..18368a04f7a
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/docs.css
@@ -0,0 +1,121 @@
+body {
+ padding-left: 3%;
+ padding-right: 3%;
+}
+h1, h2, h3 {
+ font-family: sans-serif;
+}
+h1 {
+ text-align: center;
+}
+pre {
+ font-family: "courier new", courier, typewriter, monospace;
+ font-size: 90%;
+ border: 1px solid;
+ border-color: #999966;
+ background-color: #ffffcc;
+ padding: 5px;
+ margin-left: 20px;
+ margin-right: 40px;
+}
+.code, .new_code, pre.new_code {
+ font-family: "courier new", courier, typewriter, monospace;
+ font-weight: bold;
+}
+div.copyright {
+ font-size: 80%;
+ color: gray;
+}
+div.copyright a {
+ margin-top: 1em;
+ color: gray;
+}
+ul.api {
+ border: 2px outset;
+ border-color: gray;
+ background-color: white;
+ margin: 5px;
+ margin-left: 5%;
+ margin-right: 5%;
+}
+ul.api li {
+ margin-top: 0.2em;
+ margin-bottom: 0.2em;
+ list-style: none;
+ text-indent: -3em;
+ padding-left: 1em;
+}
+div.demo {
+ border: 4px ridge;
+ border-color: gray;
+ padding: 10px;
+ margin: 5px;
+ margin-left: 20px;
+ margin-right: 40px;
+ background-color: white;
+}
+div.demo span.fail {
+ color: red;
+}
+div.demo span.pass {
+ color: green;
+}
+div.demo h1 {
+ font-size: 12pt;
+ text-align: left;
+ font-weight: bold;
+}
+div.menu {
+ text-align: center;
+}
+table {
+ border: 2px outset;
+ border-color: gray;
+ background-color: white;
+ margin: 5px;
+ margin-left: 5%;
+ margin-right: 5%;
+}
+td {
+ font-size: 90%;
+}
+.shell {
+ color: white;
+}
+pre.shell {
+ border: 4px ridge;
+ border-color: gray;
+ padding: 10px;
+ margin: 5px;
+ margin-left: 20px;
+ margin-right: 40px;
+ background-color: #000100;
+ color: #99ff99;
+ font-size: 90%;
+}
+pre.file {
+ color: black;
+ border: 1px solid;
+ border-color: black;
+ padding: 10px;
+ margin: 5px;
+ margin-left: 20px;
+ margin-right: 40px;
+ background-color: white;
+ font-size: 90%;
+}
+form.demo {
+ background-color: lightgray;
+ border: 4px outset;
+ border-color: lightgray;
+ padding: 10px;
+ margin-right: 40%;
+}
+dl, dd {
+ margin: 10px;
+ margin-left: 30px;
+}
+em {
+ font-weight: bold;
+ font-family: "courier new", courier, typewriter, monospace;
+}
diff --git a/3rdparty/simpletest/docs/en/expectation_documentation.html b/3rdparty/simpletest/docs/en/expectation_documentation.html
new file mode 100644
index 00000000000..26704d5ae83
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/expectation_documentation.html
@@ -0,0 +1,476 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>
+ Extending the SimpleTest unit tester with additional expectation classes
+ </title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <span class="chosen">Expectations</span>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Expectation documentation</h1>
+ This page...
+ <ul>
+<li>
+ Using expectations for
+ <a href="#mock">more precise testing with mock objects</a>
+ </li>
+<li>
+ <a href="#behaviour">Changing mock object behaviour</a> with expectations
+ </li>
+<li>
+ <a href="#extending">Extending the expectations</a>
+ </li>
+<li>
+ Underneath SimpleTest <a href="#unit">uses expectation classes</a>
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="mock"></a>More control over mock objects</h2>
+ <p>
+ The default behaviour of the
+ <a href="mock_objects_documentation.html">mock objects</a>
+ in
+ <a href="http://sourceforge.net/projects/simpletest/">SimpleTest</a>
+ 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.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ For example, suppose we have a news service that has failed
+ to connect to its remote source.
+<pre>
+<strong>class NewsService {
+ ...
+ function publish($writer) {
+ if (! $this-&gt;isConnected()) {
+ $writer-&gt;write('Cannot connect to news service "' .
+ $this-&gt;_name . '" at this time. ' .
+ 'Please try again later.');
+ }
+ ...
+ }
+}</strong>
+</pre>
+ Here it is sending its content to a
+ <span class="new_code">Writer</span> class.
+ We could test this behaviour with a
+ <span class="new_code">MockWriter</span> like so...
+<pre>
+class TestOfNewsService extends UnitTestCase {
+ ...
+ function testConnectionFailure() {<strong>
+ $writer = new MockWriter();
+ $writer-&gt;expectOnce('write', array(
+ 'Cannot connect to news service ' .
+ '"BBC News" at this time. ' .
+ 'Please try again later.'));
+
+ $service = new NewsService('BBC News');
+ $service-&gt;publish($writer);</strong>
+ }
+}
+</pre>
+ 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.
+ </p>
+ <p>
+ To get around this, we would like to do a regular expression
+ test rather than an exact match.
+ We can actually do this with...
+<pre>
+class TestOfNewsService extends UnitTestCase {
+ ...
+ function testConnectionFailure() {
+ $writer = new MockWriter();<strong>
+ $writer-&gt;expectOnce(
+ 'write',
+ array(new PatternExpectation('/cannot connect/i')));</strong>
+
+ $service = new NewsService('BBC News');
+ $service-&gt;publish($writer);
+ }
+}
+</pre>
+ Instead of passing in the expected parameter to the
+ <span class="new_code">MockWriter</span> we pass an
+ expectation class called
+ <span class="new_code">PatternExpectation</span>.
+ 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.
+ </p>
+ <p>
+ The <span class="new_code">PatternExpectation</span> takes
+ the regular expression to match in its constructor.
+ Whenever a comparison is made by the <span class="new_code">MockWriter</span>
+ against this expectation class, it will do a
+ <span class="new_code">preg_match()</span> 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.
+ </p>
+ <p>
+ The possible expectation classes are...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">AnythingExpectation</span></td>
+<td>Will always match</td>
+</tr>
+ <tr>
+<td><span class="new_code">EqualExpectation</span></td>
+<td>An equality, rather than the stronger identity comparison</td>
+</tr>
+ <tr>
+<td><span class="new_code">NotEqualExpectation</span></td>
+<td>An inequality comparison</td>
+</tr>
+ <tr>
+<td><span class="new_code">IndenticalExpectation</span></td>
+<td>The default mock object check which must match exactly</td>
+</tr>
+ <tr>
+<td><span class="new_code">NotIndenticalExpectation</span></td>
+<td>Inverts the mock object logic</td>
+</tr>
+ <tr>
+<td><span class="new_code">WithinMarginExpectation</span></td>
+<td>Compares a value to within a margin</td>
+</tr>
+ <tr>
+<td><span class="new_code">OutsideMarginExpectation</span></td>
+<td>Checks that a value is out side the margin</td>
+</tr>
+ <tr>
+<td><span class="new_code">PatternExpectation</span></td>
+<td>Uses a Perl Regex to match a string</td>
+</tr>
+ <tr>
+<td><span class="new_code">NoPatternExpectation</span></td>
+<td>Passes only if failing a Perl Regex</td>
+</tr>
+ <tr>
+<td><span class="new_code">IsAExpectation</span></td>
+<td>Checks the type or class name only</td>
+</tr>
+ <tr>
+<td><span class="new_code">NotAExpectation</span></td>
+<td>Opposite of the <span class="new_code">IsAExpectation</span>
+</td>
+</tr>
+ <tr>
+<td><span class="new_code">MethodExistsExpectation</span></td>
+<td>Checks a method is available on an object</td>
+</tr>
+ <tr>
+<td><span class="new_code">TrueExpectation</span></td>
+<td>Accepts any PHP variable that evaluates to true</td>
+</tr>
+ <tr>
+<td><span class="new_code">FalseExpectation</span></td>
+<td>Accepts any PHP variable that evaluates to false</td>
+</tr>
+ </tbody></table>
+ Most take the expected value in the constructor.
+ The exceptions are the pattern matchers, which take a regular expression,
+ and the <span class="new_code">IsAExpectation</span> and <span class="new_code">NotAExpectation</span> which takes a type
+ or class name as a string.
+ </p>
+ <p>
+ Some examples...
+ </p>
+ <p>
+<pre>
+$mock-&gt;expectOnce('method', array(new IdenticalExpectation(14)));
+</pre>
+ This is the same as <span class="new_code">$mock-&gt;expectOnce('method', array(14))</span>.
+<pre>
+$mock-&gt;expectOnce('method', array(new EqualExpectation(14)));
+</pre>
+ This is different from the previous version in that the string
+ <span class="new_code">"14"</span> as a parameter will also pass.
+ Sometimes the additional type checks of SimpleTest are too restrictive.
+<pre>
+$mock-&gt;expectOnce('method', array(new AnythingExpectation(14)));
+</pre>
+ This is the same as <span class="new_code">$mock-&gt;expectOnce('method', array('*'))</span>.
+<pre>
+$mock-&gt;expectOnce('method', array(new IdenticalExpectation('*')));
+</pre>
+ This is handy if you want to assert a literal <span class="new_code">"*"</span>.
+<pre>
+new NotIdenticalExpectation(14)
+</pre>
+ This matches on anything other than integer 14.
+ Even the string <span class="new_code">"14"</span> would pass.
+<pre>
+new WithinMarginExpectation(14.0, 0.001)
+</pre>
+ This will accept any value from 13.999 to 14.001 inclusive.
+ </p>
+
+ <h2>
+<a class="target" name="behaviour"></a>Using expectations to control stubs</h2>
+ <p>
+ The expectation classes can be used not just for sending assertions
+ from mock objects, but also for selecting behaviour for the
+ <a href="mock_objects_documentation.html">mock objects</a>.
+ Anywhere a list of arguments is given, a list of expectation objects
+ can be inserted instead.
+ </p>
+ <p>
+ Suppose we want a mock authorisation server to simulate a successful login,
+ but only if it receives a valid session object.
+ We can do this as follows...
+<pre>
+Mock::generate('Authorisation');
+<strong>
+$authorisation = new MockAuthorisation();
+$authorisation-&gt;returns(
+ 'isAllowed',
+ true,
+ array(new IsAExpectation('Session', 'Must be a session')));
+$authorisation-&gt;returns('isAllowed', false);</strong>
+</pre>
+ We have set the default mock behaviour to return false when
+ <span class="new_code">isAllowed</span> is called.
+ When we call the method with a single parameter that
+ is a <span class="new_code">Session</span> 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.
+ </p>
+ <p>
+ This kind of sophistication is rarely useful, but is included for
+ completeness.
+ </p>
+
+ <h2>
+<a class="target" name="extending"></a>Creating your own expectations</h2>
+ <p>
+ The expectation classes have a very simple structure.
+ So simple that it is easy to create your own versions for
+ commonly used test logic.
+ </p>
+ <p>
+ 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
+ <span class="new_code">SimpleExpectation</span> or further extend a subclass...
+<pre>
+<strong>class ValidIp extends SimpleExpectation {
+
+ function test($ip) {
+ return (ip2long($ip) != -1);
+ }
+
+ function testMessage($ip) {
+ return "Address [$ip] should be a valid IP address";
+ }
+}</strong>
+</pre>
+ There are only two methods to implement.
+ The <span class="new_code">test()</span> method should
+ evaluate to true if the expectation is to pass, and
+ false otherwise.
+ The <span class="new_code">testMessage()</span> method
+ should simply return some helpful text explaining the test
+ that was carried out.
+ </p>
+ <p>
+ This class can now be used in place of the earlier expectation
+ classes.
+ </p>
+ <p>
+ Here is a more typical example, matching part of a hash...
+<pre>
+<strong>class JustField extends EqualExpectation {
+ private $key;
+
+ function __construct($key, $expected) {
+ parent::__construct($expected);
+ $this-&gt;key = $key;
+ }
+
+ function test($compare) {
+ if (! isset($compare[$this-&gt;key])) {
+ return false;
+ }
+ return parent::test($compare[$this-&gt;key]);
+ }
+
+ function testMessage($compare) {
+ if (! isset($compare[$this-&gt;key])) {
+ return 'Key [' . $this-&gt;key . '] does not exist';
+ }
+ return 'Key [' . $this-&gt;key . '] -&gt; ' .
+ parent::testMessage($compare[$this-&gt;key]);
+ }
+}</strong>
+</pre>
+ We tend to seperate message clauses with
+ "&amp;nbsp;-&gt;&amp;nbsp;".
+ This allows derivative tools to reformat the output.
+ </p>
+ <p>
+ Suppose some authenticator is expecting to be given
+ a database row corresponding to the user, and we
+ only need to confirm the username is correct.
+ We can assert just their username with...
+<pre>
+$mock-&gt;expectOnce('authenticate',
+ array(new JustKey('username', 'marcus')));
+</pre>
+ </p>
+
+ <h2>
+<a class="target" name="unit"></a>Under the bonnet of the unit tester</h2>
+ <p>
+ The <a href="http://sourceforge.net/projects/simpletest/">SimpleTest unit testing framework</a>
+ also uses the expectation classes internally for the
+ <a href="unit_test_documentation.html">UnitTestCase class</a>.
+ We can also take advantage of these mechanisms to reuse our
+ homebrew expectation classes within the test suites directly.
+ </p>
+ <p>
+ The most crude way of doing this is to use the generic
+ <span class="new_code">SimpleTest::assert()</span> method to
+ test against it directly...
+<pre>
+<strong>class TestOfNetworking extends UnitTestCase {
+ ...
+ function testGetValidIp() {
+ $server = &amp;new Server();
+ $this-&gt;assert(
+ new ValidIp(),
+ $server-&gt;getIp(),
+ 'Server IP address-&gt;%s');
+ }
+}</strong>
+</pre>
+ <span class="new_code">assert()</span> will test any expectation class directly.
+ </p>
+ <p>
+ This is a little untidy compared with our usual
+ <span class="new_code">assert...()</span> syntax.
+ </p>
+ <p>
+ 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...
+<pre>
+class TestOfNetworking extends UnitTestCase {
+ ...<strong>
+ function assertValidIp($ip, $message = '%s') {
+ $this-&gt;assert(new ValidIp(), $ip, $message);
+ }</strong>
+
+ function testGetValidIp() {
+ $server = &amp;new Server();<strong>
+ $this-&gt;assertValidIp(
+ $server-&gt;getIp(),
+ 'Server IP address-&gt;%s');</strong>
+ }
+}
+</pre>
+ It is rare to need the expectations for more than pattern
+ matching, but these facilities do allow testers to build
+ some sort of domain language for testing their application.
+ Also, complex expectation classes could make the tests
+ harder to read and debug.
+ In effect extending the test framework to create their own tool set.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ The expectations mimic the constraints in <a href="http://www.jmock.org/">JMock</a>.
+ </li>
+<li>
+ <a href="http://simpletest.org/api/">Full API for SimpleTest</a>
+ from the PHPDoc.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <span class="chosen">Expectations</span>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/en/form_testing_documentation.html b/3rdparty/simpletest/docs/en/form_testing_documentation.html
new file mode 100644
index 00000000000..328735c9dca
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/form_testing_documentation.html
@@ -0,0 +1,351 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest documentation for testing HTML forms</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <span class="chosen">Testing forms</span>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Form testing documentation</h1>
+ This page...
+ <ul>
+<li>
+ Changing form values and successfully
+ <a href="#submit">Submitting a simple form</a>
+ </li>
+<li>
+ Handling <a href="#multiple">widgets with multiple values</a>
+ by setting lists.
+ </li>
+<li>
+ Bypassing javascript to <a href="#hidden-field">set a hidden field</a>.
+ </li>
+<li>
+ <a href="#raw">Raw posting</a> when you don't have a button
+ to click.
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="submit"></a>Submitting a simple form</h2>
+ <p>
+ When a page is fetched by the <span class="new_code">WebTestCase</span>
+ using <span class="new_code">get()</span> or
+ <span class="new_code">post()</span> the page content is
+ automatically parsed.
+ This results in any form controls that are inside &lt;form&gt; tags
+ being available from within the test case.
+ For example, if we have this snippet of HTML...
+<pre>
+&lt;form&gt;
+ &lt;input type="text" name="a" value="A default" /&gt;
+ &lt;input type="submit" value="Go" /&gt;
+&lt;/form&gt;
+</pre>
+ Which looks like this...
+ </p>
+ <p>
+ <form class="demo">
+ <input type="text" name="a" value="A default">
+ <input type="submit" value="Go">
+ </form>
+ </p>
+ <p>
+ We can navigate to this code, via the
+ <a href="http://www.lastcraft.com/form_testing_documentation.php">LastCraft</a>
+ site, with the following test...
+<pre>
+class SimpleFormTests extends WebTestCase {<strong>
+ function testDefaultValue() {
+ $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this-&gt;assertField('a', 'A default');
+ }</strong>
+}
+</pre>
+ 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".
+ As usual, we could use a pattern expectation instead of a fixed
+ string.
+<pre>
+class SimpleFormTests extends WebTestCase {
+ function testDefaultValue() {
+ $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this-&gt;assertField('a', <strong>new PatternExpectation('/default/')</strong>);
+ }
+}
+</pre>
+ We could submit the form straight away, but first we'll change
+ the value of the text field and only then submit it...
+<pre>
+class SimpleFormTests extends WebTestCase {
+ function testDefaultValue() {
+ $this-&gt;get('http://www.my-site.com/');
+ $this-&gt;assertField('a', 'A default');<strong>
+ $this-&gt;setField('a', 'New value');
+ $this-&gt;click('Go');</strong>
+ }
+}
+</pre>
+ 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 <em>GET</em>
+ request back to the same location.
+ In general SimpleTest tries to emulate typical browser behaviour as much as possible,
+ rather than attempting to catch any form of HTML omission.
+ 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
+ <a href="http://www.w3.org/People/Raggett/tidy/">HTMLTidy</a> should be used,
+ or any of the HTML and CSS validators already out there.
+ </p>
+ <p>
+ If a field is not present in any form, or if an option is unavailable,
+ then <span class="new_code">WebTestCase::setField()</span> will return
+ <span class="new_code">false</span>.
+ For example, suppose we wish to verify that a "Superuser"
+ option is not present in this form...
+<pre>
+&lt;strong&gt;Select type of user to add:&lt;/strong&gt;
+&lt;select name="type"&gt;
+ &lt;option&gt;Subscriber&lt;/option&gt;
+ &lt;option&gt;Author&lt;/option&gt;
+ &lt;option&gt;Administrator&lt;/option&gt;
+&lt;/select&gt;
+</pre>
+ Which looks like...
+ </p>
+ <p>
+ <form class="demo">
+ <strong>Select type of user to add:</strong>
+ <select name="type">
+ <option>Subscriber</option>
+ <option>Author</option>
+ <option>Administrator</option>
+ </select>
+ </form>
+ </p>
+ <p>
+ The following test will confirm it...
+<pre>
+class SimpleFormTests extends WebTestCase {
+ ...
+ function testNoSuperuserChoiceAvailable() {<strong>
+ $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this-&gt;assertFalse($this-&gt;setField('type', 'Superuser'));</strong>
+ }
+}
+</pre>
+ The current selection will not be changed if the new value is not an option.
+ </p>
+ <p>
+ Here is the full list of widgets currently supported...
+ <ul>
+ <li>Text fields, including hidden and password fields.</li>
+ <li>Submit buttons including the button tag, although not yet reset buttons</li>
+ <li>Text area. This includes text wrapping behaviour.</li>
+ <li>Checkboxes, including multiple checkboxes in the same form.</li>
+ <li>Drop down selections, including multiple selects.</li>
+ <li>Radio buttons.</li>
+ <li>Images.</li>
+ </ul>
+ </p>
+ <p>
+ The browser emulation offered by SimpleTest mimics
+ the actions which can be perform by a user on a
+ standard HTML page. Javascript is not supported, and
+ it's unlikely that support will be added any time
+ soon.
+ </p>
+ <p>
+ Of particular note is that the Javascript idiom of
+ passing form results by setting a hidden field cannot
+ be performed using the normal SimpleTest
+ commands. See below for a way to test such forms.
+ </p>
+
+ <h2>
+<a class="target" name="multiple"></a>Fields with multiple values</h2>
+ <p>
+ 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...
+<pre>
+&lt;form class="demo"&gt;
+ &lt;strong&gt;Create privileges allowed:&lt;/strong&gt;
+ &lt;input type="checkbox" name="crud" value="c" checked&gt;&lt;br&gt;
+ &lt;strong&gt;Retrieve privileges allowed:&lt;/strong&gt;
+ &lt;input type="checkbox" name="crud" value="r" checked&gt;&lt;br&gt;
+ &lt;strong&gt;Update privileges allowed:&lt;/strong&gt;
+ &lt;input type="checkbox" name="crud" value="u" checked&gt;&lt;br&gt;
+ &lt;strong&gt;Destroy privileges allowed:&lt;/strong&gt;
+ &lt;input type="checkbox" name="crud" value="d" checked&gt;&lt;br&gt;
+ &lt;input type="submit" value="Enable Privileges"&gt;
+&lt;/form&gt;
+</pre>
+ Which renders as...
+ </p>
+ <p>
+ <form class="demo">
+ <strong>Create privileges allowed:</strong>
+ <input type="checkbox" name="crud" value="c" checked><br>
+ <strong>Retrieve privileges allowed:</strong>
+ <input type="checkbox" name="crud" value="r" checked><br>
+ <strong>Update privileges allowed:</strong>
+ <input type="checkbox" name="crud" value="u" checked><br>
+ <strong>Destroy privileges allowed:</strong>
+ <input type="checkbox" name="crud" value="d" checked><br>
+ <input type="submit" value="Enable Privileges">
+ </form>
+ </p>
+ <p>
+ If we wish to disable all but the retrieval privileges and
+ submit this information we can do it like this...
+<pre>
+class SimpleFormTests extends WebTestCase {
+ ...<strong>
+ function testDisableNastyPrivileges() {
+ $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this-&gt;assertField('crud', array('c', 'r', 'u', 'd'));
+ $this-&gt;setField('crud', array('r'));
+ $this-&gt;click('Enable Privileges');
+ }</strong>
+}
+</pre>
+ 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.
+ </p>
+
+ <h2>
+<a class="target" name="hidden-field"></a>Forms which use javascript to set a hidden field</h2>
+ <p>
+ If you want to test a form which relies on javascript to set a hidden
+ field, you can't just call setField().
+ The following code will <em>not</em> work:
+<pre>
+class SimpleFormTests extends WebTestCase {
+ function testEmulateMyJavascriptForm() {
+ <strong>// This does *not* work</strong>
+ $this-&gt;setField('a_hidden_field', '123');
+ $this-&gt;clickSubmit('OK');
+ }
+}
+</pre>
+ Instead, you need to pass the additional form parameters to the
+ clickSubmit() method:
+<pre>
+class SimpleFormTests extends WebTestCase {
+ function testMyJavascriptForm() {
+ <strong>$this-&gt;clickSubmit('OK', array('a_hidden_field'=&gt;'123'));</strong>
+ }
+
+}
+</pre>
+ Bear in mind that in doing this you're effectively stubbing out a
+ part of your software (the javascript code in the form), and
+ perhaps you might be better off using something like
+ <a href="http://selenium.openqa.org/">Selenium</a> to ensure a complete
+ test.
+ </p>
+
+ <h2>
+<a class="target" name="raw"></a>Raw posting</h2>
+ <p>
+ 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.
+<pre>
+class SimpleFormTests extends WebTestCase {
+ ...<strong>
+ function testAttemptedHack() {
+ $this-&gt;post(
+ 'http://www.my-site.com/add_user.php',
+ array('type' =&gt; 'superuser'));
+ $this-&gt;assertNoText('user created');
+ }</strong>
+}
+</pre>
+ By adding data to the <span class="new_code">WebTestCase::post()</span>
+ method, we are emulating a form submission.
+ You would normally only do this as a temporary expedient, or where
+ you are expecting a 3rd party to submit to a form.
+ The exception is when you want tests to protect you from
+ attempts to spoof your pages.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ The <a href="http://simpletest.org/api/">developer's API for SimpleTest</a>
+ gives full detail on the classes and assertions available.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <span class="chosen">Testing forms</span>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/en/group_test_documentation.html b/3rdparty/simpletest/docs/en/group_test_documentation.html
new file mode 100644
index 00000000000..10f22a2b1b9
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/group_test_documentation.html
@@ -0,0 +1,252 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest for PHP test suites</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <span class="chosen">Group tests</span>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Test suite documentation</h1>
+ This page...
+ <ul>
+<li>
+ Different ways to <a href="#group">group tests</a> together.
+ </li>
+<li>
+ Combining group tests into <a href="#higher">larger groups</a>.
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="group"></a>Grouping tests into suites</h2>
+ <p>
+ There are many ways to group tests together into test suites.
+ One way is to simply place multiple test cases into a single file...
+<pre>
+<strong>&lt;?php
+require_once(dirname(__FILE__) . '/simpletest/autorun.php');
+require_once(dirname(__FILE__) . '/../classes/io.php');
+
+class FileTester extends UnitTestCase {
+ ...
+}
+
+class SocketTester extends UnitTestCase {
+ ...
+}
+?&gt;</strong>
+</pre>
+ 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 need none of the SimpleTest libraries.
+ </p>
+ <p>
+ Occasionally special subclasses are created that methods useful
+ for testing part of the application.
+ These new base classes are then used in place of <span class="new_code">UnitTestCase</span>
+ or <span class="new_code">WebTestCase</span>.
+ You don't normally want to run these as test cases.
+ Simply mark any base test cases that should not be run as abstract...
+<pre>
+<strong>abstract</strong> class MyFileTestCase extends UnitTestCase {
+ ...
+}
+
+class FileTester extends MyFileTestCase { ... }
+
+class SocketTester extends UnitTestCase { ... }
+</pre>
+ Here the <span class="new_code">FileTester</span> class does
+ not contain any actual tests, but is the base class for other
+ test cases.
+ </p>
+ <p>
+ We will call this sample <em>file_test.php</em>.
+ Currently the test cases are grouped simply by being in the same file.
+ We can build larger constructs just by including other test files in.
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('file_test.php');
+?&gt;
+</pre>
+ This will work, but create a purely flat hierarchy.
+ INstead we create a test suite file.
+ Our top level test suite can look like this...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+class AllFileTests extends TestSuite {
+ function __construct() {
+ parent::__construct();
+ <strong>$this-&gt;addFile('file_test.php');</strong>
+ }
+}
+?&gt;
+</pre>
+ What happens here is that the <span class="new_code">TestSuite</span>
+ class will do the <span class="new_code">require_once()</span>
+ for us.
+ It then checks to see if any new test case classes
+ have been created by the new file and automatically composes
+ them to the test suite.
+ This method gives us the most control as we just manually add
+ more test files as our test suite grows.
+ </p>
+ <p>
+ If this is too much typing, and you are willing to group
+ test suites together in their own directories or otherwise
+ tag the file names, then there is a more automatic way...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+class AllFileTests extends TestSuite {
+ function __construct() {
+ parent::__construct();
+ $this-&gt;collect(dirname(__FILE__) . '/unit',
+ new SimplePatternCollector('/_test.php/'));
+ }
+}
+?&gt;
+</pre>
+ This will scan a directory called "unit" for any files
+ ending with "_test.php" and load them.
+ You don't have to use <span class="new_code">SimplePatternCollector</span> to
+ filter by a pattern in the filename, but this is the most common
+ usage.
+ </p>
+ <p>
+ That snippet above is very common in practice.
+ Now all you have to do is drop a file of test cases into the
+ directory and it will run just by running the test suite script.
+ </p>
+ <p>
+ The catch is that you cannot control the order in which the test
+ cases are run.
+ If you want to see lower level components fail first in the test suite,
+ and this will make diagnosis a lot easier, then you should manually
+ call <span class="new_code">addFile()</span> for these.
+ Tests cases are only loaded once, so it's fine to have these included
+ again by a directory scan.
+ </p>
+ <p>
+ Test cases loaded with the <span class="new_code">addFile</span> method have some
+ useful properties.
+ You can guarantee that the constructor is run
+ just before the first test method and the destructor
+ is run just after the last test method.
+ This allows you to place test case wide set up and tear down
+ code in the constructor and destructor, just like a normal
+ class.
+ </p>
+
+ <h2>
+<a class="target" name="higher"></a>Composite suites</h2>
+ <p>
+ The above method places all of the test cases into one large suite.
+ For larger projects though this may not be flexible enough; you
+ may want to group the tests together in all sorts of ways.
+ </p>
+ <p>
+ Everything we have described so far with test scripts applies to
+ <span class="new_code">TestSuite</span>s as well...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+<strong>
+class BigTestSuite extends TestSuite {
+ function __construct() {
+ parent::__construct();
+ $this-&gt;addFile('file_tests.php');
+ }
+}</strong>
+?&gt;
+</pre>
+ This effectively adds our test cases and a single suite below
+ the first.
+ When a test fails, we see the breadcrumb trail of the nesting.
+ We can even mix groups and test cases freely as long as
+ we are careful about loops in our includes.
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+class BigTestSuite extends TestSuite {
+ function __construct() {
+ parent::__construct();
+ $this-&gt;addFile('file_tests.php');
+ <strong>$this-&gt;addFile('some_other_test.php');</strong>
+ }
+}
+?&gt;
+</pre>
+ Note that in the event of a double include, ony the first instance
+ of the test case will be run.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <span class="chosen">Group tests</span>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/en/index.html b/3rdparty/simpletest/docs/en/index.html
new file mode 100644
index 00000000000..9f022d6b10b
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/index.html
@@ -0,0 +1,542 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>
+ Download the SimpleTest testing framework -
+ Unit tests and mock objects for PHP
+ </title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<span class="chosen">SimpleTest</span>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>SimpleTest for PHP</h1>
+ This page...
+ <ul>
+<li>
+ <a href="#unit">Using unit tester</a>
+ with an example.
+ </li>
+<li>
+ <a href="#group">Grouping tests</a>
+ for testing with one click.
+ </li>
+<li>
+ <a href="#mock">Using mock objects</a>
+ to ease testing and gain tighter control.
+ </li>
+<li>
+ <a href="#web">Testing web pages</a>
+ at the browser level.
+ </li>
+</ul>
+<div class="content">
+
+
+ <p>
+ 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
+ <a href="https://sourceforge.net/project/showfiles.php?group_id=76550">SimpleTest</a>.
+ For fuller documentation, especially if you are new
+ to unit testing see the ongoing
+ <a href="unit_test_documentation.html">documentation</a>, and for
+ example test cases see the
+ <a href="http://www.lastcraft.com/first_test_tutorial.php">unit testing tutorial</a>.
+ </p>
+
+ <h2>
+<a class="target" name="unit"></a>Using the tester quickly</h2>
+ <p>
+ 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
+ <a href="http://www.junit.org/">JUnit</a> and the
+ <a href="http://sourceforge.net/projects/phpunit/">PHPUnit</a>
+ ports, and includes
+ <a href="http://www.mockobjects.com">mock objects</a>.
+ </p>
+ <p>
+ What makes this tool immediately useful to the PHP developer is the internal
+ web browser.
+ This allows tests that navigate web sites, fill in forms and test pages.
+ Being able to write these test in PHP means that it is easy to write
+ integrated tests.
+ An example might be confirming that a user was written to a database
+ after a signing up through the web site.
+ </p>
+ <p>
+ The quickest way to demonstrate SimpleTest is with an example.
+ </p>
+ <p>
+ Let us suppose we are testing a simple file logging class called
+ <span class="new_code">Log</span> in <em>classes/log.php</em>.
+ We start by creating a test script which we will call
+ <em>tests/log_test.php</em> and populate it as follows...
+<pre>
+&lt;?php
+<strong>require_once('simpletest/autorun.php');</strong>
+require_once('../classes/log.php');
+
+class TestOfLogging extends <strong>UnitTestCase</strong> {
+}
+?&gt;
+</pre>
+ Here the <em>simpletest</em> folder is either local or in the path.
+ You would have to edit these locations depending on where you
+ unpacked the toolset.
+ The "autorun.php" file does more than just include the
+ SimpleTest files, it also runs our test for us.
+ </p>
+ <p>
+ The <span class="new_code">TestOfLogging</span> is our first test case and it's
+ currently empty.
+ Each test case is a class that extends one of the SimpleTet base classes
+ and we can have as many of these in the file as we want.
+ </p>
+ <p>
+ With three lines of scaffolding, and our <span class="new_code">Log</span> class
+ include, we have a test suite.
+ No tests though.
+ </p>
+ <p>
+ For our first test, we'll assume that the <span class="new_code">Log</span> class
+ takes the file name to write to in the constructor, and we have
+ a temporary folder in which to place this file...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('../classes/log.php');
+
+class TestOfLogging extends UnitTestCase {
+ function <strong>testLogCreatesNewFileOnFirstMessage()</strong> {
+ @unlink('/temp/test.log');
+ $log = new Log('/temp/test.log');
+ <strong>$this-&gt;assertFalse(file_exists('/temp/test.log'));</strong>
+ $log-&gt;message('Should write this to a file');
+ <strong>$this-&gt;assertTrue(file_exists('/temp/test.log'));</strong>
+ }
+}
+?&gt;
+</pre>
+ When a test case runs, it will search for any method that
+ starts with the string "test"
+ and execute that method.
+ If the method starts "test", it's a test.
+ Note the very long name <span class="new_code">testLogCreatesNewFileOnFirstMessage()</span>.
+ This is considered good style and makes the test output more readable.
+ </p>
+ <p>
+ We would normally have more than one test method in a test case,
+ but that's for later.
+ </p>
+ <p>
+ 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
+ <span class="new_code">print</span> statements can display
+ their debugging content right next to the assertion concerned.
+ </p>
+ <p>
+ To see these results we have to actually run the tests.
+ No other code is necessary - we can just open the page
+ with our browser.
+ </p>
+ <p>
+ On failure the display looks like this...
+ <div class="demo">
+ <h1>TestOfLogging</h1>
+ <span class="fail">Fail</span>: testLogCreatesNewFileOnFirstMessage-&gt;True assertion failed.<br>
+ <div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
+ <strong>1</strong> passes and <strong>1</strong> fails.</div>
+ </div>
+ ...and if it passes like this...
+ <div class="demo">
+ <h1>TestOfLogging</h1>
+ <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
+ <strong>2</strong> passes and <strong>0</strong> fails.</div>
+ </div>
+ And if you get this...
+ <div class="demo">
+ <b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b>
+ </div>
+ it means you're missing the <em>classes/Log.php</em> file that could look like...
+<pre>
+&lt;?php<strong>
+class Log {
+ function Log($file_path) {
+ }
+
+ function message() {
+ }
+}</strong>
+?&gt;
+</pre>
+ It's fun to write the code after the test.
+ More than fun even -
+ this system is called "Test Driven Development".
+ </p>
+ <p>
+ For more information about <span class="new_code">UnitTestCase</span>, see
+ the <a href="unit_test_documentation.html">unit test documentation</a>.
+ </p>
+
+ <h2>
+<a class="target" name="group"></a>Building test suites</h2>
+ <p>
+ 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 for the application.
+ </p>
+ <p>
+ Our first step is to create a new file called <em>tests/all_tests.php</em>
+ and insert the following code...
+<pre>
+&lt;?php
+<strong>require_once('simpletest/autorun.php');</strong>
+
+class AllTests extends <strong>TestSuite</strong> {
+ function AllTests() {
+ $this-&gt;TestSuite(<strong>'All tests'</strong>);
+ <strong>$this-&gt;addFile('log_test.php');</strong>
+ }
+}
+?&gt;
+</pre>
+ The "autorun" include allows our upcoming test suite
+ to be run just by invoking this script.
+ </p>
+ <p>
+ The <span class="new_code">TestSuite</span> subclass must chain it's constructor.
+ This limitation will be removed in future versions.
+ </p>
+ <p>
+ The method <span class="new_code">TestSuite::addFile()</span>
+ will include the test case file and read any new classes
+ that are descended from <span class="new_code">SimpleTestCase</span>.
+ <span class="new_code">UnitTestCase</span> is just one example of a class derived from
+ <span class="new_code">SimpleTestCase</span>, and you can create your own.
+ <span class="new_code">TestSuite::addFile()</span> can include other test suites.
+ </p>
+ <p>
+ The class will not be instantiated yet.
+ When the test suite runs it will construct each instance once
+ it reaches that test, then destroy it straight after.
+ This means that the constructor is run just before each run
+ of that test case, and the destructor is run before the next test case starts.
+ </p>
+ <p>
+ It is common to group test case code into superclasses which are not
+ supposed to run, but become the base classes of other tests.
+ For "autorun" to work properly the test case file should not blindly run
+ 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 mark your
+ base class as <span class="new_code">abstract</span>.
+ SimpleTest won't run abstract classes.
+ If you are still using PHP4, then
+ a <span class="new_code">SimpleTestOptions::ignore()</span> directive
+ somewhere in the test case file will have the same effect.
+ </p>
+ <p>
+ 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 <span class="new_code">TestSuite::addFile()</span>
+ method will not detect them.
+ </p>
+ <p>
+ To display the results it is necessary only to invoke
+ <em>tests/all_tests.php</em> from the web server or the command line.
+ </p>
+ <p>
+ For more information about building test suites,
+ see the <a href="group_test_documentation.html">test suite documentation</a>.
+ </p>
+
+ <h2>
+<a class="target" name="mock"></a>Using mock objects</h2>
+ <p>
+ Let's move further into the future and do something really complicated.
+ </p>
+ <p>
+ 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
+ <span class="new_code">SessionPool</span>.
+ We want to test a method that will probably end up looking
+ like this...
+<pre><strong>
+class SessionPool {
+ ...
+ function logIn($username) {
+ ...
+ $this-&gt;_log-&gt;message("User $username logged in.");
+ ...
+ }
+ ...
+}
+</strong>
+</pre>
+ In the spirit of reuse, we are using our
+ <span class="new_code">Log</span> class.
+ A conventional test case might look like this...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('../classes/log.php');
+<strong>require_once('../classes/session_pool.php');</strong>
+
+class <strong>TestOfSessionLogging</strong> extends UnitTestCase {
+
+ function setUp() {
+ <strong>@unlink('/temp/test.log');</strong>
+ }
+
+ function tearDown() {
+ <strong>@unlink('/temp/test.log');</strong>
+ }
+
+ function testLoggingInIsLogged() {
+ <strong>$log = new Log('/temp/test.log');
+ $session_pool = &amp;new SessionPool($log);
+ $session_pool-&gt;logIn('fred');</strong>
+ $messages = file('/temp/test.log');
+ $this-&gt;assertEqual($messages[0], "User fred logged in.<strong>\n</strong>");
+ }
+}
+?&gt;
+</pre>
+ We'll explain the <span class="new_code">setUp()</span> and <span class="new_code">tearDown()</span>
+ methods later.
+ </p>
+ <p>
+ 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.
+ We have created close ties with the <span class="new_code">Log</span> class and
+ this test.
+ What if we don't use files any more, but use ths
+ <em>syslog</em> library instead?
+ It means that our <span class="new_code">TestOfSessionLogging</span> test will
+ fail, even thouh it's not testing Logging.
+ </p>
+ <p>
+ It's fragile in smaller ways too.
+ 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?
+ </p>
+ <p>
+ The only part that we really want to test is that a particular
+ message was sent to the logger.
+ We can reduce coupling if we 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.
+ </p>
+ <p>
+ 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.
+ <p>
+ </p>
+ Too good to be true?
+ We can create such an object easily...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('../classes/log.php');
+require_once('../classes/session_pool.php');
+
+<strong>Mock::generate('Log');</strong>
+
+class TestOfSessionLogging extends UnitTestCase {
+
+ function testLoggingInIsLogged() {<strong>
+ $log = &amp;new MockLog();
+ $log-&gt;expectOnce('message', array('User fred logged in.'));</strong>
+ $session_pool = &amp;new SessionPool(<strong>$log</strong>);
+ $session_pool-&gt;logIn('fred');
+ }
+}
+?&gt;
+</pre>
+ The <span class="new_code">Mock::generate()</span> call code generated a new class
+ called <span class="new_code">MockLog</span>.
+ This looks like an identical clone, except that we can wire test code
+ to it.
+ That's what <span class="new_code">expectOnce()</span> does.
+ It says that if <span class="new_code">message()</span> is ever called on me, it had
+ better be with the parameter "User fred logged in.".
+ </p>
+ <p>
+ The test will be triggered when the call to
+ <span class="new_code">message()</span> is invoked on the
+ <span class="new_code">MockLog</span> object by <span class="new_code">SessionPool::logIn()</span> code.
+ 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 you don't have to test every parameter of
+ a call when you only want to test one.
+ </p>
+ <p>
+ If the mock reaches the end of the test case without the
+ method being called, the <span class="new_code">expectOnce()</span>
+ expectation will trigger a test failure.
+ In other words the mocks can detect the absence of
+ behaviour as well as the presence.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ For more information about mocking and stubbing, see the
+ <a href="mock_objects_documentation.html">mock objects documentation</a>.
+ </p>
+
+ <h2>
+<a class="target" name="web"></a>Web page testing</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ The web testing in SimpleTest is fairly primitive, as there is
+ no JavaScript.
+ Most other browser operations are simulated.
+ </p>
+ <p>
+ 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.
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+<strong>require_once('simpletest/web_tester.php');</strong>
+
+class TestOfAbout extends <strong>WebTestCase</strong> {
+ function testOurAboutPageGivesFreeReignToOurEgo() {
+ <strong>$this-&gt;get('http://test-server/index.php');
+ $this-&gt;click('About');
+ $this-&gt;assertTitle('About why we are so great');
+ $this-&gt;assertText('We are really great');</strong>
+ }
+}
+?&gt;
+</pre>
+ 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.
+ </p>
+ <p>
+ You can navigate forms too...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('simpletest/web_tester.php');
+
+class TestOfRankings extends WebTestCase {
+ function testWeAreTopOfGoogle() {
+ $this-&gt;get('http://google.com/');
+ $this-&gt;setField('q', 'simpletest');
+ $this-&gt;click("I'm Feeling Lucky");
+ $this-&gt;assertTitle('SimpleTest - Unit Testing for PHP');
+ }
+}
+?&gt;
+</pre>
+ ...although this could violate Google's(tm) terms and conditions.
+ </p>
+ <p>
+ For more information about web testing, see the
+ <a href="browser_documentation.html">scriptable
+ browser documentation</a> and the
+ <a href="web_tester_documentation.html">WebTestCase</a>.
+ </p>
+ <p>
+ <a href="http://sourceforge.net/projects/simpletest/"><img src="http://sourceforge.net/sflogo.php?group_id=76550&amp;type=5" width="210" height="62" border="0" alt="SourceForge.net Logo"></a>
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ <a href="https://sourceforge.net/project/showfiles.php?group_id=76550&amp;release_id=153280">Download PHP SimpleTest</a>
+ from <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ The <a href="http://simpletest.org/api/">developer's API for SimpleTest</a>
+ gives full detail on the classes and assertions available.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<span class="chosen">SimpleTest</span>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/en/mock_objects_documentation.html b/3rdparty/simpletest/docs/en/mock_objects_documentation.html
new file mode 100644
index 00000000000..b4697f9ee3b
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/mock_objects_documentation.html
@@ -0,0 +1,870 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest for PHP mock objects documentation</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <span class="chosen">Mock objects</span>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Mock objects documentation</h1>
+ This page...
+ <ul>
+<li>
+ <a href="#what">What are mock objects?</a>
+ </li>
+<li>
+ <a href="#creation">Creating mock objects</a>.
+ </li>
+<li>
+ <a href="#expectations">Mocks as critics</a> with expectations.
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="what"></a>What are mock objects?</h2>
+ <p>
+ Mock objects have two roles during a test case: actor and critic.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ If mock objects only behaved as actors they would simply be
+ known as "server stubs".
+ This was originally a pattern named by Robert Binder (<a href="">Testing
+ object-oriented systems</a>: models, patterns, and tools,
+ Addison-Wesley) in 1999.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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.
+ </p>
+
+ <h2>
+<a class="target" name="creation"></a>Creating mock objects</h2>
+ <p>
+ All we need is an existing class or interface, say a database connection
+ that looks like this...
+<pre>
+<strong>class DatabaseConnection {
+ function DatabaseConnection() { }
+ function query($sql) { }
+ function selectQuery($sql) { }
+}</strong>
+</pre>
+ To create a mock version of the class we need to run a
+ code generator...
+<pre>
+require_once('simpletest/autorun.php');
+require_once('database_connection.php');
+
+<strong>Mock::generate('DatabaseConnection');</strong>
+</pre>
+ This code generates a clone class called
+ <span class="new_code">MockDatabaseConnection</span>.
+ This new class appears to be the same, but actually has no behaviour at all.
+ </p>
+ <p>
+ The new class is usually a subclass of <span class="new_code">DatabaseConnection</span>.
+ Unfortunately, there is no way to create a mock version of a
+ class with a <span class="new_code">final</span> method without having a living version of
+ that method.
+ We consider that unsafe.
+ If the target is an interface, or if <span class="new_code">final</span> methods are
+ present in a target class, then a whole new class
+ is created, but one implemeting the same interfaces.
+ If you try to pass this separate class through a type hint that specifies
+ the old concrete class name, it will fail.
+ Code like that insists on type hinting to a class with <span class="new_code">final</span>
+ methods probably cannot be safely tested with mocks.
+ </p>
+ <p>
+ If you want to see the generated code, then simply <span class="new_code">print</span>
+ the output of <span class="new_code">Mock::generate()</span>.
+ Here is the generated code for the <span class="new_code">DatabaseConnection</span>
+ class rather than the interface version...
+<pre>
+class MockDatabaseConnection extends DatabaseConnection {
+ public $mock;
+ protected $mocked_methods = array('databaseconnection', 'query', 'selectquery');
+
+ function MockDatabaseConnection() {
+ $this-&gt;mock = new SimpleMock();
+ $this-&gt;mock-&gt;disableExpectationNameChecks();
+ }
+ ...
+ function DatabaseConnection() {
+ $args = func_get_args();
+ $result = &amp;$this-&gt;mock-&gt;invoke("DatabaseConnection", $args);
+ return $result;
+ }
+ function query($sql) {
+ $args = func_get_args();
+ $result = &amp;$this-&gt;mock-&gt;invoke("query", $args);
+ return $result;
+ }
+ function selectQuery($sql) {
+ $args = func_get_args();
+ $result = &amp;$this-&gt;mock-&gt;invoke("selectQuery", $args);
+ return $result;
+ }
+}
+</pre>
+ Your output may vary depending on the exact version
+ of SimpleTest you are using.
+ </p>
+ <p>
+ Besides the original methods of the class, you will see some extra
+ methods that help testing.
+ More on these later.
+ </p>
+ <p>
+ We can now create instances of the new class within
+ our test case...
+<pre>
+require_once('simpletest/autorun.php');
+require_once('database_connection.php');
+
+Mock::generate('DatabaseConnection');
+
+class MyTestCase extends UnitTestCase {
+
+ function testSomething() {
+ <strong>$connection = new MockDatabaseConnection();</strong>
+ }
+}
+</pre>
+ The mock version now has all the methods of the original.
+ Also, any type hints will be faithfully preserved.
+ Say our query methods expect a <span class="new_code">Query</span> object...
+<pre>
+<strong>class DatabaseConnection {
+ function DatabaseConnection() { }
+ function query(Query $query) { }
+ function selectQuery(Query $query) { }
+}</strong>
+</pre>
+ If we now pass the wrong type of object, or worse a non-object...
+<pre>
+class MyTestCase extends UnitTestCase {
+
+ function testSomething() {
+ $connection = new MockDatabaseConnection();
+ $connection-&gt;query('insert into accounts () values ()');
+ }
+}
+</pre>
+ ...the code will throw a type violation at you just as the
+ original class would.
+ </p>
+ <p>
+ The mock version now has all the methods of the original.
+ Unfortunately, they all return <span class="new_code">null</span>.
+ As methods that always return <span class="new_code">null</span> are not that useful,
+ we need to be able to set them to something else...
+ </p>
+ <p>
+ <a class="target" name="stub"><h2>Mocks as actors</h2></a>
+ </p>
+ <p>
+ Changing the return value of a method from <span class="new_code">null</span>
+ to something else is pretty easy...
+<pre>
+<strong>$connection-&gt;returns('query', 37)</strong>
+</pre>
+ Now every time we call
+ <span class="new_code">$connection-&gt;query()</span> we get
+ the result of 37.
+ There is nothing special about 37.
+ The return value can be arbitrarily complicated.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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...
+<pre>
+class Iterator {
+ function Iterator() { }
+ function next() { }
+}
+</pre>
+ 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...
+<pre>
+Mock::generate('Iterator');
+
+class IteratorTest extends UnitTestCase() {
+
+ function testASequence() {<strong>
+ $iterator = new MockIterator();
+ $iterator-&gt;returns('next', false);
+ $iterator-&gt;returnsAt(0, 'next', 'First string');
+ $iterator-&gt;returnsAt(1, 'next', 'Second string');</strong>
+ ...
+ }
+}
+</pre>
+ When <span class="new_code">next()</span> is called on the
+ <span class="new_code">MockIterator</span> it will first return "First string",
+ on the second call "Second string" will be returned
+ and on any other call <span class="new_code">false</span> 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.
+ </p>
+ <p>
+ Another tricky situation is an overloaded
+ <span class="new_code">get()</span> operation.
+ An example of this is an information holder with name/value pairs.
+ Say we have a configuration class like...
+<pre>
+class Configuration {
+ function Configuration() { ... }
+ function get($key) { ... }
+}
+</pre>
+ This is a likely situation for using mock objects, as
+ actual configuration will vary from machine to machine and
+ even from test to test.
+ The problem though is that all the data comes through the
+ <span class="new_code">get()</span> method and yet
+ we want different results for different keys.
+ Luckily the mocks have a filter system...
+<pre>
+<strong>$config = &amp;new MockConfiguration();
+$config-&gt;returns('get', 'primary', array('db_host'));
+$config-&gt;returns('get', 'admin', array('db_user'));
+$config-&gt;returns('get', 'secret', array('db_password'));</strong>
+</pre>
+ 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
+ <span class="new_code">get()</span> method invoked
+ like this...
+<pre>
+$config-&gt;get('db_user')
+</pre>
+ ...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.
+ </p>
+ <p>
+ You can set a default argument argument like so...
+<pre><strong>
+$config-&gt;returns('get', false, array('*'));</strong>
+</pre>
+ This is not the same as setting the return value without
+ any argument requirements like this...
+<pre><strong>
+$config-&gt;returns('get', false);</strong>
+</pre>
+ 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.
+ </p>
+ <p>
+ There are times when you want a specific reference to be
+ dished out by the mock rather than a copy or object handle.
+ This a rarity to say the least, but you might be simulating
+ a container that can hold primitives such as strings.
+ For example...
+<pre>
+class Pad {
+ function Pad() { }
+ function &amp;note($index) { }
+}
+</pre>
+ In this case you can set a reference into the mock's
+ return list...
+<pre>
+function testTaskReads() {
+ $note = 'Buy books';
+ $pad = new MockPad();
+ $vector-&gt;<strong>returnsByReference(</strong>'note', $note, array(3)<strong>)</strong>;
+ $task = new Task($pad);
+ ...
+}
+</pre>
+ With this arrangement you know that every time
+ <span class="new_code">$pad-&gt;note(3)</span> is
+ called it will return the same <span class="new_code">$note</span> each time,
+ even if it get's modified.
+ </p>
+ <p>
+ These three factors, timing, parameters and whether to copy,
+ can be combined orthogonally.
+ For example...
+<pre>
+$buy_books = 'Buy books';
+$write_code = 'Write code';
+$pad = new MockPad();
+$vector-&gt;<strong>returnsByReferenceAt(0, 'note', $buy_books, array('*', 3));</strong>
+$vector-&gt;<strong>returnsByReferenceAt(1, 'note', $write_code, array('*', 3));</strong>
+</pre>
+ This will return a reference to <span class="new_code">$buy_books</span> and
+ then to <span class="new_code">$write_code</span>, but only if two parameters
+ were set the second of which must be the integer 3.
+ That should cover most situations.
+ </p>
+ <p>
+ 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 the the iterator's <span class="new_code">next()</span> giving
+ one row until false.
+ This sounds like a simulation nightmare, but in fact it can all
+ be mocked using the mechanics above...
+<pre>
+Mock::generate('DatabaseConnection');
+Mock::generate('ResultIterator');
+
+class DatabaseTest extends UnitTestCase {
+
+ function testUserFinderReadsResultsFromDatabase() {<strong>
+ $result = new MockResultIterator();
+ $result-&gt;returns('next', false);
+ $result-&gt;returnsAt(0, 'next', array(1, 'tom'));
+ $result-&gt;returnsAt(1, 'next', array(3, 'dick'));
+ $result-&gt;returnsAt(2, 'next', array(6, 'harry'));
+
+ $connection = new MockDatabaseConnection();
+ $connection-&gt;returns('selectQuery', $result);</strong>
+
+ $finder = new UserFinder(<strong>$connection</strong>);
+ $this-&gt;assertIdentical(
+ $finder-&gt;findNames(),
+ array('tom', 'dick', 'harry'));
+ }
+}
+</pre>
+ Now only if our
+ <span class="new_code">$connection</span> is called with the
+ <span class="new_code">query()</span> method will the
+ <span class="new_code">$result</span> be returned that is
+ itself exhausted after the third call to <span class="new_code">next()</span>.
+ This should be enough
+ information for our <span class="new_code">UserFinder</span> class,
+ the class actually
+ being tested here, to come up with goods.
+ A very precise test and not a real database in sight.
+ </p>
+ <p>
+ We could refine this test further by insisting that the correct
+ query is sent...
+<pre>
+$connection-&gt;returns('selectQuery', $result, array(<strong>'select name, id from people'</strong>));
+</pre>
+ This is actually a bad idea.
+ </p>
+ <p>
+ We have a <span class="new_code">UserFinder</span> in object land, talking to
+ database tables using a large interface - the whole of SQL.
+ Imagine that we have written a lot of tests that now depend
+ on the exact SQL string passed.
+ These queries could change en masse for all sorts of reasons
+ not related to the specific test.
+ For example the quoting rules could change, a table name could
+ change, a link table added or whatever.
+ This would require the rewriting of every single test any time
+ one of these refactoring is made, yet the intended behaviour has
+ stayed the same.
+ Tests are supposed to help refactoring, not hinder it.
+ I'd certainly like to have a test suite that passes while I change
+ table names.
+ </p>
+ <p>
+ As a rule it is best not to mock a fat interface.
+ </p>
+ <p>
+ By contrast, here is the round trip test...
+<pre>
+class DatabaseTest extends UnitTestCase {<strong>
+ function setUp() { ... }
+ function tearDown() { ... }</strong>
+
+ function testUserFinderReadsResultsFromDatabase() {
+ $finder = new UserFinder(<strong>new DatabaseConnection()</strong>);
+ $finder-&gt;add('tom');
+ $finder-&gt;add('dick');
+ $finder-&gt;add('harry');
+ $this-&gt;assertIdentical(
+ $finder-&gt;findNames(),
+ array('tom', 'dick', 'harry'));
+ }
+}
+</pre>
+ This test is immune to schema changes.
+ It will only fail if you actually break the functionality, which
+ is what you want a test to do.
+ </p>
+ <p>
+ The catch is those <span class="new_code">setUp()</span> and <span class="new_code">tearDown()</span>
+ methods that we've rather glossed over.
+ They have to clear out the database tables and ensure that the
+ schema is defined correctly.
+ That can be a chunk of extra work, but you usually have this code
+ lying around anyway for deployment purposes.
+ </p>
+ <p>
+ One place where you definitely need a mock is simulating failures.
+ Say the database goes down while <span class="new_code">UserFinder</span> is doing
+ it's work.
+ Does <span class="new_code">UserFinder</span> behave well...?
+<pre>
+class DatabaseTest extends UnitTestCase {
+
+ function testUserFinder() {
+ $connection = new MockDatabaseConnection();<strong>
+ $connection-&gt;throwOn('selectQuery', new TimedOut('Ouch!'));</strong>
+ $alert = new MockAlerts();<strong>
+ $alert-&gt;expectOnce('notify', 'Database is busy - please retry');</strong>
+ $finder = new UserFinder($connection, $alert);
+ $this-&gt;assertIdentical($finder-&gt;findNames(), array());
+ }
+}
+</pre>
+ We've passed the <span class="new_code">UserFinder</span> an <span class="new_code">$alert</span>
+ object.
+ This is going to do some kind of pretty notifications in the
+ user interface in the event of an error.
+ We'd rather not sprinkle our code with hard wired <span class="new_code">print</span>
+ statements if we can avoid it.
+ Wrapping the means of output means we can use this code anywhere.
+ It also makes testing easier.
+ </p>
+ <p>
+ To pass this test, the finder has to write a nice user friendly
+ message to <span class="new_code">$alert</span>, rather than propogating the exception.
+ So far, so good.
+ </p>
+ <p>
+ How do we get the mock <span class="new_code">DatabaseConnection</span> to throw an exception?
+ We generate the exception using the <span class="new_code">throwOn</span> method
+ on the mock.
+ </p>
+ <p>
+ Finally, what if the method you want to simulate does not exist yet?
+ If you set a return value on a method that is not there, SimpleTest
+ will throw an error.
+ What if you are using <span class="new_code">__call()</span> to simulate dynamic methods?
+ </p>
+ <p>
+ Objects with dynamic interfaces, using <span class="new_code">__call</span>, can
+ be problematic with the current mock objects implementation.
+ You can mock the <span class="new_code">__call()</span> method, but this is ugly.
+ Why should a test know anything about such low level implementation details?
+ It just wants to simulate the call.
+ </p>
+ <p>
+ The way round this is to add extra methods to the mock when
+ generating it.
+<pre>
+<strong>Mock::generate('DatabaseConnection', 'MockDatabaseConnection', array('setOptions'));</strong>
+</pre>
+ In a large test suite this could cause trouble, as you probably
+ already have a mock version of the class called
+ <span class="new_code">MockDatabaseConnection</span> without the extra methods.
+ The code generator will not generate a mock version of the class if
+ one of the same name already exists.
+ You will confusingly fail to see your method if another definition
+ was run first.
+ </p>
+ <p>
+ To cope with this, SimpleTest allows you to choose any name for the
+ new class at the same time as you add the extra methods.
+<pre>
+Mock::generate('DatabaseConnection', <strong>'MockDatabaseConnectionWithOptions'</strong>, array('setOptions'));
+</pre>
+ Here the mock will behave as if the <span class="new_code">setOptions()</span>
+ existed in the original class.
+ </p>
+ <p>
+ Mock objects can only be used within test cases, as upon expectations
+ they send messages straight to the currently running test case.
+ Creating them outside a test case will cause a run time error
+ when an expectation is triggered and there is no running test case
+ for the message to end up.
+ We cover expectations next.
+ </p>
+
+ <h2>
+<a class="target" name="expectations"></a>Mocks as critics</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ By way of example, let's take a simple <span class="new_code">PageController</span>
+ class to handle a credit card payment form...
+<pre>
+class PaymentForm extends PageController {
+ function __construct($alert, $payment_gateway) { ... }
+ function makePayment($request) { ... }
+}
+</pre>
+ This class takes a <span class="new_code">PaymentGateway</span> to actually talk
+ to the bank.
+ It also takes an <span class="new_code">Alert</span> object to handle errors.
+ This class talks to the page or template.
+ It's responsible for painting the error message and highlighting any
+ form fields that are incorrect.
+ </p>
+ <p>
+ It might look something like...
+<pre>
+class Alert {
+ function warn($warning, $id) {
+ print '&lt;div class="warning"&gt;' . $warning . '&lt;/div&gt;';
+ print '&lt;style type="text/css"&gt;#' . $id . ' { background-color: red }&lt;/style&gt;';
+ }
+}
+</pre>
+ </p>
+ <p>
+ Our interest is in the <span class="new_code">makePayment()</span> method.
+ If we fail to enter a "CVV2" number (the three digit number
+ on the back of the credit card), we want to show an error rather than
+ try to process the payment.
+ In test form...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('payment_form.php');
+Mock::generate('Alert');
+Mock::generate('PaymentGateway');
+
+class PaymentFormFailuresShouldBeGraceful extends UnitTestCase {
+
+ function testMissingCvv2CausesAlert() {
+ $alert = new MockAlert();
+ <strong>$alert-&gt;expectOnce(
+ 'warn',
+ array('Missing three digit security code', 'cvv2'));</strong>
+ $controller = new PaymentForm(<strong>$alert</strong>, new MockPaymentGateway());
+ $controller-&gt;makePayment($this-&gt;requestWithMissingCvv2());
+ }
+
+ function requestWithMissingCvv2() { ... }
+}
+?&gt;
+</pre>
+ The first question you may be asking is, where are the assertions?
+ </p>
+ <p>
+ The call to <span class="new_code">expectOnce('warn', array(...))</span> instructs the mock
+ to expect a call to <span class="new_code">warn()</span> before the test ends.
+ When it gets a call to <span class="new_code">warn()</span>, it checks the arguments.
+ If the arguments don't match, then a failure is generated.
+ It also fails if the method is never called at all.
+ </p>
+ <p>
+ The test above not only asserts that <span class="new_code">warn</span> was called,
+ but that it received the string "Missing three digit security code"
+ and also the tag "cvv2".
+ The equivalent of <span class="new_code">assertIdentical()</span> is applied to both
+ fields when the parameters are compared.
+ </p>
+ <p>
+ If you are not interested in the actual message, and we are not
+ for user interface code that changes often, we can skip that
+ parameter with the "*" operator...
+<pre>
+class PaymentFormFailuresShouldBeGraceful extends UnitTestCase {
+
+ function testMissingCvv2CausesAlert() {
+ $alert = new MockAlert();
+ $alert-&gt;expectOnce('warn', array(<strong>'*'</strong>, 'cvv2'));
+ $controller = new PaymentForm($alert, new MockPaymentGateway());
+ $controller-&gt;makePayment($this-&gt;requestWithMissingCvv2());
+ }
+
+ function requestWithMissingCvv2() { ... }
+}
+</pre>
+ We can weaken the test further by missing
+ out the parameters array...
+<pre>
+function testMissingCvv2CausesAlert() {
+ $alert = new MockAlert();
+ <strong>$alert-&gt;expectOnce('warn');</strong>
+ $controller = new PaymentForm($alert, new MockPaymentGateway());
+ $controller-&gt;makePayment($this-&gt;requestWithMissingCvv2());
+}
+</pre>
+ This will only test that the method is called,
+ which is a bit drastic in this case.
+ Later on, we'll see how we can weaken the expectations more precisely.
+ </p>
+ <p>
+ Tests without assertions can be both compact and very expressive.
+ Because we intercept the call on the way into an object, here of
+ the <span class="new_code">Alert</span> class, we avoid having to assert its state
+ afterwards.
+ This not only avoids the assertions in the tests, but also having
+ to add extra test only accessors to the original code.
+ If you catch yourself adding such accessors, called "state based testing",
+ it's probably time to consider using mocks in the tests.
+ This is called "behaviour based testing", and is normally superior.
+ </p>
+ <p>
+ Let's add another test.
+ Let's make sure that we don't even attempt a payment without a CVV2...
+<pre>
+class PaymentFormFailuresShouldBeGraceful extends UnitTestCase {
+
+ function testMissingCvv2CausesAlert() { ... }
+
+ function testNoPaymentAttemptedWithMissingCvv2() {
+ $payment_gateway = new MockPaymentGateway();
+ <strong>$payment_gateway-&gt;expectNever('pay');</strong>
+ $controller = new PaymentForm(new MockAlert(), $payment_gateway);
+ $controller-&gt;makePayment($this-&gt;requestWithMissingCvv2());
+ }
+
+ ...
+}
+</pre>
+ Asserting a negative can be very hard in tests, but
+ <span class="new_code">expectNever()</span> makes it easy.
+ </p>
+ <p>
+ <span class="new_code">expectOnce()</span> and <span class="new_code">expectNever()</span> are
+ sufficient for most tests, but
+ occasionally you want to test multiple events.
+ Normally for usability purposes we want all missing fields
+ in the form to light up, not just the first one.
+ This means that we should get multiple calls to
+ <span class="new_code">Alert::warn()</span>, not just one...
+<pre>
+function testAllRequiredFieldsHighlightedOnEmptyRequest() {
+ $alert = new MockAlert();<strong>
+ $alert-&gt;expectAt(0, 'warn', array('*', 'cc_number'));
+ $alert-&gt;expectAt(1, 'warn', array('*', 'expiry'));
+ $alert-&gt;expectAt(2, 'warn', array('*', 'cvv2'));
+ $alert-&gt;expectAt(3, 'warn', array('*', 'card_holder'));
+ $alert-&gt;expectAt(4, 'warn', array('*', 'address'));
+ $alert-&gt;expectAt(5, 'warn', array('*', 'postcode'));
+ $alert-&gt;expectAt(6, 'warn', array('*', 'country'));
+ $alert-&gt;expectCallCount('warn', 7);</strong>
+ $controller = new PaymentForm($alert, new MockPaymentGateway());
+ $controller-&gt;makePayment($this-&gt;requestWithMissingCvv2());
+}
+</pre>
+ The counter in <span class="new_code">expectAt()</span> is the number of times
+ the method has been called already.
+ Here we are asserting that every field will be highlighted.
+ </p>
+ <p>
+ Note that we are forced to assert the order too.
+ SimpleTest does not yet have a way to avoid this, but
+ this will be fixed in future versions.
+ </p>
+ <p>
+ Here is the full list of expectations you can set on a mock object
+ in <a href="http://simpletest.org/">SimpleTest</a>.
+ As with the assertions, these methods take an optional failure message.
+ <table>
+ <thead><tr>
+<th>Expectation</th>
+<th>Description</th>
+</tr></thead>
+ <tbody>
+ <tr>
+ <td><span class="new_code">expect($method, $args)</span></td>
+ <td>Arguments must match if called</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectAt($timing, $method, $args)</span></td>
+ <td>Arguments must match when called on the <span class="new_code">$timing</span>'th time</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectCallCount($method, $count)</span></td>
+ <td>The method must be called exactly this many times</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectMaximumCallCount($method, $count)</span></td>
+ <td>Call this method no more than <span class="new_code">$count</span> times</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectMinimumCallCount($method, $count)</span></td>
+ <td>Must be called at least <span class="new_code">$count</span> times</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectNever($method)</span></td>
+ <td>Must never be called</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectOnce($method, $args)</span></td>
+ <td>Must be called once and with the expected arguments if supplied</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectAtLeastOnce($method, $args)</span></td>
+ <td>Must be called at least once, and always with any expected arguments</td>
+ </tr>
+ </tbody>
+ </table>
+ Where the parameters are...
+ <dl>
+ <dt class="new_code">$method</dt>
+ <dd>The method name, as a string, to apply the condition to.</dd>
+ <dt class="new_code">$args</dt>
+ <dd>
+ The arguments as a list. Wildcards can be included in the same
+ manner as for <span class="new_code">setReturn()</span>.
+ This argument is optional for <span class="new_code">expectOnce()</span>
+ and <span class="new_code">expectAtLeastOnce()</span>.
+ </dd>
+ <dt class="new_code">$timing</dt>
+ <dd>
+ The only point in time to test the condition.
+ The first call starts at zero and the count is for
+ each method independently.
+ </dd>
+ <dt class="new_code">$count</dt>
+ <dd>The number of calls expected.</dd>
+ </dl>
+ </p>
+ <p>
+ If you have just one call in your test, make sure you're using
+ <span class="new_code">expectOnce</span>.<br>
+ Using <span class="new_code">$mocked-&gt;expectAt(0, 'method', 'args);</span>
+ on its own will allow the method to never be called.
+ Checking the arguments and the overall call count
+ are currently independant.
+ Add an <span class="new_code">expectCallCount()</span> expectation when you
+ are using <span class="new_code">expectAt()</span> unless zero calls is allowed.
+ </p>
+ <p>
+ 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".
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ The original
+ <a href="http://www.mockobjects.com/">Mock objects</a> paper.
+ </li>
+<li>
+ SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ SimpleTest home page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <span class="chosen">Mock objects</span>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/en/overview.html b/3rdparty/simpletest/docs/en/overview.html
new file mode 100644
index 00000000000..85ea9407749
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/overview.html
@@ -0,0 +1,487 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>
+ Overview and feature list for the SimpleTest PHP unit tester and web tester
+ </title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <span class="chosen">Overview</span>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Overview of SimpleTest</h1>
+ This page...
+ <ul>
+<li>
+ <a href="#summary">Quick summary</a>
+ of the SimpleTest tool for PHP.
+ </li>
+<li>
+ <a href="#features">List of features</a>,
+ both current ones and those planned.
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="summary"></a>What is SimpleTest?</h2>
+ <p>
+ 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.
+ Each test method of a test case class is written to invoke
+ various assertions that the developer expects to be true such as
+ <span class="new_code">assertEqual()</span>.
+ If the expectation is correct, then a successful result is
+ dispatched to the observing test reporter, but any failure
+ or unexpected exception triggers an alert and a description
+ of the mismatch.
+ These test case declarations are transformed into executable
+ test scripts by including a SimpleTest aurorun.php file.
+ </p>
+ <p>
+ These documents apply to SimpleTest version 1.1, although we
+ try hard to maintain compatibility between versions.
+ If you get a test failure after an upgrade, check out the
+ file "HELP_MY_TESTS_DONT_WORK_ANYMORE" in the
+ simpletest directory to see if a feature you are using
+ has since been deprecated and later removed.
+ </p>
+ <p>
+ A <a href="unit_test_documentation.html">test case</a> looks like this...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+class <strong>CanAddUp</strong> extends UnitTestCase {<strong>
+ function testOneAndOneMakesTwo() {
+ $this-&gt;assertEqual(1 + 1, 2);
+ }</strong>
+}
+?&gt;
+</pre>
+ Tests are grouped into test cases, which are just
+ PHP classes that extend <span class="new_code">UnitTestCase</span>
+ or <span class="new_code">WebTestCase</span>.
+ The tests themselves are just normal methods that start
+ their name with the letters "test".
+ You can have as many test cases as you want in a test
+ script and each test case can have as many test methods
+ as it wants too.
+ </p>
+ <p>
+ This test script is immediately runnable.
+ You just invoke it on the command line like so...
+<pre class="shell">
+php adding_test.php
+</pre>
+ </p>
+ <p>
+ When run on the command line you should see something like...
+<pre class="shell">
+adding_test.php
+OK
+Test cases run: 1/1, Passes: 1, Failures: 0, Exceptions: 0
+</pre>
+ </p>
+ <p>
+ If you place it on a web server and point your
+ web browser at it...
+ <div class="demo">
+ <h1>adding_test.php</h1>
+ <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
+ <strong>6</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
+ </div>
+ </p>
+ <p>
+ Of course this is a silly example.
+ A more realistic example might be...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('log.php');
+
+class <strong>TestOfLogging</strong> extends UnitTestCase {
+ function testWillCreateLogFileOnFirstMessage() {
+ $log = new Log('my.log');
+ $this-&gt;assertFalse(file_exists('my.log'));
+ $log-&gt;message('Hello');
+ $this-&gt;assertTrue(file_exists('my.log'));
+ }&lt;/strong&gt;
+}
+?&gt;
+</pre>
+ </p>
+ <p>
+ This tool is designed for the developer.
+ The target audience of this tool is anyone developing a small
+ to medium PHP application, including developers new to
+ unit and web regression testing.
+ The core principles are ease of use first, with extendibility and
+ essential features.
+ </p>
+ <p>
+ Tests are written in the PHP language itself more or less
+ as the application itself is built.
+ The advantage of using PHP 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 when they are in the same programming language.
+ </p>
+ <p>
+ The simplest type of test case is the
+ <a href="unit_tester_documentation.html">UnitTestCase</a>.
+ 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.
+ </p>
+ <p>
+ 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 <a href="web_tester_documentation.html">WebTestCase</a> 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.
+ </p>
+ <p>
+ A <a href="web_tester_documentation.html">WebTestCase</a> looks like this...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('simpletest/web_tester.php');
+
+class <strong>MySiteTest</strong> extends WebTestCase {
+ <strong>
+ function testHomePageHasContactDetailsLink() {
+ $this-&gt;get('http://www.my-site.com/index.php');
+ $this-&gt;assertTitle('My Home Page');
+ $this-&gt;clickLink('Contact');
+ $this-&gt;assertTitle('Contact me');
+ $this-&gt;assertText('/Email me at/');
+ }</strong>
+}
+?&gt;
+</pre>
+ </p>
+
+ <h2>
+<a class="target" name="features"></a>Feature list</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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 SVN directly.
+ <table>
+<thead>
+ <tr>
+<th>Feature</th>
+<th>Description</th>
+<th>Release</th>
+</tr>
+ </thead>
+<tbody>
+<tr>
+ <td>Unit test case</td>
+ <td>Core test case class and assertions</td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Html display</td>
+ <td>Simplest possible display</td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Autoloading of test cases</td>
+ <td>
+ Reading a file with test cases and loading them into a
+ group test automatically
+ </td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Mock objects</td>
+ <td>
+ Objects capable of simulating other objects removing
+ test dependencies
+ </td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Web test case</td>
+ <td>Allows link following and title tag matching</td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Partial mocks</td>
+ <td>
+ Mocking parts of a class for testing less than a class
+ or for complex simulations
+ </td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Web cookie handling</td>
+ <td>Correct handling of cookies when fetching pages</td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Following redirects</td>
+ <td>Page fetching automatically follows 300 redirects</td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Form parsing</td>
+ <td>Ability to submit simple forms and read default form values</td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Command line interface</td>
+ <td>Test display without the need of a web browser</td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Exposure of expectation classes</td>
+ <td>Can create precise tests with mocks as well as test cases</td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>XML output and parsing</td>
+ <td>
+ Allows multi host testing and the integration of acceptance
+ testing extensions
+ </td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Browser component</td>
+ <td>
+ Exposure of lower level web browser interface for more
+ detailed test cases
+ </td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>HTTP authentication</td>
+ <td>
+ Fetching protected web pages with basic authentication
+ only
+ </td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>SSL support</td>
+ <td>Can connect to https: pages</td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Proxy support</td>
+ <td>Can connect via. common proxies</td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>Frames support</td>
+ <td>Handling of frames in web test cases</td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>File upload testing</td>
+ <td>Can simulate the input type file tag</td>
+ <td style="color: green;">1.0.1</td>
+ </tr>
+ <tr>
+ <td>Mocking interfaces</td>
+ <td>
+ Can generate mock objects to interfaces as well as classes
+ and class interfaces are carried for type hints
+ </td>
+ <td style="color: green;">1.0.1</td>
+ </tr>
+ <tr>
+ <td>Testing exceptions</td>
+ <td>Similar to testing PHP errors</td>
+ <td style="color: green;">1.0.1</td>
+ </tr>
+ <tr>
+ <td>HTML label support</td>
+ <td>Can access all controls using the visual label</td>
+ <td style="color: green;">1.0.1</td>
+ </tr>
+ <tr>
+ <td>Base tag support</td>
+ <td>Respects page base tag when clicking</td>
+ <td style="color: green;">1.0.1</td>
+ </tr>
+ <tr>
+ <td>PHP 5 E_STRICT compliant</td>
+ <td>PHP 5 only version that works with the E_STRICT error level</td>
+ <td style="color: green;">1.1</td>
+ </tr>
+ <tr>
+ <td>Alternate HTML parsers</td>
+ <td>Can detect compiled parsers for performance improvements</td>
+ <td style="color: green;">1.1</td>
+ </tr>
+ <tr>
+ <td>REST support</td>
+ <td>Support for REST verbs as put(), delete(), etc.</td>
+ <td style="color: green;">1.1</td>
+ </tr>
+ <tr>
+ <td>BDD style fixtures</td>
+ <td>Can import fixtures using a mixin like given() method</td>
+ <td style="color: red;">1.5</td>
+ </tr>
+ <tr>
+ <td>Plug-in architecture</td>
+ <td>Automatic import of extensions including command line options</td>
+ <td style="color: red;">1.5</td>
+ </tr>
+ <tr>
+ <td>Reporting machinery enhancements</td>
+ <td>Improved message passing for better cooperation with IDEs</td>
+ <td style="color: red;">1.5</td>
+ </tr>
+ <tr>
+ <td>Fluent mock interface</td>
+ <td>More flexible and concise mock objects</td>
+ <td style="color: red;">1.6</td>
+ </tr>
+ <tr>
+ <td>Localisation</td>
+ <td>Messages abstracted and code generated as well as UTF support</td>
+ <td style="color: red;">1.6</td>
+ </tr>
+ <tr>
+ <td>CSS selectors</td>
+ <td>HTML content can be examined using CSS selectors</td>
+ <td style="color: red;">1.7</td>
+ </tr>
+ <tr>
+ <td>HTML table assertions</td>
+ <td>Can match HTML or other table elements to expectations</td>
+ <td style="color: red;">1.7</td>
+ </tr>
+ <tr>
+ <td>Unified acceptance testing model</td>
+ <td>Content searchable through selectors combined with expectations</td>
+ <td style="color: red;">1.7</td>
+ </tr>
+ <tr>
+ <td>DatabaseTestCase</td>
+ <td>SQL selectors and DB drivers</td>
+ <td style="color: red;">1.7</td>
+ </tr>
+ <tr>
+ <td>IFrame support</td>
+ <td>Reads IFrame content that can be refreshed</td>
+ <td style="color: red;">1.8</td>
+ </tr>
+ <tr>
+ <td>Integrated Selenium support</td>
+ <td>Easy to use built in Selenium driver and tutorial or similar browser automation</td>
+ <td style="color: red;">1.9</td>
+ </tr>
+ <tr>
+ <td>Code coverage</td>
+ <td>Reports using the bundled tool when using XDebug</td>
+ <td style="color: red;">1.9</td>
+ </tr>
+ <tr>
+ <td>Deprecation of old methods</td>
+ <td>Simpler interface for SimpleTest2</td>
+ <td style="color: red;">2.0</td>
+ </tr>
+ <tr>
+ <td>Javascript suport</td>
+ <td>Use of PECL module to add Javascript to the native browser</td>
+ <td style="color: red;">3.0</td>
+ </tr>
+ </tbody>
+</table>
+ PHP 5 migration is complete, which means that only PHP 5.0.3+
+ will be supported in SimpleTest version 1.1+.
+ Earlier versions of SimpleTest are compatible with PHP 4.2 up to
+ PHP 5 (non E_STRICT).
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ <a href="unit_test_documentation.html">Documentation for SimpleTest</a>.
+ </li>
+<li>
+ <a href="http://www.lastcraft.com/first_test_tutorial.php">How to write PHP test cases</a>
+ is a fairly advanced tutorial.
+ </li>
+<li>
+ <a href="http://simpletest.org/api/">SimpleTest API</a> from phpdoc.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <span class="chosen">Overview</span>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/en/partial_mocks_documentation.html b/3rdparty/simpletest/docs/en/partial_mocks_documentation.html
new file mode 100644
index 00000000000..cb70b1f86df
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/partial_mocks_documentation.html
@@ -0,0 +1,457 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest for PHP partial mocks documentation</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <span class="chosen">Partial mocks</span>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Partial mock objects documentation</h1>
+ This page...
+ <ul>
+<li>
+ <a href="#inject">The mock injection problem</a>.
+ </li>
+<li>
+ Moving creation to a <a href="#creation">protected factory</a> method.
+ </li>
+<li>
+ <a href="#partial">Partial mocks</a> generate subclasses.
+ </li>
+<li>
+ Partial mocks <a href="#less">test less than a class</a>.
+ </li>
+</ul>
+<div class="content">
+
+ <p>
+ 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.
+ </p>
+
+ <h2>
+<a class="target" name="inject"></a>The mock injection problem</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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...
+<pre>
+<strong>&lt;?php
+require_once('socket.php');
+
+class Telnet {
+ ...
+ function connect($ip, $port, $username, $password) {
+ $socket = new Socket($ip, $port);
+ $socket-&gt;read( ... );
+ ...
+ }
+}
+?&gt;</strong>
+</pre>
+ We would really like to have a mock object version of the socket
+ here, what can we do?
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ Here this would be...
+<pre>
+&lt;?php
+require_once('socket.php');
+
+class Telnet {
+ ...
+ <strong>function connect($socket, $username, $password) {
+ $socket-&gt;read( ... );
+ ...
+ }</strong>
+}
+?&gt;
+</pre>
+ This means that the test code is typical for a test involving
+ mock objects.
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = new MockSocket();
+ ...
+ $telnet = new Telnet();
+ $telnet-&gt;connect($socket, 'Me', 'Secret');
+ ...</strong>
+ }
+}
+</pre>
+ 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.
+ </p>
+ <p>
+ The next simplest compromise is to have the created object passed
+ in as an optional parameter...
+<pre>
+&lt;?php
+require_once('socket.php');
+
+class Telnet {
+ ...<strong>
+ function connect($ip, $port, $username, $password, $socket = false) {
+ if (! $socket) {
+ $socket = new Socket($ip, $port);
+ }
+ $socket-&gt;read( ... );</strong>
+ ...
+ return $socket;
+ }
+}
+?&gt;
+</pre>
+ For a quick solution this is usually good enough.
+ The test now looks almost the same as if the parameter
+ was formally passed...
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = new MockSocket();
+ ...
+ $telnet = new Telnet();
+ $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret', $socket);
+ ...</strong>
+ }
+}
+</pre>
+ 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.
+ </p>
+ <p>
+ The next method is to pass in a factory object to do the creation...
+<pre>
+&lt;?php
+require_once('socket.php');
+
+class Telnet {<strong>
+ function Telnet($network) {
+ $this-&gt;_network = $network;
+ }</strong>
+ ...
+ function connect($ip, $port, $username, $password) {<strong>
+ $socket = $this-&gt;_network-&gt;createSocket($ip, $port);
+ $socket-&gt;read( ... );</strong>
+ ...
+ return $socket;
+ }
+}
+?&gt;
+</pre>
+ 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...
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = new MockSocket();
+ ...
+ $network = new MockNetwork();
+ $network-&gt;returnsByReference('createSocket', $socket);
+ $telnet = new Telnet($network);
+ $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');</strong>
+ }
+}
+</pre>
+ 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.
+ </p>
+ <p>
+ Well techniques like "Dependency Injection" tackle the problem of
+ instantiating a lot of constructor parameters.
+ Unfortunately knowledge of this pattern is not widespread, and if you
+ are trying to get older code to work, rearchitecting the whole
+ application is not really an option.
+ </p>
+ <p>
+ Is there a middle ground?
+ </p>
+
+ <h2>
+<a class="target" name="creation"></a>Protected factory method</h2>
+ <p>
+ 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...
+<pre>
+&lt;?php
+require_once('socket.php');
+
+class Telnet {
+ ...
+ function connect($ip, $port, $username, $password) {
+ <strong>$socket = $this-&gt;createSocket($ip, $port);</strong>
+ $socket-&gt;read( ... );
+ ...
+ }<strong>
+
+ protected function createSocket($ip, $port) {
+ return new Socket($ip, $port);
+ }</strong>
+}
+?&gt;
+</pre>
+ This is a pretty safe step even for very tangled legacy code.
+ This is the only change we make to the application.
+ </p>
+ <p>
+ For the test case we have to create a subclass so that
+ we can intercept the socket creation...
+<pre>
+<strong>class TelnetTestVersion extends Telnet {
+ var $mock;
+
+ function TelnetTestVersion($mock) {
+ $this-&gt;mock = $mock;
+ $this-&gt;Telnet();
+ }
+
+ protected function createSocket() {
+ return $this-&gt;mock;
+ }
+}</strong>
+</pre>
+ 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
+ <span class="new_code">connect()</span>.
+ Otherwise it could get a null value from
+ <span class="new_code">createSocket()</span>.
+ </p>
+ <p>
+ After the completion of all of this extra work the
+ actual test case is fairly easy.
+ We just test our new class instead...
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = new MockSocket();
+ ...
+ $telnet = new TelnetTestVersion($socket);
+ $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');</strong>
+ }
+}
+</pre>
+ 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?
+ </p>
+
+ <h2>
+<a class="target" name="partial"></a>A partial mock</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ Here is the partial mock version of the test...
+<pre>
+<strong>Mock::generatePartial(
+ 'Telnet',
+ 'TelnetTestVersion',
+ array('createSocket'));</strong>
+
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = new MockSocket();
+ ...
+ $telnet = new TelnetTestVersion();
+ $telnet-&gt;setReturnReference('createSocket', $socket);
+ $telnet-&gt;Telnet();
+ $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');</strong>
+ }
+}
+</pre>
+ The partial mock is a subclass of the original with
+ selected methods "knocked out" with test
+ versions.
+ The <span class="new_code">generatePartial()</span> call
+ takes three parameters: the class to be subclassed,
+ the new test class name and a list of methods to mock.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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...
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {
+ $socket = new MockSocket();
+ ...
+ $telnet = new TelnetTestVersion();
+ $telnet-&gt;setReturnReference('createSocket', $socket);
+ <strong>$telnet-&gt;expectOnce('createSocket', array('127.0.0.1', 21));</strong>
+ $telnet-&gt;Telnet();
+ $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');
+ }
+}
+</pre>
+ Partial mocks are not used often.
+ I consider them transitory.
+ Useful while refactoring, but once the application has
+ all of it's dependencies nicely separated then the
+ partial mocks can wither away.
+ </p>
+
+ <h2>
+<a class="target" name="less"></a>Testing less than a class</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ This last situation is all rather hypothetical, as I've hardly
+ tried it.
+ I am 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.
+ </p>
+ <p>
+ It's all going to come down to the coding standards of your
+ project to decide if you allow test mechanisms like this.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ <a href="http://simpletest.org/api/">Full API for SimpleTest</a>
+ from the PHPDoc.
+ </li>
+<li>
+ The protected factory is described in
+ <a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html">this paper from IBM</a>.
+ This is the only formal comment I have seen on this problem.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <span class="chosen">Partial mocks</span>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/en/reporter_documentation.html b/3rdparty/simpletest/docs/en/reporter_documentation.html
new file mode 100644
index 00000000000..8924b7bb67a
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/reporter_documentation.html
@@ -0,0 +1,616 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest for PHP test runner and display documentation</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <span class="chosen">Reporting</span>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Test reporter documentation</h1>
+ This page...
+ <ul>
+<li>
+ Displaying <a href="#html">results in HTML</a>
+ </li>
+<li>
+ Displaying and <a href="#other">reporting results</a>
+ in other formats
+ </li>
+<li>
+ Using <a href="#cli">SimpleTest from the command line</a>
+ </li>
+<li>
+ <a href="#xml">Using XML</a> for remote testing
+ </li>
+</ul>
+<div class="content">
+
+ <p>
+ SimpleTest pretty much follows the MVC-ish 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.
+ </p>
+
+ <h2>
+<a class="target" name="html"></a>Reporting results in HTML</h2>
+ <p>
+ The default HTML 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...
+ <div class="demo">
+ <h1>File test</h1>
+ <span class="fail">Fail</span>: createnewfile-&gt;True assertion failed.<br>
+ <div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
+ <strong>0</strong> passes, <strong>1</strong> fails and <strong>0</strong> exceptions.</div>
+ </div>
+ And here all tests passed...
+ <div class="demo">
+ <h1>File test</h1>
+ <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
+ <strong>1</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
+ </div>
+ The good news is that there are several points in the display
+ hiearchy for subclassing.
+ </p>
+ <p>
+ For web page based displays there is the
+ <span class="new_code">HtmlReporter</span> class with the following
+ signature...
+<pre>
+class HtmlReporter extends SimpleReporter {
+ public __construct($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() { ... }
+}
+</pre>
+ Here is what some of these methods mean. First the display methods
+ that you will probably want to override...
+ <ul class="api">
+ <li>
+ <span class="new_code">HtmlReporter(string $encoding)</span><br>
+ 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 <a href="http://www.php.net/manual/en/function.htmlentities.php">html_entities()</a>
+ function.
+ </li>
+ <li>
+ <span class="new_code">void paintHeader(string $test_name)</span><br>
+ 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 <span class="new_code">$test_name</span>
+ comes from.
+ It paints the page title, CSS, body tag, etc.
+ It returns nothing (<span class="new_code">void</span>).
+ </li>
+ <li>
+ <span class="new_code">void paintFooter(string $test_name)</span><br>
+ 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.
+ </li>
+ <li>
+ <span class="new_code">void paintMethodStart(string $test_name)</span><br>
+ 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.
+ </li>
+ <li>
+ <span class="new_code">void paintMethodEnd(string $test_name)</span><br>
+ backs out of the test started with the same name.
+ </li>
+ <li>
+ <span class="new_code">void paintFail(string $message)</span><br>
+ 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.
+ </li>
+ <li>
+ <span class="new_code">void paintPass(string $message)</span><br>
+ by default does nothing.
+ </li>
+ <li>
+ <span class="new_code">string getCss()</span><br>
+ 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.
+ </li>
+ </ul>
+ There are also some accessors to get information on the current
+ state of the test suite.
+ Use these to enrich the display...
+ <ul class="api">
+ <li>
+ <span class="new_code">array getTestList()</span><br>
+ is the first convenience method for subclasses.
+ Lists the current nesting of the tests as a list
+ of test names.
+ The first, top level test case, is first in the
+ list and the current test method will be last.
+ </li>
+ <li>
+ <span class="new_code">integer getPassCount()</span><br>
+ returns the number of passes chalked up so far.
+ Needed for the display at the end.
+ </li>
+ <li>
+ <span class="new_code">integer getFailCount()</span><br>
+ is likewise the number of fails so far.
+ </li>
+ <li>
+ <span class="new_code">integer getExceptionCount()</span><br>
+ is likewise the number of errors so far.
+ </li>
+ <li>
+ <span class="new_code">integer getTestCaseCount()</span><br>
+ is the total number of test cases in the test run.
+ This includes the grouping tests themselves.
+ </li>
+ <li>
+ <span class="new_code">integer getTestCaseProgress()</span><br>
+ is the number of test cases completed so far.
+ </li>
+ </ul>
+ One simple modification is to get the HtmlReporter to display
+ the passes as well as the failures and errors...
+<pre>
+<strong>class ReporterShowingPasses extends HtmlReporter {
+
+ function paintPass($message) {
+ parent::paintPass($message);
+ print "&lt;span class=\"pass\"&gt;Pass&lt;/span&gt;: ";
+ $breadcrumb = $this-&gt;getTestList();
+ array_shift($breadcrumb);
+ print implode("-&amp;gt;", $breadcrumb);
+ print "-&amp;gt;$message&lt;br /&gt;\n";
+ }
+
+ protected function getCss() {
+ return parent::getCss() . ' .pass { color: green; }';
+ }
+}</strong>
+</pre>
+ </p>
+ <p>
+ One method that was glossed over was the <span class="new_code">makeDry()</span>
+ 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.
+ </p>
+ <p>
+ 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.
+ </p>
+
+ <h2>
+<a class="target" name="other"></a>Extending the reporter</h2>
+ <p>
+ 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
+ <span class="new_code">HtmlReporter</span> we can take one
+ step up the class hiearchy to <span class="new_code">SimpleReporter</span>
+ in the <em>simple_test.php</em> source file.
+ </p>
+ <p>
+ A do nothing display, a blank canvas for your own creation, would
+ be...
+<pre>
+<strong>require_once('simpletest/simpletest.php');</strong>
+
+class MyDisplay extends SimpleReporter {<strong>
+ </strong>
+ function paintHeader($test_name) { }
+
+ function paintFooter($test_name) { }
+
+ function paintStart($test_name, $size) {<strong>
+ parent::paintStart($test_name, $size);</strong>
+ }
+
+ function paintEnd($test_name, $size) {<strong>
+ parent::paintEnd($test_name, $size);</strong>
+ }
+
+ function paintPass($message) {<strong>
+ parent::paintPass($message);</strong>
+ }
+
+ function paintFail($message) {<strong>
+ parent::paintFail($message);</strong>
+ }
+
+ function paintError($message) {<strong>
+ parent::paintError($message);</strong>
+ }
+
+ function paintException($exception) {<strong>
+ parent::paintException($exception);</strong>
+ }
+}
+</pre>
+ No output would come from this class until you add it.
+ </p>
+ <p>
+ The catch with using this low level class is that you must
+ explicitely invoke it in the test script.
+ The "autorun" facility will not be able to use
+ its runtime context (whether it's running in a web browser
+ or the command line) to select the reporter.
+ </p>
+ <p>
+ You explicitely invoke the test runner like so...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+$test = new TestSuite('File test');
+$test-&gt;addFile('tests/file_test.php');
+$test-&gt;run(<strong>new MyReporter()</strong>);
+?&gt;
+</pre>
+ ...perhaps like this...
+<pre>
+&lt;?php
+require_once('simpletest/simpletest.php');
+require_once('my_reporter.php');
+
+class MyTest extends TestSuite {
+ function __construct() {
+ parent::__construct();
+ $this-&gt;addFile('tests/file_test.php');
+ }
+}
+
+$test = new MyTest();
+$test-&gt;run(<strong>new MyReporter()</strong>);
+?&gt;
+</pre>
+ We'll show how to fit in with "autorun" later.
+ </p>
+
+ <h2>
+<a class="target" name="cli"></a>The command line reporter</h2>
+ <p>
+ 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 explicitely, substitute it
+ for the HTML version...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+$test = new TestSuite('File test');
+$test-&gt;addFile('tests/file_test.php');
+$test-&gt;run(<strong>new TextReporter()</strong>);
+?&gt;
+</pre>
+ Then invoke the test suite from the command line...
+<pre class="shell">
+php file_test.php
+</pre>
+ You will need the command line version of PHP installed
+ of course.
+ A passing test suite looks like this...
+<pre class="shell">
+File test
+OK
+Test cases run: 1/1, Passes: 1, Failures: 0, Exceptions: 0
+</pre>
+ A failure triggers a display like this...
+<pre class="shell">
+File test
+1) True assertion failed.
+ in createNewFile
+FAILURES!!!
+Test cases run: 1/1, Passes: 0, Failures: 1, Exceptions: 0
+</pre>
+ </p>
+ <p>
+ 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 <span class="new_code">false</span>
+ is returned from the <span class="new_code">SimpleTest::run()</span>
+ method.
+ We can use that result to exit the script with the desired return
+ code...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+$test = new TestSuite('File test');
+$test-&gt;addFile('tests/file_test.php');
+<strong>exit ($test-&gt;run(new TextReporter()) ? 0 : 1);</strong>
+?&gt;
+</pre>
+ Of course we wouldn'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...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+$test = new TestSuite('File test');
+$test-&gt;addFile('tests/file_test.php');
+<strong>if (TextReporter::inCli()) {</strong>
+ exit ($test-&gt;run(new TextReporter()) ? 0 : 1);
+<strong>}</strong>
+$test-&gt;run(new HtmlReporter());
+?&gt;
+</pre>
+ This is the form used within SimpleTest itself.
+ When you use the "autorun.php", and no
+ test has been run by the end, this is pretty much
+ the code that SimpleTest will run for you implicitely.
+ </p>
+ <p>
+ In other words, this is gives the same result...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+class MyTest extends TestSuite {
+ function __construct() {
+ parent::__construct();
+ $this-&gt;addFile('tests/file_test.php');
+ }
+}
+?&gt;
+</pre>
+ </p>
+
+ <h2>
+<a class="target" name="xml"></a>Remote testing</h2>
+ <p>
+ SimpleTest ships with an <span class="new_code">XmlReporter</span> class
+ used for internal communication.
+ When run the output looks like...
+<pre class="shell">
+&lt;?xml version="1.0"?&gt;
+&lt;run&gt;
+ &lt;group size="4"&gt;
+ &lt;name&gt;Remote tests&lt;/name&gt;
+ &lt;group size="4"&gt;
+ &lt;name&gt;Visual test with 48 passes, 48 fails and 4 exceptions&lt;/name&gt;
+ &lt;case&gt;
+ &lt;name&gt;testofunittestcaseoutput&lt;/name&gt;
+ &lt;test&gt;
+ &lt;name&gt;testofresults&lt;/name&gt;
+ &lt;pass&gt;This assertion passed&lt;/pass&gt;
+ &lt;fail&gt;This assertion failed&lt;/fail&gt;
+ &lt;/test&gt;
+ &lt;test&gt;
+ ...
+ &lt;/test&gt;
+ &lt;/case&gt;
+ &lt;/group&gt;
+ &lt;/group&gt;
+&lt;/run&gt;
+</pre>
+ To get your normal test cases to produce this format, on the
+ command line add the <span class="new_code">--xml</span> flag.
+<pre class="shell">
+php my_test.php --xml
+</pre>
+ You can do teh same thing in the web browser by adding the
+ URL parameter <span class="new_code">xml=1</span>.
+ Any true value will do.
+ </p>
+ <p>
+ You can consume this format with the parser
+ supplied as part of SimpleTest itself.
+ This is called <span class="new_code">SimpleTestXmlParser</span> and
+ resides in <em>xml.php</em> within the SimpleTest package...
+<pre>
+&lt;?php
+require_once('simpletest/xml.php');
+
+...
+$parser = new SimpleTestXmlParser(new HtmlReporter());
+$parser-&gt;parse($test_output);
+?&gt;
+</pre>
+ The <span class="new_code">$test_output</span> 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.
+ </p>
+ <p>
+ Most likely it's when you want to isolate a problematic crash
+ prone test.
+ You can collect the XML output using the backtick operator
+ from another test.
+ In that way it runs in its own process...
+<pre>
+&lt;?php
+require_once('simpletest/xml.php');
+
+if (TextReporter::inCli()) {
+ $parser = new SimpleTestXmlParser(new TextReporter());
+} else {
+ $parser = new SimpleTestXmlParser(new HtmlReporter());
+}
+$parser-&gt;parse(`php flakey_test.php --xml`);
+?&gt;
+</pre>
+ </p>
+ <p>
+ Another use is breaking up large test suites.
+ </p>
+ <p>
+ A problem with large test suites is thet they can exhaust
+ the default 16Mb 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.
+ </p>
+ <p>
+ 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...
+<pre>
+&lt;?php
+<strong>require_once('../remote.php');</strong>
+require_once('simpletest/autorun.php');
+
+$test_url = ...;
+$dry_url = ...;
+
+class MyTestOnAnotherServer extends RemoteTestCase {
+ function __construct() {
+ $test_url = ...
+ parent::__construct($test_url, $test_url . ' --dry');
+ }
+}
+?&gt;
+</pre>
+ The <span class="new_code">RemoteTestCase</span> 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 <span class="new_code">RemoteTestCase</span> can be added to test suites
+ just like any other test suite.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ The <a href="http://simpletest.org/api/">developer's API for SimpleTest</a>
+ gives full detail on the classes and assertions available.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <span class="chosen">Reporting</span>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/en/unit_test_documentation.html b/3rdparty/simpletest/docs/en/unit_test_documentation.html
new file mode 100644
index 00000000000..a399bf34cb1
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/unit_test_documentation.html
@@ -0,0 +1,442 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest for PHP regression test documentation</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <span class="chosen">Unit tester</span>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>PHP Unit Test documentation</h1>
+ This page...
+ <ul>
+<li>
+ <a href="#unit">Unit test cases</a> and basic assertions.
+ </li>
+<li>
+ <a href="#extending_unit">Extending test cases</a> to
+ customise them for your own project.
+ </li>
+<li>
+ <a href="#running_unit">Running a single case</a> as
+ a single script.
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="unit"></a>Unit test cases</h2>
+ <p>
+ The core system is a regression testing framework built around
+ test cases.
+ A sample test case looks like this...
+<pre>
+<strong>class FileTestCase extends UnitTestCase {
+}</strong>
+</pre>
+ 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.
+ </p>
+ <p>
+ For example...
+<pre>
+require_once('simpletest/autorun.php');
+require_once('../classes/writer.php');
+
+class FileTestCase extends UnitTestCase {
+ function FileTestCase() {
+ $this-&gt;UnitTestCase('File test');
+ }<strong>
+
+ function setUp() {
+ @unlink('../temp/test.txt');
+ }
+
+ function tearDown() {
+ @unlink('../temp/test.txt');
+ }
+
+ function testCreation() {
+ $writer = &amp;new FileWriter('../temp/test.txt');
+ $writer-&gt;write('Hello');
+ $this-&gt;assertTrue(file_exists('../temp/test.txt'), 'File created');
+ }</strong>
+}
+</pre>
+ The constructor is optional and usually omitted.
+ Without a name, the class name is taken as the name of the test case.
+ </p>
+ <p>
+ Our only test method at the moment is <span class="new_code">testCreation()</span>
+ where we check that a file has been created by our
+ <span class="new_code">Writer</span> object.
+ We could have put the <span class="new_code">unlink()</span>
+ code into this method as well, but by placing it in
+ <span class="new_code">setUp()</span> and
+ <span class="new_code">tearDown()</span> we can use it with
+ other test methods that we add.
+ </p>
+ <p>
+ The <span class="new_code">setUp()</span> method is run
+ just before each and every test method.
+ <span class="new_code">tearDown()</span> is run just after
+ each and every test method.
+ </p>
+ <p>
+ 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 interference 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 <span class="new_code">setUp()</span>, but
+ supplies additional hooks for library writers.
+ </p>
+ <p>
+ The means of reporting test results (see below) are by a
+ visiting display class
+ that is notified by various <span class="new_code">assert...()</span>
+ methods.
+ Here is the full list for the <span class="new_code">UnitTestCase</span>
+ class, the default for SimpleTest...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">assertTrue($x)</span></td>
+<td>Fail if $x is false</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertFalse($x)</span></td>
+<td>Fail if $x is true</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNull($x)</span></td>
+<td>Fail if $x is set</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNotNull($x)</span></td>
+<td>Fail if $x not set</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertIsA($x, $t)</span></td>
+<td>Fail if $x is not the class or type $t</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNotA($x, $t)</span></td>
+<td>Fail if $x is of the class or type $t</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertEqual($x, $y)</span></td>
+<td>Fail if $x == $y is false</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNotEqual($x, $y)</span></td>
+<td>Fail if $x == $y is true</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertWithinMargin($x, $y, $m)</span></td>
+<td>Fail if abs($x - $y) &lt; $m is false</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertOutsideMargin($x, $y, $m)</span></td>
+<td>Fail if abs($x - $y) &lt; $m is true</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertIdentical($x, $y)</span></td>
+<td>Fail if $x == $y is false or a type mismatch</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNotIdentical($x, $y)</span></td>
+<td>Fail if $x == $y is true and types match</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertReference($x, $y)</span></td>
+<td>Fail unless $x and $y are the same variable</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertClone($x, $y)</span></td>
+<td>Fail unless $x and $y are identical copies</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertPattern($p, $x)</span></td>
+<td>Fail unless the regex $p matches $x</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoPattern($p, $x)</span></td>
+<td>Fail if the regex $p matches $x</td>
+</tr>
+ <tr>
+<td><span class="new_code">expectError($x)</span></td>
+<td>Fail if matching error does not occour</td>
+</tr>
+ <tr>
+<td><span class="new_code">expectException($x)</span></td>
+<td>Fail if matching exception is not thrown</td>
+</tr>
+ <tr>
+<td><span class="new_code">ignoreException($x)</span></td>
+<td>Swallows any upcoming matching exception</td>
+</tr>
+ <tr>
+<td><span class="new_code">assert($e)</span></td>
+<td>Fail on failed <a href="expectation_documentation.html">expectation</a> object $e</td>
+</tr>
+ </tbody></table>
+ All assertion methods can take an optional description as a
+ last parameter.
+ This is 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.
+ </p>
+ <p>
+ Some examples...
+<pre>
+$variable = null;
+<strong>$this-&gt;assertNull($variable, 'Should be cleared');</strong>
+</pre>
+ ...will pass and normally show no message.
+ If you have
+ <a href="http://www.lastcraft.com/display_subclass_tutorial.php">set up the tester to display passes</a>
+ as well then the message will be displayed as is.
+<pre>
+<strong>$this-&gt;assertIdentical(0, false, 'Zero is not false [%s]');</strong>
+</pre>
+ 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.
+<pre>
+$a = 1;
+$b = $a;
+<strong>$this-&gt;assertReference($a, $b);</strong>
+</pre>
+ Will fail as the variable <span class="new_code">$a</span> is a copy of <span class="new_code">$b</span>.
+<pre>
+<strong>$this-&gt;assertPattern('/hello/i', 'Hello world');</strong>
+</pre>
+ This will pass as using a case insensitive match the string
+ <span class="new_code">hello</span> is contained in <span class="new_code">Hello world</span>.
+<pre>
+<strong>$this-&gt;expectError();</strong>
+trigger_error('Catastrophe');
+</pre>
+ Here the check catches the "Catastrophe"
+ message without checking the text and passes.
+ This removes the error from the queue.
+<pre>
+<strong>$this-&gt;expectError('Catastrophe');</strong>
+trigger_error('Catastrophe');
+</pre>
+ The next error check tests not only the existence of the error,
+ but also the text which, here matches so another pass.
+ If any unchecked errors are left at the end of a test method then
+ an exception will be reported in the test.
+ </p>
+ <p>
+ Note that SimpleTest cannot catch compile time PHP errors.
+ </p>
+ <p>
+ The test cases also have some convenience methods for debugging
+ code or extending the suite...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">setUp()</span></td>
+<td>Runs this before each test method</td>
+</tr>
+ <tr>
+<td><span class="new_code">tearDown()</span></td>
+<td>Runs this after each test method</td>
+</tr>
+ <tr>
+<td><span class="new_code">pass()</span></td>
+<td>Sends a test pass</td>
+</tr>
+ <tr>
+<td><span class="new_code">fail()</span></td>
+<td>Sends a test failure</td>
+</tr>
+ <tr>
+<td><span class="new_code">error()</span></td>
+<td>Sends an exception event</td>
+</tr>
+ <tr>
+<td><span class="new_code">signal($type, $payload)</span></td>
+<td>Sends a user defined message to the test reporter</td>
+</tr>
+ <tr>
+<td><span class="new_code">dump($var)</span></td>
+<td>Does a formatted <span class="new_code">print_r()</span> for quick and dirty debugging</td>
+</tr>
+ </tbody></table>
+ </p>
+
+ <h2>
+<a class="target" name="extending_unit"></a>Extending test cases</h2>
+ <p>
+ Of course additional test methods can be added to create
+ specific types of test case, so as to extend framework...
+<pre>
+require_once('simpletest/autorun.php');
+<strong>
+class FileTester extends UnitTestCase {
+ function FileTester($name = false) {
+ $this-&gt;UnitTestCase($name);
+ }
+
+ function assertFileExists($filename, $message = '%s') {
+ $this-&gt;assertTrue(
+ file_exists($filename),
+ sprintf($message, 'File [$filename] existence check'));
+ }</strong>
+}
+</pre>
+ Here the SimpleTest library is held in a folder called
+ <em>simpletest</em> that is local.
+ Substitute your own path for this.
+ </p>
+ <p>
+ To prevent this test case being run accidently, it is
+ advisable to mark it as <span class="new_code">abstract</span>.
+ </p>
+ <p>
+ Alternatively you could add a
+ <span class="new_code">SimpleTestOptions::ignore('FileTester');</span>
+ directive in your code.
+ </p>
+ <p>
+ This new case can be now be inherited just like
+ a normal test case...
+<pre>
+class FileTestCase extends <strong>FileTester</strong> {
+
+ function setUp() {
+ @unlink('../temp/test.txt');
+ }
+
+ function tearDown() {
+ @unlink('../temp/test.txt');
+ }
+
+ function testCreation() {
+ $writer = &amp;new FileWriter('../temp/test.txt');
+ $writer-&gt;write('Hello');<strong>
+ $this-&gt;assertFileExists('../temp/test.txt');</strong>
+ }
+}
+</pre>
+ </p>
+ <p>
+ If you want a test case that does not have all of the
+ <span class="new_code">UnitTestCase</span> assertions,
+ only your own and a few basics,
+ you need to extend the <span class="new_code">SimpleTestCase</span>
+ class instead.
+ It is found in <em>simple_test.php</em> rather than
+ <em>unit_tester.php</em>.
+ See <a href="group_test_documentation.html">later</a> if you
+ want to incorporate other unit tester's
+ test cases in your test suites.
+ </p>
+
+ <h2>
+<a class="target" name="running_unit"></a>Running a single test case</h2>
+ <p>
+ 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.
+ With <em>autorun</em> no particular scaffolding is needed,
+ just launch your particular test file and you're ready to go.
+ </p>
+ <p>
+ You can even decide which reporter (for example,
+ <span class="new_code">TextReporter</span> or <span class="new_code">HtmlReporter</span>)
+ you prefer for a specific file when launched on its own...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');<strong>
+SimpleTest :: prefer(new TextReporter());</strong>
+require_once('../classes/writer.php');
+
+class FileTestCase extends UnitTestCase {
+ ...
+}
+?&gt;
+</pre>
+ This script will run as is, but of course will output zero passes
+ and zero failures until test methods are added.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ <a href="http://simpletest.org/api/">Full API for SimpleTest</a>
+ from the PHPDoc.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <span class="chosen">Unit tester</span>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/en/web_tester_documentation.html b/3rdparty/simpletest/docs/en/web_tester_documentation.html
new file mode 100644
index 00000000000..aa9df50a679
--- /dev/null
+++ b/3rdparty/simpletest/docs/en/web_tester_documentation.html
@@ -0,0 +1,588 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest for PHP web script testing documentation</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <span class="chosen">Web tester</span>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Web tester documentation</h1>
+ This page...
+ <ul>
+<li>
+ Successfully <a href="#fetch">fetching a web page</a>
+ </li>
+<li>
+ Testing the <a href="#content">page content</a>
+ </li>
+<li>
+ <a href="#navigation">Navigating a web site</a>
+ while testing
+ </li>
+<li>
+ <a href="#request">Raw request modifications</a> and debugging methods
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="fetch"></a>Fetching a page</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ SimpleTest includes a special form of test case for the testing
+ of web page actions.
+ The <span class="new_code">WebTestCase</span> includes facilities
+ for navigation, content and cookie checks and form handling.
+ Usage of these test cases is similar to the
+ <a href="unit_tester_documentation.html">UnitTestCase</a>...
+<pre>
+<strong>class TestOfLastcraft extends WebTestCase {
+}</strong>
+</pre>
+ Here we are about to test the
+ <a href="http://www.lastcraft.com/">Last Craft</a> site itself.
+ If this test case is in a file called <em>lastcraft_test.php</em>
+ then it can be loaded in a runner script just like unit tests...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');<strong>
+require_once('simpletest/web_tester.php');</strong>
+SimpleTest::prefer(new TextReporter());
+
+class WebTests extends TestSuite {
+ function WebTests() {
+ $this-&gt;TestSuite('Web site tests');<strong>
+ $this-&gt;addFile('lastcraft_test.php');</strong>
+ }
+}
+?&gt;
+</pre>
+ I am using the text reporter here to more clearly
+ distinguish the web content from the test output.
+ </p>
+ <p>
+ Nothing is being tested yet.
+ We can fetch the home page by using the
+ <span class="new_code">get()</span> method...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+ <strong>
+ function testHomepage() {
+ $this-&gt;assertTrue($this-&gt;get('http://www.lastcraft.com/'));
+ }</strong>
+}
+</pre>
+ The <span class="new_code">get()</span> 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 <span class="new_code">get()</span> method will still return true.
+ </p>
+ <p>
+ Assuming that the web server for the Last Craft site is up
+ (sadly not always the case), we should see...
+<pre class="shell">
+Web site tests
+OK
+Test cases run: 1/1, Failures: 0, Exceptions: 0
+</pre>
+ All we have really checked is that any kind of page was
+ returned.
+ We don't yet know if it was the right one.
+ </p>
+
+ <h2>
+<a class="target" name="content"></a>Testing page content</h2>
+ <p>
+ To confirm that the page we think we are on is actually the
+ page we are on, we need to verify the page content.
+<pre>
+class TestOfLastcraft extends WebTestCase {
+
+ function testHomepage() {<strong>
+ $this-&gt;get('http://www.lastcraft.com/');
+ $this-&gt;assertText('Why the last craft');</strong>
+ }
+}
+</pre>
+ 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.
+ </p>
+ <p>
+ Here is the list of possible content assertions...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">assertTitle($title)</span></td>
+<td>Pass if title is an exact match</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertText($text)</span></td>
+<td>Pass if matches visible and "alt" text</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoText($text)</span></td>
+<td>Pass if doesn't match visible and "alt" text</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertPattern($pattern)</span></td>
+<td>A Perl pattern match against the page content</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoPattern($pattern)</span></td>
+<td>A Perl pattern match to not find content</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertLink($label)</span></td>
+<td>Pass if a link with this text is present</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoLink($label)</span></td>
+<td>Pass if no link with this text is present</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertLinkById($id)</span></td>
+<td>Pass if a link with this id attribute is present</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoLinkById($id)</span></td>
+<td>Pass if no link with this id attribute is present</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertField($name, $value)</span></td>
+<td>Pass if an input tag with this name has this value</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertFieldById($id, $value)</span></td>
+<td>Pass if an input tag with this id has this value</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertResponse($codes)</span></td>
+<td>Pass if HTTP response matches this list</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertMime($types)</span></td>
+<td>Pass if MIME type is in this list</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertAuthentication($protocol)</span></td>
+<td>Pass if the current challenge is this protocol</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoAuthentication()</span></td>
+<td>Pass if there is no current challenge</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertRealm($name)</span></td>
+<td>Pass if the current challenge realm matches</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertHeader($header, $content)</span></td>
+<td>Pass if a header was fetched matching this value</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoHeader($header)</span></td>
+<td>Pass if a header was not fetched</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertCookie($name, $value)</span></td>
+<td>Pass if there is currently a matching cookie</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoCookie($name)</span></td>
+<td>Pass if there is currently no cookie of this name</td>
+</tr>
+ </tbody></table>
+ 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.
+ </p>
+ <p>
+ So now we could instead test against the title tag with...
+<pre>
+<strong>$this-&gt;assertTitle('The Last Craft? Web developer tutorials on PHP, Extreme programming and Object Oriented development');</strong>
+</pre>
+ ...or, if that is too long and fragile...
+<pre>
+<strong>$this-&gt;assertTitle(new PatternExpectation('/The Last Craft/'));</strong>
+</pre>
+ As well as the simple HTML content checks we can check
+ that the MIME type is in a list of allowed types with...
+<pre>
+<strong>$this-&gt;assertMime(array('text/plain', 'text/html'));</strong>
+</pre>
+ 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...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+
+ function testRedirects() {
+ $this-&gt;get('http://www.lastcraft.com/test/redirect.php');
+ $this-&gt;assertResponse(200);&lt;/strong&gt;
+ }
+}
+</pre>
+ 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 <span class="new_code">WebTestCase</span> 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...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+
+ function testHomepage() {<strong>
+ $this-&gt;setMaximumRedirects(0);</strong>
+ $this-&gt;get('http://www.lastcraft.com/test/redirect.php');
+ $this-&gt;assertResponse(200);
+ }
+}
+</pre>
+ The assertion now fails as expected...
+<pre class="shell">
+Web site tests
+1) Expecting response in [200] got [302]
+ in testhomepage
+ in testoflastcraft
+ in lastcraft_test.php
+FAILURES!!!
+Test cases run: 1/1, Failures: 1, Exceptions: 0
+</pre>
+ We can modify the test to correctly assert redirects with...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+
+ function testHomepage() {
+ $this-&gt;setMaximumRedirects(0);
+ $this-&gt;get('http://www.lastcraft.com/test/redirect.php');
+ $this-&gt;assertResponse(<strong>array(301, 302, 303, 307)</strong>);
+ }
+}
+</pre>
+ This now passes.
+ </p>
+
+ <h2>
+<a class="target" name="navigation"></a>Navigating a web site</h2>
+ <p>
+ 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...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+ ...
+ function testContact() {
+ $this-&gt;get('http://www.lastcraft.com/');<strong>
+ $this-&gt;clickLink('About');
+ $this-&gt;assertTitle(new PatternExpectation('/About Last Craft/'));</strong>
+ }
+}
+</pre>
+ The parameter is the text of the link.
+ </p>
+ <p>
+ If the target is a button rather than an anchor tag, then
+ <span class="new_code">clickSubmit()</span> can be used
+ with the button title...
+<pre>
+<strong>$this-&gt;clickSubmit('Go!');</strong>
+</pre>
+ If you are not sure or don't care, the usual case, then just
+ use the <span class="new_code">click()</span> method...
+<pre>
+<strong>$this-&gt;click('Go!');</strong>
+</pre>
+ </p>
+ <p>
+ The list of navigation methods is...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">getUrl()</span></td>
+<td>The current location</td>
+</tr>
+ <tr>
+<td><span class="new_code">get($url, $parameters)</span></td>
+<td>Send a GET request with these parameters</td>
+</tr>
+ <tr>
+<td><span class="new_code">post($url, $parameters)</span></td>
+<td>Send a POST request with these parameters</td>
+</tr>
+ <tr>
+<td><span class="new_code">head($url, $parameters)</span></td>
+<td>Send a HEAD request without replacing the page content</td>
+</tr>
+ <tr>
+<td><span class="new_code">retry()</span></td>
+<td>Reload the last request</td>
+</tr>
+ <tr>
+<td><span class="new_code">back()</span></td>
+<td>Like the browser back button</td>
+</tr>
+ <tr>
+<td><span class="new_code">forward()</span></td>
+<td>Like the browser forward button</td>
+</tr>
+ <tr>
+<td><span class="new_code">authenticate($name, $password)</span></td>
+<td>Retry after a challenge</td>
+</tr>
+ <tr>
+<td><span class="new_code">restart()</span></td>
+<td>Restarts the browser as if a new session</td>
+</tr>
+ <tr>
+<td><span class="new_code">getCookie($name)</span></td>
+<td>Gets the cookie value for the current context</td>
+</tr>
+ <tr>
+<td><span class="new_code">ageCookies($interval)</span></td>
+<td>Ages current cookies prior to a restart</td>
+</tr>
+ <tr>
+<td><span class="new_code">clearFrameFocus()</span></td>
+<td>Go back to treating all frames as one page</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmit($label)</span></td>
+<td>Click the first button with this label</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmitByName($name)</span></td>
+<td>Click the button with this name attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmitById($id)</span></td>
+<td>Click the button with this ID attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImage($label, $x, $y)</span></td>
+<td>Click an input tag of type image by title or alt text</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImageByName($name, $x, $y)</span></td>
+<td>Click an input tag of type image by name</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImageById($id, $x, $y)</span></td>
+<td>Click an input tag of type image by ID attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">submitFormById($id)</span></td>
+<td>Submit a form without the submit value</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickLink($label, $index)</span></td>
+<td>Click an anchor by the visible label text</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickLinkById($id)</span></td>
+<td>Click an anchor by the ID attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">getFrameFocus()</span></td>
+<td>The name of the currently selected frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFrameFocusByIndex($choice)</span></td>
+<td>Focus on a frame counting from 1</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFrameFocus($name)</span></td>
+<td>Focus on a frame by name</td>
+</tr>
+ </tbody></table>
+ </p>
+ <p>
+ The parameters in the <span class="new_code">get()</span>, <span class="new_code">post()</span> or
+ <span class="new_code">head()</span> 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.
+ </p>
+ <p>
+ The <span class="new_code">retry()</span>, <span class="new_code">back()</span> and
+ <span class="new_code">forward()</span> 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.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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
+ <a href="form_testing_documentation.html">tools for testing web forms</a>
+ as well.
+ </p>
+
+ <h2>
+<a class="target" name="request"></a>Modifying the request</h2>
+ <p>
+ 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...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">getTransportError()</span></td>
+<td>The last socket error</td>
+</tr>
+ <tr>
+<td><span class="new_code">showRequest()</span></td>
+<td>Dump the outgoing request</td>
+</tr>
+ <tr>
+<td><span class="new_code">showHeaders()</span></td>
+<td>Dump the incoming headers</td>
+</tr>
+ <tr>
+<td><span class="new_code">showSource()</span></td>
+<td>Dump the raw HTML page content</td>
+</tr>
+ <tr>
+<td><span class="new_code">ignoreFrames()</span></td>
+<td>Do not load framesets</td>
+</tr>
+ <tr>
+<td><span class="new_code">setCookie($name, $value)</span></td>
+<td>Set a cookie from now on</td>
+</tr>
+ <tr>
+<td><span class="new_code">addHeader($header)</span></td>
+<td>Always add this header to the request</td>
+</tr>
+ <tr>
+<td><span class="new_code">setMaximumRedirects($max)</span></td>
+<td>Stop after this many redirects</td>
+</tr>
+ <tr>
+<td><span class="new_code">setConnectionTimeout($timeout)</span></td>
+<td>Kill the connection after this time between bytes</td>
+</tr>
+ <tr>
+<td><span class="new_code">useProxy($proxy, $name, $password)</span></td>
+<td>Make requests via this proxy URL</td>
+</tr>
+ </tbody></table>
+ These methods are principally for debugging.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ The <a href="http://simpletest.org/api/">developer's API for SimpleTest</a>
+ gives full detail on the classes and assertions available.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <span class="chosen">Web tester</span>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/fr/authentication_documentation.html b/3rdparty/simpletest/docs/fr/authentication_documentation.html
new file mode 100644
index 00000000000..fe70e035593
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/authentication_documentation.html
@@ -0,0 +1,372 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Documentation Simple Test : tester l'authentification</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Documentation sur l'authentification</h1>
+ This page...
+ <ul>
+<li>
+ Passer au travers d'une <a href="#basique">authentification HTTP basique</a>
+ </li>
+<li>
+ Tester l'<a href="#cookies">authentification basée sur des cookies</a>
+ </li>
+<li>
+ Gérer les <a href="#session">sessions du navigateur</a> et les timeouts
+ </li>
+</ul>
+<div class="content">
+
+ <p>
+ 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.
+ </p>
+
+ <h2>
+<a class="target" name="basique"></a>Authentification HTTP basique</h2>
+ <p>
+ 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...
+<pre>
+class AuthenticationTest extends WebTestCase {<strong>
+ function test401Header() {
+ $this-&gt;get('http://www.lastcraft.com/protected/');
+ $this-&gt;showHeaders();
+ }</strong>
+}
+</pre>
+ Ce qui nous permet de voir les entêtes reçues...
+ <div class="demo">
+ <h1>File test</h1>
+<pre style="background-color: lightgray; color: black">
+HTTP/1.1 401 Authorization Required
+Date: Sat, 18 Sep 2004 19:25:18 GMT
+Server: Apache/1.3.29 (Unix) PHP/4.3.4
+WWW-Authenticate: Basic realm="SimpleTest basic authentication"
+Connection: close
+Content-Type: text/html; charset=iso-8859-1
+</pre>
+ <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
+ <strong>0</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
+ </div>
+ 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...
+<pre>
+class AuthenticationTest extends WebTestCase {
+ function test401Header() {
+ $this-&gt;get('http://www.lastcraft.com/protected/');<strong>
+ $this-&gt;assertAuthentication('Basic');
+ $this-&gt;assertResponse(401);
+ $this-&gt;assertRealm('SimpleTest basic authentication');</strong>
+ }
+}
+</pre>
+ N'importe laquelle de ces assertions suffirait,
+ tout dépend de la masse de détails que vous souhaitez voir.
+ </p>
+ <p>
+ Un des axes qui traverse SimpleTest est la possibilité d'utiliser
+ des objets <span class="new_code">SimpleExpectation</span> à chaque fois qu'une
+ vérification simple suffit.
+ Si vous souhaitez vérifiez simplement le contenu du realm - l'identification
+ du domaine - dans notre exemple, il suffit de faire...
+<pre>
+class AuthenticationTest extends WebTestCase {
+ function test401Header() {
+ $this-&gt;get('http://www.lastcraft.com/protected/');
+ $this-&gt;assertRealm(<strong>new PatternExpectation('/simpletest/i')</strong>);
+ }
+}
+</pre>
+ Ce type de test, vérifier les réponses HTTP, n'est cependant pas commun.
+ </p>
+ <p>
+ 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 :
+<pre>
+class AuthenticationTest extends WebTestCase {
+ function testAuthentication() {
+ $this-&gt;get('http://www.lastcraft.com/protected/');<strong>
+ $this-&gt;authenticate('Me', 'Secret');</strong>
+ $this-&gt;assertTitle(...);
+ }
+}
+</pre>
+ 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 mais SimpleTest est assez
+ intelligent pour fusionner les sous-répertoires dans un même domaine.
+ </p>
+ <p>
+ Vous pouvez gagner une ligne en définissant
+ l'authentification au niveau de l'URL...
+<pre>
+class AuthenticationTest extends WebTestCase {
+ function testCanReadAuthenticatedPages() {
+ $this-&gt;get('http://<strong>Me:Secret@</strong>www.lastcraft.com/protected/');
+ $this-&gt;assertTitle(...);
+ }
+}
+</pre>
+ 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.
+ </p>
+ <p>
+ Normalement, vous utilisez l'appel <span class="new_code">authenticate()</span>. SimpleTest
+ utilisera alors vos informations de connexion à chaque requête.
+ </p>
+ <p>
+ 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.
+ </p>
+
+ <h2>
+<a class="target" name="cookies"></a>Cookies</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ Commençons par un simple formulaire de connexion...
+<pre>
+&lt;form&gt;
+ Username:
+ &lt;input type="text" name="u" value="" /&gt;&lt;br /&gt;
+ Password:
+ &lt;input type="password" name="p" value="" /&gt;&lt;br /&gt;
+ &lt;input type="submit" value="Log in" /&gt;
+&lt;/form&gt;
+</pre>
+ Lequel doit ressembler à...
+ </p>
+ <p>
+ <form class="demo">
+ Username:
+ <input type="text" name="u" value=""><br>
+ Password:
+ <input type="password" name="p" value=""><br>
+ <input type="submit" value="Log in">
+ </form>
+ </p>
+ <p>
+ 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...
+<pre>
+class LogInTest extends WebTestCase {
+ function testSessionCookieSetBeforeForm() {
+ $this-&gt;get('http://www.my-site.com/login.php');<strong>
+ $this-&gt;assertCookie('SID');</strong>
+ }
+}
+</pre>
+ 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 vaudrait pas la peine d'être testée avec...
+<pre>
+class LogInTest extends WebTestCase {
+ function testSessionCookieIsCorrectPattern() {
+ $this-&gt;get('http://www.my-site.com/login.php');
+ $this-&gt;assertCookie('SID', <strong>new PatternExpectation('/[a-f0-9]{32}/i')</strong>);
+ }
+}
+</pre>
+ Si vous utilisez PHP pour gérer vos sessions alors
+ ce test est encore plus inutile, étant donné qu'il ne fait
+ que tester PHP lui-même.
+ </p>
+ <p>
+ Le test le plus simple pour vérifier que la connexion a bien eu lieu
+ reste d'inspecter visuellement la page suivante :
+ un simple appel à <span class="new_code">WebTestCase::assertText()</span> et le tour est joué.
+ </p>
+ <p>
+ 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é :
+<pre>
+class LogInTest extends WebTestCase {
+ ...
+ function testSessionCookieSameAfterLogIn() {
+ $this-&gt;get('http://www.my-site.com/login.php');<strong>
+ $session = $this-&gt;getCookie('SID');
+ $this-&gt;setField('u', 'Me');
+ $this-&gt;setField('p', 'Secret');
+ $this-&gt;clickSubmit('Log in');
+ $this-&gt;assertWantedPattern('/Welcome Me/');
+ $this-&gt;assertCookie('SID', $session);</strong>
+ }
+}
+</pre>
+ Ceci confirme que l'identifiant de session
+ est identique avant et après la connexion.
+ </p>
+ <p>
+ Nous pouvons même essayer de duper notre propre système
+ en créant un cookie arbitraire pour se connecter...
+<pre>
+class LogInTest extends WebTestCase {
+ ...
+ function testSessionCookieSameAfterLogIn() {
+ $this-&gt;get('http://www.my-site.com/login.php');<strong>
+ $this-&gt;setCookie('SID', 'Some other session');
+ $this-&gt;get('http://www.my-site.com/restricted.php');</strong>
+ $this-&gt;assertWantedPattern('/Access denied/');
+ }
+}
+</pre>
+ Votre site est-il protégé contre ce type d'attaque ?
+ </p>
+
+ <h2>
+<a class="target" name="session"></a>Sessions de navigateur</h2>
+ <p>
+ 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 :
+<pre>
+class LogInTest extends WebTestCase {
+ ...
+ function testLoseAuthenticationAfterBrowserClose() {
+ $this-&gt;get('http://www.my-site.com/login.php');
+ $this-&gt;setField('u', 'Me');
+ $this-&gt;setField('p', 'Secret');
+ $this-&gt;clickSubmit('Log in');
+ $this-&gt;assertWantedPattern('/Welcome Me/');<strong>
+
+ $this-&gt;restart();
+ $this-&gt;get('http://www.my-site.com/restricted.php');
+ $this-&gt;assertWantedPattern('/Access denied/');</strong>
+ }
+}
+</pre>
+ La méthode <span class="new_code">WebTestCase::restart()</span> préserve
+ les cookies dont le timeout n'a pas expiré,
+ mais jette les cookies temporaires ou expirés.
+ Vous pouvez spécifier l'heure et la date de leur réactivation.
+ </p>
+ <p>
+ 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...
+ </p>
+ <p>
+ Afin de provoquer leur expiration,
+ vous pouvez dater manuellement les cookies,
+ avant le début de la session.
+<pre>
+class LogInTest extends WebTestCase {
+ ...
+ function testLoseAuthenticationAfterOneHour() {
+ $this-&gt;get('http://www.my-site.com/login.php');
+ $this-&gt;setField('u', 'Me');
+ $this-&gt;setField('p', 'Secret');
+ $this-&gt;clickSubmit('Log in');
+ $this-&gt;assertWantedPattern('/Welcome Me/');
+ <strong>
+ $this-&gt;ageCookies(3600);</strong>
+ $this-&gt;restart();
+ $this-&gt;get('http://www.my-site.com/restricted.php');
+ $this-&gt;assertWantedPattern('/Access denied/');
+ }
+}
+</pre>
+ Après le redémarrage, les cookies seront plus vieux
+ d'une heure et que tous ceux dont la date d'expiration
+ sera passée auront disparus.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ La page de téléchargement de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ <a href="http://simpletest.org/api/">L'API du développeur pour SimpleTest</a> donne tous les détails sur les classes et les assertions disponibles.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/fr/browser_documentation.html b/3rdparty/simpletest/docs/fr/browser_documentation.html
new file mode 100644
index 00000000000..6be1267773b
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/browser_documentation.html
@@ -0,0 +1,500 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Documentation SimpleTest : le composant de navigation web scriptable</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Documentation sur le navigateur scriptable</h1>
+ This page...
+ <ul>
+<li>
+ Utiliser le <a href="#scripting">navigateur web dans des scripts</a>
+ </li>
+<li>
+ <a href="#deboguer">Déboguer</a> les erreurs sur les pages
+ </li>
+<li>
+ <a href="#unit">Tests complexes avec des navigateurs web multiples</a>
+ </li>
+</ul>
+<div class="content">
+
+ <p>
+ Le composant de navigation web de SimpleTest peut être utilisé
+ non seulement à l'extérieur de la classe <span class="new_code">WebTestCase</span>,
+ mais aussi indépendamment du framework SimpleTest lui-même.
+ </p>
+
+ <h2>
+<a class="target" name="script"></a>Le navigateur scriptable</h2>
+ <p>
+ 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 <a href="http://www.php.net/">site web PHP</a>...
+<pre>
+&lt;?php
+ require_once('simpletest/browser.php');
+
+ $browser = &amp;new SimpleBrowser();
+ $browser-&gt;get('http://php.net/');
+ $browser-&gt;clickLink('reporting bugs');
+ $browser-&gt;clickLink('statistics');
+ $browser-&gt;clickLink('PHP 5 bugs only');
+ $page = $browser-&gt;getContent();
+ preg_match('/status=Open.*?by=Any.*?(\d+)&lt;\/a&gt;/', $page, $matches);
+ print $matches[1];
+?&gt;
+</pre>
+ 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 <span class="new_code">file()</span> 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 formulaires et la capacité
+ d'examiner les entêtes.
+ </p>
+ <p>
+ Ces méthodes qui se basent sur le contenu textuel des pages
+ 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.
+ </p>
+ <p>
+ Toutes les méthode de navigation utilisées dans <a href="web_tester_documentation.html">WebTestCase</a> sont présente dans la classe <span class="new_code">SimpleBrowser</span>, mais les assertions sont remplacées par de simples accesseurs. Voici une liste complète des méthodes de navigation de page à page...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">addHeader($header)</span></td>
+<td>Ajouter une entête à chaque téléchargement</td>
+</tr>
+ <tr>
+<td><span class="new_code">useProxy($proxy, $username, $password)</span></td>
+<td>Utilise ce proxy à partir de maintenant</td>
+</tr>
+ <tr>
+<td><span class="new_code">head($url, $parameters)</span></td>
+<td>Effectue une requête HEAD</td>
+</tr>
+ <tr>
+<td><span class="new_code">get($url, $parameters)</span></td>
+<td>Télécharge une page avec un GET</td>
+</tr>
+ <tr>
+<td><span class="new_code">post($url, $parameters)</span></td>
+<td>Télécharge une page avec un POST</td>
+</tr>
+ <tr>
+<td><span class="new_code">click($label)</span></td>
+<td>Suit un lien visible ou un bouton texte par son étiquette</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickLink($label)</span></td>
+<td>Suit un lien par son étiquette</td>
+</tr>
+ <tr>
+<td><span class="new_code">isLink($label)</span></td>
+<td>Vérifie l'existance d'un lien par son étiquette</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickLinkById($id)</span></td>
+<td>Suit un lien par son attribut d'identification</td>
+</tr>
+ <tr>
+<td><span class="new_code">isLinkById($id)</span></td>
+<td>Vérifie l'existance d'un lien par son attribut d'identification</td>
+</tr>
+ <tr>
+<td><span class="new_code">getUrl()</span></td>
+<td>La page ou la fenêtre URL en cours</td>
+</tr>
+ <tr>
+<td><span class="new_code">getTitle()</span></td>
+<td>Le titre de la page</td>
+</tr>
+ <tr>
+<td><span class="new_code">getContent()</span></td>
+<td>Le page ou la fenêtre brute</td>
+</tr>
+ <tr>
+<td><span class="new_code">getContentAsText()</span></td>
+<td>Sans code HTML à l'exception du text "alt"</td>
+</tr>
+ <tr>
+<td><span class="new_code">retry()</span></td>
+<td>Répète la dernière requête</td>
+</tr>
+ <tr>
+<td><span class="new_code">back()</span></td>
+<td>Utilise le bouton "précédent" du navigateur</td>
+</tr>
+ <tr>
+<td><span class="new_code">forward()</span></td>
+<td>Utilise le bouton "suivant" du navigateur</td>
+</tr>
+ <tr>
+<td><span class="new_code">authenticate($username, $password)</span></td>
+<td>Retente la page ou la fenêtre après une réponse 401</td>
+</tr>
+ <tr>
+<td><span class="new_code">restart($date)</span></td>
+<td>Relance le navigateur pour une nouvelle session</td>
+</tr>
+ <tr>
+<td><span class="new_code">ageCookies($interval)</span></td>
+<td>Change la date des cookies</td>
+</tr>
+ <tr>
+<td><span class="new_code">setCookie($name, $value)</span></td>
+<td>Lance un nouveau cookie</td>
+</tr>
+ <tr>
+<td><span class="new_code">getCookieValue($host, $path, $name)</span></td>
+<td>Lit le cookie le plus spécifique</td>
+</tr>
+ <tr>
+<td><span class="new_code">getCurrentCookieValue($name)</span></td>
+<td>Lit le contenue du cookie en cours</td>
+</tr>
+ </tbody></table>
+ Les méthode <span class="new_code">SimpleBrowser::useProxy()</span> et
+ <span class="new_code">SimpleBrowser::addHeader()</span> sont spéciales.
+ Une fois appelées, elles continuent à s'appliquer sur les téléchargements suivants.
+ </p>
+ <p>
+ Naviguer dans les formulaires est similaire à la <a href="form_testing_documentation.html">navigation des formulaires via WebTestCase</a>...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">setField($label, $value)</span></td>
+<td>Modifie tous les champs avec cette étiquette ou ce nom</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFieldByName($name, $value)</span></td>
+<td>Modifie tous les champs avec ce nom</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFieldById($id, $value)</span></td>
+<td>Modifie tous les champs avec cet identifiant</td>
+</tr>
+ <tr>
+<td><span class="new_code">getField($label)</span></td>
+<td>Accesseur de la valeur d'un élément de formulaire avec cette étiquette ou ce nom</td>
+</tr>
+ <tr>
+<td><span class="new_code">getFieldByName($name)</span></td>
+<td>Accesseur de la valeur d'un élément de formulaire avec ce nom</td>
+</tr>
+ <tr>
+<td><span class="new_code">getFieldById($id)</span></td>
+<td>Accesseur de la valeur de l'élément de formulaire avec cet identifiant</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmit($label)</span></td>
+<td>Transmet le formulaire avec l'étiquette de son bouton</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmitByName($name)</span></td>
+<td>Transmet le formulaire avec l'attribut de son bouton</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmitById($id)</span></td>
+<td>Transmet le formulaire avec l'identifiant de son bouton</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImage($label, $x, $y)</span></td>
+<td>Clique sur une balise input de type image par son titre (title="*") our son texte alternatif (alt="*")</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImageByName($name, $x, $y)</span></td>
+<td>Clique sur une balise input de type image par son attribut (name="*")</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImageById($id, $x, $y)</span></td>
+<td>Clique sur une balise input de type image par son identifiant (id="*")</td>
+</tr>
+ <tr>
+<td><span class="new_code">submitFormById($id)</span></td>
+<td>Transmet le formulaire par son identifiant propre</td>
+</tr>
+ </tbody></table>
+ Au jourd d'aujourd'hui il n'existe pas beaucoup de méthodes pour lister
+ les formulaires et les champs disponibles.
+ <table><tbody>
+ <tr>
+<td><span class="new_code">isClickable($label)</span></td>
+<td>Vérifie si un lien existe avec cette étiquette ou ce nom</td>
+</tr>
+ <tr>
+<td><span class="new_code">isSubmit($label)</span></td>
+<td>Vérifie si un bouton existe avec cette étiquette ou ce nom</td>
+</tr>
+ <tr>
+<td><span class="new_code">isImage($label)</span></td>
+<td>Vérifie si un bouton image existe avec cette étiquette ou ce nom</td>
+</tr>
+ <tr>
+<td><span class="new_code">getLink($label)</span></td>
+<td>Trouve une URL à partir de son label</td>
+</tr>
+ <tr>
+<td><span class="new_code">getLinkById($label)</span></td>
+<td>Trouve une URL à partir de son identifiant</td>
+</tr>
+ <tr>
+<td><span class="new_code">getUrls()</span></td>
+<td>Liste l'ensemble des liens de la page courante</td>
+</tr>
+ </tbody></table>
+ Ce sera probablement
+ ajouté dans des versions successives de SimpleTest.
+ </p>
+ <p>
+ 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
+ une 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".
+ <table><tbody>
+ <tr>
+<td><span class="new_code">getFrames()</span></td>
+<td>Un déchargement de la structure de la fenêtre courante</td>
+</tr>
+ <tr>
+<td><span class="new_code">getFrameFocus()</span></td>
+<td>L'index ou l'étiquette de la fenêtre en courante</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFrameFocusByIndex($choice)</span></td>
+<td>Sélectionne la fenêtre numérotée à partir de 1</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFrameFocus($name)</span></td>
+<td>Sélectionne une fenêtre par son étiquette</td>
+</tr>
+ <tr>
+<td><span class="new_code">clearFrameFocus()</span></td>
+<td>Traite toutes les fenêtres comme une seule page</td>
+</tr>
+ </tbody></table>
+ 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.
+ </p>
+
+ <h2>
+<a class="target" name="deboguer"></a>Où sont les erreurs ?</h2>
+ <p>
+ 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.
+ <table><tbody>
+ <tr>
+<td><span class="new_code">setConnectionTimeout($timeout)</span></td>
+<td>Ferme la socket avec un délai trop long</td>
+</tr>
+ <tr>
+<td><span class="new_code">getUrl()</span></td>
+<td>L'URL de la page chargée le plus récemment</td>
+</tr>
+ <tr>
+<td><span class="new_code">getRequest()</span></td>
+<td>L'entête de la requête brute de la page ou de la fenêtre</td>
+</tr>
+ <tr>
+<td><span class="new_code">getHeaders()</span></td>
+<td>L'entête de réponse de la page ou de la fenêtre</td>
+</tr>
+ <tr>
+<td><span class="new_code">getTransportError()</span></td>
+<td>N'importe quel erreur au niveau de la socket dans le dernier téléchargement</td>
+</tr>
+ <tr>
+<td><span class="new_code">getResponseCode()</span></td>
+<td>La réponse HTTP de la page ou de la fenêtre</td>
+</tr>
+ <tr>
+<td><span class="new_code">getMimeType()</span></td>
+<td>Le type Mime de la page our de la fenêtre</td>
+</tr>
+ <tr>
+<td><span class="new_code">getAuthentication()</span></td>
+<td>Le type d'authentification dans l'entête d'une provocation 401</td>
+</tr>
+ <tr>
+<td><span class="new_code">getRealm()</span></td>
+<td>Le realm d'authentification dans l'entête d'une provocation 401</td>
+</tr>
+ <tr>
+<td><span class="new_code">getBaseUrl()</span></td>
+<td>Uniquement la base de l'URL de la page chargée le plus récemment</td>
+</tr>
+ <tr>
+<td><span class="new_code">setMaximumRedirects($max)</span></td>
+<td>Nombre de redirections avant que la page ne soit chargée automatiquement</td>
+</tr>
+ <tr>
+<td><span class="new_code">setMaximumNestedFrames($max)</span></td>
+<td>Protection contre des framesets récursifs</td>
+</tr>
+ <tr>
+<td><span class="new_code">ignoreFrames()</span></td>
+<td>Neutralise le support des fenêtres</td>
+</tr>
+ <tr>
+<td><span class="new_code">useFrames()</span></td>
+<td>Autorise le support des fenêtres</td>
+</tr>
+ </tbody></table>
+ Les méthodes <span class="new_code">SimpleBrowser::setConnectionTimeout()</span>,
+ <span class="new_code">SimpleBrowser::setMaximumRedirects()</span>,
+ <span class="new_code">SimpleBrowser::setMaximumNestedFrames()</span>,
+ <span class="new_code">SimpleBrowser::ignoreFrames()</span>
+ et <span class="new_code">SimpleBrowser::useFrames()</span> 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 individuelle ne se charge pas,
+ il suffit de se diriger vers elle avec
+ <span class="new_code">SimpleBrowser::setFrameFocus()</span> : ensuite on utilisera
+ <span class="new_code">SimpleBrowser::getRequest()</span>, etc. pour voir ce qui se passe.
+ </p>
+
+ <h2>
+<a class="target" name="unit"></a>Tests unitaires complexes avec des navigateurs multiples</h2>
+ <p>
+ Tout ce qui peut être fait dans
+ <a href="web_tester_documentation.html">WebTestCase</a> peut maintenant
+ être fait dans un <a href="unit_tester_documentation.html">UnitTestCase</a>.
+ Ce qui revient à dire que nous pouvons librement mélanger
+ des tests sur des objets de domaine avec l'interface web...
+<pre><strong>
+class TestOfRegistration extends UnitTestCase {
+ function testNewUserAddedToAuthenticator() {</strong>
+ $browser = new SimpleBrowser();
+ $browser-&gt;get('http://my-site.com/register.php');
+ $browser-&gt;setField('email', 'me@here');
+ $browser-&gt;setField('password', 'Secret');
+ $browser-&gt;clickSubmit('Register');
+ <strong>
+ $authenticator = new Authenticator();
+ $member = $authenticator-&gt;findByEmail('me@here');
+ $this-&gt;assertEqual($member-&gt;getPassword(), 'Secret');</strong>
+ }
+}
+</pre>
+ Bien que ça puisse être utile par convenance temporaire,
+ je ne suis pas fan de ce genre de test. Ce test s'applique
+ à plusieurs couches de l'application, ça implique qu'il est
+ plus que probable qu'il faudra le remanier lorsque le code changera.
+ </p>
+ <p>
+ Un cas plus utile d'utilisation directe du navigateur est
+ le moment où le <span class="new_code">WebTestCase</span> ne peut plus suivre.
+ Un exemple ? Quand deux navigateurs doivent être utilisés en même temps.
+ </p>
+ <p>
+ 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...
+<pre>
+class TestOfSecurity extends UnitTestCase {
+ function testNoMultipleLoginsFromSameUser() {
+ $first = &amp;new SimpleBrowser();
+ $first-&gt;get('http://my-site.com/login.php');
+ $first-&gt;setField('name', 'Me');
+ $first-&gt;setField('password', 'Secret');
+ $first-&gt;clickSubmit('Enter');
+ $this-&gt;assertEqual($first-&gt;getTitle(), 'Welcome');
+
+ $second = &amp;new SimpleBrowser();
+ $second-&gt;get('http://my-site.com/login.php');
+ $second-&gt;setField('name', 'Me');
+ $second-&gt;setField('password', 'Secret');
+ $second-&gt;clickSubmit('Enter');
+ $this-&gt;assertEqual($second-&gt;getTitle(), 'Access Denied');
+ }
+}
+</pre>
+ Vous pouvez aussi utiliser la classe <span class="new_code">SimpleBrowser</span>
+ quand vous souhaitez écrire des scénarios de test en utilisant
+ un autre outil que SimpleTest, comme PHPUnit par exemple.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ La page du projet SimpleTest sur
+ <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ La page de téléchargement de SimpleTest sur
+ <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ <a href="http://simpletest.org/api/">L'API de développeur pour SimpleTest</a>
+ donne tous les détails sur les classes et les assertions disponibles.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/fr/docs.css b/3rdparty/simpletest/docs/fr/docs.css
new file mode 100755
index 00000000000..49170486ab3
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/docs.css
@@ -0,0 +1,84 @@
+body {
+ padding-left: 3%;
+ padding-right: 3%;
+}
+pre {
+ font-family: "courier new", courier;
+ font-size: 80%;
+ border: 1px solid;
+ background-color: #cccccc;
+ padding: 5px;
+ margin-left: 5%;
+ margin-right: 8%;
+}
+.code, .new_code, pre.new_code {
+ font-weight: bold;
+}
+div.copyright {
+ font-size: 80%;
+ color: gray;
+}
+div.copyright a {
+ color: gray;
+}
+ul.api {
+ padding-left: 0em;
+ padding-right: 25%;
+}
+ul.api li {
+ margin-top: 0.2em;
+ margin-bottom: 0.2em;
+ list-style: none;
+ text-indent: -3em;
+ padding-left: 3em;
+}
+div.demo {
+ border: 4px ridge;
+ border-color: gray;
+ padding: 10px;
+ margin: 5px;
+ margin-left: 20px;
+ margin-right: 40px;
+ background-color: white;
+}
+div.demo span.fail {
+ color: red;
+}
+div.demo span.pass {
+ color: green;
+}
+div.demo h1 {
+ font-size: 12pt;
+ text-align: left;
+ font-weight: bold;
+}
+table {
+ border: 2px outset;
+ border-color: gray;
+ background-color: white;
+ margin: 5px;
+ margin-left: 5%;
+ margin-right: 5%;
+}
+td {
+ font-size: 80%;
+}
+.shell {
+ color: white;
+}
+pre.shell {
+ border: 4px ridge;
+ border-color: gray;
+ padding: 10px;
+ margin: 5px;
+ margin-left: 20px;
+ margin-right: 40px;
+ background-color: black;
+}
+form.demo {
+ background-color: lightgray;
+ border: 4px outset;
+ border-color: lightgray;
+ padding: 10px;
+ margin-right: 40%;
+}
diff --git a/3rdparty/simpletest/docs/fr/expectation_documentation.html b/3rdparty/simpletest/docs/fr/expectation_documentation.html
new file mode 100644
index 00000000000..ee579110a6d
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/expectation_documentation.html
@@ -0,0 +1,451 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Documentation SimpleTest : étendre le testeur unitaire avec des classes d'attentes supplémentaires</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Documentation sur les attentes</h1>
+ This page...
+ <ul>
+<li>
+ Utiliser les attentes <a href="#fantaisie">pour des tests
+ plus précis avec des objets fantaisie</a>
+ </li>
+<li>
+ <a href="#comportement">Changer le comportement d'un objet fantaisie</a>
+ avec des attentes
+ </li>
+<li>
+ <a href="#etendre">Créer des attentes</a>
+ </li>
+<li>
+ Par dessous SimpleTest <a href="#unitaire">utilise des classes d'attente</a>
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="fantaisie"></a>Plus de contrôle sur les objets fantaisie</h2>
+ <p>
+ Le comportement par défaut des
+ <a href="mock_objects_documentation.html">objets fantaisie</a> dans
+ <a href="http://sourceforge.net/projects/simpletest/">SimpleTest</a>
+ 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.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ Voici un cas concret, nous avons un service d'actualités
+ qui a échoué dans sa tentative de connexion à sa source distante.
+<pre>
+<strong>class NewsService {
+ ...
+ function publish($writer) {
+ if (! $this-&gt;isConnected()) {
+ $writer-&gt;write('Cannot connect to news service "' .
+ $this-&gt;_name . '" at this time. ' .
+ 'Please try again later.');
+ }
+ ...
+ }
+}</strong>
+</pre>
+ Là il envoie son contenu vers un classe <span class="new_code">Writer</span>.
+ Nous pourrions tester ce comportement avec un <span class="new_code">MockWriter</span>...
+<pre>
+class TestOfNewsService extends UnitTestCase {
+ ...
+ function testConnectionFailure() {<strong>
+ $writer = new MockWriter($this);
+ $writer-&gt;expectOnce('write', array(
+ 'Cannot connect to news service ' .
+ '"BBC News" at this time. ' .
+ 'Please try again later.'));
+
+ $service = new NewsService('BBC News');
+ $service-&gt;publish($writer);
+
+ $writer-&gt;tally();</strong>
+ }
+}
+</pre>
+ 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é.
+ </p>
+ <p>
+ 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...
+<pre>
+class TestOfNewsService extends UnitTestCase {
+ ...
+ function testConnectionFailure() {
+ $writer = new MockWriter($this);<strong>
+ $writer-&gt;expectOnce(
+ 'write',
+ array(new PatternExpectation('/cannot connect/i')));</strong>
+
+ $service = new NewsService('BBC News');
+ $service-&gt;publish($writer);
+
+ $writer-&gt;tally();
+ }
+}
+</pre>
+ Plutôt que de transmettre le paramètre attendu au <span class="new_code">MockWriter</span>,
+ nous envoyons une classe d'attente appelée <span class="new_code">PatternExpectation</span>.
+ 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.
+ </p>
+ <p>
+ <span class="new_code">PatternExpectation</span> utilise
+ l'expression rationnelle pour la comparaison avec son constructeur.
+ A chaque fois qu'une comparaison est fait à travers
+ <span class="new_code">MockWriter</span> par rapport à cette classe attente,
+ elle fera un <span class="new_code">preg_match()</span> 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.
+ </p>
+ <p>
+ Les classes attente possibles sont...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">AnythingExpectation</span></td>
+<td>Sera toujours validé</td>
+</tr>
+ <tr>
+<td><span class="new_code">EqualExpectation</span></td>
+<td>Une égalité, plutôt que la plus forte comparaison à l'identique</td>
+</tr>
+ <tr>
+<td><span class="new_code">NotEqualExpectation</span></td>
+<td>Une comparaison sur la non-égalité</td>
+</tr>
+ <tr>
+<td><span class="new_code">IndenticalExpectation</span></td>
+<td>La vérification par défaut de l'objet fantaisie qui doit correspondre exactement</td>
+</tr>
+ <tr>
+<td><span class="new_code">NotIndenticalExpectation</span></td>
+<td>Inverse la logique de l'objet fantaisie</td>
+</tr>
+ <tr>
+<td><span class="new_code">PatternExpectation</span></td>
+<td>Utilise une expression rationnelle Perl pour comparer une chaîne</td>
+</tr>
+ <tr>
+<td><span class="new_code">NoPatternExpectation</span></td>
+<td>Passe seulement si l'expression rationnelle Perl échoue</td>
+</tr>
+ <tr>
+<td><span class="new_code">IsAExpectation</span></td>
+<td>Vérifie le type ou le nom de la classe uniquement</td>
+</tr>
+ <tr>
+<td><span class="new_code">NotAExpectation</span></td>
+<td>L'opposé de <span class="new_code">IsAExpectation</span>
+</td>
+</tr>
+ <tr>
+<td><span class="new_code">MethodExistsExpectation</span></td>
+<td>Vérifie si la méthode est disponible sur un objet</td>
+</tr>
+ <tr>
+<td><span class="new_code">TrueExpectation</span></td>
+<td>Accepte n'importe quelle variable PHP qui vaut vrai</td>
+</tr>
+ <tr>
+<td><span class="new_code">FalseExpectation</span></td>
+<td>Accepte n'importe quelle variable PHP qui vaut faux</td>
+</tr>
+ </tbody></table>
+ La plupart utilisent la valeur attendue dans le constructeur.
+ Les exceptions sont les vérifications sur motif,
+ qui utilisent une expression rationnelle, ainsi que
+ <span class="new_code">IsAExpectation</span> et <span class="new_code">NotAExpectation</span>,
+ qui prennent un type ou un nom de classe comme chaîne.
+ </p>
+
+ <h2>
+<a class="target" name="comportement"></a>Utiliser les attentes pour contrôler les bouchons serveur</h2>
+ <p>
+ Les classes attente peuvent servir à autre chose
+ que l'envoi d'assertions depuis les objets fantaisie,
+ afin de choisir le comportement d'un
+ <a href="mock_objects_documentation.html">objet fantaisie</a>
+ ou celui d'un <a href="server_stubs_documentation.html">bouchon serveur</a>.
+ A chaque fois qu'une liste d'arguments est donnée,
+ une liste d'objets d'attente peut être insérée à la place.
+ </p>
+ <p>
+ 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...
+<pre>
+Stub::generate('Authorisation');
+<strong>
+$authorisation = new StubAuthorisation();
+$authorisation-&gt;returns(
+ 'isAllowed',
+ true,
+ array(new IsAExpectation('Session', 'Must be a session')));
+$authorisation-&gt;returns('isAllowed', false);</strong>
+</pre>
+ Le comportement par défaut du bouchon serveur
+ est défini pour renvoyer <span class="new_code">false</span>
+ quand <span class="new_code">isAllowed</span> est appelé.
+ Lorsque nous appelons cette méthode avec un unique paramètre
+ qui est un objet <span class="new_code">Session</span>, il renverra <span class="new_code">true</span>.
+ 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.
+ </p>
+ <p>
+ Ce niveau de sophistication est rarement utile :
+ il n'est inclut que pour être complet.
+ </p>
+
+ <h2>
+<a class="target" name="etendre"></a>Créer vos propres attentes</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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
+ <span class="new_code">SimpleExpectation</span> ou une autre de ses sous-classes...
+<pre>
+<strong>class ValidIp extends SimpleExpectation {
+
+ function test($ip) {
+ return (ip2long($ip) != -1);
+ }
+
+ function testMessage($ip) {
+ return "Address [$ip] should be a valid IP address";
+ }
+}</strong>
+</pre>
+ Il n'y a véritablement que deux méthodes à mettre en place.
+ La méthode <span class="new_code">test()</span> devrait renvoyer un <span class="new_code">true</span>
+ si l'attente doit passer, et une erreur <span class="new_code">false</span>
+ dans le cas contraire. La méthode <span class="new_code">testMessage()</span>
+ ne devrait renvoyer que du texte utile à la compréhension du test en lui-même.
+ </p>
+ <p>
+ Cette classe peut désormais être employée à la place
+ des classes d'attente précédentes.
+ </p>
+ <p>
+ Voici un exemple plus typique, vérifier un hash...
+<pre>
+<strong>class JustField extends EqualExpectation {
+ private $key;
+
+ function __construct($key, $expected) {
+ parent::__construct($expected);
+ $this-&gt;key = $key;
+ }
+
+ function test($compare) {
+ if (! isset($compare[$this-&gt;key])) {
+ return false;
+ }
+ return parent::test($compare[$this-&gt;key]);
+ }
+
+ function testMessage($compare) {
+ if (! isset($compare[$this-&gt;key])) {
+ return 'Key [' . $this-&gt;key . '] does not exist';
+ }
+ return 'Key [' . $this-&gt;key . '] -&gt; ' .
+ parent::testMessage($compare[$this-&gt;key]);
+ }
+}</strong>
+</pre>
+ L'habitude a été prise pour séparer les clauses du message avec
+ "&amp;nbsp;-&gt;&amp;nbsp;".
+ Cela permet aux outils dérivés de reformater la sortie.
+ </p>
+ <p>
+ Supposons qu'un authentificateur s'attend à recevoir
+ une ligne de base de données correspondant à l'utilisateur,
+ et que nous avons juste besoin de valider le nom d'utilisateur.
+ Nous pouvons le faire très simplement avec...
+<pre>
+$mock-&gt;expectOnce('authenticate',
+ array(new JustKey('username', 'marcus')));
+</pre>
+ </p>
+
+ <h2>
+<a class="target" name="unitaire"></a>Sous le capot du testeur unitaire</h2>
+ <p>
+ Le <a href="http://sourceforge.net/projects/simpletest/">framework
+ de test unitaire SimpleTest</a> utilise aussi dans son coeur
+ des classes d'attente pour
+ la <a href="unit_test_documentation.html">classe UnitTestCase</a>.
+ 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.
+ </p>
+ <p>
+ La méthode la plus directe est d'utiliser la méthode
+ <span class="new_code">SimpleTest::assert()</span> pour effectuer le test...
+<pre>
+<strong>class TestOfNetworking extends UnitTestCase {
+ ...
+ function testGetValidIp() {
+ $server = &amp;new Server();
+ $this-&gt;assert(
+ new ValidIp(),
+ $server-&gt;getIp(),
+ 'Server IP address-&gt;%s');
+ }
+}</strong>
+</pre>
+ <span class="new_code">assert()</span> testera toute attente directement.
+ </p>
+ <p>
+ C'est plutôt sale par rapport à notre syntaxe habituelle
+ du type <span class="new_code">assert...()</span>.
+ </p>
+ <p>
+ 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...
+<pre>
+class TestOfNetworking extends UnitTestCase {
+ ...<strong>
+ function assertValidIp($ip, $message = '%s') {
+ $this-&gt;assertExpectation(new ValidIp(), $ip, $message);
+ }</strong>
+
+ function testGetValidIp() {
+ $server = &amp;new Server();<strong>
+ $this-&gt;assertValidIp(
+ $server-&gt;getIp(),
+ 'Server IP address-&gt;%s');</strong>
+ }
+}
+</pre>
+ It is rare to need the expectations for more than pattern
+ matching, but these facilities do allow testers to build
+ some sort of domain language for testing their application.
+ Also, complex expectation classes could make the tests
+ harder to read and debug.
+ In effect extending the test framework to create their own tool set.
+
+
+ Il est assez rare que le besoin d'une attente dépasse
+ le stade de la reconnaissance d'un motif, mais ils permettent
+ aux testeurs de construire leur propre langage dédié ou DSL
+ (Domain Specific Language) pour tester leurs applications.
+ Attention, 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.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ La page du projet SimpleTest sur
+ <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ La page de téléchargement de SimpleTest sur
+ <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ Les attentes imitent les contraintes dans
+ <a href="http://www.jmock.org/">JMock</a>.
+ </li>
+<li>
+ <a href="http://simpletest.org/api/">L'API complète pour SimpleTest</a>
+ réalisé avec PHPDoc.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/fr/form_testing_documentation.html b/3rdparty/simpletest/docs/fr/form_testing_documentation.html
new file mode 100644
index 00000000000..e3cb6a10a19
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/form_testing_documentation.html
@@ -0,0 +1,363 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Documentation SimpleTest : tester des formulaires HTML</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Documentation sur les tests de formulaire</h1>
+ This page...
+ <ul>
+<li>
+ Modifier les valeurs d'un formulaire et
+ <a href="#submit">réussir à transmettre un simple formulaire</a>
+ </li>
+<li>
+ Gérer des <a href="#multiple">objets à valeurs multiples</a>
+ en initialisant des listes.
+ </li>
+<li>
+ Le cas des formulaires utilisant Javascript pour
+ modifier <a href="#hidden-field">un champ caché</a>
+ </li>
+<li>
+ <a href="#brut">Envoi brut</a> quand il n'existe pas de bouton à cliquer.
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="submit"></a>Valider un formulaire simple</h2>
+ <p>
+ Lorsqu'une page est téléchargée par <span class="new_code">WebTestCase</span>
+ en utilisant <span class="new_code">get()</span> ou <span class="new_code">post()</span>
+ 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 &lt;form&gt; sont disponibles
+ depuis l'intérieur du scénario de test.
+ Prenons par exemple cet extrait de code HTML...
+<pre>
+&lt;form&gt;
+ &lt;input type="text" name="a" value="A default" /&gt;
+ &lt;input type="submit" value="Go" /&gt;
+&lt;/form&gt;
+</pre>
+ Il ressemble à...
+ </p>
+ <p>
+ <form class="demo">
+ <input type="text" name="a" value="A default">
+ <input type="submit" value="Go">
+ </form>
+ </p>
+ <p>
+ Nous pouvons naviguer vers ce code, via le site
+ <a href="http://www.lastcraft.com/form_testing_documentation.php">LastCraft</a>,
+ avec le test suivant...
+<pre>
+class SimpleFormTests extends WebTestCase {<strong>
+ function testDefaultValue() {
+ $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this-&gt;assertField('a', 'A default');
+ }</strong>
+}
+</pre>
+ 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".
+ </p>
+ <p>
+ Nous pourrions retourner le formulaire tout de suite...
+<pre>
+class SimpleFormTests extends WebTestCase {
+ function testDefaultValue() {
+ $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this-&gt;assertField('a', <strong>new PatternExpectation('/default/')</strong>);
+ }
+}
+</pre>
+ Mais d'abord nous allons changer la valeur du champ texte.
+ Ce n'est qu'après que nous le transmettrons...
+<pre>
+class SimpleFormTests extends WebTestCase {
+
+ function testDefaultValue() {
+ $this-&gt;get('http://www.my-site.com/');
+ $this-&gt;assertField('a', 'A default');<strong>
+ $this-&gt;setField('a', 'New value');
+ $this-&gt;clickSubmit('Go');</strong>
+ }
+}
+</pre>
+ 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 <em>GET</em>
+ vers la même page. En règle générale 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
+ <a href="http://www.w3.org/People/Raggett/tidy/">HTMLTidy</a>
+ devraient être employés, ou même n'importe lequel des validateurs HTML et CSS
+ déjà sur le marché.
+ </p>
+ <p>
+ Si un champ manque dans n'importe quel formulaire ou si
+ une option est indisponible alors <span class="new_code">WebTestCase::setField()</span>
+ renverra <span class="new_code">false</span>. Par exemple, supposons que
+ nous souhaitons vérifier qu'une option "Superuser"
+ n'est pas présente dans ce formulaire...
+<pre>
+<strong>Select type of user to add:</strong>
+&lt;select name="type"&gt;
+ &lt;option&gt;Subscriber&lt;/option&gt;
+ &lt;option&gt;Author&lt;/option&gt;
+ &lt;option&gt;Administrator&lt;/option&gt;
+&lt;/select&gt;
+</pre>
+ Qui ressemble à...
+ </p>
+ <p>
+ <form class="demo">
+ <strong>Select type of user to add:</strong>
+ <select name="type">
+ <option>Subscriber</option>
+ <option>Author</option>
+ <option>Administrator</option>
+ </select>
+ </form>
+ </p>
+ <p>
+ Le test suivant le confirmera...
+<pre>
+class SimpleFormTests extends WebTestCase {
+ ...
+ function testNoSuperuserChoiceAvailable() {<strong>
+ $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this-&gt;assertFalse($this-&gt;setField('type', 'Superuser'));</strong>
+ }
+}
+</pre>
+ La sélection ne sera pas changée si la nouvelle valeur n'est pas une des options.
+ </p>
+ <p>
+ Voici la liste complète des objets supportés à aujourd'hui...
+ <ul>
+ <li>Champs texte, y compris les champs masqués (hidden) ou cryptés (password).</li>
+ <li>Boutons submit, en incluant aussi la balise button, mais pas encore les boutons reset</li>
+ <li>Aires texte (textarea) avec leur gestion des retours à la ligne (wrap).</li>
+ <li>Cases à cocher, y compris les cases à cocher multiples dans un même formulaire.</li>
+ <li>Listes à menu déroulant, y compris celles à sélections multiples.</li>
+ <li>Boutons radio.</li>
+ <li>Images.</li>
+ </ul>
+ </p>
+ <p>
+ Le navigateur proposé par SimpleTest émule les actions
+ qui peuvent être réalisées par un utilisateur sur
+ une page HTML standard. Javascript n'est pas supporté et
+ il y a peu de chance pour qu'il le soit prochainement.
+ </p>
+ <p>
+ Une attention particulière doit être porté aux techniques Javascript
+ qui changent la valeur d'un champ caché : elles ne peuvent pas être
+ réalisées avec les commandes classiques de SimpleTest.
+ Une méthode alternative est proposée plus loin.
+ </p>
+
+ <h2>
+<a class="target" name="multiple"></a>Champs à valeurs multiples</h2>
+ <p>
+ 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...
+<pre>
+&lt;form class="demo"&gt;
+ <strong>Create privileges allowed:</strong>
+ &lt;input type="checkbox" name="crud" value="c" checked&gt;&lt;br&gt;
+ <strong>Retrieve privileges allowed:</strong>
+ &lt;input type="checkbox" name="crud" value="r" checked&gt;&lt;br&gt;
+ <strong>Update privileges allowed:</strong>
+ &lt;input type="checkbox" name="crud" value="u" checked&gt;&lt;br&gt;
+ <strong>Destroy privileges allowed:</strong>
+ &lt;input type="checkbox" name="crud" value="d" checked&gt;&lt;br&gt;
+ &lt;input type="submit" value="Enable Privileges"&gt;
+&lt;/form&gt;
+</pre>
+ Qui se traduit par...
+ </p>
+ <p>
+ <form class="demo">
+ <strong>Create privileges allowed:</strong>
+ <input type="checkbox" name="crud" value="c" checked><br>
+ <strong>Retrieve privileges allowed:</strong>
+ <input type="checkbox" name="crud" value="r" checked><br>
+ <strong>Update privileges allowed:</strong>
+ <input type="checkbox" name="crud" value="u" checked><br>
+ <strong>Destroy privileges allowed:</strong>
+ <input type="checkbox" name="crud" value="d" checked><br>
+ <input type="submit" value="Enable Privileges">
+ </form>
+ </p>
+ <p>
+ 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...
+<pre>
+class SimpleFormTests extends WebTestCase {
+ ...<strong>
+ function testDisableNastyPrivileges() {
+ $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this-&gt;assertField('crud', array('c', 'r', 'u', 'd'));
+ $this-&gt;setField('crud', array('r'));
+ $this-&gt;clickSubmit('Enable Privileges');
+ }</strong>
+}
+</pre>
+ 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'autres bouts de code de test
+ pour confirmer cet effet, peut-être en nous connectant
+ comme utilisateur et en essayant d'effectuer une mise à jour.
+ </p>
+
+ <h2>
+<a class="target" name="hidden-field"></a>Formulaires utilisant Javascript pour changer un champ caché</h2>
+ <p>
+ Si vous souhaitez tester un formulaire dépendant de Javascript
+ pour la modification d'un champ caché, vous ne pouvez pas
+ simplement utiliser setField().
+ Le code suivant <em>ne fonctionnera pas</em> :
+<pre>
+class SimpleFormTests extends WebTestCase {
+ function testEmulateMyJavascriptForm() {
+ <strong>// This does *not* work</strong>
+ $this-&gt;setField('a_hidden_field', '123');
+ $this-&gt;clickSubmit('OK');
+ }
+}
+</pre>
+ A la place, vous aurez besoin d'ajouter le paramètre supplémentaire
+ du formulaire à la méthode clickSubmit() :
+<pre>
+class SimpleFormTests extends WebTestCase {
+ function testMyJavascriptForm() {
+ <strong>$this-&gt;clickSubmit('OK', array('a_hidden_field'=&gt;'123'));</strong>
+ }
+
+}
+</pre>
+ </p>
+ <p>
+ N'oubliez pas que de la sorte, vous êtes effectivement en train
+ de court-circuitez une partie de votre application (le code Javascript
+ dans le formulaire) et que peut-être serait-il plus prudent
+ d'utiliser un outil comme
+ <a href="http://selenium.openqa.org/">Selenium</a> pour mettre sur pied
+ un test complet.
+ </p>
+
+ <h2>
+<a class="target" name="brut"></a>Envoi brut</h2>
+ <p>
+ 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.
+<pre>
+class SimpleFormTests extends WebTestCase {
+ ...<strong>
+ function testAttemptedHack() {
+ $this-&gt;post(
+ 'http://www.my-site.com/add_user.php',
+ array('type' =&gt; 'superuser'));
+ $this-&gt;assertNoUnwantedPattern('/user created/i');
+ }</strong>
+}
+</pre>
+ En ajoutant des données à la méthode <span class="new_code">WebTestCase::post()</span>,
+ nous émulons la transmission d'un formulaire.
+ D'ordinaire, vous ne ferez cela que pour parer au plus pressé,
+ ou alors si vous espérez un tiers (javascript ?) transmette le formulaire.
+ Il reste quand même exception : si vous souhaitez vous protégez
+ d'attaques de type "spoofing".
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ La page du projet SimpleTest sur
+ <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ La page de téléchargement de SimpleTest sur
+ <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ <a href="http://simpletest.org/api/">L'API du développeur pour SimpleTest</a>
+ donne tous les détails sur les classes et les assertions disponibles.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/fr/group_test_documentation.html b/3rdparty/simpletest/docs/fr/group_test_documentation.html
new file mode 100644
index 00000000000..fb546af4603
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/group_test_documentation.html
@@ -0,0 +1,265 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Documentation SimpleTest : Grouper des tests</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Documentation sur le groupement des tests</h1>
+ This page...
+ <ul>
+<li>
+ Plusieurs approches pour <a href="#group">grouper des tests</a> ensemble.
+ </li>
+<li>
+ Combiner des groupes des tests dans des
+ <a href="#plus-haut">groupes plus grands</a>.
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="grouper"></a>Grouper des tests</h2>
+ <p>
+ Il existe beaucoup de moyens pour grouper des tests dans des suites de tests.
+ Le premier d'entre eux est tout simplement ajouter tous les scénarios de test
+ au fur et à mesure d'un unique fichier...
+<pre>
+<strong>&lt;?php
+require_once(dirname(__FILE__) . '/simpletest/autorun.php');
+require_once(dirname(__FILE__) . '/../classes/io.php');
+
+class FileTester extends UnitTestCase {
+ ...
+}
+
+class SocketTester extends UnitTestCase {
+ ...
+}
+?&gt;</strong>
+</pre>
+ Autant de scénarios que nécessaires peuvent être
+ mis dans cet unique fichier. Ils doivent contenir
+ tout le code nécessaire, entre autres la bibliothèque testée,
+ mais aucune des bibliothèques de SimpleTest.
+ </p>
+ <p>
+ Occasionnellement des sous-classes spéciales sont créés pour
+ ajouter des méthodes nécessaires à certains tests spécifiques
+ au sein de l'application.
+ Ces nouvelles classes de base sont ensuite utilisées
+ à la place de <span class="new_code">UnitTestCase</span>
+ ou de <span class="new_code">WebTestCase</span>.
+ Bien sûr vous ne souhaitez pas les lancer en tant que
+ scénario de tests : il suffit alors de les identifier
+ comme "abstraites"...
+<pre>
+<strong>abstract</strong> class MyFileTestCase extends UnitTestCase {
+ ...
+}
+
+class FileTester extends MyFileTestCase { ... }
+
+class SocketTester extends UnitTestCase { ... }
+</pre>
+ La classe <span class="new_code">FileTester</span> ne contient aucun test véritable,
+ il s'agit d'une classe de base pour d'autres scénarios de test.
+ </p>
+ <p>
+ Nous appelons ce fichier <em>file_test.php</em>.
+ Pour l'instant les scénarios de tests sont simplement groupés dans le même fichier.
+ Nous pouvons mettre en place des structures plus importantes
+ en incluant d'autres fichiers de tests.
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('file_test.php');
+?&gt;
+</pre>
+ Ceci fontionnera, tout en créant une hiérarchie tout à fait plate.
+ A la place, nous créons un fichier de suite de tests.
+ Notre suite des tests de premier niveau devient...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+class AllFileTests extends TestSuite {
+ function __construct() {
+ parent::__construct();
+ <strong>$this-&gt;addFile('file_test.php');</strong>
+ }
+}
+?&gt;
+</pre>
+ Voici ce qui arrive : la class <span class="new_code">TestSuite</span>
+ effecturera le <span class="new_code">require_once()</span> pour nous.
+ Ensuite elle vérifie si de nouvelles classes de test
+ ont été créées par ce nouveau fichier et les inclut
+ automatiquement dans la suite de tests.
+ Cette méthode nous donne un maximum de contrôle
+ tout comme le ferait des ajouts manuels de fichiers de tests
+ au fur et à mesure où notre suite grandit.
+ </p>
+ <p>
+ Si c'est trop de boulot pour vos petits doigts et qu'en plus
+ vous avez envie de grouper vos suites de tests par répertoire
+ ou par un tag dans le nom des fichiers, alors il y a un moyen
+ encore plus automatique...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+class AllFileTests extends TestSuite {
+ function __construct() {
+ parent::__construct();
+ $this-&gt;collect(dirname(__FILE__) . '/unit',
+ new SimplePatternCollector('/_test.php/'));
+ }
+}
+?&gt;
+</pre>
+ Cette fonctionnalités va scanner un répertoire appelé "unit",
+ y détecter tous les fichiers finissant par "_test.php"
+ et les charger.
+ Vous n'avez pas besoin d'utiliser <span class="new_code">SimplePatternCollector</span> pour
+ filtrer en fonction d'un motif dans le nom de fichier,
+ mais c'est son usage le plus courant.
+ </p>
+ <p>
+ Ce morceau de code est très courant.
+ Désormais la seule chose qu'il vous reste à faire, c'est de
+ déposer un fichier avec des scénarios de tests dans ce répertoire
+ et il sera lancé directement par le script de la suite de tests.
+ </p>
+ <p>
+ Juste un bémol : vous ne pouvez pas contrôler l'ordre de lancement
+ des tests.
+ Si vous souhaitez voir des composants de bas niveau renvoyer leurs erreurs
+ dès le début de la suite de tests - en particulier pour se facilier le travail
+ de diagnostic - alors vous devriez plutôt passer par <span class="new_code">addFile()</span>
+ pour ces cas spécifiques.
+ Les scénarios de tests ne sont chargés qu'une fois, pas d'inquiétude donc
+ lors du scan de votre répertoire avec tous les tests.
+ </p>
+ <p>
+ Les tests chargés avec la méthode <span class="new_code">addFile</span> ont certaines propriétés
+ qui peuvent s'avérer intéressantes.
+ Elle vous assure que le constructeur est lancé avant la première méthode
+ de test et que le destructeur est lancé après la dernière méthode de test.
+ Cela vous permet de placer une initialisation (setUp et tearDown) globale
+ au sein de ce destructeur et desctructeur, comme dans n'importe
+ quelle classe.
+ </p>
+
+ <h2>
+<a class="target" name="plus-haut"></a>Groupements de plus haut niveau</h2>
+ <p>
+ 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.
+ </p>
+<p>
+ Tout ce que nous avons décrit avec des scripts de tests
+ s'applique pareillement avec des <span class="new_code">TestSuite</span>s...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+<strong>
+class BigTestSuite extends TestSuite {
+ function __construct() {
+ parent::__construct();
+ $this-&gt;addFile('file_tests.php');
+ }
+}</strong>
+?&gt;
+</pre>
+ Cette opération additionne nos scénarios de tests et une unique suite
+ sous la première.
+ Quand un test échoue, nous voyons le fil d'ariane avec l'enchainement.
+ Nous pouvons même mélanger groupes et tests librement en prenant
+ quand même soin d'éviter les inclusions en boucle.
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+class BigTestSuite extends TestSuite {
+ function __construct() {
+ parent::__construct();
+ $this-&gt;addFile('file_tests.php');
+ <strong>$this-&gt;addFile('some_other_test.php');</strong>
+ }
+}
+?&gt;
+</pre>
+ Petite précision, en cas de double inclusion, seule la première instance
+ sera lancée.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ La page du projet SimpleTest sur
+ <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ La page de téléchargement de SimpleTest sur
+ <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/fr/index.html b/3rdparty/simpletest/docs/fr/index.html
new file mode 100644
index 00000000000..f7e022c36ec
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/index.html
@@ -0,0 +1,576 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>
+ Prise en main rapide de SimpleTest pour PHP -
+ Tests unitaire et objets fantaisie pour PHP
+ </title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Prise en main rapide de SimpleTest</h1>
+ This page...
+ <ul>
+<li>
+ <a href="#unit">Utiliser le testeur rapidement</a>
+ avec un exemple.
+ </li>
+<li>
+ <a href="#group">Groupes de tests</a>
+ pour tester en un seul clic.
+ </li>
+<li>
+ <a href="#mock">Utiliser les objets fantaisie</a>
+ pour faciliter les tests et gagner en contrôle.
+ </li>
+<li>
+ <a href="#web">Tester des pages web</a>
+ au niveau de l'HTML.
+ </li>
+</ul>
+<div class="content">
+
+ <p>
+ 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
+ <a href="https://sourceforge.net/project/showfiles.php?group_id=76550">SimpleTest</a>.
+ Pour une documentation plus complète, particulièrement si
+ vous découvrez les tests unitaires, consultez la
+ <a href="http://www.lastcraft.com/unit_test_documentation.php">documentation
+ en cours</a>, et pour des exemples de scénarios de test,
+ consultez le
+ <a href="http://www.lastcraft.com/first_test_tutorial.php">tutorial
+ sur les tests unitaires</a>.
+ </p>
+
+ <h2>
+<a class="target" name="unit"></a>Utiliser le testeur rapidement</h2>
+ <p>
+ 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 <a href="http://www.junit.org/">JUnit</a> et des <a href="http://sourceforge.net/projects/phpunit/">PHPUnit</a>,
+ mais elle inclut aussi les <a href="http://www.mockobjects.com/">objets fantaisie ou
+ "mock objects"</a>.
+ </p>
+ <p>
+ Ce qui rend cet outil immédiatement utile pour un développeur PHP,
+ c'est son navigateur web interne.
+ Il permet des tests qui parcourent des sites web, remplissent
+ des formulaires et testent le contenu des pages.
+ Etre capable d'écrire ces tests en PHP veut dire qu'il devient
+ facile d'écrire des tests de recette (ou d'intégration).
+ Un exemple serait de confirmer qu'un utilisateur a bien été ajouté
+ dans une base de données après s'être enregistré sur une site web.
+ </p>
+ <p>
+ La démonstration la plus rapide : l'exemple
+ </p>
+ <p>
+ Supposons que nous sommes en train de tester une simple
+ classe de log dans un fichier : elle s'appelle
+ <span class="new_code">Log</span> dans <em>classes/Log.php</em>. Commençons
+ par créer un script de test, appelé
+ <em>tests/log_test.php</em>. Son contenu est le suivant...
+<pre>
+&lt;?php
+<strong>require_once('simpletest/autorun.php');</strong>
+require_once('../classes/log.php');
+
+class TestOfLogging extends <strong>UnitTestCase</strong> {
+}
+?&gt;
+</pre>
+ Ici le répertoire <em>simpletest</em> 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.
+ Le fichier "autorun.php" fait plus que juste inclure
+ les éléments de SimpleTest : il lance aussi les tests pour nous.
+ </p>
+ <p>
+ <span class="new_code">TestOfLogging</span> est notre premier scénario de test
+ et il est pour l'instant vide.
+ Chaque scénario de test est une classe qui étend une des classes
+ de base de SimpleTest. Nous pouvons avoir autant de classes de ce type
+ que nous voulons.
+ </p>
+ <p>
+ Avec ces trois lignes d'échafaudage
+ l'inclusion de notre classe <span class="new_code">Log</span>, nous avons une suite
+ de tests. Mais pas encore de test !
+ </p>
+ <p>
+ Pour notre premier test, supposons que la classe <span class="new_code">Log</span>
+ prenne le nom du fichier à écrire au sein du constructeur,
+ et que nous avons un répertoire temporaire dans lequel placer
+ ce fichier.
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('../classes/log.php');
+
+class TestOfLogging extends UnitTestCase {
+ function <strong>testLogCreatesNewFileOnFirstMessage()</strong> {
+ @unlink('/temp/test.log');
+ $log = new Log('/temp/test.log');
+ <strong>$this-&gt;assertFalse(file_exists('/temp/test.log'));</strong>
+ $log-&gt;message('Should write this to a file');
+ <strong>$this-&gt;assertTrue(file_exists('/temp/test.log'));</strong>
+ }
+}
+?&gt;
+</pre>
+ Au lancement du scénario de test, toutes les méthodes qui
+ commencent avec la chaîne <span class="new_code">test</span> sont
+ identifiées puis exécutées.
+ Si la méthode commence par <span class="new_code">test</span>, c'est un test.
+ Remarquez bien le nom très long de notre exemple :
+ <span class="new_code">testLogCreatesNewFileOnFirstMessage()</span>.
+ C'est bel et bien délibéré : ce style est considéré désirable
+ et il rend la sortie du test plus lisible.
+ </p>
+ <p>
+ D'ordinaire nous avons bien plusieurs méthodes de tests.
+ Mais ce sera pour plus tard.
+ </p>
+ <p>
+ 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é via un appel à <span class="new_code">print</span>code&gt;.
+ </p>
+ <p>
+ Pour voir ces résultats lançons effectivement les tests.
+ Aucun autre code n'est nécessaire, il suffit d'ouvrir
+ la page dans un navigateur.
+ </p>
+ <p>
+ En cas échec, l'affichage ressemble à...
+ <div class="demo">
+ <h1>TestOfLogging</h1>
+ <span class="fail">Fail</span>: testcreatingnewfile-&gt;True assertion failed.<br>
+ <div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
+ <strong>1</strong> passes and <strong>1</strong> fails.</div>
+ </div>
+ ...et si ça passe, on obtient...
+ <div class="demo">
+ <h1>TestOfLogging</h1>
+ <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
+ <strong>2</strong> passes and <strong>0</strong> fails.</div>
+ </div>
+ Et si vous obtenez ça...
+ <div class="demo">
+ <b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b>
+ </div>
+ c'est qu'il vous manque le fichier <em>classes/Log.php</em>
+ qui pourrait ressembler à :
+<pre>
+&lt;?php<strong>
+class Log {
+ function Log($file_path) {
+ }
+
+ function message() {
+ }
+}</strong>
+?&gt;
+</pre>
+ C'est largement plus sympathique d'écrire le code après le test.
+ Plus que sympatique même - cette technique s'appelle
+ "Développement Piloté par les Tests" ou
+ "Test Driven Development" en anglais.
+ </p>
+ <p>
+ Pour plus de renseignements sur le testeur, voyez la
+ <a href="unit_test_documentation.html">documentation pour les tests de régression</a>.
+ </p>
+
+ <h2>
+<a class="target" name="group"></a>Construire des groupes de tests</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ Notre première étape est de créer un nouveau fichier appelé
+ <em>tests/all_tests.php</em> et d'y inclure le code suivant...
+<pre>
+&lt;?php
+<strong>require_once('simpletest/autorun.php');</strong>
+
+class AllTests extends <strong>TestSuite</strong> {
+ function AllTests() {
+ $this-&gt;TestSuite(<strong>'All tests'</strong>);
+ <strong>$this-&gt;addFile('log_test.php');</strong>
+ }
+}
+?&gt;
+</pre>
+ L'inclusion de "autorun" permettra à notre future suite
+ de tests d'être lancée juste en invoquant ce script.
+ </p>
+ <p>
+ La sous-classe <span class="new_code">TestSuite</span> doit chaîner
+ son constructeur. Cette limitation sera supprimée dans
+ les versions à venir.
+ </p>
+ <p>
+ The method <span class="new_code">TestSuite::addFile()</span>
+ will include the test case file and read any new classes
+ that are descended from <span class="new_code">SimpleTestCase</span>.
+
+ Cette méthode <span class="new_code">TestSuite::addTestFile()</span> va
+ inclure le fichier de scénarios de test et lire parmi
+ toutes les nouvelles classes créées celles qui sont issues
+ de <span class="new_code">SimpleTestCase</span>.
+ <span class="new_code">UnitTestCase</span> est juste un exemple de classe dérivée
+ depuis <span class="new_code">SimpleTestCase</span> et vous pouvez créer les vôtres.
+ <span class="new_code">TestSuite::addFile()</span> peut aussi inclure d'autres suites.
+ </p>
+ <p>
+ La classe ne sera pas encore instanciée.
+ Quand la suite de tests est lancée, elle construira chaque instance
+ une fois le test atteint, et le détuira juste ensuite.
+ Cela veut dire que le constructeur n'est lancé qu'une fois avant
+ chaque initialisation de ce scénario de test et que le destructeur
+ est lui aussi lancé avant que le test suivant ne commence.
+ </p>
+ <p>
+ Il est commun de grouper des scénarios de test dans des super-classes
+ qui ne sont pas sensées être lancées, mais qui deviennent une classe de base
+ pour d'autres tests.
+ Pour que "autorun" fonctionne proprement les fichiers
+ des scénarios de test ne devraient pas lancer aveuglement
+ d'autres extensions de scénarios de test qui ne lanceraient pas
+ effectivement des tests.
+ Cela pourrait aboutir à un mauvais comptages des scénarios de test
+ pendant la procédure.
+ Pas vraiement un problème majeure, mais pour éviter cet inconvénient
+ il suffit de marquer vos classes de base comme <span class="new_code">abstract</span>.
+ SimpleTest ne lance pas les classes abstraites. Et si vous utilisez encore
+ PHP4 alors une directive <span class="new_code">SimpleTestOptions::ignore()</span>
+ dans votre fichier de scénario de test aura le même effet.
+ </p>
+ <p>
+ Par ailleurs, le fichier avec le scénario de test ne devrait pas
+ avoir été inclus ailleurs. Sinon aucun scénario de test
+ ne sera inclus à ce groupe.
+ Ceci pourrait se transformer en un problème plus grave :
+ si des fichiers ont déjà été inclus par PHP alors la méthode
+ <span class="new_code">TestSuite::addFile()</span> ne les détectera pas.
+ </p>
+ <p>
+ Pour afficher les résultats, il est seulement nécessaire
+ d'invoquer <em>tests/all_tests.php</em> à partir du serveur
+ web.
+ </p>
+ <p>
+ Pour plus de renseignements des groupes de tests, voyez le
+ <a href="group_test_documentation.html">documentation sur le groupement des tests</a>.
+ </p>
+
+ <h2>
+<a class="target" name="mock"></a>Utiliser les objets fantaisie</h2>
+ <p>
+ Avançons un peu plus dans le futur.
+ </p>
+ <p>
+ 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
+ <span class="new_code">SessionPool</span>. Nous voulons tester une méthode
+ qui ressemblera probablement à quelque chose comme...
+<pre><strong>
+class SessionPool {
+ ...
+ function logIn($username) {
+ ...
+ $this-&gt;_log-&gt;message('User $username logged in.');
+ ...
+ }
+ ...
+}
+</strong>
+</pre>
+ Avec le concept de "réutilisation de code" comme fil
+ conducteur, nous utilisons notre class <span class="new_code">Log</span>. Un
+ scénario de test classique ressemblera peut-être à...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('../classes/log.php');
+<strong>require_once('../classes/session_pool.php');</strong>
+
+class <strong>TestOfSessionLogging</strong> extends UnitTestCase {
+
+ function setUp() {
+ <strong>@unlink('/temp/test.log');</strong>
+ }
+
+ function tearDown() {
+ <strong>@unlink('/temp/test.log');</strong>
+ }
+
+ function testLoggingInIsLogged() {
+ <strong>$log = new Log('/temp/test.log');
+ $session_pool = &amp;new SessionPool($log);
+ $session_pool-&gt;logIn('fred');</strong>
+ $messages = file('/temp/test.log');
+ $this-&gt;assertEqual($messages[0], "User fred logged in.<strong>\n</strong>");
+ }
+}
+?&gt;
+</pre>
+ Nous expliquerons les méthodes <span class="new_code">setUp()</span>
+ et <span class="new_code">tearDown()</span> plus tard.
+ </p>
+ <p>
+ 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 <span class="new_code">Log</span> et ce test. Que se
+ passerait-il si nous n'utilisions plus de fichiers, mais la
+ bibliothèque <em>syslog</em> à la place ?
+
+ Cela veut dire que notre test <span class="new_code">TestOfSessionLogging</span>
+ enverra un échec alors même qu'il ne teste pas Logging.
+ </p>
+ <p>
+ Il est aussi fragile sur des petites retouches. 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 ?
+ </p>
+ <p>
+ L'unique partie à tester réellement est l'envoi d'un
+ message précis au loggueur.
+ Nous pouvons réduire 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.
+ </p>
+ <p>
+ 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.
+ <p>
+ </p>
+ Trop beau pour être vrai ? Pas vraiement on peut créer un tel
+ objet très facilement...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('../classes/log.php');
+require_once('../classes/session_pool.php');
+
+<strong>Mock::generate('Log');</strong>
+
+class TestOfSessionLogging extends UnitTestCase {
+
+ function testLoggingInIsLogged() {<strong>
+ $log = &amp;new MockLog();
+ $log-&gt;expectOnce('message', array('User fred logged in.'));</strong>
+ $session_pool = &amp;new SessionPool(<strong>$log</strong>);
+ $session_pool-&gt;logIn('fred');
+ }
+}
+?&gt;
+</pre>
+ L'appel <span class="new_code">Mock::generate()</span> a généré
+ une nouvelle classe appelé <span class="new_code">MockLog</span>.
+ Cela ressemble à un clone identique, sauf que nous pouvons
+ y adjoindre du code de test.
+ C'est ce que fait <span class="new_code">expectOnce()</span>.
+ Cela dit que si <span class="new_code">message()</span> m'est appelé,
+ il a intérêt à l'être avec le paramètre
+ "User fred logged in.".
+ </p>
+ <p>
+ L'appel <span class="new_code">tally()</span> 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 à <span class="new_code">message()</span> est
+ invoqué sur l'objet <span class="new_code">MockLog</span> par le code
+ <span class="new_code">SessionPool::logIn()</span>.
+ L'appel <span class="new_code">mock</span> 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
+ pour ne pas avoir à tester tous les paramètres d'un appel
+ alors que vous ne souhaitez qu'en tester un.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ Pour que ce test fonctionne la librairie avec les objets
+ fantaisie doit être incluse dans la suite de tests, par
+ exemple dans <em>all_tests.php</em>.
+ </p>
+ <p>
+ Pour plus de renseignements sur les objets fantaisie, voyez le
+ <a href="mock_objects_documentation.html">documentation sur les objets fantaisie</a>.
+ </p>
+
+ <h2>
+<a class="target" name="web"></a>Tester une page web</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ Effectuer un test web via SimpleTest reste assez primitif :
+ il n'y a pas de javascript par exemple.
+ La plupart des autres opérations d'un navigateur sont simulées.
+ </p>
+ <p>
+ 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.
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+<strong>require_once('simpletest/web_tester.php');</strong>
+
+class TestOfAbout extends <strong>WebTestCase</strong> {
+ function testOurAboutPageGivesFreeReignToOurEgo() {
+ <strong>$this-&gt;get('http://test-server/index.php');
+ $this-&gt;click('About');
+ $this-&gt;assertTitle('About why we are so great');
+ $this-&gt;assertText('We are really great');</strong>
+ }
+}
+?&gt;
+</pre>
+ 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.
+ </p>
+ <p>
+ Vous pouvez aussi naviguer à travers des formulaires...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('simpletest/web_tester.php');
+
+class TestOfRankings extends WebTestCase {
+ function testWeAreTopOfGoogle() {
+ $this-&gt;get('http://google.com/');
+ $this-&gt;setField('q', 'simpletest');
+ $this-&gt;click("I'm Feeling Lucky");
+ $this-&gt;assertTitle('SimpleTest - Unit Testing for PHP');
+ }
+}
+?&gt;
+</pre>
+ ...même si cela pourrait constituer une violation
+ des documents juridiques de Google(tm).
+ </p>
+ <p>
+ Pour plus de renseignements sur comment tester une page web, voyez la
+ <a href="web_tester_documentation.html">documentation sur tester des scripts web</a>.
+ </p>
+ <p>
+ <a href="http://sourceforge.net/projects/simpletest/"><img src="http://sourceforge.net/sflogo.php?group_id=76550&amp;type=5" width="210" height="62" border="0" alt="SourceForge.net Logo"></a>
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ <a href="https://sourceforge.net/project/showfiles.php?group_id=76550&amp;release_id=153280">Télécharger PHP SimpleTest</a>
+ depuis <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ L'<a href="http://simpletest.org/api/">API de SimpleTest pour développeur</a>
+ donne tous les détails sur les classes et assertions existantes.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/fr/mock_objects_documentation.html b/3rdparty/simpletest/docs/fr/mock_objects_documentation.html
new file mode 100644
index 00000000000..97e2c86ee73
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/mock_objects_documentation.html
@@ -0,0 +1,933 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Documentation SimpleTest : les objets fantaise</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Documentation sur les objets fantaisie</h1>
+ This page...
+ <ul>
+<li>
+ <a href="#what">Que sont les objets fantaisie ?</a>
+ </li>
+<li>
+ <a href="#creation">Créer des objets fantaisie</a>.
+ </li>
+<li>
+ <a href="#expectations">Les objets fantaisie en tant que critiques</a> avec les attentes.
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="what"></a>Que sont les objets fantaisie ?</h2>
+ <p>
+ Les objets fantaisie - ou "mock objects" en anglais -
+ ont deux rôles pendant un scénario de test : acteur et critique.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ Si les objets fantaisie ne se comportaient que comme
+ des acteurs alors on les connaîtrait sous le nom de
+ <a href="server_stubs_documentation.html">bouchons serveur</a>.
+ Il s'agissait originairement d'un patron de conception
+ identifié par Robert Binder (<a href="">Testing
+ object-oriented systems</a>: models, patterns, and tools,
+ Addison-Wesley) en 1999.
+ </p>
+ <p>
+ Un bouchon serveur est une simulation d'un objet ou d'un composant.
+ Il doit remplacer exactement un composant dans un système
+ en vue d'effectuer des tests ou un prototypage,
+ tout en restant ultra-léger.
+ Il permet aux tests de s'exécuter plus rapidement, ou
+ si la classe simulée n'a pas encore été écrite,
+ de se lancer tout court.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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.
+ </p>
+
+ <h2>
+<a class="target" name="creation"></a>Créer des objets fantaisie</h2>
+ <p>
+ Tout ce dont nous avons besoin est une classe existante ou une interface,
+ par exemple une connexion à la base de données qui ressemblerait à...
+<pre>
+<strong>class DatabaseConnection {
+ function DatabaseConnection() { }
+ function query($sql) { }
+ function selectQuery($sql) { }
+}</strong>
+</pre>
+ Pour en créer sa version fantaisie nous devons juste
+ lancer le générateur...
+<pre>
+require_once('simpletest/autorun.php');
+require_once('database_connection.php');
+
+<strong>Mock::generate('DatabaseConnection');</strong>
+</pre>
+ Ce code génère une classe clone appelée <span class="new_code">MockDatabaseConnection</span>.
+ Cette nouvelle classe lui ressemble en tout point,
+ sauf qu'elle ne fait rien du tout.
+ </p>
+ <p>
+ Cette nouvelle classe est génératlement
+ une sous-classe de <span class="new_code">DatabaseConnection</span>.
+ Malheureusement, il n'y as aucun moyen de créer une version fantaisie
+ d'une classe avec une méthode <span class="new_code">final</span> sans avoir
+ une version fonctionnelle de cette méthode.
+ Ce n'est pas pas très satisfaisant.
+ Si la cible est une interface ou si les méthodes <span class="new_code">final</span>
+ existent dans la classe cible, alors une toute nouvelle classe
+ est créée, elle implémente juste les même interfaces.
+ Si vous essayer de faire passer cette classe à travers un indice de type
+ qui spécifie le véritable nom de l'ancienne classe, alors il échouera.
+ Du code qui forcerait un indice de type tout en utilisant
+ des méthodes <span class="new_code">final</span> ne pourrait probablement pas être
+ testé efficacement avec des objets fantaisie.
+ </p>
+ <p>
+ Si vous voulez voir le code généré, il suffit de faire un <span class="new_code">print</span>
+ de la sortie de <span class="new_code">Mock::generate()</span>.
+ VOici le code généré pour la classe <span class="new_code">DatabaseConnection</span>
+ à la place de son interface...
+<pre>
+class MockDatabaseConnection extends DatabaseConnection {
+ public $mock;
+ protected $mocked_methods = array('databaseconnection', 'query', 'selectquery');
+
+ function MockDatabaseConnection() {
+ $this-&gt;mock = new SimpleMock();
+ $this-&gt;mock-&gt;disableExpectationNameChecks();
+ }
+ ...
+ function DatabaseConnection() {
+ $args = func_get_args();
+ $result = &amp;$this-&gt;mock-&gt;invoke("DatabaseConnection", $args);
+ return $result;
+ }
+ function query($sql) {
+ $args = func_get_args();
+ $result = &amp;$this-&gt;mock-&gt;invoke("query", $args);
+ return $result;
+ }
+ function selectQuery($sql) {
+ $args = func_get_args();
+ $result = &amp;$this-&gt;mock-&gt;invoke("selectQuery", $args);
+ return $result;
+ }
+}
+</pre>
+ Votre sortie dépendra quelque peu de votre version précise de SimpleTest.
+ </p>
+ <p>
+ En plus des méthodes d'origine de la classe, vous en verrez d'autres
+ pour faciliter les tests.
+ Nous y reviendrons.
+ </p>
+ <p>
+ Nous pouvons désormais créer des instances de
+ cette nouvelle classe à l'intérieur même de notre scénario de test...
+<pre>
+require_once('simpletest/autorun.php');
+require_once('database_connection.php');
+
+Mock::generate('DatabaseConnection');
+
+class MyTestCase extends UnitTestCase {
+
+ function testSomething() {
+ <strong>$connection = new MockDatabaseConnection();</strong>
+ }
+}
+</pre>
+ La version fantaisie contient toutles méthodes de l'originale.
+ En outre, tous les indices de type seront préservés.
+ Dison que nos méthodes de requête attend un objet <span class="new_code">Query</span>...
+<pre>
+<strong>class DatabaseConnection {
+ function DatabaseConnection() { }
+ function query(Query $query) { }
+ function selectQuery(Query $query) { }
+}</strong>
+</pre>
+ Si nous lui passons le mauvais type d'objet
+ ou même pire un non-objet...
+<pre>
+class MyTestCase extends UnitTestCase {
+
+ function testSomething() {
+ $connection = new MockDatabaseConnection();
+ $connection-&gt;query('insert into accounts () values ()');
+ }
+}
+</pre>
+ ...alors le code renverra une violation de typage,
+ exactement comme on aurait pû s'y attendre
+ avec la classe d'origine.
+ </p>
+ <p>
+ Si la version fantaisie implémente bien toutes les méthodes
+ de l'originale, elle renvoit aussi systématiquement <span class="new_code">null</span>.
+ Et comme toutes les méthodes qui renvoient toujours <span class="new_code">null</span>
+ ne sont pas très utiles, nous avons besoin de leur faire dire
+ autre chose...
+ </p>
+
+ <h2>
+<a class="target" name="bouchon"></a>Objets fantaisie en action</h2>
+ <p>
+ Changer le <span class="new_code">null</span> renvoyé par la méthode fantaisie
+ en autre chose est assez facile...
+<pre>
+<strong>$connection-&gt;returns('query', 37)</strong>
+</pre>
+ Désormais à chaque appel de <span class="new_code">$connection-&gt;query()</span>
+ nous obtenons un résultat de 37.
+ Il n'y a rien de particulier à cette valeur de 37.
+ Cette valeur de retour peut être aussi compliqué que nécessaire.
+ </p>
+ <p>
+ Ici les paramètres ne sont pas significatifs,
+ nous aurons systématiquement la même valeur en retour
+ une fois initialisés de la sorte.
+ Cela pourrait ne pas ressembler à une copie convaincante
+ de notre connexion à la base de données, mais pour
+ la demi-douzaine de lignes de code de notre méthode de test
+ c'est généralement largement assez.
+ </p>
+ <p>
+ Sauf que les choses ne sont pas toujours si simples.
+ Les itérateurs sont un problème récurrent, si par exemple
+ renvoyer systématiquement la même valeur entraine
+ une boucle infinie dans l'objet testé.
+ Pour ces cas-là, nous avons besoin d'une séquence de valeurs.
+ Supposons que nous avons un itérateur simple qui ressemble à...
+<pre>
+class Iterator {
+ function Iterator() { }
+ function next() { }
+}
+</pre>
+ Il s'agit là de l'itérateur le plus basique que nous puissions imaginer.
+ Supponsons que cet itérateur ne renvoit que du texte
+ jusqu'à ce qu'il atteigne la fin et qu'il renvoie alors un false,
+ nous pouvons le simuler avec...
+<pre>
+Mock::generate('Iterator');
+
+class IteratorTest extends UnitTestCase() {
+
+ function testASequence() {<strong>
+ $iterator = new MockIterator();
+ $iterator-&gt;returns('next', false);
+ $iterator-&gt;returnsAt(0, 'next', 'First string');
+ $iterator-&gt;returnsAt(1, 'next', 'Second string');</strong>
+ ...
+ }
+}
+</pre>
+ Quand <span class="new_code">next()</span> est appelé par le <span class="new_code">MockIterator</span>
+ il commencera par renvoyer "First string",
+ au deuxième passage "Second string" sera renvoyé
+ et sur n'importe quel autre appel <span class="new_code">false</span> sera renvoyé
+ à son tour.
+ Les valeurs renvoyées les unes après les autres auront la priorité
+ sur la valeur constante.
+ Cette dernière est la valeur par défaut en quelque sorte.
+ </p>
+ <p>
+ Une autre situation délicate serait une opération
+ <span class="new_code">get()</span> surchargée.
+ Un exemple serait un conteneur d'information avec des pairs clef/valeur.
+ Nous partons cette fois d'une classe de configuration telle...
+<pre>
+class Configuration {
+ function Configuration() { ... }
+ function get($key) { ... }
+}
+</pre>
+ C'est une situation courante pour utiliser des objets fantaisie,
+ étant donné que la véritable configuration sera différente
+ d'une machine à l'autre et parfois même d'un test à l'autre.
+ Cependant un problème apparaît quand toutes les données passent
+ par la méthode <span class="new_code">get()</span> et que nous souhaitons
+ quand même des résultats différents pour des clefs différentes.
+ Par chance les objets fantaisie ont un système de filtre...
+<pre>
+<strong>$config = &amp;new MockConfiguration();
+$config-&gt;returns('get', 'primary', array('db_host'));
+$config-&gt;returns('get', 'admin', array('db_user'));
+$config-&gt;returns('get', 'secret', array('db_password'));</strong>
+</pre>
+ Le dernier paramètre est une liste d'arguements
+ pour vérifier une correspondance.
+ Dans ce cas, nous essayons de faire correspondre un argument
+ qui se trouve être la clef de recherche.
+ Désormais quand l'objet fantaisie voit
+ sa méthode <span class="new_code">get()</span> invoquée...
+<pre>
+$config-&gt;get('db_user')
+</pre>
+ ...il renverra "admin".
+ Il trouve cette valeur en essayant de faire correspondre
+ l'argument reçu à ceux de ses propres listes : dès qu'une
+ correspondance complète est trouvé, il s'arrête.
+ </p>
+ <p>
+ Vous pouvez préciser un argument par défaut via...
+<pre><strong>
+$config-&gt;returns('get', false, array('*'));</strong>
+</pre>
+ Ce n'est pas la même chose que de définir la valeur renvoyée
+ sans aucun arguement...
+<pre><strong>
+$config-&gt;returns('get', false);</strong>
+</pre>
+ Dans le premier cas, il acceptera n'importe quel argument,
+ mais il en faut au moins un.
+ Dans le deuxième cas, n'importe quel nombre d'arguments
+ fera l'affaire and il agit comme un attrape-tout après
+ toutes les autres vérifications.
+ Notez que si - dans le premier cas - nous ajoutons
+ d'autres options avec paramètre unique après le joker,
+ alors elle seront ignorés puisque le joker fera
+ la première correspondance.
+ Avec des listes complexes de paramètres, l'ordre devient
+ important au risque de voir la correspondance souhaitée
+ masqué par un joker apparu plus tôt.
+ Déclarez les plus spécifiques d'abord si vous n'êtes pas sûr.
+ </p>
+ <p>
+ Il y a des moments où vous souhaitez qu'une référence
+ bien spécifique soit servie par l'objet fantaisie plutôt
+ qu'une copie.
+ C'est plutôt rare pour dire le moins, mais vous pourriez
+ être en train de simuler un conteneur qui détiendrait
+ des primitives, tels des chaînes de caractères.
+ Par exemple.
+<pre>
+class Pad {
+ function Pad() { }
+ function &amp;note($index) { }
+}
+</pre>
+ Dans ce cas, vous pouvez définir une référence dans la liste
+ des valeurs retournées par l'objet fantaisie...
+<pre>
+function testTaskReads() {
+ $note = 'Buy books';
+ $pad = new MockPad();
+ $vector-&gt;<strong>returnsByReference(</strong>'note', $note, array(3)<strong>)</strong>;
+ $task = new Task($pad);
+ ...
+}
+</pre>
+ Avec cet assemblage vous savez qu'à chaque fois
+ que <span class="new_code">$pad-&gt;note(3)</span> est appelé
+ il renverra toujours la même <span class="new_code">$note</span>,
+ même si celle-ci est modifiée.
+ </p>
+ <p>
+ Ces trois facteurs, timing, paramètres et références,
+ peuvent être combinés orthogonalement.
+ Par exemple...
+<pre>
+$buy_books = 'Buy books';
+$write_code = 'Write code';
+$pad = new MockPad();
+$vector-&gt;<strong>returnsByReferenceAt(0, 'note', $buy_books, array('*', 3));</strong>
+$vector-&gt;<strong>returnsByReferenceAt(1, 'note', $write_code, array('*', 3));</strong>
+</pre>
+ Cela renverra une référence à <span class="new_code">$buy_books</span> et
+ ensuite à <span class="new_code">$write_code</span>, mais seuleent si deux paramètres
+ sont utilisés, le deuxième devant être l'entier 3.
+ Cela devrait couvrir la plupart des situations.
+ </p>
+ <p>
+ Un dernier cas délicat reste : celui d'un objet créant
+ un autre objet, plus connu sous le patron de conception "fabrique"
+ (ou "factory").
+ Supponsons qu'à la réussite d'une requête à
+ notre base de données imaginaire, un jeu d'enregistrements
+ est renvoyé sous la forme d'un itérateur, où chaque appel
+ au <span class="new_code">next()</span> sur notre itérateur donne une ligne
+ avant de s'arrêtre avec un false.
+ Cela semble à un cauchemar à simuler, alors qu'en fait un objet
+ fantaisie peut être créé avec les mécansimes ci-dessus...
+<pre>
+Mock::generate('DatabaseConnection');
+Mock::generate('ResultIterator');
+
+class DatabaseTest extends UnitTestCase {
+
+ function testUserFinderReadsResultsFromDatabase() {<strong>
+ $result = new MockResultIterator();
+ $result-&gt;returns('next', false);
+ $result-&gt;returnsAt(0, 'next', array(1, 'tom'));
+ $result-&gt;returnsAt(1, 'next', array(3, 'dick'));
+ $result-&gt;returnsAt(2, 'next', array(6, 'harry'));
+
+ $connection = new MockDatabaseConnection();
+ $connection-&gt;returns('selectQuery', $result);</strong>
+
+ $finder = new UserFinder(<strong>$connection</strong>);
+ $this-&gt;assertIdentical(
+ $finder-&gt;findNames(),
+ array('tom', 'dick', 'harry'));
+ }
+}
+</pre>
+ Désormais ce n'est que si notre <span class="new_code">$connection</span>
+ est appelée par la méthode <span class="new_code">query()</span>
+ que sera retourné le <span class="new_code">$result</span>,
+ lui-même s'arrêtant au troisième appel
+ à <span class="new_code">next()</span>.
+ Ce devrait être suffisant comme information
+ pour que notre classe <span class="new_code">UserFinder</span>,
+ la classe effectivement testée ici,
+ fasse son boulot.
+ Un test très précis et toujours pas
+ de base de données en vue.
+ </p>
+ <p>
+ Nous pourrsion affiner ce test encore plus
+ en insistant pour que la bonne requête
+ soit envoyée...
+<pre>
+$connection-&gt;returns('selectQuery', $result, array(<strong>'select name, id from people'</strong>));
+</pre>
+ Là, c'est une mauvaise idée.
+ </p>
+ <p>
+ Niveau objet, nous avons un <span class="new_code">UserFinder</span>
+ qui parle à une base de données à travers une interface géante -
+ l'ensemble du SQL.
+ Imaginez si nous avions écrit un grand nombre de tests
+ qui dépendrait désormais de cette requête SQL précise.
+ Ces requêtes pourraient changer en masse pour tout un tas
+ de raisons non liés à ce test spécifique.
+ Par exemple, la règle pour les quotes pourrait changer,
+ un nom de table pourrait évoluer, une table de liaison pourrait
+ être ajouté, etc.
+ Cela entrainerait une ré-écriture de tous les tests à chaque fois
+ qu'un remaniement est fait, alors même que le comportement lui
+ n'a pas bougé.
+ Les tests sont censés aider au remaniement, pas le bloquer.
+ Pour ma part, je préfère avoir une suite de tests qui passent
+ quand je fais évoluer le nom des tables.
+ </p>
+ <p>
+ Et si vous voulez une règle, c'est toujours mieux de ne pas
+ créer un objet fantaisie sur une grosse interface.
+ </p>
+ <p>
+ Par contrast, voici le test complet...
+<pre>
+class DatabaseTest extends UnitTestCase {<strong>
+ function setUp() { ... }
+ function tearDown() { ... }</strong>
+
+ function testUserFinderReadsResultsFromDatabase() {
+ $finder = new UserFinder(<strong>new DatabaseConnection()</strong>);
+ $finder-&gt;add('tom');
+ $finder-&gt;add('dick');
+ $finder-&gt;add('harry');
+ $this-&gt;assertIdentical(
+ $finder-&gt;findNames(),
+ array('tom', 'dick', 'harry'));
+ }
+}
+</pre>
+ Ce test est immunisé contre le changement de schéma.
+ Il échouera uniquement si vous changez la fonctionnalité,
+ ce qui correspond bien à ce qu'un test doit faire.
+ </p>
+ <p>
+ Il faut juste faire attention à ces méthodes <span class="new_code">setUp()</span>
+ et <span class="new_code">tearDown()</span> que nous avons survolé pour l'instant.
+ Elles doivent vider les tables de la base de données
+ et s'assurer que le schéma est bien défini.
+ Cela peut se engendrer un peu de travail supplémentaire,
+ mais d'ordinaire ce type de code existe déjà - à commencer pour
+ le déploiement.
+ </p>
+ <p>
+ Il y a au moins un endroit où vous aurez besoin d'objets fantaisie :
+ c'est la simulation des erreurs.
+ Exemple, la base de données tombe pendant que <span class="new_code">UserFinder</span>
+ fait son travail. Le <span class="new_code">UserFinder</span> se comporte-t-il bien ?
+<pre>
+class DatabaseTest extends UnitTestCase {
+
+ function testUserFinder() {
+ $connection = new MockDatabaseConnection();<strong>
+ $connection-&gt;throwOn('selectQuery', new TimedOut('Ouch!'));</strong>
+ $alert = new MockAlerts();<strong>
+ $alert-&gt;expectOnce('notify', 'Database is busy - please retry');</strong>
+ $finder = new UserFinder($connection, $alert);
+ $this-&gt;assertIdentical($finder-&gt;findNames(), array());
+ }
+}
+</pre>
+ Nous avons transmis au <span class="new_code">UserFinder</span>
+ un objet <span class="new_code">$alert</span>.
+ Il va transmettre un certain nombre de belles notifications
+ à l'interface utilisatuer en cas d'erreur.
+ Nous préfèrerions éviter de saupoudrer notre code avec
+ des commandes <span class="new_code">print</span> codées en dur si nous pouvons
+ l'éviter.
+ Emballer les moyens de sortie veut dire que nous pouvons utiliser
+ ce code partout. Et cela rend notre code plus facile.
+ </p>
+ <p>
+ Pour faire passer ce test, le finder doit écrire un message sympathique
+ et compréhensible à l'<span class="new_code">$alert</span>, plutôt que de propager
+ l'exception. Jusque là, tout va bien.
+ </p>
+ <p>
+ Comment faire en sorte que la <span class="new_code">DatabaseConnection</span> fantaisie
+ soulève une exception ?
+ Nous la générons avec la méthode <span class="new_code">throwOn</span> sur l'objet fantaisie.
+ </p>
+ <p>
+ Enfin, que se passe-t-il si la méthode voulue pour la simulation
+ n'existe pas encore ?
+ Si vous définissez une valeur de retour sur une méthode absente,
+ alors SimpleTest vous répondra avec une erreur.
+ Et si vous utilisez <span class="new_code">__call()</span> pour simuler
+ des méthodes dynamiques ?
+ </p>
+ <p>
+ Les objets avec des interfaces dynamiques, avec <span class="new_code">__call</span>,
+ peuvent être problématiques dans l'implémentation courante
+ des objets fantaisie.
+ Vous pouvez en créer un autour de la méthode <span class="new_code">__call()</span>
+ mais c'est très laid.
+ Et pourquoi un test devrait connaître quelque chose avec un niveau
+ si bas dans l'implémentation. Il n'a besoin que de simuler l'appel.
+ </p>
+ <p>
+ Il y a bien moyen de contournement : ajouter des méthodes complémentaires
+ à l'objet fantaisie à la génération.
+<pre>
+<strong>Mock::generate('DatabaseConnection', 'MockDatabaseConnection', array('setOptions'));</strong>
+</pre>
+ Dans une longue suite de tests cela pourrait entraîner des problèmes,
+ puisque vous avez probablement déjà une version fantaisie
+ de la classe appellée <span class="new_code">MockDatabaseConnection</span>
+ sans les méthodes complémentaires.
+ Le générateur de code ne générera pas la version fantaisie de la classe
+ s'il en existe déjà une version avec le même nom.
+ Il vous deviendra impossible de déterminer où est passée votre méthode
+ si une autre définition a été lancé au préalable.
+ </p>
+ <p>
+ Pour pallier à ce problème, SimpleTest vous permet de choisir
+ n'importe autre nom pour la nouvelle classe au moment même où
+ vous ajouter les méthodes complémentaires.
+<pre>
+Mock::generate('DatabaseConnection', <strong>'MockDatabaseConnectionWithOptions'</strong>, array('setOptions'));
+</pre>
+ Ici l'objet fantaisie se comportera comme si
+ <span class="new_code">setOptions()</span> existait bel et bien
+ dans la classe originale.
+ </p>
+ <p>
+ Les objets fantaisie ne peuvent être utilisés qu'à l'intérieur
+ des scénarios de test, étant donné qu'à l'apparition d'une attente
+ ils envoient des messages directement au scénario de test courant.
+ Les créer en dehors d'un scénario de test entraînera une erreur
+ de run time quand une attente est déclenchée et qu'il n'y a pas
+ de scénario de test en cours pour recevoir le message.
+ Nous pouvons désormais couvrir ces attentes.
+ </p>
+
+ <h2>
+<a class="target" name="expectations"></a>Objets fantaisie en tant que critiques</h2>
+ <p>
+ Même si les bouchons serveur isolent vos tests des perturbations
+ du monde réel, ils n'apportent que le moitié des bénéfices possibles.
+ Vous pouvez obtenir une classe de test qui reçoive les bons messages,
+ mais cette nouvelle classe envoie-t-elle les bons ?
+ Le tester peut devenir très bordélique sans
+ une librairie d'objets fantaise.
+ </p>
+ <p>
+ Voici un exemple, prenons une classe <span class="new_code">PageController</span>
+ toute simple qui traitera un formulaire de paiement
+ par carte bleue...
+<pre>
+class PaymentForm extends PageController {
+ function __construct($alert, $payment_gateway) { ... }
+ function makePayment($request) { ... }
+}
+</pre>
+ Cette classe a besoin d'un <span class="new_code">PaymentGateway</span>
+ pour parler concrètement à la banque.
+ Il utilise aussi un objet <span class="new_code">Alert</span>
+ pour gérer les erreurs.
+ Cette dernière classe parle à la page ou au template.
+ Elle est responsable de l'affichage du message d'erreur
+ et de la mise en valeur de tout champ du formulaire
+ qui serait incorrecte.
+ </p>
+ <p>
+ Elle pourrait ressembler à...
+<pre>
+class Alert {
+ function warn($warning, $id) {
+ print '&lt;div class="warning"&gt;' . $warning . '&lt;/div&gt;';
+ print '&lt;style type="text/css"&gt;#' . $id . ' { background-color: red }&lt;/style&gt;';
+ }
+}
+</pre>
+ </p>
+ <p>
+ Portons notre attention à la méthode <span class="new_code">makePayment()</span>.
+ Si nous n'inscrivons pas un numéro "CVV2" (celui à trois
+ chiffre au dos de la carte bleue), nous souhaitons afficher
+ une erreur plutôt que d'essayer de traiter le paiement.
+ En mode test...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+require_once('payment_form.php');
+Mock::generate('Alert');
+Mock::generate('PaymentGateway');
+
+class PaymentFormFailuresShouldBeGraceful extends UnitTestCase {
+
+ function testMissingCvv2CausesAlert() {
+ $alert = new MockAlert();
+ <strong>$alert-&gt;expectOnce(
+ 'warn',
+ array('Missing three digit security code', 'cvv2'));</strong>
+ $controller = new PaymentForm(<strong>$alert</strong>, new MockPaymentGateway());
+ $controller-&gt;makePayment($this-&gt;requestWithMissingCvv2());
+ }
+
+ function requestWithMissingCvv2() { ... }
+}
+?&gt;
+</pre>
+ Première question : où sont passés les assertions ?
+ </p>
+ <p>
+ L'appel à <span class="new_code">expectOnce('warn', array(...))</span> annonce
+ à l'objet fantaisie qu'il faut s'attendre à un appel à <span class="new_code">warn()</span>
+ avant la fin du test.
+ Quand il débouche sur l'appel à <span class="new_code">warn()</span>, il vérifie
+ les arguments. Si ceux-ci ne correspondent pas, alors un échec
+ est généré. Il échouera aussi si la méthode n'est jamais appelée.
+ </p>
+ <p>
+ Non seulement le test ci-dessus s'assure que <span class="new_code">warn</span>
+ a bien été appelé, mais en plus qu'il a bien reçu la chaîne
+ de caractère "Missing three digit security code"
+ et même le tag "cvv2".
+ L'équivalent de <span class="new_code">assertIdentical()</span> est appliqué
+ aux deux champs quand les paramètres sont comparés.
+ </p>
+ <p>
+ Si le contenu du message vous importe peu, surtout dans le cas
+ d'une interface utilisateur qui change régulièrement,
+ nous pouvons passer ce paramètre avec l'opérateur "*"...
+<pre>
+class PaymentFormFailuresShouldBeGraceful extends UnitTestCase {
+
+ function testMissingCvv2CausesAlert() {
+ $alert = new MockAlert();
+ $alert-&gt;expectOnce('warn', array(<strong>'*'</strong>, 'cvv2'));
+ $controller = new PaymentForm($alert, new MockPaymentGateway());
+ $controller-&gt;makePayment($this-&gt;requestWithMissingCvv2());
+ }
+
+ function requestWithMissingCvv2() { ... }
+}
+</pre>
+ Nous pouvons même rendre le test encore moins spécifique
+ en supprimant complètement la liste des paramètres...
+<pre>
+function testMissingCvv2CausesAlert() {
+ $alert = new MockAlert();
+ <strong>$alert-&gt;expectOnce('warn');</strong>
+ $controller = new PaymentForm($alert, new MockPaymentGateway());
+ $controller-&gt;makePayment($this-&gt;requestWithMissingCvv2());
+}
+</pre>
+ Ceci vérifiera uniquement si la méthode a été appelé,
+ ce qui est peut-être un peu drastique dans ce cas.
+ Plus tard, nous verrons comment alléger les attentes
+ plus précisement.
+ </p>
+ <p>
+ Des tests sans assertions peuvent être à la fois compacts
+ et très expressifs. Parce que nous interceptons l'appel
+ sur le chemin de l'objet, ici de classe <span class="new_code">Alert</span>,
+ nous évitons de tester l'état par la suite.
+ Cela évite les assertions dans les tests, mais aussi
+ l'obligation d'ajouter des accesseurs uniquement
+ pour les tests dans le code original.
+ Si vous en arrivez à ajouter des accesseurs de ce type,
+ on parle alors de "state based testing" dans le jargon
+ ("test piloté par l'état"),
+ il est probablement plus que temps d'utiliser
+ des objets fantaisie dans vos tests.
+ On peut alors parler de "behaviour based testing"
+ (ou "test piloté par le comportement") :
+ c'est largement mieux !
+ </p>
+ <p>
+ Ajoutons un autre test.
+ Assurons nous que nous essayons même pas un paiement sans CVV2...
+<pre>
+class PaymentFormFailuresShouldBeGraceful extends UnitTestCase {
+
+ function testMissingCvv2CausesAlert() { ... }
+
+ function testNoPaymentAttemptedWithMissingCvv2() {
+ $payment_gateway = new MockPaymentGateway();
+ <strong>$payment_gateway-&gt;expectNever('pay');</strong>
+ $controller = new PaymentForm(new MockAlert(), $payment_gateway);
+ $controller-&gt;makePayment($this-&gt;requestWithMissingCvv2());
+ }
+
+ ...
+}
+</pre>
+ Vérifier une négation peut être très difficile
+ dans les tests, mais <span class="new_code">expectNever()</span>
+ rend l'opération très facile heureusement.
+ </p>
+ <p>
+ <span class="new_code">expectOnce()</span> et <span class="new_code">expectNever()</span> sont
+ suffisants pour la plupart des tests, mais
+ occasionnellement vous voulez tester plusieurs évènements.
+ D'ordinaire pour des raisons d'usabilité, nous souhaitons
+ que tous les champs manquants du formulaire soient
+ mis en relief, et pas uniquement le premier.
+ Cela veut dire que nous devrions voir de multiples appels
+ à <span class="new_code">Alert::warn()</span>, pas juste un...
+<pre>
+function testAllRequiredFieldsHighlightedOnEmptyRequest() {
+ $alert = new MockAlert();<strong>
+ $alert-&gt;expectAt(0, 'warn', array('*', 'cc_number'));
+ $alert-&gt;expectAt(1, 'warn', array('*', 'expiry'));
+ $alert-&gt;expectAt(2, 'warn', array('*', 'cvv2'));
+ $alert-&gt;expectAt(3, 'warn', array('*', 'card_holder'));
+ $alert-&gt;expectAt(4, 'warn', array('*', 'address'));
+ $alert-&gt;expectAt(5, 'warn', array('*', 'postcode'));
+ $alert-&gt;expectAt(6, 'warn', array('*', 'country'));
+ $alert-&gt;expectCallCount('warn', 7);</strong>
+ $controller = new PaymentForm($alert, new MockPaymentGateway());
+ $controller-&gt;makePayment($this-&gt;requestWithMissingCvv2());
+}
+</pre>
+ Le compteur dans <span class="new_code">expectAt()</span> précise
+ le nombre de fois que la méthode a déjà été appelée.
+ Ici nous vérifions que chaque champ sera bien mis en relief.
+ </p>
+ <p>
+ Notez que nous sommes forcé de tester l'ordre en même temps.
+ SimpleTest n'a pas encore de moyen pour éviter cela,
+ mais dans une version future ce sera corrigé.
+ </p>
+ <p>
+ Voici la liste complètes des attentes
+ que vous pouvez préciser sur une objet fantaisie
+ dans <a href="http://simpletest.org/">SimpleTest</a>.
+ Comme pour les assertions, ces méthodes prennent en option
+ un message d'erreur.
+ <table>
+ <thead><tr>
+<th>Attente</th>
+<th>Description</th>
+</tr></thead>
+ <tbody>
+ <tr>
+ <td><span class="new_code">expect($method, $args)</span></td>
+ <td>Les arguements doivent correspondre si appelés</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectAt($timing, $method, $args)</span></td>
+ <td>Les arguements doiven correspondre si appelés lors du passage numéro <span class="new_code">$timing</span>
+</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectCallCount($method, $count)</span></td>
+ <td>La méthode doit être appelée exactement <span class="new_code">$count</span> fois</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectMaximumCallCount($method, $count)</span></td>
+ <td>La méthode ne doit pas être appelée plus de <span class="new_code">$count</span> fois</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectMinimumCallCount($method, $count)</span></td>
+ <td>La méthode ne doit pas être appelée moins de <span class="new_code">$count</span> fois</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectNever($method)</span></td>
+ <td>La méthode ne doit jamais être appelée</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectOnce($method, $args)</span></td>
+ <td>La méthode ne doit être appelée qu'une seule fois et avec les arguments (en option)</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectAtLeastOnce($method, $args)</span></td>
+ <td>La méthode doit être appelée au moins une seule fois et toujours avec au moins un des arguments attendus</td>
+ </tr>
+ </tbody>
+ </table>
+ Où les paramètres sont...
+ <dl>
+ <dt class="new_code">$method</dt>
+ <dd>
+ Le nom de la méthode, sous la forme d'une chaîne de caractères,
+ à laquelle il faut appliquer la condition.
+ </dd>
+ <dt class="new_code">$args</dt>
+ <dd>
+ Les argumetns sous la forme d'une liste.
+ Les jokers peuvent être inclus de la même manière
+ que pour <span class="new_code">setReturn()</span>.
+ Cet argument est optionnel pour <span class="new_code">expectOnce()</span>
+ et <span class="new_code">expectAtLeastOnce()</span>.
+ </dd>
+ <dt class="new_code">$timing</dt>
+ <dd>
+ La seule marque dans le temps pour tester la condition.
+ Le premier appel commence à zéro et le comptage se fait
+ séparement sur chaque méthode.
+ </dd>
+ <dt class="new_code">$count</dt>
+ <dd>Le nombre d'appels attendu.</dd>
+ </dl>
+ </p>
+ <p>
+ Si vous n'avez qu'un seul appel dans votre test, assurez vous
+ d'utiliser <span class="new_code">expectOnce</span>.<br>
+ Utiliser <span class="new_code">$mocked-&gt;expectAt(0, 'method', 'args);</span>
+ tout seul ne permettra qu'à la méthode de ne jamais être appelée.
+ Vérifier les arguements et le comptage total sont pour le moment
+ indépendants.
+ Ajouter une attente <span class="new_code">expectCallCount()</span> quand
+ vous utilisez <span class="new_code">expectAt()</span> (dans le cas sans appel)
+ est permis.
+ </p>
+ <p>
+ Comme les assertions à l'intérieur des scénarios de test,
+ toutes ces attentes peuvent incorporer une surchage
+ sur le message sous la forme d'un paramètre supplémentaire.
+ Par ailleurs le message original peut être inclus dans la sortie
+ avec "%s".
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ Le papier original sur les Objets fantaisie ou
+ <a href="http://www.mockobjects.com/">Mock objects</a>.
+ </li>
+<li>
+ La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ La page d'accueil de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/fr/overview.html b/3rdparty/simpletest/docs/fr/overview.html
new file mode 100644
index 00000000000..968bbc48e50
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/overview.html
@@ -0,0 +1,321 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>
+ Aperçu et liste des fonctionnalités des testeurs unitaires PHP et web de SimpleTest PHP
+ </title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Apercu de SimpleTest</h1>
+ This page...
+ <ul>
+<li>
+ <a href="#resume">Résumé rapide</a> de l'outil SimpleTest pour PHP.
+ </li>
+<li>
+ <a href="#fonctionnalites">La liste des fonctionnalites</a>, à la fois présentes et à venir.
+ </li>
+<li>
+ Il y a beaucoup de <a href="#ressources">ressources sur les tests unitaires</a> sur le web.
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="resume"></a>Qu'est-ce que SimpleTest ?</h2>
+ <p>
+ 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 <span class="new_code">run()</span> à 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, <span class="new_code">assertEqual()</span> 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.
+ </p>
+ <p>
+ Un <a href="unit_test_documentation.html">scénario de test</a> ressemble à...
+<pre>
+class <strong>MyTestCase</strong> extends UnitTestCase {
+ <strong>
+ function testLog() {
+ $log = &amp;new Log('my.log');
+ $log-&gt;message('Hello');
+ $this-&gt;assertTrue(file_exists('my.log'));
+ }</strong>
+}
+</pre>
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ Le type de scénario de test le plus simple est le <span class="new_code">UnitTestCase</span>. 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.
+ </p>
+ <p>
+ 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 <span class="new_code">WebTestCase</span> 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.
+ </p>
+ <p>
+ Un <a href="web_tester_documentation.html">scénario de test web</a> ressemble à...
+<pre>
+class <strong>MySiteTest</strong> extends WebTestCase {
+ <strong>
+ function testHomePage() {
+ $this-&gt;get('http://www.my-site.com/index.php');
+ $this-&gt;assertTitle('My Home Page');
+ $this-&gt;clickLink('Contact');
+ $this-&gt;assertTitle('Contact me');
+ $this-&gt;assertWantedPattern('/Email me at/');
+ }</strong>
+}
+</pre>
+ </p>
+
+ <h2>
+<a class="target" name="fonctionnalites"></a>Liste des fonctionnalites</h2>
+ <p>
+ 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".
+ <table>
+<thead>
+ <tr>
+<th>Fonctionnalité</th>
+<th>Description</th>
+<th>Publication</th>
+</tr>
+ </thead>
+<tbody>
+<tr>
+ <td>Scénariot de test unitaire</td>
+ <td>Les classes de test et assertions de base</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Affichage HTML</td>
+ <td>L'affichage le plus simple possible</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Autochargement des scénarios de test</td>
+ <td>Lire un fichier avec des scénarios de test et les charger dans un groupe de tests automatiquement</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Générateur de code d'objets fantaisie</td>
+ <td>Des objets capable de simuler d'autres objets, supprimant les dépendances dans les tests</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Bouchons serveur</td>
+ <td>Des objets fantaisie sans résultat attendu à utiliser à l'extérieur des scénarios de test, pour le prototypage par exemple.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Intégration d'autres testeurs unitaires</td>
+ <td>
+ La capacité de lire et simuler d'autres scénarios de test en provenance de PHPUnit et de PEAR::Phpunit.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Scénario de test web</td>
+ <td>Appariement basique de motifs dans une page téléchargée.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Analyse de page HTML</td>
+ <td>Permet de suivre les liens et de trouver la balise de titre</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Simulacre partiel</td>
+ <td>Simuler des parties d'une classe pour tester moins qu'une classe ou dans des cas complexes.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Gestion des cookies Web</td>
+ <td>Gestion correcte des cookies au téléchargement d'une page.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Suivi des redirections</td>
+ <td>Le téléchargement d'une page suit automatiquement une redirection 300.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Analyse d'un formulaire</td>
+ <td>La capacité de valider un formulaire simple et d'en lire les valeurs par défaut.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Interface en ligne de commande</td>
+ <td>Affiche le résultat des tests sans navigateur web.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Mise à nu des attentes d'une classe</td>
+ <td>Peut créer des tests précis avec des simulacres ainsi que des scénarios de test.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Sortie et analyse XML</td>
+ <td>Permet de tester sur plusieurs hôtes et d'intégrer des extensions d'acceptation de test.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Scénario de test en ligne de commande</td>
+ <td>Permet de tester des outils ou scripts en ligne de commande et de manier des fichiers.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Compatibilité avec PHP Documentor</td>
+ <td>Génération automatique et complète de la documentation au niveau des classes.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Interface navigateur</td>
+ <td>Mise à nu des niveaux bas de l'interface du navigateur web pour des scénarios de test plus précis.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Authentification HTTP</td>
+ <td>Téléchargement des pages web protégées avec une authentification basique seulement.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Boutons de navigation d'un navigateur</td>
+ <td>Arrière, avant et recommencer</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Support de SSL</td>
+ <td>Peut se connecter à des pages de type https.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Support de proxy</td>
+ <td>Peut se connecter via des proxys communs</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Support des cadres</td>
+ <td>Gère les cadres dans les scénarios de test web.</td>
+ <td style="color: green;">Fini</td>
+ </tr>
+ <tr>
+ <td>Test de l'upload de fichier</td>
+ <td>Peut simuler la balise input de type file</td>
+ <td style="color: red;">1.0.1</td>
+ </tr>
+ <tr>
+ <td>Amélioration sur la machinerie des rapports</td>
+ <td>Retouche sur la transmission des messages pour une meilleur coopération avec les IDEs</td>
+ <td style="color: red;">1.1</td>
+ </tr>
+ <tr>
+ <td>Amélioration de l'affichage des tests</td>
+ <td>Une meilleure interface graphique web, avec un arbre des scénarios de test.</td>
+ <td style="color: red;">1.1</td>
+ </tr>
+ <tr>
+ <td>Localisation</td>
+ <td>Abstraction des messages et génration du code à partir de fichiers XML.</td>
+ <td style="color: red;">1.1</td>
+ </tr>
+ <tr>
+ <td>Simulation d'interface</td>
+ <td>Peut générer des objets fantaisie tant vers des interfaces que vers des classes.</td>
+ <td style="color: red;">2.0</td>
+ </tr>
+ <tr>
+ <td>Test sur es exceptions</td>
+ <td>Dans le même esprit que sur les tests des erreurs PHP.</td>
+ <td style="color: red;">2.0</td>
+ </tr>
+ <tr>
+ <td>Rercherche d'éléments avec XPath</td>
+ <td>Peut utiliser Tidy HTML pour un appariement plus rapide et plus souple.</td>
+ <td style="color: red;">2.0</td>
+ </tr>
+ </tbody>
+</table>
+ 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.
+ </p>
+
+ <h2>
+<a class="target" name="ressources"></a>Ressources sur le web pour les tests</h2>
+ <p>
+ 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'<a href="http://www.extremeprogramming.org/">Extreme Programming</a>. Il s'agit là d'une des <a href="http://www.agilealliance.com/articles/index">méthodes agiles</a> qui combinent plusieurs pratiques pour "lisser la courbe de coût" du développement logiciel. La plus extrème reste le <a href="http://www.testdriven.com/modules/news/">développement piloté par les tests</a>, où vous devez adhérer à la règle du <cite>pas de code avant d'avoir un test</cite>. 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 <a href="http://www.therationaledge.com/content/dec_01/f_spiritOfTheRUP_pk.html">RUP</a>. Je ne l'ai pas testé mais je peux voir où vous aurez besoin d'outils de test (cf. illustration 9).
+ </p>
+ <p>
+ La plupart des testeurs unitaires sont dans une certaine mesure un clone de <a href="http://www.junit.org/">JUnit</a>, au moins dans l'interface. Il y a énormément d'information sur le site de JUnit, à commencer par la <a href="http://junit.sourceforge.net/doc/faq/faq.htm">FAQ</a> 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 <a href="http://junit.sourceforge.net/doc/testinfected/testing.htm">infecté par les tests</a> trouvée par Eric Gamma. Si vous êtes encore en train de tergiverser sur un testeur unitaire, sachez que les choix principaux sont <a href="http://phpunit.sourceforge.net/">PHPUnit</a> et <a href="http://pear.php.net/manual/en/package.php.phpunit.php">Pear PHP::PHPUnit</a>. 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 <a href="http://www.junit.org/">JUnit</a>.
+ </p>
+ <p>
+ 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 <a href="http://wact.sourceforge.net/">WACT</a> et <a href="http://sourceforge.net/projects/htmlsax">PEAR::XML_HTMLSax</a>.
+ </p>
+ <p>
+ 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'<a href="http://www.sidewize.com/company/mockobjects.pdf">article original sur les objets fantaisie</a> 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 <a href="http://xpdeveloper.com/cgi-bin/oldwiki.cgi?MockObjects">Extreme Tuesday</a> ou <a href="http://www.mockobjects.com/MocksObjectsPaper.html">www.mockobjects.com</a>ou <a href="http://c2.com/cgi/wiki?MockObject">the original C2 Wiki</a>. Injecter des objets fantaisie dans une classe est un des champs principaux du débat : cet <a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html">article chez IBM</a> en est un bon point de départ.
+ </p>
+ <p>
+ 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 <a href="http://httpunit.sourceforge.net/">HTTPUnit</a>, <a href="http://htmlunit.sourceforge.net/">HTMLUnit</a> ou <a href="http://jwebunit.sourceforge.net/">JWebUnit</a> 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.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ <a href="unit_test_documentation.html">Documentation pour SimpleTest</a>.
+ </li>
+<li>
+ <a href="http://www.lastcraft.com/first_test_tutorial.php">Comment écrire des scénarios de test en PHP</a> est un tutoriel plutôt avancé.
+ </li>
+<li>
+ <a href="http://simpletest.org/api/">L'API de SimpleTest</a> par phpdoc.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/fr/partial_mocks_documentation.html b/3rdparty/simpletest/docs/fr/partial_mocks_documentation.html
new file mode 100644
index 00000000000..740ae7b4026
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/partial_mocks_documentation.html
@@ -0,0 +1,475 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Documentation SimpleTest : les objets fantaisie partiels</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Documentation sur les objets fantaisie partiels</h1>
+ This page...
+ <ul>
+<li>
+ <a href="#injection">Le problème de l'injection d'un objet fantaisie</a>.
+ </li>
+<li>
+ Déplacer la création vers une méthode <a href="#creation">fabrique protégée</a>.
+ </li>
+<li>
+ <a href="#partiel">L'objet fantaisie partiel</a> génère une sous-classe.
+ </li>
+<li>
+ Les objets fantaisie partiels <a href="#moins">testent moins qu'une classe</a>.
+ </li>
+</ul>
+<div class="content">
+
+ <p>
+ 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à.
+ </p>
+
+ <h2>
+<a class="target" name="injection"></a>Le problème de l'injection dans un objet fantaisie</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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...
+<pre>
+<strong>&lt;?php
+require_once('socket.php');
+
+class Telnet {
+ ...
+ function connect($ip, $port, $username, $password) {
+ $socket = new Socket($ip, $port);
+ $socket-&gt;read( ... );
+ ...
+ }
+}
+?&gt;</strong>
+</pre>
+ Nous voudrions vraiment avoir une version fantaisie
+ de l'objet socket, que pouvons nous faire ?
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ Voici ce que ça devrait être...
+<pre>
+&lt;?php
+require_once('socket.php');
+
+class Telnet {
+ ...
+ <strong>function connect($socket, $username, $password) {
+ $socket-&gt;read( ... );
+ ...
+ }</strong>
+}
+?&gt;
+</pre>
+ Sous-entendu, votre code de test est typique d'un cas
+ de test avec un objet fantaisie.
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = new MockSocket();
+ ...
+ $telnet = new Telnet();
+ $telnet-&gt;connect($socket, 'Me', 'Secret');
+ ...</strong>
+ }
+}
+</pre>
+ 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.
+ </p>
+ <p>
+ La solution suivante est de passer l'objet créé sous la forme
+ d'un paramètre optionnel...
+<pre>
+&lt;?php
+require_once('socket.php');
+
+class Telnet {
+ ...<strong>
+ function connect($ip, $port, $username, $password, $socket = false) {
+ if (! $socket) {
+ $socket = new Socket($ip, $port);
+ }
+ $socket-&gt;read( ... );</strong>
+ ...
+ return $socket;
+ }
+}
+?&gt;
+</pre>
+ Pour une solution rapide, c'est généralement suffisant.
+ Ensuite le test est très similaire : comme si le paramètre
+ était transmis formellement...
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = new MockSocket();
+ ...
+ $telnet = new Telnet();
+ $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret', $socket);
+ ...</strong>
+ }
+}
+</pre>
+ 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.
+ </p>
+ <p>
+ Une autre solution encore est de laisser un objet fabrique
+ s'occuper de la création...
+<pre>
+&lt;?php
+require_once('socket.php');
+
+class Telnet {<strong>
+ function Telnet($network) {
+ $this-&gt;_network = $network;
+ }</strong>
+ ...
+ function connect($ip, $port, $username, $password) {<strong>
+ $socket = $this-&gt;_network-&gt;createSocket($ip, $port);
+ $socket-&gt;read( ... );</strong>
+ ...
+ return $socket;
+ }
+}
+?&gt;
+</pre>
+ 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...
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = new MockSocket();
+ ...
+ $network = new MockNetwork();
+ $network-&gt;returnsByReference('createSocket', $socket);
+ $telnet = new Telnet($network);
+ $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');</strong>
+ }
+}
+</pre>
+ 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.
+ </p>
+ <p>
+ Des techniques comme "l'Injection de Dépendance"
+ (ou "Dependency Injection") s'attelle au problème
+ de l'instanciation d'une classe avec beaucoup de paramètres.
+ Malheureusement la connaissance de ce patron de conception
+ n'est pas très répandue et si vous êtes en train d'essayer
+ de faire fonctionner du vieux code, ré-achitecturer toute
+ l'application n'est pas vraiment une option.
+ </p>
+ <p>
+ Peut-on trouver un juste milieu ?
+ </p>
+
+ <h2>
+<a class="target" name="creation"></a>Méthode fabrique protégée</h2>
+ <p>
+ 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...
+<pre>
+&lt;?php
+require_once('socket.php');
+
+class Telnet {
+ ...
+ function connect($ip, $port, $username, $password) {
+ <strong>$socket = $this-&gt;createSocket($ip, $port);</strong>
+ $socket-&gt;read( ... );
+ ...
+ }<strong>
+
+ protected function createSocket($ip, $port) {
+ return new Socket($ip, $port);
+ }</strong>
+}
+?&gt;
+</pre>
+ Une première étape plutôt précautionneuse même pour
+ du code legacy et intermélé.
+ Il s'agit là de la seule modification dans le code de l'application.
+ </p>
+ <p>
+ Pour le scénario de test, nous devons créer
+ une sous-classe de manière à intercepter la création de la socket...
+<pre>
+<strong>class TelnetTestVersion extends Telnet {
+ var $mock;
+
+ function TelnetTestVersion($mock) {
+ $this-&gt;mock = $mock;
+ $this-&gt;Telnet();
+ }
+
+ protected function createSocket() {
+ return $this-&gt;mock;
+ }
+}</strong>
+</pre>
+ 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
+ <span class="new_code">connect()</span>.
+ Autrement il pourrait donner un valeur nulle à partir de
+ <span class="new_code">createSocket()</span>.
+ </p>
+ <p>
+ 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...
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = new MockSocket();
+ ...
+ $telnet = new TelnetTestVersion($socket);
+ $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');</strong>
+ }
+}
+</pre>
+ 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 ?
+ </p>
+
+ <h2>
+<a class="target" name="partiel"></a>Un objet fantaisie partiel</h2>
+ <p>
+ 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.
+ </p>
+ <p>
+ Voici donc une version avec objet fantaisie partiel du test...
+<pre>
+<strong>Mock::generatePartial(
+ 'Telnet',
+ 'TelnetTestVersion',
+ array('createSocket'));</strong>
+
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = new MockSocket();
+ ...
+ $telnet = new TelnetTestVersion();
+ $telnet-&gt;setReturnReference('createSocket', $socket);
+ $telnet-&gt;Telnet();
+ $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');</strong>
+ }
+}
+</pre>
+ 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 à <span class="new_code">generatePartial()</span>
+ nécessite trois paramètres : la classe à sous classer,
+ le nom de la nouvelle classe et une liste des méthodes à simuler.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ 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...
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {
+ $socket = new MockSocket();
+ ...
+ $telnet = new TelnetTestVersion();
+ $telnet-&gt;setReturnReference('createSocket', $socket);
+ <strong>$telnet-&gt;expectOnce('createSocket', array('127.0.0.1', 21));</strong>
+ $telnet-&gt;Telnet();
+ $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');
+ }
+}
+</pre>
+ Les objets fantaisie partiels ne sont pas très utilisés.
+ Je les considère comme transitoire.
+ Utile lors d'un remaniement, mais une fois que l'application
+ a eu toutes ses dépendances bien séparées alors
+ ils peuvent disparaître.
+ </p>
+
+ <h2>
+<a class="target" name="moins"></a>Tester moins qu'une classe</h2>
+ <p>
+ 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éthodes à part celle
+ que nous voulons effectivement tester.
+ </p>
+ <p>
+ Cette situation est assez hypothétique, étant donné
+ que je ne l'ai pas souvent essayée.
+ 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.
+ </p>
+ <p>
+ On en revient toujours aux standards de code de votre projet :
+ c'est à vous de trancher si vous autorisez ce mécanisme ou non.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ La page du projet SimpleTest sur
+ <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ <a href="http://simpletest.org/api/">L'API complète pour SimpleTest</a>
+ à partir de PHPDoc.
+ </li>
+<li>
+ La méthode fabrique protégée est décrite dans
+ <a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html">
+ cet article d'IBM</a>. Il s'agit de l'unique papier
+ formel que j'ai vu sur ce problème.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/fr/reporter_documentation.html b/3rdparty/simpletest/docs/fr/reporter_documentation.html
new file mode 100644
index 00000000000..485fc74c7a4
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/reporter_documentation.html
@@ -0,0 +1,630 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Documentation SimpleTest : le rapporteur de test</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Documentation sur le rapporteur de test</h1>
+ This page...
+ <ul>
+<li>
+ Afficher <a href="#html">les résultats en HTML</a>
+ </li>
+<li>
+ Afficher et <a href="#autres">rapporter les résultats</a>
+ dans d'autres formats
+ </li>
+<li>
+ Utilisé <a href="#cli">SimpleTest depuis la ligne de commande</a>
+ </li>
+<li>
+ <a href="#xml">Utiliser XML</a> pour des tests distants
+ </li>
+</ul>
+<div class="content">
+
+ <p>
+ 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.
+ </p>
+
+ <h2>
+<a class="target" name="html"></a>Les résultats rapportés au format HTML</h2>
+ <p>
+ 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...
+ <div class="demo">
+ <h1>File test</h1>
+ <span class="fail">Fail</span>: createnewfile-&gt;True assertion failed.<br>
+ <div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
+ <strong>0</strong> passes, <strong>1</strong> fails and <strong>0</strong> exceptions.</div>
+ </div>
+ Alors qu'ici tous les tests passent...
+ <div class="demo">
+ <h1>File test</h1>
+ <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
+ <strong>1</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
+ </div>
+ 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.
+ </p>
+ <p>
+ Pour l'affichage basé sur des pages web,
+ il y a la classe <span class="new_code">HtmlReporter</span> avec la signature suivante...
+<pre>
+class HtmlReporter extends SimpleReporter {
+ public __construct($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() { ... }
+}
+</pre>
+ Voici ce que certaines de ces méthodes veulent dire.
+ Premièrement les méthodes d'affichage que vous voudrez probablement surcharger...
+ <ul class="api">
+ <li>
+ <span class="new_code">HtmlReporter(string $encoding)</span><br>
+ 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
+ <a href="http://www.php.net/manual/fr/function.htmlentities.php">html_entities()</a>.
+ </li>
+ <li>
+ <span class="new_code">void paintHeader(string $test_name)</span><br>
+ 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 tests du niveau
+ le plus haut et donc c'est de là que le
+ <span class="new_code">$test_name</span> arrive.
+ Il peint le titre de la page, CSS, la balise "body", etc.
+ Il ne renvoie rien du tout (<span class="new_code">void</span>).
+ </li>
+ <li>
+ <span class="new_code">void paintFooter(string $test_name)</span><br>
+ 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.
+ </li>
+ <li>
+ <span class="new_code">void paintMethodStart(string $test_name)</span><br>
+ 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 tests 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.
+ </li>
+ <li>
+ <span class="new_code">void paintMethodEnd(string $test_name)</span><br>
+ clôt le test lancé avec le même nom.
+ </li>
+ <li>
+ <span class="new_code">void paintFail(string $message)</span><br>
+ peint un échec. Par défaut 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.
+ </li>
+ <li>
+ <span class="new_code">void paintPass(string $message)</span><br>
+ ne fait rien, par défaut.
+ </li>
+ <li>
+ <span class="new_code">string getCss()</span><br>
+ 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.
+ </li>
+ </ul>
+ 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...
+ <ul class="api">
+ <li>
+ <span class="new_code">array getTestList()</span><br>
+ 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 de premier niveau --
+ sera le premier dans la liste et la méthode de test
+ en cours sera la dernière.
+ </li>
+ <li>
+ <span class="new_code">integer getPassCount()</span><br>
+ renvoie le nombre de succès atteint. Il est nécessaire
+ pour l'affichage à la fin.
+ </li>
+ <li>
+ <span class="new_code">integer getFailCount()</span><br>
+ renvoie de la même manière le nombre d'échecs.
+ </li>
+ <li>
+ <span class="new_code">integer getExceptionCount()</span><br>
+ renvoie quant à lui le nombre d'erreurs.
+ </li>
+ <li>
+ <span class="new_code">integer getTestCaseCount()</span><br>
+ est le nombre total de scénarios lors de l'exécution des tests.
+ Il comprend aussi les tests groupés.
+ </li>
+ <li>
+ <span class="new_code">integer getTestCaseProgress()</span><br>
+ est le nombre de scénarios réalisés jusqu'à présent.
+ </li>
+ </ul>
+ Une modification simple : demander à l'HtmlReporter d'afficher
+ aussi bien les succès que les échecs et les erreurs...
+<pre>
+<strong>class ReporterShowingPasses extends HtmlReporter {
+
+ function paintPass($message) {
+ parent::paintPass($message);
+ print "&lt;span class=\"pass\"&gt;Pass&lt;/span&gt;: ";
+ $breadcrumb = $this-&gt;getTestList();
+ array_shift($breadcrumb);
+ print implode("-&amp;gt;", $breadcrumb);
+ print "-&amp;gt;$message&lt;br /&gt;\n";
+ }
+
+ protected function getCss() {
+ return parent::getCss() . ' .pass { color: green; }';
+ }
+}</strong>
+</pre>
+ </p>
+ <p>
+ Une méthode qui a beaucoup fait jaser reste la méthode <span class="new_code">makeDry()</span>.
+ 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é.
+ </p>
+ <p>
+ 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 l'affichage, par exemple, d'une 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.
+ </p>
+
+ <h2>
+<a class="target" name="autre"></a>Etendre le rapporteur</h2>
+ <p>
+ 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
+ <span class="new_code">HtmlReporter</span> nous pouvons nous rendre
+ une étape plus haut dans la hiérarchie de classe vers
+ <span class="new_code">SimpleReporter</span> dans le fichier source <em>simple_test.php</em>.
+ </p>
+ <p>
+ Un affichage sans rien, un canevas vierge
+ pour votre propre création, serait...
+<pre>
+<strong>require_once('simpletest/simpletest.php');</strong>
+
+class MyDisplay extends SimpleReporter {<strong>
+ </strong>
+ function paintHeader($test_name) { }
+
+ function paintFooter($test_name) { }
+
+ function paintStart($test_name, $size) {<strong>
+ parent::paintStart($test_name, $size);</strong>
+ }
+
+ function paintEnd($test_name, $size) {<strong>
+ parent::paintEnd($test_name, $size);</strong>
+ }
+
+ function paintPass($message) {<strong>
+ parent::paintPass($message);</strong>
+ }
+
+ function paintFail($message) {<strong>
+ parent::paintFail($message);</strong>
+ }
+
+ function paintError($message) {<strong>
+ parent::paintError($message);</strong>
+ }
+
+ function paintException($exception) {<strong>
+ parent::paintException($exception);</strong>
+ }
+}
+</pre>
+ Aucune sortie ne viendrait de cette classe jusqu'à un ajout de votre part.
+ </p>
+ <p>
+ Sauf qu'il y a un problème : en utilisant cette cette classe
+ de bas niveau, vous devez explicitement l'invoquer
+ dans les scripts de test.
+ La commande "autorun" ne sera pas capable
+ d'utiliser son contexte courant (qu'elle soit lancée
+ dans un navigateur web ou via une ligne de commande)
+ pour sélectionner le rapporteur.
+ </p>
+ <p>
+ Vous invoquez explicitement la lanceur de tests comme suit...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+$test = new TestSuite('File test');
+$test-&gt;addFile('tests/file_test.php');
+$test-&gt;run(<strong>new MyReporter()</strong>);
+?&gt;
+</pre>
+ ...ou peut-être comme cela...
+<pre>
+&lt;?php
+require_once('simpletest/simpletest.php');
+require_once('my_reporter.php');
+
+class MyTest extends TestSuite {
+ function __construct() {
+ parent::__construct();
+ $this-&gt;addFile('tests/file_test.php');
+ }
+}
+
+$test = new MyTest();
+$test-&gt;run(<strong>new MyReporter()</strong>);
+?&gt;
+</pre>
+ Nous verrons plus comment l'intégrer avec l'"autorun".
+ </p>
+
+ <h2>
+<a class="target" name="cli"></a>Le rapporteur en ligne de commande</h2>
+ <p>
+ SimpleTest est aussi livré avec un rapporteur
+ en ligne de commande, minime lui aussi.
+ Pour utiliser le rapporteur en ligne de commande explicitement,
+ il suffit de l'intervertir avec celui de la version HTML...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+$test = new TestSuite('File test');
+$test-&gt;addFile('tests/file_test.php');
+$test-&gt;run(<strong>new TextReporter()</strong>);
+?&gt;
+</pre>
+ Et ensuite d'invoquer la suite de test à partir d'une ligne de commande...
+<pre class="shell">
+php file_test.php
+</pre>
+ Bien sûr vous aurez besoin d'installer PHP
+ en ligne de commande. Une suite de test qui
+ passerait toutes ses assertions ressemble à...
+<pre class="shell">
+File test
+OK
+Test cases run: 1/1, Passes: 1, Failures: 0, Exceptions: 0
+</pre>
+ Un échec déclenche un affichage comme...
+<pre class="shell">
+File test
+1) True assertion failed.
+ in createNewFile
+FAILURES!!!
+Test cases run: 1/1, Passes: 0, Failures: 1, Exceptions: 0
+</pre>
+ </p>
+ <p>
+ 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 <span class="new_code">false</span>
+ est renvoyée par la méthode <span class="new_code">SimpleTest::run()</span>.
+ Nous pouvons utiliser ce résultat pour terminer le script
+ avec la bonne valeur renvoyée...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+$test = new TestSuite('File test');
+$test-&gt;addFile('tests/file_test.php');
+<strong>exit ($test-&gt;run(new TextReporter()) ? 0 : 1);</strong>
+?&gt;
+</pre>
+ Bien sûr l'objectif ne serait 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...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+$test = new TestSuite('File test');
+$test-&gt;addFile('tests/file_test.php');
+<strong>if (TextReporter::inCli()) {</strong>
+ exit ($test-&gt;run(new TextReporter()) ? 0 : 1);
+<strong>}</strong>
+$test-&gt;run(new HtmlReporter());
+?&gt;
+</pre>
+ Il s'agit là de la forme utilisée par SimpleTest lui-même.
+ Quand vous utilisez l'"autorun.php"
+ et qu'aucun test n'a été lancé avant la fin,
+ c'est quasiment le code que SimpleTest lancera
+ pour vous implicitement.
+ </p>
+ <p>
+ En d'autres termes, ceci donne le même résultat...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');
+
+class MyTest extends TestSuite {
+ function __construct() {
+ parent::__construct();
+ $this-&gt;addFile('tests/file_test.php');
+ }
+}
+?&gt;
+</pre> </p>
+
+ <h2>
+<a class="target" name="xml"></a>Test distant</h2>
+ <p>
+ SimpleTest est livré avec une classe <span class="new_code">XmlReporter</span>
+ utilisée pour de la communication interne.
+ Lors de son exécution, le résultat ressemble à...
+<pre class="shell">
+&lt;?xml version="1.0"?&gt;
+&lt;run&gt;
+ &lt;group size="4"&gt;
+ &lt;name&gt;Remote tests&lt;/name&gt;
+ &lt;group size="4"&gt;
+ &lt;name&gt;Visual test with 48 passes, 48 fails and 4 exceptions&lt;/name&gt;
+ &lt;case&gt;
+ &lt;name&gt;testofunittestcaseoutput&lt;/name&gt;
+ &lt;test&gt;
+ &lt;name&gt;testofresults&lt;/name&gt;
+ &lt;pass&gt;This assertion passed&lt;/pass&gt;
+ &lt;fail&gt;This assertion failed&lt;/fail&gt;
+ &lt;/test&gt;
+ &lt;test&gt;
+ ...
+ &lt;/test&gt;
+ &lt;/case&gt;
+ &lt;/group&gt;
+ &lt;/group&gt;
+&lt;/run&gt;
+</pre>
+ Pour faire en sorte ue vos scénarios de test produisent ce format,
+ dans la ligne de commande, ajoutez le flag <span class="new_code">--xml</span>.
+<pre class="shell">
+php my_test.php --xml
+</pre>
+ Vous pouvez faire la même chose dans le navigation web
+ en ajoutant le paramètre <span class="new_code">xml=1</span> dans l'URL.
+ N'importe quelle valeur "true" fera l'affaire.
+ </p>
+ <p>
+ Vous pouvez utiliser ce format avec le parseur
+ fourni dans SimpleTest lui-même.
+ Il s'agit de <span class="new_code">SimpleTestXmlParser</span>
+ et se trouve <em>xml.php</em> à l'intérieur du paquet SimpleTest...
+<pre>
+&lt;?php
+require_once('simpletest/xml.php');
+
+...
+$parser = new SimpleTestXmlParser(new HtmlReporter());
+$parser-&gt;parse($test_output);
+?&gt;
+</pre>
+ <span class="new_code">$test_output</span> 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.
+ </p>
+ <p>
+ Le plus courant, c'est quand vous voulez isoler
+ un test sensible au crash.
+ Vous pouvez collecter la sortie XML en utilisant
+ l'opérateur antiquote (Ndt : backtick) à partir
+ d'un autre test.
+ De la sorte, il tourne dans son propre processus...
+<pre>
+&lt;?php
+require_once('simpletest/xml.php');
+
+if (TextReporter::inCli()) {
+ $parser = new SimpleTestXmlParser(new TextReporter());
+} else {
+ $parser = new SimpleTestXmlParser(new HtmlReporter());
+}
+$parser-&gt;parse(`php flakey_test.php --xml`);
+?&gt;
+</pre>
+ </p>
+ <p>
+ Un autre cas est celui des très longues suites de tests.
+ </p>
+ <p>
+ Elles peuvent venir à bout de la limite de mémoire
+ par défaut d'un process PHP - 16Mb.
+ 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 parsé à nouveau pour agréger
+ les résultats avec moins d'impact sur le test au premier niveau.
+ </p>
+ <p>
+ 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...
+<pre>
+&lt;?php
+<strong>require_once('../remote.php');</strong>
+require_once('simpletest/autorun.php');
+
+$test_url = ...;
+$dry_url = ...;
+
+class MyTestOnAnotherServer extends RemoteTestCase {
+ function __construct() {
+ $test_url = ...
+ parent::__construct($test_url, $test_url . ' --dry');
+ }
+}
+?&gt;
+</pre>
+ <span class="new_code">RemoteTestCase</span> 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.
+ <span class="new_code">RemoteTestCase</span> peut être ajouté à
+ une suite de test comme n'importe quelle autre suite de tests.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ La page du projet SimpleTest sur
+ <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ La page de téléchargement de SimpleTest sur
+ <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ L'<a href="http://simpletest.org/api/">API pour développeur de SimpleTest</a>
+ donne tous les détails sur les classes et les assertions disponibles.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/fr/unit_test_documentation.html b/3rdparty/simpletest/docs/fr/unit_test_documentation.html
new file mode 100644
index 00000000000..a7c31f95dbb
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/unit_test_documentation.html
@@ -0,0 +1,447 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Documentation SimpleTest pour les tests de régression en PHP</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Documentation sur les tests unitaires en PHP</h1>
+ This page...
+ <ul>
+<li>
+ <a href="#unitaire">Scénarios de test unitaire</a>
+ et opérations basiques.
+ </li>
+<li>
+ <a href="#extension_unitaire">Étendre des scénarios de test</a>
+ pour les personnaliser à votre propre projet.
+ </li>
+<li>
+ <a href="#lancement_unitaire">Lancer un scénario seul</a>
+ comme un script unique.
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="unitaire"></a>Scénarios de tests unitaires</h2>
+ <p>
+ Le coeur du système est un framework de tests de régression
+ construit autour des scénarios de test.
+ Un exemple de scénario de test ressemble à...
+<pre>
+<strong>class FileTestCase extends UnitTestCase {
+}</strong>
+</pre>
+ 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.
+ </p>
+ <p>
+ 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...
+<pre>
+require_once('simpletest/autorun.php');
+require_once('../classes/writer.php');
+
+class FileTestCase extends UnitTestCase {
+ function FileTestCase() {
+ $this-&gt;UnitTestCase('File test');
+ }<strong>
+
+ function setUp() {
+ @unlink('../temp/test.txt');
+ }
+
+ function tearDown() {
+ @unlink('../temp/test.txt');
+ }
+
+ function testCreation() {
+ $writer = &amp;new FileWriter('../temp/test.txt');
+ $writer-&gt;write('Hello');
+ $this-&gt;assertTrue(file_exists('../temp/test.txt'), 'File created');
+ }</strong>
+}
+</pre>
+ Le constructeur est optionnel et souvent omis. Sans nom,
+ le nom de la classe est utilisé comme nom pour le scénario de test.
+ </p>
+ <p>
+ Notre unique méthode de test pour le moment est
+ <span class="new_code">testCreation()</span> où nous vérifions
+ qu'un fichier a bien été créé par notre objet
+ <span class="new_code">Writer</span>. Nous pourrions avoir mis
+ le code <span class="new_code">unlink()</span> dans cette méthode,
+ mais en la plaçant dans <span class="new_code">setUp()</span>
+ et <span class="new_code">tearDown()</span> nous pouvons l'utiliser
+ pour nos autres méthodes de test que nous ajouterons.
+ </p>
+ <p>
+ La méthode <span class="new_code">setUp()</span> est lancé
+ juste avant chaque méthode de test.
+ <span class="new_code">tearDown()</span> est lancé après chaque méthode de test.
+ </p>
+ <p>
+ 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
+ <span class="new_code">setUp()</span>, mais fournit aux codeurs de bibliothèque d'autres crochets.
+ </p>
+ <p>
+ Pour rapporter les résultats de test,
+ le passage par une classe d'affichage - notifiée par
+ les différentes méthodes de type <span class="new_code">assert...()</span> -
+ est utilisée. En voici la liste complète pour
+ la classe <span class="new_code">UnitTestCase</span>,
+ celle par défaut dans SimpleTest...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">assertTrue($x)</span></td>
+<td>Echoue si $x est faux</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertFalse($x)</span></td>
+<td>Echoue si $x est vrai</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNull($x)</span></td>
+<td>Echoue si $x est initialisé</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNotNull($x)</span></td>
+<td>Echoue si $x n'est pas initialisé</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertIsA($x, $t)</span></td>
+<td>Echoue si $x n'est pas de la classe ou du type $t</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertEqual($x, $y)</span></td>
+<td>Echoue si $x == $y est faux</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNotEqual($x, $y)</span></td>
+<td>Echoue si $x == $y est vrai</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertIdentical($x, $y)</span></td>
+<td>Echoue si $x === $y est faux</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNotIdentical($x, $y)</span></td>
+<td>Echoue si $x === $y est vrai</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertReference($x, $y)</span></td>
+<td>Echoue sauf si $x et $y sont la même variable</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertCopy($x, $y)</span></td>
+<td>Echoue si $x et $y sont la même variable</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertPattern($p, $x)</span></td>
+<td>Echoue sauf si l'expression rationnelle $p capture $x</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoPattern($p, $x)</span></td>
+<td>Echoue si l'expression rationnelle $p capture $x</td>
+</tr>
+ <tr>
+<td><span class="new_code">expectError($x)</span></td>
+<td>Echoue si l'erreur correspondante n'arrive pas</td>
+</tr>
+ <tr>
+<td><span class="new_code">expectException($x)</span></td>
+<td>Echoue si l'exception correspondante n'est pas levée</td>
+</tr>
+ <tr>
+<td><span class="new_code">ignoreException($x)</span></td>
+<td>Avale toutes les exceptions correspondantes qui surviendraient</td>
+</tr>
+ <tr>
+<td><span class="new_code">assert($e)</span></td>
+<td>Echoue sur un objet <a href="expectation_documentation.html">attente</a> $e qui échouerait</td>
+</tr>
+ </tbody></table>
+ 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.
+ </p>
+ <p>
+ D'autres exemples...
+<pre>
+<strong>$variable = null;
+$this-&gt;assertNull($variable, 'Should be cleared');</strong>
+</pre>
+ ...passera et normalement n'affichera aucun message.
+ Si vous avez <a href="http://www.lastcraft.com/display_subclass_tutorial.php">
+ configuré le testeur pour afficher aussi les succès</a>
+ alors le message sera affiché comme tel.
+<pre>
+<strong>$this-&gt;assertIdentical(0, false, 'Zero is not false [%s]');</strong>
+</pre>
+ 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.
+<pre>
+<strong>$a = 1;
+$b = $a;
+$this-&gt;assertReference($a, $b);</strong>
+</pre>
+ Échouera étant donné que la variable <span class="new_code">$b</span>
+ est une copie de <span class="new_code">$a</span>.
+<pre>
+<strong>$this-&gt;assertPattern('/hello/i', 'Hello world');</strong>
+</pre>
+ Là, ça passe puisque la recherche est insensible
+ à la casse et que donc <span class="new_code">hello</span>
+ est bien repérable dans <span class="new_code">Hello world</span>.
+<pre>
+<strong>$this-&gt;expectError();</strong>
+trigger_error('Catastrophe');
+</pre>
+ Ici la vérification attrape le message "Catastrophe"
+ sans vérifier le texte et passe.
+ Elle enlève l'erreur de la queue au passage.
+<pre>
+<strong>$this-&gt;expectError('Catastrophe');</strong>
+trigger_error('Catastrophe');
+</pre>
+ La vérification d'erreur suivante teste non seulement
+ l'existance de l'erreur mais aussi le texte qui,
+ dans le cas présent, correspond et donc un nouveau succès.
+ Si des erreurs non vérifiées sont laissées pour compte
+ à la fin d'une méthode de test alors un exception sera levé
+ dans le test.
+ </p>
+ <p>
+ Notez que SimpleTest ne peut pas attraper des erreurs PHP
+ au moment de la compilation.
+ </p>
+ <p>
+ Les scénarios de tests peuvent utiliser des méthodes
+ bien pratiques pour déboguer le code ou pour étendre la suite...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">setUp()</span></td>
+<td>Est lancée avant chaque méthode de test</td>
+</tr>
+ <tr>
+<td><span class="new_code">tearDown()</span></td>
+<td>Est lancée après chaque méthode de test</td>
+</tr>
+ <tr>
+<td><span class="new_code">pass()</span></td>
+<td>Envoie un succès</td>
+</tr>
+ <tr>
+<td><span class="new_code">fail()</span></td>
+<td>Envoie un échec</td>
+</tr>
+ <tr>
+<td><span class="new_code">error()</span></td>
+<td>Envoi un évènement exception</td>
+</tr>
+ <tr>
+<td><span class="new_code">signal($type, $payload)</span></td>
+<td>Envoie un message défini par l'utilisateur au rapporteur du test</td>
+</tr>
+ <tr>
+<td><span class="new_code">dump($var)</span></td>
+<td>Effectue un <span class="new_code">print_r()</span> formaté pour du déboguage rapide et grossier</td>
+</tr>
+ </tbody></table>
+ </p>
+
+ <h2>
+<a class="target" name="extension_unitaire"></a>Etendre les scénarios de test</h2>
+ <p>
+ Bien sûr des méthodes supplémentaires de test
+ peuvent être ajoutées pour créer d'autres types
+ de scénario de test afin d'étendre le framework...
+<pre>
+require_once('simpletest/autorun.php');
+<strong>
+class FileTester extends UnitTestCase {
+ function FileTester($name = false) {
+ $this-&gt;UnitTestCase($name);
+ }
+
+ function assertFileExists($filename, $message = '%s') {
+ $this-&gt;assertTrue(
+ file_exists($filename),
+ sprintf($message, 'File [$filename] existence check'));
+ }</strong>
+}
+</pre>
+ Ici la bibliothèque SimpleTest est localisée
+ dans un répertoire local appelé <em>simpletest</em>.
+ Pensez à le modifier pour votre propre environnement.
+ </p>
+ <p>
+ Alternativement vous pourriez utiliser dans votre code
+ un directive <span class="new_code">SimpleTestOptions::ignore('FileTester');</span>.
+ </p>
+ <p>
+ Ce nouveau scénario peut être hérité exactement
+ comme un scénario de test classique...
+<pre>
+class FileTestCase extends <strong>FileTester</strong> {
+
+ function setUp() {
+ @unlink('../temp/test.txt');
+ }
+
+ function tearDown() {
+ @unlink('../temp/test.txt');
+ }
+
+ function testCreation() {
+ $writer = &amp;new FileWriter('../temp/test.txt');
+ $writer-&gt;write('Hello');<strong>
+ $this-&gt;assertFileExists('../temp/test.txt');</strong>
+ }
+}
+</pre>
+ </p>
+ <p>
+ Si vous souhaitez un scénario de test sans
+ toutes les assertions de <span class="new_code">UnitTestCase</span>
+ mais uniquement avec les vôtres propres,
+ vous aurez besoin d'étendre la classe
+ <span class="new_code">SimpleTestCase</span> à la place.
+ Elle se trouve dans <em>simple_test.php</em>
+ en lieu et place de <em>unit_tester.php</em>.
+ A consulter <a href="group_test_documentation.html">plus tard</a>
+ si vous souhaitez incorporer les scénarios
+ d'autres testeurs unitaires dans votre suite de test.
+ </p>
+
+ <h2>
+<a class="target" name="lancement_unitaire"></a>Lancer un unique scénario de test</h2>
+ <p>
+ 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.
+ Avec <em>autorun</em> aucun échafaudage particulier
+ n'est nécessaire, il suffit de lancer votre test et
+ vous y êtes.
+ </p>
+ <p>
+ Vous pouvez même décider quel rapporteur
+ (par exemple, <span class="new_code">TextReporter</span> ou <span class="new_code">HtmlReporter</span>)
+ vous préférez pour un fichier spécifique quand il est lancé
+ tout seul...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');<strong>
+SimpleTest :: prefer(new TextReporter());</strong>
+require_once('../classes/writer.php');
+
+class FileTestCase extends UnitTestCase {
+ ...
+}
+?&gt;
+</pre>
+ Ce script sera lancé tel que mais il n'y aura
+ aucun succès ou échec avant que des méthodes de test soient ajoutées.
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ La page de SimpleTest sur
+ <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ La page de téléchargement de SimpleTest sur
+ <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ <a href="http://simpletest.org/api/">L'API complète de SimpleTest</a>
+ à partir de PHPDoc.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/docs/fr/web_tester_documentation.html b/3rdparty/simpletest/docs/fr/web_tester_documentation.html
new file mode 100644
index 00000000000..308fbc9ccbb
--- /dev/null
+++ b/3rdparty/simpletest/docs/fr/web_tester_documentation.html
@@ -0,0 +1,570 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Documentation SimpleTest : tester des scripts web</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<h1>Documentation sur le testeur web</h1>
+ This page...
+ <ul>
+<li>
+ Réussir à <a href="#telecharger">télécharger une page web</a>
+ </li>
+<li>
+ Tester le <a href="#contenu">contenu de la page</a>
+ </li>
+<li>
+ <a href="#navigation">Naviguer sur un site web</a> pendant le test
+ </li>
+<li>
+ Méthodes pour <a href="#requete">modifier une requête</a> et pour déboguer
+ </li>
+</ul>
+<div class="content">
+ <h2>
+<a class="target" name="telecharger"></a>Télécharger une page</h2>
+ <p>
+ Tester des classes c'est 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.
+ </p>
+ <p>
+ 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.
+ </p>
+ <p>
+ SimpleTest comprend une forme spéciale de scénario
+ de test pour tester les actions d'une page web.
+ <span class="new_code">WebTestCase</span> 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 à <span class="new_code">UnitTestCase</span>...
+<pre>
+<strong>class TestOfLastcraft extends WebTestCase {
+}</strong>
+</pre>
+ Ici nous sommes sur le point de tester
+ le site de <a href="http://www.lastcraft.com/">Last Craft</a>.
+ Si ce scénario de test est situé dans un fichier appelé
+ <em>lastcraft_test.php</em> alors il peut être chargé
+ dans un script de lancement tout comme des tests unitaires...
+<pre>
+&lt;?php
+require_once('simpletest/autorun.php');<strong>
+require_once('simpletest/web_tester.php');</strong>
+SimpleTest::prefer(new TextReporter());
+
+class WebTests extends TestSuite {
+ function WebTests() {
+ $this-&gt;TestSuite('Web site tests');<strong>
+ $this-&gt;addFile('lastcraft_test.php');</strong>
+ }
+}
+?&gt;
+</pre>
+ J'utilise ici le rapporteur en mode texte
+ pour mieux distinguer le contenu au format HTML
+ du résultat du test proprement dit.
+ </p>
+ <p>
+ Rien n'est encore testé. Nous pouvons télécharger
+ la page d'accueil en utilisant la méthode <span class="new_code">get()</span>...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+ <strong>
+ function testHomepage() {
+ $this-&gt;assertTrue($this-&gt;get('http://www.lastcraft.com/'));
+ }</strong>
+}
+</pre>
+ La méthode <span class="new_code">get()</span> 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 <span class="new_code">get()</span> renverrait encore un succès.
+ </p>
+ <p>
+ 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...
+<pre class="shell">
+Web site tests
+OK
+Test cases run: 1/1, Failures: 0, Exceptions: 0
+</pre>
+ 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.
+ </p>
+
+ <h2>
+<a class="target" name="contenu"></a>Tester le contenu d'une page</h2>
+ <p>
+ Pour obtenir la confirmation que la page téléchargée
+ est bien celle que nous attendions,
+ nous devons vérifier son contenu.
+<pre>
+class TestOfLastcraft extends WebTestCase {
+
+ function testHomepage() {<strong>
+ $this-&gt;get('http://www.lastcraft.com/');
+ $this-&gt;assertWantedPattern('/why the last craft/i');</strong>
+ }
+}
+</pre>
+ 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.
+ </p>
+ <p>
+ Voici une liste possible d'assertions sur le contenu...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">assertWantedPattern($pattern)</span></td>
+<td>Vérifier une correspondance sur le contenu via une expression rationnelle Perl</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoUnwantedPattern($pattern)</span></td>
+<td>Une expression rationnelle Perl pour vérifier une absence</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertTitle($title)</span></td>
+<td>Passe si le titre de la page correspond exactement</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertLink($label)</span></td>
+<td>Passe si un lien avec ce texte est présent</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoLink($label)</span></td>
+<td>Passe si aucun lien avec ce texte est présent</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertLinkById($id)</span></td>
+<td>Passe si un lien avec cet attribut d'identification est présent</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertField($name, $value)</span></td>
+<td>Passe si une balise input avec ce nom contient cette valeur</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertFieldById($id, $value)</span></td>
+<td>Passe si une balise input avec cet identifiant contient cette valeur</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertResponse($codes)</span></td>
+<td>Passe si la réponse HTTP trouve une correspondance dans la liste</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertMime($types)</span></td>
+<td>Passe si le type MIME se retrouve dans cette liste</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertAuthentication($protocol)</span></td>
+<td>Passe si l'authentification provoquée est de ce type de protocole</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoAuthentication()</span></td>
+<td>Passe s'il n'y pas d'authentification provoquée en cours</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertRealm($name)</span></td>
+<td>Passe si le domaine provoqué correspond</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertHeader($header, $content)</span></td>
+<td>Passe si une entête téléchargée correspond à cette valeur</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoUnwantedHeader($header)</span></td>
+<td>Passe si une entête n'a pas été téléchargé</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertHeaderPattern($header, $pattern)</span></td>
+<td>Passe si une entête téléchargée correspond à cette expression rationnelle Perl</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertCookie($name, $value)</span></td>
+<td>Passe s'il existe un cookie correspondant</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoCookie($name)</span></td>
+<td>Passe s'il n'y a pas de cookie avec un tel nom</td>
+</tr>
+ </tbody></table>
+ 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".
+ </p>
+ <p>
+ A présent nous pourrions effectué le test sur le titre uniquement...
+<pre>
+<strong>$this-&gt;assertTitle('The Last Craft?');</strong>
+</pre>
+ 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...
+<pre>
+<strong>$this-&gt;assertMime(array('text/plain', 'text/html'));</strong>
+</pre>
+ 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...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+
+ function testHomepage() {
+ $this-&gt;get('http://simpletest.sourceforge.net/');<strong>
+ $this-&gt;assertResponse(200);</strong>
+ }
+}
+</pre>
+ 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 <em>http://simpletest.sourceforge.net/</em>,
+ à la place le serveur renverra une redirection vers
+ <em>http://www.lastcraft.com/simple_test.php</em>.
+ <span class="new_code">WebTestCase</span> 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...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+
+ function testHomepage() {<strong>
+ $this-&gt;setMaximumRedirects(0);</strong>
+ $this-&gt;get('http://simpletest.sourceforge.net/');
+ $this-&gt;assertResponse(200);
+ }
+}
+</pre>
+ Alors l'assertion échoue comme prévue...
+<pre class="shell">
+Web site tests
+1) Expecting response in [200] got [302]
+ in testhomepage
+ in testoflastcraft
+ in lastcraft_test.php
+FAILURES!!!
+Test cases run: 1/1, Failures: 1, Exceptions: 0
+</pre>
+ Nous pouvons modifier le test pour accepter les redirections...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+
+ function testHomepage() {
+ $this-&gt;setMaximumRedirects(0);
+ $this-&gt;get('http://simpletest.sourceforge.net/');
+ $this-&gt;assertResponse(<strong>array(301, 302, 303, 307)</strong>);
+ }
+}
+</pre>
+ Maitenant ça passe.
+ </p>
+
+ <h2>
+<a class="target" name="navigation"></a>Navigeur dans un site web</h2>
+ <p>
+ 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...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+ ...
+ function testContact() {
+ $this-&gt;get('http://www.lastcraft.com/');<strong>
+ $this-&gt;clickLink('About');
+ $this-&gt;assertTitle('About Last Craft');</strong>
+ }
+}
+</pre>
+ Le paramètre est le texte du lien.
+ </p>
+ <p>
+ Il l'objectif est un bouton plutôt qu'une balise ancre,
+ alors <span class="new_code">clickSubmit()</span> doit être utilisé avec
+ le titre du bouton...
+<pre>
+<strong>$this-&gt;clickSubmit('Go!');</strong>
+</pre>
+ </p>
+ <p>
+ La liste des méthodes de navigation est...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">get($url, $parameters)</span></td>
+<td>Envoie une requête GET avec ces paramètres</td>
+</tr>
+ <tr>
+<td><span class="new_code">post($url, $parameters)</span></td>
+<td>Envoie une requête POST avec ces paramètres</td>
+</tr>
+ <tr>
+<td><span class="new_code">head($url, $parameters)</span></td>
+<td>Envoie une requête HEAD sans remplacer le contenu de la page</td>
+</tr>
+ <tr>
+<td><span class="new_code">retry()</span></td>
+<td>Relance la dernière requête</td>
+</tr>
+ <tr>
+<td><span class="new_code">back()</span></td>
+<td>Identique au bouton "Précédent" du navigateur</td>
+</tr>
+ <tr>
+<td><span class="new_code">forward()</span></td>
+<td>Identique au bouton "Suivant" du navigateur</td>
+</tr>
+ <tr>
+<td><span class="new_code">authenticate($name, $password)</span></td>
+<td>Re-essaye avec une tentative d'authentification</td>
+</tr>
+ <tr>
+<td><span class="new_code">getFrameFocus()</span></td>
+<td>Le nom de la fenêtre en cours d'utilisation</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFrameFocusByIndex($choice)</span></td>
+<td>Change le focus d'une fenêtre en commençant par 1</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFrameFocus($name)</span></td>
+<td>Change le focus d'une fenêtre en utilisant son nom</td>
+</tr>
+ <tr>
+<td><span class="new_code">clearFrameFocus()</span></td>
+<td>Revient à un traitement de toutes les fenêtres comme une seule</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmit($label)</span></td>
+<td>Clique sur le premier bouton avec cette étiquette</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmitByName($name)</span></td>
+<td>Clique sur le bouton avec cet attribut de nom</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmitById($id)</span></td>
+<td>Clique sur le bouton avec cet attribut d'identification</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImage($label, $x, $y)</span></td>
+<td>Clique sur une balise input de type image par son titre (title="*") our son texte alternatif (alt="*")</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImageByName($name, $x, $y)</span></td>
+<td>Clique sur une balise input de type image par son attribut (name="*")</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImageById($id, $x, $y)</span></td>
+<td>Clique sur une balise input de type image par son identifiant (id="*")</td>
+</tr>
+ <tr>
+<td><span class="new_code">submitFormById($id)</span></td>
+<td>Soumet un formulaire sans valeur de soumission</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickLink($label, $index)</span></td>
+<td>Clique sur une ancre avec ce texte d'étiquette visible</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickLinkById($id)</span></td>
+<td>Clique sur une ancre avec cet attribut d'identification</td>
+</tr>
+ </tbody></table>
+ </p>
+ <p>
+ Les paramètres dans les méthodes <span class="new_code">get()</span>,
+ <span class="new_code">post()</span> et <span class="new_code">head()</span> 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.
+ </p>
+ <p>
+ Les commandes <span class="new_code">retry()</span>, <span class="new_code">back()</span>
+ et <span class="new_code">forward()</span> 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.
+ </p>
+ <p>
+ 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é.
+ </p>
+ <p>
+ 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
+ <a href="form_testing_documentation.html">
+ des outils pour tester des formulaires web</a>.
+ </p>
+
+ <h2>
+<a class="target" name="requete"></a>Modifier la requête</h2>
+ <p>
+ 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...
+ <table><tbody>
+ <tr>
+<td><span class="new_code">getTransportError()</span></td>
+<td>La dernière erreur de socket</td>
+</tr>
+ <tr>
+<td><span class="new_code">getUrl()</span></td>
+<td>La localisation courante</td>
+</tr>
+ <tr>
+<td><span class="new_code">showRequest()</span></td>
+<td>Déverse la requête sortante</td>
+</tr>
+ <tr>
+<td><span class="new_code">showHeaders()</span></td>
+<td>Déverse les entêtes d'entrée</td>
+</tr>
+ <tr>
+<td><span class="new_code">showSource()</span></td>
+<td>Déverse le contenu brut de la page HTML</td>
+</tr>
+ <tr>
+<td><span class="new_code">ignoreFrames()</span></td>
+<td>Ne recharge pas les framesets</td>
+</tr>
+ <tr>
+<td><span class="new_code">setCookie($name, $value)</span></td>
+<td>Initie un cookie à partir de maintenant</td>
+</tr>
+ <tr>
+<td><span class="new_code">addHeader($header)</span></td>
+<td>Ajoute toujours cette entête à la requête</td>
+</tr>
+ <tr>
+<td><span class="new_code">setMaximumRedirects($max)</span></td>
+<td>S'arrête après autant de redirections</td>
+</tr>
+ <tr>
+<td><span class="new_code">setConnectionTimeout($timeout)</span></td>
+<td>Termine la connexion après autant de temps entre les bytes</td>
+</tr>
+ <tr>
+<td><span class="new_code">useProxy($proxy, $name, $password)</span></td>
+<td>Effectue les requêtes à travers ce proxy d'URL</td>
+</tr>
+ </tbody></table>
+ </p>
+
+ </div>
+ References and related information...
+ <ul>
+<li>
+ La page du projet SimpleTest sur
+ <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
+ </li>
+<li>
+ La page de téléchargement de SimpleTest sur
+ <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
+ </li>
+<li>
+ <a href="http://simpletest.org/api/">L'API du développeur pour SimpleTest</a>
+ donne tous les détails sur les classes et les assertions disponibles.
+ </li>
+</ul>
+<div class="menu_back"><div class="menu">
+<a href="index.html">SimpleTest</a>
+ |
+ <a href="overview.html">Overview</a>
+ |
+ <a href="unit_test_documentation.html">Unit tester</a>
+ |
+ <a href="group_test_documentation.html">Group tests</a>
+ |
+ <a href="mock_objects_documentation.html">Mock objects</a>
+ |
+ <a href="partial_mocks_documentation.html">Partial mocks</a>
+ |
+ <a href="reporter_documentation.html">Reporting</a>
+ |
+ <a href="expectation_documentation.html">Expectations</a>
+ |
+ <a href="web_tester_documentation.html">Web tester</a>
+ |
+ <a href="form_testing_documentation.html">Testing forms</a>
+ |
+ <a href="authentication_documentation.html">Authentication</a>
+ |
+ <a href="browser_documentation.html">Scriptable browser</a>
+</div></div>
+<div class="copyright">
+ Copyright<br>Marcus Baker 2006
+ </div>
+</body>
+</html>
diff --git a/3rdparty/simpletest/dumper.php b/3rdparty/simpletest/dumper.php
new file mode 100755
index 00000000000..339923c224f
--- /dev/null
+++ b/3rdparty/simpletest/dumper.php
@@ -0,0 +1,407 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: dumper.php 1909 2009-07-29 15:58:11Z dgheath $
+ */
+/**
+ * does type matter
+ */
+if (! defined('TYPE_MATTERS')) {
+ define('TYPE_MATTERS', true);
+}
+
+/**
+ * Displays variables as text and does diffs.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleDumper {
+
+ /**
+ * Renders a variable in a shorter form than print_r().
+ * @param mixed $value Variable to render as a string.
+ * @return string Human readable string form.
+ * @access public
+ */
+ function describeValue($value) {
+ $type = $this->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, 200);
+ 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
+ */
+ protected 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
+ */
+ protected function describeGenericDifference($first, $second) {
+ return "as [" . $this->describeValue($first) .
+ "] does not match [" .
+ $this->describeValue($second) . "]";
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between a null and another variable.
+ * @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
+ */
+ protected function describeNullDifference($first, $second, $identical) {
+ return $this->describeGenericDifference($first, $second);
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between a boolean and another variable.
+ * @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
+ */
+ protected function describeBooleanDifference($first, $second, $identical) {
+ return $this->describeGenericDifference($first, $second);
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between a string and another variable.
+ * @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
+ */
+ protected 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, 200, $position) . "] and [" .
+ $this->clipString($second, 200, $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
+ */
+ protected 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
+ */
+ protected 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) . "] by " .
+ abs($first - $second);
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between two arrays.
+ * @param array $first First array.
+ * @param mixed $second Array to compare with.
+ * @param boolean $identical If true then type anomolies count.
+ * @return string Human readable description.
+ * @access private
+ */
+ protected 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
+ */
+ protected 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
+ */
+ protected 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.
+ */
+ protected function describeObjectDifference($first, $second, $identical) {
+ if (! is_object($second)) {
+ return $this->describeGenericDifference($first, $second);
+ }
+ return $this->describeArrayDifference(
+ $this->getMembers($first),
+ $this->getMembers($second),
+ $identical);
+ }
+
+ /**
+ * Get all members of an object including private and protected ones.
+ * A safer form of casting to an array.
+ * @param object $object Object to list members of,
+ * including private ones.
+ * @return array Names and values in the object.
+ */
+ protected function getMembers($object) {
+ $reflection = new ReflectionObject($object);
+ $members = array();
+ foreach ($reflection->getProperties() as $property) {
+ if (method_exists($property, 'setAccessible')) {
+ $property->setAccessible(true);
+ }
+ try {
+ $members[$property->getName()] = $property->getValue($object);
+ } catch (ReflectionException $e) {
+ $members[$property->getName()] =
+ $this->getPrivatePropertyNoMatterWhat($property->getName(), $object);
+ }
+ }
+ return $members;
+ }
+
+ /**
+ * Extracts a private member's value when reflection won't play ball.
+ * @param string $name Property name.
+ * @param object $object Object to read.
+ * @return mixed Value of property.
+ */
+ private function getPrivatePropertyNoMatterWhat($name, $object) {
+ foreach ((array)$object as $mangled_name => $value) {
+ if ($this->unmangle($mangled_name) == $name) {
+ return $value;
+ }
+ }
+ }
+
+ /**
+ * Removes crud from property name after it's been converted
+ * to an array.
+ * @param string $mangled Name from array cast.
+ * @return string Cleaned up name.
+ */
+ function unmangle($mangled) {
+ $parts = preg_split('/[^a-zA-Z0-9_\x7f-\xff]+/', $mangled);
+ return array_pop($parts);
+ }
+
+ /**
+ * Find the first character position that differs
+ * in two strings by binary chop.
+ * @param string $first First string.
+ * @param string $second String to compare with.
+ * @return integer Position of first differing
+ * character.
+ * @access private
+ */
+ protected 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
+ */
+ function dump($variable) {
+ ob_start();
+ print_r($variable);
+ $formatted = ob_get_contents();
+ ob_end_clean();
+ return $formatted;
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/eclipse.php b/3rdparty/simpletest/eclipse.php
new file mode 100644
index 00000000000..20bd4530bb6
--- /dev/null
+++ b/3rdparty/simpletest/eclipse.php
@@ -0,0 +1,307 @@
+<?php
+/**
+ * base include file for eclipse plugin
+ * @package SimpleTest
+ * @subpackage Eclipse
+ * @version $Id: eclipse.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+/**#@+
+ * simpletest include files
+ */
+include_once 'unit_tester.php';
+include_once 'test_case.php';
+include_once 'invoker.php';
+include_once 'socket.php';
+include_once 'mock_objects.php';
+/**#@-*/
+
+/**
+ * base reported class for eclipse plugin
+ * @package SimpleTest
+ * @subpackage Eclipse
+ */
+class EclipseReporter extends SimpleScorer {
+
+ /**
+ * Reporter to be run inside of Eclipse interface.
+ * @param object $listener Eclipse listener (?).
+ * @param boolean $cc Whether to include test coverage.
+ */
+ function __construct(&$listener, $cc=false){
+ $this->listener = &$listener;
+ $this->SimpleScorer();
+ $this->case = "";
+ $this->group = "";
+ $this->method = "";
+ $this->cc = $cc;
+ $this->error = false;
+ $this->fail = false;
+ }
+
+ /**
+ * Means to display human readable object comparisons.
+ * @return SimpleDumper Visual comparer.
+ */
+ function getDumper() {
+ return new SimpleDumper();
+ }
+
+ /**
+ * Localhost connection from Eclipse.
+ * @param integer $port Port to connect to Eclipse.
+ * @param string $host Normally localhost.
+ * @return SimpleSocket Connection to Eclipse.
+ */
+ function &createListener($port, $host="127.0.0.1"){
+ $tmplistener = &new SimpleSocket($host, $port, 5);
+ return $tmplistener;
+ }
+
+ /**
+ * Wraps the test in an output buffer.
+ * @param SimpleInvoker $invoker Current test runner.
+ * @return EclipseInvoker Decorator with output buffering.
+ * @access public
+ */
+ function &createInvoker(&$invoker){
+ $eclinvoker = &new EclipseInvoker($invoker, $this->listener);
+ return $eclinvoker;
+ }
+
+ /**
+ * C style escaping.
+ * @param string $raw String with backslashes, quotes and whitespace.
+ * @return string Replaced with C backslashed tokens.
+ */
+ function escapeVal($raw){
+ $needle = array("\\","\"","/","\b","\f","\n","\r","\t");
+ $replace = array('\\\\','\"','\/','\b','\f','\n','\r','\t');
+ return str_replace($needle, $replace, $raw);
+ }
+
+ /**
+ * Stash the first passing item. Clicking the test
+ * item goes to first pass.
+ * @param string $message Test message, but we only wnat the first.
+ * @access public
+ */
+ function paintPass($message){
+ if (! $this->pass){
+ $this->message = $this->escapeVal($message);
+ }
+ $this->pass = true;
+ }
+
+ /**
+ * Stash the first failing item. Clicking the test
+ * item goes to first fail.
+ * @param string $message Test message, but we only wnat the first.
+ * @access public
+ */
+ function paintFail($message){
+ //only get the first failure or error
+ if (! $this->fail && ! $this->error){
+ $this->fail = true;
+ $this->message = $this->escapeVal($message);
+ $this->listener->write('{status:"fail",message:"'.$this->message.'",group:"'.$this->group.'",case:"'.$this->case.'",method:"'.$this->method.'"}');
+ }
+ }
+
+ /**
+ * Stash the first error. Clicking the test
+ * item goes to first error.
+ * @param string $message Test message, but we only wnat the first.
+ * @access public
+ */
+ function paintError($message){
+ if (! $this->fail && ! $this->error){
+ $this->error = true;
+ $this->message = $this->escapeVal($message);
+ $this->listener->write('{status:"error",message:"'.$this->message.'",group:"'.$this->group.'",case:"'.$this->case.'",method:"'.$this->method.'"}');
+ }
+ }
+
+
+ /**
+ * Stash the first exception. Clicking the test
+ * item goes to first message.
+ * @param string $message Test message, but we only wnat the first.
+ * @access public
+ */
+ function paintException($exception){
+ if (! $this->fail && ! $this->error){
+ $this->error = true;
+ $message = 'Unexpected exception of type[' . get_class($exception) .
+ '] with message [' . $exception->getMessage() . '] in [' .
+ $exception->getFile() .' line '. $exception->getLine() . ']';
+ $this->message = $this->escapeVal($message);
+ $this->listener->write(
+ '{status:"error",message:"' . $this->message . '",group:"' .
+ $this->group . '",case:"' . $this->case . '",method:"' . $this->method
+ . '"}');
+ }
+ }
+
+
+ /**
+ * We don't display any special header.
+ * @param string $test_name First test top level
+ * to start.
+ * @access public
+ */
+ function paintHeader($test_name) {
+ }
+
+ /**
+ * We don't display any special footer.
+ * @param string $test_name The top level test.
+ * @access public
+ */
+ function paintFooter($test_name) {
+ }
+
+ /**
+ * Paints nothing at the start of a test method, but stash
+ * the method name for later.
+ * @param string $test_name Name of test that is starting.
+ * @access public
+ */
+ function paintMethodStart($method) {
+ $this->pass = false;
+ $this->fail = false;
+ $this->error = false;
+ $this->method = $this->escapeVal($method);
+ }
+
+ /**
+ * Only send one message if the test passes, after that
+ * suppress the message.
+ * @param string $test_name Name of test that is ending.
+ * @access public
+ */
+ function paintMethodEnd($method){
+ if ($this->fail || $this->error || ! $this->pass){
+ } else {
+ $this->listener->write(
+ '{status:"pass",message:"' . $this->message . '",group:"' .
+ $this->group . '",case:"' . $this->case . '",method:"' .
+ $this->method . '"}');
+ }
+ }
+
+ /**
+ * Stashes the test case name for the later failure message.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseStart($case){
+ $this->case = $this->escapeVal($case);
+ }
+
+ /**
+ * Drops the name.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseEnd($case){
+ $this->case = "";
+ }
+
+ /**
+ * Stashes the name of the test suite. Starts test coverage
+ * if enabled.
+ * @param string $group Name of test or other label.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($group, $size){
+ $this->group = $this->escapeVal($group);
+ if ($this->cc){
+ if (extension_loaded('xdebug')){
+ xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);
+ }
+ }
+ }
+
+ /**
+ * Paints coverage report if enabled.
+ * @param string $group Name of test or other label.
+ * @access public
+ */
+ function paintGroupEnd($group){
+ $this->group = "";
+ $cc = "";
+ if ($this->cc){
+ if (extension_loaded('xdebug')){
+ $arrfiles = xdebug_get_code_coverage();
+ xdebug_stop_code_coverage();
+ $thisdir = dirname(__FILE__);
+ $thisdirlen = strlen($thisdir);
+ foreach ($arrfiles as $index=>$file){
+ if (substr($index, 0, $thisdirlen)===$thisdir){
+ continue;
+ }
+ $lcnt = 0;
+ $ccnt = 0;
+ foreach ($file as $line){
+ if ($line == -2){
+ continue;
+ }
+ $lcnt++;
+ if ($line==1){
+ $ccnt++;
+ }
+ }
+ if ($lcnt > 0){
+ $cc .= round(($ccnt/$lcnt) * 100, 2) . '%';
+ }else{
+ $cc .= "0.00%";
+ }
+ $cc.= "\t". $index . "\n";
+ }
+ }
+ }
+ $this->listener->write('{status:"coverage",message:"' .
+ EclipseReporter::escapeVal($cc) . '"}');
+ }
+}
+
+/**
+ * Invoker decorator for Eclipse. Captures output until
+ * the end of the test.
+ * @package SimpleTest
+ * @subpackage Eclipse
+ */
+class EclipseInvoker extends SimpleInvokerDecorator{
+ function __construct(&$invoker, &$listener) {
+ $this->listener = &$listener;
+ $this->SimpleInvokerDecorator($invoker);
+ }
+
+ /**
+ * Starts output buffering.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function before($method){
+ ob_start();
+ $this->invoker->before($method);
+ }
+
+ /**
+ * Stops output buffering and send the captured output
+ * to the listener.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function after($method) {
+ $this->invoker->after($method);
+ $output = ob_get_contents();
+ ob_end_clean();
+ if ($output !== ""){
+ $result = $this->listener->write('{status:"info",message:"' .
+ EclipseReporter::escapeVal($output) . '"}');
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/encoding.php b/3rdparty/simpletest/encoding.php
new file mode 100644
index 00000000000..cadc84e7a3b
--- /dev/null
+++ b/3rdparty/simpletest/encoding.php
@@ -0,0 +1,649 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: encoding.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/socket.php');
+/**#@-*/
+
+/**
+ * Single post parameter.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleEncodedPair {
+ private $key;
+ private $value;
+
+ /**
+ * Stashes the data for rendering later.
+ * @param string $key Form element name.
+ * @param string $value Data to send.
+ */
+ function __construct($key, $value) {
+ $this->key = $key;
+ $this->value = $value;
+ }
+
+ /**
+ * The pair as a single string.
+ * @return string Encoded pair.
+ * @access public
+ */
+ function asRequest() {
+ return urlencode($this->key) . '=' . urlencode($this->value);
+ }
+
+ /**
+ * The MIME part as a string.
+ * @return string MIME part encoding.
+ * @access public
+ */
+ function asMime() {
+ $part = 'Content-Disposition: form-data; ';
+ $part .= "name=\"" . $this->key . "\"\r\n";
+ $part .= "\r\n" . $this->value;
+ return $part;
+ }
+
+ /**
+ * Is this the value we are looking for?
+ * @param string $key Identifier.
+ * @return boolean True if matched.
+ * @access public
+ */
+ function isKey($key) {
+ return $key == $this->key;
+ }
+
+ /**
+ * Is this the value we are looking for?
+ * @return string Identifier.
+ * @access public
+ */
+ function getKey() {
+ return $this->key;
+ }
+
+ /**
+ * Is this the value we are looking for?
+ * @return string Content.
+ * @access public
+ */
+ function getValue() {
+ return $this->value;
+ }
+}
+
+/**
+ * Single post parameter.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleAttachment {
+ private $key;
+ private $content;
+ private $filename;
+
+ /**
+ * Stashes the data for rendering later.
+ * @param string $key Key to add value to.
+ * @param string $content Raw data.
+ * @param hash $filename Original filename.
+ */
+ function __construct($key, $content, $filename) {
+ $this->key = $key;
+ $this->content = $content;
+ $this->filename = $filename;
+ }
+
+ /**
+ * The pair as a single string.
+ * @return string Encoded pair.
+ * @access public
+ */
+ function asRequest() {
+ return '';
+ }
+
+ /**
+ * The MIME part as a string.
+ * @return string MIME part encoding.
+ * @access public
+ */
+ function asMime() {
+ $part = 'Content-Disposition: form-data; ';
+ $part .= 'name="' . $this->key . '"; ';
+ $part .= 'filename="' . $this->filename . '"';
+ $part .= "\r\nContent-Type: " . $this->deduceMimeType();
+ $part .= "\r\n\r\n" . $this->content;
+ return $part;
+ }
+
+ /**
+ * Attempts to figure out the MIME type from the
+ * file extension and the content.
+ * @return string MIME type.
+ * @access private
+ */
+ protected function deduceMimeType() {
+ if ($this->isOnlyAscii($this->content)) {
+ return 'text/plain';
+ }
+ return 'application/octet-stream';
+ }
+
+ /**
+ * Tests each character is in the range 0-127.
+ * @param string $ascii String to test.
+ * @access private
+ */
+ protected function isOnlyAscii($ascii) {
+ for ($i = 0, $length = strlen($ascii); $i < $length; $i++) {
+ if (ord($ascii[$i]) > 127) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Is this the value we are looking for?
+ * @param string $key Identifier.
+ * @return boolean True if matched.
+ * @access public
+ */
+ function isKey($key) {
+ return $key == $this->key;
+ }
+
+ /**
+ * Is this the value we are looking for?
+ * @return string Identifier.
+ * @access public
+ */
+ function getKey() {
+ return $this->key;
+ }
+
+ /**
+ * Is this the value we are looking for?
+ * @return string Content.
+ * @access public
+ */
+ function getValue() {
+ return $this->filename;
+ }
+}
+
+/**
+ * Bundle of GET/POST parameters. Can include
+ * repeated parameters.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleEncoding {
+ private $request;
+
+ /**
+ * Starts empty.
+ * @param array $query Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function __construct($query = false) {
+ if (! $query) {
+ $query = array();
+ }
+ $this->clear();
+ $this->merge($query);
+ }
+
+ /**
+ * Empties the request of parameters.
+ * @access public
+ */
+ function clear() {
+ $this->request = array();
+ }
+
+ /**
+ * 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 (is_array($value)) {
+ foreach ($value as $item) {
+ $this->addPair($key, $item);
+ }
+ } else {
+ $this->addPair($key, $value);
+ }
+ }
+
+ /**
+ * Adds a new value into the request.
+ * @param string $key Key to add value to.
+ * @param string/array $value New data.
+ * @access private
+ */
+ protected function addPair($key, $value) {
+ $this->request[] = new SimpleEncodedPair($key, $value);
+ }
+
+ /**
+ * Adds a MIME part to the query. Does nothing for a
+ * form encoded packet.
+ * @param string $key Key to add value to.
+ * @param string $content Raw data.
+ * @param hash $filename Original filename.
+ * @access public
+ */
+ function attach($key, $content, $filename) {
+ $this->request[] = new SimpleAttachment($key, $content, $filename);
+ }
+
+ /**
+ * Adds a set of parameters to this query.
+ * @param array/SimpleQueryString $query Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function merge($query) {
+ if (is_object($query)) {
+ $this->request = array_merge($this->request, $query->getAll());
+ } elseif (is_array($query)) {
+ foreach ($query as $key => $value) {
+ $this->add($key, $value);
+ }
+ }
+ }
+
+ /**
+ * Accessor for single value.
+ * @return string/array False if missing, string
+ * if present and array if
+ * multiple entries.
+ * @access public
+ */
+ function getValue($key) {
+ $values = array();
+ foreach ($this->request as $pair) {
+ if ($pair->isKey($key)) {
+ $values[] = $pair->getValue();
+ }
+ }
+ if (count($values) == 0) {
+ return false;
+ } elseif (count($values) == 1) {
+ return $values[0];
+ } else {
+ return $values;
+ }
+ }
+
+ /**
+ * Accessor for listing of pairs.
+ * @return array All pair objects.
+ * @access public
+ */
+ function getAll() {
+ return $this->request;
+ }
+
+ /**
+ * Renders the query string as a URL encoded
+ * request part.
+ * @return string Part of URL.
+ * @access protected
+ */
+ protected function encode() {
+ $statements = array();
+ foreach ($this->request as $pair) {
+ if ($statement = $pair->asRequest()) {
+ $statements[] = $statement;
+ }
+ }
+ return implode('&', $statements);
+ }
+}
+
+/**
+ * Bundle of GET parameters. Can include
+ * repeated parameters.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleGetEncoding extends SimpleEncoding {
+
+ /**
+ * Starts empty.
+ * @param array $query Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function __construct($query = false) {
+ parent::__construct($query);
+ }
+
+ /**
+ * HTTP request method.
+ * @return string Always GET.
+ * @access public
+ */
+ function getMethod() {
+ return 'GET';
+ }
+
+ /**
+ * Writes no extra headers.
+ * @param SimpleSocket $socket Socket to write to.
+ * @access public
+ */
+ function writeHeadersTo(&$socket) {
+ }
+
+ /**
+ * No data is sent to the socket as the data is encoded into
+ * the URL.
+ * @param SimpleSocket $socket Socket to write to.
+ * @access public
+ */
+ function writeTo(&$socket) {
+ }
+
+ /**
+ * Renders the query string as a URL encoded
+ * request part for attaching to a URL.
+ * @return string Part of URL.
+ * @access public
+ */
+ function asUrlRequest() {
+ return $this->encode();
+ }
+}
+
+/**
+ * Bundle of URL parameters for a HEAD request.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleHeadEncoding extends SimpleGetEncoding {
+
+ /**
+ * Starts empty.
+ * @param array $query Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function __construct($query = false) {
+ parent::__construct($query);
+ }
+
+ /**
+ * HTTP request method.
+ * @return string Always HEAD.
+ * @access public
+ */
+ function getMethod() {
+ return 'HEAD';
+ }
+}
+
+/**
+ * Bundle of URL parameters for a DELETE request.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleDeleteEncoding extends SimpleGetEncoding {
+
+ /**
+ * Starts empty.
+ * @param array $query Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function __construct($query = false) {
+ parent::__construct($query);
+ }
+
+ /**
+ * HTTP request method.
+ * @return string Always DELETE.
+ * @access public
+ */
+ function getMethod() {
+ return 'DELETE';
+ }
+}
+
+/**
+ * Bundles an entity-body for transporting
+ * a raw content payload with the request.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleEntityEncoding extends SimpleEncoding {
+ private $content_type;
+ private $body;
+
+ function __construct($query = false, $content_type = false) {
+ $this->content_type = $content_type;
+ if (is_string($query)) {
+ $this->body = $query;
+ parent::__construct();
+ } else {
+ parent::__construct($query);
+ }
+ }
+
+ /**
+ * Returns the media type of the entity body
+ * @return string
+ * @access public
+ */
+ function getContentType() {
+ if (!$this->content_type) {
+ return ($this->body) ? 'text/plain' : 'application/x-www-form-urlencoded';
+ }
+ return $this->content_type;
+ }
+
+ /**
+ * Dispatches the form headers down the socket.
+ * @param SimpleSocket $socket Socket to write to.
+ * @access public
+ */
+ function writeHeadersTo(&$socket) {
+ $socket->write("Content-Length: " . (integer)strlen($this->encode()) . "\r\n");
+ $socket->write("Content-Type: " . $this->getContentType() . "\r\n");
+ }
+
+ /**
+ * Dispatches the form data down the socket.
+ * @param SimpleSocket $socket Socket to write to.
+ * @access public
+ */
+ function writeTo(&$socket) {
+ $socket->write($this->encode());
+ }
+
+ /**
+ * Renders the request body
+ * @return Encoded entity body
+ * @access protected
+ */
+ protected function encode() {
+ return ($this->body) ? $this->body : parent::encode();
+ }
+}
+
+/**
+ * Bundle of POST parameters. Can include
+ * repeated parameters.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimplePostEncoding extends SimpleEntityEncoding {
+
+ /**
+ * Starts empty.
+ * @param array $query Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function __construct($query = false, $content_type = false) {
+ if (is_array($query) and $this->hasMoreThanOneLevel($query)) {
+ $query = $this->rewriteArrayWithMultipleLevels($query);
+ }
+ parent::__construct($query, $content_type);
+ }
+
+ function hasMoreThanOneLevel($query) {
+ foreach ($query as $key => $value) {
+ if (is_array($value)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function rewriteArrayWithMultipleLevels($query) {
+ $query_ = array();
+ foreach ($query as $key => $value) {
+ if (is_array($value)) {
+ foreach ($value as $sub_key => $sub_value) {
+ $query_[$key."[".$sub_key."]"] = $sub_value;
+ }
+ } else {
+ $query_[$key] = $value;
+ }
+ }
+ if ($this->hasMoreThanOneLevel($query_)) {
+ $query_ = $this->rewriteArrayWithMultipleLevels($query_);
+ }
+
+ return $query_;
+ }
+
+ /**
+ * HTTP request method.
+ * @return string Always POST.
+ * @access public
+ */
+ function getMethod() {
+ return 'POST';
+ }
+
+ /**
+ * Renders the query string as a URL encoded
+ * request part for attaching to a URL.
+ * @return string Part of URL.
+ * @access public
+ */
+ function asUrlRequest() {
+ return '';
+ }
+}
+
+/**
+ * Encoded entity body for a PUT request.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimplePutEncoding extends SimpleEntityEncoding {
+
+ /**
+ * Starts empty.
+ * @param array $query Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function __construct($query = false, $content_type = false) {
+ parent::__construct($query, $content_type);
+ }
+
+ /**
+ * HTTP request method.
+ * @return string Always PUT.
+ * @access public
+ */
+ function getMethod() {
+ return 'PUT';
+ }
+}
+
+/**
+ * Bundle of POST parameters in the multipart
+ * format. Can include file uploads.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleMultipartEncoding extends SimplePostEncoding {
+ private $boundary;
+
+ /**
+ * Starts empty.
+ * @param array $query Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function __construct($query = false, $boundary = false) {
+ parent::__construct($query);
+ $this->boundary = ($boundary === false ? uniqid('st') : $boundary);
+ }
+
+ /**
+ * Dispatches the form headers down the socket.
+ * @param SimpleSocket $socket Socket to write to.
+ * @access public
+ */
+ function writeHeadersTo(&$socket) {
+ $socket->write("Content-Length: " . (integer)strlen($this->encode()) . "\r\n");
+ $socket->write("Content-Type: multipart/form-data; boundary=" . $this->boundary . "\r\n");
+ }
+
+ /**
+ * Dispatches the form data down the socket.
+ * @param SimpleSocket $socket Socket to write to.
+ * @access public
+ */
+ function writeTo(&$socket) {
+ $socket->write($this->encode());
+ }
+
+ /**
+ * Renders the query string as a URL encoded
+ * request part.
+ * @return string Part of URL.
+ * @access public
+ */
+ function encode() {
+ $stream = '';
+ foreach ($this->getAll() as $pair) {
+ $stream .= "--" . $this->boundary . "\r\n";
+ $stream .= $pair->asMime() . "\r\n";
+ }
+ $stream .= "--" . $this->boundary . "--\r\n";
+ return $stream;
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/errors.php b/3rdparty/simpletest/errors.php
new file mode 100644
index 00000000000..b3d0c2a0753
--- /dev/null
+++ b/3rdparty/simpletest/errors.php
@@ -0,0 +1,267 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: errors.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**#@+
+ * Includes SimpleTest files.
+ */
+require_once dirname(__FILE__) . '/invoker.php';
+require_once dirname(__FILE__) . '/test_case.php';
+require_once dirname(__FILE__) . '/expectation.php';
+/**#@-*/
+
+/**
+ * Extension that traps errors into an error queue.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleErrorTrappingInvoker extends SimpleInvokerDecorator {
+
+ /**
+ * Stores the invoker to wrap.
+ * @param SimpleInvoker $invoker Test method runner.
+ */
+ function __construct($invoker) {
+ parent::__construct($invoker);
+ }
+
+ /**
+ * Invokes a test method and dispatches any
+ * untrapped errors. Called back from
+ * the visiting runner.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function invoke($method) {
+ $queue = $this->createErrorQueue();
+ set_error_handler('SimpleTestErrorHandler');
+ parent::invoke($method);
+ restore_error_handler();
+ $queue->tally();
+ }
+
+ /**
+ * Wires up the error queue for a single test.
+ * @return SimpleErrorQueue Queue connected to the test.
+ * @access private
+ */
+ protected function createErrorQueue() {
+ $context = SimpleTest::getContext();
+ $test = $this->getTestCase();
+ $queue = $context->get('SimpleErrorQueue');
+ $queue->setTestCase($test);
+ return $queue;
+ }
+}
+
+/**
+ * Error queue used to record trapped
+ * errors.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleErrorQueue {
+ private $queue;
+ private $expectation_queue;
+ private $test;
+ private $using_expect_style = false;
+
+ /**
+ * Starts with an empty queue.
+ */
+ function __construct() {
+ $this->clear();
+ }
+
+ /**
+ * Discards the contents of the error queue.
+ * @access public
+ */
+ function clear() {
+ $this->queue = array();
+ $this->expectation_queue = array();
+ }
+
+ /**
+ * Sets the currently running test case.
+ * @param SimpleTestCase $test Test case to send messages to.
+ * @access public
+ */
+ function setTestCase($test) {
+ $this->test = $test;
+ }
+
+ /**
+ * Sets up an expectation of an error. If this is
+ * not fulfilled at the end of the test, a failure
+ * will occour. If the error does happen, then this
+ * will cancel it out and send a pass message.
+ * @param SimpleExpectation $expected Expected error match.
+ * @param string $message Message to display.
+ * @access public
+ */
+ function expectError($expected, $message) {
+ array_push($this->expectation_queue, array($expected, $message));
+ }
+
+ /**
+ * Adds an error to the front of the queue.
+ * @param integer $severity PHP error code.
+ * @param string $content Text of error.
+ * @param string $filename File error occoured in.
+ * @param integer $line Line number of error.
+ * @access public
+ */
+ function add($severity, $content, $filename, $line) {
+ $content = str_replace('%', '%%', $content);
+ $this->testLatestError($severity, $content, $filename, $line);
+ }
+
+ /**
+ * Any errors still in the queue are sent to the test
+ * case. Any unfulfilled expectations trigger failures.
+ * @access public
+ */
+ function tally() {
+ while (list($severity, $message, $file, $line) = $this->extract()) {
+ $severity = $this->getSeverityAsString($severity);
+ $this->test->error($severity, $message, $file, $line);
+ }
+ while (list($expected, $message) = $this->extractExpectation()) {
+ $this->test->assert($expected, false, "%s -> Expected error not caught");
+ }
+ }
+
+ /**
+ * Tests the error against the most recent expected
+ * error.
+ * @param integer $severity PHP error code.
+ * @param string $content Text of error.
+ * @param string $filename File error occoured in.
+ * @param integer $line Line number of error.
+ * @access private
+ */
+ protected function testLatestError($severity, $content, $filename, $line) {
+ if ($expectation = $this->extractExpectation()) {
+ list($expected, $message) = $expectation;
+ $this->test->assert($expected, $content, sprintf(
+ $message,
+ "%s -> PHP error [$content] severity [" .
+ $this->getSeverityAsString($severity) .
+ "] in [$filename] line [$line]"));
+ } else {
+ $this->test->error($severity, $content, $filename, $line);
+ }
+ }
+
+ /**
+ * Pulls the earliest error from the queue.
+ * @return mixed 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;
+ }
+
+ /**
+ * Pulls the earliest expectation from the queue.
+ * @return SimpleExpectation False if none.
+ * @access private
+ */
+ protected function extractExpectation() {
+ if (count($this->expectation_queue)) {
+ return array_shift($this->expectation_queue);
+ }
+ return false;
+ }
+
+ /**
+ * Converts an error code into it's string
+ * representation.
+ * @param $severity PHP integer error code.
+ * @return String version of error code.
+ * @access public
+ */
+ static function getSeverityAsString($severity) {
+ static $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');
+ if (defined('E_RECOVERABLE_ERROR')) {
+ $map[E_RECOVERABLE_ERROR] = 'E_RECOVERABLE_ERROR';
+ }
+ if (defined('E_DEPRECATED')) {
+ $map[E_DEPRECATED] = 'E_DEPRECATED';
+ }
+ 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.
+ * @access public
+ */
+function SimpleTestErrorHandler($severity, $message, $filename = null, $line = null, $super_globals = null, $mask = null) {
+ $severity = $severity & error_reporting();
+ if ($severity) {
+ restore_error_handler();
+ if (IsNotCausedBySimpleTest($message) && IsNotTimeZoneNag($message)) {
+ if (ini_get('log_errors')) {
+ $label = SimpleErrorQueue::getSeverityAsString($severity);
+ error_log("$label: $message in $filename on line $line");
+ }
+ $queue = SimpleTest::getContext()->get('SimpleErrorQueue');
+ $queue->add($severity, $message, $filename, $line);
+ }
+ set_error_handler('SimpleTestErrorHandler');
+ }
+ return true;
+}
+
+/**
+ * Certain messages can be caused by the unit tester itself.
+ * These have to be filtered.
+ * @param string $message Message to filter.
+ * @return boolean True if genuine failure.
+ */
+function IsNotCausedBySimpleTest($message) {
+ return ! preg_match('/returned by reference/', $message);
+}
+
+/**
+ * Certain messages caused by PHP are just noise.
+ * These have to be filtered.
+ * @param string $message Message to filter.
+ * @return boolean True if genuine failure.
+ */
+function IsNotTimeZoneNag($message) {
+ return ! preg_match('/not safe to rely .* timezone settings/', $message);
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/exceptions.php b/3rdparty/simpletest/exceptions.php
new file mode 100755
index 00000000000..2f469e93a45
--- /dev/null
+++ b/3rdparty/simpletest/exceptions.php
@@ -0,0 +1,226 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: exceptions.php 1882 2009-07-01 14:30:05Z lastcraft $
+ */
+
+/**#@+
+ * Include required SimpleTest files
+ */
+require_once dirname(__FILE__) . '/invoker.php';
+require_once dirname(__FILE__) . '/expectation.php';
+/**#@-*/
+
+/**
+ * Extension that traps exceptions and turns them into
+ * an error message. PHP5 only.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleExceptionTrappingInvoker extends SimpleInvokerDecorator {
+
+ /**
+ * Stores the invoker to be wrapped.
+ * @param SimpleInvoker $invoker Test method runner.
+ */
+ function __construct($invoker) {
+ parent::__construct($invoker);
+ }
+
+ /**
+ * Invokes a test method whilst trapping expected
+ * exceptions. Any left over unthrown exceptions
+ * are then reported as failures.
+ * @param string $method Test method to call.
+ */
+ function invoke($method) {
+ $trap = SimpleTest::getContext()->get('SimpleExceptionTrap');
+ $trap->clear();
+ try {
+ $has_thrown = false;
+ parent::invoke($method);
+ } catch (Exception $exception) {
+ $has_thrown = true;
+ if (! $trap->isExpected($this->getTestCase(), $exception)) {
+ $this->getTestCase()->exception($exception);
+ }
+ $trap->clear();
+ }
+ if ($message = $trap->getOutstanding()) {
+ $this->getTestCase()->fail($message);
+ }
+ if ($has_thrown) {
+ try {
+ parent::getTestCase()->tearDown();
+ } catch (Exception $e) { }
+ }
+ }
+}
+
+/**
+ * Tests exceptions either by type or the exact
+ * exception. This could be improved to accept
+ * a pattern expectation to test the error
+ * message, but that will have to come later.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class ExceptionExpectation extends SimpleExpectation {
+ private $expected;
+
+ /**
+ * Sets up the conditions to test against.
+ * If the expected value is a string, then
+ * it will act as a test of the class name.
+ * An exception as the comparison will
+ * trigger an identical match. Writing this
+ * down now makes it look doubly dumb. I hope
+ * come up with a better scheme later.
+ * @param mixed $expected A class name or an actual
+ * exception to compare with.
+ * @param string $message Message to display.
+ */
+ function __construct($expected, $message = '%s') {
+ $this->expected = $expected;
+ parent::__construct($message);
+ }
+
+ /**
+ * Carry out the test.
+ * @param Exception $compare Value to check.
+ * @return boolean True if matched.
+ */
+ function test($compare) {
+ if (is_string($this->expected)) {
+ return ($compare instanceof $this->expected);
+ }
+ if (get_class($compare) != get_class($this->expected)) {
+ return false;
+ }
+ return $compare->getMessage() == $this->expected->getMessage();
+ }
+
+ /**
+ * Create the message to display describing the test.
+ * @param Exception $compare Exception to match.
+ * @return string Final message.
+ */
+ function testMessage($compare) {
+ if (is_string($this->expected)) {
+ return "Exception [" . $this->describeException($compare) .
+ "] should be type [" . $this->expected . "]";
+ }
+ return "Exception [" . $this->describeException($compare) .
+ "] should match [" .
+ $this->describeException($this->expected) . "]";
+ }
+
+ /**
+ * Summary of an Exception object.
+ * @param Exception $compare Exception to describe.
+ * @return string Text description.
+ */
+ protected function describeException($exception) {
+ return get_class($exception) . ": " . $exception->getMessage();
+ }
+}
+
+/**
+ * Stores expected exceptions for when they
+ * get thrown. Saves the irritating try...catch
+ * block.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleExceptionTrap {
+ private $expected;
+ private $ignored;
+ private $message;
+
+ /**
+ * Clears down the queue ready for action.
+ */
+ function __construct() {
+ $this->clear();
+ }
+
+ /**
+ * Sets up an expectation of an exception.
+ * This has the effect of intercepting an
+ * exception that matches.
+ * @param SimpleExpectation $expected Expected exception to match.
+ * @param string $message Message to display.
+ * @access public
+ */
+ function expectException($expected = false, $message = '%s') {
+ $this->expected = $this->coerceToExpectation($expected);
+ $this->message = $message;
+ }
+
+ /**
+ * Adds an exception to the ignore list. This is the list
+ * of exceptions that when thrown do not affect the test.
+ * @param SimpleExpectation $ignored Exception to skip.
+ * @access public
+ */
+ function ignoreException($ignored) {
+ $this->ignored[] = $this->coerceToExpectation($ignored);
+ }
+
+ /**
+ * Compares the expected exception with any
+ * in the queue. Issues a pass or fail and
+ * returns the state of the test.
+ * @param SimpleTestCase $test Test case to send messages to.
+ * @param Exception $exception Exception to compare.
+ * @return boolean False on no match.
+ */
+ function isExpected($test, $exception) {
+ if ($this->expected) {
+ return $test->assert($this->expected, $exception, $this->message);
+ }
+ foreach ($this->ignored as $ignored) {
+ if ($ignored->test($exception)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Turns an expected exception into a SimpleExpectation object.
+ * @param mixed $exception Exception, expectation or
+ * class name of exception.
+ * @return SimpleExpectation Expectation that will match the
+ * exception.
+ */
+ private function coerceToExpectation($exception) {
+ if ($exception === false) {
+ return new AnythingExpectation();
+ }
+ if (! SimpleExpectation::isExpectation($exception)) {
+ return new ExceptionExpectation($exception);
+ }
+ return $exception;
+ }
+
+ /**
+ * Tests for any left over exception.
+ * @return string/false The failure message or false if none.
+ */
+ function getOutstanding() {
+ return sprintf($this->message, 'Failed to trap exception');
+ }
+
+ /**
+ * Discards the contents of the error queue.
+ */
+ function clear() {
+ $this->expected = false;
+ $this->message = false;
+ $this->ignored = array();
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/expectation.php b/3rdparty/simpletest/expectation.php
new file mode 100755
index 00000000000..a480a366c5c
--- /dev/null
+++ b/3rdparty/simpletest/expectation.php
@@ -0,0 +1,984 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: expectation.php 2009 2011-04-28 08:57:25Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/dumper.php');
+require_once(dirname(__FILE__) . '/compatibility.php');
+/**#@-*/
+
+/**
+ * Assertion that can display failure information.
+ * Also includes various helper methods.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @abstract
+ */
+class SimpleExpectation {
+ protected $dumper = false;
+ private $message;
+
+ /**
+ * Creates a dumper for displaying values and sets
+ * the test message.
+ * @param string $message Customised message on failure.
+ */
+ function __construct($message = '%s') {
+ $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. An additional message can be interjected.
+ * @param mixed $compare Comparison value.
+ * @param SimpleDumper $dumper For formatting the results.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function overlayMessage($compare, $dumper) {
+ $this->dumper = $dumper;
+ return sprintf($this->message, $this->testMessage($compare));
+ }
+
+ /**
+ * Accessor for the dumper.
+ * @return SimpleDumper Current value dumper.
+ * @access protected
+ */
+ protected function getDumper() {
+ if (! $this->dumper) {
+ $dumper = new SimpleDumper();
+ return $dumper;
+ }
+ return $this->dumper;
+ }
+
+ /**
+ * Test to see if a value is an expectation object.
+ * A useful utility method.
+ * @param mixed $expectation Hopefully an Expectation
+ * class.
+ * @return boolean True if descended from
+ * this class.
+ * @access public
+ */
+ static function isExpectation($expectation) {
+ return is_object($expectation) &&
+ SimpleTestCompatibility::isA($expectation, 'SimpleExpectation');
+ }
+}
+
+/**
+ * A wildcard expectation always matches.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class AnythingExpectation extends 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 'Anything always matches [' . $dumper->describeValue($compare) . ']';
+ }
+}
+
+/**
+ * An expectation that never matches.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class FailedExpectation extends SimpleExpectation {
+
+ /**
+ * Tests the expectation. Always false.
+ * @param mixed $compare Ignored.
+ * @return boolean True.
+ * @access public
+ */
+ function test($compare) {
+ return false;
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ $dumper = $this->getDumper();
+ return 'Failed expectation never matches [' . $dumper->describeValue($compare) . ']';
+ }
+}
+
+/**
+ * An expectation that passes on boolean true.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class TrueExpectation extends SimpleExpectation {
+
+ /**
+ * Tests the expectation.
+ * @param mixed $compare Should be true.
+ * @return boolean True on match.
+ * @access public
+ */
+ function test($compare) {
+ return (boolean)$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 'Expected true, got [' . $dumper->describeValue($compare) . ']';
+ }
+}
+
+/**
+ * An expectation that passes on boolean false.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class FalseExpectation extends SimpleExpectation {
+
+ /**
+ * Tests the expectation.
+ * @param mixed $compare Should be false.
+ * @return boolean True on match.
+ * @access public
+ */
+ function test($compare) {
+ return ! (boolean)$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 'Expected false, got [' . $dumper->describeValue($compare) . ']';
+ }
+}
+
+/**
+ * Test for equality.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class EqualExpectation extends SimpleExpectation {
+ private $value;
+
+ /**
+ * Sets the value to compare against.
+ * @param mixed $value Test value to match.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function __construct($value, $message = '%s') {
+ parent::__construct($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
+ */
+ 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 __construct($value, $message = '%s') {
+ parent::__construct($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 being within a range.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class WithinMarginExpectation extends SimpleExpectation {
+ private $upper;
+ private $lower;
+
+ /**
+ * Sets the value to compare against and the fuzziness of
+ * the match. Used for comparing floating point values.
+ * @param mixed $value Test value to match.
+ * @param mixed $margin Fuzziness of match.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function __construct($value, $margin, $message = '%s') {
+ parent::__construct($message);
+ $this->upper = $value + $margin;
+ $this->lower = $value - $margin;
+ }
+
+ /**
+ * Tests the expectation. True if it matches the
+ * held value.
+ * @param mixed $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return (($compare <= $this->upper) && ($compare >= $this->lower));
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ if ($this->test($compare)) {
+ return $this->withinMessage($compare);
+ } else {
+ return $this->outsideMessage($compare);
+ }
+ }
+
+ /**
+ * Creates a the message for being within the range.
+ * @param mixed $compare Value being tested.
+ * @access private
+ */
+ protected function withinMessage($compare) {
+ return "Within expectation [" . $this->dumper->describeValue($this->lower) . "] and [" .
+ $this->dumper->describeValue($this->upper) . "]";
+ }
+
+ /**
+ * Creates a the message for being within the range.
+ * @param mixed $compare Value being tested.
+ * @access private
+ */
+ protected function outsideMessage($compare) {
+ if ($compare > $this->upper) {
+ return "Outside expectation " .
+ $this->dumper->describeDifference($compare, $this->upper);
+ } else {
+ return "Outside expectation " .
+ $this->dumper->describeDifference($compare, $this->lower);
+ }
+ }
+}
+
+/**
+ * Test for being outside of a range.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class OutsideMarginExpectation extends WithinMarginExpectation {
+
+ /**
+ * Sets the value to compare against and the fuzziness of
+ * the match. Used for comparing floating point values.
+ * @param mixed $value Test value to not match.
+ * @param mixed $margin Fuzziness of match.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function __construct($value, $margin, $message = '%s') {
+ parent::__construct($value, $margin, $message);
+ }
+
+ /**
+ * Tests the expectation. True if it matches the
+ * held value.
+ * @param mixed $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return ! parent::test($compare);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ if (! $this->test($compare)) {
+ return $this->withinMessage($compare);
+ } else {
+ return $this->outsideMessage($compare);
+ }
+ }
+}
+
+/**
+ * Test for reference.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class ReferenceExpectation {
+ private $value;
+
+ /**
+ * Sets the reference value to compare against.
+ * @param mixed $value Test reference to match.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function __construct(&$value, $message = '%s') {
+ $this->message = $message;
+ $this->value = &$value;
+ }
+
+ /**
+ * Tests the expectation. True if it exactly
+ * references the held value.
+ * @param mixed $compare Comparison reference.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test(&$compare) {
+ return SimpleTestCompatibility::isReference($this->value, $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 "Reference expectation [" . $this->dumper->describeValue($this->value) . "]";
+ } else {
+ return "Reference expectation fails " .
+ $this->dumper->describeDifference($this->value, $compare);
+ }
+ }
+
+ /**
+ * Overlays the generated message onto the stored user
+ * message. An additional message can be interjected.
+ * @param mixed $compare Comparison value.
+ * @param SimpleDumper $dumper For formatting the results.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function overlayMessage($compare, $dumper) {
+ $this->dumper = $dumper;
+ return sprintf($this->message, $this->testMessage($compare));
+ }
+
+ /**
+ * Accessor for the dumper.
+ * @return SimpleDumper Current value dumper.
+ * @access protected
+ */
+ protected function getDumper() {
+ if (! $this->dumper) {
+ $dumper = new SimpleDumper();
+ return $dumper;
+ }
+ return $this->dumper;
+ }
+}
+
+/**
+ * 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 __construct($value, $message = '%s') {
+ parent::__construct($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 __construct($value, $message = '%s') {
+ parent::__construct($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 PatternExpectation extends SimpleExpectation {
+ private $pattern;
+
+ /**
+ * Sets the value to compare against.
+ * @param string $pattern Pattern to search for.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function __construct($pattern, $message = '%s') {
+ parent::__construct($message);
+ $this->pattern = $pattern;
+ }
+
+ /**
+ * Accessor for the pattern.
+ * @return string Perl regex as string.
+ * @access protected
+ */
+ 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
+ */
+ 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 NoPatternExpectation extends PatternExpectation {
+
+ /**
+ * Sets the reject pattern
+ * @param string $pattern Pattern to search for.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function __construct($pattern, $message = '%s') {
+ parent::__construct($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 {
+ private $type;
+
+ /**
+ * Sets the type to compare with.
+ * @param string $type Type or class name.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function __construct($type, $message = '%s') {
+ parent::__construct($message);
+ $this->type = $type;
+ }
+
+ /**
+ * Accessor for type to check against.
+ * @return string Type or class name.
+ * @access protected
+ */
+ 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 {
+ $function = 'is_'.$this->canonicalType($this->type);
+ if (is_callable($function)) {
+ return $function($compare);
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Coerces type name into a is_*() match.
+ * @param string $type User type.
+ * @return string Simpler type.
+ * @access private
+ */
+ protected function canonicalType($type) {
+ $type = strtolower($type);
+ $map = array('boolean' => 'bool');
+ 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 {
+ private $type;
+
+ /**
+ * Sets the type to compare with.
+ * @param string $type Type or class name.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function __construct($type, $message = '%s') {
+ parent::__construct($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 {
+ private $method;
+
+ /**
+ * Sets the value to compare against.
+ * @param string $method Method to check.
+ * @param string $message Customised message on failure.
+ * @return void
+ */
+ function __construct($method, $message = '%s') {
+ parent::__construct($message);
+ $this->method = &$method;
+ }
+
+ /**
+ * Tests the expectation. True if the method exists in the test object.
+ * @param string $compare Comparison method name.
+ * @return boolean True if correct.
+ */
+ 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.
+ */
+ 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]";
+ }
+}
+
+/**
+ * Compares an object member's value even if private.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class MemberExpectation extends IdenticalExpectation {
+ private $name;
+
+ /**
+ * Sets the value to compare against.
+ * @param string $method Method to check.
+ * @param string $message Customised message on failure.
+ * @return void
+ */
+ function __construct($name, $expected) {
+ $this->name = $name;
+ parent::__construct($expected);
+ }
+
+ /**
+ * Tests the expectation. True if the property value is identical.
+ * @param object $actual Comparison object.
+ * @return boolean True if identical.
+ */
+ function test($actual) {
+ if (! is_object($actual)) {
+ return false;
+ }
+ return parent::test($this->getProperty($this->name, $actual));
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ */
+ function testMessage($actual) {
+ return parent::testMessage($this->getProperty($this->name, $actual));
+ }
+
+ /**
+ * Extracts the member value even if private using reflection.
+ * @param string $name Property name.
+ * @param object $object Object to read.
+ * @return mixed Value of property.
+ */
+ private function getProperty($name, $object) {
+ $reflection = new ReflectionObject($object);
+ $property = $reflection->getProperty($name);
+ if (method_exists($property, 'setAccessible')) {
+ $property->setAccessible(true);
+ }
+ try {
+ return $property->getValue($object);
+ } catch (ReflectionException $e) {
+ return $this->getPrivatePropertyNoMatterWhat($name, $object);
+ }
+ }
+
+ /**
+ * Extracts a private member's value when reflection won't play ball.
+ * @param string $name Property name.
+ * @param object $object Object to read.
+ * @return mixed Value of property.
+ */
+ private function getPrivatePropertyNoMatterWhat($name, $object) {
+ foreach ((array)$object as $mangled_name => $value) {
+ if ($this->unmangle($mangled_name) == $name) {
+ return $value;
+ }
+ }
+ }
+
+ /**
+ * Removes crud from property name after it's been converted
+ * to an array.
+ * @param string $mangled Name from array cast.
+ * @return string Cleaned up name.
+ */
+ function unmangle($mangled) {
+ $parts = preg_split('/[^a-zA-Z0-9_\x7f-\xff]+/', $mangled);
+ return array_pop($parts);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/extensions/pear_test_case.php b/3rdparty/simpletest/extensions/pear_test_case.php
new file mode 100755
index 00000000000..71657ae4cea
--- /dev/null
+++ b/3rdparty/simpletest/extensions/pear_test_case.php
@@ -0,0 +1,196 @@
+<?php
+ /**
+ * adapter for SimpleTest to use PEAR PHPUnit test cases
+ * @package SimpleTest
+ * @subpackage Extensions
+ * @version $Id: pear_test_case.php 1836 2008-12-21 00:02:26Z edwardzyang $
+ */
+
+ /**#@+
+ * include SimpleTest files
+ */
+ require_once(dirname(__FILE__) . '/../dumper.php');
+ require_once(dirname(__FILE__) . '/../compatibility.php');
+ require_once(dirname(__FILE__) . '/../test_case.php');
+ require_once(dirname(__FILE__) . '/../expectation.php');
+ /**#@-*/
+
+ /**
+ * Adapter for PEAR PHPUnit test case to allow
+ * legacy PEAR test cases to be used with SimpleTest.
+ * @package SimpleTest
+ * @subpackage Extensions
+ */
+ class PHPUnit_TestCase extends SimpleTestCase {
+ private $_loosely_typed;
+
+ /**
+ * Constructor. Sets the test name.
+ * @param $label Test name to display.
+ * @public
+ */
+ function __construct($label = false) {
+ parent::__construct($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->assert($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::assert(new TrueExpectation(), 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::assert(new TrueExpectation(), !isset($value), $message);
+ }
+
+ /**
+ * Identity test tests for the same object.
+ * @param $first First object handle.
+ * @param $second Hopefully the same handle.
+ * @param $message Message to display.
+ * @public
+ */
+ function assertSame($first, $second, $message = "%s") {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ "[" . $dumper->describeValue($first) .
+ "] and [" . $dumper->describeValue($second) .
+ "] should reference the same object");
+ return $this->assert(
+ new TrueExpectation(),
+ SimpleTestCompatibility::isReference($first, $second),
+ $message);
+ }
+
+ /**
+ * Inverted identity test.
+ * @param $first First object handle.
+ * @param $second Hopefully a different handle.
+ * @param $message Message to display.
+ * @public
+ */
+ function assertNotSame($first, $second, $message = "%s") {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ "[" . $dumper->describeValue($first) .
+ "] and [" . $dumper->describeValue($second) .
+ "] should not be the same object");
+ return $this->assert(
+ new falseExpectation(),
+ 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::assert(new TrueExpectation(), $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::assert(new FalseExpectation(), $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->assert(new PatternExpectation($pattern), $subject, $message);
+ }
+
+ /**
+ * Tests the type of a value.
+ * @param $value Value to take type of.
+ * @param $type Hoped for type.
+ * @param $message Message to display.
+ * @public
+ */
+ function assertType($value, $type, $message = "%s") {
+ parent::assert(new TrueExpectation(), 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) {
+ }
+ }
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/extensions/testdox.php b/3rdparty/simpletest/extensions/testdox.php
new file mode 100755
index 00000000000..5cf32f35162
--- /dev/null
+++ b/3rdparty/simpletest/extensions/testdox.php
@@ -0,0 +1,53 @@
+<?php
+/**
+ * Extension for a TestDox reporter
+ * @package SimpleTest
+ * @subpackage Extensions
+ * @version $Id: testdox.php 2004 2010-10-31 13:44:14Z jsweat $
+ */
+
+/**
+ * TestDox reporter
+ * @package SimpleTest
+ * @subpackage Extensions
+ */
+class TestDoxReporter extends SimpleReporter
+{
+ var $_test_case_pattern = '/^TestOf(.*)$/';
+
+ function __construct($test_case_pattern = '/^TestOf(.*)$/') {
+ parent::__construct();
+ $this->_test_case_pattern = empty($test_case_pattern) ? '/^(.*)$/' : $test_case_pattern;
+ }
+
+ function paintCaseStart($test_name) {
+ preg_match($this->_test_case_pattern, $test_name, $matches);
+ if (!empty($matches[1])) {
+ echo $matches[1] . "\n";
+ } else {
+ echo $test_name . "\n";
+ }
+ }
+
+ function paintCaseEnd($test_name) {
+ echo "\n";
+ }
+
+ function paintMethodStart($test_name) {
+ if (!preg_match('/^test(.*)$/i', $test_name, $matches)) {
+ return;
+ }
+ $test_name = $matches[1];
+ $test_name = preg_replace('/([A-Z])([A-Z])/', '$1 $2', $test_name);
+ echo '- ' . strtolower(preg_replace('/([a-zA-Z])([A-Z0-9])/', '$1 $2', $test_name));
+ }
+
+ function paintMethodEnd($test_name) {
+ echo "\n";
+ }
+
+ function paintFail($message) {
+ echo " [FAILED]";
+ }
+}
+?>
diff --git a/3rdparty/simpletest/extensions/testdox/test.php b/3rdparty/simpletest/extensions/testdox/test.php
new file mode 100755
index 00000000000..b03abe510ab
--- /dev/null
+++ b/3rdparty/simpletest/extensions/testdox/test.php
@@ -0,0 +1,107 @@
+<?php
+// $Id: test.php 1748 2008-04-14 01:50:41Z lastcraft $
+require_once dirname(__FILE__) . '/../../autorun.php';
+require_once dirname(__FILE__) . '/../testdox.php';
+
+// uncomment to see test dox in action
+//SimpleTest::prefer(new TestDoxReporter());
+
+class TestOfTestDoxReporter extends UnitTestCase
+{
+ function testIsAnInstanceOfSimpleScorerAndReporter() {
+ $dox = new TestDoxReporter();
+ $this->assertIsA($dox, 'SimpleScorer');
+ $this->assertIsA($dox, 'SimpleReporter');
+ }
+
+ function testOutputsNameOfTestCase() {
+ $dox = new TestDoxReporter();
+ ob_start();
+ $dox->paintCaseStart('TestOfTestDoxReporter');
+ $buffer = ob_get_clean();
+ $this->assertPattern('/^TestDoxReporter/', $buffer);
+ }
+
+ function testOutputOfTestCaseNameFilteredByConstructParameter() {
+ $dox = new TestDoxReporter('/^(.*)Test$/');
+ ob_start();
+ $dox->paintCaseStart('SomeGreatWidgetTest');
+ $buffer = ob_get_clean();
+ $this->assertPattern('/^SomeGreatWidget/', $buffer);
+ }
+
+ function testIfTest_case_patternIsEmptyAssumeEverythingMatches() {
+ $dox = new TestDoxReporter('');
+ ob_start();
+ $dox->paintCaseStart('TestOfTestDoxReporter');
+ $buffer = ob_get_clean();
+ $this->assertPattern('/^TestOfTestDoxReporter/', $buffer);
+ }
+
+ function testEmptyLineInsertedWhenCaseEnds() {
+ $dox = new TestDoxReporter();
+ ob_start();
+ $dox->paintCaseEnd('TestOfTestDoxReporter');
+ $buffer = ob_get_clean();
+ $this->assertEqual("\n", $buffer);
+ }
+
+ function testPaintsTestMethodInTestDoxFormat() {
+ $dox = new TestDoxReporter();
+ ob_start();
+ $dox->paintMethodStart('testSomeGreatTestCase');
+ $buffer = ob_get_clean();
+ $this->assertEqual("- some great test case", $buffer);
+ unset($buffer);
+
+ $random = rand(100, 200);
+ ob_start();
+ $dox->paintMethodStart("testRandomNumberIs{$random}");
+ $buffer = ob_get_clean();
+ $this->assertEqual("- random number is {$random}", $buffer);
+ }
+
+ function testDoesNotOutputAnythingOnNoneTestMethods() {
+ $dox = new TestDoxReporter();
+ ob_start();
+ $dox->paintMethodStart('nonMatchingMethod');
+ $buffer = ob_get_clean();
+ $this->assertEqual('', $buffer);
+ }
+
+ function testPaintMethodAddLineBreak() {
+ $dox = new TestDoxReporter();
+ ob_start();
+ $dox->paintMethodEnd('someMethod');
+ $buffer = ob_get_clean();
+ $this->assertEqual("\n", $buffer);
+ }
+
+ function testProperlySpacesSingleLettersInMethodName() {
+ $dox = new TestDoxReporter();
+ ob_start();
+ $dox->paintMethodStart('testAVerySimpleAgainAVerySimpleMethod');
+ $buffer = ob_get_clean();
+ $this->assertEqual('- a very simple again a very simple method', $buffer);
+ }
+
+ function testOnFailureThisPrintsFailureNotice() {
+ $dox = new TestDoxReporter();
+ ob_start();
+ $dox->paintFail('');
+ $buffer = ob_get_clean();
+ $this->assertEqual(' [FAILED]', $buffer);
+ }
+
+ function testWhenMatchingMethodNamesTestPrefixIsCaseInsensitive() {
+ $dox = new TestDoxReporter();
+ ob_start();
+ $dox->paintMethodStart('TESTSupportsAllUppercaseTestPrefixEvenThoughIDoNotKnowWhyYouWouldDoThat');
+ $buffer = ob_get_clean();
+ $this->assertEqual(
+ '- supports all uppercase test prefix even though i do not know why you would do that',
+ $buffer
+ );
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/form.php b/3rdparty/simpletest/form.php
new file mode 100644
index 00000000000..5e423a9df82
--- /dev/null
+++ b/3rdparty/simpletest/form.php
@@ -0,0 +1,361 @@
+<?php
+/**
+ * Base include file for SimpleTest.
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: form.php 2013 2011-04-29 09:29:45Z pp11 $
+ */
+
+/**#@+
+ * include SimpleTest files
+ */
+require_once(dirname(__FILE__) . '/tag.php');
+require_once(dirname(__FILE__) . '/encoding.php');
+require_once(dirname(__FILE__) . '/selector.php');
+/**#@-*/
+
+/**
+ * Form tag class to hold widget values.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleForm {
+ private $method;
+ private $action;
+ private $encoding;
+ private $default_target;
+ private $id;
+ private $buttons;
+ private $images;
+ private $widgets;
+ private $radios;
+ private $checkboxes;
+
+ /**
+ * Starts with no held controls/widgets.
+ * @param SimpleTag $tag Form tag to read.
+ * @param SimplePage $page Holding page.
+ */
+ function __construct($tag, $page) {
+ $this->method = $tag->getAttribute('method');
+ $this->action = $this->createAction($tag->getAttribute('action'), $page);
+ $this->encoding = $this->setEncodingClass($tag);
+ $this->default_target = false;
+ $this->id = $tag->getAttribute('id');
+ $this->buttons = array();
+ $this->images = array();
+ $this->widgets = array();
+ $this->radios = array();
+ $this->checkboxes = array();
+ }
+
+ /**
+ * Creates the request packet to be sent by the form.
+ * @param SimpleTag $tag Form tag to read.
+ * @return string Packet class.
+ * @access private
+ */
+ protected function setEncodingClass($tag) {
+ if (strtolower($tag->getAttribute('method')) == 'post') {
+ if (strtolower($tag->getAttribute('enctype')) == 'multipart/form-data') {
+ return 'SimpleMultipartEncoding';
+ }
+ return 'SimplePostEncoding';
+ }
+ return 'SimpleGetEncoding';
+ }
+
+ /**
+ * Sets the frame target within a frameset.
+ * @param string $frame Name of frame.
+ * @access public
+ */
+ function setDefaultTarget($frame) {
+ $this->default_target = $frame;
+ }
+
+ /**
+ * Accessor for method of form submission.
+ * @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.
+ */
+ protected function createAction($action, $page) {
+ if (($action === '') || ($action === false)) {
+ return $page->expandUrl($page->getUrl());
+ }
+ return $page->expandUrl(new SimpleUrl($action));;
+ }
+
+ /**
+ * Absolute URL of the target.
+ * @return SimpleUrl URL target.
+ * @access public
+ */
+ function getAction() {
+ $url = $this->action;
+ if ($this->default_target && ! $url->getTarget()) {
+ $url->setTarget($this->default_target);
+ }
+ if ($this->getMethod() == 'get') {
+ $url->clearRequest();
+ }
+ return $url;
+ }
+
+ /**
+ * Creates the encoding for the current values in the
+ * form.
+ * @return SimpleFormEncoding Request to submit.
+ * @access private
+ */
+ protected function encode() {
+ $class = $this->encoding;
+ $encoding = new $class();
+ for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
+ $this->widgets[$i]->write($encoding);
+ }
+ return $encoding;
+ }
+
+ /**
+ * ID field of form for unique identification.
+ * @return string Unique tag ID.
+ * @access public
+ */
+ function getId() {
+ return $this->id;
+ }
+
+ /**
+ * Adds a tag contents to the form.
+ * @param SimpleWidget $tag Input tag to add.
+ */
+ 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
+ */
+ protected 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
+ */
+ protected function addRadioButton($tag) {
+ if (! isset($this->radios[$tag->getName()])) {
+ $this->widgets[] = new SimpleRadioGroup();
+ $this->radios[$tag->getName()] = count($this->widgets) - 1;
+ }
+ $this->widgets[$this->radios[$tag->getName()]]->addWidget($tag);
+ }
+
+ /**
+ * Adds a checkbox, making it a group on a repeated name.
+ * @param SimpleCheckboxTag $tag Incoming form control.
+ * @access private
+ */
+ protected function addCheckbox($tag) {
+ if (! isset($this->checkboxes[$tag->getName()])) {
+ $this->widgets[] = $tag;
+ $this->checkboxes[$tag->getName()] = count($this->widgets) - 1;
+ } else {
+ $index = $this->checkboxes[$tag->getName()];
+ if (! SimpleTestCompatibility::isA($this->widgets[$index], 'SimpleCheckboxGroup')) {
+ $previous = $this->widgets[$index];
+ $this->widgets[$index] = new SimpleCheckboxGroup();
+ $this->widgets[$index]->addWidget($previous);
+ }
+ $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 getValue($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;
+ }
+
+ /**
+ * Sets a widget value within the form.
+ * @param SimpleSelector $selector Criteria to apply.
+ * @param string $value Value to input into the widget.
+ * @return boolean True if value is legal, false
+ * otherwise. If the field is not
+ * present, nothing will be set.
+ * @access public
+ */
+ function setField($selector, $value, $position=false) {
+ $success = false;
+ $_position = 0;
+ for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
+ if ($selector->isMatch($this->widgets[$i])) {
+ $_position++;
+ if ($position === false or $_position === (int)$position) {
+ if ($this->widgets[$i]->setValue($value)) {
+ $success = true;
+ }
+ }
+ }
+ }
+ return $success;
+ }
+
+ /**
+ * Used by the page object to set widgets labels to
+ * external label tags.
+ * @param SimpleSelector $selector Criteria to apply.
+ * @access public
+ */
+ function attachLabelBySelector($selector, $label) {
+ for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
+ if ($selector->isMatch($this->widgets[$i])) {
+ if (method_exists($this->widgets[$i], 'setLabel')) {
+ $this->widgets[$i]->setLabel($label);
+ return;
+ }
+ }
+ }
+ }
+
+ /**
+ * Test to see if a form has a submit button.
+ * @param SimpleSelector $selector Criteria to apply.
+ * @return boolean True if present.
+ * @access public
+ */
+ function hasSubmit($selector) {
+ foreach ($this->buttons as $button) {
+ if ($selector->isMatch($button)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Test to see if a form has an image control.
+ * @param SimpleSelector $selector Criteria to apply.
+ * @return boolean True if present.
+ * @access public
+ */
+ function hasImage($selector) {
+ foreach ($this->images as $image) {
+ if ($selector->isMatch($image)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Gets the submit values for a selected button.
+ * @param SimpleSelector $selector Criteria to apply.
+ * @param hash $additional Additional data for the form.
+ * @return SimpleEncoding Submitted values or false
+ * if there is no such button
+ * in the form.
+ * @access public
+ */
+ function submitButton($selector, $additional = false) {
+ $additional = $additional ? $additional : array();
+ foreach ($this->buttons as $button) {
+ if ($selector->isMatch($button)) {
+ $encoding = $this->encode();
+ $button->write($encoding);
+ if ($additional) {
+ $encoding->merge($additional);
+ }
+ return $encoding;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Gets the submit values for an image.
+ * @param SimpleSelector $selector Criteria to apply.
+ * @param integer $x X-coordinate of click.
+ * @param integer $y Y-coordinate of click.
+ * @param hash $additional Additional data for the form.
+ * @return SimpleEncoding Submitted values or false
+ * if there is no such button in the
+ * form.
+ * @access public
+ */
+ function submitImage($selector, $x, $y, $additional = false) {
+ $additional = $additional ? $additional : array();
+ foreach ($this->images as $image) {
+ if ($selector->isMatch($image)) {
+ $encoding = $this->encode();
+ $image->write($encoding, $x, $y);
+ if ($additional) {
+ $encoding->merge($additional);
+ }
+ return $encoding;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * 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($additional = false) {
+ $encoding = $this->encode();
+ if ($additional) {
+ $encoding->merge($additional);
+ }
+ return $encoding;
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/frames.php b/3rdparty/simpletest/frames.php
new file mode 100755
index 00000000000..d6d8e96fd0c
--- /dev/null
+++ b/3rdparty/simpletest/frames.php
@@ -0,0 +1,592 @@
+<?php
+/**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: frames.php 1784 2008-04-26 13:07:14Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/page.php');
+require_once(dirname(__FILE__) . '/user_agent.php');
+/**#@-*/
+
+/**
+ * A composite page. Wraps a frameset page and
+ * adds subframes. The original page will be
+ * mostly ignored. Implements the SimplePage
+ * interface so as to be interchangeable.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleFrameset {
+ private $frameset;
+ private $frames;
+ private $focus;
+ private $names;
+
+ /**
+ * Stashes the frameset page. Will make use of the
+ * browser to fetch the sub frames recursively.
+ * @param SimplePage $page Frameset page.
+ */
+ function __construct($page) {
+ $this->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
+ */
+ protected 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
+ */
+ protected 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;
+ }
+
+ /**
+ * Page base URL.
+ * @return SimpleUrl Current url.
+ * @access public
+ */
+ function getBaseUrl() {
+ if (is_integer($this->focus)) {
+ $url = $this->frames[$this->focus]->getBaseUrl();
+ } else {
+ $url = $this->frameset->getBaseUrl();
+ }
+ return $url;
+ }
+
+ /**
+ * Expands expandomatic URLs into fully qualified
+ * URLs for the frameset page.
+ * @param SimpleUrl $url Relative URL.
+ * @return SimpleUrl Absolute URL.
+ * @access public
+ */
+ function expandUrl($url) {
+ return $this->frameset->expandUrl($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 as strings.
+ * @access public
+ */
+ function getUrls() {
+ if (is_integer($this->focus)) {
+ return $this->frames[$this->focus]->getUrls();
+ }
+ $urls = array();
+ foreach ($this->frames as $frame) {
+ $urls = array_merge($urls, $frame->getUrls());
+ }
+ 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
+ */
+ protected 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.
+ * @param SimpleSelector $selector Button finder.
+ * @return SimpleForm Form object containing
+ * the button.
+ * @access public
+ */
+ function getFormBySubmit($selector) {
+ return $this->findForm('getFormBySubmit', $selector);
+ }
+
+ /**
+ * Finds a held form by image using a selector.
+ * Will only search correctly built forms. The first
+ * form found either within the focused frame, or
+ * across frames, will be the one returned.
+ * @param SimpleSelector $selector Image finder.
+ * @return SimpleForm Form object containing
+ * the image.
+ * @access public
+ */
+ function getFormByImage($selector) {
+ return $this->findForm('getFormByImage', $selector);
+ }
+
+ /**
+ * 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 private
+ */
+ 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;
+ }
+ }
+ $null = null;
+ return $null;
+ }
+
+ /**
+ * Finds a form in a page using a form finding method. Will
+ * also tag the form with the frame name it belongs in.
+ * @param SimplePage $page Page content of frame.
+ * @param integer $index Internal frame representation.
+ * @param string $method Method to use to find in a page.
+ * @param string $attribute Label, name or ID.
+ * @return SimpleForm Form object containing the matching ID.
+ * @access private
+ */
+ 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 SimpleSelector $selector Field finder.
+ * @param string $value Value to set field to.
+ * @return boolean True if value is valid.
+ * @access public
+ */
+ function setField($selector, $value) {
+ if (is_integer($this->focus)) {
+ $this->frames[$this->focus]->setField($selector, $value);
+ } else {
+ for ($i = 0; $i < count($this->frames); $i++) {
+ $this->frames[$i]->setField($selector, $value);
+ }
+ }
+ }
+
+ /**
+ * Accessor for a form element value within a page.
+ * @param SimpleSelector $selector Field finder.
+ * @return string/boolean A string if the field is
+ * present, false if unchecked
+ * and null if missing.
+ * @access public
+ */
+ function getField($selector) {
+ for ($i = 0; $i < count($this->frames); $i++) {
+ $value = $this->frames[$i]->getField($selector);
+ if (isset($value)) {
+ return $value;
+ }
+ }
+ return null;
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/http.php b/3rdparty/simpletest/http.php
new file mode 100644
index 00000000000..1bd74031a48
--- /dev/null
+++ b/3rdparty/simpletest/http.php
@@ -0,0 +1,628 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: http.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/socket.php');
+require_once(dirname(__FILE__) . '/cookies.php');
+require_once(dirname(__FILE__) . '/url.php');
+/**#@-*/
+
+/**
+ * Creates HTTP headers for the end point of
+ * a HTTP request.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleRoute {
+ private $url;
+
+ /**
+ * Sets the target URL.
+ * @param SimpleUrl $url URL as object.
+ * @access public
+ */
+ function __construct($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
+ */
+ 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
+ */
+ 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
+ */
+ protected function createSocket($scheme, $host, $port, $timeout) {
+ if (in_array($scheme, array('file'))) {
+ return new SimpleFileSocket($this->url);
+ } elseif (in_array($scheme, array('https'))) {
+ return new SimpleSecureSocket($host, $port, $timeout);
+ } else {
+ 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 {
+ private $proxy;
+ private $username;
+ private $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 __construct($url, $proxy, $username = false, $password = false) {
+ parent::__construct($url);
+ $this->proxy = $proxy;
+ $this->username = $username;
+ $this->password = $password;
+ }
+
+ /**
+ * Creates the first line which is the actual request.
+ * @param string $method HTTP request method, usually GET.
+ * @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()) {
+ return $socket;
+ }
+ $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 {
+ private $route;
+ private $encoding;
+ private $headers;
+ private $cookies;
+
+ /**
+ * Builds the socket request from the different pieces.
+ * These include proxy information, URL, cookies, headers,
+ * request method and choice of encoding.
+ * @param SimpleRoute $route Request route.
+ * @param SimpleFormEncoding $encoding Content to send with
+ * request.
+ * @access public
+ */
+ function __construct($route, $encoding) {
+ $this->route = $route;
+ $this->encoding = $encoding;
+ $this->headers = array();
+ $this->cookies = array();
+ }
+
+ /**
+ * Dispatches the content to the route's socket.
+ * @param integer $timeout Connection timeout.
+ * @return SimpleHttpResponse A response which may only have
+ * an error, but hopefully has a
+ * complete web page.
+ * @access public
+ */
+ function fetch($timeout) {
+ $socket = $this->route->createConnection($this->encoding->getMethod(), $timeout);
+ if (! $socket->isError()) {
+ $this->dispatchRequest($socket, $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
+ */
+ protected function dispatchRequest($socket, $encoding) {
+ foreach ($this->headers as $header_line) {
+ $socket->write($header_line . "\r\n");
+ }
+ if (count($this->cookies) > 0) {
+ $socket->write("Cookie: " . implode(";", $this->cookies) . "\r\n");
+ }
+ $encoding->writeHeadersTo($socket);
+ $socket->write("\r\n");
+ $encoding->writeTo($socket);
+ }
+
+ /**
+ * Adds a header line to the request.
+ * @param string $header_line Text of full header line.
+ * @access public
+ */
+ function addHeaderLine($header_line) {
+ $this->headers[] = $header_line;
+ }
+
+ /**
+ * Reads all the relevant cookies from the
+ * cookie jar.
+ * @param SimpleCookieJar $jar Jar to read
+ * @param SimpleUrl $url Url to use for scope.
+ * @access public
+ */
+ function readCookiesFromJar($jar, $url) {
+ $this->cookies = $jar->selectAsPairs($url);
+ }
+
+ /**
+ * Wraps the socket in a response parser.
+ * @param SimpleSocket $socket Responding socket.
+ * @return SimpleHttpResponse Parsed response object.
+ * @access protected
+ */
+ protected function createResponse($socket) {
+ $response = new SimpleHttpResponse(
+ $socket,
+ $this->route->getUrl(),
+ $this->encoding);
+ $socket->close();
+ return $response;
+ }
+}
+
+/**
+ * Collection of header lines in the response.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleHttpHeaders {
+ private $raw_headers;
+ private $response_code;
+ private $http_version;
+ private $mime_type;
+ private $location;
+ private $cookies;
+ private $authentication;
+ private $realm;
+
+ /**
+ * Parses the incoming header block.
+ * @param string $headers Header block.
+ * @access public
+ */
+ function __construct($headers) {
+ $this->raw_headers = $headers;
+ $this->response_code = false;
+ $this->http_version = false;
+ $this->mime_type = '';
+ $this->location = false;
+ $this->cookies = array();
+ $this->authentication = false;
+ $this->realm = false;
+ foreach (explode("\r\n", $headers) as $header_line) {
+ $this->parseHeaderLine($header_line);
+ }
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * Writes new cookies to the cookie jar.
+ * @param SimpleCookieJar $jar Jar to write to.
+ * @param SimpleUrl $url Host and path to write under.
+ * @access public
+ */
+ function writeCookiesToJar($jar, $url) {
+ foreach ($this->cookies as $cookie) {
+ $jar->setCookie(
+ $cookie->getName(),
+ $cookie->getValue(),
+ $url->getHost(),
+ $cookie->getPath(),
+ $cookie->getExpiry());
+ }
+ }
+
+ /**
+ * Called on each header line to accumulate the held
+ * data within the class.
+ * @param string $header_line One line of header.
+ * @access protected
+ */
+ protected function parseHeaderLine($header_line) {
+ if (preg_match('/HTTP\/(\d+\.\d+)\s+(\d+)/i', $header_line, $matches)) {
+ $this->http_version = $matches[1];
+ $this->response_code = $matches[2];
+ }
+ 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
+ */
+ protected function parseCookie($cookie_line) {
+ $parts = explode(";", $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 {
+ private $url;
+ private $encoding;
+ private $sent;
+ private $content;
+ private $headers;
+
+ /**
+ * Constructor. Reads and parses the incoming
+ * content and headers.
+ * @param SimpleSocket $socket Network connection to fetch
+ * response text from.
+ * @param SimpleUrl $url Resource name.
+ * @param mixed $encoding Record of content sent.
+ * @access public
+ */
+ function __construct($socket, $url, $encoding) {
+ parent::__construct();
+ $this->url = $url;
+ $this->encoding = $encoding;
+ $this->sent = $socket->getSent();
+ $this->content = false;
+ $raw = $this->readAll($socket);
+ if ($socket->isError()) {
+ $this->setError('Error reading socket [' . $socket->getError() . ']');
+ return;
+ }
+ $this->parse($raw);
+ }
+
+ /**
+ * Splits up the headers and the rest of the content.
+ * @param string $raw Content to parse.
+ * @access private
+ */
+ protected function parse($raw) {
+ if (! $raw) {
+ $this->setError('Nothing fetched');
+ $this->headers = new SimpleHttpHeaders('');
+ } elseif ('file' == $this->url->getScheme()) {
+ $this->headers = new SimpleHttpHeaders('');
+ $this->content = $raw;
+ } elseif (! strstr($raw, "\r\n\r\n")) {
+ $this->setError('Could not split headers from content');
+ $this->headers = new SimpleHttpHeaders($raw);
+ } else {
+ list($headers, $this->content) = explode("\r\n\r\n", $raw, 2);
+ $this->headers = new SimpleHttpHeaders($headers);
+ }
+ }
+
+ /**
+ * Original request method.
+ * @return string GET, POST or HEAD.
+ * @access public
+ */
+ function getMethod() {
+ return $this->encoding->getMethod();
+ }
+
+ /**
+ * 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->encoding;
+ }
+
+ /**
+ * 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
+ */
+ protected 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
+ */
+ protected function isLastPacket($packet) {
+ if (is_string($packet)) {
+ return $packet === '';
+ }
+ return ! $packet;
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/invoker.php b/3rdparty/simpletest/invoker.php
new file mode 100755
index 00000000000..ee310343fc7
--- /dev/null
+++ b/3rdparty/simpletest/invoker.php
@@ -0,0 +1,139 @@
+<?php
+/**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: invoker.php 1785 2008-04-26 13:56:41Z pp11 $
+ */
+
+/**#@+
+ * Includes SimpleTest files and defined the root constant
+ * for dependent libraries.
+ */
+require_once(dirname(__FILE__) . '/errors.php');
+require_once(dirname(__FILE__) . '/compatibility.php');
+require_once(dirname(__FILE__) . '/scorer.php');
+require_once(dirname(__FILE__) . '/expectation.php');
+require_once(dirname(__FILE__) . '/dumper.php');
+if (! defined('SIMPLE_TEST')) {
+ define('SIMPLE_TEST', dirname(__FILE__) . '/');
+}
+/**#@-*/
+
+/**
+ * This is called by the class runner to run a
+ * single test method. Will also run the setUp()
+ * and tearDown() methods.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleInvoker {
+ private $test_case;
+
+ /**
+ * Stashes the test case for later.
+ * @param SimpleTestCase $test_case Test case to run.
+ */
+ function __construct($test_case) {
+ $this->test_case = $test_case;
+ }
+
+ /**
+ * Accessor for test case being run.
+ * @return SimpleTestCase Test case.
+ * @access public
+ */
+ function getTestCase() {
+ return $this->test_case;
+ }
+
+ /**
+ * Runs test level set up. Used for changing
+ * the mechanics of base test cases.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function before($method) {
+ $this->test_case->before($method);
+ }
+
+ /**
+ * Invokes a test method and buffered with setUp()
+ * and tearDown() calls.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function invoke($method) {
+ $this->test_case->setUp();
+ $this->test_case->$method();
+ $this->test_case->tearDown();
+ }
+
+ /**
+ * Runs test level clean up. Used for changing
+ * the mechanics of base test cases.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function after($method) {
+ $this->test_case->after($method);
+ }
+}
+
+/**
+ * Do nothing decorator. Just passes the invocation
+ * straight through.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleInvokerDecorator {
+ private $invoker;
+
+ /**
+ * Stores the invoker to wrap.
+ * @param SimpleInvoker $invoker Test method runner.
+ */
+ function __construct($invoker) {
+ $this->invoker = $invoker;
+ }
+
+ /**
+ * Accessor for test case being run.
+ * @return SimpleTestCase Test case.
+ * @access public
+ */
+ function getTestCase() {
+ return $this->invoker->getTestCase();
+ }
+
+ /**
+ * Runs test level set up. Used for changing
+ * the mechanics of base test cases.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function before($method) {
+ $this->invoker->before($method);
+ }
+
+ /**
+ * Invokes a test method and buffered with setUp()
+ * and tearDown() calls.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function invoke($method) {
+ $this->invoker->invoke($method);
+ }
+
+ /**
+ * Runs test level clean up. Used for changing
+ * the mechanics of base test cases.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function after($method) {
+ $this->invoker->after($method);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/mock_objects.php b/3rdparty/simpletest/mock_objects.php
new file mode 100755
index 00000000000..93a827b6c02
--- /dev/null
+++ b/3rdparty/simpletest/mock_objects.php
@@ -0,0 +1,1641 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage MockObjects
+ * @version $Id: mock_objects.php 1973 2009-12-22 01:16:59Z lastcraft $
+ */
+
+/**#@+
+ * include SimpleTest files
+ */
+require_once(dirname(__FILE__) . '/expectation.php');
+require_once(dirname(__FILE__) . '/simpletest.php');
+require_once(dirname(__FILE__) . '/dumper.php');
+require_once(dirname(__FILE__) . '/reflection_php5.php');
+/**#@-*/
+
+/**
+ * Default character simpletest will substitute for any value
+ */
+if (! defined('MOCK_ANYTHING')) {
+ define('MOCK_ANYTHING', '*');
+}
+
+/**
+ * Parameter comparison assertion.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class ParametersExpectation extends SimpleExpectation {
+ private $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 string $message Customised message on failure.
+ */
+ function __construct($expected = false, $message = '%s') {
+ parent::__construct($message);
+ $this->expected = $expected;
+ }
+
+ /**
+ * Tests the assertion. True if correct.
+ * @param array $parameters Comparison values.
+ * @return boolean True if correct.
+ */
+ 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.
+ */
+ protected 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.
+ */
+ 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.
+ */
+ protected 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], $this->getDumper()) . "]";
+ }
+ }
+ 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.
+ */
+ protected function coerceToExpectation($expected) {
+ if (SimpleExpectation::isExpectation($expected)) {
+ 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.
+ */
+ protected 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.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class CallCountExpectation extends SimpleExpectation {
+ private $method;
+ private $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 __construct($method, $count, $message = '%s') {
+ $this->method = $method;
+ $this->count = $count;
+ parent::__construct($message);
+ }
+
+ /**
+ * Tests the assertion. True if correct.
+ * @param integer $compare Measured call count.
+ * @return boolean True if expected.
+ */
+ function test($compare) {
+ return ($this->count == $compare);
+ }
+
+ /**
+ * Reports the comparison.
+ * @param integer $compare Measured call count.
+ * @return string Message to show.
+ */
+ 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.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class MinimumCallCountExpectation extends SimpleExpectation {
+ private $method;
+ private $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 __construct($method, $count, $message = '%s') {
+ $this->method = $method;
+ $this->count = $count;
+ parent::__construct($message);
+ }
+
+ /**
+ * Tests the assertion. True if correct.
+ * @param integer $compare Measured call count.
+ * @return boolean True if enough.
+ */
+ function test($compare) {
+ return ($this->count <= $compare);
+ }
+
+ /**
+ * Reports the comparison.
+ * @param integer $compare Measured call count.
+ * @return string Message to show.
+ */
+ 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.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class MaximumCallCountExpectation extends SimpleExpectation {
+ private $method;
+ private $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 __construct($method, $count, $message = '%s') {
+ $this->method = $method;
+ $this->count = $count;
+ parent::__construct($message);
+ }
+
+ /**
+ * Tests the assertion. True if correct.
+ * @param integer $compare Measured call count.
+ * @return boolean True if not over.
+ */
+ function test($compare) {
+ return ($this->count >= $compare);
+ }
+
+ /**
+ * Reports the comparison.
+ * @param integer $compare Measured call count.
+ * @return string Message to show.
+ */
+ function testMessage($compare) {
+ return 'Maximum call count for [' . $this->method .
+ '] was [' . $this->count .
+ '] got [' . $compare . ']';
+ }
+}
+
+/**
+ * Retrieves method actions by searching the
+ * parameter lists until an expected match is found.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class SimpleSignatureMap {
+ private $map;
+
+ /**
+ * Creates an empty call map.
+ */
+ function __construct() {
+ $this->map = array();
+ }
+
+ /**
+ * Stashes a reference against a method call.
+ * @param array $parameters Array of arguments (including wildcards).
+ * @param mixed $action Reference placed in the map.
+ */
+ function add($parameters, $action) {
+ $place = count($this->map);
+ $this->map[$place] = array();
+ $this->map[$place]['params'] = new ParametersExpectation($parameters);
+ $this->map[$place]['content'] = $action;
+ }
+
+ /**
+ * 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.
+ */
+ function &findFirstAction($parameters) {
+ $slot = $this->findFirstSlot($parameters);
+ if (isset($slot) && isset($slot['content'])) {
+ return $slot['content'];
+ }
+ $null = null;
+ return $null;
+ }
+
+ /**
+ * 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.
+ */
+ function isMatch($parameters) {
+ return ($this->findFirstSlot($parameters) != null);
+ }
+
+ /**
+ * Compares the incoming parameters with the
+ * internal expectation. Uses the incoming $test
+ * to dispatch the test message.
+ * @param SimpleTestCase $test Test to dispatch to.
+ * @param array $parameters The actual calling arguments.
+ * @param string $message The message to overlay.
+ */
+ function test($test, $parameters, $message) {
+ }
+
+ /**
+ * Searches the map for a matching item.
+ * @param array $parameters Parameters to search by
+ * without wildcards.
+ * @return array Reference to slot or null.
+ */
+ function &findFirstSlot($parameters) {
+ $count = count($this->map);
+ for ($i = 0; $i < $count; $i++) {
+ if ($this->map[$i]["params"]->test($parameters)) {
+ return $this->map[$i];
+ }
+ }
+ $null = null;
+ return $null;
+ }
+}
+
+/**
+ * Allows setting of actions against call signatures either
+ * at a specific time, or always. Specific time settings
+ * trump lasting ones, otherwise the most recently added
+ * will mask an earlier match.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class SimpleCallSchedule {
+ private $wildcard = MOCK_ANYTHING;
+ private $always;
+ private $at;
+
+ /**
+ * Sets up an empty response schedule.
+ * Creates an empty call map.
+ */
+ function __construct() {
+ $this->always = array();
+ $this->at = array();
+ }
+
+ /**
+ * Stores an action against a signature that
+ * will always fire unless masked by a time
+ * specific one.
+ * @param string $method Method name.
+ * @param array $args Calling parameters.
+ * @param SimpleAction $action Actually simpleByValue, etc.
+ */
+ function register($method, $args, $action) {
+ $args = $this->replaceWildcards($args);
+ $method = strtolower($method);
+ if (! isset($this->always[$method])) {
+ $this->always[$method] = new SimpleSignatureMap();
+ }
+ $this->always[$method]->add($args, $action);
+ }
+
+ /**
+ * Stores an action against a signature that
+ * will fire at a specific time in the future.
+ * @param integer $step delay of calls to this method,
+ * 0 is next.
+ * @param string $method Method name.
+ * @param array $args Calling parameters.
+ * @param SimpleAction $action Actually SimpleByValue, etc.
+ */
+ function registerAt($step, $method, $args, $action) {
+ $args = $this->replaceWildcards($args);
+ $method = strtolower($method);
+ if (! isset($this->at[$method])) {
+ $this->at[$method] = array();
+ }
+ if (! isset($this->at[$method][$step])) {
+ $this->at[$method][$step] = new SimpleSignatureMap();
+ }
+ $this->at[$method][$step]->add($args, $action);
+ }
+
+ /**
+ * Sets up an expectation on the argument list.
+ * @param string $method Method to test.
+ * @param array $args Bare arguments or list of
+ * expectation objects.
+ * @param string $message Failure message.
+ */
+ function expectArguments($method, $args, $message) {
+ $args = $this->replaceWildcards($args);
+ $message .= Mock::getExpectationLine();
+ $this->expected_args[strtolower($method)] =
+ new ParametersExpectation($args, $message);
+
+ }
+
+ /**
+ * Actually carry out the action stored previously,
+ * if the parameters match.
+ * @param integer $step Time of call.
+ * @param string $method Method name.
+ * @param array $args The parameters making up the
+ * rest of the call.
+ * @return mixed The result of the action.
+ */
+ function &respond($step, $method, $args) {
+ $method = strtolower($method);
+ if (isset($this->at[$method][$step])) {
+ if ($this->at[$method][$step]->isMatch($args)) {
+ $action = $this->at[$method][$step]->findFirstAction($args);
+ if (isset($action)) {
+ return $action->act();
+ }
+ }
+ }
+ if (isset($this->always[$method])) {
+ $action = $this->always[$method]->findFirstAction($args);
+ if (isset($action)) {
+ return $action->act();
+ }
+ }
+ $null = null;
+ return $null;
+ }
+
+ /**
+ * Replaces wildcard matches with wildcard
+ * expectations in the argument list.
+ * @param array $args Raw argument list.
+ * @return array Argument list with
+ * expectations.
+ */
+ protected function replaceWildcards($args) {
+ if ($args === false) {
+ return false;
+ }
+ for ($i = 0; $i < count($args); $i++) {
+ if ($args[$i] === $this->wildcard) {
+ $args[$i] = new AnythingExpectation();
+ }
+ }
+ return $args;
+ }
+}
+
+/**
+ * A type of SimpleMethodAction.
+ * Stashes a value for returning later. Follows usual
+ * PHP5 semantics of objects being returned by reference.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class SimpleReturn {
+ private $value;
+
+ /**
+ * Stashes it for later.
+ * @param mixed $value You need to clone objects
+ * if you want copy semantics
+ * for these.
+ */
+ function __construct($value) {
+ $this->value = $value;
+ }
+
+ /**
+ * Returns the value stored earlier.
+ * @return mixed Whatever was stashed.
+ */
+ function act() {
+ return $this->value;
+ }
+}
+
+/**
+ * A type of SimpleMethodAction.
+ * Stashes a reference for returning later.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class SimpleByReference {
+ private $reference;
+
+ /**
+ * Stashes it for later.
+ * @param mixed $reference Actual PHP4 style reference.
+ */
+ function __construct(&$reference) {
+ $this->reference = &$reference;
+ }
+
+ /**
+ * Returns the reference stored earlier.
+ * @return mixed Whatever was stashed.
+ */
+ function &act() {
+ return $this->reference;
+ }
+}
+
+/**
+ * A type of SimpleMethodAction.
+ * Stashes a value for returning later.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class SimpleByValue {
+ private $value;
+
+ /**
+ * Stashes it for later.
+ * @param mixed $value You need to clone objects
+ * if you want copy semantics
+ * for these.
+ */
+ function __construct($value) {
+ $this->value = $value;
+ }
+
+ /**
+ * Returns the value stored earlier.
+ * @return mixed Whatever was stashed.
+ */
+ function &act() {
+ $dummy = $this->value;
+ return $dummy;
+ }
+}
+
+/**
+ * A type of SimpleMethodAction.
+ * Stashes an exception for throwing later.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class SimpleThrower {
+ private $exception;
+
+ /**
+ * Stashes it for later.
+ * @param Exception $exception The exception object to throw.
+ */
+ function __construct($exception) {
+ $this->exception = $exception;
+ }
+
+ /**
+ * Throws the exceptins stashed earlier.
+ */
+ function act() {
+ throw $this->exception;
+ }
+}
+
+/**
+ * A type of SimpleMethodAction.
+ * Stashes an error for emitting later.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class SimpleErrorThrower {
+ private $error;
+ private $severity;
+
+ /**
+ * Stashes an error to throw later.
+ * @param string $error Error message.
+ * @param integer $severity PHP error constant, e.g E_USER_ERROR.
+ */
+ function __construct($error, $severity) {
+ $this->error = $error;
+ $this->severity = $severity;
+ }
+
+ /**
+ * Triggers the stashed error.
+ */
+ function &act() {
+ trigger_error($this->error, $this->severity);
+ $null = null;
+ return $null;
+ }
+}
+
+/**
+ * A base class or delegate that extends 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 or returning
+ * preprogrammed responses.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class SimpleMock {
+ private $actions;
+ private $expectations;
+ private $wildcard = MOCK_ANYTHING;
+ private $is_strict = true;
+ private $call_counts;
+ private $expected_counts;
+ private $max_counts;
+ private $expected_args;
+ private $expected_args_at;
+
+ /**
+ * Creates an empty action list and expectation list.
+ * All call counts are set to zero.
+ */
+ function SimpleMock() {
+ $this->actions = new SimpleCallSchedule();
+ $this->expectations = new SimpleCallSchedule();
+ $this->call_counts = array();
+ $this->expected_counts = array();
+ $this->max_counts = array();
+ $this->expected_args = array();
+ $this->expected_args_at = array();
+ $this->getCurrentTestCase()->tell($this);
+ }
+
+ /**
+ * Disables a name check when setting expectations.
+ * This hack is needed for the partial mocks.
+ */
+ function disableExpectationNameChecks() {
+ $this->is_strict = false;
+ }
+
+ /**
+ * Finds currently running test.
+ * @return SimpeTestCase Current test case.
+ */
+ protected function getCurrentTestCase() {
+ return SimpleTest::getContext()->getTest();
+ }
+
+ /**
+ * 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
+ */
+ protected function checkArgumentsIsArray($args, $task) {
+ if (! is_array($args)) {
+ trigger_error(
+ "Cannot $task as \$args parameter is not an array",
+ E_USER_ERROR);
+ }
+ }
+
+ /**
+ * 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.
+ */
+ 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);
+ }
+ }
+
+ /**
+ * Replaces wildcard matches with wildcard
+ * expectations in the argument list.
+ * @param array $args Raw argument list.
+ * @return array Argument list with
+ * expectations.
+ */
+ function replaceWildcards($args) {
+ if ($args === false) {
+ return false;
+ }
+ for ($i = 0; $i < count($args); $i++) {
+ if ($args[$i] === $this->wildcard) {
+ $args[$i] = new AnythingExpectation();
+ }
+ }
+ return $args;
+ }
+
+ /**
+ * Adds one to the call count of a method.
+ * @param string $method Method called.
+ * @param array $args Arguments as an array.
+ */
+ 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 integer Number of calls so far.
+ */
+ 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 on by all calls to this method that match.
+ * @param string $method Method name.
+ * @param mixed $value Result of call by value/handle.
+ * @param array $args List of parameters to match
+ * including wildcards.
+ */
+ function returns($method, $value, $args = false) {
+ $this->dieOnNoMethod($method, "set return");
+ $this->actions->register($method, $args, new SimpleReturn($value));
+ }
+
+ /**
+ * Sets a return for a parameter list that will
+ * be passed 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.
+ * @param array $args List of parameters to match
+ * including wildcards.
+ */
+ function returnsAt($timing, $method, $value, $args = false) {
+ $this->dieOnNoMethod($method, "set return value sequence");
+ $this->actions->registerAt($timing, $method, $args, new SimpleReturn($value));
+ }
+
+ /**
+ * 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.
+ */
+ function returnsByValue($method, $value, $args = false) {
+ $this->dieOnNoMethod($method, "set return value");
+ $this->actions->register($method, $args, new SimpleByValue($value));
+ }
+
+ /** @deprecated */
+ function setReturnValue($method, $value, $args = false) {
+ $this->returnsByValue($method, $value, $args);
+ }
+
+ /**
+ * 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.
+ */
+ function returnsByValueAt($timing, $method, $value, $args = false) {
+ $this->dieOnNoMethod($method, "set return value sequence");
+ $this->actions->registerAt($timing, $method, $args, new SimpleByValue($value));
+ }
+
+ /** @deprecated */
+ function setReturnValueAt($timing, $method, $value, $args = false) {
+ $this->returnsByValueAt($timing, $method, $value, $args);
+ }
+
+ /**
+ * 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.
+ */
+ function returnsByReference($method, &$reference, $args = false) {
+ $this->dieOnNoMethod($method, "set return reference");
+ $this->actions->register($method, $args, new SimpleByReference($reference));
+ }
+
+ /** @deprecated */
+ function setReturnReference($method, &$reference, $args = false) {
+ $this->returnsByReference($method, $reference, $args);
+ }
+
+ /**
+ * 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.
+ */
+ function returnsByReferenceAt($timing, $method, &$reference, $args = false) {
+ $this->dieOnNoMethod($method, "set return reference sequence");
+ $this->actions->registerAt($timing, $method, $args, new SimpleByReference($reference));
+ }
+
+ /** @deprecated */
+ function setReturnReferenceAt($timing, $method, &$reference, $args = false) {
+ $this->returnsByReferenceAt($timing, $method, $reference, $args);
+ }
+
+ /**
+ * 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.
+ */
+ function expect($method, $args, $message = '%s') {
+ $this->dieOnNoMethod($method, 'set expected arguments');
+ $this->checkArgumentsIsArray($args, 'set expected arguments');
+ $this->expectations->expectArguments($method, $args, $message);
+ $args = $this->replaceWildcards($args);
+ $message .= Mock::getExpectationLine();
+ $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.
+ */
+ function expectAt($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();
+ $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.
+ */
+ function expectCallCount($method, $count, $message = '%s') {
+ $this->dieOnNoMethod($method, 'set expected call count');
+ $message .= Mock::getExpectationLine();
+ $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.
+ */
+ function expectMaximumCallCount($method, $count, $message = '%s') {
+ $this->dieOnNoMethod($method, 'set maximum call count');
+ $message .= Mock::getExpectationLine();
+ $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.
+ */
+ function expectMinimumCallCount($method, $count, $message = '%s') {
+ $this->dieOnNoMethod($method, 'set minimum call count');
+ $message .= Mock::getExpectationLine();
+ $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.
+ */
+ 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.
+ */
+ function expectOnce($method, $args = false, $message = '%s') {
+ $this->expectCallCount($method, 1, $message);
+ if ($args !== false) {
+ $this->expect($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.
+ */
+ function expectAtLeastOnce($method, $args = false, $message = '%s') {
+ $this->expectMinimumCallCount($method, 1, $message);
+ if ($args !== false) {
+ $this->expect($method, $args, $message);
+ }
+ }
+
+ /**
+ * Sets up a trigger to throw an exception upon the
+ * method call.
+ * @param string $method Method name to throw on.
+ * @param object $exception Exception object to throw.
+ * If not given then a simple
+ * Exception object is thrown.
+ * @param array $args Optional argument list filter.
+ * If given then the exception
+ * will only be thrown if the
+ * method call matches the arguments.
+ */
+ function throwOn($method, $exception = false, $args = false) {
+ $this->dieOnNoMethod($method, "throw on");
+ $this->actions->register($method, $args,
+ new SimpleThrower($exception ? $exception : new Exception()));
+ }
+
+ /**
+ * Sets up a trigger to throw an exception upon the
+ * method call.
+ * @param integer $timing When to throw the exception. A
+ * value of 0 throws immediately.
+ * A value of 1 actually allows one call
+ * to this method before throwing. 2
+ * will allow two calls before throwing
+ * and so on.
+ * @param string $method Method name to throw on.
+ * @param object $exception Exception object to throw.
+ * If not given then a simple
+ * Exception object is thrown.
+ * @param array $args Optional argument list filter.
+ * If given then the exception
+ * will only be thrown if the
+ * method call matches the arguments.
+ */
+ function throwAt($timing, $method, $exception = false, $args = false) {
+ $this->dieOnNoMethod($method, "throw at");
+ $this->actions->registerAt($timing, $method, $args,
+ new SimpleThrower($exception ? $exception : new Exception()));
+ }
+
+ /**
+ * Sets up a trigger to throw an error upon the
+ * method call.
+ * @param string $method Method name to throw on.
+ * @param object $error Error message to trigger.
+ * @param array $args Optional argument list filter.
+ * If given then the exception
+ * will only be thrown if the
+ * method call matches the arguments.
+ * @param integer $severity The PHP severity level. Defaults
+ * to E_USER_ERROR.
+ */
+ function errorOn($method, $error = 'A mock error', $args = false, $severity = E_USER_ERROR) {
+ $this->dieOnNoMethod($method, "error on");
+ $this->actions->register($method, $args, new SimpleErrorThrower($error, $severity));
+ }
+
+ /**
+ * Sets up a trigger to throw an error upon a specific
+ * method call.
+ * @param integer $timing When to throw the exception. A
+ * value of 0 throws immediately.
+ * A value of 1 actually allows one call
+ * to this method before throwing. 2
+ * will allow two calls before throwing
+ * and so on.
+ * @param string $method Method name to throw on.
+ * @param object $error Error message to trigger.
+ * @param array $args Optional argument list filter.
+ * If given then the exception
+ * will only be thrown if the
+ * method call matches the arguments.
+ * @param integer $severity The PHP severity level. Defaults
+ * to E_USER_ERROR.
+ */
+ function errorAt($timing, $method, $error = 'A mock error', $args = false, $severity = E_USER_ERROR) {
+ $this->dieOnNoMethod($method, "error at");
+ $this->actions->registerAt($timing, $method, $args, new SimpleErrorThrower($error, $severity));
+ }
+
+ /**
+ * Receives event from unit test that the current
+ * test method has finished. Totals up the call
+ * counts and triggers a test assertion if a test
+ * is present for expected call counts.
+ * @param string $test_method Current method name.
+ * @param SimpleTestCase $test Test to send message to.
+ */
+ function atTestEnd($test_method, &$test) {
+ foreach ($this->expected_counts as $method => $expectation) {
+ $test->assert($expectation, $this->getCallCount($method));
+ }
+ foreach ($this->max_counts as $method => $expectation) {
+ if ($expectation->test($this->getCallCount($method))) {
+ $test->assert($expectation, $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.
+ */
+ function &invoke($method, $args) {
+ $method = strtolower($method);
+ $step = $this->getCallCount($method);
+ $this->addCall($method, $args);
+ $this->checkExpectations($method, $args, $step);
+ $was = $this->disableEStrict();
+ try {
+ $result = &$this->emulateCall($method, $args, $step);
+ } catch (Exception $e) {
+ $this->restoreEStrict($was);
+ throw $e;
+ }
+ $this->restoreEStrict($was);
+ return $result;
+ }
+
+ /**
+ * 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 or other action.
+ */
+ protected function &emulateCall($method, $args, $step) {
+ return $this->actions->respond($step, $method, $args);
+ }
+
+ /**
+ * 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.
+ */
+ protected function checkExpectations($method, $args, $timing) {
+ $test = $this->getCurrentTestCase();
+ if (isset($this->max_counts[$method])) {
+ if (! $this->max_counts[$method]->test($timing + 1)) {
+ $test->assert($this->max_counts[$method], $timing + 1);
+ }
+ }
+ if (isset($this->expected_args_at[$timing][$method])) {
+ $test->assert(
+ $this->expected_args_at[$timing][$method],
+ $args,
+ "Mock method [$method] at [$timing] -> %s");
+ } elseif (isset($this->expected_args[$method])) {
+ $test->assert(
+ $this->expected_args[$method],
+ $args,
+ "Mock method [$method] -> %s");
+ }
+ }
+
+ /**
+ * Our mock has to be able to return anything, including
+ * variable references. To allow for these mixed returns
+ * we have to disable the E_STRICT warnings while the
+ * method calls are emulated.
+ */
+ private function disableEStrict() {
+ $was = error_reporting();
+ error_reporting($was & ~E_STRICT);
+ return $was;
+ }
+
+ /**
+ * Restores the E_STRICT level if it was previously set.
+ * @param integer $was Previous error reporting level.
+ */
+ private function restoreEStrict($was) {
+ error_reporting($was);
+ }
+}
+
+/**
+ * Static methods only service class for code generation of
+ * mock objects.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class Mock {
+
+ /**
+ * Factory for mock object classes.
+ */
+ function __construct() {
+ trigger_error('Mock factory methods are static.');
+ }
+
+ /**
+ * 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 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.sta
+ */
+ static function generate($class, $mock_class = false, $methods = false) {
+ $generator = new MockGenerator($class, $mock_class);
+ return @$generator->generateSubclass($methods);
+ }
+
+ /**
+ * 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 function generatePartial($class, $mock_class, $methods) {
+ $generator = new MockGenerator($class, $mock_class);
+ return @$generator->generatePartial($methods);
+ }
+
+ /**
+ * Uses a stack trace to find the line of an assertion.
+ */
+ static function getExpectationLine() {
+ $trace = new SimpleStackTrace(array('expect'));
+ return $trace->traceMethod();
+ }
+}
+
+/**
+ * Service class for code generation of mock objects.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+class MockGenerator {
+ private $class;
+ private $mock_class;
+ private $mock_base;
+ private $reflection;
+
+ /**
+ * Builds initial reflection object.
+ * @param string $class Class to be mocked.
+ * @param string $mock_class New class with identical interface,
+ * but no behaviour.
+ */
+ function __construct($class, $mock_class) {
+ $this->class = $class;
+ $this->mock_class = $mock_class;
+ if (! $this->mock_class) {
+ $this->mock_class = 'Mock' . $this->class;
+ }
+ $this->mock_base = SimpleTest::getMockBaseClass();
+ $this->reflection = new SimpleReflection($this->class);
+ }
+
+ /**
+ * Clones a class' interface and creates a mock version
+ * that can have return values and expectations set.
+ * @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.
+ */
+ function generate($methods) {
+ if (! $this->reflection->classOrInterfaceExists()) {
+ return false;
+ }
+ $mock_reflection = new SimpleReflection($this->mock_class);
+ if ($mock_reflection->classExistsSansAutoload()) {
+ return false;
+ }
+ $code = $this->createClassCode($methods ? $methods : array());
+ return eval("$code return \$code;");
+ }
+
+ /**
+ * Subclasses a class and overrides every method with a mock one
+ * that can have return values and expectations set. Chains
+ * to an aggregated SimpleMock.
+ * @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.
+ */
+ function generateSubclass($methods) {
+ if (! $this->reflection->classOrInterfaceExists()) {
+ return false;
+ }
+ $mock_reflection = new SimpleReflection($this->mock_class);
+ if ($mock_reflection->classExistsSansAutoload()) {
+ return false;
+ }
+ if ($this->reflection->isInterface() || $this->reflection->hasFinal()) {
+ $code = $this->createClassCode($methods ? $methods : array());
+ return eval("$code return \$code;");
+ } else {
+ $code = $this->createSubclassCode($methods ? $methods : array());
+ return eval("$code return \$code;");
+ }
+ }
+
+ /**
+ * 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 array $methods Methods to be overridden
+ * with mock versions.
+ */
+ function generatePartial($methods) {
+ if (! $this->reflection->classExists($this->class)) {
+ return false;
+ }
+ $mock_reflection = new SimpleReflection($this->mock_class);
+ if ($mock_reflection->classExistsSansAutoload()) {
+ trigger_error('Partial mock class [' . $this->mock_class . '] already exists');
+ return false;
+ }
+ $code = $this->extendClassCode($methods);
+ return eval("$code return \$code;");
+ }
+
+ /**
+ * The new mock class code as a string.
+ * @param array $methods Additional methods.
+ * @return string Code for new mock class.
+ */
+ protected function createClassCode($methods) {
+ $implements = '';
+ $interfaces = $this->reflection->getInterfaces();
+ if (function_exists('spl_classes')) {
+ $interfaces = array_diff($interfaces, array('Traversable'));
+ }
+ if (count($interfaces) > 0) {
+ $implements = 'implements ' . implode(', ', $interfaces);
+ }
+ $code = "class " . $this->mock_class . " extends " . $this->mock_base . " $implements {\n";
+ $code .= " function " . $this->mock_class . "() {\n";
+ $code .= " \$this->" . $this->mock_base . "();\n";
+ $code .= " }\n";
+ if (in_array('__construct', $this->reflection->getMethods())) {
+ $code .= " function __construct() {\n";
+ $code .= " \$this->" . $this->mock_base . "();\n";
+ $code .= " }\n";
+ }
+ $code .= $this->createHandlerCode($methods);
+ $code .= "}\n";
+ return $code;
+ }
+
+ /**
+ * The new mock class code as a string. The mock will
+ * be a subclass of the original mocked class.
+ * @param array $methods Additional methods.
+ * @return string Code for new mock class.
+ */
+ protected function createSubclassCode($methods) {
+ $code = "class " . $this->mock_class . " extends " . $this->class . " {\n";
+ $code .= " public \$mock;\n";
+ $code .= $this->addMethodList(array_merge($methods, $this->reflection->getMethods()));
+ $code .= "\n";
+ $code .= " function " . $this->mock_class . "() {\n";
+ $code .= " \$this->mock = new " . $this->mock_base . "();\n";
+ $code .= " \$this->mock->disableExpectationNameChecks();\n";
+ $code .= " }\n";
+ $code .= $this->chainMockReturns();
+ $code .= $this->chainMockExpectations();
+ $code .= $this->chainThrowMethods();
+ $code .= $this->overrideMethods($this->reflection->getMethods());
+ $code .= $this->createNewMethodCode($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 array $methods Mocked methods.
+ * @return string Code for a new class.
+ */
+ protected function extendClassCode($methods) {
+ $code = "class " . $this->mock_class . " extends " . $this->class . " {\n";
+ $code .= " protected \$mock;\n";
+ $code .= $this->addMethodList($methods);
+ $code .= "\n";
+ $code .= " function " . $this->mock_class . "() {\n";
+ $code .= " \$this->mock = new " . $this->mock_base . "();\n";
+ $code .= " \$this->mock->disableExpectationNameChecks();\n";
+ $code .= " }\n";
+ $code .= $this->chainMockReturns();
+ $code .= $this->chainMockExpectations();
+ $code .= $this->chainThrowMethods();
+ $code .= $this->overrideMethods($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 array $methods Additional methods.
+ */
+ protected function createHandlerCode($methods) {
+ $code = '';
+ $methods = array_merge($methods, $this->reflection->getMethods());
+ foreach ($methods as $method) {
+ if ($this->isConstructor($method)) {
+ continue;
+ }
+ $mock_reflection = new SimpleReflection($this->mock_base);
+ if (in_array($method, $mock_reflection->getMethods())) {
+ continue;
+ }
+ $code .= " " . $this->reflection->getSignature($method) . " {\n";
+ $code .= " \$args = func_get_args();\n";
+ $code .= " \$result = &\$this->invoke(\"$method\", \$args);\n";
+ $code .= " return \$result;\n";
+ $code .= " }\n";
+ }
+ return $code;
+ }
+
+ /**
+ * Creates code within a class to generate a new
+ * methods. All methods call the invoke() handler
+ * on the internal mock with the method name and
+ * the arguments in an array.
+ * @param array $methods Additional methods.
+ */
+ protected function createNewMethodCode($methods) {
+ $code = '';
+ foreach ($methods as $method) {
+ if ($this->isConstructor($method)) {
+ continue;
+ }
+ $mock_reflection = new SimpleReflection($this->mock_base);
+ if (in_array($method, $mock_reflection->getMethods())) {
+ continue;
+ }
+ $code .= " " . $this->reflection->getSignature($method) . " {\n";
+ $code .= " \$args = func_get_args();\n";
+ $code .= " \$result = &\$this->mock->invoke(\"$method\", \$args);\n";
+ $code .= " return \$result;\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.
+ */
+ protected function isConstructor($method) {
+ return in_array(
+ strtolower($method),
+ array('__construct', '__destruct'));
+ }
+
+ /**
+ * Creates a list of mocked methods for error checking.
+ * @param array $methods Mocked methods.
+ * @return string Code for a method list.
+ */
+ protected function addMethodList($methods) {
+ return " protected \$mocked_methods = array('" .
+ implode("', '", array_map('strtolower', $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.
+ */
+ protected function bailOutIfNotMocked($alias) {
+ $code = " if (! in_array(strtolower($alias), \$this->mocked_methods)) {\n";
+ $code .= " trigger_error(\"Method [$alias] is not mocked\");\n";
+ $code .= " \$null = null;\n";
+ $code .= " return \$null;\n";
+ $code .= " }\n";
+ return $code;
+ }
+
+ /**
+ * Creates source code for chaining to the composited
+ * mock object.
+ * @return string Code for mock set up.
+ */
+ protected function chainMockReturns() {
+ $code = " function returns(\$method, \$value, \$args = false) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->returns(\$method, \$value, \$args);\n";
+ $code .= " }\n";
+ $code .= " function returnsAt(\$timing, \$method, \$value, \$args = false) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->returnsAt(\$timing, \$method, \$value, \$args);\n";
+ $code .= " }\n";
+ $code .= " function returnsByValue(\$method, \$value, \$args = false) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->setReturnValue(\$method, \$value, \$args);\n";
+ $code .= " }\n";
+ $code .= " function returnsByValueAt(\$timing, \$method, \$value, \$args = false) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n";
+ $code .= " }\n";
+ $code .= " function returnsByReference(\$method, &\$ref, \$args = false) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->setReturnReference(\$method, \$ref, \$args);\n";
+ $code .= " }\n";
+ $code .= " function returnsByReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->setReturnReferenceAt(\$timing, \$method, \$ref, \$args);\n";
+ $code .= " }\n";
+ $code .= " function setReturnValue(\$method, \$value, \$args = false) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->setReturnValue(\$method, \$value, \$args);\n";
+ $code .= " }\n";
+ $code .= " function setReturnValueAt(\$timing, \$method, \$value, \$args = false) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n";
+ $code .= " }\n";
+ $code .= " function setReturnReference(\$method, &\$ref, \$args = false) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->setReturnReference(\$method, \$ref, \$args);\n";
+ $code .= " }\n";
+ $code .= " function setReturnReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n";
+ $code .= $this->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.
+ */
+ protected function chainMockExpectations() {
+ $code = " function expect(\$method, \$args = false, \$msg = '%s') {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->expect(\$method, \$args, \$msg);\n";
+ $code .= " }\n";
+ $code .= " function expectAt(\$timing, \$method, \$args = false, \$msg = '%s') {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->expectAt(\$timing, \$method, \$args, \$msg);\n";
+ $code .= " }\n";
+ $code .= " function expectCallCount(\$method, \$count) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->expectCallCount(\$method, \$count, \$msg = '%s');\n";
+ $code .= " }\n";
+ $code .= " function expectMaximumCallCount(\$method, \$count, \$msg = '%s') {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->expectMaximumCallCount(\$method, \$count, \$msg = '%s');\n";
+ $code .= " }\n";
+ $code .= " function expectMinimumCallCount(\$method, \$count, \$msg = '%s') {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->expectMinimumCallCount(\$method, \$count, \$msg = '%s');\n";
+ $code .= " }\n";
+ $code .= " function expectNever(\$method) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->expectNever(\$method);\n";
+ $code .= " }\n";
+ $code .= " function expectOnce(\$method, \$args = false, \$msg = '%s') {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->expectOnce(\$method, \$args, \$msg);\n";
+ $code .= " }\n";
+ $code .= " function expectAtLeastOnce(\$method, \$args = false, \$msg = '%s') {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->expectAtLeastOnce(\$method, \$args, \$msg);\n";
+ $code .= " }\n";
+ return $code;
+ }
+
+ /**
+ * Adds code for chaining the throw methods.
+ * @return string Code for chains.
+ */
+ protected function chainThrowMethods() {
+ $code = " function throwOn(\$method, \$exception = false, \$args = false) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->throwOn(\$method, \$exception, \$args);\n";
+ $code .= " }\n";
+ $code .= " function throwAt(\$timing, \$method, \$exception = false, \$args = false) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->throwAt(\$timing, \$method, \$exception, \$args);\n";
+ $code .= " }\n";
+ $code .= " function errorOn(\$method, \$error = 'A mock error', \$args = false, \$severity = E_USER_ERROR) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->errorOn(\$method, \$error, \$args, \$severity);\n";
+ $code .= " }\n";
+ $code .= " function errorAt(\$timing, \$method, \$error = 'A mock error', \$args = false, \$severity = E_USER_ERROR) {\n";
+ $code .= $this->bailOutIfNotMocked("\$method");
+ $code .= " \$this->mock->errorAt(\$timing, \$method, \$error, \$args, \$severity);\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.
+ */
+ protected function overrideMethods($methods) {
+ $code = "";
+ foreach ($methods as $method) {
+ if ($this->isConstructor($method)) {
+ continue;
+ }
+ $code .= " " . $this->reflection->getSignature($method) . " {\n";
+ $code .= " \$args = func_get_args();\n";
+ $code .= " \$result = &\$this->mock->invoke(\"$method\", \$args);\n";
+ $code .= " return \$result;\n";
+ $code .= " }\n";
+ }
+ return $code;
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/page.php b/3rdparty/simpletest/page.php
new file mode 100755
index 00000000000..5c0bce7079d
--- /dev/null
+++ b/3rdparty/simpletest/page.php
@@ -0,0 +1,542 @@
+<?php
+/**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: page.php 1938 2009-08-05 17:16:23Z dgheath $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/http.php');
+require_once(dirname(__FILE__) . '/php_parser.php');
+require_once(dirname(__FILE__) . '/tag.php');
+require_once(dirname(__FILE__) . '/form.php');
+require_once(dirname(__FILE__) . '/selector.php');
+/**#@-*/
+
+/**
+ * A wrapper for a web page.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimplePage {
+ private $links = array();
+ private $title = false;
+ private $last_widget;
+ private $label;
+ private $forms = array();
+ private $frames = array();
+ private $transport_error;
+ private $raw;
+ private $text = false;
+ private $sent;
+ private $headers;
+ private $method;
+ private $url;
+ private $base = false;
+ private $request_data;
+
+ /**
+ * Parses a page ready to access it's contents.
+ * @param SimpleHttpResponse $response Result of HTTP fetch.
+ * @access public
+ */
+ function __construct($response = false) {
+ if ($response) {
+ $this->extractResponse($response);
+ } else {
+ $this->noResponse();
+ }
+ }
+
+ /**
+ * Extracts all of the response information.
+ * @param SimpleHttpResponse $response Response being parsed.
+ * @access private
+ */
+ protected function extractResponse($response) {
+ $this->transport_error = $response->getError();
+ $this->raw = $response->getContent();
+ $this->sent = $response->getSent();
+ $this->headers = $response->getHeaders();
+ $this->method = $response->getMethod();
+ $this->url = $response->getUrl();
+ $this->request_data = $response->getRequestData();
+ }
+
+ /**
+ * Sets up a missing response.
+ * @access private
+ */
+ protected function noResponse() {
+ $this->transport_error = 'No page fetched yet';
+ $this->raw = false;
+ $this->sent = false;
+ $this->headers = false;
+ $this->method = 'GET';
+ $this->url = false;
+ $this->request_data = false;
+ }
+
+ /**
+ * 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 = SimplePage::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;
+ }
+
+ /**
+ * Base URL if set via BASE tag page url otherwise
+ * @return SimpleUrl Base url.
+ * @access public
+ */
+ function getBaseUrl() {
+ return $this->base;
+ }
+
+ /**
+ * 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() {
+ }
+
+ /**
+ * TODO: write docs
+ */
+ function setFrames($frames) {
+ $this->frames = $frames;
+ }
+
+ /**
+ * Test to see if link is an absolute one.
+ * @param string $url Url to test.
+ * @return boolean True if absolute.
+ * @access protected
+ */
+ 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.
+ */
+ function addLink($tag) {
+ $this->links[] = $tag;
+ }
+
+ /**
+ * Set the forms
+ * @param array $forms An array of SimpleForm objects
+ */
+ function setForms($forms) {
+ $this->forms = $forms;
+ }
+
+ /**
+ * Test for the presence of a frameset.
+ * @return boolean True if frameset.
+ * @access public
+ */
+ function hasFrames() {
+ return count($this->frames) > 0;
+ }
+
+ /**
+ * 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->hasFrames()) {
+ return false;
+ }
+ $urls = array();
+ for ($i = 0; $i < count($this->frames); $i++) {
+ $name = $this->frames[$i]->getAttribute('name');
+ $url = new SimpleUrl($this->frames[$i]->getAttribute('src'));
+ $urls[$name ? $name : $i + 1] = $this->expandUrl($url);
+ }
+ return $urls;
+ }
+
+ /**
+ * Fetches a list of loaded frames.
+ * @return array/string Just the URL for a single page.
+ * @access public
+ */
+ function getFrames() {
+ $url = $this->expandUrl($this->getUrl());
+ return $url->asString();
+ }
+
+ /**
+ * Accessor for a list of all links.
+ * @return array List of urls with scheme of
+ * http or https and hostname.
+ * @access public
+ */
+ function getUrls() {
+ $all = array();
+ foreach ($this->links as $link) {
+ $url = $this->getUrlFromLink($link);
+ $all[] = $url->asString();
+ }
+ 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 tag into a target URL.
+ * @param SimpleAnchor $link Parsed link.
+ * @return SimpleUrl URL with frame target if any.
+ * @access private
+ */
+ protected function getUrlFromLink($link) {
+ $url = $this->expandUrl($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 public
+ */
+ function expandUrl($url) {
+ if (! is_object($url)) {
+ $url = new SimpleUrl($url);
+ }
+ $location = $this->getBaseUrl() ? $this->getBaseUrl() : new SimpleUrl();
+ return $url->makeAbsolute($location->makeAbsolute($this->getUrl()));
+ }
+
+ /**
+ * Sets the base url for the page.
+ * @param string $url Base URL for page.
+ */
+ function setBase($url) {
+ $this->base = new SimpleUrl($url);
+ }
+
+ /**
+ * Sets the title tag contents.
+ * @param SimpleTitleTag $tag Title of page.
+ */
+ 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 SimpleSelector $selector Button finder.
+ * @return SimpleForm Form object containing
+ * the button.
+ * @access public
+ */
+ function getFormBySubmit($selector) {
+ for ($i = 0; $i < count($this->forms); $i++) {
+ if ($this->forms[$i]->hasSubmit($selector)) {
+ return $this->forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by image using a selector.
+ * Will only search correctly built forms.
+ * @param SimpleSelector $selector Image finder.
+ * @return SimpleForm Form object containing
+ * the image.
+ * @access public
+ */
+ function getFormByImage($selector) {
+ for ($i = 0; $i < count($this->forms); $i++) {
+ if ($this->forms[$i]->hasImage($selector)) {
+ return $this->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->forms); $i++) {
+ if ($this->forms[$i]->getId() == $id) {
+ return $this->forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Sets a field on each form in which the field is
+ * available.
+ * @param SimpleSelector $selector Field finder.
+ * @param string $value Value to set field to.
+ * @return boolean True if value is valid.
+ * @access public
+ */
+ function setField($selector, $value, $position=false) {
+ $is_set = false;
+ for ($i = 0; $i < count($this->forms); $i++) {
+ if ($this->forms[$i]->setField($selector, $value, $position)) {
+ $is_set = true;
+ }
+ }
+ return $is_set;
+ }
+
+ /**
+ * Accessor for a form element value within a page.
+ * @param SimpleSelector $selector Field finder.
+ * @return string/boolean A string if the field is
+ * present, false if unchecked
+ * and null if missing.
+ * @access public
+ */
+ function getField($selector) {
+ for ($i = 0; $i < count($this->forms); $i++) {
+ $value = $this->forms[$i]->getValue($selector);
+ if (isset($value)) {
+ return $value;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Turns HTML into text browser visible text. Images
+ * are converted to their alt text and tags are supressed.
+ * Entities are converted to their visible representation.
+ * @param string $html HTML to convert.
+ * @return string Plain text.
+ * @access public
+ */
+ static function normalise($html) {
+ $text = preg_replace('#<!--.*?-->#si', '', $html);
+ $text = preg_replace('#<(script|option|textarea)[^>]*>.*?</\1>#si', '', $text);
+ $text = preg_replace('#<img[^>]*alt\s*=\s*("([^"]*)"|\'([^\']*)\'|([a-zA-Z_]+))[^>]*>#', ' \2\3\4 ', $text);
+ $text = preg_replace('#<[^>]*>#', '', $text);
+ $text = html_entity_decode($text, ENT_QUOTES);
+ $text = preg_replace('#\s+#', ' ', $text);
+ return trim(trim($text), "\xA0"); // TODO: The \xAO is a &nbsp;. Add a test for this.
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/php_parser.php b/3rdparty/simpletest/php_parser.php
new file mode 100755
index 00000000000..4c5b8f00bae
--- /dev/null
+++ b/3rdparty/simpletest/php_parser.php
@@ -0,0 +1,1054 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: php_parser.php 1927 2009-07-31 12:45:36Z dgheath $
+ */
+
+/**#@+
+ * Lexer mode stack constants
+ */
+foreach (array('LEXER_ENTER', 'LEXER_MATCHED',
+ 'LEXER_UNMATCHED', 'LEXER_EXIT',
+ 'LEXER_SPECIAL') as $i => $constant) {
+ if (! defined($constant)) {
+ define($constant, $i + 1);
+ }
+}
+/**#@-*/
+
+/**
+ * Compounded regular expression. Any of
+ * the contained patterns could match and
+ * when one does, it's label is returned.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class ParallelRegex {
+ private $patterns;
+ private $labels;
+ private $regex;
+ private $case;
+
+ /**
+ * Constructor. Starts with no patterns.
+ * @param boolean $case True for case sensitive, false
+ * for insensitive.
+ * @access public
+ */
+ function __construct($case) {
+ $this->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
+ */
+ protected 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
+ */
+ protected function getPerlMatchingFlags() {
+ return ($this->case ? "msS" : "msSi");
+ }
+}
+
+/**
+ * States for a stack machine.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleStateStack {
+ private $stack;
+
+ /**
+ * Constructor. Starts in named state.
+ * @param string $start Starting state name.
+ * @access public
+ */
+ function __construct($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 {
+ private $regexes;
+ private $parser;
+ private $mode;
+ private $mode_handlers;
+ private $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 __construct($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
+ */
+ protected 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
+ */
+ protected 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
+ */
+ protected 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
+ */
+ protected 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
+ */
+ protected 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
+ */
+ protected 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;
+ }
+}
+
+/**
+ * Breaks HTML into SAX events.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleHtmlLexer extends SimpleLexer {
+
+ /**
+ * Sets up the lexer with case insensitive matching
+ * and adds the HTML handlers.
+ * @param SimpleSaxParser $parser Handling strategy by
+ * reference.
+ * @access public
+ */
+ function __construct($parser) {
+ parent::__construct($parser, 'text');
+ $this->mapHandler('text', 'acceptTextToken');
+ $this->addSkipping();
+ foreach ($this->getParsedTags() as $tag) {
+ $this->addTag($tag);
+ }
+ $this->addInTagTokens();
+ }
+
+ /**
+ * List of parsed tags. Others are ignored.
+ * @return array List of searched for tags.
+ * @access private
+ */
+ protected function getParsedTags() {
+ return array('a', 'base', 'title', 'form', 'input', 'button', 'textarea', 'select',
+ 'option', 'frameset', 'frame', 'label');
+ }
+
+ /**
+ * The lexer has to skip certain sections such
+ * as server code, client code and styles.
+ * @access private
+ */
+ protected function addSkipping() {
+ $this->mapHandler('css', 'ignore');
+ $this->addEntryPattern('<style', 'text', 'css');
+ $this->addExitPattern('</style>', 'css');
+ $this->mapHandler('js', 'ignore');
+ $this->addEntryPattern('<script', 'text', 'js');
+ $this->addExitPattern('</script>', 'js');
+ $this->mapHandler('comment', 'ignore');
+ $this->addEntryPattern('<!--', 'text', 'comment');
+ $this->addExitPattern('-->', 'comment');
+ }
+
+ /**
+ * Pattern matches to start and end a tag.
+ * @param string $tag Name of tag to scan for.
+ * @access private
+ */
+ protected function addTag($tag) {
+ $this->addSpecialPattern("</$tag>", 'text', 'acceptEndToken');
+ $this->addEntryPattern("<$tag", 'text', 'tag');
+ }
+
+ /**
+ * Pattern matches to parse the inside of a tag
+ * including the attributes and their quoting.
+ * @access private
+ */
+ protected function addInTagTokens() {
+ $this->mapHandler('tag', 'acceptStartToken');
+ $this->addSpecialPattern('\s+', 'tag', 'ignore');
+ $this->addAttributeTokens();
+ $this->addExitPattern('/>', 'tag');
+ $this->addExitPattern('>', 'tag');
+ }
+
+ /**
+ * Matches attributes that are either single quoted,
+ * double quoted or unquoted.
+ * @access private
+ */
+ protected function addAttributeTokens() {
+ $this->mapHandler('dq_attribute', 'acceptAttributeToken');
+ $this->addEntryPattern('=\s*"', 'tag', 'dq_attribute');
+ $this->addPattern("\\\\\"", 'dq_attribute');
+ $this->addExitPattern('"', 'dq_attribute');
+ $this->mapHandler('sq_attribute', 'acceptAttributeToken');
+ $this->addEntryPattern("=\s*'", 'tag', 'sq_attribute');
+ $this->addPattern("\\\\'", 'sq_attribute');
+ $this->addExitPattern("'", 'sq_attribute');
+ $this->mapHandler('uq_attribute', 'acceptAttributeToken');
+ $this->addSpecialPattern('=\s*[^>\s]*', 'tag', 'uq_attribute');
+ }
+}
+
+/**
+ * Converts HTML tokens into selected SAX events.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleHtmlSaxParser {
+ private $lexer;
+ private $listener;
+ private $tag;
+ private $attributes;
+ private $current_attribute;
+
+ /**
+ * Sets the listener.
+ * @param SimplePhpPageBuilder $listener SAX event handler.
+ * @access public
+ */
+ function __construct($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) {
+ return new SimpleHtmlLexer($parser);
+ }
+
+ /**
+ * 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(html_entity_decode($token, ENT_QUOTES));
+ $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 ($this->current_attribute) {
+ if ($event == LEXER_UNMATCHED) {
+ $this->attributes[$this->current_attribute] .=
+ html_entity_decode($token, ENT_QUOTES);
+ }
+ if ($event == LEXER_SPECIAL) {
+ $this->attributes[$this->current_attribute] .=
+ preg_replace('/^=\s*/' , '', html_entity_decode($token, ENT_QUOTES));
+ }
+ }
+ 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;
+ }
+}
+
+/**
+ * SAX event handler. Maintains a list of
+ * open tags and dispatches them as they close.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimplePhpPageBuilder {
+ private $tags;
+ private $page;
+ private $private_content_tag;
+ private $open_forms = array();
+ private $complete_forms = array();
+ private $frameset = false;
+ private $loading_frames = array();
+ private $frameset_nesting_level = 0;
+ private $left_over_labels = array();
+
+ /**
+ * Frees up any references so as to allow the PHP garbage
+ * collection from unset() to work.
+ * @access public
+ */
+ function free() {
+ unset($this->tags);
+ unset($this->page);
+ unset($this->private_content_tags);
+ $this->open_forms = array();
+ $this->complete_forms = array();
+ $this->frameset = false;
+ $this->loading_frames = array();
+ $this->frameset_nesting_level = 0;
+ $this->left_over_labels = array();
+ }
+
+ /**
+ * This builder is always available.
+ * @return boolean Always true.
+ */
+ function can() {
+ return true;
+ }
+
+ /**
+ * 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->acceptPageEnd();
+ $page = $this->page;
+ $this->free();
+ return $page;
+ }
+
+ /**
+ * Creates an empty page.
+ * @return SimplePage New unparsed page.
+ * @access protected
+ */
+ protected function createPage($response) {
+ return new SimplePage($response);
+ }
+
+ /**
+ * Creates the parser used with the builder.
+ * @param SimplePhpPageBuilder $listener Target of parser.
+ * @return SimpleSaxParser Parser to generate
+ * events for the builder.
+ * @access protected
+ */
+ protected function createParser(&$listener) {
+ return new SimpleHtmlSaxParser($listener);
+ }
+
+ /**
+ * Start of element event. Opens a new tag.
+ * @param string $name Element name.
+ * @param hash $attributes Attributes without content
+ * are marked as true.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function startElement($name, $attributes) {
+ $factory = new SimpleTagBuilder();
+ $tag = $factory->createTag($name, $attributes);
+ if (! $tag) {
+ return true;
+ }
+ if ($tag->getTagName() == 'label') {
+ $this->acceptLabelStart($tag);
+ $this->openTag($tag);
+ return true;
+ }
+ if ($tag->getTagName() == 'form') {
+ $this->acceptFormStart($tag);
+ return true;
+ }
+ if ($tag->getTagName() == 'frameset') {
+ $this->acceptFramesetStart($tag);
+ return true;
+ }
+ if ($tag->getTagName() == 'frame') {
+ $this->acceptFrame($tag);
+ return true;
+ }
+ if ($tag->isPrivateContent() && ! isset($this->private_content_tag)) {
+ $this->private_content_tag = &$tag;
+ }
+ if ($tag->expectEndTag()) {
+ $this->openTag($tag);
+ return true;
+ }
+ $this->acceptTag($tag);
+ return true;
+ }
+
+ /**
+ * End of element event.
+ * @param string $name Element name.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function endElement($name) {
+ if ($name == 'label') {
+ $this->acceptLabelEnd();
+ return true;
+ }
+ if ($name == 'form') {
+ $this->acceptFormEnd();
+ return true;
+ }
+ if ($name == 'frameset') {
+ $this->acceptFramesetEnd();
+ return true;
+ }
+ if ($this->hasNamedTagOnOpenTagStack($name)) {
+ $tag = array_pop($this->tags[$name]);
+ if ($tag->isPrivateContent() && $this->private_content_tag->getTagName() == $name) {
+ unset($this->private_content_tag);
+ }
+ $this->addContentTagToOpenTags($tag);
+ $this->acceptTag($tag);
+ return true;
+ }
+ return true;
+ }
+
+ /**
+ * Test to see if there are any open tags awaiting
+ * closure that match the tag name.
+ * @param string $name Element name.
+ * @return boolean True if any are still open.
+ * @access private
+ */
+ protected function hasNamedTagOnOpenTagStack($name) {
+ return isset($this->tags[$name]) && (count($this->tags[$name]) > 0);
+ }
+
+ /**
+ * Unparsed, but relevant data. The data is added
+ * to every open tag.
+ * @param string $text May include unparsed tags.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function addContent($text) {
+ if (isset($this->private_content_tag)) {
+ $this->private_content_tag->addContent($text);
+ } else {
+ $this->addContentToAllOpenTags($text);
+ }
+ return true;
+ }
+
+ /**
+ * Any content fills all currently open tags unless it
+ * is part of an option tag.
+ * @param string $text May include unparsed tags.
+ * @access private
+ */
+ protected function addContentToAllOpenTags($text) {
+ foreach (array_keys($this->tags) as $name) {
+ for ($i = 0, $count = count($this->tags[$name]); $i < $count; $i++) {
+ $this->tags[$name][$i]->addContent($text);
+ }
+ }
+ }
+
+ /**
+ * Parsed data in tag form. The parsed tag is added
+ * to every open tag. Used for adding options to select
+ * fields only.
+ * @param SimpleTag $tag Option tags only.
+ * @access private
+ */
+ protected 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
+ */
+ protected function openTag($tag) {
+ $name = $tag->getTagName();
+ if (! in_array($name, array_keys($this->tags))) {
+ $this->tags[$name] = array();
+ }
+ $this->tags[$name][] = $tag;
+ }
+
+ /**
+ * Adds a tag to the page.
+ * @param SimpleTag $tag Tag to accept.
+ * @access public
+ */
+ protected function acceptTag($tag) {
+ if ($tag->getTagName() == "a") {
+ $this->page->addLink($tag);
+ } elseif ($tag->getTagName() == "base") {
+ $this->page->setBase($tag->getAttribute('href'));
+ } elseif ($tag->getTagName() == "title") {
+ $this->page->setTitle($tag);
+ } elseif ($this->isFormElement($tag->getTagName())) {
+ for ($i = 0; $i < count($this->open_forms); $i++) {
+ $this->open_forms[$i]->addWidget($tag);
+ }
+ $this->last_widget = $tag;
+ }
+ }
+
+ /**
+ * Opens a label for a described widget.
+ * @param SimpleFormTag $tag Tag to accept.
+ * @access public
+ */
+ protected function acceptLabelStart($tag) {
+ $this->label = $tag;
+ unset($this->last_widget);
+ }
+
+ /**
+ * Closes the most recently opened label.
+ * @access public
+ */
+ protected function acceptLabelEnd() {
+ if (isset($this->label)) {
+ if (isset($this->last_widget)) {
+ $this->last_widget->setLabel($this->label->getText());
+ unset($this->last_widget);
+ } else {
+ $this->left_over_labels[] = SimpleTestCompatibility::copy($this->label);
+ }
+ unset($this->label);
+ }
+ }
+
+ /**
+ * Tests to see if a tag is a possible form
+ * element.
+ * @param string $name HTML element name.
+ * @return boolean True if form element.
+ * @access private
+ */
+ protected 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
+ */
+ protected function acceptFormStart($tag) {
+ $this->open_forms[] = new SimpleForm($tag, $this->page);
+ }
+
+ /**
+ * Closes the most recently opened form.
+ * @access public
+ */
+ protected 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
+ */
+ protected function acceptFramesetStart($tag) {
+ if (! $this->isLoadingFrames()) {
+ $this->frameset = $tag;
+ }
+ $this->frameset_nesting_level++;
+ }
+
+ /**
+ * Closes the most recently opened frameset.
+ * @access public
+ */
+ protected 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
+ */
+ protected function acceptFrame($tag) {
+ if ($this->isLoadingFrames()) {
+ if ($tag->getAttribute('src')) {
+ $this->loading_frames[] = $tag;
+ }
+ }
+ }
+
+ /**
+ * Test to see if in the middle of reading
+ * a frameset.
+ * @return boolean True if inframeset.
+ * @access private
+ */
+ protected function isLoadingFrames() {
+ return $this->frameset and $this->frameset_nesting_level > 0;
+ }
+
+ /**
+ * Marker for end of complete page. Any work in
+ * progress can now be closed.
+ * @access public
+ */
+ protected function acceptPageEnd() {
+ while (count($this->open_forms)) {
+ $this->complete_forms[] = array_pop($this->open_forms);
+ }
+ foreach ($this->left_over_labels as $label) {
+ for ($i = 0, $count = count($this->complete_forms); $i < $count; $i++) {
+ $this->complete_forms[$i]->attachLabelBySelector(
+ new SimpleById($label->getFor()),
+ $label->getText());
+ }
+ }
+ $this->page->setForms($this->complete_forms);
+ $this->page->setFrames($this->loading_frames);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/recorder.php b/3rdparty/simpletest/recorder.php
new file mode 100644
index 00000000000..b3d0d01c625
--- /dev/null
+++ b/3rdparty/simpletest/recorder.php
@@ -0,0 +1,101 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage Extensions
+ * @author Rene vd O (original code)
+ * @author Perrick Penet
+ * @author Marcus Baker
+ * @version $Id: recorder.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/scorer.php');
+
+/**
+ * A single test result.
+ * @package SimpleTest
+ * @subpackage Extensions
+ */
+abstract class SimpleResult {
+ public $time;
+ public $breadcrumb;
+ public $message;
+
+ /**
+ * Records the test result as public members.
+ * @param array $breadcrumb Test stack at the time of the event.
+ * @param string $message The messsage to the human.
+ */
+ function __construct($breadcrumb, $message) {
+ list($this->time, $this->breadcrumb, $this->message) =
+ array(time(), $breadcrumb, $message);
+ }
+}
+
+/**
+ * A single pass captured for later.
+ * @package SimpleTest
+ * @subpackage Extensions
+ */
+class SimpleResultOfPass extends SimpleResult { }
+
+/**
+ * A single failure captured for later.
+ * @package SimpleTest
+ * @subpackage Extensions
+ */
+class SimpleResultOfFail extends SimpleResult { }
+
+/**
+ * A single exception captured for later.
+ * @package SimpleTest
+ * @subpackage Extensions
+ */
+class SimpleResultOfException extends SimpleResult { }
+
+/**
+ * Array-based test recorder. Returns an array
+ * with timestamp, status, test name and message for each pass and failure.
+ * @package SimpleTest
+ * @subpackage Extensions
+ */
+class Recorder extends SimpleReporterDecorator {
+ public $results = array();
+
+ /**
+ * Stashes the pass as a SimpleResultOfPass
+ * for later retrieval.
+ * @param string $message Pass message to be displayed
+ * eventually.
+ */
+ function paintPass($message) {
+ parent::paintPass($message);
+ $this->results[] = new SimpleResultOfPass(parent::getTestList(), $message);
+ }
+
+ /**
+ * Stashes the fail as a SimpleResultOfFail
+ * for later retrieval.
+ * @param string $message Failure message to be displayed
+ * eventually.
+ */
+ function paintFail($message) {
+ parent::paintFail($message);
+ $this->results[] = new SimpleResultOfFail(parent::getTestList(), $message);
+ }
+
+ /**
+ * Stashes the exception as a SimpleResultOfException
+ * for later retrieval.
+ * @param string $message Exception message to be displayed
+ * eventually.
+ */
+ function paintException($message) {
+ parent::paintException($message);
+ $this->results[] = new SimpleResultOfException(parent::getTestList(), $message);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/reflection_php4.php b/3rdparty/simpletest/reflection_php4.php
new file mode 100644
index 00000000000..39801ea1bdb
--- /dev/null
+++ b/3rdparty/simpletest/reflection_php4.php
@@ -0,0 +1,136 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: reflection_php4.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**
+ * Version specific reflection API.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @ignore duplicate with reflection_php5.php
+ */
+class SimpleReflection {
+ var $_interface;
+
+ /**
+ * Stashes the class/interface.
+ * @param string $interface Class or interface
+ * to inspect.
+ */
+ function SimpleReflection($interface) {
+ $this->_interface = $interface;
+ }
+
+ /**
+ * Checks that a class has been declared.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classExists() {
+ return class_exists($this->_interface);
+ }
+
+ /**
+ * Needed to kill the autoload feature in PHP5
+ * for classes created dynamically.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classExistsSansAutoload() {
+ return class_exists($this->_interface);
+ }
+
+ /**
+ * Checks that a class or interface has been
+ * declared.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classOrInterfaceExists() {
+ return class_exists($this->_interface);
+ }
+
+ /**
+ * Needed to kill the autoload feature in PHP5
+ * for classes created dynamically.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classOrInterfaceExistsSansAutoload() {
+ return class_exists($this->_interface);
+ }
+
+ /**
+ * Gets the list of methods on a class or
+ * interface.
+ * @returns array List of method names.
+ * @access public
+ */
+ function getMethods() {
+ return get_class_methods($this->_interface);
+ }
+
+ /**
+ * Gets the list of interfaces from a class. If the
+ * class name is actually an interface then just that
+ * interface is returned.
+ * @returns array List of interfaces.
+ * @access public
+ */
+ function getInterfaces() {
+ return array();
+ }
+
+ /**
+ * Finds the parent class name.
+ * @returns string Parent class name.
+ * @access public
+ */
+ function getParent() {
+ return strtolower(get_parent_class($this->_interface));
+ }
+
+ /**
+ * Determines if the class is abstract, which for PHP 4
+ * will never be the case.
+ * @returns boolean True if abstract.
+ * @access public
+ */
+ function isAbstract() {
+ return false;
+ }
+
+ /**
+ * Determines if the the entity is an interface, which for PHP 4
+ * will never be the case.
+ * @returns boolean True if interface.
+ * @access public
+ */
+ function isInterface() {
+ return false;
+ }
+
+ /**
+ * Scans for final methods, but as it's PHP 4 there
+ * aren't any.
+ * @returns boolean True if the class has a final method.
+ * @access public
+ */
+ function hasFinal() {
+ return false;
+ }
+
+ /**
+ * Gets the source code matching the declaration
+ * of a method.
+ * @param string $method Method name.
+ * @access public
+ */
+ function getSignature($method) {
+ return "function &$method()";
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/reflection_php5.php b/3rdparty/simpletest/reflection_php5.php
new file mode 100644
index 00000000000..43d8a7b287f
--- /dev/null
+++ b/3rdparty/simpletest/reflection_php5.php
@@ -0,0 +1,386 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: reflection_php5.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**
+ * Version specific reflection API.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleReflection {
+ private $interface;
+
+ /**
+ * Stashes the class/interface.
+ * @param string $interface Class or interface
+ * to inspect.
+ */
+ function __construct($interface) {
+ $this->interface = $interface;
+ }
+
+ /**
+ * Checks that a class has been declared. Versions
+ * before PHP5.0.2 need a check that it's not really
+ * an interface.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classExists() {
+ if (! class_exists($this->interface)) {
+ return false;
+ }
+ $reflection = new ReflectionClass($this->interface);
+ return ! $reflection->isInterface();
+ }
+
+ /**
+ * Needed to kill the autoload feature in PHP5
+ * for classes created dynamically.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classExistsSansAutoload() {
+ return class_exists($this->interface, false);
+ }
+
+ /**
+ * Checks that a class or interface has been
+ * declared.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classOrInterfaceExists() {
+ return $this->classOrInterfaceExistsWithAutoload($this->interface, true);
+ }
+
+ /**
+ * Needed to kill the autoload feature in PHP5
+ * for classes created dynamically.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classOrInterfaceExistsSansAutoload() {
+ return $this->classOrInterfaceExistsWithAutoload($this->interface, false);
+ }
+
+ /**
+ * Needed to select the autoload feature in PHP5
+ * for classes created dynamically.
+ * @param string $interface Class or interface name.
+ * @param boolean $autoload True totriggerautoload.
+ * @return boolean True if interface defined.
+ * @access private
+ */
+ protected function classOrInterfaceExistsWithAutoload($interface, $autoload) {
+ if (function_exists('interface_exists')) {
+ if (interface_exists($this->interface, $autoload)) {
+ return true;
+ }
+ }
+ return class_exists($this->interface, $autoload);
+ }
+
+ /**
+ * Gets the list of methods on a class or
+ * interface.
+ * @returns array List of method names.
+ * @access public
+ */
+ function getMethods() {
+ return array_unique(get_class_methods($this->interface));
+ }
+
+ /**
+ * Gets the list of interfaces from a class. If the
+ * class name is actually an interface then just that
+ * interface is returned.
+ * @returns array List of interfaces.
+ * @access public
+ */
+ function getInterfaces() {
+ $reflection = new ReflectionClass($this->interface);
+ if ($reflection->isInterface()) {
+ return array($this->interface);
+ }
+ return $this->onlyParents($reflection->getInterfaces());
+ }
+
+ /**
+ * Gets the list of methods for the implemented
+ * interfaces only.
+ * @returns array List of enforced method signatures.
+ * @access public
+ */
+ function getInterfaceMethods() {
+ $methods = array();
+ foreach ($this->getInterfaces() as $interface) {
+ $methods = array_merge($methods, get_class_methods($interface));
+ }
+ return array_unique($methods);
+ }
+
+ /**
+ * Checks to see if the method signature has to be tightly
+ * specified.
+ * @param string $method Method name.
+ * @returns boolean True if enforced.
+ * @access private
+ */
+ protected function isInterfaceMethod($method) {
+ return in_array($method, $this->getInterfaceMethods());
+ }
+
+ /**
+ * Finds the parent class name.
+ * @returns string Parent class name.
+ * @access public
+ */
+ function getParent() {
+ $reflection = new ReflectionClass($this->interface);
+ $parent = $reflection->getParentClass();
+ if ($parent) {
+ return $parent->getName();
+ }
+ return false;
+ }
+
+ /**
+ * Trivially determines if the class is abstract.
+ * @returns boolean True if abstract.
+ * @access public
+ */
+ function isAbstract() {
+ $reflection = new ReflectionClass($this->interface);
+ return $reflection->isAbstract();
+ }
+
+ /**
+ * Trivially determines if the class is an interface.
+ * @returns boolean True if interface.
+ * @access public
+ */
+ function isInterface() {
+ $reflection = new ReflectionClass($this->interface);
+ return $reflection->isInterface();
+ }
+
+ /**
+ * Scans for final methods, as they screw up inherited
+ * mocks by not allowing you to override them.
+ * @returns boolean True if the class has a final method.
+ * @access public
+ */
+ function hasFinal() {
+ $reflection = new ReflectionClass($this->interface);
+ foreach ($reflection->getMethods() as $method) {
+ if ($method->isFinal()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Whittles a list of interfaces down to only the
+ * necessary top level parents.
+ * @param array $interfaces Reflection API interfaces
+ * to reduce.
+ * @returns array List of parent interface names.
+ * @access private
+ */
+ protected function onlyParents($interfaces) {
+ $parents = array();
+ $blacklist = array();
+ foreach ($interfaces as $interface) {
+ foreach($interfaces as $possible_parent) {
+ if ($interface->getName() == $possible_parent->getName()) {
+ continue;
+ }
+ if ($interface->isSubClassOf($possible_parent)) {
+ $blacklist[$possible_parent->getName()] = true;
+ }
+ }
+ if (!isset($blacklist[$interface->getName()])) {
+ $parents[] = $interface->getName();
+ }
+ }
+ return $parents;
+ }
+
+ /**
+ * Checks whether a method is abstract or not.
+ * @param string $name Method name.
+ * @return bool true if method is abstract, else false
+ * @access private
+ */
+ protected function isAbstractMethod($name) {
+ $interface = new ReflectionClass($this->interface);
+ if (! $interface->hasMethod($name)) {
+ return false;
+ }
+ return $interface->getMethod($name)->isAbstract();
+ }
+
+ /**
+ * Checks whether a method is the constructor.
+ * @param string $name Method name.
+ * @return bool true if method is the constructor
+ * @access private
+ */
+ protected function isConstructor($name) {
+ return ($name == '__construct') || ($name == $this->interface);
+ }
+
+ /**
+ * Checks whether a method is abstract in all parents or not.
+ * @param string $name Method name.
+ * @return bool true if method is abstract in parent, else false
+ * @access private
+ */
+ protected function isAbstractMethodInParents($name) {
+ $interface = new ReflectionClass($this->interface);
+ $parent = $interface->getParentClass();
+ while($parent) {
+ if (! $parent->hasMethod($name)) {
+ return false;
+ }
+ if ($parent->getMethod($name)->isAbstract()) {
+ return true;
+ }
+ $parent = $parent->getParentClass();
+ }
+ return false;
+ }
+
+ /**
+ * Checks whether a method is static or not.
+ * @param string $name Method name
+ * @return bool true if method is static, else false
+ * @access private
+ */
+ protected function isStaticMethod($name) {
+ $interface = new ReflectionClass($this->interface);
+ if (! $interface->hasMethod($name)) {
+ return false;
+ }
+ return $interface->getMethod($name)->isStatic();
+ }
+
+ /**
+ * Writes the source code matching the declaration
+ * of a method.
+ * @param string $name Method name.
+ * @return string Method signature up to last
+ * bracket.
+ * @access public
+ */
+ function getSignature($name) {
+ if ($name == '__set') {
+ return 'function __set($key, $value)';
+ }
+ if ($name == '__call') {
+ return 'function __call($method, $arguments)';
+ }
+ if (version_compare(phpversion(), '5.1.0', '>=')) {
+ if (in_array($name, array('__get', '__isset', $name == '__unset'))) {
+ return "function {$name}(\$key)";
+ }
+ }
+ if ($name == '__toString') {
+ return "function $name()";
+ }
+
+ // This wonky try-catch is a work around for a faulty method_exists()
+ // in early versions of PHP 5 which would return false for static
+ // methods. The Reflection classes work fine, but hasMethod()
+ // doesn't exist prior to PHP 5.1.0, so we need to use a more crude
+ // detection method.
+ try {
+ $interface = new ReflectionClass($this->interface);
+ $interface->getMethod($name);
+ } catch (ReflectionException $e) {
+ return "function $name()";
+ }
+ return $this->getFullSignature($name);
+ }
+
+ /**
+ * For a signature specified in an interface, full
+ * details must be replicated to be a valid implementation.
+ * @param string $name Method name.
+ * @return string Method signature up to last
+ * bracket.
+ * @access private
+ */
+ protected function getFullSignature($name) {
+ $interface = new ReflectionClass($this->interface);
+ $method = $interface->getMethod($name);
+ $reference = $method->returnsReference() ? '&' : '';
+ $static = $method->isStatic() ? 'static ' : '';
+ return "{$static}function $reference$name(" .
+ implode(', ', $this->getParameterSignatures($method)) .
+ ")";
+ }
+
+ /**
+ * Gets the source code for each parameter.
+ * @param ReflectionMethod $method Method object from
+ * reflection API
+ * @return array List of strings, each
+ * a snippet of code.
+ * @access private
+ */
+ protected function getParameterSignatures($method) {
+ $signatures = array();
+ foreach ($method->getParameters() as $parameter) {
+ $signature = '';
+ $type = $parameter->getClass();
+ if (is_null($type) && version_compare(phpversion(), '5.1.0', '>=') && $parameter->isArray()) {
+ $signature .= 'array ';
+ } elseif (!is_null($type)) {
+ $signature .= $type->getName() . ' ';
+ }
+ if ($parameter->isPassedByReference()) {
+ $signature .= '&';
+ }
+ $signature .= '$' . $this->suppressSpurious($parameter->getName());
+ if ($this->isOptional($parameter)) {
+ $signature .= ' = null';
+ }
+ $signatures[] = $signature;
+ }
+ return $signatures;
+ }
+
+ /**
+ * The SPL library has problems with the
+ * Reflection library. In particular, you can
+ * get extra characters in parameter names :(.
+ * @param string $name Parameter name.
+ * @return string Cleaner name.
+ * @access private
+ */
+ protected function suppressSpurious($name) {
+ return str_replace(array('[', ']', ' '), '', $name);
+ }
+
+ /**
+ * Test of a reflection parameter being optional
+ * that works with early versions of PHP5.
+ * @param reflectionParameter $parameter Is this optional.
+ * @return boolean True if optional.
+ * @access private
+ */
+ protected function isOptional($parameter) {
+ if (method_exists($parameter, 'isOptional')) {
+ return $parameter->isOptional();
+ }
+ return false;
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/remote.php b/3rdparty/simpletest/remote.php
new file mode 100644
index 00000000000..4bb37b7c51b
--- /dev/null
+++ b/3rdparty/simpletest/remote.php
@@ -0,0 +1,115 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: remote.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/browser.php');
+require_once(dirname(__FILE__) . '/xml.php');
+require_once(dirname(__FILE__) . '/test_case.php');
+/**#@-*/
+
+/**
+ * Runs an XML formated test on a remote server.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class RemoteTestCase {
+ private $url;
+ private $dry_url;
+ private $size;
+
+ /**
+ * Sets the location of the remote test.
+ * @param string $url Test location.
+ * @param string $dry_url Location for dry run.
+ * @access public
+ */
+ function __construct($url, $dry_url = false) {
+ $this->url = $url;
+ $this->dry_url = $dry_url ? $dry_url : $url;
+ $this->size = false;
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->url;
+ }
+
+ /**
+ * 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
+ */
+ protected function createBrowser() {
+ return new SimpleBrowser();
+ }
+
+ /**
+ * Creates the XML parser.
+ * @param SimpleReporter $reporter Target of test results.
+ * @return SimpleTestXmlListener XML reader.
+ * @access protected
+ */
+ 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/3rdparty/simpletest/reporter.php b/3rdparty/simpletest/reporter.php
new file mode 100755
index 00000000000..bd4f3fa41dd
--- /dev/null
+++ b/3rdparty/simpletest/reporter.php
@@ -0,0 +1,445 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: reporter.php 2005 2010-11-02 14:09:34Z lastcraft $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/scorer.php');
+//require_once(dirname(__FILE__) . '/arguments.php');
+/**#@-*/
+
+/**
+ * Sample minimal test displayer. Generates only
+ * failure messages and a pass count.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class HtmlReporter extends SimpleReporter {
+ private $character_set;
+
+ /**
+ * Does nothing yet. The first output will
+ * be sent on the first test start. For use
+ * by a web browser.
+ * @access public
+ */
+ function __construct($character_set = 'ISO-8859-1') {
+ parent::__construct();
+ $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 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
+ print "<html>\n<head>\n<title>$test_name</title>\n";
+ print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" .
+ $this->character_set . "\">\n";
+ print "<style type=\"text/css\">\n";
+ print $this->getCss() . "\n";
+ print "</style>\n";
+ print "</head>\n<body>\n";
+ print "<h1>$test_name</h1>\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
+ */
+ protected function getCss() {
+ return ".fail { background-color: inherit; color: red; }" .
+ ".pass { background-color: inherit; color: green; }" .
+ " pre { background-color: lightgray; color: inherit; }";
+ }
+
+ /**
+ * Paints the end of the test with a summary of
+ * the passes and failures.
+ * @param string $test_name Name class of test.
+ * @access public
+ */
+ function paintFooter($test_name) {
+ $colour = ($this->getFailCount() + $this->getExceptionCount() > 0 ? "red" : "green");
+ print "<div style=\"";
+ print "padding: 8px; margin-top: 1em; background-color: $colour; color: white;";
+ print "\">";
+ print $this->getTestCaseProgress() . "/" . $this->getTestCaseCount();
+ print " test cases complete:\n";
+ print "<strong>" . $this->getPassCount() . "</strong> passes, ";
+ print "<strong>" . $this->getFailCount() . "</strong> fails and ";
+ print "<strong>" . $this->getExceptionCount() . "</strong> exceptions.";
+ print "</div>\n";
+ print "</body>\n</html>\n";
+ }
+
+ /**
+ * Paints the test failure with a breadcrumbs
+ * trail of the nesting test suites below the
+ * top level test.
+ * @param string $message Failure message displayed in
+ * the context of the other tests.
+ */
+ function paintFail($message) {
+ parent::paintFail($message);
+ print "<span class=\"fail\">Fail</span>: ";
+ $breadcrumb = $this->getTestList();
+ array_shift($breadcrumb);
+ print implode(" -&gt; ", $breadcrumb);
+ print " -&gt; " . $this->htmlEntities($message) . "<br />\n";
+ }
+
+ /**
+ * Paints a PHP error.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintError($message) {
+ parent::paintError($message);
+ print "<span class=\"fail\">Exception</span>: ";
+ $breadcrumb = $this->getTestList();
+ array_shift($breadcrumb);
+ print implode(" -&gt; ", $breadcrumb);
+ print " -&gt; <strong>" . $this->htmlEntities($message) . "</strong><br />\n";
+ }
+
+ /**
+ * Paints a PHP exception.
+ * @param Exception $exception Exception to display.
+ * @access public
+ */
+ function paintException($exception) {
+ parent::paintException($exception);
+ print "<span class=\"fail\">Exception</span>: ";
+ $breadcrumb = $this->getTestList();
+ array_shift($breadcrumb);
+ print implode(" -&gt; ", $breadcrumb);
+ $message = 'Unexpected exception of type [' . get_class($exception) .
+ '] with message ['. $exception->getMessage() .
+ '] in ['. $exception->getFile() .
+ ' line ' . $exception->getLine() . ']';
+ print " -&gt; <strong>" . $this->htmlEntities($message) . "</strong><br />\n";
+ }
+
+ /**
+ * Prints the message for skipping tests.
+ * @param string $message Text of skip condition.
+ * @access public
+ */
+ function paintSkip($message) {
+ parent::paintSkip($message);
+ print "<span class=\"pass\">Skipped</span>: ";
+ $breadcrumb = $this->getTestList();
+ array_shift($breadcrumb);
+ print implode(" -&gt; ", $breadcrumb);
+ print " -&gt; " . $this->htmlEntities($message) . "<br />\n";
+ }
+
+ /**
+ * Paints formatted text such as dumped privateiables.
+ * @param string $message Text to show.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ print '<pre>' . $this->htmlEntities($message) . '</pre>';
+ }
+
+ /**
+ * Character set adjusted entity conversion.
+ * @param string $message Plain text or Unicode message.
+ * @return string Browser readable message.
+ * @access protected
+ */
+ protected function htmlEntities($message) {
+ return htmlentities($message, ENT_COMPAT, $this->character_set);
+ }
+}
+
+/**
+ * Sample minimal test displayer. Generates only
+ * failure messages and a pass count. For command
+ * line use. I've tried to make it look like JUnit,
+ * but I wanted to output the errors as they arrived
+ * which meant dropping the dots.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class TextReporter extends SimpleReporter {
+
+ /**
+ * Does nothing yet. The first output will
+ * be sent on the first test start.
+ */
+ function __construct() {
+ parent::__construct();
+ }
+
+ /**
+ * Paints the title only.
+ * @param string $test_name Name class of test.
+ * @access public
+ */
+ function paintHeader($test_name) {
+ if (! SimpleReporter::inCli()) {
+ header('Content-type: text/plain');
+ }
+ print "$test_name\n";
+ flush();
+ }
+
+ /**
+ * Paints the end of the test with a summary of
+ * the passes and failures.
+ * @param string $test_name Name class of test.
+ * @access public
+ */
+ function paintFooter($test_name) {
+ if ($this->getFailCount() + $this->getExceptionCount() == 0) {
+ print "OK\n";
+ } else {
+ print "FAILURES!!!\n";
+ }
+ print "Test cases run: " . $this->getTestCaseProgress() .
+ "/" . $this->getTestCaseCount() .
+ ", Passes: " . $this->getPassCount() .
+ ", Failures: " . $this->getFailCount() .
+ ", Exceptions: " . $this->getExceptionCount() . "\n";
+ }
+
+ /**
+ * Paints the test failure as a stack trace.
+ * @param string $message Failure message displayed in
+ * the context of the other tests.
+ * @access public
+ */
+ function paintFail($message) {
+ parent::paintFail($message);
+ print $this->getFailCount() . ") $message\n";
+ $breadcrumb = $this->getTestList();
+ array_shift($breadcrumb);
+ print "\tin " . implode("\n\tin ", array_reverse($breadcrumb));
+ print "\n";
+ }
+
+ /**
+ * Paints a PHP error or exception.
+ * @param string $message Message to be shown.
+ * @access public
+ * @abstract
+ */
+ function paintError($message) {
+ parent::paintError($message);
+ print "Exception " . $this->getExceptionCount() . "!\n$message\n";
+ $breadcrumb = $this->getTestList();
+ array_shift($breadcrumb);
+ print "\tin " . implode("\n\tin ", array_reverse($breadcrumb));
+ print "\n";
+ }
+
+ /**
+ * Paints a PHP error or exception.
+ * @param Exception $exception Exception to describe.
+ * @access public
+ * @abstract
+ */
+ function paintException($exception) {
+ parent::paintException($exception);
+ $message = 'Unexpected exception of type [' . get_class($exception) .
+ '] with message ['. $exception->getMessage() .
+ '] in ['. $exception->getFile() .
+ ' line ' . $exception->getLine() . ']';
+ print "Exception " . $this->getExceptionCount() . "!\n$message\n";
+ $breadcrumb = $this->getTestList();
+ array_shift($breadcrumb);
+ print "\tin " . implode("\n\tin ", array_reverse($breadcrumb));
+ print "\n";
+ }
+
+ /**
+ * Prints the message for skipping tests.
+ * @param string $message Text of skip condition.
+ * @access public
+ */
+ function paintSkip($message) {
+ parent::paintSkip($message);
+ print "Skip: $message\n";
+ }
+
+ /**
+ * Paints formatted text such as dumped privateiables.
+ * @param string $message Text to show.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ print "$message\n";
+ flush();
+ }
+}
+
+/**
+ * Runs just a single test group, a single case or
+ * even a single test within that case.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SelectiveReporter extends SimpleReporterDecorator {
+ private $just_this_case = false;
+ private $just_this_test = false;
+ private $on;
+
+ /**
+ * Selects the test case or group to be run,
+ * and optionally a specific test.
+ * @param SimpleScorer $reporter Reporter to receive events.
+ * @param string $just_this_case Only this case or group will run.
+ * @param string $just_this_test Only this test method will run.
+ */
+ function __construct($reporter, $just_this_case = false, $just_this_test = false) {
+ if (isset($just_this_case) && $just_this_case) {
+ $this->just_this_case = strtolower($just_this_case);
+ $this->off();
+ } else {
+ $this->on();
+ }
+ if (isset($just_this_test) && $just_this_test) {
+ $this->just_this_test = strtolower($just_this_test);
+ }
+ parent::__construct($reporter);
+ }
+
+ /**
+ * Compares criteria to actual the case/group name.
+ * @param string $test_case The incoming test.
+ * @return boolean True if matched.
+ * @access protected
+ */
+ protected function matchesTestCase($test_case) {
+ return $this->just_this_case == strtolower($test_case);
+ }
+
+ /**
+ * Compares criteria to actual the test name. If no
+ * name was specified at the beginning, then all tests
+ * can run.
+ * @param string $method The incoming test method.
+ * @return boolean True if matched.
+ * @access protected
+ */
+ protected function shouldRunTest($test_case, $method) {
+ if ($this->isOn() || $this->matchesTestCase($test_case)) {
+ if ($this->just_this_test) {
+ return $this->just_this_test == strtolower($method);
+ } else {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Switch on testing for the group or subgroup.
+ * @access private
+ */
+ protected function on() {
+ $this->on = true;
+ }
+
+ /**
+ * Switch off testing for the group or subgroup.
+ * @access private
+ */
+ protected function off() {
+ $this->on = false;
+ }
+
+ /**
+ * Is this group actually being tested?
+ * @return boolean True if the current test group is active.
+ * @access private
+ */
+ protected function isOn() {
+ return $this->on;
+ }
+
+ /**
+ * Veto everything that doesn't match the method wanted.
+ * @param string $test_case Name of test case.
+ * @param string $method Name of test method.
+ * @return boolean True if test should be run.
+ * @access public
+ */
+ function shouldInvoke($test_case, $method) {
+ if ($this->shouldRunTest($test_case, $method)) {
+ return $this->reporter->shouldInvoke($test_case, $method);
+ }
+ return false;
+ }
+
+ /**
+ * Paints the start of a group test.
+ * @param string $test_case Name of test or other label.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($test_case, $size) {
+ if ($this->just_this_case && $this->matchesTestCase($test_case)) {
+ $this->on();
+ }
+ $this->reporter->paintGroupStart($test_case, $size);
+ }
+
+ /**
+ * Paints the end of a group test.
+ * @param string $test_case Name of test or other label.
+ * @access public
+ */
+ function paintGroupEnd($test_case) {
+ $this->reporter->paintGroupEnd($test_case);
+ if ($this->just_this_case && $this->matchesTestCase($test_case)) {
+ $this->off();
+ }
+ }
+}
+
+/**
+ * Suppresses skip messages.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class NoSkipsReporter extends SimpleReporterDecorator {
+
+ /**
+ * Does nothing.
+ * @param string $message Text of skip condition.
+ * @access public
+ */
+ function paintSkip($message) { }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/scorer.php b/3rdparty/simpletest/scorer.php
new file mode 100644
index 00000000000..27776f4b631
--- /dev/null
+++ b/3rdparty/simpletest/scorer.php
@@ -0,0 +1,875 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: scorer.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**#@+*/
+require_once(dirname(__FILE__) . '/invoker.php');
+/**#@-*/
+
+/**
+ * Can receive test events and display them. Display
+ * is achieved by making display methods available
+ * and visiting the incoming event.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @abstract
+ */
+class SimpleScorer {
+ private $passes;
+ private $fails;
+ private $exceptions;
+ private $is_dry_run;
+
+ /**
+ * Starts the test run with no results.
+ * @access public
+ */
+ function __construct() {
+ $this->passes = 0;
+ $this->fails = 0;
+ $this->exceptions = 0;
+ $this->is_dry_run = false;
+ }
+
+ /**
+ * Signals that the next evaluation will be a dry
+ * run. That is, the structure events will be
+ * recorded, but no tests will be run.
+ * @param boolean $is_dry Dry run if true.
+ * @access public
+ */
+ function makeDry($is_dry = true) {
+ $this->is_dry_run = $is_dry;
+ }
+
+ /**
+ * The reporter has a veto on what should be run.
+ * @param string $test_case_name name of test case.
+ * @param string $method Name of test method.
+ * @access public
+ */
+ function shouldInvoke($test_case_name, $method) {
+ return ! $this->is_dry_run;
+ }
+
+ /**
+ * Can wrap the invoker in preperation for running
+ * a test.
+ * @param SimpleInvoker $invoker Individual test runner.
+ * @return SimpleInvoker Wrapped test runner.
+ * @access public
+ */
+ function createInvoker($invoker) {
+ return $invoker;
+ }
+
+ /**
+ * Accessor for current status. Will be false
+ * if there have been any failures or exceptions.
+ * Used for command line tools.
+ * @return boolean True if no failures.
+ * @access public
+ */
+ function getStatus() {
+ if ($this->exceptions + $this->fails > 0) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Paints the start of a group test.
+ * @param string $test_name Name of test or other label.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($test_name, $size) {
+ }
+
+ /**
+ * Paints the end of a group test.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintGroupEnd($test_name) {
+ }
+
+ /**
+ * Paints the start of a test case.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseStart($test_name) {
+ }
+
+ /**
+ * Paints the end of a test case.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseEnd($test_name) {
+ }
+
+ /**
+ * Paints the start of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodStart($test_name) {
+ }
+
+ /**
+ * Paints the end of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodEnd($test_name) {
+ }
+
+ /**
+ * Increments the pass count.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintPass($message) {
+ $this->passes++;
+ }
+
+ /**
+ * Increments the fail count.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintFail($message) {
+ $this->fails++;
+ }
+
+ /**
+ * Deals with PHP 4 throwing an error.
+ * @param string $message Text of error formatted by
+ * the test case.
+ * @access public
+ */
+ function paintError($message) {
+ $this->exceptions++;
+ }
+
+ /**
+ * Deals with PHP 5 throwing an exception.
+ * @param Exception $exception The actual exception thrown.
+ * @access public
+ */
+ function paintException($exception) {
+ $this->exceptions++;
+ }
+
+ /**
+ * Prints the message for skipping tests.
+ * @param string $message Text of skip condition.
+ * @access public
+ */
+ function paintSkip($message) {
+ }
+
+ /**
+ * Accessor for the number of passes so far.
+ * @return integer Number of passes.
+ * @access public
+ */
+ function getPassCount() {
+ return $this->passes;
+ }
+
+ /**
+ * Accessor for the number of fails so far.
+ * @return integer Number of fails.
+ * @access public
+ */
+ function getFailCount() {
+ return $this->fails;
+ }
+
+ /**
+ * Accessor for the number of untrapped errors
+ * so far.
+ * @return integer Number of exceptions.
+ * @access public
+ */
+ function getExceptionCount() {
+ return $this->exceptions;
+ }
+
+ /**
+ * Paints a simple supplementary message.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintMessage($message) {
+ }
+
+ /**
+ * Paints a formatted ASCII message such as a
+ * privateiable dump.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ }
+
+ /**
+ * By default just ignores user generated events.
+ * @param string $type Event type as text.
+ * @param mixed $payload Message or object.
+ * @access public
+ */
+ function paintSignal($type, $payload) {
+ }
+}
+
+/**
+ * Recipient of generated test messages that can display
+ * page footers and headers. Also keeps track of the
+ * test nesting. This is the main base class on which
+ * to build the finished test (page based) displays.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleReporter extends SimpleScorer {
+ private $test_stack;
+ private $size;
+ private $progress;
+
+ /**
+ * Starts the display with no results in.
+ * @access public
+ */
+ function __construct() {
+ parent::__construct();
+ $this->test_stack = array();
+ $this->size = null;
+ $this->progress = 0;
+ }
+
+ /**
+ * Gets the formatter for small generic data items.
+ * @return SimpleDumper Formatter.
+ * @access public
+ */
+ function getDumper() {
+ return new SimpleDumper();
+ }
+
+ /**
+ * Paints the start of a group test. Will also paint
+ * the page header and footer if this is the
+ * first test. Will stash the size if the first
+ * start.
+ * @param string $test_name Name of test that is starting.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($test_name, $size) {
+ if (! isset($this->size)) {
+ $this->size = $size;
+ }
+ if (count($this->test_stack) == 0) {
+ $this->paintHeader($test_name);
+ }
+ $this->test_stack[] = $test_name;
+ }
+
+ /**
+ * Paints the end of a group test. Will paint the page
+ * footer if the stack of tests has unwound.
+ * @param string $test_name Name of test that is ending.
+ * @param integer $progress Number of test cases ending.
+ * @access public
+ */
+ function paintGroupEnd($test_name) {
+ array_pop($this->test_stack);
+ if (count($this->test_stack) == 0) {
+ $this->paintFooter($test_name);
+ }
+ }
+
+ /**
+ * Paints the start of a test case. Will also paint
+ * the page header and footer if this is the
+ * first test. Will stash the size if the first
+ * start.
+ * @param string $test_name Name of test that is starting.
+ * @access public
+ */
+ function paintCaseStart($test_name) {
+ if (! isset($this->size)) {
+ $this->size = 1;
+ }
+ if (count($this->test_stack) == 0) {
+ $this->paintHeader($test_name);
+ }
+ $this->test_stack[] = $test_name;
+ }
+
+ /**
+ * Paints the end of a test case. Will paint the page
+ * footer if the stack of tests has unwound.
+ * @param string $test_name Name of test that is ending.
+ * @access public
+ */
+ function paintCaseEnd($test_name) {
+ $this->progress++;
+ array_pop($this->test_stack);
+ if (count($this->test_stack) == 0) {
+ $this->paintFooter($test_name);
+ }
+ }
+
+ /**
+ * Paints the start of a test method.
+ * @param string $test_name Name of test that is starting.
+ * @access public
+ */
+ function paintMethodStart($test_name) {
+ $this->test_stack[] = $test_name;
+ }
+
+ /**
+ * Paints the end of a test method. Will paint the page
+ * footer if the stack of tests has unwound.
+ * @param string $test_name Name of test that is ending.
+ * @access public
+ */
+ function paintMethodEnd($test_name) {
+ array_pop($this->test_stack);
+ }
+
+ /**
+ * Paints the test document header.
+ * @param string $test_name First test top level
+ * to start.
+ * @access public
+ * @abstract
+ */
+ function paintHeader($test_name) {
+ }
+
+ /**
+ * Paints the test document footer.
+ * @param string $test_name The top level test.
+ * @access public
+ * @abstract
+ */
+ function paintFooter($test_name) {
+ }
+
+ /**
+ * Accessor for internal test stack. For
+ * subclasses that need to see the whole test
+ * history for display purposes.
+ * @return array List of methods in nesting order.
+ * @access public
+ */
+ function getTestList() {
+ return $this->test_stack;
+ }
+
+ /**
+ * Accessor for total test size in number
+ * of test cases. Null until the first
+ * test is started.
+ * @return integer Total number of cases at start.
+ * @access public
+ */
+ function getTestCaseCount() {
+ return $this->size;
+ }
+
+ /**
+ * Accessor for the number of test cases
+ * completed so far.
+ * @return integer Number of ended cases.
+ * @access public
+ */
+ function getTestCaseProgress() {
+ return $this->progress;
+ }
+
+ /**
+ * Static check for running in the comand line.
+ * @return boolean True if CLI.
+ * @access public
+ */
+ static function inCli() {
+ return php_sapi_name() == 'cli';
+ }
+}
+
+/**
+ * For modifying the behaviour of the visual reporters.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleReporterDecorator {
+ protected $reporter;
+
+ /**
+ * Mediates between the reporter and the test case.
+ * @param SimpleScorer $reporter Reporter to receive events.
+ */
+ function __construct($reporter) {
+ $this->reporter = $reporter;
+ }
+
+ /**
+ * Signals that the next evaluation will be a dry
+ * run. That is, the structure events will be
+ * recorded, but no tests will be run.
+ * @param boolean $is_dry Dry run if true.
+ * @access public
+ */
+ function makeDry($is_dry = true) {
+ $this->reporter->makeDry($is_dry);
+ }
+
+ /**
+ * Accessor for current status. Will be false
+ * if there have been any failures or exceptions.
+ * Used for command line tools.
+ * @return boolean True if no failures.
+ * @access public
+ */
+ function getStatus() {
+ return $this->reporter->getStatus();
+ }
+
+ /**
+ * The nesting of the test cases so far. Not
+ * all reporters have this facility.
+ * @return array Test list if accessible.
+ * @access public
+ */
+ function getTestList() {
+ if (method_exists($this->reporter, 'getTestList')) {
+ return $this->reporter->getTestList();
+ } else {
+ return array();
+ }
+ }
+
+ /**
+ * The reporter has a veto on what should be run.
+ * @param string $test_case_name Name of test case.
+ * @param string $method Name of test method.
+ * @return boolean True if test should be run.
+ * @access public
+ */
+ function shouldInvoke($test_case_name, $method) {
+ return $this->reporter->shouldInvoke($test_case_name, $method);
+ }
+
+ /**
+ * Can wrap the invoker in preparation for running
+ * a test.
+ * @param SimpleInvoker $invoker Individual test runner.
+ * @return SimpleInvoker Wrapped test runner.
+ * @access public
+ */
+ function createInvoker($invoker) {
+ return $this->reporter->createInvoker($invoker);
+ }
+
+ /**
+ * Gets the formatter for privateiables and other small
+ * generic data items.
+ * @return SimpleDumper Formatter.
+ * @access public
+ */
+ function getDumper() {
+ return $this->reporter->getDumper();
+ }
+
+ /**
+ * Paints the start of a group test.
+ * @param string $test_name Name of test or other label.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($test_name, $size) {
+ $this->reporter->paintGroupStart($test_name, $size);
+ }
+
+ /**
+ * Paints the end of a group test.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintGroupEnd($test_name) {
+ $this->reporter->paintGroupEnd($test_name);
+ }
+
+ /**
+ * Paints the start of a test case.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseStart($test_name) {
+ $this->reporter->paintCaseStart($test_name);
+ }
+
+ /**
+ * Paints the end of a test case.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseEnd($test_name) {
+ $this->reporter->paintCaseEnd($test_name);
+ }
+
+ /**
+ * Paints the start of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodStart($test_name) {
+ $this->reporter->paintMethodStart($test_name);
+ }
+
+ /**
+ * Paints the end of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodEnd($test_name) {
+ $this->reporter->paintMethodEnd($test_name);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintPass($message) {
+ $this->reporter->paintPass($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintFail($message) {
+ $this->reporter->paintFail($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text of error formatted by
+ * the test case.
+ * @access public
+ */
+ function paintError($message) {
+ $this->reporter->paintError($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param Exception $exception Exception to show.
+ * @access public
+ */
+ function paintException($exception) {
+ $this->reporter->paintException($exception);
+ }
+
+ /**
+ * Prints the message for skipping tests.
+ * @param string $message Text of skip condition.
+ * @access public
+ */
+ function paintSkip($message) {
+ $this->reporter->paintSkip($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintMessage($message) {
+ $this->reporter->paintMessage($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ $this->reporter->paintFormattedMessage($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $type Event type as text.
+ * @param mixed $payload Message or object.
+ * @return boolean Should return false if this
+ * type of signal should fail the
+ * test suite.
+ * @access public
+ */
+ function paintSignal($type, $payload) {
+ $this->reporter->paintSignal($type, $payload);
+ }
+}
+
+/**
+ * For sending messages to multiple reporters at
+ * the same time.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class MultipleReporter {
+ private $reporters = array();
+
+ /**
+ * Adds a reporter to the subscriber list.
+ * @param SimpleScorer $reporter Reporter to receive events.
+ * @access public
+ */
+ function attachReporter($reporter) {
+ $this->reporters[] = $reporter;
+ }
+
+ /**
+ * Signals that the next evaluation will be a dry
+ * run. That is, the structure events will be
+ * recorded, but no tests will be run.
+ * @param boolean $is_dry Dry run if true.
+ * @access public
+ */
+ function makeDry($is_dry = true) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->makeDry($is_dry);
+ }
+ }
+
+ /**
+ * Accessor for current status. Will be false
+ * if there have been any failures or exceptions.
+ * If any reporter reports a failure, the whole
+ * suite fails.
+ * @return boolean True if no failures.
+ * @access public
+ */
+ function getStatus() {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ if (! $this->reporters[$i]->getStatus()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * The reporter has a veto on what should be run.
+ * It requires all reporters to want to run the method.
+ * @param string $test_case_name name of test case.
+ * @param string $method Name of test method.
+ * @access public
+ */
+ function shouldInvoke($test_case_name, $method) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ if (! $this->reporters[$i]->shouldInvoke($test_case_name, $method)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Every reporter gets a chance to wrap the invoker.
+ * @param SimpleInvoker $invoker Individual test runner.
+ * @return SimpleInvoker Wrapped test runner.
+ * @access public
+ */
+ function createInvoker($invoker) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $invoker = $this->reporters[$i]->createInvoker($invoker);
+ }
+ return $invoker;
+ }
+
+ /**
+ * Gets the formatter for privateiables and other small
+ * generic data items.
+ * @return SimpleDumper Formatter.
+ * @access public
+ */
+ function getDumper() {
+ return new SimpleDumper();
+ }
+
+ /**
+ * Paints the start of a group test.
+ * @param string $test_name Name of test or other label.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($test_name, $size) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintGroupStart($test_name, $size);
+ }
+ }
+
+ /**
+ * Paints the end of a group test.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintGroupEnd($test_name) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintGroupEnd($test_name);
+ }
+ }
+
+ /**
+ * Paints the start of a test case.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseStart($test_name) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintCaseStart($test_name);
+ }
+ }
+
+ /**
+ * Paints the end of a test case.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseEnd($test_name) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintCaseEnd($test_name);
+ }
+ }
+
+ /**
+ * Paints the start of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodStart($test_name) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintMethodStart($test_name);
+ }
+ }
+
+ /**
+ * Paints the end of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodEnd($test_name) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintMethodEnd($test_name);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintPass($message) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintPass($message);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintFail($message) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintFail($message);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text of error formatted by
+ * the test case.
+ * @access public
+ */
+ function paintError($message) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintError($message);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param Exception $exception Exception to display.
+ * @access public
+ */
+ function paintException($exception) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintException($exception);
+ }
+ }
+
+ /**
+ * Prints the message for skipping tests.
+ * @param string $message Text of skip condition.
+ * @access public
+ */
+ function paintSkip($message) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintSkip($message);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintMessage($message) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintMessage($message);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintFormattedMessage($message);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $type Event type as text.
+ * @param mixed $payload Message or object.
+ * @return boolean Should return false if this
+ * type of signal should fail the
+ * test suite.
+ * @access public
+ */
+ function paintSignal($type, $payload) {
+ for ($i = 0; $i < count($this->reporters); $i++) {
+ $this->reporters[$i]->paintSignal($type, $payload);
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/selector.php b/3rdparty/simpletest/selector.php
new file mode 100755
index 00000000000..ba2fed312a8
--- /dev/null
+++ b/3rdparty/simpletest/selector.php
@@ -0,0 +1,141 @@
+<?php
+/**
+ * Base include file for SimpleTest.
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: selector.php 1786 2008-04-26 17:32:20Z pp11 $
+ */
+
+/**#@+
+ * include SimpleTest files
+ */
+require_once(dirname(__FILE__) . '/tag.php');
+require_once(dirname(__FILE__) . '/encoding.php');
+/**#@-*/
+
+/**
+ * Used to extract form elements for testing against.
+ * Searches by name attribute.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleByName {
+ private $name;
+
+ /**
+ * Stashes the name for later comparison.
+ * @param string $name Name attribute to match.
+ */
+ function __construct($name) {
+ $this->name = $name;
+ }
+
+ /**
+ * Accessor for name.
+ * @returns string $name Name to match.
+ */
+ function getName() {
+ return $this->name;
+ }
+
+ /**
+ * Compares with name attribute of widget.
+ * @param SimpleWidget $widget Control to compare.
+ * @access public
+ */
+ function isMatch($widget) {
+ return ($widget->getName() == $this->name);
+ }
+}
+
+/**
+ * Used to extract form elements for testing against.
+ * Searches by visible label or alt text.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleByLabel {
+ private $label;
+
+ /**
+ * Stashes the name for later comparison.
+ * @param string $label Visible text to match.
+ */
+ function __construct($label) {
+ $this->label = $label;
+ }
+
+ /**
+ * Comparison. Compares visible text of widget or
+ * related label.
+ * @param SimpleWidget $widget Control to compare.
+ * @access public
+ */
+ function isMatch($widget) {
+ if (! method_exists($widget, 'isLabel')) {
+ return false;
+ }
+ return $widget->isLabel($this->label);
+ }
+}
+
+/**
+ * Used to extract form elements for testing against.
+ * Searches dy id attribute.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleById {
+ private $id;
+
+ /**
+ * Stashes the name for later comparison.
+ * @param string $id ID atribute to match.
+ */
+ function __construct($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);
+ }
+}
+
+/**
+ * Used to extract form elements for testing against.
+ * Searches by visible label, name or alt text.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleByLabelOrName {
+ private $label;
+
+ /**
+ * Stashes the name/label for later comparison.
+ * @param string $label Visible text to match.
+ */
+ function __construct($label) {
+ $this->label = $label;
+ }
+
+ /**
+ * Comparison. Compares visible text of widget or
+ * related label or name.
+ * @param SimpleWidget $widget Control to compare.
+ * @access public
+ */
+ function isMatch($widget) {
+ if (method_exists($widget, 'isLabel')) {
+ if ($widget->isLabel($this->label)) {
+ return true;
+ }
+ }
+ return ($widget->getName() == $this->label);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/shell_tester.php b/3rdparty/simpletest/shell_tester.php
new file mode 100644
index 00000000000..9a3bd389eeb
--- /dev/null
+++ b/3rdparty/simpletest/shell_tester.php
@@ -0,0 +1,330 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: shell_tester.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/test_case.php');
+/**#@-*/
+
+/**
+ * Wrapper for exec() functionality.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleShell {
+ private $output;
+
+ /**
+ * Executes the shell comand and stashes the output.
+ * @access public
+ */
+ function __construct() {
+ $this->output = false;
+ }
+
+ /**
+ * Actually runs the command. Does not trap the
+ * error stream output as this need PHP 4.3+.
+ * @param string $command The actual command line
+ * to run.
+ * @return integer Exit code.
+ * @access public
+ */
+ function execute($command) {
+ $this->output = false;
+ exec($command, $this->output, $ret);
+ return $ret;
+ }
+
+ /**
+ * Accessor for the last output.
+ * @return string Output as text.
+ * @access public
+ */
+ function getOutput() {
+ return implode("\n", $this->output);
+ }
+
+ /**
+ * Accessor for the last output.
+ * @return array Output as array of lines.
+ * @access public
+ */
+ function getOutputAsList() {
+ return $this->output;
+ }
+}
+
+/**
+ * Test case for testing of command line scripts and
+ * utilities. Usually scripts that are external to the
+ * PHP code, but support it in some way.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class ShellTestCase extends SimpleTestCase {
+ private $current_shell;
+ private $last_status;
+ private $last_command;
+
+ /**
+ * Creates an empty test case. Should be subclassed
+ * with test methods for a functional test case.
+ * @param string $label Name of test case. Will use
+ * the class name if none specified.
+ * @access public
+ */
+ function __construct($label = false) {
+ parent::__construct($label);
+ $this->current_shell = $this->createShell();
+ $this->last_status = false;
+ $this->last_command = '';
+ }
+
+ /**
+ * Executes a command and buffers the results.
+ * @param string $command Command to run.
+ * @return boolean True if zero exit code.
+ * @access public
+ */
+ function execute($command) {
+ $shell = $this->getShell();
+ $this->last_status = $shell->execute($command);
+ $this->last_command = $command;
+ return ($this->last_status === 0);
+ }
+
+ /**
+ * Dumps the output of the last command.
+ * @access public
+ */
+ function dumpOutput() {
+ $this->dump($this->getOutput());
+ }
+
+ /**
+ * Accessor for the last output.
+ * @return string Output as text.
+ * @access public
+ */
+ function getOutput() {
+ $shell = $this->getShell();
+ return $shell->getOutput();
+ }
+
+ /**
+ * Accessor for the last output.
+ * @return array Output as array of lines.
+ * @access public
+ */
+ function getOutputAsList() {
+ $shell = $this->getShell();
+ return $shell->getOutputAsList();
+ }
+
+ /**
+ * Called from within the test methods to register
+ * passes and failures.
+ * @param boolean $result Pass on true.
+ * @param string $message Message to display describing
+ * the test state.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertTrue($result, $message = false) {
+ return $this->assert(new TrueExpectation(), $result, $message);
+ }
+
+ /**
+ * Will be true on false and vice versa. False
+ * is the PHP definition of false, so that null,
+ * empty strings, zero and an empty array all count
+ * as false.
+ * @param boolean $result Pass on false.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertFalse($result, $message = '%s') {
+ return $this->assert(new FalseExpectation(), $result, $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * the same value only. Otherwise a fail. This
+ * is for testing hand extracted text, etc.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertEqual($first, $second, $message = "%s") {
+ return $this->assert(
+ new EqualExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * a different value. Otherwise a fail. This
+ * is for testing hand extracted text, etc.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNotEqual($first, $second, $message = "%s") {
+ return $this->assert(
+ new NotEqualExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Tests the last status code from the shell.
+ * @param integer $status Expected status of last
+ * command.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertExitCode($status, $message = "%s") {
+ $message = sprintf($message, "Expected status code of [$status] from [" .
+ $this->last_command . "], but got [" .
+ $this->last_status . "]");
+ return $this->assertTrue($status === $this->last_status, $message);
+ }
+
+ /**
+ * Attempt to exactly match the combined STDERR and
+ * STDOUT output.
+ * @param string $expected Expected output.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertOutput($expected, $message = "%s") {
+ $shell = $this->getShell();
+ return $this->assert(
+ new EqualExpectation($expected),
+ $shell->getOutput(),
+ $message);
+ }
+
+ /**
+ * Scans the output for a Perl regex. If found
+ * anywhere it passes, else it fails.
+ * @param string $pattern Regex to search for.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertOutputPattern($pattern, $message = "%s") {
+ $shell = $this->getShell();
+ return $this->assert(
+ new PatternExpectation($pattern),
+ $shell->getOutput(),
+ $message);
+ }
+
+ /**
+ * If a Perl regex is found anywhere in the current
+ * output then a failure is generated, else a pass.
+ * @param string $pattern Regex to search for.
+ * @param $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoOutputPattern($pattern, $message = "%s") {
+ $shell = $this->getShell();
+ return $this->assert(
+ new NoPatternExpectation($pattern),
+ $shell->getOutput(),
+ $message);
+ }
+
+ /**
+ * File existence check.
+ * @param string $path Full filename and path.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertFileExists($path, $message = "%s") {
+ $message = sprintf($message, "File [$path] should exist");
+ return $this->assertTrue(file_exists($path), $message);
+ }
+
+ /**
+ * File non-existence check.
+ * @param string $path Full filename and path.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertFileNotExists($path, $message = "%s") {
+ $message = sprintf($message, "File [$path] should not exist");
+ return $this->assertFalse(file_exists($path), $message);
+ }
+
+ /**
+ * Scans a file for a Perl regex. If found
+ * anywhere it passes, else it fails.
+ * @param string $pattern Regex to search for.
+ * @param string $path Full filename and path.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertFilePattern($pattern, $path, $message = "%s") {
+ return $this->assert(
+ new PatternExpectation($pattern),
+ implode('', file($path)),
+ $message);
+ }
+
+ /**
+ * If a Perl regex is found anywhere in the named
+ * file then a failure is generated, else a pass.
+ * @param string $pattern Regex to search for.
+ * @param string $path Full filename and path.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoFilePattern($pattern, $path, $message = "%s") {
+ return $this->assert(
+ new NoPatternExpectation($pattern),
+ implode('', file($path)),
+ $message);
+ }
+
+ /**
+ * Accessor for current shell. Used for testing the
+ * the tester itself.
+ * @return Shell Current shell.
+ * @access protected
+ */
+ protected function getShell() {
+ return $this->current_shell;
+ }
+
+ /**
+ * Factory for the shell to run the command on.
+ * @return Shell New shell object.
+ * @access protected
+ */
+ protected function createShell() {
+ return new SimpleShell();
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/simpletest.php b/3rdparty/simpletest/simpletest.php
new file mode 100644
index 00000000000..425c869a825
--- /dev/null
+++ b/3rdparty/simpletest/simpletest.php
@@ -0,0 +1,391 @@
+<?php
+/**
+ * Global state for SimpleTest and kicker script in future versions.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: simpletest.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**#@+
+ * include SimpleTest files
+ */
+require_once(dirname(__FILE__) . '/reflection_php5.php');
+require_once(dirname(__FILE__) . '/default_reporter.php');
+require_once(dirname(__FILE__) . '/compatibility.php');
+/**#@-*/
+
+/**
+ * Registry and test context. Includes a few
+ * global options that I'm slowly getting rid of.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleTest {
+
+ /**
+ * Reads the SimpleTest version from the release file.
+ * @return string Version string.
+ */
+ static function getVersion() {
+ $content = file(dirname(__FILE__) . '/VERSION');
+ return trim($content[0]);
+ }
+
+ /**
+ * Sets the name of a test case to ignore, usually
+ * because the class is an abstract case that should
+ * @param string $class Add a class to ignore.
+ */
+ static function ignore($class) {
+ $registry = &SimpleTest::getRegistry();
+ $registry['IgnoreList'][strtolower($class)] = true;
+ }
+
+ /**
+ * Scans the now complete ignore list, and adds
+ * all parent classes to the list. If a class
+ * is not a runnable test case, then it's parents
+ * wouldn't be either. This is syntactic sugar
+ * to cut down on ommissions of ignore()'s or
+ * missing abstract declarations. This cannot
+ * be done whilst loading classes wiithout forcing
+ * a particular order on the class declarations and
+ * the ignore() calls. It's just nice to have the ignore()
+ * calls at the top of the file before the actual declarations.
+ * @param array $classes Class names of interest.
+ */
+ static function ignoreParentsIfIgnored($classes) {
+ $registry = &SimpleTest::getRegistry();
+ foreach ($classes as $class) {
+ if (SimpleTest::isIgnored($class)) {
+ $reflection = new SimpleReflection($class);
+ if ($parent = $reflection->getParent()) {
+ SimpleTest::ignore($parent);
+ }
+ }
+ }
+ }
+
+ /**
+ * Puts the object to the global pool of 'preferred' objects
+ * which can be retrieved with SimpleTest :: preferred() method.
+ * Instances of the same class are overwritten.
+ * @param object $object Preferred object
+ * @see preferred()
+ */
+ static function prefer($object) {
+ $registry = &SimpleTest::getRegistry();
+ $registry['Preferred'][] = $object;
+ }
+
+ /**
+ * Retrieves 'preferred' objects from global pool. Class filter
+ * can be applied in order to retrieve the object of the specific
+ * class
+ * @param array|string $classes Allowed classes or interfaces.
+ * @return array|object|null
+ * @see prefer()
+ */
+ static function preferred($classes) {
+ if (! is_array($classes)) {
+ $classes = array($classes);
+ }
+ $registry = &SimpleTest::getRegistry();
+ for ($i = count($registry['Preferred']) - 1; $i >= 0; $i--) {
+ foreach ($classes as $class) {
+ if (SimpleTestCompatibility::isA($registry['Preferred'][$i], $class)) {
+ return $registry['Preferred'][$i];
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Test to see if a test case is in the ignore
+ * list. Quite obviously the ignore list should
+ * be a separate object and will be one day.
+ * This method is internal to SimpleTest. Don't
+ * use it.
+ * @param string $class Class name to test.
+ * @return boolean True if should not be run.
+ */
+ static function isIgnored($class) {
+ $registry = &SimpleTest::getRegistry();
+ return isset($registry['IgnoreList'][strtolower($class)]);
+ }
+
+ /**
+ * Sets proxy to use on all requests for when
+ * testing from behind a firewall. Set host
+ * to false to disable. This will take effect
+ * if there are no other proxy settings.
+ * @param string $proxy Proxy host as URL.
+ * @param string $username Proxy username for authentication.
+ * @param string $password Proxy password for authentication.
+ */
+ static function useProxy($proxy, $username = false, $password = false) {
+ $registry = &SimpleTest::getRegistry();
+ $registry['DefaultProxy'] = $proxy;
+ $registry['DefaultProxyUsername'] = $username;
+ $registry['DefaultProxyPassword'] = $password;
+ }
+
+ /**
+ * Accessor for default proxy host.
+ * @return string Proxy URL.
+ */
+ static function getDefaultProxy() {
+ $registry = &SimpleTest::getRegistry();
+ return $registry['DefaultProxy'];
+ }
+
+ /**
+ * Accessor for default proxy username.
+ * @return string Proxy username for authentication.
+ */
+ static function getDefaultProxyUsername() {
+ $registry = &SimpleTest::getRegistry();
+ return $registry['DefaultProxyUsername'];
+ }
+
+ /**
+ * Accessor for default proxy password.
+ * @return string Proxy password for authentication.
+ */
+ static function getDefaultProxyPassword() {
+ $registry = &SimpleTest::getRegistry();
+ return $registry['DefaultProxyPassword'];
+ }
+
+ /**
+ * Accessor for default HTML parsers.
+ * @return array List of parsers to try in
+ * order until one responds true
+ * to can().
+ */
+ static function getParsers() {
+ $registry = &SimpleTest::getRegistry();
+ return $registry['Parsers'];
+ }
+
+ /**
+ * Set the list of HTML parsers to attempt to use by default.
+ * @param array $parsers List of parsers to try in
+ * order until one responds true
+ * to can().
+ */
+ static function setParsers($parsers) {
+ $registry = &SimpleTest::getRegistry();
+ $registry['Parsers'] = $parsers;
+ }
+
+ /**
+ * Accessor for global registry of options.
+ * @return hash All stored values.
+ */
+ protected static function &getRegistry() {
+ static $registry = false;
+ if (! $registry) {
+ $registry = SimpleTest::getDefaults();
+ }
+ return $registry;
+ }
+
+ /**
+ * Accessor for the context of the current
+ * test run.
+ * @return SimpleTestContext Current test run.
+ */
+ static function getContext() {
+ static $context = false;
+ if (! $context) {
+ $context = new SimpleTestContext();
+ }
+ return $context;
+ }
+
+ /**
+ * Constant default values.
+ * @return hash All registry defaults.
+ */
+ protected static function getDefaults() {
+ return array(
+ 'Parsers' => false,
+ 'MockBaseClass' => 'SimpleMock',
+ 'IgnoreList' => array(),
+ 'DefaultProxy' => false,
+ 'DefaultProxyUsername' => false,
+ 'DefaultProxyPassword' => false,
+ 'Preferred' => array(new HtmlReporter(), new TextReporter(), new XmlReporter()));
+ }
+
+ /**
+ * @deprecated
+ */
+ static function setMockBaseClass($mock_base) {
+ $registry = &SimpleTest::getRegistry();
+ $registry['MockBaseClass'] = $mock_base;
+ }
+
+ /**
+ * @deprecated
+ */
+ static function getMockBaseClass() {
+ $registry = &SimpleTest::getRegistry();
+ return $registry['MockBaseClass'];
+ }
+}
+
+/**
+ * Container for all components for a specific
+ * test run. Makes things like error queues
+ * available to PHP event handlers, and also
+ * gets around some nasty reference issues in
+ * the mocks.
+ * @package SimpleTest
+ */
+class SimpleTestContext {
+ private $test;
+ private $reporter;
+ private $resources;
+
+ /**
+ * Clears down the current context.
+ * @access public
+ */
+ function clear() {
+ $this->resources = array();
+ }
+
+ /**
+ * Sets the current test case instance. This
+ * global instance can be used by the mock objects
+ * to send message to the test cases.
+ * @param SimpleTestCase $test Test case to register.
+ */
+ function setTest($test) {
+ $this->clear();
+ $this->test = $test;
+ }
+
+ /**
+ * Accessor for currently running test case.
+ * @return SimpleTestCase Current test.
+ */
+ function getTest() {
+ return $this->test;
+ }
+
+ /**
+ * Sets the current reporter. This
+ * global instance can be used by the mock objects
+ * to send messages.
+ * @param SimpleReporter $reporter Reporter to register.
+ */
+ function setReporter($reporter) {
+ $this->clear();
+ $this->reporter = $reporter;
+ }
+
+ /**
+ * Accessor for current reporter.
+ * @return SimpleReporter Current reporter.
+ */
+ function getReporter() {
+ return $this->reporter;
+ }
+
+ /**
+ * Accessor for the Singleton resource.
+ * @return object Global resource.
+ */
+ function get($resource) {
+ if (! isset($this->resources[$resource])) {
+ $this->resources[$resource] = new $resource();
+ }
+ return $this->resources[$resource];
+ }
+}
+
+/**
+ * Interrogates the stack trace to recover the
+ * failure point.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleStackTrace {
+ private $prefixes;
+
+ /**
+ * Stashes the list of target prefixes.
+ * @param array $prefixes List of method prefixes
+ * to search for.
+ */
+ function __construct($prefixes) {
+ $this->prefixes = $prefixes;
+ }
+
+ /**
+ * Extracts the last method name that was not within
+ * Simpletest itself. Captures a stack trace if none given.
+ * @param array $stack List of stack frames.
+ * @return string Snippet of test report with line
+ * number and file.
+ */
+ function traceMethod($stack = false) {
+ $stack = $stack ? $stack : $this->captureTrace();
+ foreach ($stack as $frame) {
+ if ($this->frameLiesWithinSimpleTestFolder($frame)) {
+ continue;
+ }
+ if ($this->frameMatchesPrefix($frame)) {
+ return ' at [' . $frame['file'] . ' line ' . $frame['line'] . ']';
+ }
+ }
+ return '';
+ }
+
+ /**
+ * Test to see if error is generated by SimpleTest itself.
+ * @param array $frame PHP stack frame.
+ * @return boolean True if a SimpleTest file.
+ */
+ protected function frameLiesWithinSimpleTestFolder($frame) {
+ if (isset($frame['file'])) {
+ $path = substr(SIMPLE_TEST, 0, -1);
+ if (strpos($frame['file'], $path) === 0) {
+ if (dirname($frame['file']) == $path) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Tries to determine if the method call is an assert, etc.
+ * @param array $frame PHP stack frame.
+ * @return boolean True if matches a target.
+ */
+ protected function frameMatchesPrefix($frame) {
+ foreach ($this->prefixes as $prefix) {
+ if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Grabs a current stack trace.
+ * @return array Fulle trace.
+ */
+ protected function captureTrace() {
+ if (function_exists('debug_backtrace')) {
+ return array_reverse(debug_backtrace());
+ }
+ return array();
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/socket.php b/3rdparty/simpletest/socket.php
new file mode 100755
index 00000000000..06e8ca62d00
--- /dev/null
+++ b/3rdparty/simpletest/socket.php
@@ -0,0 +1,312 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage MockObjects
+ * @version $Id: socket.php 1953 2009-09-20 01:26:25Z jsweat $
+ */
+
+/**#@+
+ * include SimpleTest files
+ */
+require_once(dirname(__FILE__) . '/compatibility.php');
+/**#@-*/
+
+/**
+ * Stashes an error for later. Useful for constructors
+ * until PHP gets exceptions.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleStickyError {
+ private $error = 'Constructor not chained';
+
+ /**
+ * Sets the error to empty.
+ * @access public
+ */
+ function __construct() {
+ $this->clearError();
+ }
+
+ /**
+ * Test for an outstanding error.
+ * @return boolean True if there is an error.
+ * @access public
+ */
+ function isError() {
+ return ($this->error != '');
+ }
+
+ /**
+ * Accessor for an outstanding error.
+ * @return string Empty string if no error otherwise
+ * the error message.
+ * @access public
+ */
+ function getError() {
+ return $this->error;
+ }
+
+ /**
+ * Sets the internal error.
+ * @param string Error message to stash.
+ * @access protected
+ */
+ function setError($error) {
+ $this->error = $error;
+ }
+
+ /**
+ * Resets the error state to no error.
+ * @access protected
+ */
+ function clearError() {
+ $this->setError('');
+ }
+}
+
+/**
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleFileSocket extends SimpleStickyError {
+ private $handle;
+ private $is_open = false;
+ private $sent = '';
+ private $block_size;
+
+ /**
+ * Opens a socket for reading and writing.
+ * @param SimpleUrl $file Target URI to fetch.
+ * @param integer $block_size Size of chunk to read.
+ * @access public
+ */
+ function __construct($file, $block_size = 1024) {
+ parent::__construct();
+ if (! ($this->handle = $this->openFile($file, $error))) {
+ $file_string = $file->asString();
+ $this->setError("Cannot open [$file_string] with [$error]");
+ return;
+ }
+ $this->is_open = true;
+ $this->block_size = $block_size;
+ }
+
+ /**
+ * Writes some data to the socket and saves alocal copy.
+ * @param string $message String to send to socket.
+ * @return boolean True if successful.
+ * @access public
+ */
+ function write($message) {
+ return true;
+ }
+
+ /**
+ * Reads data from the socket. The error suppresion
+ * is a workaround for PHP4 always throwing a warning
+ * with a secure socket.
+ * @return integer/boolean Incoming bytes. False
+ * on error.
+ * @access public
+ */
+ function read() {
+ $raw = @fread($this->handle, $this->block_size);
+ if ($raw === false) {
+ $this->setError('Cannot read from socket');
+ $this->close();
+ }
+ return $raw;
+ }
+
+ /**
+ * Accessor for socket open state.
+ * @return boolean True if open.
+ * @access public
+ */
+ function isOpen() {
+ return $this->is_open;
+ }
+
+ /**
+ * Closes the socket preventing further reads.
+ * Cannot be reopened once closed.
+ * @return boolean True if successful.
+ * @access public
+ */
+ function close() {
+ if (!$this->is_open) return false;
+ $this->is_open = false;
+ return fclose($this->handle);
+ }
+
+ /**
+ * Accessor for content so far.
+ * @return string Bytes sent only.
+ * @access public
+ */
+ function getSent() {
+ return $this->sent;
+ }
+
+ /**
+ * Actually opens the low level socket.
+ * @param SimpleUrl $file SimpleUrl file target.
+ * @param string $error Recipient of error message.
+ * @param integer $timeout Maximum time to wait for connection.
+ * @access protected
+ */
+ protected function openFile($file, &$error) {
+ return @fopen($file->asString(), 'r');
+ }
+}
+
+/**
+ * Wrapper for TCP/IP socket.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleSocket extends SimpleStickyError {
+ private $handle;
+ private $is_open = false;
+ private $sent = '';
+ private $lock_size;
+
+ /**
+ * Opens a socket for reading and writing.
+ * @param string $host Hostname to send request to.
+ * @param integer $port Port on remote machine to open.
+ * @param integer $timeout Connection timeout in seconds.
+ * @param integer $block_size Size of chunk to read.
+ * @access public
+ */
+ function __construct($host, $port, $timeout, $block_size = 255) {
+ parent::__construct();
+ if (! ($this->handle = $this->openSocket($host, $port, $error_number, $error, $timeout))) {
+ $this->setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds");
+ return;
+ }
+ $this->is_open = true;
+ $this->block_size = $block_size;
+ SimpleTestCompatibility::setTimeout($this->handle, $timeout);
+ }
+
+ /**
+ * Writes some data to the socket and saves alocal copy.
+ * @param string $message String to send to socket.
+ * @return boolean True if successful.
+ * @access public
+ */
+ function write($message) {
+ if ($this->isError() || ! $this->isOpen()) {
+ return false;
+ }
+ $count = fwrite($this->handle, $message);
+ if (! $count) {
+ if ($count === false) {
+ $this->setError('Cannot write to socket');
+ $this->close();
+ }
+ return false;
+ }
+ fflush($this->handle);
+ $this->sent .= $message;
+ return true;
+ }
+
+ /**
+ * Reads data from the socket. The error suppresion
+ * is a workaround for PHP4 always throwing a warning
+ * with a secure socket.
+ * @return integer/boolean Incoming bytes. False
+ * on error.
+ * @access public
+ */
+ function read() {
+ if ($this->isError() || ! $this->isOpen()) {
+ return false;
+ }
+ $raw = @fread($this->handle, $this->block_size);
+ if ($raw === false) {
+ $this->setError('Cannot read from socket');
+ $this->close();
+ }
+ return $raw;
+ }
+
+ /**
+ * Accessor for socket open state.
+ * @return boolean True if open.
+ * @access public
+ */
+ function isOpen() {
+ return $this->is_open;
+ }
+
+ /**
+ * Closes the socket preventing further reads.
+ * Cannot be reopened once closed.
+ * @return boolean True if successful.
+ * @access public
+ */
+ function close() {
+ $this->is_open = false;
+ return fclose($this->handle);
+ }
+
+ /**
+ * Accessor for content so far.
+ * @return string Bytes sent only.
+ * @access public
+ */
+ function getSent() {
+ return $this->sent;
+ }
+
+ /**
+ * Actually opens the low level socket.
+ * @param string $host Host to connect to.
+ * @param integer $port Port on host.
+ * @param integer $error_number Recipient of error code.
+ * @param string $error Recipoent of error message.
+ * @param integer $timeout Maximum time to wait for connection.
+ * @access protected
+ */
+ protected function openSocket($host, $port, &$error_number, &$error, $timeout) {
+ return @fsockopen($host, $port, $error_number, $error, $timeout);
+ }
+}
+
+/**
+ * Wrapper for TCP/IP socket over TLS.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleSecureSocket extends SimpleSocket {
+
+ /**
+ * Opens a secure socket for reading and writing.
+ * @param string $host Hostname to send request to.
+ * @param integer $port Port on remote machine to open.
+ * @param integer $timeout Connection timeout in seconds.
+ * @access public
+ */
+ function __construct($host, $port, $timeout) {
+ parent::__construct($host, $port, $timeout);
+ }
+
+ /**
+ * Actually opens the low level socket.
+ * @param string $host Host to connect to.
+ * @param integer $port Port on host.
+ * @param integer $error_number Recipient of error code.
+ * @param string $error Recipient of error message.
+ * @param integer $timeout Maximum time to wait for connection.
+ * @access protected
+ */
+ function openSocket($host, $port, &$error_number, &$error, $timeout) {
+ return parent::openSocket("tls://$host", $port, $error_number, $error, $timeout);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/tag.php b/3rdparty/simpletest/tag.php
new file mode 100644
index 00000000000..afe649ec5dd
--- /dev/null
+++ b/3rdparty/simpletest/tag.php
@@ -0,0 +1,1527 @@
+<?php
+/**
+ * Base include file for SimpleTest.
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: tag.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**#@+
+ * include SimpleTest files
+ */
+require_once(dirname(__FILE__) . '/page.php');
+require_once(dirname(__FILE__) . '/encoding.php');
+/**#@-*/
+
+/**
+ * Creates tags and widgets given HTML tag
+ * attributes.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleTagBuilder {
+
+ /**
+ * Factory for the tag objects. Creates the
+ * appropriate tag object for the incoming tag name
+ * and attributes.
+ * @param string $name HTML tag name.
+ * @param hash $attributes Element attributes.
+ * @return SimpleTag Tag object.
+ * @access public
+ */
+ function createTag($name, $attributes) {
+ static $map = array(
+ 'a' => 'SimpleAnchorTag',
+ 'title' => 'SimpleTitleTag',
+ 'base' => 'SimpleBaseTag',
+ 'button' => 'SimpleButtonTag',
+ 'textarea' => 'SimpleTextAreaTag',
+ 'option' => 'SimpleOptionTag',
+ 'label' => 'SimpleLabelTag',
+ 'form' => 'SimpleFormTag',
+ 'frame' => 'SimpleFrameTag');
+ $attributes = $this->keysToLowerCase($attributes);
+ if (array_key_exists($name, $map)) {
+ $tag_class = $map[$name];
+ return new $tag_class($attributes);
+ } elseif ($name == 'select') {
+ return $this->createSelectionTag($attributes);
+ } elseif ($name == 'input') {
+ return $this->createInputTag($attributes);
+ }
+ return new SimpleTag($name, $attributes);
+ }
+
+ /**
+ * Factory for selection fields.
+ * @param hash $attributes Element attributes.
+ * @return SimpleTag Tag object.
+ * @access protected
+ */
+ 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
+ */
+ protected function createInputTag($attributes) {
+ if (! isset($attributes['type'])) {
+ return new SimpleTextTag($attributes);
+ }
+ $type = strtolower(trim($attributes['type']));
+ $map = array(
+ 'submit' => 'SimpleSubmitTag',
+ 'image' => 'SimpleImageSubmitTag',
+ 'checkbox' => 'SimpleCheckboxTag',
+ 'radio' => 'SimpleRadioButtonTag',
+ 'text' => 'SimpleTextTag',
+ 'hidden' => 'SimpleTextTag',
+ 'password' => 'SimpleTextTag',
+ 'file' => 'SimpleUploadTag');
+ if (array_key_exists($type, $map)) {
+ $tag_class = $map[$type];
+ return new $tag_class($attributes);
+ }
+ return false;
+ }
+
+ /**
+ * Make the keys lower case for case insensitive look-ups.
+ * @param hash $map Hash to convert.
+ * @return hash Unchanged values, but keys lower case.
+ * @access private
+ */
+ protected function keysToLowerCase($map) {
+ $lower = array();
+ foreach ($map as $key => $value) {
+ $lower[strtolower($key)] = $value;
+ }
+ return $lower;
+ }
+}
+
+/**
+ * HTML or XML tag.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleTag {
+ private $name;
+ private $attributes;
+ private $content;
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param string $name Tag name.
+ * @param hash $attributes Attribute names and
+ * string values. Note that
+ * the keys must have been
+ * converted to lower case.
+ */
+ function __construct($name, $attributes) {
+ $this->name = strtolower(trim($name));
+ $this->attributes = $attributes;
+ $this->content = '';
+ }
+
+ /**
+ * Check to see if the tag can have both start and
+ * end tags with content in between.
+ * @return boolean True if content allowed.
+ * @access public
+ */
+ function expectEndTag() {
+ return true;
+ }
+
+ /**
+ * The current tag should not swallow all content for
+ * itself as it's searchable page content. Private
+ * content tags are usually widgets that contain default
+ * values.
+ * @return boolean False as content is available
+ * to other tags by default.
+ * @access public
+ */
+ function isPrivateContent() {
+ return false;
+ }
+
+ /**
+ * Appends string content to the current content.
+ * @param string $content Additional text.
+ * @access public
+ */
+ function addContent($content) {
+ $this->content .= (string)$content;
+ return $this;
+ }
+
+ /**
+ * Adds an enclosed tag to the content.
+ * @param SimpleTag $tag New tag.
+ * @access public
+ */
+ function addTag($tag) {
+ }
+
+ /**
+ * Adds multiple enclosed tags to the content.
+ * @param array List of SimpleTag objects to be added.
+ */
+ function addTags($tags) {
+ foreach ($tags as $tag) {
+ $this->addTag($tag);
+ }
+ }
+
+ /**
+ * Accessor for tag name.
+ * @return string Name of tag.
+ * @access public
+ */
+ function getTagName() {
+ return $this->name;
+ }
+
+ /**
+ * List of legal child elements.
+ * @return array List of element names.
+ * @access public
+ */
+ function getChildElements() {
+ return array();
+ }
+
+ /**
+ * Accessor for an attribute.
+ * @param string $label Attribute name.
+ * @return string Attribute value.
+ * @access public
+ */
+ function getAttribute($label) {
+ $label = strtolower($label);
+ if (! isset($this->attributes[$label])) {
+ return false;
+ }
+ return (string)$this->attributes[$label];
+ }
+
+ /**
+ * Sets an attribute.
+ * @param string $label Attribute name.
+ * @return string $value New attribute value.
+ * @access protected
+ */
+ protected function setAttribute($label, $value) {
+ $this->attributes[strtolower($label)] = $value;
+ }
+
+ /**
+ * Accessor for the whole content so far.
+ * @return string Content as big raw string.
+ * @access public
+ */
+ function getContent() {
+ return $this->content;
+ }
+
+ /**
+ * Accessor for content reduced to visible text. Acts
+ * like a text mode browser, normalising space and
+ * reducing images to their alt text.
+ * @return string Content as plain text.
+ * @access public
+ */
+ function getText() {
+ return SimplePage::normalise($this->content);
+ }
+
+ /**
+ * Test to see if id attribute matches.
+ * @param string $id ID to test against.
+ * @return boolean True on match.
+ * @access public
+ */
+ function isId($id) {
+ return ($this->getAttribute('id') == $id);
+ }
+}
+
+/**
+ * Base url.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleBaseTag extends SimpleTag {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('base', $attributes);
+ }
+
+ /**
+ * Base tag is not a block tag.
+ * @return boolean false
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+}
+
+/**
+ * Page title.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleTitleTag extends SimpleTag {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('title', $attributes);
+ }
+}
+
+/**
+ * Link.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleAnchorTag extends SimpleTag {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('a', $attributes);
+ }
+
+ /**
+ * Accessor for URL as string.
+ * @return string Coerced as string.
+ * @access public
+ */
+ function getHref() {
+ $url = $this->getAttribute('href');
+ if (is_bool($url)) {
+ $url = '';
+ }
+ return $url;
+ }
+}
+
+/**
+ * Form element.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleWidget extends SimpleTag {
+ private $value;
+ private $label;
+ private $is_set;
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param string $name Tag name.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($name, $attributes) {
+ parent::__construct($name, $attributes);
+ $this->value = false;
+ $this->label = false;
+ $this->is_set = false;
+ }
+
+ /**
+ * Accessor for name submitted as the key in
+ * GET/POST privateiables hash.
+ * @return string Parsed value.
+ * @access public
+ */
+ function getName() {
+ return $this->getAttribute('name');
+ }
+
+ /**
+ * Accessor for default value parsed with the tag.
+ * @return string Parsed value.
+ * @access public
+ */
+ function getDefault() {
+ return $this->getAttribute('value');
+ }
+
+ /**
+ * Accessor for currently set value or default if
+ * none.
+ * @return string Value set by form or default
+ * if none.
+ * @access public
+ */
+ function getValue() {
+ if (! $this->is_set) {
+ return $this->getDefault();
+ }
+ return $this->value;
+ }
+
+ /**
+ * Sets the current form element value.
+ * @param string $value New value.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ $this->value = $value;
+ $this->is_set = true;
+ return true;
+ }
+
+ /**
+ * Resets the form element value back to the
+ * default.
+ * @access public
+ */
+ function resetValue() {
+ $this->is_set = false;
+ }
+
+ /**
+ * Allows setting of a label externally, say by a
+ * label tag.
+ * @param string $label Label to attach.
+ * @access public
+ */
+ function setLabel($label) {
+ $this->label = trim($label);
+ return $this;
+ }
+
+ /**
+ * Reads external or internal label.
+ * @param string $label Label to test.
+ * @return boolean True is match.
+ * @access public
+ */
+ function isLabel($label) {
+ return $this->label == trim($label);
+ }
+
+ /**
+ * Dispatches the value into the form encoded packet.
+ * @param SimpleEncoding $encoding Form packet.
+ * @access public
+ */
+ function write($encoding) {
+ if ($this->getName()) {
+ $encoding->add($this->getName(), $this->getValue());
+ }
+ }
+}
+
+/**
+ * Text, password and hidden field.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleTextTag extends SimpleWidget {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('input', $attributes);
+ if ($this->getAttribute('value') === false) {
+ $this->setAttribute('value', '');
+ }
+ }
+
+ /**
+ * Tag contains no content.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+
+ /**
+ * Sets the current form element value. Cannot
+ * change the value of a hidden field.
+ * @param string $value New value.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ if ($this->getAttribute('type') == 'hidden') {
+ return false;
+ }
+ return parent::setValue($value);
+ }
+}
+
+/**
+ * Submit button as input tag.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleSubmitTag extends SimpleWidget {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('input', $attributes);
+ if ($this->getAttribute('value') === false) {
+ $this->setAttribute('value', 'Submit');
+ }
+ }
+
+ /**
+ * Tag contains no end element.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+
+ /**
+ * Disables the setting of the button value.
+ * @param string $value Ignored.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ return false;
+ }
+
+ /**
+ * Value of browser visible text.
+ * @return string Visible label.
+ * @access public
+ */
+ function getLabel() {
+ return $this->getValue();
+ }
+
+ /**
+ * Test for a label match when searching.
+ * @param string $label Label to test.
+ * @return boolean True on match.
+ * @access public
+ */
+ function isLabel($label) {
+ return trim($label) == trim($this->getLabel());
+ }
+}
+
+/**
+ * Image button as input tag.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleImageSubmitTag extends SimpleWidget {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('input', $attributes);
+ }
+
+ /**
+ * Tag contains no end element.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+
+ /**
+ * Disables the setting of the button value.
+ * @param string $value Ignored.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ return false;
+ }
+
+ /**
+ * Value of browser visible text.
+ * @return string Visible label.
+ * @access public
+ */
+ function getLabel() {
+ if ($this->getAttribute('title')) {
+ return $this->getAttribute('title');
+ }
+ return $this->getAttribute('alt');
+ }
+
+ /**
+ * Test for a label match when searching.
+ * @param string $label Label to test.
+ * @return boolean True on match.
+ * @access public
+ */
+ function isLabel($label) {
+ return trim($label) == trim($this->getLabel());
+ }
+
+ /**
+ * Dispatches the value into the form encoded packet.
+ * @param SimpleEncoding $encoding Form packet.
+ * @param integer $x X coordinate of click.
+ * @param integer $y Y coordinate of click.
+ * @access public
+ */
+ function write($encoding, $x = 1, $y = 1) {
+ if ($this->getName()) {
+ $encoding->add($this->getName() . '.x', $x);
+ $encoding->add($this->getName() . '.y', $y);
+ } else {
+ $encoding->add('x', $x);
+ $encoding->add('y', $y);
+ }
+ }
+}
+
+/**
+ * Submit button as button tag.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleButtonTag extends SimpleWidget {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * Defaults are very browser dependent.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('button', $attributes);
+ }
+
+ /**
+ * Check to see if the tag can have both start and
+ * end tags with content in between.
+ * @return boolean True if content allowed.
+ * @access public
+ */
+ function expectEndTag() {
+ return true;
+ }
+
+ /**
+ * Disables the setting of the button value.
+ * @param string $value Ignored.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ return false;
+ }
+
+ /**
+ * Value of browser visible text.
+ * @return string Visible label.
+ * @access public
+ */
+ function getLabel() {
+ return $this->getContent();
+ }
+
+ /**
+ * Test for a label match when searching.
+ * @param string $label Label to test.
+ * @return boolean True on match.
+ * @access public
+ */
+ function isLabel($label) {
+ return trim($label) == trim($this->getLabel());
+ }
+}
+
+/**
+ * Content tag for text area.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleTextAreaTag extends SimpleWidget {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('textarea', $attributes);
+ }
+
+ /**
+ * Accessor for starting value.
+ * @return string Parsed value.
+ * @access public
+ */
+ function getDefault() {
+ return $this->wrap(html_entity_decode($this->getContent(), ENT_QUOTES));
+ }
+
+ /**
+ * Applies word wrapping if needed.
+ * @param string $value New value.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ return parent::setValue($this->wrap($value));
+ }
+
+ /**
+ * Test to see if text should be wrapped.
+ * @return boolean True if wrapping on.
+ * @access private
+ */
+ function wrapIsEnabled() {
+ if ($this->getAttribute('cols')) {
+ $wrap = $this->getAttribute('wrap');
+ if (($wrap == 'physical') || ($wrap == 'hard')) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Performs the formatting that is peculiar to
+ * this tag. There is strange behaviour in this
+ * one, including stripping a leading new line.
+ * Go figure. I am using Firefox as a guide.
+ * @param string $text Text to wrap.
+ * @return string Text wrapped with carriage
+ * returns and line feeds
+ * @access private
+ */
+ protected function wrap($text) {
+ $text = str_replace("\r\r\n", "\r\n", str_replace("\n", "\r\n", $text));
+ $text = str_replace("\r\n\n", "\r\n", str_replace("\r", "\r\n", $text));
+ if (strncmp($text, "\r\n", strlen("\r\n")) == 0) {
+ $text = substr($text, strlen("\r\n"));
+ }
+ if ($this->wrapIsEnabled()) {
+ return wordwrap(
+ $text,
+ (integer)$this->getAttribute('cols'),
+ "\r\n");
+ }
+ return $text;
+ }
+
+ /**
+ * The content of textarea is not part of the page.
+ * @return boolean True.
+ * @access public
+ */
+ function isPrivateContent() {
+ return true;
+ }
+}
+
+/**
+ * File upload widget.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleUploadTag extends SimpleWidget {
+
+ /**
+ * Starts with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('input', $attributes);
+ }
+
+ /**
+ * Tag contains no content.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+
+ /**
+ * Dispatches the value into the form encoded packet.
+ * @param SimpleEncoding $encoding Form packet.
+ * @access public
+ */
+ function write($encoding) {
+ if (! file_exists($this->getValue())) {
+ return;
+ }
+ $encoding->attach(
+ $this->getName(),
+ implode('', file($this->getValue())),
+ basename($this->getValue()));
+ }
+}
+
+/**
+ * Drop down widget.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleSelectionTag extends SimpleWidget {
+ private $options;
+ private $choice;
+
+ /**
+ * Starts with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('select', $attributes);
+ $this->options = array();
+ $this->choice = false;
+ }
+
+ /**
+ * Adds an option tag to a selection field.
+ * @param SimpleOptionTag $tag New option.
+ * @access public
+ */
+ function addTag($tag) {
+ if ($tag->getTagName() == 'option') {
+ $this->options[] = $tag;
+ }
+ }
+
+ /**
+ * Text within the selection element is ignored.
+ * @param string $content Ignored.
+ * @access public
+ */
+ function addContent($content) {
+ return $this;
+ }
+
+ /**
+ * Scans options for defaults. If none, then
+ * the first option is selected.
+ * @return string Selected field.
+ * @access public
+ */
+ function getDefault() {
+ for ($i = 0, $count = count($this->options); $i < $count; $i++) {
+ if ($this->options[$i]->getAttribute('selected') !== false) {
+ return $this->options[$i]->getDefault();
+ }
+ }
+ if ($count > 0) {
+ return $this->options[0]->getDefault();
+ }
+ return '';
+ }
+
+ /**
+ * Can only set allowed values.
+ * @param string $value New choice.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ for ($i = 0, $count = count($this->options); $i < $count; $i++) {
+ if ($this->options[$i]->isValue($value)) {
+ $this->choice = $i;
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for current selection value.
+ * @return string Value attribute or
+ * content of opton.
+ * @access public
+ */
+ function getValue() {
+ if ($this->choice === false) {
+ return $this->getDefault();
+ }
+ return $this->options[$this->choice]->getValue();
+ }
+}
+
+/**
+ * Drop down widget.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class MultipleSelectionTag extends SimpleWidget {
+ private $options;
+ private $values;
+
+ /**
+ * Starts with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('select', $attributes);
+ $this->options = array();
+ $this->values = false;
+ }
+
+ /**
+ * Adds an option tag to a selection field.
+ * @param SimpleOptionTag $tag New option.
+ * @access public
+ */
+ function addTag($tag) {
+ if ($tag->getTagName() == 'option') {
+ $this->options[] = &$tag;
+ }
+ }
+
+ /**
+ * Text within the selection element is ignored.
+ * @param string $content Ignored.
+ * @access public
+ */
+ function addContent($content) {
+ return $this;
+ }
+
+ /**
+ * Scans options for defaults to populate the
+ * value array().
+ * @return array Selected fields.
+ * @access public
+ */
+ function getDefault() {
+ $default = array();
+ for ($i = 0, $count = count($this->options); $i < $count; $i++) {
+ if ($this->options[$i]->getAttribute('selected') !== false) {
+ $default[] = $this->options[$i]->getDefault();
+ }
+ }
+ return $default;
+ }
+
+ /**
+ * Can only set allowed values. Any illegal value
+ * will result in a failure, but all correct values
+ * will be set.
+ * @param array $desired New choices.
+ * @return boolean True if all allowed.
+ * @access public
+ */
+ function setValue($desired) {
+ $achieved = array();
+ foreach ($desired as $value) {
+ $success = false;
+ for ($i = 0, $count = count($this->options); $i < $count; $i++) {
+ if ($this->options[$i]->isValue($value)) {
+ $achieved[] = $this->options[$i]->getValue();
+ $success = true;
+ break;
+ }
+ }
+ if (! $success) {
+ return false;
+ }
+ }
+ $this->values = $achieved;
+ return true;
+ }
+
+ /**
+ * Accessor for current selection value.
+ * @return array List of currently set options.
+ * @access public
+ */
+ function getValue() {
+ if ($this->values === false) {
+ return $this->getDefault();
+ }
+ return $this->values;
+ }
+}
+
+/**
+ * Option for selection field.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleOptionTag extends SimpleWidget {
+
+ /**
+ * Stashes the attributes.
+ */
+ function __construct($attributes) {
+ parent::__construct('option', $attributes);
+ }
+
+ /**
+ * Does nothing.
+ * @param string $value Ignored.
+ * @return boolean Not allowed.
+ * @access public
+ */
+ function setValue($value) {
+ return false;
+ }
+
+ /**
+ * Test to see if a value matches the option.
+ * @param string $compare Value to compare with.
+ * @return boolean True if possible match.
+ * @access public
+ */
+ function isValue($compare) {
+ $compare = trim($compare);
+ if (trim($this->getValue()) == $compare) {
+ return true;
+ }
+ return trim(strip_tags($this->getContent())) == $compare;
+ }
+
+ /**
+ * Accessor for starting value. Will be set to
+ * the option label if no value exists.
+ * @return string Parsed value.
+ * @access public
+ */
+ function getDefault() {
+ if ($this->getAttribute('value') === false) {
+ return strip_tags($this->getContent());
+ }
+ return $this->getAttribute('value');
+ }
+
+ /**
+ * The content of options is not part of the page.
+ * @return boolean True.
+ * @access public
+ */
+ function isPrivateContent() {
+ return true;
+ }
+}
+
+/**
+ * Radio button.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleRadioButtonTag extends SimpleWidget {
+
+ /**
+ * Stashes the attributes.
+ * @param array $attributes Hash of attributes.
+ */
+ function __construct($attributes) {
+ parent::__construct('input', $attributes);
+ if ($this->getAttribute('value') === false) {
+ $this->setAttribute('value', 'on');
+ }
+ }
+
+ /**
+ * Tag contains no content.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+
+ /**
+ * The only allowed value sn the one in the
+ * "value" attribute.
+ * @param string $value New value.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ if ($value === false) {
+ return parent::setValue($value);
+ }
+ if ($value != $this->getAttribute('value')) {
+ return false;
+ }
+ return parent::setValue($value);
+ }
+
+ /**
+ * Accessor for starting value.
+ * @return string Parsed value.
+ * @access public
+ */
+ function getDefault() {
+ if ($this->getAttribute('checked') !== false) {
+ return $this->getAttribute('value');
+ }
+ return false;
+ }
+}
+
+/**
+ * Checkbox widget.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleCheckboxTag extends SimpleWidget {
+
+ /**
+ * Starts with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('input', $attributes);
+ if ($this->getAttribute('value') === false) {
+ $this->setAttribute('value', 'on');
+ }
+ }
+
+ /**
+ * Tag contains no content.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+
+ /**
+ * The only allowed value in the one in the
+ * "value" attribute. The default for this
+ * attribute is "on". If this widget is set to
+ * true, then the usual value will be taken.
+ * @param string $value New value.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ if ($value === false) {
+ return parent::setValue($value);
+ }
+ if ($value === true) {
+ return parent::setValue($this->getAttribute('value'));
+ }
+ if ($value != $this->getAttribute('value')) {
+ return false;
+ }
+ return parent::setValue($value);
+ }
+
+ /**
+ * Accessor for starting value. The default
+ * value is "on".
+ * @return string Parsed value.
+ * @access public
+ */
+ function getDefault() {
+ if ($this->getAttribute('checked') !== false) {
+ return $this->getAttribute('value');
+ }
+ return false;
+ }
+}
+
+/**
+ * A group of multiple widgets with some shared behaviour.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleTagGroup {
+ private $widgets = array();
+
+ /**
+ * Adds a tag to the group.
+ * @param SimpleWidget $widget
+ * @access public
+ */
+ function addWidget($widget) {
+ $this->widgets[] = $widget;
+ }
+
+ /**
+ * Accessor to widget set.
+ * @return array All widgets.
+ * @access protected
+ */
+ protected function &getWidgets() {
+ return $this->widgets;
+ }
+
+ /**
+ * Accessor for an attribute.
+ * @param string $label Attribute name.
+ * @return boolean Always false.
+ * @access public
+ */
+ function getAttribute($label) {
+ return false;
+ }
+
+ /**
+ * Fetches the name for the widget from the first
+ * member.
+ * @return string Name of widget.
+ * @access public
+ */
+ function getName() {
+ if (count($this->widgets) > 0) {
+ return $this->widgets[0]->getName();
+ }
+ }
+
+ /**
+ * Scans the widgets for one with the appropriate
+ * ID field.
+ * @param string $id ID value to try.
+ * @return boolean True if matched.
+ * @access public
+ */
+ function isId($id) {
+ for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
+ if ($this->widgets[$i]->isId($id)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Scans the widgets for one with the appropriate
+ * attached label.
+ * @param string $label Attached label to try.
+ * @return boolean True if matched.
+ * @access public
+ */
+ function isLabel($label) {
+ for ($i = 0, $count = count($this->widgets); $i < $count; $i++) {
+ if ($this->widgets[$i]->isLabel($label)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Dispatches the value into the form encoded packet.
+ * @param SimpleEncoding $encoding Form packet.
+ * @access public
+ */
+ function write($encoding) {
+ $encoding->add($this->getName(), $this->getValue());
+ }
+}
+
+/**
+ * A group of tags with the same name within a form.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleCheckboxGroup extends SimpleTagGroup {
+
+ /**
+ * Accessor for current selected widget or false
+ * if none.
+ * @return string/array Widget values or false if none.
+ * @access public
+ */
+ function getValue() {
+ $values = array();
+ $widgets = $this->getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ if ($widgets[$i]->getValue() !== false) {
+ $values[] = $widgets[$i]->getValue();
+ }
+ }
+ return $this->coerceValues($values);
+ }
+
+ /**
+ * Accessor for starting value that is active.
+ * @return string/array Widget values or false if none.
+ * @access public
+ */
+ function getDefault() {
+ $values = array();
+ $widgets = $this->getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ if ($widgets[$i]->getDefault() !== false) {
+ $values[] = $widgets[$i]->getDefault();
+ }
+ }
+ return $this->coerceValues($values);
+ }
+
+ /**
+ * Accessor for current set values.
+ * @param string/array/boolean $values Either a single string, a
+ * hash or false for nothing set.
+ * @return boolean True if all values can be set.
+ * @access public
+ */
+ function setValue($values) {
+ $values = $this->makeArray($values);
+ if (! $this->valuesArePossible($values)) {
+ return false;
+ }
+ $widgets = $this->getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ $possible = $widgets[$i]->getAttribute('value');
+ if (in_array($widgets[$i]->getAttribute('value'), $values)) {
+ $widgets[$i]->setValue($possible);
+ } else {
+ $widgets[$i]->setValue(false);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Tests to see if a possible value set is legal.
+ * @param string/array/boolean $values Either a single string, a
+ * hash or false for nothing set.
+ * @return boolean False if trying to set a
+ * missing value.
+ * @access private
+ */
+ protected function valuesArePossible($values) {
+ $matches = array();
+ $widgets = &$this->getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ $possible = $widgets[$i]->getAttribute('value');
+ if (in_array($possible, $values)) {
+ $matches[] = $possible;
+ }
+ }
+ return ($values == $matches);
+ }
+
+ /**
+ * Converts the output to an appropriate format. This means
+ * that no values is false, a single value is just that
+ * value and only two or more are contained in an array.
+ * @param array $values List of values of widgets.
+ * @return string/array/boolean Expected format for a tag.
+ * @access private
+ */
+ protected function coerceValues($values) {
+ if (count($values) == 0) {
+ return false;
+ } elseif (count($values) == 1) {
+ return $values[0];
+ } else {
+ return $values;
+ }
+ }
+
+ /**
+ * Converts false or string into array. The opposite of
+ * the coercian method.
+ * @param string/array/boolean $value A single item is converted
+ * to a one item list. False
+ * gives an empty list.
+ * @return array List of values, possibly empty.
+ * @access private
+ */
+ protected function makeArray($value) {
+ if ($value === false) {
+ return array();
+ }
+ if (is_string($value)) {
+ return array($value);
+ }
+ return $value;
+ }
+}
+
+/**
+ * A group of tags with the same name within a form.
+ * Used for radio buttons.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleRadioGroup extends SimpleTagGroup {
+
+ /**
+ * Each tag is tried in turn until one is
+ * successfully set. The others will be
+ * unchecked if successful.
+ * @param string $value New value.
+ * @return boolean True if any allowed.
+ * @access public
+ */
+ function setValue($value) {
+ if (! $this->valueIsPossible($value)) {
+ return false;
+ }
+ $index = false;
+ $widgets = $this->getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ if (! $widgets[$i]->setValue($value)) {
+ $widgets[$i]->setValue(false);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Tests to see if a value is allowed.
+ * @param string Attempted value.
+ * @return boolean True if a valid value.
+ * @access private
+ */
+ protected function valueIsPossible($value) {
+ $widgets = $this->getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ if ($widgets[$i]->getAttribute('value') == $value) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for current selected widget or false
+ * if none.
+ * @return string/boolean Value attribute or
+ * content of opton.
+ * @access public
+ */
+ function getValue() {
+ $widgets = $this->getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ if ($widgets[$i]->getValue() !== false) {
+ return $widgets[$i]->getValue();
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for starting value that is active.
+ * @return string/boolean Value of first checked
+ * widget or false if none.
+ * @access public
+ */
+ function getDefault() {
+ $widgets = $this->getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ if ($widgets[$i]->getDefault() !== false) {
+ return $widgets[$i]->getDefault();
+ }
+ }
+ return false;
+ }
+}
+
+/**
+ * Tag to keep track of labels.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleLabelTag extends SimpleTag {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('label', $attributes);
+ }
+
+ /**
+ * Access for the ID to attach the label to.
+ * @return string For attribute.
+ * @access public
+ */
+ function getFor() {
+ return $this->getAttribute('for');
+ }
+}
+
+/**
+ * Tag to aid parsing the form.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleFormTag extends SimpleTag {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('form', $attributes);
+ }
+}
+
+/**
+ * Tag to aid parsing the frames in a page.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleFrameTag extends SimpleTag {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function __construct($attributes) {
+ parent::__construct('frame', $attributes);
+ }
+
+ /**
+ * Tag contains no content.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/acceptance_test.php b/3rdparty/simpletest/test/acceptance_test.php
new file mode 100644
index 00000000000..e96fe737e5f
--- /dev/null
+++ b/3rdparty/simpletest/test/acceptance_test.php
@@ -0,0 +1,1729 @@
+<?php
+// $Id: acceptance_test.php 2013 2011-04-29 09:29:45Z pp11 $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../compatibility.php');
+require_once(dirname(__FILE__) . '/../browser.php');
+require_once(dirname(__FILE__) . '/../web_tester.php');
+require_once(dirname(__FILE__) . '/../unit_tester.php');
+
+class SimpleTestAcceptanceTest extends WebTestCase {
+ static function samples() {
+ return 'http://www.lastcraft.com/test/';
+ }
+}
+
+class TestOfLiveBrowser extends UnitTestCase {
+ function samples() {
+ return SimpleTestAcceptanceTest::samples();
+ }
+
+ function testGet() {
+ $browser = new SimpleBrowser();
+ $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ $this->assertTrue($browser->get($this->samples() . 'network_confirm.php'));
+ $this->assertPattern('/target for the SimpleTest/', $browser->getContent());
+ $this->assertPattern('/Request method.*?<dd>GET<\/dd>/', $browser->getContent());
+ $this->assertEqual($browser->getTitle(), 'Simple test target file');
+ $this->assertEqual($browser->getResponseCode(), 200);
+ $this->assertEqual($browser->getMimeType(), 'text/html');
+ }
+
+ function testPost() {
+ $browser = new SimpleBrowser();
+ $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ $this->assertTrue($browser->post($this->samples() . 'network_confirm.php'));
+ $this->assertPattern('/target for the SimpleTest/', $browser->getContent());
+ $this->assertPattern('/Request method.*?<dd>POST<\/dd>/', $browser->getContent());
+ }
+
+ function testAbsoluteLinkFollowing() {
+ $browser = new SimpleBrowser();
+ $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ $browser->get($this->samples() . 'link_confirm.php');
+ $this->assertTrue($browser->clickLink('Absolute'));
+ $this->assertPattern('/target for the SimpleTest/', $browser->getContent());
+ }
+
+ function testRelativeEncodedLinkFollowing() {
+ $browser = new SimpleBrowser();
+ $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ $browser->get($this->samples() . 'link_confirm.php');
+ // Warning: the below data is ISO 8859-1 encoded
+ $this->assertTrue($browser->clickLink("m\xE4rc\xEAl kiek'eboe"));
+ $this->assertPattern('/target for the SimpleTest/', $browser->getContent());
+ }
+
+ function testRelativeLinkFollowing() {
+ $browser = new SimpleBrowser();
+ $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ $browser->get($this->samples() . 'link_confirm.php');
+ $this->assertTrue($browser->clickLink('Relative'));
+ $this->assertPattern('/target for the SimpleTest/', $browser->getContent());
+ }
+
+ function testUnifiedClickLinkClicking() {
+ $browser = new SimpleBrowser();
+ $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ $browser->get($this->samples() . 'link_confirm.php');
+ $this->assertTrue($browser->click('Relative'));
+ $this->assertPattern('/target for the SimpleTest/', $browser->getContent());
+ }
+
+ function testIdLinkFollowing() {
+ $browser = new SimpleBrowser();
+ $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ $browser->get($this->samples() . 'link_confirm.php');
+ $this->assertTrue($browser->clickLinkById(1));
+ $this->assertPattern('/target for the SimpleTest/', $browser->getContent());
+ }
+
+ function testCookieReading() {
+ $browser = new SimpleBrowser();
+ $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ $browser->get($this->samples() . 'set_cookies.php');
+ $this->assertEqual($browser->getCurrentCookieValue('session_cookie'), 'A');
+ $this->assertEqual($browser->getCurrentCookieValue('short_cookie'), 'B');
+ $this->assertEqual($browser->getCurrentCookieValue('day_cookie'), 'C');
+ }
+
+ function testSimpleSubmit() {
+ $browser = new SimpleBrowser();
+ $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ $browser->get($this->samples() . 'form.html');
+ $this->assertTrue($browser->clickSubmit('Go!'));
+ $this->assertPattern('/Request method.*?<dd>POST<\/dd>/', $browser->getContent());
+ $this->assertPattern('/go=\[Go!\]/', $browser->getContent());
+ }
+
+ function testUnifiedClickCanSubmit() {
+ $browser = new SimpleBrowser();
+ $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ $browser->get($this->samples() . 'form.html');
+ $this->assertTrue($browser->click('Go!'));
+ $this->assertPattern('/go=\[Go!\]/', $browser->getContent());
+ }
+}
+
+class TestOfLocalFileBrowser extends UnitTestCase {
+ function samples() {
+ return 'file://'.dirname(__FILE__).'/site/';
+ }
+
+ function testGet() {
+ $browser = new SimpleBrowser();
+ $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ $this->assertTrue($browser->get($this->samples() . 'file.html'));
+ $this->assertPattern('/Link to SimpleTest/', $browser->getContent());
+ $this->assertEqual($browser->getTitle(), 'Link to SimpleTest');
+ $this->assertFalse($browser->getResponseCode());
+ $this->assertEqual($browser->getMimeType(), '');
+ }
+}
+
+class TestOfRequestMethods extends UnitTestCase {
+ function samples() {
+ return SimpleTestAcceptanceTest::samples();
+ }
+
+ function testHeadRequest() {
+ $browser = new SimpleBrowser();
+ $this->assertTrue($browser->head($this->samples() . 'request_methods.php'));
+ $this->assertEqual($browser->getResponseCode(), 202);
+ }
+
+ function testGetRequest() {
+ $browser = new SimpleBrowser();
+ $this->assertTrue($browser->get($this->samples() . 'request_methods.php'));
+ $this->assertEqual($browser->getResponseCode(), 405);
+ }
+
+ function testPostWithPlainEncoding() {
+ $browser = new SimpleBrowser();
+ $this->assertTrue($browser->post($this->samples() . 'request_methods.php', 'A content message'));
+ $this->assertEqual($browser->getResponseCode(), 406);
+ $this->assertPattern('/Please ensure content type is an XML format/', $browser->getContent());
+ }
+
+ function testPostWithXmlEncoding() {
+ $browser = new SimpleBrowser();
+ $this->assertTrue($browser->post($this->samples() . 'request_methods.php', '<a><b>c</b></a>', 'text/xml'));
+ $this->assertEqual($browser->getResponseCode(), 201);
+ $this->assertPattern('/c/', $browser->getContent());
+ }
+
+ function testPutWithPlainEncoding() {
+ $browser = new SimpleBrowser();
+ $this->assertTrue($browser->put($this->samples() . 'request_methods.php', 'A content message'));
+ $this->assertEqual($browser->getResponseCode(), 406);
+ $this->assertPattern('/Please ensure content type is an XML format/', $browser->getContent());
+ }
+
+ function testPutWithXmlEncoding() {
+ $browser = new SimpleBrowser();
+ $this->assertTrue($browser->put($this->samples() . 'request_methods.php', '<a><b>c</b></a>', 'application/xml'));
+ $this->assertEqual($browser->getResponseCode(), 201);
+ $this->assertPattern('/c/', $browser->getContent());
+ }
+
+ function testDeleteRequest() {
+ $browser = new SimpleBrowser();
+ $browser->delete($this->samples() . 'request_methods.php');
+ $this->assertEqual($browser->getResponseCode(), 202);
+ $this->assertPattern('/Your delete request was accepted/', $browser->getContent());
+ }
+
+}
+
+class TestRadioFields extends SimpleTestAcceptanceTest {
+ function testSetFieldAsInteger() {
+ $this->get($this->samples() . 'form_with_radio_buttons.html');
+ $this->assertTrue($this->setField('tested_field', 2));
+ $this->clickSubmitByName('send');
+ $this->assertEqual($this->getUrl(), $this->samples() . 'form_with_radio_buttons.html?tested_field=2&send=click+me');
+ }
+
+ function testSetFieldAsString() {
+ $this->get($this->samples() . 'form_with_radio_buttons.html');
+ $this->assertTrue($this->setField('tested_field', '2'));
+ $this->clickSubmitByName('send');
+ $this->assertEqual($this->getUrl(), $this->samples() . 'form_with_radio_buttons.html?tested_field=2&send=click+me');
+ }
+}
+
+class TestOfLiveFetching extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testFormWithArrayBasedInputs() {
+ $this->get($this->samples() . 'form_with_array_based_inputs.php');
+ $this->setField('value[]', '3', '1');
+ $this->setField('value[]', '4', '2');
+ $this->clickSubmit('Go');
+ $this->assertPattern('/QUERY_STRING : value%5B%5D=3&value%5B%5D=4&submit=Go/');
+ }
+
+ function testFormWithQuotedValues() {
+ $this->get($this->samples() . 'form_with_quoted_values.php');
+ $this->assertField('a', 'default');
+ $this->assertFieldById('text_field', 'default');
+ $this->clickSubmit('Go');
+ $this->assertPattern('/a=default&submit=Go/');
+ }
+
+ function testGet() {
+ $this->assertTrue($this->get($this->samples() . 'network_confirm.php'));
+ $this->assertEqual($this->getUrl(), $this->samples() . 'network_confirm.php');
+ $this->assertText('target for the SimpleTest');
+ $this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
+ $this->assertTitle('Simple test target file');
+ $this->assertTitle(new PatternExpectation('/target file/'));
+ $this->assertResponse(200);
+ $this->assertMime('text/html');
+ $this->assertHeader('connection', 'close');
+ $this->assertHeader('connection', new PatternExpectation('/los/'));
+ }
+
+ function testSlowGet() {
+ $this->assertTrue($this->get($this->samples() . 'slow_page.php'));
+ }
+
+ function testTimedOutGet() {
+ $this->setConnectionTimeout(1);
+ $this->ignoreErrors();
+ $this->assertFalse($this->get($this->samples() . 'slow_page.php'));
+ }
+
+ function testPost() {
+ $this->assertTrue($this->post($this->samples() . 'network_confirm.php'));
+ $this->assertText('target for the SimpleTest');
+ $this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
+ }
+
+ function testGetWithData() {
+ $this->get($this->samples() . 'network_confirm.php', array("a" => "aaa"));
+ $this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
+ $this->assertText('a=[aaa]');
+ }
+
+ function testPostWithData() {
+ $this->post($this->samples() . 'network_confirm.php', array("a" => "aaa"));
+ $this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
+ $this->assertText('a=[aaa]');
+ }
+
+ function testPostWithRecursiveData() {
+ $this->post($this->samples() . 'network_confirm.php', array("a" => "aaa"));
+ $this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
+ $this->assertText('a=[aaa]');
+
+ $this->post($this->samples() . 'network_confirm.php', array("a[aa]" => "aaa"));
+ $this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
+ $this->assertText('a=[aa=[aaa]]');
+
+ $this->post($this->samples() . 'network_confirm.php', array("a[aa][aaa]" => "aaaa"));
+ $this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
+ $this->assertText('a=[aa=[aaa=[aaaa]]]');
+
+ $this->post($this->samples() . 'network_confirm.php', array("a" => array("aa" => "aaa")));
+ $this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
+ $this->assertText('a=[aa=[aaa]]');
+
+ $this->post($this->samples() . 'network_confirm.php', array("a" => array("aa" => array("aaa" => "aaaa"))));
+ $this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
+ $this->assertText('a=[aa=[aaa=[aaaa]]]');
+ }
+
+ function testRelativeGet() {
+ $this->get($this->samples() . 'link_confirm.php');
+ $this->assertTrue($this->get('network_confirm.php'));
+ $this->assertText('target for the SimpleTest');
+ }
+
+ function testRelativePost() {
+ $this->post($this->samples() . 'link_confirm.php', array('a' => '123'));
+ $this->assertTrue($this->post('network_confirm.php'));
+ $this->assertText('target for the SimpleTest');
+ }
+}
+
+class TestOfLinkFollowing extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testLinkAssertions() {
+ $this->get($this->samples() . 'link_confirm.php');
+ $this->assertLink('Absolute', $this->samples() . 'network_confirm.php');
+ $this->assertLink('Absolute', new PatternExpectation('/confirm/'));
+ $this->assertClickable('Absolute');
+ }
+
+ function testAbsoluteLinkFollowing() {
+ $this->get($this->samples() . 'link_confirm.php');
+ $this->assertTrue($this->clickLink('Absolute'));
+ $this->assertText('target for the SimpleTest');
+ }
+
+ function testRelativeLinkFollowing() {
+ $this->get($this->samples() . 'link_confirm.php');
+ $this->assertTrue($this->clickLink('Relative'));
+ $this->assertText('target for the SimpleTest');
+ }
+
+ function testLinkIdFollowing() {
+ $this->get($this->samples() . 'link_confirm.php');
+ $this->assertLinkById(1);
+ $this->assertTrue($this->clickLinkById(1));
+ $this->assertText('target for the SimpleTest');
+ }
+
+ function testAbsoluteUrlBehavesAbsolutely() {
+ $this->get($this->samples() . 'link_confirm.php');
+ $this->get('http://www.lastcraft.com');
+ $this->assertText('No guarantee of quality is given or even intended');
+ }
+
+ function testRelativeUrlRespectsBaseTag() {
+ $this->get($this->samples() . 'base_tag/base_link.html');
+ $this->click('Back to test pages');
+ $this->assertTitle('Simple test target file');
+ }
+}
+
+class TestOfLivePageLinkingWithMinimalLinks extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testClickToExplicitelyNamedSelfReturns() {
+ $this->get($this->samples() . 'front_controller_style/a_page.php');
+ $this->assertEqual($this->getUrl(), $this->samples() . 'front_controller_style/a_page.php');
+ $this->assertTitle('Simple test page with links');
+ $this->assertLink('Self');
+ $this->clickLink('Self');
+ $this->assertTitle('Simple test page with links');
+ }
+
+ function testClickToMissingPageReturnsToSamePage() {
+ $this->get($this->samples() . 'front_controller_style/a_page.php');
+ $this->clickLink('No page');
+ $this->assertTitle('Simple test page with links');
+ $this->assertText('[action=no_page]');
+ }
+
+ function testClickToBareActionReturnsToSamePage() {
+ $this->get($this->samples() . 'front_controller_style/a_page.php');
+ $this->clickLink('Bare action');
+ $this->assertTitle('Simple test page with links');
+ $this->assertText('[action=]');
+ }
+
+ function testClickToSingleQuestionMarkReturnsToSamePage() {
+ $this->get($this->samples() . 'front_controller_style/a_page.php');
+ $this->clickLink('Empty query');
+ $this->assertTitle('Simple test page with links');
+ }
+
+ function testClickToEmptyStringReturnsToSamePage() {
+ $this->get($this->samples() . 'front_controller_style/a_page.php');
+ $this->clickLink('Empty link');
+ $this->assertTitle('Simple test page with links');
+ }
+
+ function testClickToSingleDotGoesToCurrentDirectory() {
+ $this->get($this->samples() . 'front_controller_style/a_page.php');
+ $this->clickLink('Current directory');
+ $this->assertTitle(
+ 'Simple test front controller',
+ '%s -> index.php needs to be set as a default web server home page');
+ }
+
+ function testClickBackADirectoryLevel() {
+ $this->get($this->samples() . 'front_controller_style/');
+ $this->clickLink('Down one');
+ $this->assertPattern('|Index of .*?/test|i');
+ }
+}
+
+class TestOfLiveFrontControllerEmulation extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testJumpToNamedPage() {
+ $this->get($this->samples() . 'front_controller_style/');
+ $this->assertText('Simple test front controller');
+ $this->clickLink('Index');
+ $this->assertResponse(200);
+ $this->assertText('[action=index]');
+ }
+
+ function testJumpToUnnamedPage() {
+ $this->get($this->samples() . 'front_controller_style/');
+ $this->clickLink('No page');
+ $this->assertResponse(200);
+ $this->assertText('Simple test front controller');
+ $this->assertText('[action=no_page]');
+ }
+
+ function testJumpToUnnamedPageWithBareParameter() {
+ $this->get($this->samples() . 'front_controller_style/');
+ $this->clickLink('Bare action');
+ $this->assertResponse(200);
+ $this->assertText('Simple test front controller');
+ $this->assertText('[action=]');
+ }
+
+ function testJumpToUnnamedPageWithEmptyQuery() {
+ $this->get($this->samples() . 'front_controller_style/');
+ $this->clickLink('Empty query');
+ $this->assertResponse(200);
+ $this->assertPattern('/Simple test front controller/');
+ $this->assertPattern('/raw get data.*?\[\].*?get data/si');
+ }
+
+ function testJumpToUnnamedPageWithEmptyLink() {
+ $this->get($this->samples() . 'front_controller_style/');
+ $this->clickLink('Empty link');
+ $this->assertResponse(200);
+ $this->assertPattern('/Simple test front controller/');
+ $this->assertPattern('/raw get data.*?\[\].*?get data/si');
+ }
+
+ function testJumpBackADirectoryLevel() {
+ $this->get($this->samples() . 'front_controller_style/');
+ $this->clickLink('Down one');
+ $this->assertPattern('|Index of .*?/test|');
+ }
+
+ function testSubmitToNamedPage() {
+ $this->get($this->samples() . 'front_controller_style/');
+ $this->assertText('Simple test front controller');
+ $this->clickSubmit('Index');
+ $this->assertResponse(200);
+ $this->assertText('[action=Index]');
+ }
+
+ function testSubmitToSameDirectory() {
+ $this->get($this->samples() . 'front_controller_style/index.php');
+ $this->clickSubmit('Same directory');
+ $this->assertResponse(200);
+ $this->assertText('[action=Same+directory]');
+ }
+
+ function testSubmitToEmptyAction() {
+ $this->get($this->samples() . 'front_controller_style/index.php');
+ $this->clickSubmit('Empty action');
+ $this->assertResponse(200);
+ $this->assertText('[action=Empty+action]');
+ }
+
+ function testSubmitToNoAction() {
+ $this->get($this->samples() . 'front_controller_style/index.php');
+ $this->clickSubmit('No action');
+ $this->assertResponse(200);
+ $this->assertText('[action=No+action]');
+ }
+
+ function testSubmitBackADirectoryLevel() {
+ $this->get($this->samples() . 'front_controller_style/');
+ $this->clickSubmit('Down one');
+ $this->assertPattern('|Index of .*?/test|');
+ }
+
+ function testSubmitToNamedPageWithMixedPostAndGet() {
+ $this->get($this->samples() . 'front_controller_style/?a=A');
+ $this->assertText('Simple test front controller');
+ $this->clickSubmit('Index post');
+ $this->assertText('action=[Index post]');
+ $this->assertNoText('[a=A]');
+ }
+
+ function testSubmitToSameDirectoryMixedPostAndGet() {
+ $this->get($this->samples() . 'front_controller_style/index.php?a=A');
+ $this->clickSubmit('Same directory post');
+ $this->assertText('action=[Same directory post]');
+ $this->assertNoText('[a=A]');
+ }
+
+ function testSubmitToEmptyActionMixedPostAndGet() {
+ $this->get($this->samples() . 'front_controller_style/index.php?a=A');
+ $this->clickSubmit('Empty action post');
+ $this->assertText('action=[Empty action post]');
+ $this->assertText('[a=A]');
+ }
+
+ function testSubmitToNoActionMixedPostAndGet() {
+ $this->get($this->samples() . 'front_controller_style/index.php?a=A');
+ $this->clickSubmit('No action post');
+ $this->assertText('action=[No action post]');
+ $this->assertText('[a=A]');
+ }
+}
+
+class TestOfLiveHeaders extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testConfirmingHeaderExistence() {
+ $this->get('http://www.lastcraft.com/');
+ $this->assertHeader('content-type');
+ $this->assertHeader('content-type', 'text/html');
+ $this->assertHeader('content-type', new PatternExpectation('/HTML/i'));
+ $this->assertNoHeader('WWW-Authenticate');
+ }
+}
+
+class TestOfLiveRedirects extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testNoRedirects() {
+ $this->setMaximumRedirects(0);
+ $this->get($this->samples() . 'redirect.php');
+ $this->assertTitle('Redirection test');
+ }
+
+ function testRedirects() {
+ $this->setMaximumRedirects(1);
+ $this->get($this->samples() . 'redirect.php');
+ $this->assertTitle('Simple test target file');
+ }
+
+ function testRedirectLosesGetData() {
+ $this->get($this->samples() . 'redirect.php', array('a' => 'aaa'));
+ $this->assertNoText('a=[aaa]');
+ }
+
+ function testRedirectKeepsExtraRequestDataOfItsOwn() {
+ $this->get($this->samples() . 'redirect.php');
+ $this->assertText('r=[rrr]');
+ }
+
+ function testRedirectLosesPostData() {
+ $this->post($this->samples() . 'redirect.php', array('a' => 'aaa'));
+ $this->assertTitle('Simple test target file');
+ $this->assertNoText('a=[aaa]');
+ }
+
+ function testRedirectWithBaseUrlChange() {
+ $this->get($this->samples() . 'base_change_redirect.php');
+ $this->assertTitle('Simple test target file in folder');
+ $this->get($this->samples() . 'path/base_change_redirect.php');
+ $this->assertTitle('Simple test target file');
+ }
+
+ function testRedirectWithDoubleBaseUrlChange() {
+ $this->get($this->samples() . 'double_base_change_redirect.php');
+ $this->assertTitle('Simple test target file');
+ }
+}
+
+class TestOfLiveCookies extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function here() {
+ return new SimpleUrl($this->samples());
+ }
+
+ function thisHost() {
+ $here = $this->here();
+ return $here->getHost();
+ }
+
+ function thisPath() {
+ $here = $this->here();
+ return $here->getPath();
+ }
+
+ function testCookieSettingAndAssertions() {
+ $this->setCookie('a', 'Test cookie a');
+ $this->setCookie('b', 'Test cookie b', $this->thisHost());
+ $this->setCookie('c', 'Test cookie c', $this->thisHost(), $this->thisPath());
+ $this->get($this->samples() . 'network_confirm.php');
+ $this->assertText('Test cookie a');
+ $this->assertText('Test cookie b');
+ $this->assertText('Test cookie c');
+ $this->assertCookie('a');
+ $this->assertCookie('b', 'Test cookie b');
+ $this->assertTrue($this->getCookie('c') == 'Test cookie c');
+ }
+
+ function testNoCookieSetWhenCookiesDisabled() {
+ $this->setCookie('a', 'Test cookie a');
+ $this->ignoreCookies();
+ $this->get($this->samples() . 'network_confirm.php');
+ $this->assertNoText('Test cookie a');
+ }
+
+ function testCookieReading() {
+ $this->get($this->samples() . 'set_cookies.php');
+ $this->assertCookie('session_cookie', 'A');
+ $this->assertCookie('short_cookie', 'B');
+ $this->assertCookie('day_cookie', 'C');
+ }
+
+ function testNoCookie() {
+ $this->assertNoCookie('aRandomCookie');
+ }
+
+ function testNoCookieReadingWhenCookiesDisabled() {
+ $this->ignoreCookies();
+ $this->get($this->samples() . 'set_cookies.php');
+ $this->assertNoCookie('session_cookie');
+ $this->assertNoCookie('short_cookie');
+ $this->assertNoCookie('day_cookie');
+ }
+
+ function testCookiePatternAssertions() {
+ $this->get($this->samples() . 'set_cookies.php');
+ $this->assertCookie('session_cookie', new PatternExpectation('/a/i'));
+ }
+
+ function testTemporaryCookieExpiry() {
+ $this->get($this->samples() . 'set_cookies.php');
+ $this->restart();
+ $this->assertNoCookie('session_cookie');
+ $this->assertCookie('day_cookie', 'C');
+ }
+
+ function testTimedCookieExpiryWith100SecondMargin() {
+ $this->get($this->samples() . 'set_cookies.php');
+ $this->ageCookies(3600);
+ $this->restart(time() + 100);
+ $this->assertNoCookie('session_cookie');
+ $this->assertNoCookie('hour_cookie');
+ $this->assertCookie('day_cookie', 'C');
+ }
+
+ function testNoClockOverDriftBy100Seconds() {
+ $this->get($this->samples() . 'set_cookies.php');
+ $this->restart(time() + 200);
+ $this->assertNoCookie(
+ 'short_cookie',
+ '%s -> Please check your computer clock setting if you are not using NTP');
+ }
+
+ function testNoClockUnderDriftBy100Seconds() {
+ $this->get($this->samples() . 'set_cookies.php');
+ $this->restart(time() + 0);
+ $this->assertCookie(
+ 'short_cookie',
+ 'B',
+ '%s -> Please check your computer clock setting if you are not using NTP');
+ }
+
+ function testCookiePath() {
+ $this->get($this->samples() . 'set_cookies.php');
+ $this->assertNoCookie('path_cookie', 'D');
+ $this->get('./path/show_cookies.php');
+ $this->assertPattern('/path_cookie/');
+ $this->assertCookie('path_cookie', 'D');
+ }
+}
+
+class LiveTestOfForms extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testSimpleSubmit() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertTrue($this->clickSubmit('Go!'));
+ $this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
+ $this->assertText('go=[Go!]');
+ }
+
+ function testDefaultFormValues() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertFieldByName('a', '');
+ $this->assertFieldByName('b', 'Default text');
+ $this->assertFieldByName('c', '');
+ $this->assertFieldByName('d', 'd1');
+ $this->assertFieldByName('e', false);
+ $this->assertFieldByName('f', 'on');
+ $this->assertFieldByName('g', 'g3');
+ $this->assertFieldByName('h', 2);
+ $this->assertFieldByName('go', 'Go!');
+ $this->assertClickable('Go!');
+ $this->assertSubmit('Go!');
+ $this->assertTrue($this->clickSubmit('Go!'));
+ $this->assertText('go=[Go!]');
+ $this->assertText('a=[]');
+ $this->assertText('b=[Default text]');
+ $this->assertText('c=[]');
+ $this->assertText('d=[d1]');
+ $this->assertNoText('e=[');
+ $this->assertText('f=[on]');
+ $this->assertText('g=[g3]');
+ }
+
+ function testFormSubmissionByButtonLabel() {
+ $this->get($this->samples() . 'form.html');
+ $this->setFieldByName('a', 'aaa');
+ $this->setFieldByName('b', 'bbb');
+ $this->setFieldByName('c', 'ccc');
+ $this->setFieldByName('d', 'D2');
+ $this->setFieldByName('e', 'on');
+ $this->setFieldByName('f', false);
+ $this->setFieldByName('g', 'g2');
+ $this->setFieldByName('h', 1);
+ $this->assertTrue($this->clickSubmit('Go!'));
+ $this->assertText('a=[aaa]');
+ $this->assertText('b=[bbb]');
+ $this->assertText('c=[ccc]');
+ $this->assertText('d=[d2]');
+ $this->assertText('e=[on]');
+ $this->assertNoText('f=[');
+ $this->assertText('g=[g2]');
+ }
+
+ function testAdditionalFormValues() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertTrue($this->clickSubmit('Go!', array('add' => 'A')));
+ $this->assertText('go=[Go!]');
+ $this->assertText('add=[A]');
+ }
+
+ function testFormSubmissionByName() {
+ $this->get($this->samples() . 'form.html');
+ $this->setFieldByName('a', 'A');
+ $this->assertTrue($this->clickSubmitByName('go'));
+ $this->assertText('a=[A]');
+ }
+
+ function testFormSubmissionByNameAndAdditionalParameters() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertTrue($this->clickSubmitByName('go', array('add' => 'A')));
+ $this->assertText('go=[Go!]');
+ $this->assertText('add=[A]');
+ }
+
+ function testFormSubmissionBySubmitButtonLabeledSubmit() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertTrue($this->clickSubmitByName('test'));
+ $this->assertText('test=[Submit]');
+ }
+
+ function testFormSubmissionWithIds() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertFieldById(1, '');
+ $this->assertFieldById(2, 'Default text');
+ $this->assertFieldById(3, '');
+ $this->assertFieldById(4, 'd1');
+ $this->assertFieldById(5, false);
+ $this->assertFieldById(6, 'on');
+ $this->assertFieldById(8, 'g3');
+ $this->assertFieldById(11, 2);
+ $this->setFieldById(1, 'aaa');
+ $this->setFieldById(2, 'bbb');
+ $this->setFieldById(3, 'ccc');
+ $this->setFieldById(4, 'D2');
+ $this->setFieldById(5, 'on');
+ $this->setFieldById(6, false);
+ $this->setFieldById(8, 'g2');
+ $this->setFieldById(11, 'H1');
+ $this->assertTrue($this->clickSubmitById(99));
+ $this->assertText('a=[aaa]');
+ $this->assertText('b=[bbb]');
+ $this->assertText('c=[ccc]');
+ $this->assertText('d=[d2]');
+ $this->assertText('e=[on]');
+ $this->assertNoText('f=[');
+ $this->assertText('g=[g2]');
+ $this->assertText('h=[1]');
+ $this->assertText('go=[Go!]');
+ }
+
+ function testFormSubmissionWithIdsAndAdditionnalData() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertTrue($this->clickSubmitById(99, array('additionnal' => "data")));
+ $this->assertText('additionnal=[data]');
+ }
+
+ function testFormSubmissionWithLabels() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertField('Text A', '');
+ $this->assertField('Text B', 'Default text');
+ $this->assertField('Text area C', '');
+ $this->assertField('Selection D', 'd1');
+ $this->assertField('Checkbox E', false);
+ $this->assertField('Checkbox F', 'on');
+ $this->assertField('3', 'g3');
+ $this->assertField('Selection H', 2);
+ $this->setField('Text A', 'aaa');
+ $this->setField('Text B', 'bbb');
+ $this->setField('Text area C', 'ccc');
+ $this->setField('Selection D', 'D2');
+ $this->setField('Checkbox E', 'on');
+ $this->setField('Checkbox F', false);
+ $this->setField('2', 'g2');
+ $this->setField('Selection H', 'H1');
+ $this->clickSubmit('Go!');
+ $this->assertText('a=[aaa]');
+ $this->assertText('b=[bbb]');
+ $this->assertText('c=[ccc]');
+ $this->assertText('d=[d2]');
+ $this->assertText('e=[on]');
+ $this->assertNoText('f=[');
+ $this->assertText('g=[g2]');
+ $this->assertText('h=[1]');
+ $this->assertText('go=[Go!]');
+ }
+
+ function testSettingCheckboxWithBooleanTrueSetsUnderlyingValue() {
+ $this->get($this->samples() . 'form.html');
+ $this->setField('Checkbox E', true);
+ $this->assertField('Checkbox E', 'on');
+ $this->clickSubmit('Go!');
+ $this->assertText('e=[on]');
+ }
+
+ function testFormSubmissionWithMixedPostAndGet() {
+ $this->get($this->samples() . 'form_with_mixed_post_and_get.html');
+ $this->setField('Text A', 'Hello');
+ $this->assertTrue($this->clickSubmit('Go!'));
+ $this->assertText('a=[Hello]');
+ $this->assertText('x=[X]');
+ $this->assertText('y=[Y]');
+ }
+
+ function testFormSubmissionWithMixedPostAndEncodedGet() {
+ $this->get($this->samples() . 'form_with_mixed_post_and_get.html');
+ $this->setField('Text B', 'Hello');
+ $this->assertTrue($this->clickSubmit('Go encoded!'));
+ $this->assertText('b=[Hello]');
+ $this->assertText('x=[X]');
+ $this->assertText('y=[Y]');
+ }
+
+ function testFormSubmissionWithoutAction() {
+ $this->get($this->samples() . 'form_without_action.php?test=test');
+ $this->assertText('_GET : [test]');
+ $this->assertTrue($this->clickSubmit('Submit Post With Empty Action'));
+ $this->assertText('_GET : [test]');
+ $this->assertText('_POST : [test]');
+ }
+
+ function testImageSubmissionByLabel() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertImage('Image go!');
+ $this->assertTrue($this->clickImage('Image go!', 10, 12));
+ $this->assertText('go_x=[10]');
+ $this->assertText('go_y=[12]');
+ }
+
+ function testImageSubmissionByLabelWithAdditionalParameters() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertTrue($this->clickImage('Image go!', 10, 12, array('add' => 'A')));
+ $this->assertText('add=[A]');
+ }
+
+ function testImageSubmissionByName() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertTrue($this->clickImageByName('go', 10, 12));
+ $this->assertText('go_x=[10]');
+ $this->assertText('go_y=[12]');
+ }
+
+ function testImageSubmissionById() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertTrue($this->clickImageById(97, 10, 12));
+ $this->assertText('go_x=[10]');
+ $this->assertText('go_y=[12]');
+ }
+
+ function testButtonSubmissionByLabel() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertTrue($this->clickSubmit('Button go!', 10, 12));
+ $this->assertPattern('/go=\[ButtonGo\]/s');
+ }
+
+ function testNamelessSubmitSendsNoValue() {
+ $this->get($this->samples() . 'form_with_unnamed_submit.html');
+ $this->click('Go!');
+ $this->assertNoText('Go!');
+ $this->assertNoText('submit');
+ }
+
+ function testNamelessImageSendsXAndYValues() {
+ $this->get($this->samples() . 'form_with_unnamed_submit.html');
+ $this->clickImage('Image go!', 4, 5);
+ $this->assertNoText('ImageGo');
+ $this->assertText('x=[4]');
+ $this->assertText('y=[5]');
+ }
+
+ function testNamelessButtonSendsNoValue() {
+ $this->get($this->samples() . 'form_with_unnamed_submit.html');
+ $this->click('Button Go!');
+ $this->assertNoText('ButtonGo');
+ }
+
+ function testSelfSubmit() {
+ $this->get($this->samples() . 'self_form.php');
+ $this->assertNoText('[Submitted]');
+ $this->assertNoText('[Wrong form]');
+ $this->assertTrue($this->clickSubmit());
+ $this->assertText('[Submitted]');
+ $this->assertNoText('[Wrong form]');
+ $this->assertTitle('Test of form self submission');
+ }
+
+ function testSelfSubmitWithParameters() {
+ $this->get($this->samples() . 'self_form.php');
+ $this->setFieldByName('visible', 'Resent');
+ $this->assertTrue($this->clickSubmit());
+ $this->assertText('[Resent]');
+ }
+
+ function testSettingOfBlankOption() {
+ $this->get($this->samples() . 'form.html');
+ $this->assertTrue($this->setFieldByName('d', ''));
+ $this->clickSubmit('Go!');
+ $this->assertText('d=[]');
+ }
+
+ function testAssertingFieldValueWithPattern() {
+ $this->get($this->samples() . 'form.html');
+ $this->setField('c', 'A very long string');
+ $this->assertField('c', new PatternExpectation('/very long/'));
+ }
+
+ function testSendingMultipartFormDataEncodedForm() {
+ $this->get($this->samples() . 'form_data_encoded_form.html');
+ $this->assertField('Text A', '');
+ $this->assertField('Text B', 'Default text');
+ $this->assertField('Text area C', '');
+ $this->assertField('Selection D', 'd1');
+ $this->assertField('Checkbox E', false);
+ $this->assertField('Checkbox F', 'on');
+ $this->assertField('3', 'g3');
+ $this->assertField('Selection H', 2);
+ $this->setField('Text A', 'aaa');
+ $this->setField('Text B', 'bbb');
+ $this->setField('Text area C', 'ccc');
+ $this->setField('Selection D', 'D2');
+ $this->setField('Checkbox E', 'on');
+ $this->setField('Checkbox F', false);
+ $this->setField('2', 'g2');
+ $this->setField('Selection H', 'H1');
+ $this->assertTrue($this->clickSubmit('Go!'));
+ $this->assertText('a=[aaa]');
+ $this->assertText('b=[bbb]');
+ $this->assertText('c=[ccc]');
+ $this->assertText('d=[d2]');
+ $this->assertText('e=[on]');
+ $this->assertNoText('f=[');
+ $this->assertText('g=[g2]');
+ $this->assertText('h=[1]');
+ $this->assertText('go=[Go!]');
+ }
+
+ function testSettingVariousBlanksInFields() {
+ $this->get($this->samples() . 'form_with_false_defaults.html');
+ $this->assertField('Text A', '');
+ $this->setField('Text A', '0');
+ $this->assertField('Text A', '0');
+ $this->assertField('Text area B', '');
+ $this->setField('Text area B', '0');
+ $this->assertField('Text area B', '0');
+ $this->assertField('Selection D', '');
+ $this->setField('Selection D', 'D2');
+ $this->assertField('Selection D', 'D2');
+ $this->setField('Selection D', 'D3');
+ $this->assertField('Selection D', '0');
+ $this->setField('Selection D', 'D4');
+ $this->assertField('Selection D', '?');
+ $this->assertField('Checkbox E', '');
+ $this->assertField('Checkbox F', 'on');
+ $this->assertField('Checkbox G', '0');
+ $this->assertField('Checkbox H', '?');
+ $this->assertFieldByName('i', 'on');
+ $this->setFieldByName('i', '');
+ $this->assertFieldByName('i', '');
+ $this->setFieldByName('i', '0');
+ $this->assertFieldByName('i', '0');
+ $this->setFieldByName('i', '?');
+ $this->assertFieldByName('i', '?');
+ }
+
+ function testDefaultValueOfTextareaHasNewlinesAndWhitespacePreserved() {
+ $this->get($this->samples() . 'form_with_false_defaults.html');
+ $this->assertField('Text area C', ' ');
+ }
+
+ function chars($t) {
+ for ($i = 0; $i < strlen($t); $i++) {
+ print "[$t[$i]]";
+ }
+ }
+
+ function testSubmissionOfBlankFields() {
+ $this->get($this->samples() . 'form_with_false_defaults.html');
+ $this->setField('Text A', '');
+ $this->setField('Text area B', '');
+ $this->setFieldByName('i', '');
+ $this->click('Go!');
+ $this->assertText('a=[]');
+ $this->assertText('b=[]');
+ $this->assertText('d=[]');
+ $this->assertText('e=[]');
+ $this->assertText('i=[]');
+ }
+
+ function testDefaultValueOfTextareaHasNewlinesAndWhitespacePreservedOnSubmission() {
+ $this->get($this->samples() . 'form_with_false_defaults.html');
+ $this->click('Go!');
+ $this->assertPattern('/c=\[ \]/');
+ }
+
+ function testSubmissionOfEmptyValues() {
+ $this->get($this->samples() . 'form_with_false_defaults.html');
+ $this->setField('Selection D', 'D2');
+ $this->click('Go!');
+ $this->assertText('a=[]');
+ $this->assertText('b=[]');
+ $this->assertText('d=[D2]');
+ $this->assertText('f=[on]');
+ $this->assertText('i=[on]');
+ }
+
+ function testSubmissionOfZeroes() {
+ $this->get($this->samples() . 'form_with_false_defaults.html');
+ $this->setField('Text A', '0');
+ $this->setField('Text area B', '0');
+ $this->setField('Selection D', 'D3');
+ $this->setFieldByName('i', '0');
+ $this->click('Go!');
+ $this->assertText('a=[0]');
+ $this->assertText('b=[0]');
+ $this->assertText('d=[0]');
+ $this->assertText('g=[0]');
+ $this->assertText('i=[0]');
+ }
+
+ function testSubmissionOfQuestionMarks() {
+ $this->get($this->samples() . 'form_with_false_defaults.html');
+ $this->setField('Text A', '?');
+ $this->setField('Text area B', '?');
+ $this->setField('Selection D', 'D4');
+ $this->setFieldByName('i', '?');
+ $this->click('Go!');
+ $this->assertText('a=[?]');
+ $this->assertText('b=[?]');
+ $this->assertText('d=[?]');
+ $this->assertText('h=[?]');
+ $this->assertText('i=[?]');
+ }
+
+ function testSubmissionOfHtmlEncodedValues() {
+ $this->get($this->samples() . 'form_with_tricky_defaults.html');
+ $this->assertField('Text A', '&\'"<>');
+ $this->assertField('Text B', '"');
+ $this->assertField('Text area C', '&\'"<>');
+ $this->assertField('Selection D', "'");
+ $this->assertField('Checkbox E', '&\'"<>');
+ $this->assertField('Checkbox F', false);
+ $this->assertFieldByname('i', "'");
+ $this->click('Go!');
+ $this->assertText('a=[&\'"<>, "]');
+ $this->assertText('c=[&\'"<>]');
+ $this->assertText("d=[']");
+ $this->assertText('e=[&\'"<>]');
+ $this->assertText("i=[']");
+ }
+
+ function testFormActionRespectsBaseTag() {
+ $this->get($this->samples() . 'base_tag/form.html');
+ $this->assertTrue($this->clickSubmit('Go!'));
+ $this->assertText('go=[Go!]');
+ $this->assertText('a=[]');
+ }
+}
+
+class TestOfLiveMultiValueWidgets extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testDefaultFormValueSubmission() {
+ $this->get($this->samples() . 'multiple_widget_form.html');
+ $this->assertFieldByName('a', array('a2', 'a3'));
+ $this->assertFieldByName('b', array('b2', 'b3'));
+ $this->assertFieldByName('c[]', array('c2', 'c3'));
+ $this->assertFieldByName('d', array('2', '3'));
+ $this->assertFieldByName('e', array('2', '3'));
+ $this->assertTrue($this->clickSubmit('Go!'));
+ $this->assertText('a=[a2, a3]');
+ $this->assertText('b=[b2, b3]');
+ $this->assertText('c=[c2, c3]');
+ $this->assertText('d=[2, 3]');
+ $this->assertText('e=[2, 3]');
+ }
+
+ function testSubmittingMultipleValues() {
+ $this->get($this->samples() . 'multiple_widget_form.html');
+ $this->setFieldByName('a', array('a1', 'a4'));
+ $this->assertFieldByName('a', array('a1', 'a4'));
+ $this->assertFieldByName('a', array('a4', 'a1'));
+ $this->setFieldByName('b', array('b1', 'b4'));
+ $this->assertFieldByName('b', array('b1', 'b4'));
+ $this->setFieldByName('c[]', array('c1', 'c4'));
+ $this->assertField('c[]', array('c1', 'c4'));
+ $this->setFieldByName('d', array('1', '4'));
+ $this->assertField('d', array('1', '4'));
+ $this->setFieldByName('e', array('e1', 'e4'));
+ $this->assertField('e', array('1', '4'));
+ $this->assertTrue($this->clickSubmit('Go!'));
+ $this->assertText('a=[a1, a4]');
+ $this->assertText('b=[b1, b4]');
+ $this->assertText('c=[c1, c4]');
+ $this->assertText('d=[1, 4]');
+ $this->assertText('e=[1, 4]');
+ }
+
+ function testSettingByOptionValue() {
+ $this->get($this->samples() . 'multiple_widget_form.html');
+ $this->setFieldByName('d', array('1', '4'));
+ $this->assertField('d', array('1', '4'));
+ $this->assertTrue($this->clickSubmit('Go!'));
+ $this->assertText('d=[1, 4]');
+ }
+
+ function testSubmittingMultipleValuesByLabel() {
+ $this->get($this->samples() . 'multiple_widget_form.html');
+ $this->setField('Multiple selection A', array('a1', 'a4'));
+ $this->assertField('Multiple selection A', array('a1', 'a4'));
+ $this->assertField('Multiple selection A', array('a4', 'a1'));
+ $this->setField('multiple selection C', array('c1', 'c4'));
+ $this->assertField('multiple selection C', array('c1', 'c4'));
+ $this->assertTrue($this->clickSubmit('Go!'));
+ $this->assertText('a=[a1, a4]');
+ $this->assertText('c=[c1, c4]');
+ }
+
+ function testSavantStyleHiddenFieldDefaults() {
+ $this->get($this->samples() . 'savant_style_form.html');
+ $this->assertFieldByName('a', array('a0'));
+ $this->assertFieldByName('b', array('b0'));
+ $this->assertTrue($this->clickSubmit('Go!'));
+ $this->assertText('a=[a0]');
+ $this->assertText('b=[b0]');
+ }
+
+ function testSavantStyleHiddenDefaultsAreOverridden() {
+ $this->get($this->samples() . 'savant_style_form.html');
+ $this->assertTrue($this->setFieldByName('a', array('a1')));
+ $this->assertTrue($this->setFieldByName('b', 'b1'));
+ $this->assertTrue($this->clickSubmit('Go!'));
+ $this->assertText('a=[a1]');
+ $this->assertText('b=[b1]');
+ }
+
+ function testSavantStyleFormSettingById() {
+ $this->get($this->samples() . 'savant_style_form.html');
+ $this->assertFieldById(1, array('a0'));
+ $this->assertFieldById(4, array('b0'));
+ $this->assertTrue($this->setFieldById(2, 'a1'));
+ $this->assertTrue($this->setFieldById(5, 'b1'));
+ $this->assertTrue($this->clickSubmitById(99));
+ $this->assertText('a=[a1]');
+ $this->assertText('b=[b1]');
+ }
+}
+
+class TestOfFileUploads extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testSingleFileUpload() {
+ $this->get($this->samples() . 'upload_form.html');
+ $this->assertTrue($this->setField('Content:',
+ dirname(__FILE__) . '/support/upload_sample.txt'));
+ $this->assertField('Content:', dirname(__FILE__) . '/support/upload_sample.txt');
+ $this->click('Go!');
+ $this->assertText('Sample for testing file upload');
+ }
+
+ function testMultipleFileUpload() {
+ $this->get($this->samples() . 'upload_form.html');
+ $this->assertTrue($this->setField('Content:',
+ dirname(__FILE__) . '/support/upload_sample.txt'));
+ $this->assertTrue($this->setField('Supplemental:',
+ dirname(__FILE__) . '/support/supplementary_upload_sample.txt'));
+ $this->assertField('Supplemental:',
+ dirname(__FILE__) . '/support/supplementary_upload_sample.txt');
+ $this->click('Go!');
+ $this->assertText('Sample for testing file upload');
+ $this->assertText('Some more text content');
+ }
+
+ function testBinaryFileUpload() {
+ $this->get($this->samples() . 'upload_form.html');
+ $this->assertTrue($this->setField('Content:',
+ dirname(__FILE__) . '/support/latin1_sample'));
+ $this->click('Go!');
+ $this->assertText(
+ implode('', file(dirname(__FILE__) . '/support/latin1_sample')));
+ }
+}
+
+class TestOfLiveHistoryNavigation extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testRetry() {
+ $this->get($this->samples() . 'cookie_based_counter.php');
+ $this->assertPattern('/count: 1/i');
+ $this->retry();
+ $this->assertPattern('/count: 2/i');
+ $this->retry();
+ $this->assertPattern('/count: 3/i');
+ }
+
+ function testOfBackButton() {
+ $this->get($this->samples() . '1.html');
+ $this->clickLink('2');
+ $this->assertTitle('2');
+ $this->assertTrue($this->back());
+ $this->assertTitle('1');
+ $this->assertTrue($this->forward());
+ $this->assertTitle('2');
+ $this->assertFalse($this->forward());
+ }
+
+ function testGetRetryResubmitsData() {
+ $this->assertTrue($this->get(
+ $this->samples() . 'network_confirm.php?a=aaa'));
+ $this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
+ $this->assertText('a=[aaa]');
+ $this->retry();
+ $this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
+ $this->assertText('a=[aaa]');
+ }
+
+ function testGetRetryResubmitsExtraData() {
+ $this->assertTrue($this->get(
+ $this->samples() . 'network_confirm.php',
+ array('a' => 'aaa')));
+ $this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
+ $this->assertText('a=[aaa]');
+ $this->retry();
+ $this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
+ $this->assertText('a=[aaa]');
+ }
+
+ function testPostRetryResubmitsData() {
+ $this->assertTrue($this->post(
+ $this->samples() . 'network_confirm.php',
+ array('a' => 'aaa')));
+ $this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
+ $this->assertText('a=[aaa]');
+ $this->retry();
+ $this->assertPattern('/Request method.*?<dd>POST<\/dd>/');
+ $this->assertText('a=[aaa]');
+ }
+
+ function testGetRetryResubmitsRepeatedData() {
+ $this->assertTrue($this->get(
+ $this->samples() . 'network_confirm.php?a=1&a=2'));
+ $this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
+ $this->assertText('a=[1, 2]');
+ $this->retry();
+ $this->assertPattern('/Request method.*?<dd>GET<\/dd>/');
+ $this->assertText('a=[1, 2]');
+ }
+}
+
+class TestOfLiveAuthentication extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testChallengeFromProtectedPage() {
+ $this->get($this->samples() . 'protected/');
+ $this->assertResponse(401);
+ $this->assertAuthentication('Basic');
+ $this->assertRealm('SimpleTest basic authentication');
+ $this->assertRealm(new PatternExpectation('/simpletest/i'));
+ $this->authenticate('test', 'secret');
+ $this->assertResponse(200);
+ $this->retry();
+ $this->assertResponse(200);
+ }
+
+ function testTrailingSlashImpliedWithinRealm() {
+ $this->get($this->samples() . 'protected/');
+ $this->authenticate('test', 'secret');
+ $this->assertResponse(200);
+ $this->get($this->samples() . 'protected');
+ $this->assertResponse(200);
+ }
+
+ function testTrailingSlashImpliedSettingRealm() {
+ $this->get($this->samples() . 'protected');
+ $this->authenticate('test', 'secret');
+ $this->assertResponse(200);
+ $this->get($this->samples() . 'protected/');
+ $this->assertResponse(200);
+ }
+
+ function testEncodedAuthenticationFetchesPage() {
+ $this->get('http://test:secret@www.lastcraft.com/test/protected/');
+ $this->assertResponse(200);
+ }
+
+ function testEncodedAuthenticationFetchesPageAfterTrailingSlashRedirect() {
+ $this->get('http://test:secret@www.lastcraft.com/test/protected');
+ $this->assertResponse(200);
+ }
+
+ function testRealmExtendsToWholeDirectory() {
+ $this->get($this->samples() . 'protected/1.html');
+ $this->authenticate('test', 'secret');
+ $this->clickLink('2');
+ $this->assertResponse(200);
+ $this->clickLink('3');
+ $this->assertResponse(200);
+ }
+
+ function testRedirectKeepsAuthentication() {
+ $this->get($this->samples() . 'protected/local_redirect.php');
+ $this->authenticate('test', 'secret');
+ $this->assertTitle('Simple test target file');
+ }
+
+ function testRedirectKeepsEncodedAuthentication() {
+ $this->get('http://test:secret@www.lastcraft.com/test/protected/local_redirect.php');
+ $this->assertResponse(200);
+ $this->assertTitle('Simple test target file');
+ }
+
+ function testSessionRestartLosesAuthentication() {
+ $this->get($this->samples() . 'protected/');
+ $this->authenticate('test', 'secret');
+ $this->assertResponse(200);
+ $this->restart();
+ $this->get($this->samples() . 'protected/');
+ $this->assertResponse(401);
+ }
+}
+
+class TestOfLoadingFrames extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testNoFramesContentWhenFramesDisabled() {
+ $this->ignoreFrames();
+ $this->get($this->samples() . 'one_page_frameset.html');
+ $this->assertTitle('Frameset for testing of SimpleTest');
+ $this->assertText('This content is for no frames only');
+ }
+
+ function testPatternMatchCanReadTheOnlyFrame() {
+ $this->get($this->samples() . 'one_page_frameset.html');
+ $this->assertText('A target for the SimpleTest test suite');
+ $this->assertNoText('This content is for no frames only');
+ }
+
+ function testMessyFramesetResponsesByName() {
+ $this->assertTrue($this->get(
+ $this->samples() . 'messy_frameset.html'));
+ $this->assertTitle('Frameset for testing of SimpleTest');
+
+ $this->assertTrue($this->setFrameFocus('Front controller'));
+ $this->assertResponse(200);
+ $this->assertText('Simple test front controller');
+
+ $this->assertTrue($this->setFrameFocus('One'));
+ $this->assertResponse(200);
+ $this->assertLink('2');
+
+ $this->assertTrue($this->setFrameFocus('Frame links'));
+ $this->assertResponse(200);
+ $this->assertLink('Set one to 2');
+
+ $this->assertTrue($this->setFrameFocus('Counter'));
+ $this->assertResponse(200);
+ $this->assertText('Count: 1');
+
+ $this->assertTrue($this->setFrameFocus('Redirected'));
+ $this->assertResponse(200);
+ $this->assertText('r=rrr');
+
+ $this->assertTrue($this->setFrameFocus('Protected'));
+ $this->assertResponse(401);
+
+ $this->assertTrue($this->setFrameFocus('Protected redirect'));
+ $this->assertResponse(401);
+
+ $this->assertTrue($this->setFrameFocusByIndex(1));
+ $this->assertResponse(200);
+ $this->assertText('Simple test front controller');
+
+ $this->assertTrue($this->setFrameFocusByIndex(2));
+ $this->assertResponse(200);
+ $this->assertLink('2');
+
+ $this->assertTrue($this->setFrameFocusByIndex(3));
+ $this->assertResponse(200);
+ $this->assertLink('Set one to 2');
+
+ $this->assertTrue($this->setFrameFocusByIndex(4));
+ $this->assertResponse(200);
+ $this->assertText('Count: 1');
+
+ $this->assertTrue($this->setFrameFocusByIndex(5));
+ $this->assertResponse(200);
+ $this->assertText('r=rrr');
+
+ $this->assertTrue($this->setFrameFocusByIndex(6));
+ $this->assertResponse(401);
+
+ $this->assertTrue($this->setFrameFocusByIndex(7));
+ }
+
+ function testReloadingFramesetPage() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->assertText('Count: 1');
+ $this->retry();
+ $this->assertText('Count: 2');
+ $this->retry();
+ $this->assertText('Count: 3');
+ }
+
+ function testReloadingSingleFrameWithCookieCounter() {
+ $this->get($this->samples() . 'counting_frameset.html');
+ $this->setFrameFocus('a');
+ $this->assertText('Count: 1');
+ $this->setFrameFocus('b');
+ $this->assertText('Count: 2');
+
+ $this->setFrameFocus('a');
+ $this->retry();
+ $this->assertText('Count: 3');
+ $this->retry();
+ $this->assertText('Count: 4');
+ $this->setFrameFocus('b');
+ $this->assertText('Count: 2');
+ }
+
+ function testReloadingFrameWhenUnfocusedReloadsWholeFrameset() {
+ $this->get($this->samples() . 'counting_frameset.html');
+ $this->setFrameFocus('a');
+ $this->assertText('Count: 1');
+ $this->setFrameFocus('b');
+ $this->assertText('Count: 2');
+
+ $this->clearFrameFocus('a');
+ $this->retry();
+
+ $this->assertTitle('Frameset for testing of SimpleTest');
+ $this->setFrameFocus('a');
+ $this->assertText('Count: 3');
+ $this->setFrameFocus('b');
+ $this->assertText('Count: 4');
+ }
+
+ function testClickingNormalLinkReplacesJustThatFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->clickLink('2');
+ $this->assertLink('3');
+ $this->assertText('Simple test front controller');
+ }
+
+ function testJumpToNamedPageReplacesJustThatFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->assertPattern('/Simple test front controller/');
+ $this->clickLink('Index');
+ $this->assertResponse(200);
+ $this->assertText('[action=index]');
+ $this->assertText('Count: 1');
+ }
+
+ function testJumpToUnnamedPageReplacesJustThatFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->clickLink('No page');
+ $this->assertResponse(200);
+ $this->assertText('Simple test front controller');
+ $this->assertText('[action=no_page]');
+ $this->assertText('Count: 1');
+ }
+
+ function testJumpToUnnamedPageWithBareParameterReplacesJustThatFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->clickLink('Bare action');
+ $this->assertResponse(200);
+ $this->assertText('Simple test front controller');
+ $this->assertText('[action=]');
+ $this->assertText('Count: 1');
+ }
+
+ function testJumpToUnnamedPageWithEmptyQueryReplacesJustThatFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->clickLink('Empty query');
+ $this->assertResponse(200);
+ $this->assertPattern('/Simple test front controller/');
+ $this->assertPattern('/raw get data.*?\[\].*?get data/si');
+ $this->assertPattern('/Count: 1/');
+ }
+
+ function testJumpToUnnamedPageWithEmptyLinkReplacesJustThatFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->clickLink('Empty link');
+ $this->assertResponse(200);
+ $this->assertPattern('/Simple test front controller/');
+ $this->assertPattern('/raw get data.*?\[\].*?get data/si');
+ $this->assertPattern('/Count: 1/');
+ }
+
+ function testJumpBackADirectoryLevelReplacesJustThatFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->clickLink('Down one');
+ $this->assertPattern('/index of .*\/test/i');
+ $this->assertPattern('/Count: 1/');
+ }
+
+ function testSubmitToNamedPageReplacesJustThatFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->assertPattern('/Simple test front controller/');
+ $this->clickSubmit('Index');
+ $this->assertResponse(200);
+ $this->assertText('[action=Index]');
+ $this->assertText('Count: 1');
+ }
+
+ function testSubmitToSameDirectoryReplacesJustThatFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->clickSubmit('Same directory');
+ $this->assertResponse(200);
+ $this->assertText('[action=Same+directory]');
+ $this->assertText('Count: 1');
+ }
+
+ function testSubmitToEmptyActionReplacesJustThatFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->clickSubmit('Empty action');
+ $this->assertResponse(200);
+ $this->assertText('[action=Empty+action]');
+ $this->assertText('Count: 1');
+ }
+
+ function testSubmitToNoActionReplacesJustThatFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->clickSubmit('No action');
+ $this->assertResponse(200);
+ $this->assertText('[action=No+action]');
+ $this->assertText('Count: 1');
+ }
+
+ function testSubmitBackADirectoryLevelReplacesJustThatFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->clickSubmit('Down one');
+ $this->assertPattern('/index of .*\/test/i');
+ $this->assertPattern('/Count: 1/');
+ }
+
+ function testTopLinkExitsFrameset() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->clickLink('Exit the frameset');
+ $this->assertTitle('Simple test target file');
+ }
+
+ function testLinkInOnePageCanLoadAnother() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->assertNoLink('3');
+ $this->clickLink('Set one to 2');
+ $this->assertLink('3');
+ $this->assertNoLink('2');
+ $this->assertTitle('Frameset for testing of SimpleTest');
+ }
+
+ function testFrameWithRelativeLinksRespectsBaseTagForThatPage() {
+ $this->get($this->samples() . 'base_tag/frameset.html');
+ $this->click('Back to test pages');
+ $this->assertTitle('Frameset for testing of SimpleTest');
+ $this->assertText('A target for the SimpleTest test suite');
+ }
+
+ function testRelativeLinkInFrameIsNotAffectedByFramesetBaseTag() {
+ $this->get($this->samples() . 'base_tag/frameset_with_base_tag.html');
+ $this->assertText('This is page 1');
+ $this->click('To page 2');
+ $this->assertTitle('Frameset for testing of SimpleTest');
+ $this->assertText('This is page 2');
+ }
+}
+
+class TestOfFrameAuthentication extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testUnauthenticatedFrameSendsChallenge() {
+ $this->get($this->samples() . 'protected/');
+ $this->setFrameFocus('Protected');
+ $this->assertAuthentication('Basic');
+ $this->assertRealm('SimpleTest basic authentication');
+ $this->assertResponse(401);
+ }
+
+ function testCanReadFrameFromAlreadyAuthenticatedRealm() {
+ $this->get($this->samples() . 'protected/');
+ $this->authenticate('test', 'secret');
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->setFrameFocus('Protected');
+ $this->assertResponse(200);
+ $this->assertText('A target for the SimpleTest test suite');
+ }
+
+ function testCanAuthenticateFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->setFrameFocus('Protected');
+ $this->authenticate('test', 'secret');
+ $this->assertResponse(200);
+ $this->assertText('A target for the SimpleTest test suite');
+ $this->clearFrameFocus();
+ $this->assertText('Count: 1');
+ }
+
+ function testCanAuthenticateRedirectedFrame() {
+ $this->get($this->samples() . 'messy_frameset.html');
+ $this->setFrameFocus('Protected redirect');
+ $this->assertResponse(401);
+ $this->authenticate('test', 'secret');
+ $this->assertResponse(200);
+ $this->assertText('A target for the SimpleTest test suite');
+ $this->clearFrameFocus();
+ $this->assertText('Count: 1');
+ }
+}
+
+class TestOfNestedFrames extends SimpleTestAcceptanceTest {
+ function setUp() {
+ $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion());
+ }
+
+ function testCanNavigateToSpecificContent() {
+ $this->get($this->samples() . 'nested_frameset.html');
+ $this->assertTitle('Nested frameset for testing of SimpleTest');
+
+ $this->assertPattern('/This is frame A/');
+ $this->assertPattern('/This is frame B/');
+ $this->assertPattern('/Simple test front controller/');
+ $this->assertLink('2');
+ $this->assertLink('Set one to 2');
+ $this->assertPattern('/Count: 1/');
+ $this->assertPattern('/r=rrr/');
+
+ $this->setFrameFocus('pair');
+ $this->assertPattern('/This is frame A/');
+ $this->assertPattern('/This is frame B/');
+ $this->assertNoPattern('/Simple test front controller/');
+ $this->assertNoLink('2');
+
+ $this->setFrameFocus('aaa');
+ $this->assertPattern('/This is frame A/');
+ $this->assertNoPattern('/This is frame B/');
+
+ $this->clearFrameFocus();
+ $this->assertResponse(200);
+ $this->setFrameFocus('messy');
+ $this->assertResponse(200);
+ $this->setFrameFocus('Front controller');
+ $this->assertResponse(200);
+ $this->assertPattern('/Simple test front controller/');
+ $this->assertNoLink('2');
+ }
+
+ function testReloadingFramesetPage() {
+ $this->get($this->samples() . 'nested_frameset.html');
+ $this->assertPattern('/Count: 1/');
+ $this->retry();
+ $this->assertPattern('/Count: 2/');
+ $this->retry();
+ $this->assertPattern('/Count: 3/');
+ }
+
+ function testRetryingNestedPageOnlyRetriesThatSet() {
+ $this->get($this->samples() . 'nested_frameset.html');
+ $this->assertPattern('/Count: 1/');
+ $this->setFrameFocus('messy');
+ $this->retry();
+ $this->assertPattern('/Count: 2/');
+ $this->setFrameFocus('Counter');
+ $this->retry();
+ $this->assertPattern('/Count: 3/');
+
+ $this->clearFrameFocus();
+ $this->setFrameFocus('messy');
+ $this->setFrameFocus('Front controller');
+ $this->retry();
+
+ $this->clearFrameFocus();
+ $this->assertPattern('/Count: 3/');
+ }
+
+ function testAuthenticatingNestedPage() {
+ $this->get($this->samples() . 'nested_frameset.html');
+ $this->setFrameFocus('messy');
+ $this->setFrameFocus('Protected');
+ $this->assertAuthentication('Basic');
+ $this->assertRealm('SimpleTest basic authentication');
+ $this->assertResponse(401);
+
+ $this->authenticate('test', 'secret');
+ $this->assertResponse(200);
+ $this->assertPattern('/A target for the SimpleTest test suite/');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/adapter_test.php b/3rdparty/simpletest/test/adapter_test.php
new file mode 100755
index 00000000000..c1a06a2f653
--- /dev/null
+++ b/3rdparty/simpletest/test/adapter_test.php
@@ -0,0 +1,50 @@
+<?php
+// $Id: adapter_test.php 1748 2008-04-14 01:50:41Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../extensions/pear_test_case.php');
+
+class SameTestClass {
+}
+
+class TestOfPearAdapter extends PHPUnit_TestCase {
+
+ function testBoolean() {
+ $this->assertTrue(true, "PEAR true");
+ $this->assertFalse(false, "PEAR false");
+ }
+
+ function testName() {
+ $this->assertTrue($this->getName() == get_class($this));
+ }
+
+ function testPass() {
+ $this->pass("PEAR pass");
+ }
+
+ function testNulls() {
+ $value = null;
+ $this->assertNull($value, "PEAR null");
+ $value = 0;
+ $this->assertNotNull($value, "PEAR not null");
+ }
+
+ function testType() {
+ $this->assertType("Hello", "string", "PEAR type");
+ }
+
+ function testEquals() {
+ $this->assertEquals(12, 12, "PEAR identity");
+ $this->setLooselyTyped(true);
+ $this->assertEquals("12", 12, "PEAR equality");
+ }
+
+ function testSame() {
+ $same = new SameTestClass();
+ $this->assertSame($same, $same, "PEAR same");
+ }
+
+ function testRegExp() {
+ $this->assertRegExp('/hello/', "A big hello from me", "PEAR regex");
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/all_tests.php b/3rdparty/simpletest/test/all_tests.php
new file mode 100755
index 00000000000..99ce9451e32
--- /dev/null
+++ b/3rdparty/simpletest/test/all_tests.php
@@ -0,0 +1,13 @@
+<?php
+require_once(dirname(__FILE__) . '/../autorun.php');
+
+class AllTests extends TestSuite {
+ function AllTests() {
+ $this->TestSuite('All tests for SimpleTest ' . SimpleTest::getVersion());
+ $this->addFile(dirname(__FILE__) . '/unit_tests.php');
+ $this->addFile(dirname(__FILE__) . '/shell_test.php');
+ $this->addFile(dirname(__FILE__) . '/live_test.php');
+ $this->addFile(dirname(__FILE__) . '/acceptance_test.php');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/arguments_test.php b/3rdparty/simpletest/test/arguments_test.php
new file mode 100755
index 00000000000..0cca4e99b24
--- /dev/null
+++ b/3rdparty/simpletest/test/arguments_test.php
@@ -0,0 +1,82 @@
+<?php
+// $Id: cookies_test.php 1506 2007-05-07 00:58:03Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../arguments.php');
+
+class TestOfCommandLineArgumentParsing extends UnitTestCase {
+ function testArgumentListWithJustProgramNameGivesFalseToEveryName() {
+ $arguments = new SimpleArguments(array('me'));
+ $this->assertIdentical($arguments->a, false);
+ $this->assertIdentical($arguments->all(), array());
+ }
+
+ function testSingleArgumentNameRecordedAsTrue() {
+ $arguments = new SimpleArguments(array('me', '-a'));
+ $this->assertIdentical($arguments->a, true);
+ }
+
+ function testSingleArgumentCanBeGivenAValue() {
+ $arguments = new SimpleArguments(array('me', '-a=AAA'));
+ $this->assertIdentical($arguments->a, 'AAA');
+ }
+
+ function testSingleArgumentCanBeGivenSpaceSeparatedValue() {
+ $arguments = new SimpleArguments(array('me', '-a', 'AAA'));
+ $this->assertIdentical($arguments->a, 'AAA');
+ }
+
+ function testWillBuildArrayFromRepeatedValue() {
+ $arguments = new SimpleArguments(array('me', '-a', 'A', '-a', 'AA'));
+ $this->assertIdentical($arguments->a, array('A', 'AA'));
+ }
+
+ function testWillBuildArrayFromMultiplyRepeatedValues() {
+ $arguments = new SimpleArguments(array('me', '-a', 'A', '-a', 'AA', '-a', 'AAA'));
+ $this->assertIdentical($arguments->a, array('A', 'AA', 'AAA'));
+ }
+
+ function testCanParseLongFormArguments() {
+ $arguments = new SimpleArguments(array('me', '--aa=AA', '--bb', 'BB'));
+ $this->assertIdentical($arguments->aa, 'AA');
+ $this->assertIdentical($arguments->bb, 'BB');
+ }
+
+ function testGetsFullSetOfResultsAsHash() {
+ $arguments = new SimpleArguments(array('me', '-a', '-b=1', '-b', '2', '--aa=AA', '--bb', 'BB', '-c'));
+ $this->assertEqual($arguments->all(),
+ array('a' => true, 'b' => array('1', '2'), 'aa' => 'AA', 'bb' => 'BB', 'c' => true));
+ }
+}
+
+class TestOfHelpOutput extends UnitTestCase {
+ function testDisplaysGeneralHelpBanner() {
+ $help = new SimpleHelp('Cool program');
+ $this->assertEqual($help->render(), "Cool program\n");
+ }
+
+ function testDisplaysOnlySingleLineEndings() {
+ $help = new SimpleHelp("Cool program\n");
+ $this->assertEqual($help->render(), "Cool program\n");
+ }
+
+ function testDisplaysHelpOnShortFlag() {
+ $help = new SimpleHelp('Cool program');
+ $help->explainFlag('a', 'Enables A');
+ $this->assertEqual($help->render(), "Cool program\n-a Enables A\n");
+ }
+
+ function testHasAtleastFourSpacesAfterLongestFlag() {
+ $help = new SimpleHelp('Cool program');
+ $help->explainFlag('a', 'Enables A');
+ $help->explainFlag('long', 'Enables Long');
+ $this->assertEqual($help->render(),
+ "Cool program\n-a Enables A\n--long Enables Long\n");
+ }
+
+ function testCanDisplaysMultipleFlagsForEachOption() {
+ $help = new SimpleHelp('Cool program');
+ $help->explainFlag(array('a', 'aa'), 'Enables A');
+ $this->assertEqual($help->render(), "Cool program\n-a Enables A\n --aa\n");
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/authentication_test.php b/3rdparty/simpletest/test/authentication_test.php
new file mode 100755
index 00000000000..081cccddfae
--- /dev/null
+++ b/3rdparty/simpletest/test/authentication_test.php
@@ -0,0 +1,145 @@
+<?php
+// $Id: authentication_test.php 1748 2008-04-14 01:50:41Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../authentication.php');
+require_once(dirname(__FILE__) . '/../http.php');
+Mock::generate('SimpleHttpRequest');
+
+class TestOfRealm extends UnitTestCase {
+
+ function testWithinSameUrl() {
+ $realm = new SimpleRealm(
+ 'Basic',
+ new SimpleUrl('http://www.here.com/path/hello.html'));
+ $this->assertTrue($realm->isWithin(
+ new SimpleUrl('http://www.here.com/path/hello.html')));
+ }
+
+ function testInsideWithLongerUrl() {
+ $realm = new SimpleRealm(
+ 'Basic',
+ new SimpleUrl('http://www.here.com/path/'));
+ $this->assertTrue($realm->isWithin(
+ new SimpleUrl('http://www.here.com/path/hello.html')));
+ }
+
+ function testBelowRootIsOutside() {
+ $realm = new SimpleRealm(
+ 'Basic',
+ new SimpleUrl('http://www.here.com/path/'));
+ $this->assertTrue($realm->isWithin(
+ new SimpleUrl('http://www.here.com/path/more/hello.html')));
+ }
+
+ function testOldNetscapeDefinitionIsOutside() {
+ $realm = new SimpleRealm(
+ 'Basic',
+ new SimpleUrl('http://www.here.com/path/'));
+ $this->assertFalse($realm->isWithin(
+ new SimpleUrl('http://www.here.com/pathmore/hello.html')));
+ }
+
+ function testInsideWithMissingTrailingSlash() {
+ $realm = new SimpleRealm(
+ 'Basic',
+ new SimpleUrl('http://www.here.com/path/'));
+ $this->assertTrue($realm->isWithin(
+ new SimpleUrl('http://www.here.com/path')));
+ }
+
+ function testDifferentPageNameStillInside() {
+ $realm = new SimpleRealm(
+ 'Basic',
+ new SimpleUrl('http://www.here.com/path/hello.html'));
+ $this->assertTrue($realm->isWithin(
+ new SimpleUrl('http://www.here.com/path/goodbye.html')));
+ }
+
+ function testNewUrlInSameDirectoryDoesNotChangeRealm() {
+ $realm = new SimpleRealm(
+ 'Basic',
+ new SimpleUrl('http://www.here.com/path/hello.html'));
+ $realm->stretch(new SimpleUrl('http://www.here.com/path/goodbye.html'));
+ $this->assertTrue($realm->isWithin(
+ new SimpleUrl('http://www.here.com/path/index.html')));
+ $this->assertFalse($realm->isWithin(
+ new SimpleUrl('http://www.here.com/index.html')));
+ }
+
+ function testNewUrlMakesRealmTheCommonPath() {
+ $realm = new SimpleRealm(
+ 'Basic',
+ new SimpleUrl('http://www.here.com/path/here/hello.html'));
+ $realm->stretch(new SimpleUrl('http://www.here.com/path/there/goodbye.html'));
+ $this->assertTrue($realm->isWithin(
+ new SimpleUrl('http://www.here.com/path/here/index.html')));
+ $this->assertTrue($realm->isWithin(
+ new SimpleUrl('http://www.here.com/path/there/index.html')));
+ $this->assertTrue($realm->isWithin(
+ new SimpleUrl('http://www.here.com/path/index.html')));
+ $this->assertFalse($realm->isWithin(
+ new SimpleUrl('http://www.here.com/index.html')));
+ $this->assertFalse($realm->isWithin(
+ new SimpleUrl('http://www.here.com/paths/index.html')));
+ $this->assertFalse($realm->isWithin(
+ new SimpleUrl('http://www.here.com/pathindex.html')));
+ }
+}
+
+class TestOfAuthenticator extends UnitTestCase {
+
+ function testNoRealms() {
+ $request = new MockSimpleHttpRequest();
+ $request->expectNever('addHeaderLine');
+ $authenticator = new SimpleAuthenticator();
+ $authenticator->addHeaders($request, new SimpleUrl('http://here.com/'));
+ }
+
+ function &createSingleRealm() {
+ $authenticator = new SimpleAuthenticator();
+ $authenticator->addRealm(
+ new SimpleUrl('http://www.here.com/path/hello.html'),
+ 'Basic',
+ 'Sanctuary');
+ $authenticator->setIdentityForRealm('www.here.com', 'Sanctuary', 'test', 'secret');
+ return $authenticator;
+ }
+
+ function testOutsideRealm() {
+ $request = new MockSimpleHttpRequest();
+ $request->expectNever('addHeaderLine');
+ $authenticator = &$this->createSingleRealm();
+ $authenticator->addHeaders(
+ $request,
+ new SimpleUrl('http://www.here.com/hello.html'));
+ }
+
+ function testWithinRealm() {
+ $request = new MockSimpleHttpRequest();
+ $request->expectOnce('addHeaderLine');
+ $authenticator = &$this->createSingleRealm();
+ $authenticator->addHeaders(
+ $request,
+ new SimpleUrl('http://www.here.com/path/more/hello.html'));
+ }
+
+ function testRestartingClearsRealm() {
+ $request = new MockSimpleHttpRequest();
+ $request->expectNever('addHeaderLine');
+ $authenticator = &$this->createSingleRealm();
+ $authenticator->restartSession();
+ $authenticator->addHeaders(
+ $request,
+ new SimpleUrl('http://www.here.com/hello.html'));
+ }
+
+ function testDifferentHostIsOutsideRealm() {
+ $request = new MockSimpleHttpRequest();
+ $request->expectNever('addHeaderLine');
+ $authenticator = &$this->createSingleRealm();
+ $authenticator->addHeaders(
+ $request,
+ new SimpleUrl('http://here.com/path/hello.html'));
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/autorun_test.php b/3rdparty/simpletest/test/autorun_test.php
new file mode 100755
index 00000000000..d85ea19897c
--- /dev/null
+++ b/3rdparty/simpletest/test/autorun_test.php
@@ -0,0 +1,23 @@
+<?php
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/support/test1.php');
+
+class TestOfAutorun extends UnitTestCase {
+ function testLoadIfIncluded() {
+ $tests = new TestSuite();
+ $tests->addFile(dirname(__FILE__) . '/support/test1.php');
+ $this->assertEqual($tests->getSize(), 1);
+ }
+
+ function testExitStatusOneIfTestsFail() {
+ exec('php ' . dirname(__FILE__) . '/support/failing_test.php', $output, $exit_status);
+ $this->assertEqual($exit_status, 1);
+ }
+
+ function testExitStatusZeroIfTestsPass() {
+ exec('php ' . dirname(__FILE__) . '/support/passing_test.php', $output, $exit_status);
+ $this->assertEqual($exit_status, 0);
+ }
+}
+
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/bad_test_suite.php b/3rdparty/simpletest/test/bad_test_suite.php
new file mode 100755
index 00000000000..b426013be40
--- /dev/null
+++ b/3rdparty/simpletest/test/bad_test_suite.php
@@ -0,0 +1,10 @@
+<?php
+require_once(dirname(__FILE__) . '/../autorun.php');
+
+class BadTestCases extends TestSuite {
+ function BadTestCases() {
+ $this->TestSuite('Two bad test cases');
+ $this->addFile(dirname(__FILE__) . '/support/empty_test_file.php');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/browser_test.php b/3rdparty/simpletest/test/browser_test.php
new file mode 100755
index 00000000000..3a52aaa8ff4
--- /dev/null
+++ b/3rdparty/simpletest/test/browser_test.php
@@ -0,0 +1,802 @@
+<?php
+// $Id: browser_test.php 1964 2009-10-13 15:27:31Z maetl_ $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../browser.php');
+require_once(dirname(__FILE__) . '/../user_agent.php');
+require_once(dirname(__FILE__) . '/../http.php');
+require_once(dirname(__FILE__) . '/../page.php');
+require_once(dirname(__FILE__) . '/../encoding.php');
+
+Mock::generate('SimpleHttpResponse');
+Mock::generate('SimplePage');
+Mock::generate('SimpleForm');
+Mock::generate('SimpleUserAgent');
+Mock::generatePartial(
+ 'SimpleBrowser',
+ 'MockParseSimpleBrowser',
+ array('createUserAgent', 'parse'));
+Mock::generatePartial(
+ 'SimpleBrowser',
+ 'MockUserAgentSimpleBrowser',
+ array('createUserAgent'));
+
+class TestOfHistory extends UnitTestCase {
+
+ function testEmptyHistoryHasFalseContents() {
+ $history = new SimpleBrowserHistory();
+ $this->assertIdentical($history->getUrl(), false);
+ $this->assertIdentical($history->getParameters(), false);
+ }
+
+ function testCannotMoveInEmptyHistory() {
+ $history = new SimpleBrowserHistory();
+ $this->assertFalse($history->back());
+ $this->assertFalse($history->forward());
+ }
+
+ function testCurrentTargetAccessors() {
+ $history = new SimpleBrowserHistory();
+ $history->recordEntry(
+ new SimpleUrl('http://www.here.com/'),
+ new SimpleGetEncoding());
+ $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.here.com/'));
+ $this->assertIdentical($history->getParameters(), new SimpleGetEncoding());
+ }
+
+ function testSecondEntryAccessors() {
+ $history = new SimpleBrowserHistory();
+ $history->recordEntry(
+ new SimpleUrl('http://www.first.com/'),
+ new SimpleGetEncoding());
+ $history->recordEntry(
+ new SimpleUrl('http://www.second.com/'),
+ new SimplePostEncoding(array('a' => 1)));
+ $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/'));
+ $this->assertIdentical(
+ $history->getParameters(),
+ new SimplePostEncoding(array('a' => 1)));
+ }
+
+ function testGoingBackwards() {
+ $history = new SimpleBrowserHistory();
+ $history->recordEntry(
+ new SimpleUrl('http://www.first.com/'),
+ new SimpleGetEncoding());
+ $history->recordEntry(
+ new SimpleUrl('http://www.second.com/'),
+ new SimplePostEncoding(array('a' => 1)));
+ $this->assertTrue($history->back());
+ $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/'));
+ $this->assertIdentical($history->getParameters(), new SimpleGetEncoding());
+ }
+
+ function testGoingBackwardsOffBeginning() {
+ $history = new SimpleBrowserHistory();
+ $history->recordEntry(
+ new SimpleUrl('http://www.first.com/'),
+ new SimpleGetEncoding());
+ $this->assertFalse($history->back());
+ $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/'));
+ $this->assertIdentical($history->getParameters(), new SimpleGetEncoding());
+ }
+
+ function testGoingForwardsOffEnd() {
+ $history = new SimpleBrowserHistory();
+ $history->recordEntry(
+ new SimpleUrl('http://www.first.com/'),
+ new SimpleGetEncoding());
+ $this->assertFalse($history->forward());
+ $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/'));
+ $this->assertIdentical($history->getParameters(), new SimpleGetEncoding());
+ }
+
+ function testGoingBackwardsAndForwards() {
+ $history = new SimpleBrowserHistory();
+ $history->recordEntry(
+ new SimpleUrl('http://www.first.com/'),
+ new SimpleGetEncoding());
+ $history->recordEntry(
+ new SimpleUrl('http://www.second.com/'),
+ new SimplePostEncoding(array('a' => 1)));
+ $this->assertTrue($history->back());
+ $this->assertTrue($history->forward());
+ $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/'));
+ $this->assertIdentical(
+ $history->getParameters(),
+ new SimplePostEncoding(array('a' => 1)));
+ }
+
+ function testNewEntryReplacesNextOne() {
+ $history = new SimpleBrowserHistory();
+ $history->recordEntry(
+ new SimpleUrl('http://www.first.com/'),
+ new SimpleGetEncoding());
+ $history->recordEntry(
+ new SimpleUrl('http://www.second.com/'),
+ new SimplePostEncoding(array('a' => 1)));
+ $history->back();
+ $history->recordEntry(
+ new SimpleUrl('http://www.third.com/'),
+ new SimpleGetEncoding());
+ $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.third.com/'));
+ $this->assertIdentical($history->getParameters(), new SimpleGetEncoding());
+ }
+
+ function testNewEntryDropsFutureEntries() {
+ $history = new SimpleBrowserHistory();
+ $history->recordEntry(
+ new SimpleUrl('http://www.first.com/'),
+ new SimpleGetEncoding());
+ $history->recordEntry(
+ new SimpleUrl('http://www.second.com/'),
+ new SimpleGetEncoding());
+ $history->recordEntry(
+ new SimpleUrl('http://www.third.com/'),
+ new SimpleGetEncoding());
+ $history->back();
+ $history->back();
+ $history->recordEntry(
+ new SimpleUrl('http://www.fourth.com/'),
+ new SimpleGetEncoding());
+ $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.fourth.com/'));
+ $this->assertFalse($history->forward());
+ $history->back();
+ $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/'));
+ $this->assertFalse($history->back());
+ }
+}
+
+class TestOfParsedPageAccess extends UnitTestCase {
+
+ function loadPage(&$page) {
+ $response = new MockSimpleHttpResponse($this);
+ $agent = new MockSimpleUserAgent($this);
+ $agent->returns('fetchResponse', $response);
+
+ $browser = new MockParseSimpleBrowser($this);
+ $browser->returns('createUserAgent', $agent);
+ $browser->returns('parse', $page);
+ $browser->__construct();
+
+ $browser->get('http://this.com/page.html');
+ return $browser;
+ }
+
+ function testAccessorsWhenNoPage() {
+ $agent = new MockSimpleUserAgent($this);
+ $browser = new MockParseSimpleBrowser($this);
+ $browser->returns('createUserAgent', $agent);
+ $browser->__construct();
+ $this->assertEqual($browser->getContent(), '');
+ }
+
+ function testParse() {
+ $page = new MockSimplePage();
+ $page->setReturnValue('getRequest', "GET here.html\r\n\r\n");
+ $page->setReturnValue('getRaw', 'Raw HTML');
+ $page->setReturnValue('getTitle', 'Here');
+ $page->setReturnValue('getFrameFocus', 'Frame');
+ $page->setReturnValue('getMimeType', 'text/html');
+ $page->setReturnValue('getResponseCode', 200);
+ $page->setReturnValue('getAuthentication', 'Basic');
+ $page->setReturnValue('getRealm', 'Somewhere');
+ $page->setReturnValue('getTransportError', 'Ouch!');
+
+ $browser = $this->loadPage($page);
+ $this->assertEqual($browser->getRequest(), "GET here.html\r\n\r\n");
+ $this->assertEqual($browser->getContent(), 'Raw HTML');
+ $this->assertEqual($browser->getTitle(), 'Here');
+ $this->assertEqual($browser->getFrameFocus(), 'Frame');
+ $this->assertIdentical($browser->getResponseCode(), 200);
+ $this->assertEqual($browser->getMimeType(), 'text/html');
+ $this->assertEqual($browser->getAuthentication(), 'Basic');
+ $this->assertEqual($browser->getRealm(), 'Somewhere');
+ $this->assertEqual($browser->getTransportError(), 'Ouch!');
+ }
+
+ function testLinkAffirmationWhenPresent() {
+ $page = new MockSimplePage();
+ $page->setReturnValue('getUrlsByLabel', array('http://www.nowhere.com'));
+ $page->expectOnce('getUrlsByLabel', array('a link label'));
+ $browser = $this->loadPage($page);
+ $this->assertIdentical($browser->getLink('a link label'), 'http://www.nowhere.com');
+ }
+
+ function testLinkAffirmationByIdWhenPresent() {
+ $page = new MockSimplePage();
+ $page->setReturnValue('getUrlById', 'a_page.com', array(99));
+ $page->setReturnValue('getUrlById', false, array('*'));
+ $browser = $this->loadPage($page);
+ $this->assertIdentical($browser->getLinkById(99), 'a_page.com');
+ $this->assertFalse($browser->getLinkById(98));
+ }
+
+ function testSettingFieldIsPassedToPage() {
+ $page = new MockSimplePage();
+ $page->expectOnce('setField', array(new SimpleByLabelOrName('key'), 'Value', false));
+ $page->setReturnValue('getField', 'Value');
+ $browser = $this->loadPage($page);
+ $this->assertEqual($browser->getField('key'), 'Value');
+ $browser->setField('key', 'Value');
+ }
+}
+
+class TestOfBrowserNavigation extends UnitTestCase {
+ function createBrowser($agent, $page) {
+ $browser = new MockParseSimpleBrowser();
+ $browser->returns('createUserAgent', $agent);
+ $browser->returns('parse', $page);
+ $browser->__construct();
+ return $browser;
+ }
+
+ function testBrowserRequestMethods() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+ $agent->expectAt(
+ 0,
+ 'fetchResponse',
+ array(new SimpleUrl('http://this.com/get.req'), new SimpleGetEncoding()));
+ $agent->expectAt(
+ 1,
+ 'fetchResponse',
+ array(new SimpleUrl('http://this.com/post.req'), new SimplePostEncoding()));
+ $agent->expectAt(
+ 2,
+ 'fetchResponse',
+ array(new SimpleUrl('http://this.com/put.req'), new SimplePutEncoding()));
+ $agent->expectAt(
+ 3,
+ 'fetchResponse',
+ array(new SimpleUrl('http://this.com/delete.req'), new SimpleDeleteEncoding()));
+ $agent->expectAt(
+ 4,
+ 'fetchResponse',
+ array(new SimpleUrl('http://this.com/head.req'), new SimpleHeadEncoding()));
+ $agent->expectCallCount('fetchResponse', 5);
+
+ $page = new MockSimplePage();
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/get.req');
+ $browser->post('http://this.com/post.req');
+ $browser->put('http://this.com/put.req');
+ $browser->delete('http://this.com/delete.req');
+ $browser->head('http://this.com/head.req');
+ }
+
+ function testClickLinkRequestsPage() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+ $agent->expectAt(
+ 0,
+ 'fetchResponse',
+ array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding()));
+ $agent->expectAt(
+ 1,
+ 'fetchResponse',
+ array(new SimpleUrl('http://this.com/new.html'), new SimpleGetEncoding()));
+ $agent->expectCallCount('fetchResponse', 2);
+
+ $page = new MockSimplePage();
+ $page->setReturnValue('getUrlsByLabel', array(new SimpleUrl('http://this.com/new.html')));
+ $page->expectOnce('getUrlsByLabel', array('New'));
+ $page->setReturnValue('getRaw', 'A page');
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertTrue($browser->clickLink('New'));
+ }
+
+ function testClickLinkWithUnknownFrameStillRequestsWholePage() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+ $agent->expectAt(
+ 0,
+ 'fetchResponse',
+ array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding()));
+ $target = new SimpleUrl('http://this.com/new.html');
+ $target->setTarget('missing');
+ $agent->expectAt(
+ 1,
+ 'fetchResponse',
+ array($target, new SimpleGetEncoding()));
+ $agent->expectCallCount('fetchResponse', 2);
+
+ $parsed_url = new SimpleUrl('http://this.com/new.html');
+ $parsed_url->setTarget('missing');
+
+ $page = new MockSimplePage();
+ $page->setReturnValue('getUrlsByLabel', array($parsed_url));
+ $page->setReturnValue('hasFrames', false);
+ $page->expectOnce('getUrlsByLabel', array('New'));
+ $page->setReturnValue('getRaw', 'A page');
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertTrue($browser->clickLink('New'));
+ }
+
+ function testClickingMissingLinkFails() {
+ $agent = new MockSimpleUserAgent($this);
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+
+ $page = new MockSimplePage();
+ $page->setReturnValue('getUrlsByLabel', array());
+ $page->setReturnValue('getRaw', 'stuff');
+
+ $browser = $this->createBrowser($agent, $page);
+ $this->assertTrue($browser->get('http://this.com/page.html'));
+ $this->assertFalse($browser->clickLink('New'));
+ }
+
+ function testClickIndexedLink() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+ $agent->expectAt(
+ 1,
+ 'fetchResponse',
+ array(new SimpleUrl('1.html'), new SimpleGetEncoding()));
+ $agent->expectCallCount('fetchResponse', 2);
+
+ $page = new MockSimplePage();
+ $page->setReturnValue(
+ 'getUrlsByLabel',
+ array(new SimpleUrl('0.html'), new SimpleUrl('1.html')));
+ $page->setReturnValue('getRaw', 'A page');
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertTrue($browser->clickLink('New', 1));
+ }
+
+ function testClinkLinkById() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+ $agent->expectAt(1, 'fetchResponse', array(
+ new SimpleUrl('http://this.com/link.html'),
+ new SimpleGetEncoding()));
+ $agent->expectCallCount('fetchResponse', 2);
+
+ $page = new MockSimplePage();
+ $page->setReturnValue('getUrlById', new SimpleUrl('http://this.com/link.html'));
+ $page->expectOnce('getUrlById', array(2));
+ $page->setReturnValue('getRaw', 'A page');
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertTrue($browser->clickLinkById(2));
+ }
+
+ function testClickingMissingLinkIdFails() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+
+ $page = new MockSimplePage();
+ $page->setReturnValue('getUrlById', false);
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertFalse($browser->clickLink(0));
+ }
+
+ function testSubmitFormByLabel() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+ $agent->expectAt(1, 'fetchResponse', array(
+ new SimpleUrl('http://this.com/handler.html'),
+ new SimplePostEncoding(array('a' => 'A'))));
+ $agent->expectCallCount('fetchResponse', 2);
+
+ $form = new MockSimpleForm();
+ $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
+ $form->setReturnValue('getMethod', 'post');
+ $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A')));
+ $form->expectOnce('submitButton', array(new SimpleByLabel('Go'), false));
+
+ $page = new MockSimplePage();
+ $page->returns('getFormBySubmit', $form);
+ $page->expectOnce('getFormBySubmit', array(new SimpleByLabel('Go')));
+ $page->setReturnValue('getRaw', 'stuff');
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertTrue($browser->clickSubmit('Go'));
+ }
+
+ function testDefaultSubmitFormByLabel() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+ $agent->expectAt(1, 'fetchResponse', array(
+ new SimpleUrl('http://this.com/page.html'),
+ new SimpleGetEncoding(array('a' => 'A'))));
+ $agent->expectCallCount('fetchResponse', 2);
+
+ $form = new MockSimpleForm();
+ $form->setReturnValue('getAction', new SimpleUrl('http://this.com/page.html'));
+ $form->setReturnValue('getMethod', 'get');
+ $form->setReturnValue('submitButton', new SimpleGetEncoding(array('a' => 'A')));
+
+ $page = new MockSimplePage();
+ $page->returns('getFormBySubmit', $form);
+ $page->expectOnce('getFormBySubmit', array(new SimpleByLabel('Submit')));
+ $page->setReturnValue('getRaw', 'stuff');
+ $page->setReturnValue('getUrl', new SimpleUrl('http://this.com/page.html'));
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertTrue($browser->clickSubmit());
+ }
+
+ function testSubmitFormByName() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+
+ $form = new MockSimpleForm();
+ $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
+ $form->setReturnValue('getMethod', 'post');
+ $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A')));
+
+ $page = new MockSimplePage();
+ $page->returns('getFormBySubmit', $form);
+ $page->expectOnce('getFormBySubmit', array(new SimpleByName('me')));
+ $page->setReturnValue('getRaw', 'stuff');
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertTrue($browser->clickSubmitByName('me'));
+ }
+
+ function testSubmitFormById() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+
+ $form = new MockSimpleForm();
+ $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
+ $form->setReturnValue('getMethod', 'post');
+ $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A')));
+ $form->expectOnce('submitButton', array(new SimpleById(99), false));
+
+ $page = new MockSimplePage();
+ $page->returns('getFormBySubmit', $form);
+ $page->expectOnce('getFormBySubmit', array(new SimpleById(99)));
+ $page->setReturnValue('getRaw', 'stuff');
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertTrue($browser->clickSubmitById(99));
+ }
+
+ function testSubmitFormByImageLabel() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+
+ $form = new MockSimpleForm();
+ $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
+ $form->setReturnValue('getMethod', 'post');
+ $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A')));
+ $form->expectOnce('submitImage', array(new SimpleByLabel('Go!'), 10, 11, false));
+
+ $page = new MockSimplePage();
+ $page->returns('getFormByImage', $form);
+ $page->expectOnce('getFormByImage', array(new SimpleByLabel('Go!')));
+ $page->setReturnValue('getRaw', 'stuff');
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertTrue($browser->clickImage('Go!', 10, 11));
+ }
+
+ function testSubmitFormByImageName() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+
+ $form = new MockSimpleForm();
+ $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
+ $form->setReturnValue('getMethod', 'post');
+ $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A')));
+ $form->expectOnce('submitImage', array(new SimpleByName('a'), 10, 11, false));
+
+ $page = new MockSimplePage();
+ $page->returns('getFormByImage', $form);
+ $page->expectOnce('getFormByImage', array(new SimpleByName('a')));
+ $page->setReturnValue('getRaw', 'stuff');
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertTrue($browser->clickImageByName('a', 10, 11));
+ }
+
+ function testSubmitFormByImageId() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+
+ $form = new MockSimpleForm();
+ $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
+ $form->setReturnValue('getMethod', 'post');
+ $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A')));
+ $form->expectOnce('submitImage', array(new SimpleById(99), 10, 11, false));
+
+ $page = new MockSimplePage();
+ $page->returns('getFormByImage', $form);
+ $page->expectOnce('getFormByImage', array(new SimpleById(99)));
+ $page->setReturnValue('getRaw', 'stuff');
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertTrue($browser->clickImageById(99, 10, 11));
+ }
+
+ function testSubmitFormByFormId() {
+ $agent = new MockSimpleUserAgent();
+ $agent->returns('fetchResponse', new MockSimpleHttpResponse());
+ $agent->expectAt(1, 'fetchResponse', array(
+ new SimpleUrl('http://this.com/handler.html'),
+ new SimplePostEncoding(array('a' => 'A'))));
+ $agent->expectCallCount('fetchResponse', 2);
+
+ $form = new MockSimpleForm();
+ $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html'));
+ $form->setReturnValue('getMethod', 'post');
+ $form->setReturnValue('submit', new SimplePostEncoding(array('a' => 'A')));
+
+ $page = new MockSimplePage();
+ $page->returns('getFormById', $form);
+ $page->expectOnce('getFormById', array(33));
+ $page->setReturnValue('getRaw', 'stuff');
+
+ $browser = $this->createBrowser($agent, $page);
+ $browser->get('http://this.com/page.html');
+ $this->assertTrue($browser->submitFormById(33));
+ }
+}
+
+class TestOfBrowserFrames extends UnitTestCase {
+
+ function createBrowser($agent) {
+ $browser = new MockUserAgentSimpleBrowser();
+ $browser->returns('createUserAgent', $agent);
+ $browser->__construct();
+ return $browser;
+ }
+
+ function createUserAgent($pages) {
+ $agent = new MockSimpleUserAgent();
+ foreach ($pages as $url => $raw) {
+ $url = new SimpleUrl($url);
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue('getUrl', $url);
+ $response->setReturnValue('getContent', $raw);
+ $agent->returns('fetchResponse', $response, array($url, '*'));
+ }
+ return $agent;
+ }
+
+ function testSimplePageHasNoFrames() {
+ $browser = $this->createBrowser($this->createUserAgent(
+ array('http://site.with.no.frames/' => 'A non-framed page')));
+ $this->assertEqual(
+ $browser->get('http://site.with.no.frames/'),
+ 'A non-framed page');
+ $this->assertIdentical($browser->getFrames(), 'http://site.with.no.frames/');
+ }
+
+ function testFramesetWithSingleFrame() {
+ $frameset = '<frameset><frame name="a" src="frame.html"></frameset>';
+ $browser = $this->createBrowser($this->createUserAgent(array(
+ 'http://site.with.one.frame/' => $frameset,
+ 'http://site.with.one.frame/frame.html' => 'A frame')));
+ $this->assertEqual($browser->get('http://site.with.one.frame/'), 'A frame');
+ $this->assertIdentical(
+ $browser->getFrames(),
+ array('a' => 'http://site.with.one.frame/frame.html'));
+ }
+
+ function testTitleTakenFromFramesetPage() {
+ $frameset = '<title>Frameset title</title>' .
+ '<frameset><frame name="a" src="frame.html"></frameset>';
+ $browser = $this->createBrowser($this->createUserAgent(array(
+ 'http://site.with.one.frame/' => $frameset,
+ 'http://site.with.one.frame/frame.html' => '<title>Page title</title>')));
+ $browser->get('http://site.with.one.frame/');
+ $this->assertEqual($browser->getTitle(), 'Frameset title');
+ }
+
+ function testFramesetWithSingleUnnamedFrame() {
+ $frameset = '<frameset><frame src="frame.html"></frameset>';
+ $browser = $this->createBrowser($this->createUserAgent(array(
+ 'http://site.with.one.frame/' => $frameset,
+ 'http://site.with.one.frame/frame.html' => 'One frame')));
+ $this->assertEqual(
+ $browser->get('http://site.with.one.frame/'),
+ 'One frame');
+ $this->assertIdentical(
+ $browser->getFrames(),
+ array(1 => 'http://site.with.one.frame/frame.html'));
+ }
+
+ function testFramesetWithMultipleFrames() {
+ $frameset = '<frameset>' .
+ '<frame name="a" src="frame_a.html">' .
+ '<frame name="b" src="frame_b.html">' .
+ '<frame name="c" src="frame_c.html">' .
+ '</frameset>';
+ $browser = $this->createBrowser($this->createUserAgent(array(
+ 'http://site.with.frames/' => $frameset,
+ 'http://site.with.frames/frame_a.html' => 'A frame',
+ 'http://site.with.frames/frame_b.html' => 'B frame',
+ 'http://site.with.frames/frame_c.html' => 'C frame')));
+ $this->assertEqual(
+ $browser->get('http://site.with.frames/'),
+ 'A frameB frameC frame');
+ $this->assertIdentical($browser->getFrames(), array(
+ 'a' => 'http://site.with.frames/frame_a.html',
+ 'b' => 'http://site.with.frames/frame_b.html',
+ 'c' => 'http://site.with.frames/frame_c.html'));
+ }
+
+ function testFrameFocusByName() {
+ $frameset = '<frameset>' .
+ '<frame name="a" src="frame_a.html">' .
+ '<frame name="b" src="frame_b.html">' .
+ '<frame name="c" src="frame_c.html">' .
+ '</frameset>';
+ $browser = $this->createBrowser($this->createUserAgent(array(
+ 'http://site.with.frames/' => $frameset,
+ 'http://site.with.frames/frame_a.html' => 'A frame',
+ 'http://site.with.frames/frame_b.html' => 'B frame',
+ 'http://site.with.frames/frame_c.html' => 'C frame')));
+ $browser->get('http://site.with.frames/');
+ $browser->setFrameFocus('a');
+ $this->assertEqual($browser->getContent(), 'A frame');
+ $browser->setFrameFocus('b');
+ $this->assertEqual($browser->getContent(), 'B frame');
+ $browser->setFrameFocus('c');
+ $this->assertEqual($browser->getContent(), 'C frame');
+ }
+
+ function testFramesetWithSomeNamedFrames() {
+ $frameset = '<frameset>' .
+ '<frame name="a" src="frame_a.html">' .
+ '<frame src="frame_b.html">' .
+ '<frame name="c" src="frame_c.html">' .
+ '<frame src="frame_d.html">' .
+ '</frameset>';
+ $browser = $this->createBrowser($this->createUserAgent(array(
+ 'http://site.with.frames/' => $frameset,
+ 'http://site.with.frames/frame_a.html' => 'A frame',
+ 'http://site.with.frames/frame_b.html' => 'B frame',
+ 'http://site.with.frames/frame_c.html' => 'C frame',
+ 'http://site.with.frames/frame_d.html' => 'D frame')));
+ $this->assertEqual(
+ $browser->get('http://site.with.frames/'),
+ 'A frameB frameC frameD frame');
+ $this->assertIdentical($browser->getFrames(), array(
+ 'a' => 'http://site.with.frames/frame_a.html',
+ 2 => 'http://site.with.frames/frame_b.html',
+ 'c' => 'http://site.with.frames/frame_c.html',
+ 4 => 'http://site.with.frames/frame_d.html'));
+ }
+
+ function testFrameFocusWithMixedNamesAndIndexes() {
+ $frameset = '<frameset>' .
+ '<frame name="a" src="frame_a.html">' .
+ '<frame src="frame_b.html">' .
+ '<frame name="c" src="frame_c.html">' .
+ '<frame src="frame_d.html">' .
+ '</frameset>';
+ $browser = $this->createBrowser($this->createUserAgent(array(
+ 'http://site.with.frames/' => $frameset,
+ 'http://site.with.frames/frame_a.html' => 'A frame',
+ 'http://site.with.frames/frame_b.html' => 'B frame',
+ 'http://site.with.frames/frame_c.html' => 'C frame',
+ 'http://site.with.frames/frame_d.html' => 'D frame')));
+ $browser->get('http://site.with.frames/');
+ $browser->setFrameFocus('a');
+ $this->assertEqual($browser->getContent(), 'A frame');
+ $browser->setFrameFocus(2);
+ $this->assertEqual($browser->getContent(), 'B frame');
+ $browser->setFrameFocus('c');
+ $this->assertEqual($browser->getContent(), 'C frame');
+ $browser->setFrameFocus(4);
+ $this->assertEqual($browser->getContent(), 'D frame');
+ $browser->clearFrameFocus();
+ $this->assertEqual($browser->getContent(), 'A frameB frameC frameD frame');
+ }
+
+ function testNestedFrameset() {
+ $inner = '<frameset>' .
+ '<frame name="page" src="page.html">' .
+ '</frameset>';
+ $outer = '<frameset>' .
+ '<frame name="inner" src="inner.html">' .
+ '</frameset>';
+ $browser = $this->createBrowser($this->createUserAgent(array(
+ 'http://site.with.nested.frame/' => $outer,
+ 'http://site.with.nested.frame/inner.html' => $inner,
+ 'http://site.with.nested.frame/page.html' => 'The page')));
+ $this->assertEqual(
+ $browser->get('http://site.with.nested.frame/'),
+ 'The page');
+ $this->assertIdentical($browser->getFrames(), array(
+ 'inner' => array(
+ 'page' => 'http://site.with.nested.frame/page.html')));
+ }
+
+ function testCanNavigateToNestedFrame() {
+ $inner = '<frameset>' .
+ '<frame name="one" src="one.html">' .
+ '<frame name="two" src="two.html">' .
+ '</frameset>';
+ $outer = '<frameset>' .
+ '<frame name="inner" src="inner.html">' .
+ '<frame name="three" src="three.html">' .
+ '</frameset>';
+ $browser = $this->createBrowser($this->createUserAgent(array(
+ 'http://site.with.nested.frames/' => $outer,
+ 'http://site.with.nested.frames/inner.html' => $inner,
+ 'http://site.with.nested.frames/one.html' => 'Page one',
+ 'http://site.with.nested.frames/two.html' => 'Page two',
+ 'http://site.with.nested.frames/three.html' => 'Page three')));
+
+ $browser->get('http://site.with.nested.frames/');
+ $this->assertEqual($browser->getContent(), 'Page onePage twoPage three');
+
+ $this->assertTrue($browser->setFrameFocus('inner'));
+ $this->assertEqual($browser->getFrameFocus(), array('inner'));
+ $this->assertTrue($browser->setFrameFocus('one'));
+ $this->assertEqual($browser->getFrameFocus(), array('inner', 'one'));
+ $this->assertEqual($browser->getContent(), 'Page one');
+
+ $this->assertTrue($browser->setFrameFocus('two'));
+ $this->assertEqual($browser->getFrameFocus(), array('inner', 'two'));
+ $this->assertEqual($browser->getContent(), 'Page two');
+
+ $browser->clearFrameFocus();
+ $this->assertTrue($browser->setFrameFocus('three'));
+ $this->assertEqual($browser->getFrameFocus(), array('three'));
+ $this->assertEqual($browser->getContent(), 'Page three');
+
+ $this->assertTrue($browser->setFrameFocus('inner'));
+ $this->assertEqual($browser->getContent(), 'Page onePage two');
+ }
+
+ function testCanNavigateToNestedFrameByIndex() {
+ $inner = '<frameset>' .
+ '<frame src="one.html">' .
+ '<frame src="two.html">' .
+ '</frameset>';
+ $outer = '<frameset>' .
+ '<frame src="inner.html">' .
+ '<frame src="three.html">' .
+ '</frameset>';
+ $browser = $this->createBrowser($this->createUserAgent(array(
+ 'http://site.with.nested.frames/' => $outer,
+ 'http://site.with.nested.frames/inner.html' => $inner,
+ 'http://site.with.nested.frames/one.html' => 'Page one',
+ 'http://site.with.nested.frames/two.html' => 'Page two',
+ 'http://site.with.nested.frames/three.html' => 'Page three')));
+
+ $browser->get('http://site.with.nested.frames/');
+ $this->assertEqual($browser->getContent(), 'Page onePage twoPage three');
+
+ $this->assertTrue($browser->setFrameFocusByIndex(1));
+ $this->assertEqual($browser->getFrameFocus(), array(1));
+ $this->assertTrue($browser->setFrameFocusByIndex(1));
+ $this->assertEqual($browser->getFrameFocus(), array(1, 1));
+ $this->assertEqual($browser->getContent(), 'Page one');
+
+ $this->assertTrue($browser->setFrameFocusByIndex(2));
+ $this->assertEqual($browser->getFrameFocus(), array(1, 2));
+ $this->assertEqual($browser->getContent(), 'Page two');
+
+ $browser->clearFrameFocus();
+ $this->assertTrue($browser->setFrameFocusByIndex(2));
+ $this->assertEqual($browser->getFrameFocus(), array(2));
+ $this->assertEqual($browser->getContent(), 'Page three');
+
+ $this->assertTrue($browser->setFrameFocusByIndex(1));
+ $this->assertEqual($browser->getContent(), 'Page onePage two');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/collector_test.php b/3rdparty/simpletest/test/collector_test.php
new file mode 100755
index 00000000000..efdbf377ece
--- /dev/null
+++ b/3rdparty/simpletest/test/collector_test.php
@@ -0,0 +1,50 @@
+<?php
+// $Id: collector_test.php 1769 2008-04-19 14:39:00Z pp11 $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../collector.php');
+SimpleTest::ignore('MockTestSuite');
+Mock::generate('TestSuite');
+
+class PathEqualExpectation extends EqualExpectation {
+ function __construct($value, $message = '%s') {
+ parent::__construct(str_replace("\\", '/', $value), $message);
+ }
+
+ function test($compare) {
+ return parent::test(str_replace("\\", '/', $compare));
+ }
+}
+
+class TestOfCollector extends UnitTestCase {
+ function testCollectionIsAddedToGroup() {
+ $suite = new MockTestSuite();
+ $suite->expectMinimumCallCount('addFile', 2);
+ $suite->expect(
+ 'addFile',
+ array(new PatternExpectation('/collectable\\.(1|2)$/')));
+ $collector = new SimpleCollector();
+ $collector->collect($suite, dirname(__FILE__) . '/support/collector/');
+ }
+}
+
+class TestOfPatternCollector extends UnitTestCase {
+
+ function testAddingEverythingToGroup() {
+ $suite = new MockTestSuite();
+ $suite->expectCallCount('addFile', 2);
+ $suite->expect(
+ 'addFile',
+ array(new PatternExpectation('/collectable\\.(1|2)$/')));
+ $collector = new SimplePatternCollector('/.*/');
+ $collector->collect($suite, dirname(__FILE__) . '/support/collector/');
+ }
+
+ function testOnlyMatchedFilesAreAddedToGroup() {
+ $suite = new MockTestSuite();
+ $suite->expectOnce('addFile', array(new PathEqualExpectation(
+ dirname(__FILE__) . '/support/collector/collectable.1')));
+ $collector = new SimplePatternCollector('/1$/');
+ $collector->collect($suite, dirname(__FILE__) . '/support/collector/');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/command_line_test.php b/3rdparty/simpletest/test/command_line_test.php
new file mode 100755
index 00000000000..5baabff33c6
--- /dev/null
+++ b/3rdparty/simpletest/test/command_line_test.php
@@ -0,0 +1,40 @@
+<?php
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../default_reporter.php');
+
+class TestOfCommandLineParsing extends UnitTestCase {
+
+ function testDefaultsToEmptyStringToMeanNullToTheSelectiveReporter() {
+ $parser = new SimpleCommandLineParser(array());
+ $this->assertIdentical($parser->getTest(), '');
+ $this->assertIdentical($parser->getTestCase(), '');
+ }
+
+ function testNotXmlByDefault() {
+ $parser = new SimpleCommandLineParser(array());
+ $this->assertFalse($parser->isXml());
+ }
+
+ function testCanDetectRequestForXml() {
+ $parser = new SimpleCommandLineParser(array('--xml'));
+ $this->assertTrue($parser->isXml());
+ }
+
+ function testCanReadAssignmentSyntax() {
+ $parser = new SimpleCommandLineParser(array('--test=myTest'));
+ $this->assertEqual($parser->getTest(), 'myTest');
+ }
+
+ function testCanReadFollowOnSyntax() {
+ $parser = new SimpleCommandLineParser(array('--test', 'myTest'));
+ $this->assertEqual($parser->getTest(), 'myTest');
+ }
+
+ function testCanReadShortForms() {
+ $parser = new SimpleCommandLineParser(array('-t', 'myTest', '-c', 'MyClass', '-x'));
+ $this->assertEqual($parser->getTest(), 'myTest');
+ $this->assertEqual($parser->getTestCase(), 'MyClass');
+ $this->assertTrue($parser->isXml());
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/compatibility_test.php b/3rdparty/simpletest/test/compatibility_test.php
new file mode 100755
index 00000000000..b8635e5bb83
--- /dev/null
+++ b/3rdparty/simpletest/test/compatibility_test.php
@@ -0,0 +1,87 @@
+<?php
+// $Id: compatibility_test.php 1748 2008-04-14 01:50:41Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../compatibility.php');
+
+class ComparisonClass { }
+class ComparisonSubclass extends ComparisonClass { }
+interface ComparisonInterface { }
+class ComparisonClassWithInterface implements ComparisonInterface { }
+
+class TestOfCompatibility extends UnitTestCase {
+
+ function testIsA() {
+ $this->assertTrue(SimpleTestCompatibility::isA(
+ new ComparisonClass(),
+ 'ComparisonClass'));
+ $this->assertFalse(SimpleTestCompatibility::isA(
+ new ComparisonClass(),
+ 'ComparisonSubclass'));
+ $this->assertTrue(SimpleTestCompatibility::isA(
+ new ComparisonSubclass(),
+ 'ComparisonClass'));
+ }
+
+ function testIdentityOfNumericStrings() {
+ $numericString1 = "123";
+ $numericString2 = "00123";
+ $this->assertNotIdentical($numericString1, $numericString2);
+ }
+
+ function testIdentityOfObjects() {
+ $object1 = new ComparisonClass();
+ $object2 = new ComparisonClass();
+ $this->assertIdentical($object1, $object2);
+ }
+
+ function testReferences () {
+ $thing = "Hello";
+ $thing_reference = &$thing;
+ $thing_copy = $thing;
+ $this->assertTrue(SimpleTestCompatibility::isReference(
+ $thing,
+ $thing));
+ $this->assertTrue(SimpleTestCompatibility::isReference(
+ $thing,
+ $thing_reference));
+ $this->assertFalse(SimpleTestCompatibility::isReference(
+ $thing,
+ $thing_copy));
+ }
+
+ function testObjectReferences () {
+ $object = new ComparisonClass();
+ $object_reference = $object;
+ $object_copy = new ComparisonClass();
+ $object_assignment = $object;
+ $this->assertTrue(SimpleTestCompatibility::isReference(
+ $object,
+ $object));
+ $this->assertTrue(SimpleTestCompatibility::isReference(
+ $object,
+ $object_reference));
+ $this->assertFalse(SimpleTestCompatibility::isReference(
+ $object,
+ $object_copy));
+ if (version_compare(phpversion(), '5', '>=')) {
+ $this->assertTrue(SimpleTestCompatibility::isReference(
+ $object,
+ $object_assignment));
+ } else {
+ $this->assertFalse(SimpleTestCompatibility::isReference(
+ $object,
+ $object_assignment));
+ }
+ }
+
+ function testInteraceComparison() {
+ $object = new ComparisonClassWithInterface();
+ $this->assertFalse(SimpleTestCompatibility::isA(
+ new ComparisonClass(),
+ 'ComparisonInterface'));
+ $this->assertTrue(SimpleTestCompatibility::isA(
+ new ComparisonClassWithInterface(),
+ 'ComparisonInterface'));
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/cookies_test.php b/3rdparty/simpletest/test/cookies_test.php
new file mode 100755
index 00000000000..0b49e43bf9f
--- /dev/null
+++ b/3rdparty/simpletest/test/cookies_test.php
@@ -0,0 +1,227 @@
+<?php
+// $Id: cookies_test.php 1506 2007-05-07 00:58:03Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../cookies.php');
+
+class TestOfCookie extends UnitTestCase {
+
+ function testCookieDefaults() {
+ $cookie = new SimpleCookie("name");
+ $this->assertFalse($cookie->getValue());
+ $this->assertEqual($cookie->getPath(), "/");
+ $this->assertIdentical($cookie->getHost(), false);
+ $this->assertFalse($cookie->getExpiry());
+ $this->assertFalse($cookie->isSecure());
+ }
+
+ function testCookieAccessors() {
+ $cookie = new SimpleCookie(
+ "name",
+ "value",
+ "/path",
+ "Mon, 18 Nov 2002 15:50:29 GMT",
+ true);
+ $this->assertEqual($cookie->getName(), "name");
+ $this->assertEqual($cookie->getValue(), "value");
+ $this->assertEqual($cookie->getPath(), "/path/");
+ $this->assertEqual($cookie->getExpiry(), "Mon, 18 Nov 2002 15:50:29 GMT");
+ $this->assertTrue($cookie->isSecure());
+ }
+
+ function testFullHostname() {
+ $cookie = new SimpleCookie("name");
+ $this->assertTrue($cookie->setHost("host.name.here"));
+ $this->assertEqual($cookie->getHost(), "host.name.here");
+ $this->assertTrue($cookie->setHost("host.com"));
+ $this->assertEqual($cookie->getHost(), "host.com");
+ }
+
+ function testHostTruncation() {
+ $cookie = new SimpleCookie("name");
+ $cookie->setHost("this.host.name.here");
+ $this->assertEqual($cookie->getHost(), "host.name.here");
+ $cookie->setHost("this.host.com");
+ $this->assertEqual($cookie->getHost(), "host.com");
+ $this->assertTrue($cookie->setHost("dashes.in-host.com"));
+ $this->assertEqual($cookie->getHost(), "in-host.com");
+ }
+
+ function testBadHosts() {
+ $cookie = new SimpleCookie("name");
+ $this->assertFalse($cookie->setHost("gibberish"));
+ $this->assertFalse($cookie->setHost("host.here"));
+ $this->assertFalse($cookie->setHost("host..com"));
+ $this->assertFalse($cookie->setHost("..."));
+ $this->assertFalse($cookie->setHost("host.com."));
+ }
+
+ function testHostValidity() {
+ $cookie = new SimpleCookie("name");
+ $cookie->setHost("this.host.name.here");
+ $this->assertTrue($cookie->isValidHost("host.name.here"));
+ $this->assertTrue($cookie->isValidHost("that.host.name.here"));
+ $this->assertFalse($cookie->isValidHost("bad.host"));
+ $this->assertFalse($cookie->isValidHost("nearly.name.here"));
+ }
+
+ function testPathValidity() {
+ $cookie = new SimpleCookie("name", "value", "/path");
+ $this->assertFalse($cookie->isValidPath("/"));
+ $this->assertTrue($cookie->isValidPath("/path/"));
+ $this->assertTrue($cookie->isValidPath("/path/more"));
+ }
+
+ function testSessionExpiring() {
+ $cookie = new SimpleCookie("name", "value", "/path");
+ $this->assertTrue($cookie->isExpired(0));
+ }
+
+ function testTimestampExpiry() {
+ $cookie = new SimpleCookie("name", "value", "/path", 456);
+ $this->assertFalse($cookie->isExpired(0));
+ $this->assertTrue($cookie->isExpired(457));
+ $this->assertFalse($cookie->isExpired(455));
+ }
+
+ function testDateExpiry() {
+ $cookie = new SimpleCookie(
+ "name",
+ "value",
+ "/path",
+ "Mon, 18 Nov 2002 15:50:29 GMT");
+ $this->assertTrue($cookie->isExpired("Mon, 18 Nov 2002 15:50:30 GMT"));
+ $this->assertFalse($cookie->isExpired("Mon, 18 Nov 2002 15:50:28 GMT"));
+ }
+
+ function testAging() {
+ $cookie = new SimpleCookie("name", "value", "/path", 200);
+ $cookie->agePrematurely(199);
+ $this->assertFalse($cookie->isExpired(0));
+ $cookie->agePrematurely(2);
+ $this->assertTrue($cookie->isExpired(0));
+ }
+}
+
+class TestOfCookieJar extends UnitTestCase {
+
+ function testAddCookie() {
+ $jar = new SimpleCookieJar();
+ $jar->setCookie("a", "A");
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A'));
+ }
+
+ function testHostFilter() {
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'A', 'my-host.com');
+ $jar->setCookie('b', 'B', 'another-host.com');
+ $jar->setCookie('c', 'C');
+ $this->assertEqual(
+ $jar->selectAsPairs(new SimpleUrl('my-host.com')),
+ array('a=A', 'c=C'));
+ $this->assertEqual(
+ $jar->selectAsPairs(new SimpleUrl('another-host.com')),
+ array('b=B', 'c=C'));
+ $this->assertEqual(
+ $jar->selectAsPairs(new SimpleUrl('www.another-host.com')),
+ array('b=B', 'c=C'));
+ $this->assertEqual(
+ $jar->selectAsPairs(new SimpleUrl('new-host.org')),
+ array('c=C'));
+ $this->assertEqual(
+ $jar->selectAsPairs(new SimpleUrl('/')),
+ array('a=A', 'b=B', 'c=C'));
+ }
+
+ function testPathFilter() {
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'A', false, '/path/');
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array());
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/elsewhere')), array());
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/')), array('a=A'));
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path')), array('a=A'));
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/pa')), array());
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/here')), array('a=A'));
+ }
+
+ function testPathFilterDeeply() {
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'A', false, '/path/more_path/');
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/')), array());
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path')), array());
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/pa')), array());
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/more_path/')), array('a=A'));
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/more_path/and_more')), array('a=A'));
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/not_here/')), array());
+ }
+
+ function testMultipleCookieWithDifferentPathsButSameName() {
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'abc', false, '/');
+ $jar->setCookie('a', '123', false, '/path/here/');
+ $this->assertEqual(
+ $jar->selectAsPairs(new SimpleUrl('/')),
+ array('a=abc'));
+ $this->assertEqual(
+ $jar->selectAsPairs(new SimpleUrl('my-host.com/')),
+ array('a=abc'));
+ $this->assertEqual(
+ $jar->selectAsPairs(new SimpleUrl('my-host.com/path/')),
+ array('a=abc'));
+ $this->assertEqual(
+ $jar->selectAsPairs(new SimpleUrl('my-host.com/path/here')),
+ array('a=abc', 'a=123'));
+ $this->assertEqual(
+ $jar->selectAsPairs(new SimpleUrl('my-host.com/path/here/there')),
+ array('a=abc', 'a=123'));
+ }
+
+ function testOverwrite() {
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'abc', false, '/');
+ $jar->setCookie('a', 'cde', false, '/');
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=cde'));
+ }
+
+ function testClearSessionCookies() {
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'A', false, '/');
+ $jar->restartSession();
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array());
+ }
+
+ function testExpiryFilterByDate() {
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'A', false, '/', 'Wed, 25-Dec-02 04:24:20 GMT');
+ $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT");
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A'));
+ $jar->restartSession("Wed, 25-Dec-02 04:24:21 GMT");
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array());
+ }
+
+ function testExpiryFilterByAgeing() {
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'A', false, '/', 'Wed, 25-Dec-02 04:24:20 GMT');
+ $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT");
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A'));
+ $jar->agePrematurely(2);
+ $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT");
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array());
+ }
+
+ function testCookieClearing() {
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'abc', false, '/');
+ $jar->setCookie('a', '', false, '/');
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a='));
+ }
+
+ function testCookieClearByLoweringDate() {
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'abc', false, '/', 'Wed, 25-Dec-02 04:24:21 GMT');
+ $jar->setCookie('a', 'def', false, '/', 'Wed, 25-Dec-02 04:24:19 GMT');
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=def'));
+ $jar->restartSession('Wed, 25-Dec-02 04:24:20 GMT');
+ $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array());
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/detached_test.php b/3rdparty/simpletest/test/detached_test.php
new file mode 100755
index 00000000000..f651d97eb61
--- /dev/null
+++ b/3rdparty/simpletest/test/detached_test.php
@@ -0,0 +1,15 @@
+<?php
+// $Id: detached_test.php 1884 2009-07-01 16:30:40Z lastcraft $
+require_once('../detached.php');
+require_once('../reporter.php');
+
+// The following URL will depend on your own installation.
+$command = 'php ' . dirname(__FILE__) . '/visual_test.php xml';
+
+$test = new TestSuite('Remote tests');
+$test->add(new DetachedTestCase($command));
+if (SimpleReporter::inCli()) {
+ exit ($test->run(new TextReporter()) ? 0 : 1);
+}
+$test->run(new HtmlReporter());
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/dumper_test.php b/3rdparty/simpletest/test/dumper_test.php
new file mode 100755
index 00000000000..789047de924
--- /dev/null
+++ b/3rdparty/simpletest/test/dumper_test.php
@@ -0,0 +1,88 @@
+<?php
+// $Id: dumper_test.php 1505 2007-04-30 23:39:59Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+
+class DumperDummy {
+}
+
+class TestOfTextFormatting extends UnitTestCase {
+
+ function testClipping() {
+ $dumper = new SimpleDumper();
+ $this->assertEqual(
+ $dumper->clipString("Hello", 6),
+ "Hello",
+ "Hello, 6->%s");
+ $this->assertEqual(
+ $dumper->clipString("Hello", 5),
+ "Hello",
+ "Hello, 5->%s");
+ $this->assertEqual(
+ $dumper->clipString("Hello world", 3),
+ "Hel...",
+ "Hello world, 3->%s");
+ $this->assertEqual(
+ $dumper->clipString("Hello world", 6, 3),
+ "Hello ...",
+ "Hello world, 6, 3->%s");
+ $this->assertEqual(
+ $dumper->clipString("Hello world", 3, 6),
+ "...o w...",
+ "Hello world, 3, 6->%s");
+ $this->assertEqual(
+ $dumper->clipString("Hello world", 4, 11),
+ "...orld",
+ "Hello world, 4, 11->%s");
+ $this->assertEqual(
+ $dumper->clipString("Hello world", 4, 12),
+ "...orld",
+ "Hello world, 4, 12->%s");
+ }
+
+ function testDescribeNull() {
+ $dumper = new SimpleDumper();
+ $this->assertPattern('/null/i', $dumper->describeValue(null));
+ }
+
+ function testDescribeBoolean() {
+ $dumper = new SimpleDumper();
+ $this->assertPattern('/boolean/i', $dumper->describeValue(true));
+ $this->assertPattern('/true/i', $dumper->describeValue(true));
+ $this->assertPattern('/false/i', $dumper->describeValue(false));
+ }
+
+ function testDescribeString() {
+ $dumper = new SimpleDumper();
+ $this->assertPattern('/string/i', $dumper->describeValue('Hello'));
+ $this->assertPattern('/Hello/', $dumper->describeValue('Hello'));
+ }
+
+ function testDescribeInteger() {
+ $dumper = new SimpleDumper();
+ $this->assertPattern('/integer/i', $dumper->describeValue(35));
+ $this->assertPattern('/35/', $dumper->describeValue(35));
+ }
+
+ function testDescribeFloat() {
+ $dumper = new SimpleDumper();
+ $this->assertPattern('/float/i', $dumper->describeValue(0.99));
+ $this->assertPattern('/0\.99/', $dumper->describeValue(0.99));
+ }
+
+ function testDescribeArray() {
+ $dumper = new SimpleDumper();
+ $this->assertPattern('/array/i', $dumper->describeValue(array(1, 4)));
+ $this->assertPattern('/2/i', $dumper->describeValue(array(1, 4)));
+ }
+
+ function testDescribeObject() {
+ $dumper = new SimpleDumper();
+ $this->assertPattern(
+ '/object/i',
+ $dumper->describeValue(new DumperDummy()));
+ $this->assertPattern(
+ '/DumperDummy/i',
+ $dumper->describeValue(new DumperDummy()));
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/eclipse_test.php b/3rdparty/simpletest/test/eclipse_test.php
new file mode 100755
index 00000000000..c90cbc918fd
--- /dev/null
+++ b/3rdparty/simpletest/test/eclipse_test.php
@@ -0,0 +1,32 @@
+<?php
+// $Id: eclipse_test.php 1739 2008-04-09 20:48:37Z edwardzyang $
+
+//To run this from the eclipse plugin...you need to make sure that the
+//SimpleTest path in the preferences is the same as the location of the
+//eclipse.php file below otherwise you end up with two "different" eclipse.php
+//files included and that does not work...
+
+include_once(dirname(__FILE__) . '/../eclipse.php');
+Mock::generate('SimpleSocket');
+
+class TestOfEclipse extends UnitTestCase {
+
+ function testPass() {
+ $listener = &new MockSimpleSocket();
+
+ $fullpath = realpath(dirname(__FILE__).'/support/test1.php');
+ $testpath = EclipseReporter::escapeVal($fullpath);
+ $expected = "{status:\"pass\",message:\"pass1 at [$testpath line 4]\",group:\"$testpath\",case:\"test1\",method:\"test_pass\"}";
+ //this should work...but it doesn't so the next line and the last line are the hacks
+ //$listener->expectOnce('write',array($expected));
+ $listener->setReturnValue('write',-1);
+
+ $pathparts = pathinfo($fullpath);
+ $filename = $pathparts['basename'];
+ $test= &new TestSuite($filename);
+ $test->addTestFile($fullpath);
+ $test->run(new EclipseReporter($listener));
+ $this->assertEqual($expected,$listener->output);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/encoding_test.php b/3rdparty/simpletest/test/encoding_test.php
new file mode 100755
index 00000000000..a09236e057c
--- /dev/null
+++ b/3rdparty/simpletest/test/encoding_test.php
@@ -0,0 +1,240 @@
+<?php
+// $Id: encoding_test.php 1963 2009-10-07 11:57:52Z maetl_ $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../url.php');
+require_once(dirname(__FILE__) . '/../socket.php');
+
+Mock::generate('SimpleSocket');
+
+class TestOfEncodedParts extends UnitTestCase {
+
+ function testFormEncodedAsKeyEqualsValue() {
+ $pair = new SimpleEncodedPair('a', 'A');
+ $this->assertEqual($pair->asRequest(), 'a=A');
+ }
+
+ function testMimeEncodedAsHeadersAndContent() {
+ $pair = new SimpleEncodedPair('a', 'A');
+ $this->assertEqual(
+ $pair->asMime(),
+ "Content-Disposition: form-data; name=\"a\"\r\n\r\nA");
+ }
+
+ function testAttachmentEncodedAsHeadersWithDispositionAndContent() {
+ $part = new SimpleAttachment('a', 'A', 'aaa.txt');
+ $this->assertEqual(
+ $part->asMime(),
+ "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" .
+ "Content-Type: text/plain\r\n\r\nA");
+ }
+}
+
+class TestOfEncoding extends UnitTestCase {
+ private $content_so_far;
+
+ function write($content) {
+ $this->content_so_far .= $content;
+ }
+
+ function clear() {
+ $this->content_so_far = '';
+ }
+
+ function assertWritten($encoding, $content, $message = '%s') {
+ $this->clear();
+ $encoding->writeTo($this);
+ $this->assertIdentical($this->content_so_far, $content, $message);
+ }
+
+ function testGetEmpty() {
+ $encoding = new SimpleGetEncoding();
+ $this->assertIdentical($encoding->getValue('a'), false);
+ $this->assertIdentical($encoding->asUrlRequest(), '');
+ }
+
+ function testPostEmpty() {
+ $encoding = new SimplePostEncoding();
+ $this->assertIdentical($encoding->getValue('a'), false);
+ $this->assertWritten($encoding, '');
+ }
+
+ function testPrefilled() {
+ $encoding = new SimplePostEncoding(array('a' => 'aaa'));
+ $this->assertIdentical($encoding->getValue('a'), 'aaa');
+ $this->assertWritten($encoding, 'a=aaa');
+ }
+
+ function testPrefilledWithTwoLevels() {
+ $query = array('a' => array('aa' => 'aaa'));
+ $encoding = new SimplePostEncoding($query);
+ $this->assertTrue($encoding->hasMoreThanOneLevel($query));
+ $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[aa]' => 'aaa'));
+ $this->assertIdentical($encoding->getValue('a[aa]'), 'aaa');
+ $this->assertWritten($encoding, 'a%5Baa%5D=aaa');
+ }
+
+ function testPrefilledWithThreeLevels() {
+ $query = array('a' => array('aa' => array('aaa' => 'aaaa')));
+ $encoding = new SimplePostEncoding($query);
+ $this->assertTrue($encoding->hasMoreThanOneLevel($query));
+ $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[aa][aaa]' => 'aaaa'));
+ $this->assertIdentical($encoding->getValue('a[aa][aaa]'), 'aaaa');
+ $this->assertWritten($encoding, 'a%5Baa%5D%5Baaa%5D=aaaa');
+ }
+
+ function testPrefilledWithObject() {
+ $encoding = new SimplePostEncoding(new SimpleEncoding(array('a' => 'aaa')));
+ $this->assertIdentical($encoding->getValue('a'), 'aaa');
+ $this->assertWritten($encoding, 'a=aaa');
+ }
+
+ function testMultiplePrefilled() {
+ $query = array('a' => array('a1', 'a2'));
+ $encoding = new SimplePostEncoding($query);
+ $this->assertTrue($encoding->hasMoreThanOneLevel($query));
+ $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[0]' => 'a1', 'a[1]' => 'a2'));
+ $this->assertIdentical($encoding->getValue('a[0]'), 'a1');
+ $this->assertIdentical($encoding->getValue('a[1]'), 'a2');
+ $this->assertWritten($encoding, 'a%5B0%5D=a1&a%5B1%5D=a2');
+ }
+
+ function testSingleParameter() {
+ $encoding = new SimplePostEncoding();
+ $encoding->add('a', 'Hello');
+ $this->assertEqual($encoding->getValue('a'), 'Hello');
+ $this->assertWritten($encoding, 'a=Hello');
+ }
+
+ function testFalseParameter() {
+ $encoding = new SimplePostEncoding();
+ $encoding->add('a', false);
+ $this->assertEqual($encoding->getValue('a'), false);
+ $this->assertWritten($encoding, '');
+ }
+
+ function testUrlEncoding() {
+ $encoding = new SimplePostEncoding();
+ $encoding->add('a', 'Hello there!');
+ $this->assertWritten($encoding, 'a=Hello+there%21');
+ }
+
+ function testUrlEncodingOfKey() {
+ $encoding = new SimplePostEncoding();
+ $encoding->add('a!', 'Hello');
+ $this->assertWritten($encoding, 'a%21=Hello');
+ }
+
+ function testMultipleParameter() {
+ $encoding = new SimplePostEncoding();
+ $encoding->add('a', 'Hello');
+ $encoding->add('b', 'Goodbye');
+ $this->assertWritten($encoding, 'a=Hello&b=Goodbye');
+ }
+
+ function testEmptyParameters() {
+ $encoding = new SimplePostEncoding();
+ $encoding->add('a', '');
+ $encoding->add('b', '');
+ $this->assertWritten($encoding, 'a=&b=');
+ }
+
+ function testRepeatedParameter() {
+ $encoding = new SimplePostEncoding();
+ $encoding->add('a', 'Hello');
+ $encoding->add('a', 'Goodbye');
+ $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye'));
+ $this->assertWritten($encoding, 'a=Hello&a=Goodbye');
+ }
+
+ function testAddingLists() {
+ $encoding = new SimplePostEncoding();
+ $encoding->add('a', array('Hello', 'Goodbye'));
+ $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye'));
+ $this->assertWritten($encoding, 'a=Hello&a=Goodbye');
+ }
+
+ function testMergeInHash() {
+ $encoding = new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B'));
+ $encoding->merge(array('a' => 'A2'));
+ $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2'));
+ $this->assertIdentical($encoding->getValue('b'), 'B');
+ }
+
+ function testMergeInObject() {
+ $encoding = new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B'));
+ $encoding->merge(new SimpleEncoding(array('a' => 'A2')));
+ $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2'));
+ $this->assertIdentical($encoding->getValue('b'), 'B');
+ }
+
+ function testPrefilledMultipart() {
+ $encoding = new SimpleMultipartEncoding(array('a' => 'aaa'), 'boundary');
+ $this->assertIdentical($encoding->getValue('a'), 'aaa');
+ $this->assertwritten($encoding,
+ "--boundary\r\n" .
+ "Content-Disposition: form-data; name=\"a\"\r\n" .
+ "\r\n" .
+ "aaa\r\n" .
+ "--boundary--\r\n");
+ }
+
+ function testAttachment() {
+ $encoding = new SimpleMultipartEncoding(array(), 'boundary');
+ $encoding->attach('a', 'aaa', 'aaa.txt');
+ $this->assertIdentical($encoding->getValue('a'), 'aaa.txt');
+ $this->assertwritten($encoding,
+ "--boundary\r\n" .
+ "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" .
+ "Content-Type: text/plain\r\n" .
+ "\r\n" .
+ "aaa\r\n" .
+ "--boundary--\r\n");
+ }
+
+ function testEntityEncodingDefaultContentType() {
+ $encoding = new SimpleEntityEncoding();
+ $this->assertIdentical($encoding->getContentType(), 'application/x-www-form-urlencoded');
+ $this->assertWritten($encoding, '');
+ }
+
+ function testEntityEncodingTextBody() {
+ $encoding = new SimpleEntityEncoding('plain text');
+ $this->assertIdentical($encoding->getContentType(), 'text/plain');
+ $this->assertWritten($encoding, 'plain text');
+ }
+
+ function testEntityEncodingXmlBody() {
+ $encoding = new SimpleEntityEncoding('<p><a>xml</b><b>text</b></p>', 'text/xml');
+ $this->assertIdentical($encoding->getContentType(), 'text/xml');
+ $this->assertWritten($encoding, '<p><a>xml</b><b>text</b></p>');
+ }
+}
+
+class TestOfEncodingHeaders extends UnitTestCase {
+
+ function testEmptyEncodingWritesZeroContentLength() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("Content-Length: 0\r\n"));
+ $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n"));
+ $encoding = new SimpleEntityEncoding();
+ $encoding->writeHeadersTo($socket);
+ }
+
+ function testTextEncodingWritesDefaultContentType() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("Content-Length: 18\r\n"));
+ $socket->expectAt(1, 'write', array("Content-Type: text/plain\r\n"));
+ $encoding = new SimpleEntityEncoding('one two three four');
+ $encoding->writeHeadersTo($socket);
+ }
+
+ function testEmptyMultipartEncodingWritesEndBoundaryContentLength() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("Content-Length: 14\r\n"));
+ $socket->expectAt(1, 'write', array("Content-Type: multipart/form-data; boundary=boundary\r\n"));
+ $encoding = new SimpleMultipartEncoding(array(), 'boundary');
+ $encoding->writeHeadersTo($socket);
+ }
+
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/errors_test.php b/3rdparty/simpletest/test/errors_test.php
new file mode 100755
index 00000000000..ebb9e05891f
--- /dev/null
+++ b/3rdparty/simpletest/test/errors_test.php
@@ -0,0 +1,229 @@
+<?php
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../errors.php');
+require_once(dirname(__FILE__) . '/../expectation.php');
+require_once(dirname(__FILE__) . '/../test_case.php');
+Mock::generate('SimpleTestCase');
+Mock::generate('SimpleExpectation');
+SimpleTest::ignore('MockSimpleTestCase');
+
+class TestOfErrorQueue extends UnitTestCase {
+
+ function setUp() {
+ $context = SimpleTest::getContext();
+ $queue = $context->get('SimpleErrorQueue');
+ $queue->clear();
+ }
+
+ function tearDown() {
+ $context = SimpleTest::getContext();
+ $queue = $context->get('SimpleErrorQueue');
+ $queue->clear();
+ }
+
+ function testExpectationMatchCancelsIncomingError() {
+ $test = new MockSimpleTestCase();
+ $test->expectOnce('assert', array(
+ new IdenticalExpectation(new AnythingExpectation()),
+ 'B',
+ 'a message'));
+ $test->setReturnValue('assert', true);
+ $test->expectNever('error');
+ $queue = new SimpleErrorQueue();
+ $queue->setTestCase($test);
+ $queue->expectError(new AnythingExpectation(), 'a message');
+ $queue->add(1024, 'B', 'b.php', 100);
+ }
+}
+
+class TestOfErrorTrap extends UnitTestCase {
+ private $old;
+
+ function setUp() {
+ $this->old = error_reporting(E_ALL);
+ set_error_handler('SimpleTestErrorHandler');
+ }
+
+ function tearDown() {
+ restore_error_handler();
+ error_reporting($this->old);
+ }
+
+ function testQueueStartsEmpty() {
+ $context = SimpleTest::getContext();
+ $queue = $context->get('SimpleErrorQueue');
+ $this->assertFalse($queue->extract());
+ }
+
+ function testErrorsAreSwallowedByMatchingExpectation() {
+ $this->expectError('Ouch!');
+ trigger_error('Ouch!');
+ }
+
+ function testErrorsAreSwallowedInOrder() {
+ $this->expectError('a');
+ $this->expectError('b');
+ trigger_error('a');
+ trigger_error('b');
+ }
+
+ function testAnyErrorCanBeSwallowed() {
+ $this->expectError();
+ trigger_error('Ouch!');
+ }
+
+ function testErrorCanBeSwallowedByPatternMatching() {
+ $this->expectError(new PatternExpectation('/ouch/i'));
+ trigger_error('Ouch!');
+ }
+
+ function testErrorWithPercentsPassesWithNoSprintfError() {
+ $this->expectError("%");
+ trigger_error('%');
+ }
+}
+
+class TestOfErrors extends UnitTestCase {
+ private $old;
+
+ function setUp() {
+ $this->old = error_reporting(E_ALL);
+ }
+
+ function tearDown() {
+ error_reporting($this->old);
+ }
+
+ function testDefaultWhenAllReported() {
+ error_reporting(E_ALL);
+ $this->expectError('Ouch!');
+ trigger_error('Ouch!');
+ }
+
+ function testNoticeWhenReported() {
+ error_reporting(E_ALL);
+ $this->expectError('Ouch!');
+ trigger_error('Ouch!', E_USER_NOTICE);
+ }
+
+ function testWarningWhenReported() {
+ error_reporting(E_ALL);
+ $this->expectError('Ouch!');
+ trigger_error('Ouch!', E_USER_WARNING);
+ }
+
+ function testErrorWhenReported() {
+ error_reporting(E_ALL);
+ $this->expectError('Ouch!');
+ trigger_error('Ouch!', E_USER_ERROR);
+ }
+
+ function testNoNoticeWhenNotReported() {
+ error_reporting(0);
+ trigger_error('Ouch!', E_USER_NOTICE);
+ }
+
+ function testNoWarningWhenNotReported() {
+ error_reporting(0);
+ trigger_error('Ouch!', E_USER_WARNING);
+ }
+
+ function testNoticeSuppressedWhenReported() {
+ error_reporting(E_ALL);
+ @trigger_error('Ouch!', E_USER_NOTICE);
+ }
+
+ function testWarningSuppressedWhenReported() {
+ error_reporting(E_ALL);
+ @trigger_error('Ouch!', E_USER_WARNING);
+ }
+
+ function testErrorWithPercentsReportedWithNoSprintfError() {
+ $this->expectError('%');
+ trigger_error('%');
+ }
+}
+
+class TestOfPHP52RecoverableErrors extends UnitTestCase {
+ function skip() {
+ $this->skipIf(
+ version_compare(phpversion(), '5.2', '<'),
+ 'E_RECOVERABLE_ERROR not tested for PHP below 5.2');
+ }
+
+ function testError() {
+ eval('
+ class RecoverableErrorTestingStub {
+ function ouch(RecoverableErrorTestingStub $obj) {
+ }
+ }
+ ');
+
+ $stub = new RecoverableErrorTestingStub();
+ $this->expectError(new PatternExpectation('/must be an instance of RecoverableErrorTestingStub/i'));
+ $stub->ouch(new stdClass());
+ }
+}
+
+class TestOfErrorsExcludingPHP52AndAbove extends UnitTestCase {
+ function skip() {
+ $this->skipIf(
+ version_compare(phpversion(), '5.2', '>='),
+ 'E_USER_ERROR not tested for PHP 5.2 and above');
+ }
+
+ function testNoErrorWhenNotReported() {
+ error_reporting(0);
+ trigger_error('Ouch!', E_USER_ERROR);
+ }
+
+ function testErrorSuppressedWhenReported() {
+ error_reporting(E_ALL);
+ @trigger_error('Ouch!', E_USER_ERROR);
+ }
+}
+
+SimpleTest::ignore('TestOfNotEnoughErrors');
+/**
+ * This test is ignored as it is used by {@link TestRunnerForLeftOverAndNotEnoughErrors}
+ * to verify that it fails as expected.
+ *
+ * @ignore
+ */
+class TestOfNotEnoughErrors extends UnitTestCase {
+ function testExpectTwoErrorsThrowOne() {
+ $this->expectError('Error 1');
+ trigger_error('Error 1');
+ $this->expectError('Error 2');
+ }
+}
+
+SimpleTest::ignore('TestOfLeftOverErrors');
+/**
+ * This test is ignored as it is used by {@link TestRunnerForLeftOverAndNotEnoughErrors}
+ * to verify that it fails as expected.
+ *
+ * @ignore
+ */
+class TestOfLeftOverErrors extends UnitTestCase {
+ function testExpectOneErrorGetTwo() {
+ $this->expectError('Error 1');
+ trigger_error('Error 1');
+ trigger_error('Error 2');
+ }
+}
+
+class TestRunnerForLeftOverAndNotEnoughErrors extends UnitTestCase {
+ function testRunLeftOverErrorsTestCase() {
+ $test = new TestOfLeftOverErrors();
+ $this->assertFalse($test->run(new SimpleReporter()));
+ }
+
+ function testRunNotEnoughErrors() {
+ $test = new TestOfNotEnoughErrors();
+ $this->assertFalse($test->run(new SimpleReporter()));
+ }
+}
+
+// TODO: Add stacked error handler test
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/exceptions_test.php b/3rdparty/simpletest/test/exceptions_test.php
new file mode 100755
index 00000000000..1011543d4fa
--- /dev/null
+++ b/3rdparty/simpletest/test/exceptions_test.php
@@ -0,0 +1,183 @@
+<?php
+// $Id: exceptions_test.php 1882 2009-07-01 14:30:05Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../exceptions.php');
+require_once(dirname(__FILE__) . '/../expectation.php');
+require_once(dirname(__FILE__) . '/../test_case.php');
+Mock::generate('SimpleTestCase');
+Mock::generate('SimpleExpectation');
+
+class MyTestException extends Exception {}
+class HigherTestException extends MyTestException {}
+class OtherTestException extends Exception {}
+
+class TestOfExceptionExpectation extends UnitTestCase {
+
+ function testExceptionClassAsStringWillMatchExceptionsRootedOnThatClass() {
+ $expectation = new ExceptionExpectation('MyTestException');
+ $this->assertTrue($expectation->test(new MyTestException()));
+ $this->assertTrue($expectation->test(new HigherTestException()));
+ $this->assertFalse($expectation->test(new OtherTestException()));
+ }
+
+ function testMatchesClassAndMessageWhenExceptionExpected() {
+ $expectation = new ExceptionExpectation(new MyTestException('Hello'));
+ $this->assertTrue($expectation->test(new MyTestException('Hello')));
+ $this->assertFalse($expectation->test(new HigherTestException('Hello')));
+ $this->assertFalse($expectation->test(new OtherTestException('Hello')));
+ $this->assertFalse($expectation->test(new MyTestException('Goodbye')));
+ $this->assertFalse($expectation->test(new MyTestException()));
+ }
+
+ function testMessagelessExceptionMatchesOnlyOnClass() {
+ $expectation = new ExceptionExpectation(new MyTestException());
+ $this->assertTrue($expectation->test(new MyTestException()));
+ $this->assertFalse($expectation->test(new HigherTestException()));
+ }
+}
+
+class TestOfExceptionTrap extends UnitTestCase {
+
+ function testNoExceptionsInQueueMeansNoTestMessages() {
+ $test = new MockSimpleTestCase();
+ $test->expectNever('assert');
+ $queue = new SimpleExceptionTrap();
+ $this->assertFalse($queue->isExpected($test, new Exception()));
+ }
+
+ function testMatchingExceptionGivesTrue() {
+ $expectation = new MockSimpleExpectation();
+ $expectation->setReturnValue('test', true);
+ $test = new MockSimpleTestCase();
+ $test->setReturnValue('assert', true);
+ $queue = new SimpleExceptionTrap();
+ $queue->expectException($expectation, 'message');
+ $this->assertTrue($queue->isExpected($test, new Exception()));
+ }
+
+ function testMatchingExceptionTriggersAssertion() {
+ $test = new MockSimpleTestCase();
+ $test->expectOnce('assert', array(
+ '*',
+ new ExceptionExpectation(new Exception()),
+ 'message'));
+ $queue = new SimpleExceptionTrap();
+ $queue->expectException(new ExceptionExpectation(new Exception()), 'message');
+ $queue->isExpected($test, new Exception());
+ }
+}
+
+class TestOfCatchingExceptions extends UnitTestCase {
+
+ function testCanCatchAnyExpectedException() {
+ $this->expectException();
+ throw new Exception();
+ }
+
+ function testCanMatchExceptionByClass() {
+ $this->expectException('MyTestException');
+ throw new HigherTestException();
+ }
+
+ function testCanMatchExceptionExactly() {
+ $this->expectException(new Exception('Ouch'));
+ throw new Exception('Ouch');
+ }
+
+ function testLastListedExceptionIsTheOneThatCounts() {
+ $this->expectException('OtherTestException');
+ $this->expectException('MyTestException');
+ throw new HigherTestException();
+ }
+}
+
+class TestOfIgnoringExceptions extends UnitTestCase {
+
+ function testCanIgnoreAnyException() {
+ $this->ignoreException();
+ throw new Exception();
+ }
+
+ function testCanIgnoreSpecificException() {
+ $this->ignoreException('MyTestException');
+ throw new MyTestException();
+ }
+
+ function testCanIgnoreExceptionExactly() {
+ $this->ignoreException(new Exception('Ouch'));
+ throw new Exception('Ouch');
+ }
+
+ function testIgnoredExceptionsDoNotMaskExpectedExceptions() {
+ $this->ignoreException('Exception');
+ $this->expectException('MyTestException');
+ throw new MyTestException();
+ }
+
+ function testCanIgnoreMultipleExceptions() {
+ $this->ignoreException('MyTestException');
+ $this->ignoreException('OtherTestException');
+ throw new OtherTestException();
+ }
+}
+
+class TestOfCallingTearDownAfterExceptions extends UnitTestCase {
+ private $debri = 0;
+
+ function tearDown() {
+ $this->debri--;
+ }
+
+ function testLeaveSomeDebri() {
+ $this->debri++;
+ $this->expectException();
+ throw new Exception(__FUNCTION__);
+ }
+
+ function testDebriWasRemovedOnce() {
+ $this->assertEqual($this->debri, 0);
+ }
+}
+
+class TestOfExceptionThrownInSetUpDoesNotRunTestBody extends UnitTestCase {
+
+ function setUp() {
+ $this->expectException();
+ throw new Exception();
+ }
+
+ function testShouldNotBeRun() {
+ $this->fail('This test body should not be run');
+ }
+
+ function testShouldNotBeRunEither() {
+ $this->fail('This test body should not be run either');
+ }
+}
+
+class TestOfExpectExceptionWithSetUp extends UnitTestCase {
+
+ function setUp() {
+ $this->expectException();
+ }
+
+ function testThisExceptionShouldBeCaught() {
+ throw new Exception();
+ }
+
+ function testJustThrowingMyTestException() {
+ throw new MyTestException();
+ }
+}
+
+class TestOfThrowingExceptionsInTearDown extends UnitTestCase {
+
+ function tearDown() {
+ throw new Exception();
+ }
+
+ function testDoesntFatal() {
+ $this->expectException();
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/expectation_test.php b/3rdparty/simpletest/test/expectation_test.php
new file mode 100755
index 00000000000..31fbe65e683
--- /dev/null
+++ b/3rdparty/simpletest/test/expectation_test.php
@@ -0,0 +1,317 @@
+<?php
+// $Id: expectation_test.php 2009 2011-04-28 08:57:25Z pp11 $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../expectation.php');
+
+class TestOfEquality extends UnitTestCase {
+
+ function testBoolean() {
+ $is_true = new EqualExpectation(true);
+ $this->assertTrue($is_true->test(true));
+ $this->assertFalse($is_true->test(false));
+ }
+
+ function testStringMatch() {
+ $hello = new EqualExpectation("Hello");
+ $this->assertTrue($hello->test("Hello"));
+ $this->assertFalse($hello->test("Goodbye"));
+ }
+
+ function testInteger() {
+ $fifteen = new EqualExpectation(15);
+ $this->assertTrue($fifteen->test(15));
+ $this->assertFalse($fifteen->test(14));
+ }
+
+ function testFloat() {
+ $pi = new EqualExpectation(3.14);
+ $this->assertTrue($pi->test(3.14));
+ $this->assertFalse($pi->test(3.15));
+ }
+
+ function testArray() {
+ $colours = new EqualExpectation(array("r", "g", "b"));
+ $this->assertTrue($colours->test(array("r", "g", "b")));
+ $this->assertFalse($colours->test(array("g", "b", "r")));
+ }
+
+ function testHash() {
+ $is_blue = new EqualExpectation(array("r" => 0, "g" => 0, "b" => 255));
+ $this->assertTrue($is_blue->test(array("r" => 0, "g" => 0, "b" => 255)));
+ $this->assertFalse($is_blue->test(array("r" => 0, "g" => 255, "b" => 0)));
+ }
+
+ function testHashWithOutOfOrderKeysShouldStillMatch() {
+ $any_order = new EqualExpectation(array('a' => 1, 'b' => 2));
+ $this->assertTrue($any_order->test(array('b' => 2, 'a' => 1)));
+ }
+}
+
+class TestOfWithin extends UnitTestCase {
+
+ function testWithinFloatingPointMargin() {
+ $within = new WithinMarginExpectation(1.0, 0.2);
+ $this->assertFalse($within->test(0.7));
+ $this->assertTrue($within->test(0.8));
+ $this->assertTrue($within->test(0.9));
+ $this->assertTrue($within->test(1.1));
+ $this->assertTrue($within->test(1.2));
+ $this->assertFalse($within->test(1.3));
+ }
+
+ function testOutsideFloatingPointMargin() {
+ $within = new OutsideMarginExpectation(1.0, 0.2);
+ $this->assertTrue($within->test(0.7));
+ $this->assertFalse($within->test(0.8));
+ $this->assertFalse($within->test(1.2));
+ $this->assertTrue($within->test(1.3));
+ }
+}
+
+class TestOfInequality extends UnitTestCase {
+
+ function testStringMismatch() {
+ $not_hello = new NotEqualExpectation("Hello");
+ $this->assertTrue($not_hello->test("Goodbye"));
+ $this->assertFalse($not_hello->test("Hello"));
+ }
+}
+
+class RecursiveNasty {
+ private $me;
+
+ function RecursiveNasty() {
+ $this->me = $this;
+ }
+}
+
+class OpaqueContainer {
+ private $stuff;
+ private $value;
+
+ public function __construct($value) {
+ $this->value = $value;
+ }
+}
+
+class DerivedOpaqueContainer extends OpaqueContainer {
+ // Deliberately have a variable whose name with the same suffix as a later
+ // variable
+ private $new_value = 1;
+
+ // Deliberately obscures the variable of the same name in the base
+ // class.
+ private $value;
+
+ public function __construct($value, $base_value) {
+ parent::__construct($base_value);
+ $this->value = $value;
+ }
+}
+
+class TestOfIdentity extends UnitTestCase {
+
+ function testType() {
+ $string = new IdenticalExpectation("37");
+ $this->assertTrue($string->test("37"));
+ $this->assertFalse($string->test(37));
+ $this->assertFalse($string->test("38"));
+ }
+
+ function _testNastyPhp5Bug() {
+ $this->assertFalse(new RecursiveNasty() != new RecursiveNasty());
+ }
+
+ function _testReallyHorribleRecursiveStructure() {
+ $hopeful = new IdenticalExpectation(new RecursiveNasty());
+ $this->assertTrue($hopeful->test(new RecursiveNasty()));
+ }
+
+ function testCanComparePrivateMembers() {
+ $expectFive = new IdenticalExpectation(new OpaqueContainer(5));
+ $this->assertTrue($expectFive->test(new OpaqueContainer(5)));
+ $this->assertFalse($expectFive->test(new OpaqueContainer(6)));
+ }
+
+ function testCanComparePrivateMembersOfObjectsInArrays() {
+ $expectFive = new IdenticalExpectation(array(new OpaqueContainer(5)));
+ $this->assertTrue($expectFive->test(array(new OpaqueContainer(5))));
+ $this->assertFalse($expectFive->test(array(new OpaqueContainer(6))));
+ }
+
+ function testCanComparePrivateMembersOfObjectsWherePrivateMemberOfBaseClassIsObscured() {
+ $expectFive = new IdenticalExpectation(array(new DerivedOpaqueContainer(1,2)));
+ $this->assertTrue($expectFive->test(array(new DerivedOpaqueContainer(1,2))));
+ $this->assertFalse($expectFive->test(array(new DerivedOpaqueContainer(0,2))));
+ $this->assertFalse($expectFive->test(array(new DerivedOpaqueContainer(0,9))));
+ $this->assertFalse($expectFive->test(array(new DerivedOpaqueContainer(1,0))));
+ }
+}
+
+class TransparentContainer {
+ public $value;
+
+ public function __construct($value) {
+ $this->value = $value;
+ }
+}
+
+class TestOfMemberComparison extends UnitTestCase {
+
+ function testMemberExpectationCanMatchPublicMember() {
+ $expect_five = new MemberExpectation('value', 5);
+ $this->assertTrue($expect_five->test(new TransparentContainer(5)));
+ $this->assertFalse($expect_five->test(new TransparentContainer(8)));
+ }
+
+ function testMemberExpectationCanMatchPrivateMember() {
+ $expect_five = new MemberExpectation('value', 5);
+ $this->assertTrue($expect_five->test(new OpaqueContainer(5)));
+ $this->assertFalse($expect_five->test(new OpaqueContainer(8)));
+ }
+
+ function testMemberExpectationCanMatchPrivateMemberObscuredByDerivedClass() {
+ $expect_five = new MemberExpectation('value', 5);
+ $this->assertTrue($expect_five->test(new DerivedOpaqueContainer(5,8)));
+ $this->assertTrue($expect_five->test(new DerivedOpaqueContainer(5,5)));
+ $this->assertFalse($expect_five->test(new DerivedOpaqueContainer(8,8)));
+ $this->assertFalse($expect_five->test(new DerivedOpaqueContainer(8,5)));
+ }
+
+}
+
+class DummyReferencedObject{}
+
+class TestOfReference extends UnitTestCase {
+
+ function testReference() {
+ $foo = "foo";
+ $ref = &$foo;
+ $not_ref = $foo;
+ $bar = "bar";
+
+ $expect = new ReferenceExpectation($foo);
+ $this->assertTrue($expect->test($ref));
+ $this->assertFalse($expect->test($not_ref));
+ $this->assertFalse($expect->test($bar));
+ }
+}
+
+class TestOfNonIdentity extends UnitTestCase {
+
+ function testType() {
+ $string = new NotIdenticalExpectation("37");
+ $this->assertTrue($string->test("38"));
+ $this->assertTrue($string->test(37));
+ $this->assertFalse($string->test("37"));
+ }
+}
+
+class TestOfPatterns extends UnitTestCase {
+
+ function testWanted() {
+ $pattern = new PatternExpectation('/hello/i');
+ $this->assertTrue($pattern->test("Hello world"));
+ $this->assertFalse($pattern->test("Goodbye world"));
+ }
+
+ function testUnwanted() {
+ $pattern = new NoPatternExpectation('/hello/i');
+ $this->assertFalse($pattern->test("Hello world"));
+ $this->assertTrue($pattern->test("Goodbye world"));
+ }
+}
+
+class ExpectedMethodTarget {
+ function hasThisMethod() {}
+}
+
+class TestOfMethodExistence extends UnitTestCase {
+
+ function testHasMethod() {
+ $instance = new ExpectedMethodTarget();
+ $expectation = new MethodExistsExpectation('hasThisMethod');
+ $this->assertTrue($expectation->test($instance));
+ $expectation = new MethodExistsExpectation('doesNotHaveThisMethod');
+ $this->assertFalse($expectation->test($instance));
+ }
+}
+
+class TestOfIsA extends UnitTestCase {
+
+ function testString() {
+ $expectation = new IsAExpectation('string');
+ $this->assertTrue($expectation->test('Hello'));
+ $this->assertFalse($expectation->test(5));
+ }
+
+ function testBoolean() {
+ $expectation = new IsAExpectation('boolean');
+ $this->assertTrue($expectation->test(true));
+ $this->assertFalse($expectation->test(1));
+ }
+
+ function testBool() {
+ $expectation = new IsAExpectation('bool');
+ $this->assertTrue($expectation->test(true));
+ $this->assertFalse($expectation->test(1));
+ }
+
+ function testDouble() {
+ $expectation = new IsAExpectation('double');
+ $this->assertTrue($expectation->test(5.0));
+ $this->assertFalse($expectation->test(5));
+ }
+
+ function testFloat() {
+ $expectation = new IsAExpectation('float');
+ $this->assertTrue($expectation->test(5.0));
+ $this->assertFalse($expectation->test(5));
+ }
+
+ function testReal() {
+ $expectation = new IsAExpectation('real');
+ $this->assertTrue($expectation->test(5.0));
+ $this->assertFalse($expectation->test(5));
+ }
+
+ function testInteger() {
+ $expectation = new IsAExpectation('integer');
+ $this->assertTrue($expectation->test(5));
+ $this->assertFalse($expectation->test(5.0));
+ }
+
+ function testInt() {
+ $expectation = new IsAExpectation('int');
+ $this->assertTrue($expectation->test(5));
+ $this->assertFalse($expectation->test(5.0));
+ }
+
+ function testScalar() {
+ $expectation = new IsAExpectation('scalar');
+ $this->assertTrue($expectation->test(5));
+ $this->assertFalse($expectation->test(array(5)));
+ }
+
+ function testNumeric() {
+ $expectation = new IsAExpectation('numeric');
+ $this->assertTrue($expectation->test(5));
+ $this->assertFalse($expectation->test('string'));
+ }
+
+ function testNull() {
+ $expectation = new IsAExpectation('null');
+ $this->assertTrue($expectation->test(null));
+ $this->assertFalse($expectation->test('string'));
+ }
+}
+
+class TestOfNotA extends UnitTestCase {
+
+ function testString() {
+ $expectation = new NotAExpectation('string');
+ $this->assertFalse($expectation->test('Hello'));
+ $this->assertTrue($expectation->test(5));
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/form_test.php b/3rdparty/simpletest/test/form_test.php
new file mode 100755
index 00000000000..70a18f2b3a0
--- /dev/null
+++ b/3rdparty/simpletest/test/form_test.php
@@ -0,0 +1,344 @@
+<?php
+// $Id: form_test.php 1996 2010-07-27 09:11:59Z pp11 $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../url.php');
+require_once(dirname(__FILE__) . '/../form.php');
+require_once(dirname(__FILE__) . '/../page.php');
+require_once(dirname(__FILE__) . '/../encoding.php');
+Mock::generate('SimplePage');
+
+class TestOfForm extends UnitTestCase {
+
+ function page($url, $action = false) {
+ $page = new MockSimplePage();
+ $page->returns('getUrl', new SimpleUrl($url));
+ $page->returns('expandUrl', new SimpleUrl($url));
+ return $page;
+ }
+
+ function testFormAttributes() {
+ $tag = new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php', 'id' => '33'));
+ $form = new SimpleForm($tag, $this->page('http://host/a/index.html'));
+ $this->assertEqual($form->getMethod(), 'get');
+ $this->assertIdentical($form->getId(), '33');
+ $this->assertNull($form->getValue(new SimpleByName('a')));
+ }
+
+ function testAction() {
+ $page = new MockSimplePage();
+ $page->expectOnce('expandUrl', array(new SimpleUrl('here.php')));
+ $page->setReturnValue('expandUrl', new SimpleUrl('http://host/here.php'));
+ $tag = new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php'));
+ $form = new SimpleForm($tag, $page);
+ $this->assertEqual($form->getAction(), new SimpleUrl('http://host/here.php'));
+ }
+
+ function testEmptyAction() {
+ $tag = new SimpleFormTag(array('method' => 'GET', 'action' => '', 'id' => '33'));
+ $form = new SimpleForm($tag, $this->page('http://host/a/index.html'));
+ $this->assertEqual(
+ $form->getAction(),
+ new SimpleUrl('http://host/a/index.html'));
+ }
+
+ function testMissingAction() {
+ $tag = new SimpleFormTag(array('method' => 'GET'));
+ $form = new SimpleForm($tag, $this->page('http://host/a/index.html'));
+ $this->assertEqual(
+ $form->getAction(),
+ new SimpleUrl('http://host/a/index.html'));
+ }
+
+ function testRootAction() {
+ $page = new MockSimplePage();
+ $page->expectOnce('expandUrl', array(new SimpleUrl('/')));
+ $page->setReturnValue('expandUrl', new SimpleUrl('http://host/'));
+ $tag = new SimpleFormTag(array('method' => 'GET', 'action' => '/'));
+ $form = new SimpleForm($tag, $page);
+ $this->assertEqual(
+ $form->getAction(),
+ new SimpleUrl('http://host/'));
+ }
+
+ function testDefaultFrameTargetOnForm() {
+ $page = new MockSimplePage();
+ $page->expectOnce('expandUrl', array(new SimpleUrl('here.php')));
+ $page->setReturnValue('expandUrl', new SimpleUrl('http://host/here.php'));
+ $tag = new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php'));
+ $form = new SimpleForm($tag, $page);
+ $form->setDefaultTarget('frame');
+ $expected = new SimpleUrl('http://host/here.php');
+ $expected->setTarget('frame');
+ $this->assertEqual($form->getAction(), $expected);
+ }
+
+ function testTextWidget() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $form->addWidget(new SimpleTextTag(
+ array('name' => 'me', 'type' => 'text', 'value' => 'Myself')));
+ $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Myself');
+ $this->assertTrue($form->setField(new SimpleByName('me'), 'Not me'));
+ $this->assertFalse($form->setField(new SimpleByName('not_present'), 'Not me'));
+ $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Not me');
+ $this->assertNull($form->getValue(new SimpleByName('not_present')));
+ }
+
+ function testTextWidgetById() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $form->addWidget(new SimpleTextTag(
+ array('name' => 'me', 'type' => 'text', 'value' => 'Myself', 'id' => 50)));
+ $this->assertIdentical($form->getValue(new SimpleById(50)), 'Myself');
+ $this->assertTrue($form->setField(new SimpleById(50), 'Not me'));
+ $this->assertIdentical($form->getValue(new SimpleById(50)), 'Not me');
+ }
+
+ function testTextWidgetByLabel() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $widget = new SimpleTextTag(array('name' => 'me', 'type' => 'text', 'value' => 'a'));
+ $form->addWidget($widget);
+ $widget->setLabel('thing');
+ $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'a');
+ $this->assertTrue($form->setField(new SimpleByLabel('thing'), 'b'));
+ $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'b');
+ }
+
+ function testSubmitEmpty() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $this->assertIdentical($form->submit(), new SimpleGetEncoding());
+ }
+
+ function testSubmitButton() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host'));
+ $form->addWidget(new SimpleSubmitTag(
+ array('type' => 'submit', 'name' => 'go', 'value' => 'Go!', 'id' => '9')));
+ $this->assertTrue($form->hasSubmit(new SimpleByName('go')));
+ $this->assertEqual($form->getValue(new SimpleByName('go')), 'Go!');
+ $this->assertEqual($form->getValue(new SimpleById(9)), 'Go!');
+ $this->assertEqual(
+ $form->submitButton(new SimpleByName('go')),
+ new SimpleGetEncoding(array('go' => 'Go!')));
+ $this->assertEqual(
+ $form->submitButton(new SimpleByLabel('Go!')),
+ new SimpleGetEncoding(array('go' => 'Go!')));
+ $this->assertEqual(
+ $form->submitButton(new SimpleById(9)),
+ new SimpleGetEncoding(array('go' => 'Go!')));
+ }
+
+ function testSubmitWithAdditionalParameters() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host'));
+ $form->addWidget(new SimpleSubmitTag(
+ array('type' => 'submit', 'name' => 'go', 'value' => 'Go!')));
+ $this->assertEqual(
+ $form->submitButton(new SimpleByLabel('Go!'), array('a' => 'A')),
+ new SimpleGetEncoding(array('go' => 'Go!', 'a' => 'A')));
+ }
+
+ function testSubmitButtonWithLabelOfSubmit() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host'));
+ $form->addWidget(new SimpleSubmitTag(
+ array('type' => 'submit', 'name' => 'test', 'value' => 'Submit')));
+ $this->assertEqual(
+ $form->submitButton(new SimpleByName('test')),
+ new SimpleGetEncoding(array('test' => 'Submit')));
+ $this->assertEqual(
+ $form->submitButton(new SimpleByLabel('Submit')),
+ new SimpleGetEncoding(array('test' => 'Submit')));
+ }
+
+ function testSubmitButtonWithWhitespacePaddedLabelOfSubmit() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host'));
+ $form->addWidget(new SimpleSubmitTag(
+ array('type' => 'submit', 'name' => 'test', 'value' => ' Submit ')));
+ $this->assertEqual(
+ $form->submitButton(new SimpleByLabel('Submit')),
+ new SimpleGetEncoding(array('test' => ' Submit ')));
+ }
+
+ function testImageSubmitButton() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $form->addWidget(new SimpleImageSubmitTag(array(
+ 'type' => 'image',
+ 'src' => 'source.jpg',
+ 'name' => 'go',
+ 'alt' => 'Go!',
+ 'id' => '9')));
+ $this->assertTrue($form->hasImage(new SimpleByLabel('Go!')));
+ $this->assertEqual(
+ $form->submitImage(new SimpleByLabel('Go!'), 100, 101),
+ new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101)));
+ $this->assertTrue($form->hasImage(new SimpleByName('go')));
+ $this->assertEqual(
+ $form->submitImage(new SimpleByName('go'), 100, 101),
+ new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101)));
+ $this->assertTrue($form->hasImage(new SimpleById(9)));
+ $this->assertEqual(
+ $form->submitImage(new SimpleById(9), 100, 101),
+ new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101)));
+ }
+
+ function testImageSubmitButtonWithAdditionalData() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $form->addWidget(new SimpleImageSubmitTag(array(
+ 'type' => 'image',
+ 'src' => 'source.jpg',
+ 'name' => 'go',
+ 'alt' => 'Go!')));
+ $this->assertEqual(
+ $form->submitImage(new SimpleByLabel('Go!'), 100, 101, array('a' => 'A')),
+ new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A')));
+ }
+
+ function testButtonTag() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host'));
+ $widget = new SimpleButtonTag(
+ array('type' => 'submit', 'name' => 'go', 'value' => 'Go', 'id' => '9'));
+ $widget->addContent('Go!');
+ $form->addWidget($widget);
+ $this->assertTrue($form->hasSubmit(new SimpleByName('go')));
+ $this->assertTrue($form->hasSubmit(new SimpleByLabel('Go!')));
+ $this->assertEqual(
+ $form->submitButton(new SimpleByName('go')),
+ new SimpleGetEncoding(array('go' => 'Go')));
+ $this->assertEqual(
+ $form->submitButton(new SimpleByLabel('Go!')),
+ new SimpleGetEncoding(array('go' => 'Go')));
+ $this->assertEqual(
+ $form->submitButton(new SimpleById(9)),
+ new SimpleGetEncoding(array('go' => 'Go')));
+ }
+
+ function testMultipleFieldsWithSameNameSubmitted() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $input = new SimpleTextTag(array('name' => 'elements[]', 'value' => '1'));
+ $form->addWidget($input);
+ $input = new SimpleTextTag(array('name' => 'elements[]', 'value' => '2'));
+ $form->addWidget($input);
+ $form->setField(new SimpleByLabelOrName('elements[]'), '3', 1);
+ $form->setField(new SimpleByLabelOrName('elements[]'), '4', 2);
+ $submit = $form->submit();
+ $requests = $submit->getAll();
+ $this->assertEqual(count($requests), 2);
+ $this->assertIdentical($requests[0], new SimpleEncodedPair('elements[]', '3'));
+ $this->assertIdentical($requests[1], new SimpleEncodedPair('elements[]', '4'));
+ }
+
+ function testSingleSelectFieldSubmitted() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $select = new SimpleSelectionTag(array('name' => 'a'));
+ $select->addTag(new SimpleOptionTag(
+ array('value' => 'aaa', 'selected' => '')));
+ $form->addWidget($select);
+ $this->assertIdentical(
+ $form->submit(),
+ new SimpleGetEncoding(array('a' => 'aaa')));
+ }
+
+ function testSingleSelectFieldSubmittedWithPost() {
+ $form = new SimpleForm(new SimpleFormTag(array('method' => 'post')), $this->page('htp://host'));
+ $select = new SimpleSelectionTag(array('name' => 'a'));
+ $select->addTag(new SimpleOptionTag(
+ array('value' => 'aaa', 'selected' => '')));
+ $form->addWidget($select);
+ $this->assertIdentical(
+ $form->submit(),
+ new SimplePostEncoding(array('a' => 'aaa')));
+ }
+
+ function testUnchecked() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $form->addWidget(new SimpleCheckboxTag(
+ array('name' => 'me', 'type' => 'checkbox')));
+ $this->assertIdentical($form->getValue(new SimpleByName('me')), false);
+ $this->assertTrue($form->setField(new SimpleByName('me'), 'on'));
+ $this->assertEqual($form->getValue(new SimpleByName('me')), 'on');
+ $this->assertFalse($form->setField(new SimpleByName('me'), 'other'));
+ $this->assertEqual($form->getValue(new SimpleByName('me')), 'on');
+ }
+
+ function testChecked() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $form->addWidget(new SimpleCheckboxTag(
+ array('name' => 'me', 'value' => 'a', 'type' => 'checkbox', 'checked' => '')));
+ $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a');
+ $this->assertTrue($form->setField(new SimpleByName('me'), 'a'));
+ $this->assertEqual($form->getValue(new SimpleByName('me')), 'a');
+ $this->assertTrue($form->setField(new SimpleByName('me'), false));
+ $this->assertEqual($form->getValue(new SimpleByName('me')), false);
+ }
+
+ function testSingleUncheckedRadioButton() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $form->addWidget(new SimpleRadioButtonTag(
+ array('name' => 'me', 'value' => 'a', 'type' => 'radio')));
+ $this->assertIdentical($form->getValue(new SimpleByName('me')), false);
+ $this->assertTrue($form->setField(new SimpleByName('me'), 'a'));
+ $this->assertEqual($form->getValue(new SimpleByName('me')), 'a');
+ }
+
+ function testSingleCheckedRadioButton() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $form->addWidget(new SimpleRadioButtonTag(
+ array('name' => 'me', 'value' => 'a', 'type' => 'radio', 'checked' => '')));
+ $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a');
+ $this->assertFalse($form->setField(new SimpleByName('me'), 'other'));
+ }
+
+ function testUncheckedRadioButtons() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $form->addWidget(new SimpleRadioButtonTag(
+ array('name' => 'me', 'value' => 'a', 'type' => 'radio')));
+ $form->addWidget(new SimpleRadioButtonTag(
+ array('name' => 'me', 'value' => 'b', 'type' => 'radio')));
+ $this->assertIdentical($form->getValue(new SimpleByName('me')), false);
+ $this->assertTrue($form->setField(new SimpleByName('me'), 'a'));
+ $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a');
+ $this->assertTrue($form->setField(new SimpleByName('me'), 'b'));
+ $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b');
+ $this->assertFalse($form->setField(new SimpleByName('me'), 'c'));
+ $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b');
+ }
+
+ function testCheckedRadioButtons() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $form->addWidget(new SimpleRadioButtonTag(
+ array('name' => 'me', 'value' => 'a', 'type' => 'radio')));
+ $form->addWidget(new SimpleRadioButtonTag(
+ array('name' => 'me', 'value' => 'b', 'type' => 'radio', 'checked' => '')));
+ $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b');
+ $this->assertTrue($form->setField(new SimpleByName('me'), 'a'));
+ $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a');
+ }
+
+ function testMultipleFieldsWithSameKey() {
+ $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host'));
+ $form->addWidget(new SimpleCheckboxTag(
+ array('name' => 'a', 'type' => 'checkbox', 'value' => 'me')));
+ $form->addWidget(new SimpleCheckboxTag(
+ array('name' => 'a', 'type' => 'checkbox', 'value' => 'you')));
+ $this->assertIdentical($form->getValue(new SimpleByName('a')), false);
+ $this->assertTrue($form->setField(new SimpleByName('a'), 'me'));
+ $this->assertIdentical($form->getValue(new SimpleByName('a')), 'me');
+ }
+
+ function testRemoveGetParamsFromAction() {
+ Mock::generatePartial('SimplePage', 'MockPartialSimplePage', array('getUrl'));
+ $page = new MockPartialSimplePage();
+ $page->returns('getUrl', new SimpleUrl('htp://host/'));
+
+ # Keep GET params in "action", if the form has no widgets
+ $form = new SimpleForm(new SimpleFormTag(array('action'=>'?test=1')), $page);
+ $this->assertEqual($form->getAction()->asString(), 'htp://host/');
+
+ $form = new SimpleForm(new SimpleFormTag(array('action'=>'?test=1')), $page);
+ $form->addWidget(new SimpleTextTag(array('name' => 'me', 'type' => 'text', 'value' => 'a')));
+ $this->assertEqual($form->getAction()->asString(), 'htp://host/');
+
+ $form = new SimpleForm(new SimpleFormTag(array('action'=>'')), $page);
+ $this->assertEqual($form->getAction()->asString(), 'htp://host/');
+
+ $form = new SimpleForm(new SimpleFormTag(array('action'=>'?test=1', 'method'=>'post')), $page);
+ $this->assertEqual($form->getAction()->asString(), 'htp://host/?test=1');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/frames_test.php b/3rdparty/simpletest/test/frames_test.php
new file mode 100755
index 00000000000..29309700e31
--- /dev/null
+++ b/3rdparty/simpletest/test/frames_test.php
@@ -0,0 +1,549 @@
+<?php
+// $Id: frames_test.php 1899 2009-07-28 19:33:42Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../tag.php');
+require_once(dirname(__FILE__) . '/../page.php');
+require_once(dirname(__FILE__) . '/../frames.php');
+Mock::generate('SimplePage');
+Mock::generate('SimpleForm');
+
+class TestOfFrameset extends UnitTestCase {
+
+ function testTitleReadFromFramesetPage() {
+ $page = new MockSimplePage();
+ $page->setReturnValue('getTitle', 'This page');
+ $frameset = new SimpleFrameset($page);
+ $this->assertEqual($frameset->getTitle(), 'This page');
+ }
+
+ function TestHeadersReadFromFramesetByDefault() {
+ $page = new MockSimplePage();
+ $page->setReturnValue('getHeaders', 'Header: content');
+ $page->setReturnValue('getMimeType', 'text/xml');
+ $page->setReturnValue('getResponseCode', 401);
+ $page->setReturnValue('getTransportError', 'Could not parse headers');
+ $page->setReturnValue('getAuthentication', 'Basic');
+ $page->setReturnValue('getRealm', 'Safe place');
+
+ $frameset = new SimpleFrameset($page);
+
+ $this->assertIdentical($frameset->getHeaders(), 'Header: content');
+ $this->assertIdentical($frameset->getMimeType(), 'text/xml');
+ $this->assertIdentical($frameset->getResponseCode(), 401);
+ $this->assertIdentical($frameset->getTransportError(), 'Could not parse headers');
+ $this->assertIdentical($frameset->getAuthentication(), 'Basic');
+ $this->assertIdentical($frameset->getRealm(), 'Safe place');
+ }
+
+ function testEmptyFramesetHasNoContent() {
+ $page = new MockSimplePage();
+ $page->setReturnValue('getRaw', 'This content');
+ $frameset = new SimpleFrameset($page);
+ $this->assertEqual($frameset->getRaw(), '');
+ }
+
+ function testRawContentIsFromOnlyFrame() {
+ $page = new MockSimplePage();
+ $page->expectNever('getRaw');
+
+ $frame = new MockSimplePage();
+ $frame->setReturnValue('getRaw', 'Stuff');
+
+ $frameset = new SimpleFrameset($page);
+ $frameset->addFrame($frame);
+ $this->assertEqual($frameset->getRaw(), 'Stuff');
+ }
+
+ function testRawContentIsFromAllFrames() {
+ $page = new MockSimplePage();
+ $page->expectNever('getRaw');
+
+ $frame1 = new MockSimplePage();
+ $frame1->setReturnValue('getRaw', 'Stuff1');
+
+ $frame2 = new MockSimplePage();
+ $frame2->setReturnValue('getRaw', 'Stuff2');
+
+ $frameset = new SimpleFrameset($page);
+ $frameset->addFrame($frame1);
+ $frameset->addFrame($frame2);
+ $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2');
+ }
+
+ function testTextContentIsFromOnlyFrame() {
+ $page = new MockSimplePage();
+ $page->expectNever('getText');
+
+ $frame = new MockSimplePage();
+ $frame->setReturnValue('getText', 'Stuff');
+
+ $frameset = new SimpleFrameset($page);
+ $frameset->addFrame($frame);
+ $this->assertEqual($frameset->getText(), 'Stuff');
+ }
+
+ function testTextContentIsFromAllFrames() {
+ $page = new MockSimplePage();
+ $page->expectNever('getText');
+
+ $frame1 = new MockSimplePage();
+ $frame1->setReturnValue('getText', 'Stuff1');
+
+ $frame2 = new MockSimplePage();
+ $frame2->setReturnValue('getText', 'Stuff2');
+
+ $frameset = new SimpleFrameset($page);
+ $frameset->addFrame($frame1);
+ $frameset->addFrame($frame2);
+ $this->assertEqual($frameset->getText(), 'Stuff1 Stuff2');
+ }
+
+ function testFieldFoundIsFirstInFramelist() {
+ $frame1 = new MockSimplePage();
+ $frame1->setReturnValue('getField', null);
+ $frame1->expectOnce('getField', array(new SimpleByName('a')));
+
+ $frame2 = new MockSimplePage();
+ $frame2->setReturnValue('getField', 'A');
+ $frame2->expectOnce('getField', array(new SimpleByName('a')));
+
+ $frame3 = new MockSimplePage();
+ $frame3->expectNever('getField');
+
+ $page = new MockSimplePage();
+ $frameset = new SimpleFrameset($page);
+ $frameset->addFrame($frame1);
+ $frameset->addFrame($frame2);
+ $frameset->addFrame($frame3);
+ $this->assertIdentical($frameset->getField(new SimpleByName('a')), 'A');
+ }
+
+ function testFrameReplacementByIndex() {
+ $page = new MockSimplePage();
+ $page->expectNever('getRaw');
+
+ $frame1 = new MockSimplePage();
+ $frame1->setReturnValue('getRaw', 'Stuff1');
+
+ $frame2 = new MockSimplePage();
+ $frame2->setReturnValue('getRaw', 'Stuff2');
+
+ $frameset = new SimpleFrameset($page);
+ $frameset->addFrame($frame1);
+ $frameset->setFrame(array(1), $frame2);
+ $this->assertEqual($frameset->getRaw(), 'Stuff2');
+ }
+
+ function testFrameReplacementByName() {
+ $page = new MockSimplePage();
+ $page->expectNever('getRaw');
+
+ $frame1 = new MockSimplePage();
+ $frame1->setReturnValue('getRaw', 'Stuff1');
+
+ $frame2 = new MockSimplePage();
+ $frame2->setReturnValue('getRaw', 'Stuff2');
+
+ $frameset = new SimpleFrameset($page);
+ $frameset->addFrame($frame1, 'a');
+ $frameset->setFrame(array('a'), $frame2);
+ $this->assertEqual($frameset->getRaw(), 'Stuff2');
+ }
+}
+
+class TestOfFrameNavigation extends UnitTestCase {
+
+ function testStartsWithoutFrameFocus() {
+ $page = new MockSimplePage();
+ $frameset = new SimpleFrameset($page);
+ $frameset->addFrame(new MockSimplePage());
+ $this->assertFalse($frameset->getFrameFocus());
+ }
+
+ function testCanFocusOnSingleFrame() {
+ $page = new MockSimplePage();
+ $page->expectNever('getRaw');
+
+ $frame = new MockSimplePage();
+ $frame->setReturnValue('getFrameFocus', array());
+ $frame->setReturnValue('getRaw', 'Stuff');
+
+ $frameset = new SimpleFrameset($page);
+ $frameset->addFrame($frame);
+
+ $this->assertFalse($frameset->setFrameFocusByIndex(0));
+ $this->assertTrue($frameset->setFrameFocusByIndex(1));
+ $this->assertEqual($frameset->getRaw(), 'Stuff');
+ $this->assertFalse($frameset->setFrameFocusByIndex(2));
+ $this->assertIdentical($frameset->getFrameFocus(), array(1));
+ }
+
+ function testContentComesFromFrameInFocus() {
+ $page = new MockSimplePage();
+
+ $frame1 = new MockSimplePage();
+ $frame1->setReturnValue('getRaw', 'Stuff1');
+ $frame1->setReturnValue('getFrameFocus', array());
+
+ $frame2 = new MockSimplePage();
+ $frame2->setReturnValue('getRaw', 'Stuff2');
+ $frame2->setReturnValue('getFrameFocus', array());
+
+ $frameset = new SimpleFrameset($page);
+ $frameset->addFrame($frame1);
+ $frameset->addFrame($frame2);
+
+ $this->assertTrue($frameset->setFrameFocusByIndex(1));
+ $this->assertEqual($frameset->getFrameFocus(), array(1));
+ $this->assertEqual($frameset->getRaw(), 'Stuff1');
+
+ $this->assertTrue($frameset->setFrameFocusByIndex(2));
+ $this->assertEqual($frameset->getFrameFocus(), array(2));
+ $this->assertEqual($frameset->getRaw(), 'Stuff2');
+
+ $this->assertFalse($frameset->setFrameFocusByIndex(3));
+ $this->assertEqual($frameset->getFrameFocus(), array(2));
+
+ $frameset->clearFrameFocus();
+ $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2');
+ }
+
+ function testCanFocusByName() {
+ $page = new MockSimplePage();
+
+ $frame1 = new MockSimplePage();
+ $frame1->setReturnValue('getRaw', 'Stuff1');
+ $frame1->setReturnValue('getFrameFocus', array());
+
+ $frame2 = new MockSimplePage();
+ $frame2->setReturnValue('getRaw', 'Stuff2');
+ $frame2->setReturnValue('getFrameFocus', array());
+
+ $frameset = new SimpleFrameset($page);
+ $frameset->addFrame($frame1, 'A');
+ $frameset->addFrame($frame2, 'B');
+
+ $this->assertTrue($frameset->setFrameFocus('A'));
+ $this->assertEqual($frameset->getFrameFocus(), array('A'));
+ $this->assertEqual($frameset->getRaw(), 'Stuff1');
+
+ $this->assertTrue($frameset->setFrameFocusByIndex(2));
+ $this->assertEqual($frameset->getFrameFocus(), array('B'));
+ $this->assertEqual($frameset->getRaw(), 'Stuff2');
+
+ $this->assertFalse($frameset->setFrameFocus('z'));
+
+ $frameset->clearFrameFocus();
+ $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2');
+ }
+}
+
+class TestOfFramesetPageInterface extends UnitTestCase {
+ private $page_interface;
+ private $frameset_interface;
+
+ function __construct() {
+ parent::__construct();
+ $this->page_interface = $this->getPageMethods();
+ $this->frameset_interface = $this->getFramesetMethods();
+ }
+
+ function assertListInAnyOrder($list, $expected) {
+ sort($list);
+ sort($expected);
+ $this->assertEqual($list, $expected);
+ }
+
+ private function getPageMethods() {
+ $methods = array();
+ foreach (get_class_methods('SimplePage') as $method) {
+ if (strtolower($method) == strtolower('SimplePage')) {
+ continue;
+ }
+ if (strtolower($method) == strtolower('getFrameset')) {
+ continue;
+ }
+ if (strncmp($method, '_', 1) == 0) {
+ continue;
+ }
+ if (in_array($method, array('setTitle', 'setBase', 'setForms', 'normalise', 'setFrames', 'addLink'))) {
+ continue;
+ }
+ $methods[] = $method;
+ }
+ return $methods;
+ }
+
+ private function getFramesetMethods() {
+ $methods = array();
+ foreach (get_class_methods('SimpleFrameset') as $method) {
+ if (strtolower($method) == strtolower('SimpleFrameset')) {
+ continue;
+ }
+ if (strncmp($method, '_', 1) == 0) {
+ continue;
+ }
+ if (strncmp($method, 'add', 3) == 0) {
+ continue;
+ }
+ $methods[] = $method;
+ }
+ return $methods;
+ }
+
+ function testFramsetHasPageInterface() {
+ $difference = array();
+ foreach ($this->page_interface as $method) {
+ if (! in_array($method, $this->frameset_interface)) {
+ $this->fail("No [$method] in Frameset class");
+ return;
+ }
+ }
+ $this->pass('Frameset covers Page interface');
+ }
+
+ function testHeadersReadFromFrameIfInFocus() {
+ $frame = new MockSimplePage();
+ $frame->setReturnValue('getUrl', new SimpleUrl('http://localhost/stuff'));
+
+ $frame->setReturnValue('getRequest', 'POST stuff');
+ $frame->setReturnValue('getMethod', 'POST');
+ $frame->setReturnValue('getRequestData', array('a' => 'A'));
+ $frame->setReturnValue('getHeaders', 'Header: content');
+ $frame->setReturnValue('getMimeType', 'text/xml');
+ $frame->setReturnValue('getResponseCode', 401);
+ $frame->setReturnValue('getTransportError', 'Could not parse headers');
+ $frame->setReturnValue('getAuthentication', 'Basic');
+ $frame->setReturnValue('getRealm', 'Safe place');
+
+ $frameset = new SimpleFrameset(new MockSimplePage());
+ $frameset->addFrame($frame);
+ $frameset->setFrameFocusByIndex(1);
+
+ $url = new SimpleUrl('http://localhost/stuff');
+ $url->setTarget(1);
+ $this->assertIdentical($frameset->getUrl(), $url);
+
+ $this->assertIdentical($frameset->getRequest(), 'POST stuff');
+ $this->assertIdentical($frameset->getMethod(), 'POST');
+ $this->assertIdentical($frameset->getRequestData(), array('a' => 'A'));
+ $this->assertIdentical($frameset->getHeaders(), 'Header: content');
+ $this->assertIdentical($frameset->getMimeType(), 'text/xml');
+ $this->assertIdentical($frameset->getResponseCode(), 401);
+ $this->assertIdentical($frameset->getTransportError(), 'Could not parse headers');
+ $this->assertIdentical($frameset->getAuthentication(), 'Basic');
+ $this->assertIdentical($frameset->getRealm(), 'Safe place');
+ }
+
+ function testUrlsComeFromBothFrames() {
+ $page = new MockSimplePage();
+ $page->expectNever('getUrls');
+
+ $frame1 = new MockSimplePage();
+ $frame1->setReturnValue(
+ 'getUrls',
+ array('http://www.lastcraft.com/', 'http://myserver/'));
+
+ $frame2 = new MockSimplePage();
+ $frame2->setReturnValue(
+ 'getUrls',
+ array('http://www.lastcraft.com/', 'http://test/'));
+
+ $frameset = new SimpleFrameset($page);
+ $frameset->addFrame($frame1);
+ $frameset->addFrame($frame2);
+ $this->assertListInAnyOrder(
+ $frameset->getUrls(),
+ array('http://www.lastcraft.com/', 'http://myserver/', 'http://test/'));
+ }
+
+ function testLabelledUrlsComeFromBothFrames() {
+ $frame1 = new MockSimplePage();
+ $frame1->setReturnValue(
+ 'getUrlsByLabel',
+ array(new SimpleUrl('goodbye.php')),
+ array('a'));
+
+ $frame2 = new MockSimplePage();
+ $frame2->setReturnValue(
+ 'getUrlsByLabel',
+ array(new SimpleUrl('hello.php')),
+ array('a'));
+
+ $frameset = new SimpleFrameset(new MockSimplePage());
+ $frameset->addFrame($frame1);
+ $frameset->addFrame($frame2, 'Two');
+
+ $expected1 = new SimpleUrl('goodbye.php');
+ $expected1->setTarget(1);
+ $expected2 = new SimpleUrl('hello.php');
+ $expected2->setTarget('Two');
+ $this->assertEqual(
+ $frameset->getUrlsByLabel('a'),
+ array($expected1, $expected2));
+ }
+
+ function testUrlByIdComesFromFirstFrameToRespond() {
+ $frame1 = new MockSimplePage();
+ $frame1->setReturnValue('getUrlById', new SimpleUrl('four.php'), array(4));
+ $frame1->setReturnValue('getUrlById', false, array(5));
+
+ $frame2 = new MockSimplePage();
+ $frame2->setReturnValue('getUrlById', false, array(4));
+ $frame2->setReturnValue('getUrlById', new SimpleUrl('five.php'), array(5));
+
+ $frameset = new SimpleFrameset(new MockSimplePage());
+ $frameset->addFrame($frame1);
+ $frameset->addFrame($frame2);
+
+ $four = new SimpleUrl('four.php');
+ $four->setTarget(1);
+ $this->assertEqual($frameset->getUrlById(4), $four);
+ $five = new SimpleUrl('five.php');
+ $five->setTarget(2);
+ $this->assertEqual($frameset->getUrlById(5), $five);
+ }
+
+ function testReadUrlsFromFrameInFocus() {
+ $frame1 = new MockSimplePage();
+ $frame1->setReturnValue('getUrls', array('a'));
+ $frame1->setReturnValue('getUrlsByLabel', array(new SimpleUrl('l')));
+ $frame1->setReturnValue('getUrlById', new SimpleUrl('i'));
+
+ $frame2 = new MockSimplePage();
+ $frame2->expectNever('getUrls');
+ $frame2->expectNever('getUrlsByLabel');
+ $frame2->expectNever('getUrlById');
+
+ $frameset = new SimpleFrameset(new MockSimplePage());
+ $frameset->addFrame($frame1, 'A');
+ $frameset->addFrame($frame2, 'B');
+ $frameset->setFrameFocus('A');
+
+ $this->assertIdentical($frameset->getUrls(), array('a'));
+ $expected = new SimpleUrl('l');
+ $expected->setTarget('A');
+ $this->assertIdentical($frameset->getUrlsByLabel('label'), array($expected));
+ $expected = new SimpleUrl('i');
+ $expected->setTarget('A');
+ $this->assertIdentical($frameset->getUrlById(99), $expected);
+ }
+
+ function testReadFrameTaggedUrlsFromFrameInFocus() {
+ $frame = new MockSimplePage();
+
+ $by_label = new SimpleUrl('l');
+ $by_label->setTarget('L');
+ $frame->setReturnValue('getUrlsByLabel', array($by_label));
+
+ $by_id = new SimpleUrl('i');
+ $by_id->setTarget('I');
+ $frame->setReturnValue('getUrlById', $by_id);
+
+ $frameset = new SimpleFrameset(new MockSimplePage());
+ $frameset->addFrame($frame, 'A');
+ $frameset->setFrameFocus('A');
+
+ $this->assertIdentical($frameset->getUrlsByLabel('label'), array($by_label));
+ $this->assertIdentical($frameset->getUrlById(99), $by_id);
+ }
+
+ function testFindingFormsById() {
+ $frame = new MockSimplePage();
+ $form = new MockSimpleForm();
+ $frame->returns('getFormById', $form, array('a'));
+
+ $frameset = new SimpleFrameset(new MockSimplePage());
+ $frameset->addFrame(new MockSimplePage(), 'A');
+ $frameset->addFrame($frame, 'B');
+ $this->assertSame($frameset->getFormById('a'), $form);
+
+ $frameset->setFrameFocus('A');
+ $this->assertNull($frameset->getFormById('a'));
+
+ $frameset->setFrameFocus('B');
+ $this->assertSame($frameset->getFormById('a'), $form);
+ }
+
+ function testFindingFormsBySubmit() {
+ $frame = new MockSimplePage();
+ $form = new MockSimpleForm();
+ $frame->returns(
+ 'getFormBySubmit',
+ $form,
+ array(new SimpleByLabel('a')));
+
+ $frameset = new SimpleFrameset(new MockSimplePage());
+ $frameset->addFrame(new MockSimplePage(), 'A');
+ $frameset->addFrame($frame, 'B');
+ $this->assertSame($frameset->getFormBySubmit(new SimpleByLabel('a')), $form);
+
+ $frameset->setFrameFocus('A');
+ $this->assertNull($frameset->getFormBySubmit(new SimpleByLabel('a')));
+
+ $frameset->setFrameFocus('B');
+ $this->assertSame($frameset->getFormBySubmit(new SimpleByLabel('a')), $form);
+ }
+
+ function testFindingFormsByImage() {
+ $frame = new MockSimplePage();
+ $form = new MockSimpleForm();
+ $frame->returns(
+ 'getFormByImage',
+ $form,
+ array(new SimpleByLabel('a')));
+
+ $frameset = new SimpleFrameset(new MockSimplePage());
+ $frameset->addFrame(new MockSimplePage(), 'A');
+ $frameset->addFrame($frame, 'B');
+ $this->assertSame($frameset->getFormByImage(new SimpleByLabel('a')), $form);
+
+ $frameset->setFrameFocus('A');
+ $this->assertNull($frameset->getFormByImage(new SimpleByLabel('a')));
+
+ $frameset->setFrameFocus('B');
+ $this->assertSame($frameset->getFormByImage(new SimpleByLabel('a')), $form);
+ }
+
+ function testSettingAllFrameFieldsWhenNoFrameFocus() {
+ $frame1 = new MockSimplePage();
+ $frame1->expectOnce('setField', array(new SimpleById(22), 'A'));
+
+ $frame2 = new MockSimplePage();
+ $frame2->expectOnce('setField', array(new SimpleById(22), 'A'));
+
+ $frameset = new SimpleFrameset(new MockSimplePage());
+ $frameset->addFrame($frame1, 'A');
+ $frameset->addFrame($frame2, 'B');
+ $frameset->setField(new SimpleById(22), 'A');
+ }
+
+ function testOnlySettingFieldFromFocusedFrame() {
+ $frame1 = new MockSimplePage();
+ $frame1->expectOnce('setField', array(new SimpleByLabelOrName('a'), 'A'));
+
+ $frame2 = new MockSimplePage();
+ $frame2->expectNever('setField');
+
+ $frameset = new SimpleFrameset(new MockSimplePage());
+ $frameset->addFrame($frame1, 'A');
+ $frameset->addFrame($frame2, 'B');
+ $frameset->setFrameFocus('A');
+ $frameset->setField(new SimpleByLabelOrName('a'), 'A');
+ }
+
+ function testOnlyGettingFieldFromFocusedFrame() {
+ $frame1 = new MockSimplePage();
+ $frame1->setReturnValue('getField', 'f', array(new SimpleByName('a')));
+
+ $frame2 = new MockSimplePage();
+ $frame2->expectNever('getField');
+
+ $frameset = new SimpleFrameset(new MockSimplePage());
+ $frameset->addFrame($frame1, 'A');
+ $frameset->addFrame($frame2, 'B');
+ $frameset->setFrameFocus('A');
+ $this->assertIdentical($frameset->getField(new SimpleByName('a')), 'f');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/http_test.php b/3rdparty/simpletest/test/http_test.php
new file mode 100755
index 00000000000..bd3fdd0d028
--- /dev/null
+++ b/3rdparty/simpletest/test/http_test.php
@@ -0,0 +1,492 @@
+<?php
+// $Id: http_test.php 1964 2009-10-13 15:27:31Z maetl_ $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../encoding.php');
+require_once(dirname(__FILE__) . '/../http.php');
+require_once(dirname(__FILE__) . '/../socket.php');
+require_once(dirname(__FILE__) . '/../cookies.php');
+Mock::generate('SimpleSocket');
+Mock::generate('SimpleCookieJar');
+Mock::generate('SimpleRoute');
+Mock::generatePartial(
+ 'SimpleRoute',
+ 'PartialSimpleRoute',
+array('createSocket'));
+Mock::generatePartial(
+ 'SimpleProxyRoute',
+ 'PartialSimpleProxyRoute',
+array('createSocket'));
+
+class TestOfDirectRoute extends UnitTestCase {
+
+ function testDefaultGetRequest() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("GET /here.html HTTP/1.0\r\n"));
+ $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n"));
+ $socket->expectAt(2, 'write', array("Connection: close\r\n"));
+ $socket->expectCallCount('write', 3);
+ $route = new PartialSimpleRoute();
+ $route->setReturnReference('createSocket', $socket);
+ $route->__construct(new SimpleUrl('http://a.valid.host/here.html'));
+ $this->assertSame($route->createConnection('GET', 15), $socket);
+ }
+
+ function testDefaultPostRequest() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("POST /here.html HTTP/1.0\r\n"));
+ $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n"));
+ $socket->expectAt(2, 'write', array("Connection: close\r\n"));
+ $socket->expectCallCount('write', 3);
+ $route = new PartialSimpleRoute();
+ $route->setReturnReference('createSocket', $socket);
+ $route->__construct(new SimpleUrl('http://a.valid.host/here.html'));
+
+ $route->createConnection('POST', 15);
+ }
+
+ function testDefaultDeleteRequest() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("DELETE /here.html HTTP/1.0\r\n"));
+ $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n"));
+ $socket->expectAt(2, 'write', array("Connection: close\r\n"));
+ $socket->expectCallCount('write', 3);
+ $route = new PartialSimpleRoute();
+ $route->setReturnReference('createSocket', $socket);
+ $route->__construct(new SimpleUrl('http://a.valid.host/here.html'));
+ $this->assertSame($route->createConnection('DELETE', 15), $socket);
+ }
+
+ function testDefaultHeadRequest() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("HEAD /here.html HTTP/1.0\r\n"));
+ $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n"));
+ $socket->expectAt(2, 'write', array("Connection: close\r\n"));
+ $socket->expectCallCount('write', 3);
+ $route = new PartialSimpleRoute();
+ $route->setReturnReference('createSocket', $socket);
+ $route->__construct(new SimpleUrl('http://a.valid.host/here.html'));
+ $this->assertSame($route->createConnection('HEAD', 15), $socket);
+ }
+
+ function testGetWithPort() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("GET /here.html HTTP/1.0\r\n"));
+ $socket->expectAt(1, 'write', array("Host: a.valid.host:81\r\n"));
+ $socket->expectAt(2, 'write', array("Connection: close\r\n"));
+ $socket->expectCallCount('write', 3);
+
+ $route = new PartialSimpleRoute();
+ $route->setReturnReference('createSocket', $socket);
+ $route->__construct(new SimpleUrl('http://a.valid.host:81/here.html'));
+
+ $route->createConnection('GET', 15);
+ }
+
+ function testGetWithParameters() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("GET /here.html?a=1&b=2 HTTP/1.0\r\n"));
+ $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n"));
+ $socket->expectAt(2, 'write', array("Connection: close\r\n"));
+ $socket->expectCallCount('write', 3);
+
+ $route = new PartialSimpleRoute();
+ $route->setReturnReference('createSocket', $socket);
+ $route->__construct(new SimpleUrl('http://a.valid.host/here.html?a=1&b=2'));
+
+ $route->createConnection('GET', 15);
+ }
+}
+
+class TestOfProxyRoute extends UnitTestCase {
+
+ function testDefaultGet() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("GET http://a.valid.host/here.html HTTP/1.0\r\n"));
+ $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n"));
+ $socket->expectAt(2, 'write', array("Connection: close\r\n"));
+ $socket->expectCallCount('write', 3);
+
+ $route = new PartialSimpleProxyRoute();
+ $route->setReturnReference('createSocket', $socket);
+ $route->__construct(
+ new SimpleUrl('http://a.valid.host/here.html'),
+ new SimpleUrl('http://my-proxy'));
+ $route->createConnection('GET', 15);
+ }
+
+ function testDefaultPost() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("POST http://a.valid.host/here.html HTTP/1.0\r\n"));
+ $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n"));
+ $socket->expectAt(2, 'write', array("Connection: close\r\n"));
+ $socket->expectCallCount('write', 3);
+
+ $route = new PartialSimpleProxyRoute();
+ $route->setReturnReference('createSocket', $socket);
+ $route->__construct(
+ new SimpleUrl('http://a.valid.host/here.html'),
+ new SimpleUrl('http://my-proxy'));
+ $route->createConnection('POST', 15);
+ }
+
+ function testGetWithPort() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("GET http://a.valid.host:81/here.html HTTP/1.0\r\n"));
+ $socket->expectAt(1, 'write', array("Host: my-proxy:8081\r\n"));
+ $socket->expectAt(2, 'write', array("Connection: close\r\n"));
+ $socket->expectCallCount('write', 3);
+
+ $route = new PartialSimpleProxyRoute();
+ $route->setReturnReference('createSocket', $socket);
+ $route->__construct(
+ new SimpleUrl('http://a.valid.host:81/here.html'),
+ new SimpleUrl('http://my-proxy:8081'));
+ $route->createConnection('GET', 15);
+ }
+
+ function testGetWithParameters() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("GET http://a.valid.host/here.html?a=1&b=2 HTTP/1.0\r\n"));
+ $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n"));
+ $socket->expectAt(2, 'write', array("Connection: close\r\n"));
+ $socket->expectCallCount('write', 3);
+
+ $route = new PartialSimpleProxyRoute();
+ $route->setReturnReference('createSocket', $socket);
+ $route->__construct(
+ new SimpleUrl('http://a.valid.host/here.html?a=1&b=2'),
+ new SimpleUrl('http://my-proxy'));
+ $route->createConnection('GET', 15);
+ }
+
+ function testGetWithAuthentication() {
+ $encoded = base64_encode('Me:Secret');
+
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("GET http://a.valid.host/here.html HTTP/1.0\r\n"));
+ $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n"));
+ $socket->expectAt(2, 'write', array("Proxy-Authorization: Basic $encoded\r\n"));
+ $socket->expectAt(3, 'write', array("Connection: close\r\n"));
+ $socket->expectCallCount('write', 4);
+
+ $route = new PartialSimpleProxyRoute();
+ $route->setReturnReference('createSocket', $socket);
+ $route->__construct(
+ new SimpleUrl('http://a.valid.host/here.html'),
+ new SimpleUrl('http://my-proxy'),
+ 'Me',
+ 'Secret');
+ $route->createConnection('GET', 15);
+ }
+}
+
+class TestOfHttpRequest extends UnitTestCase {
+
+ function testReadingBadConnection() {
+ $socket = new MockSimpleSocket();
+ $route = new MockSimpleRoute();
+ $route->setReturnReference('createConnection', $socket);
+ $request = new SimpleHttpRequest($route, new SimpleGetEncoding());
+ $reponse = $request->fetch(15);
+ $this->assertTrue($reponse->isError());
+ }
+
+ function testReadingGoodConnection() {
+ $socket = new MockSimpleSocket();
+ $socket->expectOnce('write', array("\r\n"));
+
+ $route = new MockSimpleRoute();
+ $route->setReturnReference('createConnection', $socket);
+ $route->expect('createConnection', array('GET', 15));
+
+ $request = new SimpleHttpRequest($route, new SimpleGetEncoding());
+ $this->assertIsA($request->fetch(15), 'SimpleHttpResponse');
+ }
+
+ function testWritingAdditionalHeaders() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("My: stuff\r\n"));
+ $socket->expectAt(1, 'write', array("\r\n"));
+ $socket->expectCallCount('write', 2);
+
+ $route = new MockSimpleRoute();
+ $route->setReturnReference('createConnection', $socket);
+
+ $request = new SimpleHttpRequest($route, new SimpleGetEncoding());
+ $request->addHeaderLine('My: stuff');
+ $request->fetch(15);
+ }
+
+ function testCookieWriting() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("Cookie: a=A\r\n"));
+ $socket->expectAt(1, 'write', array("\r\n"));
+ $socket->expectCallCount('write', 2);
+
+ $route = new MockSimpleRoute();
+ $route->setReturnReference('createConnection', $socket);
+
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'A');
+
+ $request = new SimpleHttpRequest($route, new SimpleGetEncoding());
+ $request->readCookiesFromJar($jar, new SimpleUrl('/'));
+ $this->assertIsA($request->fetch(15), 'SimpleHttpResponse');
+ }
+
+ function testMultipleCookieWriting() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("Cookie: a=A;b=B\r\n"));
+
+ $route = new MockSimpleRoute();
+ $route->setReturnReference('createConnection', $socket);
+
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'A');
+ $jar->setCookie('b', 'B');
+
+ $request = new SimpleHttpRequest($route, new SimpleGetEncoding());
+ $request->readCookiesFromJar($jar, new SimpleUrl('/'));
+ $request->fetch(15);
+ }
+
+ function testReadingDeleteConnection() {
+ $socket = new MockSimpleSocket();
+
+ $route = new MockSimpleRoute();
+ $route->setReturnReference('createConnection', $socket);
+ $route->expect('createConnection', array('DELETE', 15));
+
+ $request = new SimpleHttpRequest($route, new SimpleDeleteEncoding());
+ $this->assertIsA($request->fetch(15), 'SimpleHttpResponse');
+ }
+}
+
+class TestOfHttpPostRequest extends UnitTestCase {
+
+ function testReadingBadConnectionCausesErrorBecauseOfDeadSocket() {
+ $socket = new MockSimpleSocket();
+ $route = new MockSimpleRoute();
+ $route->setReturnReference('createConnection', $socket);
+ $request = new SimpleHttpRequest($route, new SimplePostEncoding());
+ $reponse = $request->fetch(15);
+ $this->assertTrue($reponse->isError());
+ }
+
+ function testReadingGoodConnection() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("Content-Length: 0\r\n"));
+ $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n"));
+ $socket->expectAt(2, 'write', array("\r\n"));
+ $socket->expectAt(3, 'write', array(""));
+
+ $route = new MockSimpleRoute();
+ $route->setReturnReference('createConnection', $socket);
+ $route->expect('createConnection', array('POST', 15));
+
+ $request = new SimpleHttpRequest($route, new SimplePostEncoding());
+ $this->assertIsA($request->fetch(15), 'SimpleHttpResponse');
+ }
+
+ function testContentHeadersCalculatedWithUrlEncodedParams() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("Content-Length: 3\r\n"));
+ $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n"));
+ $socket->expectAt(2, 'write', array("\r\n"));
+ $socket->expectAt(3, 'write', array("a=A"));
+
+ $route = new MockSimpleRoute();
+ $route->setReturnReference('createConnection', $socket);
+ $route->expect('createConnection', array('POST', 15));
+
+ $request = new SimpleHttpRequest(
+ $route,
+ new SimplePostEncoding(array('a' => 'A')));
+ $this->assertIsA($request->fetch(15), 'SimpleHttpResponse');
+ }
+
+ function testContentHeadersCalculatedWithRawEntityBody() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("Content-Length: 8\r\n"));
+ $socket->expectAt(1, 'write', array("Content-Type: text/plain\r\n"));
+ $socket->expectAt(2, 'write', array("\r\n"));
+ $socket->expectAt(3, 'write', array("raw body"));
+
+ $route = new MockSimpleRoute();
+ $route->setReturnReference('createConnection', $socket);
+ $route->expect('createConnection', array('POST', 15));
+
+ $request = new SimpleHttpRequest(
+ $route,
+ new SimplePostEncoding('raw body'));
+ $this->assertIsA($request->fetch(15), 'SimpleHttpResponse');
+ }
+
+ function testContentHeadersCalculatedWithXmlEntityBody() {
+ $socket = new MockSimpleSocket();
+ $socket->expectAt(0, 'write', array("Content-Length: 27\r\n"));
+ $socket->expectAt(1, 'write', array("Content-Type: text/xml\r\n"));
+ $socket->expectAt(2, 'write', array("\r\n"));
+ $socket->expectAt(3, 'write', array("<a><b>one</b><c>two</c></a>"));
+
+ $route = new MockSimpleRoute();
+ $route->setReturnReference('createConnection', $socket);
+ $route->expect('createConnection', array('POST', 15));
+
+ $request = new SimpleHttpRequest(
+ $route,
+ new SimplePostEncoding('<a><b>one</b><c>two</c></a>', 'text/xml'));
+ $this->assertIsA($request->fetch(15), 'SimpleHttpResponse');
+ }
+}
+
+class TestOfHttpHeaders extends UnitTestCase {
+
+ function testParseBasicHeaders() {
+ $headers = new SimpleHttpHeaders(
+ "HTTP/1.1 200 OK\r\n" .
+ "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n" .
+ "Content-Type: text/plain\r\n" .
+ "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n" .
+ "Connection: close");
+ $this->assertIdentical($headers->getHttpVersion(), "1.1");
+ $this->assertIdentical($headers->getResponseCode(), 200);
+ $this->assertEqual($headers->getMimeType(), "text/plain");
+ }
+
+ function testNonStandardResponseHeader() {
+ $headers = new SimpleHttpHeaders(
+ "HTTP/1.1 302 (HTTP-Version SP Status-Code CRLF)\r\n" .
+ "Connection: close");
+ $this->assertIdentical($headers->getResponseCode(), 302);
+ }
+
+ function testCanParseMultipleCookies() {
+ $jar = new MockSimpleCookieJar();
+ $jar->expectAt(0, 'setCookie', array('a', 'aaa', 'host', '/here/', 'Wed, 25 Dec 2002 04:24:20 GMT'));
+ $jar->expectAt(1, 'setCookie', array('b', 'bbb', 'host', '/', false));
+
+ $headers = new SimpleHttpHeaders(
+ "HTTP/1.1 200 OK\r\n" .
+ "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n" .
+ "Content-Type: text/plain\r\n" .
+ "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n" .
+ "Set-Cookie: a=aaa; expires=Wed, 25-Dec-02 04:24:20 GMT; path=/here/\r\n" .
+ "Set-Cookie: b=bbb\r\n" .
+ "Connection: close");
+ $headers->writeCookiesToJar($jar, new SimpleUrl('http://host'));
+ }
+
+ function testCanRecogniseRedirect() {
+ $headers = new SimpleHttpHeaders("HTTP/1.1 301 OK\r\n" .
+ "Content-Type: text/plain\r\n" .
+ "Content-Length: 0\r\n" .
+ "Location: http://www.somewhere-else.com/\r\n" .
+ "Connection: close");
+ $this->assertIdentical($headers->getResponseCode(), 301);
+ $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/");
+ $this->assertTrue($headers->isRedirect());
+ }
+
+ function testCanParseChallenge() {
+ $headers = new SimpleHttpHeaders("HTTP/1.1 401 Authorization required\r\n" .
+ "Content-Type: text/plain\r\n" .
+ "Connection: close\r\n" .
+ "WWW-Authenticate: Basic realm=\"Somewhere\"");
+ $this->assertEqual($headers->getAuthentication(), 'Basic');
+ $this->assertEqual($headers->getRealm(), 'Somewhere');
+ $this->assertTrue($headers->isChallenge());
+ }
+}
+
+class TestOfHttpResponse extends UnitTestCase {
+
+ function testBadRequest() {
+ $socket = new MockSimpleSocket();
+ $socket->setReturnValue('getSent', '');
+
+ $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
+ $this->assertTrue($response->isError());
+ $this->assertPattern('/Nothing fetched/', $response->getError());
+ $this->assertIdentical($response->getContent(), false);
+ $this->assertIdentical($response->getSent(), '');
+ }
+
+ function testBadSocketDuringResponse() {
+ $socket = new MockSimpleSocket();
+ $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\n");
+ $socket->setReturnValueAt(1, "read", "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n");
+ $socket->setReturnValue("read", "");
+ $socket->setReturnValue('getSent', 'HTTP/1.1 ...');
+
+ $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
+ $this->assertTrue($response->isError());
+ $this->assertEqual($response->getContent(), '');
+ $this->assertEqual($response->getSent(), 'HTTP/1.1 ...');
+ }
+
+ function testIncompleteHeader() {
+ $socket = new MockSimpleSocket();
+ $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\n");
+ $socket->setReturnValueAt(1, "read", "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n");
+ $socket->setReturnValueAt(2, "read", "Content-Type: text/plain\r\n");
+ $socket->setReturnValue("read", "");
+
+ $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
+ $this->assertTrue($response->isError());
+ $this->assertEqual($response->getContent(), "");
+ }
+
+ function testParseOfResponseHeadersWhenChunked() {
+ $socket = new MockSimpleSocket();
+ $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\nDate: Mon, 18 Nov 2002 15:50:29 GMT\r\n");
+ $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n");
+ $socket->setReturnValueAt(2, "read", "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\nConne");
+ $socket->setReturnValueAt(3, "read", "ction: close\r\n\r\nthis is a test file\n");
+ $socket->setReturnValueAt(4, "read", "with two lines in it\n");
+ $socket->setReturnValue("read", "");
+
+ $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
+ $this->assertFalse($response->isError());
+ $this->assertEqual(
+ $response->getContent(),
+ "this is a test file\nwith two lines in it\n");
+ $headers = $response->getHeaders();
+ $this->assertIdentical($headers->getHttpVersion(), "1.1");
+ $this->assertIdentical($headers->getResponseCode(), 200);
+ $this->assertEqual($headers->getMimeType(), "text/plain");
+ $this->assertFalse($headers->isRedirect());
+ $this->assertFalse($headers->getLocation());
+ }
+
+ function testRedirect() {
+ $socket = new MockSimpleSocket();
+ $socket->setReturnValueAt(0, "read", "HTTP/1.1 301 OK\r\n");
+ $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n");
+ $socket->setReturnValueAt(2, "read", "Location: http://www.somewhere-else.com/\r\n");
+ $socket->setReturnValueAt(3, "read", "Connection: close\r\n");
+ $socket->setReturnValueAt(4, "read", "\r\n");
+ $socket->setReturnValue("read", "");
+
+ $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
+ $headers = $response->getHeaders();
+ $this->assertTrue($headers->isRedirect());
+ $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/");
+ }
+
+ function testRedirectWithPort() {
+ $socket = new MockSimpleSocket();
+ $socket->setReturnValueAt(0, "read", "HTTP/1.1 301 OK\r\n");
+ $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n");
+ $socket->setReturnValueAt(2, "read", "Location: http://www.somewhere-else.com:80/\r\n");
+ $socket->setReturnValueAt(3, "read", "Connection: close\r\n");
+ $socket->setReturnValueAt(4, "read", "\r\n");
+ $socket->setReturnValue("read", "");
+
+ $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding());
+ $headers = $response->getHeaders();
+ $this->assertTrue($headers->isRedirect());
+ $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com:80/");
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/interfaces_test.php b/3rdparty/simpletest/test/interfaces_test.php
new file mode 100755
index 00000000000..ab30fe47ff8
--- /dev/null
+++ b/3rdparty/simpletest/test/interfaces_test.php
@@ -0,0 +1,137 @@
+<?php
+// $Id: interfaces_test.php 1981 2010-03-23 23:29:56Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+if (function_exists('spl_classes')) {
+ include(dirname(__FILE__) . '/support/spl_examples.php');
+}
+if (version_compare(PHP_VERSION, '5.1', '>=')) {
+ include(dirname(__FILE__) . '/interfaces_test_php5_1.php');
+}
+
+interface DummyInterface {
+ function aMethod();
+ function anotherMethod($a);
+ function &referenceMethod(&$a);
+}
+
+Mock::generate('DummyInterface');
+Mock::generatePartial('DummyInterface', 'PartialDummyInterface', array());
+
+class TestOfMockInterfaces extends UnitTestCase {
+
+ function testCanMockAnInterface() {
+ $mock = new MockDummyInterface();
+ $this->assertIsA($mock, 'SimpleMock');
+ $this->assertIsA($mock, 'MockDummyInterface');
+ $this->assertTrue(method_exists($mock, 'aMethod'));
+ $this->assertTrue(method_exists($mock, 'anotherMethod'));
+ $this->assertNull($mock->aMethod());
+ }
+
+ function testMockedInterfaceExpectsParameters() {
+ $mock = new MockDummyInterface();
+ $this->expectError();
+ $mock->anotherMethod();
+ }
+
+ function testCannotPartiallyMockAnInterface() {
+ $this->assertFalse(class_exists('PartialDummyInterface'));
+ }
+}
+
+class TestOfSpl extends UnitTestCase {
+
+ function skip() {
+ $this->skipUnless(function_exists('spl_classes'), 'No SPL module loaded');
+ }
+
+ function testCanMockAllSplClasses() {
+ if (! function_exists('spl_classes')) {
+ return;
+ }
+ foreach(spl_classes() as $class) {
+ if ($class == 'SplHeap' or $class = 'SplFileObject') {
+ continue;
+ }
+ if (version_compare(PHP_VERSION, '5.1', '<') &&
+ $class == 'CachingIterator' ||
+ $class == 'CachingRecursiveIterator' ||
+ $class == 'FilterIterator' ||
+ $class == 'LimitIterator' ||
+ $class == 'ParentIterator') {
+ // These iterators require an iterator be passed to them during
+ // construction in PHP 5.0; there is no way for SimpleTest
+ // to supply such an iterator, however, so support for it is
+ // disabled.
+ continue;
+ }
+ $mock_class = "Mock$class";
+ Mock::generate($class);
+ $this->assertIsA(new $mock_class(), $mock_class);
+ }
+ }
+
+ function testExtensionOfCommonSplClasses() {
+ Mock::generate('IteratorImplementation');
+ $this->assertIsA(
+ new IteratorImplementation(),
+ 'IteratorImplementation');
+ Mock::generate('IteratorAggregateImplementation');
+ $this->assertIsA(
+ new IteratorAggregateImplementation(),
+ 'IteratorAggregateImplementation');
+ }
+}
+
+class WithHint {
+ function hinted(DummyInterface $object) { }
+}
+
+class ImplementsDummy implements DummyInterface {
+ function aMethod() { }
+ function anotherMethod($a) { }
+ function &referenceMethod(&$a) { }
+ function extraMethod($a = false) { }
+}
+Mock::generate('ImplementsDummy');
+
+class TestOfImplementations extends UnitTestCase {
+
+ function testMockedInterfaceCanPassThroughTypeHint() {
+ $mock = new MockDummyInterface();
+ $hinter = new WithHint();
+ $hinter->hinted($mock);
+ }
+
+ function testImplementedInterfacesAreCarried() {
+ $mock = new MockImplementsDummy();
+ $hinter = new WithHint();
+ $hinter->hinted($mock);
+ }
+
+ function testNoSpuriousWarningsWhenSkippingDefaultedParameter() {
+ $mock = new MockImplementsDummy();
+ $mock->extraMethod();
+ }
+}
+
+interface SampleInterfaceWithConstruct {
+ function __construct($something);
+}
+
+class TestOfInterfaceMocksWithConstruct extends UnitTestCase {
+ function TODO_testBasicConstructOfAnInterface() { // Fails in PHP 5.3dev
+ Mock::generate('SampleInterfaceWithConstruct');
+ }
+}
+
+interface SampleInterfaceWithClone {
+ function __clone();
+}
+
+class TestOfSampleInterfaceWithClone extends UnitTestCase {
+ function testCanMockWithoutErrors() {
+ Mock::generate('SampleInterfaceWithClone');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/interfaces_test_php5_1.php b/3rdparty/simpletest/test/interfaces_test_php5_1.php
new file mode 100755
index 00000000000..3d154f99539
--- /dev/null
+++ b/3rdparty/simpletest/test/interfaces_test_php5_1.php
@@ -0,0 +1,14 @@
+<?php
+
+interface SampleInterfaceWithHintInSignature {
+ function method(array $hinted);
+}
+
+class TestOfInterfaceMocksWithHintInSignature extends UnitTestCase {
+ function testBasicConstructOfAnInterfaceWithHintInSignature() {
+ Mock::generate('SampleInterfaceWithHintInSignature');
+ $mock = new MockSampleInterfaceWithHintInSignature();
+ $this->assertIsA($mock, 'SampleInterfaceWithHintInSignature');
+ }
+}
+
diff --git a/3rdparty/simpletest/test/live_test.php b/3rdparty/simpletest/test/live_test.php
new file mode 100755
index 00000000000..3fbb54499d3
--- /dev/null
+++ b/3rdparty/simpletest/test/live_test.php
@@ -0,0 +1,47 @@
+<?php
+// $Id: live_test.php 1748 2008-04-14 01:50:41Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../socket.php');
+require_once(dirname(__FILE__) . '/../http.php');
+require_once(dirname(__FILE__) . '/../compatibility.php');
+
+if (SimpleTest::getDefaultProxy()) {
+ SimpleTest::ignore('LiveHttpTestCase');
+}
+
+class LiveHttpTestCase extends UnitTestCase {
+
+ function testBadSocket() {
+ $socket = new SimpleSocket('bad_url', 111, 5);
+ $this->assertTrue($socket->isError());
+ $this->assertPattern(
+ '/Cannot open \\[bad_url:111\\] with \\[/',
+ $socket->getError());
+ $this->assertFalse($socket->isOpen());
+ $this->assertFalse($socket->write('A message'));
+ }
+
+ function testSocketClosure() {
+ $socket = new SimpleSocket('www.lastcraft.com', 80, 15, 8);
+ $this->assertTrue($socket->isOpen());
+ $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n"));
+ $socket->write("Host: www.lastcraft.com\r\n");
+ $socket->write("Connection: close\r\n\r\n");
+ $this->assertEqual($socket->read(), "HTTP/1.1");
+ $socket->close();
+ $this->assertIdentical($socket->read(), false);
+ }
+
+ function testRecordOfSentCharacters() {
+ $socket = new SimpleSocket('www.lastcraft.com', 80, 15);
+ $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n"));
+ $socket->write("Host: www.lastcraft.com\r\n");
+ $socket->write("Connection: close\r\n\r\n");
+ $socket->close();
+ $this->assertEqual($socket->getSent(),
+ "GET /test/network_confirm.php HTTP/1.0\r\n" .
+ "Host: www.lastcraft.com\r\n" .
+ "Connection: close\r\n\r\n");
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/mock_objects_test.php b/3rdparty/simpletest/test/mock_objects_test.php
new file mode 100755
index 00000000000..7f3178995a7
--- /dev/null
+++ b/3rdparty/simpletest/test/mock_objects_test.php
@@ -0,0 +1,985 @@
+<?php
+// $Id: mock_objects_test.php 1900 2009-07-29 11:44:37Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../expectation.php');
+require_once(dirname(__FILE__) . '/../mock_objects.php');
+
+class TestOfAnythingExpectation extends UnitTestCase {
+ function testSimpleInteger() {
+ $expectation = new AnythingExpectation();
+ $this->assertTrue($expectation->test(33));
+ $this->assertTrue($expectation->test(false));
+ $this->assertTrue($expectation->test(null));
+ }
+}
+
+class TestOfParametersExpectation extends UnitTestCase {
+
+ function testEmptyMatch() {
+ $expectation = new ParametersExpectation(array());
+ $this->assertTrue($expectation->test(array()));
+ $this->assertFalse($expectation->test(array(33)));
+ }
+
+ function testSingleMatch() {
+ $expectation = new ParametersExpectation(array(0));
+ $this->assertFalse($expectation->test(array(1)));
+ $this->assertTrue($expectation->test(array(0)));
+ }
+
+ function testAnyMatch() {
+ $expectation = new ParametersExpectation(false);
+ $this->assertTrue($expectation->test(array()));
+ $this->assertTrue($expectation->test(array(1, 2)));
+ }
+
+ function testMissingParameter() {
+ $expectation = new ParametersExpectation(array(0));
+ $this->assertFalse($expectation->test(array()));
+ }
+
+ function testNullParameter() {
+ $expectation = new ParametersExpectation(array(null));
+ $this->assertTrue($expectation->test(array(null)));
+ $this->assertFalse($expectation->test(array()));
+ }
+
+ function testAnythingExpectations() {
+ $expectation = new ParametersExpectation(array(new AnythingExpectation()));
+ $this->assertFalse($expectation->test(array()));
+ $this->assertIdentical($expectation->test(array(null)), true);
+ $this->assertIdentical($expectation->test(array(13)), true);
+ }
+
+ function testOtherExpectations() {
+ $expectation = new ParametersExpectation(
+ array(new PatternExpectation('/hello/i')));
+ $this->assertFalse($expectation->test(array('Goodbye')));
+ $this->assertTrue($expectation->test(array('hello')));
+ $this->assertTrue($expectation->test(array('Hello')));
+ }
+
+ function testIdentityOnly() {
+ $expectation = new ParametersExpectation(array("0"));
+ $this->assertFalse($expectation->test(array(0)));
+ $this->assertTrue($expectation->test(array("0")));
+ }
+
+ function testLongList() {
+ $expectation = new ParametersExpectation(
+ array("0", 0, new AnythingExpectation(), false));
+ $this->assertTrue($expectation->test(array("0", 0, 37, false)));
+ $this->assertFalse($expectation->test(array("0", 0, 37, true)));
+ $this->assertFalse($expectation->test(array("0", 0, 37)));
+ }
+}
+
+class TestOfSimpleSignatureMap extends UnitTestCase {
+
+ function testEmpty() {
+ $map = new SimpleSignatureMap();
+ $this->assertFalse($map->isMatch("any", array()));
+ $this->assertNull($map->findFirstAction("any", array()));
+ }
+
+ function testDifferentCallSignaturesCanHaveDifferentReferences() {
+ $map = new SimpleSignatureMap();
+ $fred = 'Fred';
+ $jim = 'jim';
+ $map->add(array(0), $fred);
+ $map->add(array('0'), $jim);
+ $this->assertSame($fred, $map->findFirstAction(array(0)));
+ $this->assertSame($jim, $map->findFirstAction(array('0')));
+ }
+
+ function testWildcard() {
+ $fred = 'Fred';
+ $map = new SimpleSignatureMap();
+ $map->add(array(new AnythingExpectation(), 1, 3), $fred);
+ $this->assertTrue($map->isMatch(array(2, 1, 3)));
+ $this->assertSame($map->findFirstAction(array(2, 1, 3)), $fred);
+ }
+
+ function testAllWildcard() {
+ $fred = 'Fred';
+ $map = new SimpleSignatureMap();
+ $this->assertFalse($map->isMatch(array(2, 1, 3)));
+ $map->add('', $fred);
+ $this->assertTrue($map->isMatch(array(2, 1, 3)));
+ $this->assertSame($map->findFirstAction(array(2, 1, 3)), $fred);
+ }
+
+ function testOrdering() {
+ $map = new SimpleSignatureMap();
+ $map->add(array(1, 2), new SimpleByValue("1, 2"));
+ $map->add(array(1, 3), new SimpleByValue("1, 3"));
+ $map->add(array(1), new SimpleByValue("1"));
+ $map->add(array(1, 4), new SimpleByValue("1, 4"));
+ $map->add(array(new AnythingExpectation()), new SimpleByValue("Any"));
+ $map->add(array(2), new SimpleByValue("2"));
+ $map->add("", new SimpleByValue("Default"));
+ $map->add(array(), new SimpleByValue("None"));
+ $this->assertEqual($map->findFirstAction(array(1, 2)), new SimpleByValue("1, 2"));
+ $this->assertEqual($map->findFirstAction(array(1, 3)), new SimpleByValue("1, 3"));
+ $this->assertEqual($map->findFirstAction(array(1, 4)), new SimpleByValue("1, 4"));
+ $this->assertEqual($map->findFirstAction(array(1)), new SimpleByValue("1"));
+ $this->assertEqual($map->findFirstAction(array(2)), new SimpleByValue("Any"));
+ $this->assertEqual($map->findFirstAction(array(3)), new SimpleByValue("Any"));
+ $this->assertEqual($map->findFirstAction(array()), new SimpleByValue("Default"));
+ }
+}
+
+class TestOfCallSchedule extends UnitTestCase {
+ function testCanBeSetToAlwaysReturnTheSameReference() {
+ $a = 5;
+ $schedule = new SimpleCallSchedule();
+ $schedule->register('aMethod', false, new SimpleByReference($a));
+ $this->assertReference($schedule->respond(0, 'aMethod', array()), $a);
+ $this->assertReference($schedule->respond(1, 'aMethod', array()), $a);
+ }
+
+ function testSpecificSignaturesOverrideTheAlwaysCase() {
+ $any = 'any';
+ $one = 'two';
+ $schedule = new SimpleCallSchedule();
+ $schedule->register('aMethod', array(1), new SimpleByReference($one));
+ $schedule->register('aMethod', false, new SimpleByReference($any));
+ $this->assertReference($schedule->respond(0, 'aMethod', array(2)), $any);
+ $this->assertReference($schedule->respond(0, 'aMethod', array(1)), $one);
+ }
+
+ function testReturnsCanBeSetOverTime() {
+ $one = 'one';
+ $two = 'two';
+ $schedule = new SimpleCallSchedule();
+ $schedule->registerAt(0, 'aMethod', false, new SimpleByReference($one));
+ $schedule->registerAt(1, 'aMethod', false, new SimpleByReference($two));
+ $this->assertReference($schedule->respond(0, 'aMethod', array()), $one);
+ $this->assertReference($schedule->respond(1, 'aMethod', array()), $two);
+ }
+
+ function testReturnsOverTimecanBeAlteredByTheArguments() {
+ $one = '1';
+ $two = '2';
+ $two_a = '2a';
+ $schedule = new SimpleCallSchedule();
+ $schedule->registerAt(0, 'aMethod', false, new SimpleByReference($one));
+ $schedule->registerAt(1, 'aMethod', array('a'), new SimpleByReference($two_a));
+ $schedule->registerAt(1, 'aMethod', false, new SimpleByReference($two));
+ $this->assertReference($schedule->respond(0, 'aMethod', array()), $one);
+ $this->assertReference($schedule->respond(1, 'aMethod', array()), $two);
+ $this->assertReference($schedule->respond(1, 'aMethod', array('a')), $two_a);
+ }
+
+ function testCanReturnByValue() {
+ $a = 5;
+ $schedule = new SimpleCallSchedule();
+ $schedule->register('aMethod', false, new SimpleByValue($a));
+ $this->assertCopy($schedule->respond(0, 'aMethod', array()), $a);
+ }
+
+ function testCanThrowException() {
+ if (version_compare(phpversion(), '5', '>=')) {
+ $schedule = new SimpleCallSchedule();
+ $schedule->register('aMethod', false, new SimpleThrower(new Exception('Ouch')));
+ $this->expectException(new Exception('Ouch'));
+ $schedule->respond(0, 'aMethod', array());
+ }
+ }
+
+ function testCanEmitError() {
+ $schedule = new SimpleCallSchedule();
+ $schedule->register('aMethod', false, new SimpleErrorThrower('Ouch', E_USER_WARNING));
+ $this->expectError('Ouch');
+ $schedule->respond(0, 'aMethod', array());
+ }
+}
+
+class Dummy {
+ function Dummy() {
+ }
+
+ function aMethod() {
+ return true;
+ }
+
+ function &aReferenceMethod() {
+ return true;
+ }
+
+ function anotherMethod() {
+ return true;
+ }
+}
+Mock::generate('Dummy');
+Mock::generate('Dummy', 'AnotherMockDummy');
+Mock::generate('Dummy', 'MockDummyWithExtraMethods', array('extraMethod'));
+
+class TestOfMockGeneration extends UnitTestCase {
+
+ function testCloning() {
+ $mock = new MockDummy();
+ $this->assertTrue(method_exists($mock, "aMethod"));
+ $this->assertNull($mock->aMethod());
+ }
+
+ function testCloningWithExtraMethod() {
+ $mock = new MockDummyWithExtraMethods();
+ $this->assertTrue(method_exists($mock, "extraMethod"));
+ }
+
+ function testCloningWithChosenClassName() {
+ $mock = new AnotherMockDummy();
+ $this->assertTrue(method_exists($mock, "aMethod"));
+ }
+}
+
+class TestOfMockReturns extends UnitTestCase {
+
+ function testDefaultReturn() {
+ $mock = new MockDummy();
+ $mock->returnsByValue("aMethod", "aaa");
+ $this->assertIdentical($mock->aMethod(), "aaa");
+ $this->assertIdentical($mock->aMethod(), "aaa");
+ }
+
+ function testParameteredReturn() {
+ $mock = new MockDummy();
+ $mock->returnsByValue('aMethod', 'aaa', array(1, 2, 3));
+ $this->assertNull($mock->aMethod());
+ $this->assertIdentical($mock->aMethod(1, 2, 3), 'aaa');
+ }
+
+ function testSetReturnGivesObjectReference() {
+ $mock = new MockDummy();
+ $object = new Dummy();
+ $mock->returns('aMethod', $object, array(1, 2, 3));
+ $this->assertSame($mock->aMethod(1, 2, 3), $object);
+ }
+
+ function testSetReturnReferenceGivesOriginalReference() {
+ $mock = new MockDummy();
+ $object = 1;
+ $mock->returnsByReference('aReferenceMethod', $object, array(1, 2, 3));
+ $this->assertReference($mock->aReferenceMethod(1, 2, 3), $object);
+ }
+
+ function testReturnValueCanBeChosenJustByPatternMatchingArguments() {
+ $mock = new MockDummy();
+ $mock->returnsByValue(
+ "aMethod",
+ "aaa",
+ array(new PatternExpectation('/hello/i')));
+ $this->assertIdentical($mock->aMethod('Hello'), 'aaa');
+ $this->assertNull($mock->aMethod('Goodbye'));
+ }
+
+ function testMultipleMethods() {
+ $mock = new MockDummy();
+ $mock->returnsByValue("aMethod", 100, array(1));
+ $mock->returnsByValue("aMethod", 200, array(2));
+ $mock->returnsByValue("anotherMethod", 10, array(1));
+ $mock->returnsByValue("anotherMethod", 20, array(2));
+ $this->assertIdentical($mock->aMethod(1), 100);
+ $this->assertIdentical($mock->anotherMethod(1), 10);
+ $this->assertIdentical($mock->aMethod(2), 200);
+ $this->assertIdentical($mock->anotherMethod(2), 20);
+ }
+
+ function testReturnSequence() {
+ $mock = new MockDummy();
+ $mock->returnsByValueAt(0, "aMethod", "aaa");
+ $mock->returnsByValueAt(1, "aMethod", "bbb");
+ $mock->returnsByValueAt(3, "aMethod", "ddd");
+ $this->assertIdentical($mock->aMethod(), "aaa");
+ $this->assertIdentical($mock->aMethod(), "bbb");
+ $this->assertNull($mock->aMethod());
+ $this->assertIdentical($mock->aMethod(), "ddd");
+ }
+
+ function testSetReturnReferenceAtGivesOriginal() {
+ $mock = new MockDummy();
+ $object = 100;
+ $mock->returnsByReferenceAt(1, "aReferenceMethod", $object);
+ $this->assertNull($mock->aReferenceMethod());
+ $this->assertReference($mock->aReferenceMethod(), $object);
+ $this->assertNull($mock->aReferenceMethod());
+ }
+
+ function testReturnsAtGivesOriginalObjectHandle() {
+ $mock = new MockDummy();
+ $object = new Dummy();
+ $mock->returnsAt(1, "aMethod", $object);
+ $this->assertNull($mock->aMethod());
+ $this->assertSame($mock->aMethod(), $object);
+ $this->assertNull($mock->aMethod());
+ }
+
+ function testComplicatedReturnSequence() {
+ $mock = new MockDummy();
+ $object = new Dummy();
+ $mock->returnsAt(1, "aMethod", "aaa", array("a"));
+ $mock->returnsAt(1, "aMethod", "bbb");
+ $mock->returnsAt(2, "aMethod", $object, array('*', 2));
+ $mock->returnsAt(2, "aMethod", "value", array('*', 3));
+ $mock->returns("aMethod", 3, array(3));
+ $this->assertNull($mock->aMethod());
+ $this->assertEqual($mock->aMethod("a"), "aaa");
+ $this->assertSame($mock->aMethod(1, 2), $object);
+ $this->assertEqual($mock->aMethod(3), 3);
+ $this->assertNull($mock->aMethod());
+ }
+
+ function testMultipleMethodSequences() {
+ $mock = new MockDummy();
+ $mock->returnsByValueAt(0, "aMethod", "aaa");
+ $mock->returnsByValueAt(1, "aMethod", "bbb");
+ $mock->returnsByValueAt(0, "anotherMethod", "ccc");
+ $mock->returnsByValueAt(1, "anotherMethod", "ddd");
+ $this->assertIdentical($mock->aMethod(), "aaa");
+ $this->assertIdentical($mock->anotherMethod(), "ccc");
+ $this->assertIdentical($mock->aMethod(), "bbb");
+ $this->assertIdentical($mock->anotherMethod(), "ddd");
+ }
+
+ function testSequenceFallback() {
+ $mock = new MockDummy();
+ $mock->returnsByValueAt(0, "aMethod", "aaa", array('a'));
+ $mock->returnsByValueAt(1, "aMethod", "bbb", array('a'));
+ $mock->returnsByValue("aMethod", "AAA");
+ $this->assertIdentical($mock->aMethod('a'), "aaa");
+ $this->assertIdentical($mock->aMethod('b'), "AAA");
+ }
+
+ function testMethodInterference() {
+ $mock = new MockDummy();
+ $mock->returnsByValueAt(0, "anotherMethod", "aaa");
+ $mock->returnsByValue("aMethod", "AAA");
+ $this->assertIdentical($mock->aMethod(), "AAA");
+ $this->assertIdentical($mock->anotherMethod(), "aaa");
+ }
+}
+
+class TestOfMockExpectationsThatPass extends UnitTestCase {
+
+ function testAnyArgument() {
+ $mock = new MockDummy();
+ $mock->expect('aMethod', array('*'));
+ $mock->aMethod(1);
+ $mock->aMethod('hello');
+ }
+
+ function testAnyTwoArguments() {
+ $mock = new MockDummy();
+ $mock->expect('aMethod', array('*', '*'));
+ $mock->aMethod(1, 2);
+ }
+
+ function testSpecificArgument() {
+ $mock = new MockDummy();
+ $mock->expect('aMethod', array(1));
+ $mock->aMethod(1);
+ }
+
+ function testExpectation() {
+ $mock = new MockDummy();
+ $mock->expect('aMethod', array(new IsAExpectation('Dummy')));
+ $mock->aMethod(new Dummy());
+ }
+
+ function testArgumentsInSequence() {
+ $mock = new MockDummy();
+ $mock->expectAt(0, 'aMethod', array(1, 2));
+ $mock->expectAt(1, 'aMethod', array(3, 4));
+ $mock->aMethod(1, 2);
+ $mock->aMethod(3, 4);
+ }
+
+ function testAtLeastOnceSatisfiedByOneCall() {
+ $mock = new MockDummy();
+ $mock->expectAtLeastOnce('aMethod');
+ $mock->aMethod();
+ }
+
+ function testAtLeastOnceSatisfiedByTwoCalls() {
+ $mock = new MockDummy();
+ $mock->expectAtLeastOnce('aMethod');
+ $mock->aMethod();
+ $mock->aMethod();
+ }
+
+ function testOnceSatisfiedByOneCall() {
+ $mock = new MockDummy();
+ $mock->expectOnce('aMethod');
+ $mock->aMethod();
+ }
+
+ function testMinimumCallsSatisfiedByEnoughCalls() {
+ $mock = new MockDummy();
+ $mock->expectMinimumCallCount('aMethod', 1);
+ $mock->aMethod();
+ }
+
+ function testMinimumCallsSatisfiedByTooManyCalls() {
+ $mock = new MockDummy();
+ $mock->expectMinimumCallCount('aMethod', 3);
+ $mock->aMethod();
+ $mock->aMethod();
+ $mock->aMethod();
+ $mock->aMethod();
+ }
+
+ function testMaximumCallsSatisfiedByEnoughCalls() {
+ $mock = new MockDummy();
+ $mock->expectMaximumCallCount('aMethod', 1);
+ $mock->aMethod();
+ }
+
+ function testMaximumCallsSatisfiedByNoCalls() {
+ $mock = new MockDummy();
+ $mock->expectMaximumCallCount('aMethod', 1);
+ }
+}
+
+class MockWithInjectedTestCase extends SimpleMock {
+ protected function getCurrentTestCase() {
+ return SimpleTest::getContext()->getTest()->getMockedTest();
+ }
+}
+SimpleTest::setMockBaseClass('MockWithInjectedTestCase');
+Mock::generate('Dummy', 'MockDummyWithInjectedTestCase');
+SimpleTest::setMockBaseClass('SimpleMock');
+Mock::generate('SimpleTestCase');
+
+class LikeExpectation extends IdenticalExpectation {
+ function __construct($expectation) {
+ $expectation->message = '';
+ parent::__construct($expectation);
+ }
+
+ function test($compare) {
+ $compare->message = '';
+ return parent::test($compare);
+ }
+
+ function testMessage($compare) {
+ $compare->message = '';
+ return parent::testMessage($compare);
+ }
+}
+
+class TestOfMockExpectations extends UnitTestCase {
+ private $test;
+
+ function setUp() {
+ $this->test = new MockSimpleTestCase();
+ }
+
+ function getMockedTest() {
+ return $this->test;
+ }
+
+ function testSettingExpectationOnNonMethodThrowsError() {
+ $mock = new MockDummyWithInjectedTestCase();
+ $this->expectError();
+ $mock->expectMaximumCallCount('aMissingMethod', 2);
+ }
+
+ function testMaxCallsDetectsOverrun() {
+ $this->test->expectOnce('assert', array(new MemberExpectation('count', 2), 3));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expectMaximumCallCount('aMethod', 2);
+ $mock->aMethod();
+ $mock->aMethod();
+ $mock->aMethod();
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testTallyOnMaxCallsSendsPassOnUnderrun() {
+ $this->test->expectOnce('assert', array(new MemberExpectation('count', 2), 2));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expectMaximumCallCount("aMethod", 2);
+ $mock->aMethod();
+ $mock->aMethod();
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testExpectNeverDetectsOverrun() {
+ $this->test->expectOnce('assert', array(new MemberExpectation('count', 0), 1));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expectNever('aMethod');
+ $mock->aMethod();
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testTallyOnExpectNeverStillSendsPassOnUnderrun() {
+ $this->test->expectOnce('assert', array(new MemberExpectation('count', 0), 0));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expectNever('aMethod');
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testMinCalls() {
+ $this->test->expectOnce('assert', array(new MemberExpectation('count', 2), 2));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expectMinimumCallCount('aMethod', 2);
+ $mock->aMethod();
+ $mock->aMethod();
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testFailedNever() {
+ $this->test->expectOnce('assert', array(new MemberExpectation('count', 0), 1));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expectNever('aMethod');
+ $mock->aMethod();
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testUnderOnce() {
+ $this->test->expectOnce('assert', array(new MemberExpectation('count', 1), 0));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expectOnce('aMethod');
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testOverOnce() {
+ $this->test->expectOnce('assert', array(new MemberExpectation('count', 1), 2));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expectOnce('aMethod');
+ $mock->aMethod();
+ $mock->aMethod();
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testUnderAtLeastOnce() {
+ $this->test->expectOnce('assert', array(new MemberExpectation('count', 1), 0));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expectAtLeastOnce("aMethod");
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testZeroArguments() {
+ $this->test->expectOnce('assert',
+ array(new MemberExpectation('expected', array()), array(), '*'));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expect('aMethod', array());
+ $mock->aMethod();
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testExpectedArguments() {
+ $this->test->expectOnce('assert',
+ array(new MemberExpectation('expected', array(1, 2, 3)), array(1, 2, 3), '*'));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expect('aMethod', array(1, 2, 3));
+ $mock->aMethod(1, 2, 3);
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testFailedArguments() {
+ $this->test->expectOnce('assert',
+ array(new MemberExpectation('expected', array('this')), array('that'), '*'));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expect('aMethod', array('this'));
+ $mock->aMethod('that');
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testWildcardsAreTranslatedToAnythingExpectations() {
+ $this->test->expectOnce('assert',
+ array(new MemberExpectation('expected',
+ array(new AnythingExpectation(),
+ 123,
+ new AnythingExpectation())),
+ array(100, 123, 101), '*'));
+ $mock = new MockDummyWithInjectedTestCase($this);
+ $mock->expect("aMethod", array('*', 123, '*'));
+ $mock->aMethod(100, 123, 101);
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testSpecificPassingSequence() {
+ $this->test->expectAt(0, 'assert',
+ array(new MemberExpectation('expected', array(1, 2, 3)), array(1, 2, 3), '*'));
+ $this->test->expectAt(1, 'assert',
+ array(new MemberExpectation('expected', array('Hello')), array('Hello'), '*'));
+ $mock = new MockDummyWithInjectedTestCase();
+ $mock->expectAt(1, 'aMethod', array(1, 2, 3));
+ $mock->expectAt(2, 'aMethod', array('Hello'));
+ $mock->aMethod();
+ $mock->aMethod(1, 2, 3);
+ $mock->aMethod('Hello');
+ $mock->aMethod();
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+
+ function testNonArrayForExpectedParametersGivesError() {
+ $mock = new MockDummyWithInjectedTestCase();
+ $this->expectError(new PatternExpectation('/\$args.*not an array/i'));
+ $mock->expect("aMethod", "foo");
+ $mock->aMethod();
+ $mock->mock->atTestEnd('testSomething', $this->test);
+ }
+}
+
+class TestOfMockComparisons extends UnitTestCase {
+
+ function testEqualComparisonOfMocksDoesNotCrash() {
+ $expectation = new EqualExpectation(new MockDummy());
+ $this->assertTrue($expectation->test(new MockDummy(), true));
+ }
+
+ function testIdenticalComparisonOfMocksDoesNotCrash() {
+ $expectation = new IdenticalExpectation(new MockDummy());
+ $this->assertTrue($expectation->test(new MockDummy()));
+ }
+}
+
+class ClassWithSpecialMethods {
+ function __get($name) { }
+ function __set($name, $value) { }
+ function __isset($name) { }
+ function __unset($name) { }
+ function __call($method, $arguments) { }
+ function __toString() { }
+}
+Mock::generate('ClassWithSpecialMethods');
+
+class TestOfSpecialMethodsAfterPHP51 extends UnitTestCase {
+
+ function skip() {
+ $this->skipIf(version_compare(phpversion(), '5.1', '<'), '__isset and __unset overloading not tested unless PHP 5.1+');
+ }
+
+ function testCanEmulateIsset() {
+ $mock = new MockClassWithSpecialMethods();
+ $mock->returnsByValue('__isset', true);
+ $this->assertIdentical(isset($mock->a), true);
+ }
+
+ function testCanExpectUnset() {
+ $mock = new MockClassWithSpecialMethods();
+ $mock->expectOnce('__unset', array('a'));
+ unset($mock->a);
+ }
+
+}
+
+class TestOfSpecialMethods extends UnitTestCase {
+ function skip() {
+ $this->skipIf(version_compare(phpversion(), '5', '<'), 'Overloading not tested unless PHP 5+');
+ }
+
+ function testCanMockTheThingAtAll() {
+ $mock = new MockClassWithSpecialMethods();
+ }
+
+ function testReturnFromSpecialAccessor() {
+ $mock = new MockClassWithSpecialMethods();
+ $mock->returnsByValue('__get', '1st Return', array('first'));
+ $mock->returnsByValue('__get', '2nd Return', array('second'));
+ $this->assertEqual($mock->first, '1st Return');
+ $this->assertEqual($mock->second, '2nd Return');
+ }
+
+ function testcanExpectTheSettingOfValue() {
+ $mock = new MockClassWithSpecialMethods();
+ $mock->expectOnce('__set', array('a', 'A'));
+ $mock->a = 'A';
+ }
+
+ function testCanSimulateAnOverloadmethod() {
+ $mock = new MockClassWithSpecialMethods();
+ $mock->expectOnce('__call', array('amOverloaded', array('A')));
+ $mock->returnsByValue('__call', 'aaa');
+ $this->assertIdentical($mock->amOverloaded('A'), 'aaa');
+ }
+
+ function testToStringMagic() {
+ $mock = new MockClassWithSpecialMethods();
+ $mock->expectOnce('__toString');
+ $mock->returnsByValue('__toString', 'AAA');
+ ob_start();
+ print $mock;
+ $output = ob_get_contents();
+ ob_end_clean();
+ $this->assertEqual($output, 'AAA');
+ }
+}
+
+class WithStaticMethod {
+ static function aStaticMethod() { }
+}
+Mock::generate('WithStaticMethod');
+
+class TestOfMockingClassesWithStaticMethods extends UnitTestCase {
+
+ function testStaticMethodIsMockedAsStatic() {
+ $mock = new WithStaticMethod();
+ $reflection = new ReflectionClass($mock);
+ $method = $reflection->getMethod('aStaticMethod');
+ $this->assertTrue($method->isStatic());
+ }
+}
+
+class MockTestException extends Exception { }
+
+class TestOfThrowingExceptionsFromMocks extends UnitTestCase {
+
+ function testCanThrowOnMethodCall() {
+ $mock = new MockDummy();
+ $mock->throwOn('aMethod');
+ $this->expectException();
+ $mock->aMethod();
+ }
+
+ function testCanThrowSpecificExceptionOnMethodCall() {
+ $mock = new MockDummy();
+ $mock->throwOn('aMethod', new MockTestException());
+ $this->expectException();
+ $mock->aMethod();
+ }
+
+ function testThrowsOnlyWhenCallSignatureMatches() {
+ $mock = new MockDummy();
+ $mock->throwOn('aMethod', new MockTestException(), array(3));
+ $mock->aMethod(1);
+ $mock->aMethod(2);
+ $this->expectException();
+ $mock->aMethod(3);
+ }
+
+ function testCanThrowOnParticularInvocation() {
+ $mock = new MockDummy();
+ $mock->throwAt(2, 'aMethod', new MockTestException());
+ $mock->aMethod();
+ $mock->aMethod();
+ $this->expectException();
+ $mock->aMethod();
+ }
+}
+
+class TestOfThrowingErrorsFromMocks extends UnitTestCase {
+
+ function testCanGenerateErrorFromMethodCall() {
+ $mock = new MockDummy();
+ $mock->errorOn('aMethod', 'Ouch!');
+ $this->expectError('Ouch!');
+ $mock->aMethod();
+ }
+
+ function testGeneratesErrorOnlyWhenCallSignatureMatches() {
+ $mock = new MockDummy();
+ $mock->errorOn('aMethod', 'Ouch!', array(3));
+ $mock->aMethod(1);
+ $mock->aMethod(2);
+ $this->expectError();
+ $mock->aMethod(3);
+ }
+
+ function testCanGenerateErrorOnParticularInvocation() {
+ $mock = new MockDummy();
+ $mock->errorAt(2, 'aMethod', 'Ouch!');
+ $mock->aMethod();
+ $mock->aMethod();
+ $this->expectError();
+ $mock->aMethod();
+ }
+}
+
+Mock::generatePartial('Dummy', 'TestDummy', array('anotherMethod', 'aReferenceMethod'));
+
+class TestOfPartialMocks extends UnitTestCase {
+
+ function testMethodReplacementWithNoBehaviourReturnsNull() {
+ $mock = new TestDummy();
+ $this->assertEqual($mock->aMethod(99), 99);
+ $this->assertNull($mock->anotherMethod());
+ }
+
+ function testSettingReturns() {
+ $mock = new TestDummy();
+ $mock->returnsByValue('anotherMethod', 33, array(3));
+ $mock->returnsByValue('anotherMethod', 22);
+ $mock->returnsByValueAt(2, 'anotherMethod', 44, array(3));
+ $this->assertEqual($mock->anotherMethod(), 22);
+ $this->assertEqual($mock->anotherMethod(3), 33);
+ $this->assertEqual($mock->anotherMethod(3), 44);
+ }
+
+ function testSetReturnReferenceGivesOriginal() {
+ $mock = new TestDummy();
+ $object = 99;
+ $mock->returnsByReferenceAt(0, 'aReferenceMethod', $object, array(3));
+ $this->assertReference($mock->aReferenceMethod(3), $object);
+ }
+
+ function testReturnsAtGivesOriginalObjectHandle() {
+ $mock = new TestDummy();
+ $object = new Dummy();
+ $mock->returnsAt(0, 'anotherMethod', $object, array(3));
+ $this->assertSame($mock->anotherMethod(3), $object);
+ }
+
+ function testExpectations() {
+ $mock = new TestDummy();
+ $mock->expectCallCount('anotherMethod', 2);
+ $mock->expect('anotherMethod', array(77));
+ $mock->expectAt(1, 'anotherMethod', array(66));
+ $mock->anotherMethod(77);
+ $mock->anotherMethod(66);
+ }
+
+ function testSettingExpectationOnMissingMethodThrowsError() {
+ $mock = new TestDummy();
+ $this->expectError();
+ $mock->expectCallCount('aMissingMethod', 2);
+ }
+}
+
+class ConstructorSuperClass {
+ function ConstructorSuperClass() { }
+}
+
+class ConstructorSubClass extends ConstructorSuperClass { }
+
+class TestOfPHP4StyleSuperClassConstruct extends UnitTestCase {
+ function testBasicConstruct() {
+ Mock::generate('ConstructorSubClass');
+ $mock = new MockConstructorSubClass();
+ $this->assertIsA($mock, 'ConstructorSubClass');
+ $this->assertTrue(method_exists($mock, 'ConstructorSuperClass'));
+ }
+}
+
+class TestOfPHP5StaticMethodMocking extends UnitTestCase {
+ function testCanCreateAMockObjectWithStaticMethodsWithoutError() {
+ eval('
+ class SimpleObjectContainingStaticMethod {
+ static function someStatic() { }
+ }
+ ');
+ Mock::generate('SimpleObjectContainingStaticMethod');
+ }
+}
+
+class TestOfPHP5AbstractMethodMocking extends UnitTestCase {
+ function testCanCreateAMockObjectFromAnAbstractWithProperFunctionDeclarations() {
+ eval('
+ abstract class SimpleAbstractClassContainingAbstractMethods {
+ abstract function anAbstract();
+ abstract function anAbstractWithParameter($foo);
+ abstract function anAbstractWithMultipleParameters($foo, $bar);
+ }
+ ');
+ Mock::generate('SimpleAbstractClassContainingAbstractMethods');
+ $this->assertTrue(
+ method_exists(
+ // Testing with class name alone does not work in PHP 5.0
+ new MockSimpleAbstractClassContainingAbstractMethods,
+ 'anAbstract'
+ )
+ );
+ $this->assertTrue(
+ method_exists(
+ new MockSimpleAbstractClassContainingAbstractMethods,
+ 'anAbstractWithParameter'
+ )
+ );
+ $this->assertTrue(
+ method_exists(
+ new MockSimpleAbstractClassContainingAbstractMethods,
+ 'anAbstractWithMultipleParameters'
+ )
+ );
+ }
+
+ function testMethodsDefinedAsAbstractInParentShouldHaveFullSignature() {
+ eval('
+ abstract class SimpleParentAbstractClassContainingAbstractMethods {
+ abstract function anAbstract();
+ abstract function anAbstractWithParameter($foo);
+ abstract function anAbstractWithMultipleParameters($foo, $bar);
+ }
+
+ class SimpleChildAbstractClassContainingAbstractMethods extends SimpleParentAbstractClassContainingAbstractMethods {
+ function anAbstract(){}
+ function anAbstractWithParameter($foo){}
+ function anAbstractWithMultipleParameters($foo, $bar){}
+ }
+
+ class EvenDeeperEmptyChildClass extends SimpleChildAbstractClassContainingAbstractMethods {}
+ ');
+ Mock::generate('SimpleChildAbstractClassContainingAbstractMethods');
+ $this->assertTrue(
+ method_exists(
+ new MockSimpleChildAbstractClassContainingAbstractMethods,
+ 'anAbstract'
+ )
+ );
+ $this->assertTrue(
+ method_exists(
+ new MockSimpleChildAbstractClassContainingAbstractMethods,
+ 'anAbstractWithParameter'
+ )
+ );
+ $this->assertTrue(
+ method_exists(
+ new MockSimpleChildAbstractClassContainingAbstractMethods,
+ 'anAbstractWithMultipleParameters'
+ )
+ );
+ Mock::generate('EvenDeeperEmptyChildClass');
+ $this->assertTrue(
+ method_exists(
+ new MockEvenDeeperEmptyChildClass,
+ 'anAbstract'
+ )
+ );
+ $this->assertTrue(
+ method_exists(
+ new MockEvenDeeperEmptyChildClass,
+ 'anAbstractWithParameter'
+ )
+ );
+ $this->assertTrue(
+ method_exists(
+ new MockEvenDeeperEmptyChildClass,
+ 'anAbstractWithMultipleParameters'
+ )
+ );
+ }
+}
+
+class DummyWithProtected
+{
+ public function aMethodCallsProtected() { return $this->aProtectedMethod(); }
+ protected function aProtectedMethod() { return true; }
+}
+
+Mock::generatePartial('DummyWithProtected', 'TestDummyWithProtected', array('aProtectedMethod'));
+class TestOfProtectedMethodPartialMocks extends UnitTestCase
+{
+ function testProtectedMethodExists() {
+ $this->assertTrue(
+ method_exists(
+ new TestDummyWithProtected,
+ 'aProtectedMethod'
+ )
+ );
+ }
+
+ function testProtectedMethodIsCalled() {
+ $object = new DummyWithProtected();
+ $this->assertTrue($object->aMethodCallsProtected(), 'ensure original was called');
+ }
+
+ function testMockedMethodIsCalled() {
+ $object = new TestDummyWithProtected();
+ $object->returnsByValue('aProtectedMethod', false);
+ $this->assertFalse($object->aMethodCallsProtected());
+ }
+}
+
+?>
diff --git a/3rdparty/simpletest/test/page_test.php b/3rdparty/simpletest/test/page_test.php
new file mode 100755
index 00000000000..fdc15c5d008
--- /dev/null
+++ b/3rdparty/simpletest/test/page_test.php
@@ -0,0 +1,166 @@
+<?php
+// $Id: page_test.php 1913 2009-07-29 16:50:56Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../expectation.php');
+require_once(dirname(__FILE__) . '/../http.php');
+require_once(dirname(__FILE__) . '/../page.php');
+Mock::generate('SimpleHttpHeaders');
+Mock::generate('SimpleHttpResponse');
+
+class TestOfPageInterface extends UnitTestCase {
+ function testInterfaceOnEmptyPage() {
+ $page = new SimplePage();
+ $this->assertEqual($page->getTransportError(), 'No page fetched yet');
+ $this->assertIdentical($page->getRaw(), false);
+ $this->assertIdentical($page->getHeaders(), false);
+ $this->assertIdentical($page->getMimeType(), false);
+ $this->assertIdentical($page->getResponseCode(), false);
+ $this->assertIdentical($page->getAuthentication(), false);
+ $this->assertIdentical($page->getRealm(), false);
+ $this->assertFalse($page->hasFrames());
+ $this->assertIdentical($page->getUrls(), array());
+ $this->assertIdentical($page->getTitle(), false);
+ }
+}
+
+class TestOfPageHeaders extends UnitTestCase {
+
+ function testUrlAccessor() {
+ $headers = new MockSimpleHttpHeaders();
+
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue('getHeaders', $headers);
+ $response->setReturnValue('getMethod', 'POST');
+ $response->setReturnValue('getUrl', new SimpleUrl('here'));
+ $response->setReturnValue('getRequestData', array('a' => 'A'));
+
+ $page = new SimplePage($response);
+ $this->assertEqual($page->getMethod(), 'POST');
+ $this->assertEqual($page->getUrl(), new SimpleUrl('here'));
+ $this->assertEqual($page->getRequestData(), array('a' => 'A'));
+ }
+
+ function testTransportError() {
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue('getError', 'Ouch');
+
+ $page = new SimplePage($response);
+ $this->assertEqual($page->getTransportError(), 'Ouch');
+ }
+
+ function testHeadersAccessor() {
+ $headers = new MockSimpleHttpHeaders();
+ $headers->setReturnValue('getRaw', 'My: Headers');
+
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue('getHeaders', $headers);
+
+ $page = new SimplePage($response);
+ $this->assertEqual($page->getHeaders(), 'My: Headers');
+ }
+
+ function testMimeAccessor() {
+ $headers = new MockSimpleHttpHeaders();
+ $headers->setReturnValue('getMimeType', 'text/html');
+
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue('getHeaders', $headers);
+
+ $page = new SimplePage($response);
+ $this->assertEqual($page->getMimeType(), 'text/html');
+ }
+
+ function testResponseAccessor() {
+ $headers = new MockSimpleHttpHeaders();
+ $headers->setReturnValue('getResponseCode', 301);
+
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue('getHeaders', $headers);
+
+ $page = new SimplePage($response);
+ $this->assertIdentical($page->getResponseCode(), 301);
+ }
+
+ function testAuthenticationAccessors() {
+ $headers = new MockSimpleHttpHeaders();
+ $headers->setReturnValue('getAuthentication', 'Basic');
+ $headers->setReturnValue('getRealm', 'Secret stuff');
+
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue('getHeaders', $headers);
+
+ $page = new SimplePage($response);
+ $this->assertEqual($page->getAuthentication(), 'Basic');
+ $this->assertEqual($page->getRealm(), 'Secret stuff');
+ }
+}
+
+class TestOfHtmlStrippingAndNormalisation extends UnitTestCase {
+
+ function testImageSuppressionWhileKeepingParagraphsAndAltText() {
+ $this->assertEqual(
+ SimplePage::normalise('<img src="foo.png" /><p>some text</p><img src="bar.png" alt="bar" />'),
+ 'some text bar');
+ }
+
+ function testSpaceNormalisation() {
+ $this->assertEqual(
+ SimplePage::normalise("\nOne\tTwo \nThree\t"),
+ 'One Two Three');
+ }
+
+ function testMultilinesCommentSuppression() {
+ $this->assertEqual(
+ SimplePage::normalise('<!--\n Hello \n-->'),
+ '');
+ }
+
+ function testCommentSuppression() {
+ $this->assertEqual(
+ SimplePage::normalise('<!--Hello-->'),
+ '');
+ }
+
+ function testJavascriptSuppression() {
+ $this->assertEqual(
+ SimplePage::normalise('<script attribute="test">\nHello\n</script>'),
+ '');
+ $this->assertEqual(
+ SimplePage::normalise('<script attribute="test">Hello</script>'),
+ '');
+ $this->assertEqual(
+ SimplePage::normalise('<script>Hello</script>'),
+ '');
+ }
+
+ function testTagSuppression() {
+ $this->assertEqual(
+ SimplePage::normalise('<b>Hello</b>'),
+ 'Hello');
+ }
+
+ function testAdjoiningTagSuppression() {
+ $this->assertEqual(
+ SimplePage::normalise('<b>Hello</b><em>Goodbye</em>'),
+ 'HelloGoodbye');
+ }
+
+ function testExtractImageAltTextWithDifferentQuotes() {
+ $this->assertEqual(
+ SimplePage::normalise('<img alt="One"><img alt=\'Two\'><img alt=Three>'),
+ 'One Two Three');
+ }
+
+ function testExtractImageAltTextMultipleTimes() {
+ $this->assertEqual(
+ SimplePage::normalise('<img alt="One"><img alt="Two"><img alt="Three">'),
+ 'One Two Three');
+ }
+
+ function testHtmlEntityTranslation() {
+ $this->assertEqual(
+ SimplePage::normalise('&lt;&gt;&quot;&amp;&#039;'),
+ '<>"&\'');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/parse_error_test.php b/3rdparty/simpletest/test/parse_error_test.php
new file mode 100755
index 00000000000..c3ffb3d4205
--- /dev/null
+++ b/3rdparty/simpletest/test/parse_error_test.php
@@ -0,0 +1,9 @@
+<?php
+// $Id: parse_error_test.php 1509 2007-05-08 22:11:49Z lastcraft $
+require_once('../unit_tester.php');
+require_once('../reporter.php');
+
+$test = &new TestSuite('This should fail');
+$test->addFile('test_with_parse_error.php');
+$test->run(new HtmlReporter());
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/parsing_test.php b/3rdparty/simpletest/test/parsing_test.php
new file mode 100755
index 00000000000..2c5e6cafe1d
--- /dev/null
+++ b/3rdparty/simpletest/test/parsing_test.php
@@ -0,0 +1,642 @@
+<?php
+// $Id: page_test.php 1912 2009-07-29 16:39:17Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../page.php');
+require_once(dirname(__FILE__) . '/../php_parser.php');
+require_once(dirname(__FILE__) . '/../tidy_parser.php');
+Mock::generate('SimpleHttpResponse');
+
+abstract class TestOfParsing extends UnitTestCase {
+
+ function testRawAccessor() {
+ $page = $this->whenVisiting('http://host/', 'Raw HTML');
+ $this->assertEqual($page->getRaw(), 'Raw HTML');
+ }
+
+ function testTextAccessor() {
+ $page = $this->whenVisiting('http://host/', '<b>Some</b> &quot;messy&quot; HTML');
+ $this->assertEqual($page->getText(), 'Some "messy" HTML');
+ }
+
+ function testFramesetAbsence() {
+ $page = $this->whenVisiting('http://here/', '');
+ $this->assertFalse($page->hasFrames());
+ $this->assertIdentical($page->getFrameset(), false);
+ }
+
+ function testPageWithNoUrlsGivesEmptyArrayOfLinks() {
+ $page = $this->whenVisiting('http://here/', '<html><body><p>Stuff</p></body></html>');
+ $this->assertIdentical($page->getUrls(), array());
+ }
+
+ function testAddAbsoluteLink() {
+ $page = $this->whenVisiting('http://host',
+ '<html><a href="http://somewhere.com">Label</a></html>');
+ $this->assertEqual(
+ $page->getUrlsByLabel('Label'),
+ array(new SimpleUrl('http://somewhere.com')));
+ }
+
+ function testUrlLabelsHaveHtmlTagsStripped() {
+ $page = $this->whenVisiting('http://host',
+ '<html><a href="http://somewhere.com"><b>Label</b></a></html>');
+ $this->assertEqual(
+ $page->getUrlsByLabel('Label'),
+ array(new SimpleUrl('http://somewhere.com')));
+ }
+
+ function testAddStrictRelativeLink() {
+ $page = $this->whenVisiting('http://host',
+ '<html><a href="./somewhere.php">Label</a></html>');
+ $this->assertEqual(
+ $page->getUrlsByLabel('Label'),
+ array(new SimpleUrl('http://host/somewhere.php')));
+ }
+
+ function testAddBareRelativeLink() {
+ $page = $this->whenVisiting('http://host',
+ '<html><a href="somewhere.php">Label</a></html>');
+ $this->assertEqual(
+ $page->getUrlsByLabel('Label'),
+ array(new SimpleUrl('http://host/somewhere.php')));
+ }
+
+ function testAddRelativeLinkWithBaseTag() {
+ $raw = '<html><head><base href="http://www.lastcraft.com/stuff/"></head>' .
+ '<body><a href="somewhere.php">Label</a></body>' .
+ '</html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual(
+ $page->getUrlsByLabel('Label'),
+ array(new SimpleUrl('http://www.lastcraft.com/stuff/somewhere.php')));
+ }
+
+ function testAddAbsoluteLinkWithBaseTag() {
+ $raw = '<html><head><base href="http://www.lastcraft.com/stuff/"></head>' .
+ '<body><a href="http://here.com/somewhere.php">Label</a></body>' .
+ '</html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual(
+ $page->getUrlsByLabel('Label'),
+ array(new SimpleUrl('http://here.com/somewhere.php')));
+ }
+
+ function testCanFindLinkInsideForm() {
+ $raw = '<html><body><form><a href="./somewhere.php">Label</a></form></body></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual(
+ $page->getUrlsByLabel('Label'),
+ array(new SimpleUrl('http://host/somewhere.php')));
+ }
+
+ function testCanGetLinksByIdOrLabel() {
+ $raw = '<html><body><a href="./somewhere.php" id="33">Label</a></body></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual(
+ $page->getUrlsByLabel('Label'),
+ array(new SimpleUrl('http://host/somewhere.php')));
+ $this->assertFalse($page->getUrlById(0));
+ $this->assertEqual(
+ $page->getUrlById(33),
+ new SimpleUrl('http://host/somewhere.php'));
+ }
+
+ function testCanFindLinkByNormalisedLabel() {
+ $raw = '<html><body><a href="./somewhere.php" id="33"><em>Long &amp; thin</em></a></body></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual(
+ $page->getUrlsByLabel('Long & thin'),
+ array(new SimpleUrl('http://host/somewhere.php')));
+ }
+
+ function testCanFindLinkByImageAltText() {
+ $raw = '<a href="./somewhere.php" id="33"><img src="pic.jpg" alt="&lt;A picture&gt;"></a>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual(
+ array_map(array($this, 'urlToString'), $page->getUrlsByLabel('<A picture>')),
+ array('http://host/somewhere.php'));
+ }
+
+ function testTitle() {
+ $page = $this->whenVisiting('http://host',
+ '<html><head><title>Me</title></head></html>');
+ $this->assertEqual($page->getTitle(), 'Me');
+ }
+
+ function testTitleWithEntityReference() {
+ $page = $this->whenVisiting('http://host',
+ '<html><head><Title>Me&amp;Me</TITLE></head></html>');
+ $this->assertEqual($page->getTitle(), "Me&Me");
+ }
+
+ function testOnlyFramesInFramesetAreRecognised() {
+ $raw =
+ '<frameset>' .
+ ' <frame src="2.html"></frame>' .
+ ' <frame src="3.html"></frame>' .
+ '</frameset>' .
+ '<frame src="4.html"></frame>';
+ $page = $this->whenVisiting('http://here', $raw);
+ $this->assertTrue($page->hasFrames());
+ $this->assertSameFrameset($page->getFrameset(), array(
+ 1 => new SimpleUrl('http://here/2.html'),
+ 2 => new SimpleUrl('http://here/3.html')));
+ }
+
+ function testReadsNamesInFrames() {
+ $raw =
+ '<frameset>' .
+ ' <frame src="1.html"></frame>' .
+ ' <frame src="2.html" name="A"></frame>' .
+ ' <frame src="3.html" name="B"></frame>' .
+ ' <frame src="4.html"></frame>' .
+ '</frameset>';
+ $page = $this->whenVisiting('http://here', $raw);
+ $this->assertTrue($page->hasFrames());
+ $this->assertSameFrameset($page->getFrameset(), array(
+ 1 => new SimpleUrl('http://here/1.html'),
+ 'A' => new SimpleUrl('http://here/2.html'),
+ 'B' => new SimpleUrl('http://here/3.html'),
+ 4 => new SimpleUrl('http://here/4.html')));
+ }
+
+ function testRelativeFramesRespectBaseTag() {
+ $raw = '<base href="https://there.com/stuff/"><frameset><frame src="1.html"></frameset>';
+ $page = $this->whenVisiting('http://here', $raw);
+ $this->assertSameFrameset(
+ $page->getFrameset(),
+ array(1 => new SimpleUrl('https://there.com/stuff/1.html')));
+ }
+
+ function testSingleFrameInNestedFrameset() {
+ $raw = '<html><frameset><frameset>' .
+ '<frame src="a.html">' .
+ '</frameset></frameset></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertTrue($page->hasFrames());
+ $this->assertIdentical(
+ $page->getFrameset(),
+ array(1 => new SimpleUrl('http://host/a.html')));
+ }
+
+ function testFramesCollectedWithNestedFramesetTags() {
+ $raw = '<html><frameset>' .
+ '<frame src="a.html">' .
+ '<frameset><frame src="b.html"></frameset>' .
+ '<frame src="c.html">' .
+ '</frameset></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertTrue($page->hasFrames());
+ $this->assertIdentical($page->getFrameset(), array(
+ 1 => new SimpleUrl('http://host/a.html'),
+ 2 => new SimpleUrl('http://host/b.html'),
+ 3 => new SimpleUrl('http://host/c.html')));
+ }
+
+ function testNamedFrames() {
+ $raw = '<html><frameset>' .
+ '<frame src="a.html">' .
+ '<frame name="_one" src="b.html">' .
+ '<frame src="c.html">' .
+ '<frame src="d.html" name="_two">' .
+ '</frameset></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertTrue($page->hasFrames());
+ $this->assertIdentical($page->getFrameset(), array(
+ 1 => new SimpleUrl('http://host/a.html'),
+ '_one' => new SimpleUrl('http://host/b.html'),
+ 3 => new SimpleUrl('http://host/c.html'),
+ '_two' => new SimpleUrl('http://host/d.html')));
+ }
+
+ function testCanReadElementOfCompleteForm() {
+ $raw = '<html><head><form>' .
+ '<input type="text" name="here" value="Hello">' .
+ '</form></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('here')), "Hello");
+ }
+
+ function testCanReadElementOfUnclosedForm() {
+ $raw = '<html><head><form>' .
+ '<input type="text" name="here" value="Hello">' .
+ '</head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('here')), "Hello");
+ }
+
+ function testCanReadElementByLabel() {
+ $raw = '<html><head><form>' .
+ '<label>Where<input type="text" name="here" value="Hello"></label>' .
+ '</head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByLabel('Where')), "Hello");
+ }
+
+ function testCanFindFormByLabel() {
+ $raw = '<html><head><form><input type="submit"></form></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertNull($page->getFormBySubmit(new SimpleByLabel('submit')));
+ $this->assertNull($page->getFormBySubmit(new SimpleByName('submit')));
+ $this->assertIsA(
+ $page->getFormBySubmit(new SimpleByLabel('Submit')),
+ 'SimpleForm');
+ }
+
+ function testConfirmSubmitAttributesAreCaseSensitive() {
+ $raw = '<html><head><FORM><INPUT TYPE="SUBMIT" NAME="S" VALUE="S"></FORM></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertIsA(
+ $page->getFormBySubmit(new SimpleByName('S')),
+ 'SimpleForm');
+ $this->assertIsA(
+ $page->getFormBySubmit(new SimpleByLabel('S')),
+ 'SimpleForm');
+ }
+
+ function testCanFindFormByImage() {
+ $raw = '<html><head><form>' .
+ '<input type="image" id=100 alt="Label" name="me">' .
+ '</form></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertIsA(
+ $page->getFormByImage(new SimpleByLabel('Label')),
+ 'SimpleForm');
+ $this->assertIsA(
+ $page->getFormByImage(new SimpleByName('me')),
+ 'SimpleForm');
+ $this->assertIsA(
+ $page->getFormByImage(new SimpleById(100)),
+ 'SimpleForm');
+ }
+
+ function testCanFindFormByButtonTag() {
+ $raw = '<html><head><form>' .
+ '<button type="submit" name="b" value="B">BBB</button>' .
+ '</form></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertNull($page->getFormBySubmit(new SimpleByLabel('b')));
+ $this->assertNull($page->getFormBySubmit(new SimpleByLabel('B')));
+ $this->assertIsA(
+ $page->getFormBySubmit(new SimpleByName('b')),
+ 'SimpleForm');
+ $this->assertIsA(
+ $page->getFormBySubmit(new SimpleByLabel('BBB')),
+ 'SimpleForm');
+ }
+
+ function testCanFindFormById() {
+ $raw = '<html><head><form id="55"><input type="submit"></form></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertNull($page->getFormById(54));
+ $this->assertIsA($page->getFormById(55), 'SimpleForm');
+ }
+
+ function testFormCanBeSubmitted() {
+ $raw = '<html><head><form method="GET" action="here.php">' .
+ '<input type="submit" name="s" value="Submit">' .
+ '</form></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $form = $page->getFormBySubmit(new SimpleByLabel('Submit'));
+ $this->assertEqual(
+ $form->submitButton(new SimpleByLabel('Submit')),
+ new SimpleGetEncoding(array('s' => 'Submit')));
+ }
+
+ function testUnparsedTagDoesNotCrash() {
+ $raw = '<form><input type="reset" name="Clear"></form>';
+ $this->whenVisiting('http://host', $raw);
+ }
+
+ function testReadingTextField() {
+ $raw = '<html><head><form>' .
+ '<input type="text" name="a">' .
+ '<input type="text" name="b" value="bbb" id=3>' .
+ '</form></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertNull($page->getField(new SimpleByName('missing')));
+ $this->assertIdentical($page->getField(new SimpleByName('a')), '');
+ $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb');
+ }
+
+ function testEntitiesAreDecodedInDefaultTextFieldValue() {
+ $raw = '<form><input type="text" name="a" value="&amp;\'&quot;&lt;&gt;"></form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('a')), '&\'"<>');
+ }
+
+ function testReadingTextFieldIsCaseInsensitive() {
+ $raw = '<html><head><FORM>' .
+ '<INPUT TYPE="TEXT" NAME="a">' .
+ '<INPUT TYPE="TEXT" NAME="b" VALUE="bbb" id=3>' .
+ '</FORM></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertNull($page->getField(new SimpleByName('missing')));
+ $this->assertIdentical($page->getField(new SimpleByName('a')), '');
+ $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb');
+ }
+
+ function testSettingTextField() {
+ $raw = '<html><head><form>' .
+ '<input type="text" name="a">' .
+ '<input type="text" name="b" id=3>' .
+ '<input type="submit">' .
+ '</form></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa'));
+ $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa');
+ $this->assertTrue($page->setField(new SimpleById(3), 'bbb'));
+ $this->assertEqual($page->getField(new SimpleBYId(3)), 'bbb');
+ $this->assertFalse($page->setField(new SimpleByName('z'), 'zzz'));
+ $this->assertNull($page->getField(new SimpleByName('z')));
+ }
+
+ function testSettingTextFieldByEnclosingLabel() {
+ $raw = '<html><head><form>' .
+ '<label>Stuff' .
+ '<input type="text" name="a" value="A">' .
+ '</label>' .
+ '</form></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('a')), 'A');
+ $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A');
+ $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa'));
+ $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa');
+ }
+
+ function testLabelsWithoutForDoNotAttachToInputsWithNoId() {
+ $raw = '<form action="network_confirm.php?x=X&y=Y" method="post">
+ <label>Text A <input type="text" name="a" value="one"></label>
+ <label>Text B <input type="text" name="b" value="two"></label>
+ </form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByLabelOrName('Text A')), 'one');
+ $this->assertEqual($page->getField(new SimpleByLabelOrName('Text B')), 'two');
+ $this->assertTrue($page->setField(new SimpleByLabelOrName('Text A'), '1'));
+ $this->assertTrue($page->setField(new SimpleByLabelOrName('Text B'), '2'));
+ $this->assertEqual($page->getField(new SimpleByLabelOrName('Text A')), '1');
+ $this->assertEqual($page->getField(new SimpleByLabelOrName('Text B')), '2');
+ }
+
+ function testGettingTextFieldByEnclosingLabelWithConflictingOtherFields() {
+ $raw = '<html><head><form>' .
+ '<label>Stuff' .
+ '<input type="text" name="a" value="A">' .
+ '</label>' .
+ '<input type="text" name="b" value="B">' .
+ '</form></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('a')), 'A');
+ $this->assertEqual($page->getField(new SimpleByName('b')), 'B');
+ $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A');
+ }
+
+ function testSettingTextFieldByExternalLabel() {
+ $raw = '<html><head><form>' .
+ '<label for="aaa">Stuff</label>' .
+ '<input id="aaa" type="text" name="a" value="A">' .
+ '</form></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A');
+ $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa'));
+ $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa');
+ }
+
+ function testReadingTextArea() {
+ $raw = '<html><head><form>' .
+ '<textarea name="a">aaa</textarea>' .
+ '<input type="submit">' .
+ '</form></head></html>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa');
+ }
+
+ function testEntitiesAreDecodedInTextareaValue() {
+ $raw = '<form><textarea name="a">&amp;\'&quot;&lt;&gt;</textarea></form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('a')), '&\'"<>');
+ }
+
+ function testNewlinesPreservedInTextArea() {
+ $raw = "<form><textarea name=\"a\">hello\r\nworld</textarea></form>";
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('a')), "hello\r\nworld");
+ }
+
+ function testWhitespacePreservedInTextArea() {
+ $raw = '<form><textarea name="a"> </textarea></form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('a')), ' ');
+ }
+
+ function testComplexWhitespaceInTextArea() {
+ $raw = "<html>\n" .
+ " <head><title></title></head>\n" .
+ " <body>\n" .
+ " <form>\n".
+ " <label>Text area C\n" .
+ " <textarea name='c'>\n" .
+ " </textarea>\n" .
+ " </label>\n" .
+ " </form>\n" .
+ " </body>\n" .
+ "</html>";
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('c')), " ");
+ }
+
+ function testSettingTextArea() {
+ $raw = '<form>' .
+ '<textarea name="a">aaa</textarea>' .
+ '<input type="submit">' .
+ '</form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertTrue($page->setField(new SimpleByName('a'), 'AAA'));
+ $this->assertEqual($page->getField(new SimpleByName('a')), 'AAA');
+ }
+
+ function testDontIncludeTextAreaContentInLabel() {
+ $raw = '<form><label>Text area C<textarea id=3 name="c">mouse</textarea></label></form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByLabel('Text area C')), 'mouse');
+ }
+
+ function testSettingSelectionField() {
+ $raw = '<form>' .
+ '<select name="a">' .
+ '<option>aaa</option>' .
+ '<option selected>bbb</option>' .
+ '</select>' .
+ '<input type="submit">' .
+ '</form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('a')), 'bbb');
+ $this->assertFalse($page->setField(new SimpleByName('a'), 'ccc'));
+ $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa'));
+ $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa');
+ }
+
+ function testSelectionOptionsAreNormalised() {
+ $raw = '<form>' .
+ '<select name="a">' .
+ '<option selected><b>Big</b> bold</option>' .
+ '<option>small <em>italic</em></option>' .
+ '</select>' .
+ '</form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('a')), 'Big bold');
+ $this->assertTrue($page->setField(new SimpleByName('a'), 'small italic'));
+ $this->assertEqual($page->getField(new SimpleByName('a')), 'small italic');
+ }
+
+ function testCanParseBlankOptions() {
+ $raw = '<form>
+ <select id=4 name="d">
+ <option value="d1">D1</option>
+ <option value="d2">D2</option>
+ <option></option>
+ </select>
+ </form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertTrue($page->setField(new SimpleByName('d'), ''));
+ }
+
+ function testTwoSelectionFieldsAreIndependent() {
+ $raw = '<form>
+ <select id=4 name="d">
+ <option value="d1" selected>D1</option>
+ <option value="d2">D2</option>
+ </select>
+ <select id=11 name="h">
+ <option value="h1">H1</option>
+ <option value="h2" selected>H2</option>
+ </select>
+ </form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertTrue($page->setField(new SimpleByName('d'), 'd2'));
+ $this->assertTrue($page->setField(new SimpleByName('h'), 'h1'));
+ $this->assertEqual($page->getField(new SimpleByName('d')), 'd2');
+ }
+
+ function testEmptyOptionDoesNotScrewUpTwoSelectionFields() {
+ $raw = '<form>
+ <select name="d">
+ <option value="d1" selected>D1</option>
+ <option value="d2">D2</option>
+ <option></option>
+ </select>
+ <select name="h">
+ <option value="h1">H1</option>
+ <option value="h2" selected>H2</option>
+ </select>
+ </form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertTrue($page->setField(new SimpleByName('d'), 'd2'));
+ $this->assertTrue($page->setField(new SimpleByName('h'), 'h1'));
+ $this->assertEqual($page->getField(new SimpleByName('d')), 'd2');
+ }
+
+ function testSettingSelectionFieldByEnclosingLabel() {
+ $raw = '<form>' .
+ '<label>Stuff' .
+ '<select name="a"><option selected>A</option><option>B</option></select>' .
+ '</label>' .
+ '</form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A');
+ $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'B'));
+ $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'B');
+ }
+
+ function testTwoSelectionFieldsWithLabelsAreIndependent() {
+ $raw = '<form>
+ <label>Labelled D
+ <select id=4 name="d">
+ <option value="d1" selected>D1</option>
+ <option value="d2">D2</option>
+ </select>
+ </label>
+ <label>Labelled H
+ <select id=11 name="h">
+ <option value="h1">H1</option>
+ <option value="h2" selected>H2</option>
+ </select>
+ </label>
+ </form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertTrue($page->setField(new SimpleByLabel('Labelled D'), 'd2'));
+ $this->assertTrue($page->setField(new SimpleByLabel('Labelled H'), 'h1'));
+ $this->assertEqual($page->getField(new SimpleByLabel('Labelled D')), 'd2');
+ }
+
+ function testSettingRadioButtonByEnclosingLabel() {
+ $raw = '<form>' .
+ '<label>A<input type="radio" name="r" value="a" checked></label>' .
+ '<label>B<input type="radio" name="r" value="b"></label>' .
+ '</form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByLabel('A')), 'a');
+ $this->assertTrue($page->setField(new SimpleBylabel('B'), 'b'));
+ $this->assertEqual($page->getField(new SimpleByLabel('B')), 'b');
+ }
+
+ function testCanParseInputsWithAllKindsOfAttributeQuoting() {
+ $raw = '<form>' .
+ '<input type="checkbox" name=\'first\' value=one checked></input>' .
+ '<input type=checkbox name="second" value="two"></input>' .
+ '<input type=checkbox name="third" value=\'three\' checked="checked" />' .
+ '</form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByName('first')), 'one');
+ $this->assertEqual($page->getField(new SimpleByName('second')), false);
+ $this->assertEqual($page->getField(new SimpleByName('third')), 'three');
+ }
+
+ function urlToString($url) {
+ return $url->asString();
+ }
+
+ function assertSameFrameset($actual, $expected) {
+ $this->assertIdentical(array_map(array($this, 'urlToString'), $actual),
+ array_map(array($this, 'urlToString'), $expected));
+ }
+}
+
+class TestOfParsingUsingPhpParser extends TestOfParsing {
+
+ function whenVisiting($url, $content) {
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue('getContent', $content);
+ $response->setReturnValue('getUrl', new SimpleUrl($url));
+ $builder = new SimplePhpPageBuilder();
+ return $builder->parse($response);
+ }
+
+ function testNastyTitle() {
+ $page = $this->whenVisiting('http://host',
+ '<html><head><Title> <b>Me&amp;Me </TITLE></b></head></html>');
+ $this->assertEqual($page->getTitle(), "Me&Me");
+ }
+
+ function testLabelShouldStopAtClosingLabelTag() {
+ $raw = '<form><label>start<textarea id=3 name="c" wrap="hard">stuff</textarea>end</label>stuff</form>';
+ $page = $this->whenVisiting('http://host', $raw);
+ $this->assertEqual($page->getField(new SimpleByLabel('startend')), 'stuff');
+ }
+}
+
+class TestOfParsingUsingTidyParser extends TestOfParsing {
+
+ function skip() {
+ $this->skipUnless(extension_loaded('tidy'), 'Install \'tidy\' php extension to enable html tidy based parser');
+ }
+
+ function whenVisiting($url, $content) {
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue('getContent', $content);
+ $response->setReturnValue('getUrl', new SimpleUrl($url));
+ $builder = new SimpleTidyPageBuilder();
+ return $builder->parse($response);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/php_parser_test.php b/3rdparty/simpletest/test/php_parser_test.php
new file mode 100755
index 00000000000..d95c7d06a60
--- /dev/null
+++ b/3rdparty/simpletest/test/php_parser_test.php
@@ -0,0 +1,489 @@
+<?php
+// $Id: php_parser_test.php 1911 2009-07-29 16:38:04Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../php_parser.php');
+require_once(dirname(__FILE__) . '/../tag.php');
+Mock::generate('SimplePage');
+Mock::generate('SimplePhpPageBuilder');
+Mock::generate('SimpleHttpResponse');
+Mock::generatePartial(
+ 'SimplePhpPageBuilder',
+ 'PartialSimplePhpPageBuilder',
+ array('createPage', 'createParser'));
+Mock::generate('SimpleHtmlSaxParser');
+Mock::generate('SimplePhpPageBuilder');
+
+class TestOfParallelRegex extends UnitTestCase {
+
+ function testNoPatterns() {
+ $regex = new ParallelRegex(false);
+ $this->assertFalse($regex->match("Hello", $match));
+ $this->assertEqual($match, "");
+ }
+
+ function testNoSubject() {
+ $regex = new ParallelRegex(false);
+ $regex->addPattern(".*");
+ $this->assertTrue($regex->match("", $match));
+ $this->assertEqual($match, "");
+ }
+
+ function testMatchAll() {
+ $regex = new ParallelRegex(false);
+ $regex->addPattern(".*");
+ $this->assertTrue($regex->match("Hello", $match));
+ $this->assertEqual($match, "Hello");
+ }
+
+ function testCaseSensitive() {
+ $regex = new ParallelRegex(true);
+ $regex->addPattern("abc");
+ $this->assertTrue($regex->match("abcdef", $match));
+ $this->assertEqual($match, "abc");
+ $this->assertTrue($regex->match("AAABCabcdef", $match));
+ $this->assertEqual($match, "abc");
+ }
+
+ function testCaseInsensitive() {
+ $regex = new ParallelRegex(false);
+ $regex->addPattern("abc");
+ $this->assertTrue($regex->match("abcdef", $match));
+ $this->assertEqual($match, "abc");
+ $this->assertTrue($regex->match("AAABCabcdef", $match));
+ $this->assertEqual($match, "ABC");
+ }
+
+ function testMatchMultiple() {
+ $regex = new ParallelRegex(true);
+ $regex->addPattern("abc");
+ $regex->addPattern("ABC");
+ $this->assertTrue($regex->match("abcdef", $match));
+ $this->assertEqual($match, "abc");
+ $this->assertTrue($regex->match("AAABCabcdef", $match));
+ $this->assertEqual($match, "ABC");
+ $this->assertFalse($regex->match("Hello", $match));
+ }
+
+ function testPatternLabels() {
+ $regex = new ParallelRegex(false);
+ $regex->addPattern("abc", "letter");
+ $regex->addPattern("123", "number");
+ $this->assertIdentical($regex->match("abcdef", $match), "letter");
+ $this->assertEqual($match, "abc");
+ $this->assertIdentical($regex->match("0123456789", $match), "number");
+ $this->assertEqual($match, "123");
+ }
+}
+
+class TestOfStateStack extends UnitTestCase {
+
+ function testStartState() {
+ $stack = new SimpleStateStack("one");
+ $this->assertEqual($stack->getCurrent(), "one");
+ }
+
+ function testExhaustion() {
+ $stack = new SimpleStateStack("one");
+ $this->assertFalse($stack->leave());
+ }
+
+ function testStateMoves() {
+ $stack = new SimpleStateStack("one");
+ $stack->enter("two");
+ $this->assertEqual($stack->getCurrent(), "two");
+ $stack->enter("three");
+ $this->assertEqual($stack->getCurrent(), "three");
+ $this->assertTrue($stack->leave());
+ $this->assertEqual($stack->getCurrent(), "two");
+ $stack->enter("third");
+ $this->assertEqual($stack->getCurrent(), "third");
+ $this->assertTrue($stack->leave());
+ $this->assertTrue($stack->leave());
+ $this->assertEqual($stack->getCurrent(), "one");
+ }
+}
+
+class TestParser {
+
+ function accept() {
+ }
+
+ function a() {
+ }
+
+ function b() {
+ }
+}
+Mock::generate('TestParser');
+
+class TestOfLexer extends UnitTestCase {
+
+ function testEmptyPage() {
+ $handler = new MockTestParser();
+ $handler->expectNever("accept");
+ $handler->setReturnValue("accept", true);
+ $handler->expectNever("accept");
+ $handler->setReturnValue("accept", true);
+ $lexer = new SimpleLexer($handler);
+ $lexer->addPattern("a+");
+ $this->assertTrue($lexer->parse(""));
+ }
+
+ function testSinglePattern() {
+ $handler = new MockTestParser();
+ $handler->expectAt(0, "accept", array("aaa", LEXER_MATCHED));
+ $handler->expectAt(1, "accept", array("x", LEXER_UNMATCHED));
+ $handler->expectAt(2, "accept", array("a", LEXER_MATCHED));
+ $handler->expectAt(3, "accept", array("yyy", LEXER_UNMATCHED));
+ $handler->expectAt(4, "accept", array("a", LEXER_MATCHED));
+ $handler->expectAt(5, "accept", array("x", LEXER_UNMATCHED));
+ $handler->expectAt(6, "accept", array("aaa", LEXER_MATCHED));
+ $handler->expectAt(7, "accept", array("z", LEXER_UNMATCHED));
+ $handler->expectCallCount("accept", 8);
+ $handler->setReturnValue("accept", true);
+ $lexer = new SimpleLexer($handler);
+ $lexer->addPattern("a+");
+ $this->assertTrue($lexer->parse("aaaxayyyaxaaaz"));
+ }
+
+ function testMultiplePattern() {
+ $handler = new MockTestParser();
+ $target = array("a", "b", "a", "bb", "x", "b", "a", "xxxxxx", "a", "x");
+ for ($i = 0; $i < count($target); $i++) {
+ $handler->expectAt($i, "accept", array($target[$i], '*'));
+ }
+ $handler->expectCallCount("accept", count($target));
+ $handler->setReturnValue("accept", true);
+ $lexer = new SimpleLexer($handler);
+ $lexer->addPattern("a+");
+ $lexer->addPattern("b+");
+ $this->assertTrue($lexer->parse("ababbxbaxxxxxxax"));
+ }
+}
+
+class TestOfLexerModes extends UnitTestCase {
+
+ function testIsolatedPattern() {
+ $handler = new MockTestParser();
+ $handler->expectAt(0, "a", array("a", LEXER_MATCHED));
+ $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED));
+ $handler->expectAt(2, "a", array("aa", LEXER_MATCHED));
+ $handler->expectAt(3, "a", array("bxb", LEXER_UNMATCHED));
+ $handler->expectAt(4, "a", array("aaa", LEXER_MATCHED));
+ $handler->expectAt(5, "a", array("x", LEXER_UNMATCHED));
+ $handler->expectAt(6, "a", array("aaaa", LEXER_MATCHED));
+ $handler->expectAt(7, "a", array("x", LEXER_UNMATCHED));
+ $handler->expectCallCount("a", 8);
+ $handler->setReturnValue("a", true);
+ $lexer = new SimpleLexer($handler, "a");
+ $lexer->addPattern("a+", "a");
+ $lexer->addPattern("b+", "b");
+ $this->assertTrue($lexer->parse("abaabxbaaaxaaaax"));
+ }
+
+ function testModeChange() {
+ $handler = new MockTestParser();
+ $handler->expectAt(0, "a", array("a", LEXER_MATCHED));
+ $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED));
+ $handler->expectAt(2, "a", array("aa", LEXER_MATCHED));
+ $handler->expectAt(3, "a", array("b", LEXER_UNMATCHED));
+ $handler->expectAt(4, "a", array("aaa", LEXER_MATCHED));
+ $handler->expectAt(0, "b", array(":", LEXER_ENTER));
+ $handler->expectAt(1, "b", array("a", LEXER_UNMATCHED));
+ $handler->expectAt(2, "b", array("b", LEXER_MATCHED));
+ $handler->expectAt(3, "b", array("a", LEXER_UNMATCHED));
+ $handler->expectAt(4, "b", array("bb", LEXER_MATCHED));
+ $handler->expectAt(5, "b", array("a", LEXER_UNMATCHED));
+ $handler->expectAt(6, "b", array("bbb", LEXER_MATCHED));
+ $handler->expectAt(7, "b", array("a", LEXER_UNMATCHED));
+ $handler->expectCallCount("a", 5);
+ $handler->expectCallCount("b", 8);
+ $handler->setReturnValue("a", true);
+ $handler->setReturnValue("b", true);
+ $lexer = new SimpleLexer($handler, "a");
+ $lexer->addPattern("a+", "a");
+ $lexer->addEntryPattern(":", "a", "b");
+ $lexer->addPattern("b+", "b");
+ $this->assertTrue($lexer->parse("abaabaaa:ababbabbba"));
+ }
+
+ function testNesting() {
+ $handler = new MockTestParser();
+ $handler->setReturnValue("a", true);
+ $handler->setReturnValue("b", true);
+ $handler->expectAt(0, "a", array("aa", LEXER_MATCHED));
+ $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED));
+ $handler->expectAt(2, "a", array("aa", LEXER_MATCHED));
+ $handler->expectAt(3, "a", array("b", LEXER_UNMATCHED));
+ $handler->expectAt(0, "b", array("(", LEXER_ENTER));
+ $handler->expectAt(1, "b", array("bb", LEXER_MATCHED));
+ $handler->expectAt(2, "b", array("a", LEXER_UNMATCHED));
+ $handler->expectAt(3, "b", array("bb", LEXER_MATCHED));
+ $handler->expectAt(4, "b", array(")", LEXER_EXIT));
+ $handler->expectAt(4, "a", array("aa", LEXER_MATCHED));
+ $handler->expectAt(5, "a", array("b", LEXER_UNMATCHED));
+ $handler->expectCallCount("a", 6);
+ $handler->expectCallCount("b", 5);
+ $lexer = new SimpleLexer($handler, "a");
+ $lexer->addPattern("a+", "a");
+ $lexer->addEntryPattern("(", "a", "b");
+ $lexer->addPattern("b+", "b");
+ $lexer->addExitPattern(")", "b");
+ $this->assertTrue($lexer->parse("aabaab(bbabb)aab"));
+ }
+
+ function testSingular() {
+ $handler = new MockTestParser();
+ $handler->setReturnValue("a", true);
+ $handler->setReturnValue("b", true);
+ $handler->expectAt(0, "a", array("aa", LEXER_MATCHED));
+ $handler->expectAt(1, "a", array("aa", LEXER_MATCHED));
+ $handler->expectAt(2, "a", array("xx", LEXER_UNMATCHED));
+ $handler->expectAt(3, "a", array("xx", LEXER_UNMATCHED));
+ $handler->expectAt(0, "b", array("b", LEXER_SPECIAL));
+ $handler->expectAt(1, "b", array("bbb", LEXER_SPECIAL));
+ $handler->expectCallCount("a", 4);
+ $handler->expectCallCount("b", 2);
+ $lexer = new SimpleLexer($handler, "a");
+ $lexer->addPattern("a+", "a");
+ $lexer->addSpecialPattern("b+", "a", "b");
+ $this->assertTrue($lexer->parse("aabaaxxbbbxx"));
+ }
+
+ function testUnwindTooFar() {
+ $handler = new MockTestParser();
+ $handler->setReturnValue("a", true);
+ $handler->expectAt(0, "a", array("aa", LEXER_MATCHED));
+ $handler->expectAt(1, "a", array(")", LEXER_EXIT));
+ $handler->expectCallCount("a", 2);
+ $lexer = new SimpleLexer($handler, "a");
+ $lexer->addPattern("a+", "a");
+ $lexer->addExitPattern(")", "a");
+ $this->assertFalse($lexer->parse("aa)aa"));
+ }
+}
+
+class TestOfLexerHandlers extends UnitTestCase {
+
+ function testModeMapping() {
+ $handler = new MockTestParser();
+ $handler->setReturnValue("a", true);
+ $handler->expectAt(0, "a", array("aa", LEXER_MATCHED));
+ $handler->expectAt(1, "a", array("(", LEXER_ENTER));
+ $handler->expectAt(2, "a", array("bb", LEXER_MATCHED));
+ $handler->expectAt(3, "a", array("a", LEXER_UNMATCHED));
+ $handler->expectAt(4, "a", array("bb", LEXER_MATCHED));
+ $handler->expectAt(5, "a", array(")", LEXER_EXIT));
+ $handler->expectAt(6, "a", array("b", LEXER_UNMATCHED));
+ $handler->expectCallCount("a", 7);
+ $lexer = new SimpleLexer($handler, "mode_a");
+ $lexer->addPattern("a+", "mode_a");
+ $lexer->addEntryPattern("(", "mode_a", "mode_b");
+ $lexer->addPattern("b+", "mode_b");
+ $lexer->addExitPattern(")", "mode_b");
+ $lexer->mapHandler("mode_a", "a");
+ $lexer->mapHandler("mode_b", "a");
+ $this->assertTrue($lexer->parse("aa(bbabb)b"));
+ }
+}
+
+class TestOfSimpleHtmlLexer extends UnitTestCase {
+
+ function &createParser() {
+ $parser = new MockSimpleHtmlSaxParser();
+ $parser->setReturnValue('acceptStartToken', true);
+ $parser->setReturnValue('acceptEndToken', true);
+ $parser->setReturnValue('acceptAttributeToken', true);
+ $parser->setReturnValue('acceptEntityToken', true);
+ $parser->setReturnValue('acceptTextToken', true);
+ $parser->setReturnValue('ignore', true);
+ return $parser;
+ }
+
+ function testNoContent() {
+ $parser = $this->createParser();
+ $parser->expectNever('acceptStartToken');
+ $parser->expectNever('acceptEndToken');
+ $parser->expectNever('acceptAttributeToken');
+ $parser->expectNever('acceptEntityToken');
+ $parser->expectNever('acceptTextToken');
+ $lexer = new SimpleHtmlLexer($parser);
+ $this->assertTrue($lexer->parse(''));
+ }
+
+ function testUninteresting() {
+ $parser = $this->createParser();
+ $parser->expectOnce('acceptTextToken', array('<html></html>', '*'));
+ $lexer = new SimpleHtmlLexer($parser);
+ $this->assertTrue($lexer->parse('<html></html>'));
+ }
+
+ function testSkipCss() {
+ $parser = $this->createParser();
+ $parser->expectNever('acceptTextToken');
+ $parser->expectAtLeastOnce('ignore');
+ $lexer = new SimpleHtmlLexer($parser);
+ $this->assertTrue($lexer->parse("<style>Lot's of styles</style>"));
+ }
+
+ function testSkipJavaScript() {
+ $parser = $this->createParser();
+ $parser->expectNever('acceptTextToken');
+ $parser->expectAtLeastOnce('ignore');
+ $lexer = new SimpleHtmlLexer($parser);
+ $this->assertTrue($lexer->parse("<SCRIPT>Javascript code {';:^%^%£$'@\"*(}</SCRIPT>"));
+ }
+
+ function testSkipHtmlComments() {
+ $parser = $this->createParser();
+ $parser->expectNever('acceptTextToken');
+ $parser->expectAtLeastOnce('ignore');
+ $lexer = new SimpleHtmlLexer($parser);
+ $this->assertTrue($lexer->parse("<!-- <title>title</title><style>styles</style> -->"));
+ }
+
+ function testTagWithNoAttributes() {
+ $parser = $this->createParser();
+ $parser->expectAt(0, 'acceptStartToken', array('<title', '*'));
+ $parser->expectAt(1, 'acceptStartToken', array('>', '*'));
+ $parser->expectCallCount('acceptStartToken', 2);
+ $parser->expectOnce('acceptTextToken', array('Hello', '*'));
+ $parser->expectOnce('acceptEndToken', array('</title>', '*'));
+ $lexer = new SimpleHtmlLexer($parser);
+ $this->assertTrue($lexer->parse('<title>Hello</title>'));
+ }
+
+ function testTagWithAttributes() {
+ $parser = $this->createParser();
+ $parser->expectOnce('acceptTextToken', array('label', '*'));
+ $parser->expectAt(0, 'acceptStartToken', array('<a', '*'));
+ $parser->expectAt(1, 'acceptStartToken', array('href', '*'));
+ $parser->expectAt(2, 'acceptStartToken', array('>', '*'));
+ $parser->expectCallCount('acceptStartToken', 3);
+ $parser->expectAt(0, 'acceptAttributeToken', array('= "', '*'));
+ $parser->expectAt(1, 'acceptAttributeToken', array('here.html', '*'));
+ $parser->expectAt(2, 'acceptAttributeToken', array('"', '*'));
+ $parser->expectCallCount('acceptAttributeToken', 3);
+ $parser->expectOnce('acceptEndToken', array('</a>', '*'));
+ $lexer = new SimpleHtmlLexer($parser);
+ $this->assertTrue($lexer->parse('<a href = "here.html">label</a>'));
+ }
+}
+
+class TestOfHtmlSaxParser extends UnitTestCase {
+
+ function createListener() {
+ $listener = new MockSimplePhpPageBuilder();
+ $listener->setReturnValue('startElement', true);
+ $listener->setReturnValue('addContent', true);
+ $listener->setReturnValue('endElement', true);
+ return $listener;
+ }
+
+ function testFramesetTag() {
+ $listener = $this->createListener();
+ $listener->expectOnce('startElement', array('frameset', array()));
+ $listener->expectOnce('addContent', array('Frames'));
+ $listener->expectOnce('endElement', array('frameset'));
+ $parser = new SimpleHtmlSaxParser($listener);
+ $this->assertTrue($parser->parse('<frameset>Frames</frameset>'));
+ }
+
+ function testTagWithUnquotedAttributes() {
+ $listener = $this->createListener();
+ $listener->expectOnce(
+ 'startElement',
+ array('input', array('name' => 'a.b.c', 'value' => 'd')));
+ $parser = new SimpleHtmlSaxParser($listener);
+ $this->assertTrue($parser->parse('<input name=a.b.c value = d>'));
+ }
+
+ function testTagInsideContent() {
+ $listener = $this->createListener();
+ $listener->expectOnce('startElement', array('a', array()));
+ $listener->expectAt(0, 'addContent', array('<html>'));
+ $listener->expectAt(1, 'addContent', array('</html>'));
+ $parser = new SimpleHtmlSaxParser($listener);
+ $this->assertTrue($parser->parse('<html><a></a></html>'));
+ }
+
+ function testTagWithInternalContent() {
+ $listener = $this->createListener();
+ $listener->expectOnce('startElement', array('a', array()));
+ $listener->expectOnce('addContent', array('label'));
+ $listener->expectOnce('endElement', array('a'));
+ $parser = new SimpleHtmlSaxParser($listener);
+ $this->assertTrue($parser->parse('<a>label</a>'));
+ }
+
+ function testLinkAddress() {
+ $listener = $this->createListener();
+ $listener->expectOnce('startElement', array('a', array('href' => 'here.html')));
+ $listener->expectOnce('addContent', array('label'));
+ $listener->expectOnce('endElement', array('a'));
+ $parser = new SimpleHtmlSaxParser($listener);
+ $this->assertTrue($parser->parse("<a href = 'here.html'>label</a>"));
+ }
+
+ function testEncodedAttribute() {
+ $listener = $this->createListener();
+ $listener->expectOnce('startElement', array('a', array('href' => 'here&there.html')));
+ $listener->expectOnce('addContent', array('label'));
+ $listener->expectOnce('endElement', array('a'));
+ $parser = new SimpleHtmlSaxParser($listener);
+ $this->assertTrue($parser->parse("<a href = 'here&amp;there.html'>label</a>"));
+ }
+
+ function testTagWithId() {
+ $listener = $this->createListener();
+ $listener->expectOnce('startElement', array('a', array('id' => '0')));
+ $listener->expectOnce('addContent', array('label'));
+ $listener->expectOnce('endElement', array('a'));
+ $parser = new SimpleHtmlSaxParser($listener);
+ $this->assertTrue($parser->parse('<a id="0">label</a>'));
+ }
+
+ function testTagWithEmptyAttributes() {
+ $listener = $this->createListener();
+ $listener->expectOnce(
+ 'startElement',
+ array('option', array('value' => '', 'selected' => '')));
+ $listener->expectOnce('addContent', array('label'));
+ $listener->expectOnce('endElement', array('option'));
+ $parser = new SimpleHtmlSaxParser($listener);
+ $this->assertTrue($parser->parse('<option value="" selected>label</option>'));
+ }
+
+ function testComplexTagWithLotsOfCaseVariations() {
+ $listener = $this->createListener();
+ $listener->expectOnce(
+ 'startElement',
+ array('a', array('href' => 'here.html', 'style' => "'cool'")));
+ $listener->expectOnce('addContent', array('label'));
+ $listener->expectOnce('endElement', array('a'));
+ $parser = new SimpleHtmlSaxParser($listener);
+ $this->assertTrue($parser->parse('<A HREF = \'here.html\' Style="\'cool\'">label</A>'));
+ }
+
+ function testXhtmlSelfClosingTag() {
+ $listener = $this->createListener();
+ $listener->expectOnce(
+ 'startElement',
+ array('input', array('type' => 'submit', 'name' => 'N', 'value' => 'V')));
+ $parser = new SimpleHtmlSaxParser($listener);
+ $this->assertTrue($parser->parse('<input type="submit" name="N" value="V" />'));
+ }
+
+ function testNestedFrameInFrameset() {
+ $listener = $this->createListener();
+ $listener->expectAt(0, 'startElement', array('frameset', array()));
+ $listener->expectAt(1, 'startElement', array('frame', array('src' => 'frame.html')));
+ $listener->expectCallCount('startElement', 2);
+ $listener->expectOnce('addContent', array('<noframes>Hello</noframes>'));
+ $listener->expectOnce('endElement', array('frameset'));
+ $parser = new SimpleHtmlSaxParser($listener);
+ $this->assertTrue($parser->parse(
+ '<frameset><frame src="frame.html"><noframes>Hello</noframes></frameset>'));
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/recorder_test.php b/3rdparty/simpletest/test/recorder_test.php
new file mode 100755
index 00000000000..fdae4c1cccc
--- /dev/null
+++ b/3rdparty/simpletest/test/recorder_test.php
@@ -0,0 +1,23 @@
+<?php
+// $Id: test.php 1500 2007-04-29 14:33:31Z pp11 $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../recorder.php');
+
+class TestOfRecorder extends UnitTestCase {
+
+ function testContentOfRecorderWithOnePassAndOneFailure() {
+ $test = new TestSuite();
+ $test->addFile(dirname(__FILE__) . '/support/recorder_sample.php');
+ $recorder = new Recorder(new SimpleReporter());
+ $test->run($recorder);
+ $this->assertEqual(count($recorder->results), 2);
+ $this->assertIsA($recorder->results[0], 'SimpleResultOfPass');
+ $this->assertEqual('testTrueIsTrue', array_pop($recorder->results[0]->breadcrumb));
+ $this->assertPattern('/ at \[.*\Wrecorder_sample\.php line 7\]/', $recorder->results[0]->message);
+ $this->assertIsA($recorder->results[1], 'SimpleResultOfFail');
+ $this->assertEqual('testFalseIsTrue', array_pop($recorder->results[1]->breadcrumb));
+ $this->assertPattern("/Expected false, got \[Boolean: true\] at \[.*\Wrecorder_sample\.php line 11\]/",
+ $recorder->results[1]->message);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/reflection_php5_test.php b/3rdparty/simpletest/test/reflection_php5_test.php
new file mode 100755
index 00000000000..d9f46e6db78
--- /dev/null
+++ b/3rdparty/simpletest/test/reflection_php5_test.php
@@ -0,0 +1,263 @@
+<?php
+// $Id: reflection_php5_test.php 1778 2008-04-21 16:13:08Z edwardzyang $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../reflection_php5.php');
+
+class AnyOldLeafClass {
+ function aMethod() { }
+}
+
+abstract class AnyOldClass {
+ function aMethod() { }
+}
+
+class AnyOldLeafClassWithAFinal {
+ final function aMethod() { }
+}
+
+interface AnyOldInterface {
+ function aMethod();
+}
+
+interface AnyOldArgumentInterface {
+ function aMethod(AnyOldInterface $argument);
+}
+
+interface AnyDescendentInterface extends AnyOldInterface {
+}
+
+class AnyOldImplementation implements AnyOldInterface {
+ function aMethod() { }
+ function extraMethod() { }
+}
+
+abstract class AnyAbstractImplementation implements AnyOldInterface {
+}
+
+abstract class AnotherOldAbstractClass {
+ protected abstract function aMethod(AnyOldInterface $argument);
+}
+
+class AnyOldSubclass extends AnyOldImplementation { }
+
+class AnyOldArgumentClass {
+ function aMethod($argument) { }
+}
+
+class AnyOldArgumentImplementation implements AnyOldArgumentInterface {
+ function aMethod(AnyOldInterface $argument) { }
+}
+
+class AnyOldTypeHintedClass implements AnyOldArgumentInterface {
+ function aMethod(AnyOldInterface $argument) { }
+}
+
+class AnyDescendentImplementation implements AnyDescendentInterface {
+ function aMethod() { }
+}
+
+class AnyOldOverloadedClass {
+ function __isset($key) { }
+ function __unset($key) { }
+}
+
+class AnyOldClassWithStaticMethods {
+ static function aStatic() { }
+ static function aStaticWithParameters($arg1, $arg2) { }
+}
+
+abstract class AnyOldAbstractClassWithAbstractMethods {
+ abstract function anAbstract();
+ abstract function anAbstractWithParameter($foo);
+ abstract function anAbstractWithMultipleParameters($foo, $bar);
+}
+
+class TestOfReflection extends UnitTestCase {
+
+ function testClassExistence() {
+ $reflection = new SimpleReflection('AnyOldLeafClass');
+ $this->assertTrue($reflection->classOrInterfaceExists());
+ $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload());
+ $this->assertFalse($reflection->isAbstract());
+ $this->assertFalse($reflection->isInterface());
+ }
+
+ function testClassNonExistence() {
+ $reflection = new SimpleReflection('UnknownThing');
+ $this->assertFalse($reflection->classOrInterfaceExists());
+ $this->assertFalse($reflection->classOrInterfaceExistsSansAutoload());
+ }
+
+ function testDetectionOfAbstractClass() {
+ $reflection = new SimpleReflection('AnyOldClass');
+ $this->assertTrue($reflection->isAbstract());
+ }
+
+ function testDetectionOfFinalMethods() {
+ $reflection = new SimpleReflection('AnyOldClass');
+ $this->assertFalse($reflection->hasFinal());
+ $reflection = new SimpleReflection('AnyOldLeafClassWithAFinal');
+ $this->assertTrue($reflection->hasFinal());
+ }
+
+ function testFindingParentClass() {
+ $reflection = new SimpleReflection('AnyOldSubclass');
+ $this->assertEqual($reflection->getParent(), 'AnyOldImplementation');
+ }
+
+ function testInterfaceExistence() {
+ $reflection = new SimpleReflection('AnyOldInterface');
+ $this->assertTrue($reflection->classOrInterfaceExists());
+ $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload());
+ $this->assertTrue($reflection->isInterface());
+ }
+
+ function testMethodsListFromClass() {
+ $reflection = new SimpleReflection('AnyOldClass');
+ $this->assertIdentical($reflection->getMethods(), array('aMethod'));
+ }
+
+ function testMethodsListFromInterface() {
+ $reflection = new SimpleReflection('AnyOldInterface');
+ $this->assertIdentical($reflection->getMethods(), array('aMethod'));
+ $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod'));
+ }
+
+ function testMethodsComeFromDescendentInterfacesASWell() {
+ $reflection = new SimpleReflection('AnyDescendentInterface');
+ $this->assertIdentical($reflection->getMethods(), array('aMethod'));
+ }
+
+ function testCanSeparateInterfaceMethodsFromOthers() {
+ $reflection = new SimpleReflection('AnyOldImplementation');
+ $this->assertIdentical($reflection->getMethods(), array('aMethod', 'extraMethod'));
+ $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod'));
+ }
+
+ function testMethodsComeFromDescendentInterfacesInAbstractClass() {
+ $reflection = new SimpleReflection('AnyAbstractImplementation');
+ $this->assertIdentical($reflection->getMethods(), array('aMethod'));
+ }
+
+ function testInterfaceHasOnlyItselfToImplement() {
+ $reflection = new SimpleReflection('AnyOldInterface');
+ $this->assertEqual(
+ $reflection->getInterfaces(),
+ array('AnyOldInterface'));
+ }
+
+ function testInterfacesListedForClass() {
+ $reflection = new SimpleReflection('AnyOldImplementation');
+ $this->assertEqual(
+ $reflection->getInterfaces(),
+ array('AnyOldInterface'));
+ }
+
+ function testInterfacesListedForSubclass() {
+ $reflection = new SimpleReflection('AnyOldSubclass');
+ $this->assertEqual(
+ $reflection->getInterfaces(),
+ array('AnyOldInterface'));
+ }
+
+ function testNoParameterCreationWhenNoInterface() {
+ $reflection = new SimpleReflection('AnyOldArgumentClass');
+ $function = $reflection->getSignature('aMethod');
+ if (version_compare(phpversion(), '5.0.2', '<=')) {
+ $this->assertEqual('function amethod($argument)', strtolower($function));
+ } else {
+ $this->assertEqual('function aMethod($argument)', $function);
+ }
+ }
+
+ function testParameterCreationWithoutTypeHinting() {
+ $reflection = new SimpleReflection('AnyOldArgumentImplementation');
+ $function = $reflection->getSignature('aMethod');
+ if (version_compare(phpversion(), '5.0.2', '<=')) {
+ $this->assertEqual('function amethod(AnyOldInterface $argument)', $function);
+ } else {
+ $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function);
+ }
+ }
+
+ function testParameterCreationForTypeHinting() {
+ $reflection = new SimpleReflection('AnyOldTypeHintedClass');
+ $function = $reflection->getSignature('aMethod');
+ if (version_compare(phpversion(), '5.0.2', '<=')) {
+ $this->assertEqual('function amethod(AnyOldInterface $argument)', $function);
+ } else {
+ $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function);
+ }
+ }
+
+ function testIssetFunctionSignature() {
+ $reflection = new SimpleReflection('AnyOldOverloadedClass');
+ $function = $reflection->getSignature('__isset');
+ $this->assertEqual('function __isset($key)', $function);
+ }
+
+ function testUnsetFunctionSignature() {
+ $reflection = new SimpleReflection('AnyOldOverloadedClass');
+ $function = $reflection->getSignature('__unset');
+ $this->assertEqual('function __unset($key)', $function);
+ }
+
+ function testProperlyReflectsTheFinalInterfaceWhenObjectImplementsAnExtendedInterface() {
+ $reflection = new SimpleReflection('AnyDescendentImplementation');
+ $interfaces = $reflection->getInterfaces();
+ $this->assertEqual(1, count($interfaces));
+ $this->assertEqual('AnyDescendentInterface', array_shift($interfaces));
+ }
+
+ function testCreatingSignatureForAbstractMethod() {
+ $reflection = new SimpleReflection('AnotherOldAbstractClass');
+ $this->assertEqual($reflection->getSignature('aMethod'), 'function aMethod(AnyOldInterface $argument)');
+ }
+
+ function testCanProperlyGenerateStaticMethodSignatures() {
+ $reflection = new SimpleReflection('AnyOldClassWithStaticMethods');
+ $this->assertEqual('static function aStatic()', $reflection->getSignature('aStatic'));
+ $this->assertEqual(
+ 'static function aStaticWithParameters($arg1, $arg2)',
+ $reflection->getSignature('aStaticWithParameters')
+ );
+ }
+}
+
+class TestOfReflectionWithTypeHints extends UnitTestCase {
+ function skip() {
+ $this->skipIf(version_compare(phpversion(), '5.1.0', '<'), 'Reflection with type hints only tested for PHP 5.1.0 and above');
+ }
+
+ function testParameterCreationForTypeHintingWithArray() {
+ eval('interface AnyOldArrayTypeHintedInterface {
+ function amethod(array $argument);
+ }
+ class AnyOldArrayTypeHintedClass implements AnyOldArrayTypeHintedInterface {
+ function amethod(array $argument) {}
+ }');
+ $reflection = new SimpleReflection('AnyOldArrayTypeHintedClass');
+ $function = $reflection->getSignature('amethod');
+ $this->assertEqual('function amethod(array $argument)', $function);
+ }
+}
+
+class TestOfAbstractsWithAbstractMethods extends UnitTestCase {
+ function testCanProperlyGenerateAbstractMethods() {
+ $reflection = new SimpleReflection('AnyOldAbstractClassWithAbstractMethods');
+ $this->assertEqual(
+ 'function anAbstract()',
+ $reflection->getSignature('anAbstract')
+ );
+ $this->assertEqual(
+ 'function anAbstractWithParameter($foo)',
+ $reflection->getSignature('anAbstractWithParameter')
+ );
+ $this->assertEqual(
+ 'function anAbstractWithMultipleParameters($foo, $bar)',
+ $reflection->getSignature('anAbstractWithMultipleParameters')
+ );
+ }
+}
+
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/remote_test.php b/3rdparty/simpletest/test/remote_test.php
new file mode 100755
index 00000000000..5f3f96a4de9
--- /dev/null
+++ b/3rdparty/simpletest/test/remote_test.php
@@ -0,0 +1,19 @@
+<?php
+// $Id: remote_test.php 1759 2008-04-15 02:37:07Z edwardzyang $
+require_once('../remote.php');
+require_once('../reporter.php');
+
+// The following URL will depend on your own installation.
+if (isset($_SERVER['SCRIPT_URI'])) {
+ $base_uri = $_SERVER['SCRIPT_URI'];
+} elseif (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['PHP_SELF'])) {
+ $base_uri = 'http://'. $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
+};
+$test_url = str_replace('remote_test.php', 'visual_test.php', $base_uri);
+
+$test = new TestSuite('Remote tests');
+$test->add(new RemoteTestCase($test_url . '?xml=yes', $test_url . '?xml=yes&dry=yes'));
+if (SimpleReporter::inCli()) {
+ exit ($test->run(new TextReporter()) ? 0 : 1);
+}
+$test->run(new HtmlReporter());
diff --git a/3rdparty/simpletest/test/shell_test.php b/3rdparty/simpletest/test/shell_test.php
new file mode 100755
index 00000000000..d1d769a6795
--- /dev/null
+++ b/3rdparty/simpletest/test/shell_test.php
@@ -0,0 +1,38 @@
+<?php
+// $Id: shell_test.php 1748 2008-04-14 01:50:41Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../shell_tester.php');
+
+class TestOfShell extends UnitTestCase {
+
+ function testEcho() {
+ $shell = new SimpleShell();
+ $this->assertIdentical($shell->execute('echo Hello'), 0);
+ $this->assertPattern('/Hello/', $shell->getOutput());
+ }
+
+ function testBadCommand() {
+ $shell = new SimpleShell();
+ $this->assertNotEqual($ret = $shell->execute('blurgh! 2>&1'), 0);
+ }
+}
+
+class TestOfShellTesterAndShell extends ShellTestCase {
+
+ function testEcho() {
+ $this->assertTrue($this->execute('echo Hello'));
+ $this->assertExitCode(0);
+ $this->assertoutput('Hello');
+ }
+
+ function testFileExistence() {
+ $this->assertFileExists(dirname(__FILE__) . '/all_tests.php');
+ $this->assertFileNotExists('wibble');
+ }
+
+ function testFilePatterns() {
+ $this->assertFilePattern('/all[_ ]tests/i', dirname(__FILE__) . '/all_tests.php');
+ $this->assertNoFilePattern('/sputnik/i', dirname(__FILE__) . '/all_tests.php');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/shell_tester_test.php b/3rdparty/simpletest/test/shell_tester_test.php
new file mode 100755
index 00000000000..b12c602a39f
--- /dev/null
+++ b/3rdparty/simpletest/test/shell_tester_test.php
@@ -0,0 +1,42 @@
+<?php
+// $Id: shell_tester_test.php 1787 2008-04-26 20:35:39Z pp11 $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../shell_tester.php');
+Mock::generate('SimpleShell');
+
+class TestOfShellTestCase extends ShellTestCase {
+ private $mock_shell = false;
+
+ function getShell() {
+ return $this->mock_shell;
+ }
+
+ function testGenericEquality() {
+ $this->assertEqual('a', 'a');
+ $this->assertNotEqual('a', 'A');
+ }
+
+ function testExitCode() {
+ $this->mock_shell = new MockSimpleShell();
+ $this->mock_shell->setReturnValue('execute', 0);
+ $this->mock_shell->expectOnce('execute', array('ls'));
+ $this->assertTrue($this->execute('ls'));
+ $this->assertExitCode(0);
+ }
+
+ function testOutput() {
+ $this->mock_shell = new MockSimpleShell();
+ $this->mock_shell->setReturnValue('execute', 0);
+ $this->mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n");
+ $this->assertOutput("Line 1\nLine 2\n");
+ }
+
+ function testOutputPatterns() {
+ $this->mock_shell = new MockSimpleShell();
+ $this->mock_shell->setReturnValue('execute', 0);
+ $this->mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n");
+ $this->assertOutputPattern('/line/i');
+ $this->assertNoOutputPattern('/line 2/');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/simpletest_test.php b/3rdparty/simpletest/test/simpletest_test.php
new file mode 100755
index 00000000000..daa65c6f472
--- /dev/null
+++ b/3rdparty/simpletest/test/simpletest_test.php
@@ -0,0 +1,58 @@
+<?php
+// $Id: simpletest_test.php 1748 2008-04-14 01:50:41Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../simpletest.php');
+
+SimpleTest::ignore('ShouldNeverBeRunEither');
+
+class ShouldNeverBeRun extends UnitTestCase {
+ function testWithNoChanceOfSuccess() {
+ $this->fail('Should be ignored');
+ }
+}
+
+class ShouldNeverBeRunEither extends ShouldNeverBeRun { }
+
+class TestOfStackTrace extends UnitTestCase {
+
+ function testCanFindAssertInTrace() {
+ $trace = new SimpleStackTrace(array('assert'));
+ $this->assertEqual(
+ $trace->traceMethod(array(array(
+ 'file' => '/my_test.php',
+ 'line' => 24,
+ 'function' => 'assertSomething'))),
+ ' at [/my_test.php line 24]');
+ }
+}
+
+class DummyResource { }
+
+class TestOfContext extends UnitTestCase {
+
+ function testCurrentContextIsUnique() {
+ $this->assertSame(
+ SimpleTest::getContext(),
+ SimpleTest::getContext());
+ }
+
+ function testContextHoldsCurrentTestCase() {
+ $context = SimpleTest::getContext();
+ $this->assertSame($this, $context->getTest());
+ }
+
+ function testResourceIsSingleInstanceWithContext() {
+ $context = new SimpleTestContext();
+ $this->assertSame(
+ $context->get('DummyResource'),
+ $context->get('DummyResource'));
+ }
+
+ function testClearingContextResetsResources() {
+ $context = new SimpleTestContext();
+ $resource = $context->get('DummyResource');
+ $context->clear();
+ $this->assertClone($resource, $context->get('DummyResource'));
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/site/file.html b/3rdparty/simpletest/test/site/file.html
new file mode 100755
index 00000000000..cc41aee1b8b
--- /dev/null
+++ b/3rdparty/simpletest/test/site/file.html
@@ -0,0 +1,6 @@
+<html>
+ <head><title>Link to SimpleTest</title></head>
+ <body>
+ <a href="http://simpletest.org/">Link to SimpleTest</a>
+ </body>
+</html> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/socket_test.php b/3rdparty/simpletest/test/socket_test.php
new file mode 100755
index 00000000000..729adda4960
--- /dev/null
+++ b/3rdparty/simpletest/test/socket_test.php
@@ -0,0 +1,25 @@
+<?php
+// $Id: socket_test.php 1782 2008-04-25 17:09:06Z pp11 $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../socket.php');
+Mock::generate('SimpleSocket');
+
+class TestOfSimpleStickyError extends UnitTestCase {
+
+ function testSettingError() {
+ $error = new SimpleStickyError();
+ $this->assertFalse($error->isError());
+ $error->setError('Ouch');
+ $this->assertTrue($error->isError());
+ $this->assertEqual($error->getError(), 'Ouch');
+ }
+
+ function testClearingError() {
+ $error = new SimpleStickyError();
+ $error->setError('Ouch');
+ $this->assertTrue($error->isError());
+ $error->clearError();
+ $this->assertFalse($error->isError());
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/support/collector/collectable.1 b/3rdparty/simpletest/test/support/collector/collectable.1
new file mode 100755
index 00000000000..e69de29bb2d
--- /dev/null
+++ b/3rdparty/simpletest/test/support/collector/collectable.1
diff --git a/3rdparty/simpletest/test/support/collector/collectable.2 b/3rdparty/simpletest/test/support/collector/collectable.2
new file mode 100755
index 00000000000..e69de29bb2d
--- /dev/null
+++ b/3rdparty/simpletest/test/support/collector/collectable.2
diff --git a/3rdparty/simpletest/test/support/empty_test_file.php b/3rdparty/simpletest/test/support/empty_test_file.php
new file mode 100755
index 00000000000..31e3f7bed62
--- /dev/null
+++ b/3rdparty/simpletest/test/support/empty_test_file.php
@@ -0,0 +1,3 @@
+<?php
+require_once(dirname(__FILE__) . '/../../autorun.php');
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/support/failing_test.php b/3rdparty/simpletest/test/support/failing_test.php
new file mode 100755
index 00000000000..30f0d7507d9
--- /dev/null
+++ b/3rdparty/simpletest/test/support/failing_test.php
@@ -0,0 +1,9 @@
+<?php
+require_once(dirname(__FILE__) . '/../../autorun.php');
+
+class FailingTest extends UnitTestCase {
+ function test_fail() {
+ $this->assertEqual(1,2);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/support/latin1_sample b/3rdparty/simpletest/test/support/latin1_sample
new file mode 100755
index 00000000000..19035257766
--- /dev/null
+++ b/3rdparty/simpletest/test/support/latin1_sample
@@ -0,0 +1 @@
+£¹²³¼½¾@¶øþðßæ«»¢µ \ No newline at end of file
diff --git a/3rdparty/simpletest/test/support/passing_test.php b/3rdparty/simpletest/test/support/passing_test.php
new file mode 100755
index 00000000000..b7863216353
--- /dev/null
+++ b/3rdparty/simpletest/test/support/passing_test.php
@@ -0,0 +1,9 @@
+<?php
+require_once(dirname(__FILE__) . '/../../autorun.php');
+
+class PassingTest extends UnitTestCase {
+ function test_pass() {
+ $this->assertEqual(2,2);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/support/recorder_sample.php b/3rdparty/simpletest/test/support/recorder_sample.php
new file mode 100755
index 00000000000..4f157f6b601
--- /dev/null
+++ b/3rdparty/simpletest/test/support/recorder_sample.php
@@ -0,0 +1,14 @@
+<?php
+// $Id: sample_test.php 1500 2007-04-29 14:33:31Z pp11 $
+require_once dirname(__FILE__) . '/../../autorun.php';
+
+class SampleTestForRecorder extends UnitTestCase {
+ function testTrueIsTrue() {
+ $this->assertTrue(true);
+ }
+
+ function testFalseIsTrue() {
+ $this->assertFalse(true);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/support/spl_examples.php b/3rdparty/simpletest/test/support/spl_examples.php
new file mode 100755
index 00000000000..45add356c44
--- /dev/null
+++ b/3rdparty/simpletest/test/support/spl_examples.php
@@ -0,0 +1,15 @@
+<?php
+ // $Id: spl_examples.php 1262 2006-02-05 19:35:31Z lastcraft $
+
+ class IteratorImplementation implements Iterator {
+ function current() { }
+ function next() { }
+ function key() { }
+ function valid() { }
+ function rewind() { }
+ }
+
+ class IteratorAggregateImplementation implements IteratorAggregate {
+ function getIterator() { }
+ }
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/support/supplementary_upload_sample.txt b/3rdparty/simpletest/test/support/supplementary_upload_sample.txt
new file mode 100755
index 00000000000..d8aa9e81013
--- /dev/null
+++ b/3rdparty/simpletest/test/support/supplementary_upload_sample.txt
@@ -0,0 +1 @@
+Some more text content \ No newline at end of file
diff --git a/3rdparty/simpletest/test/support/test1.php b/3rdparty/simpletest/test/support/test1.php
new file mode 100755
index 00000000000..b414586d642
--- /dev/null
+++ b/3rdparty/simpletest/test/support/test1.php
@@ -0,0 +1,7 @@
+<?php
+class test1 extends UnitTestCase {
+ function test_pass(){
+ $this->assertEqual(3,1+2, "pass1");
+ }
+}
+?>
diff --git a/3rdparty/simpletest/test/support/upload_sample.txt b/3rdparty/simpletest/test/support/upload_sample.txt
new file mode 100755
index 00000000000..ec98d7c5e3f
--- /dev/null
+++ b/3rdparty/simpletest/test/support/upload_sample.txt
@@ -0,0 +1 @@
+Sample for testing file upload \ No newline at end of file
diff --git a/3rdparty/simpletest/test/tag_test.php b/3rdparty/simpletest/test/tag_test.php
new file mode 100755
index 00000000000..5e8a377f089
--- /dev/null
+++ b/3rdparty/simpletest/test/tag_test.php
@@ -0,0 +1,554 @@
+<?php
+// $Id: tag_test.php 1748 2008-04-14 01:50:41Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../tag.php');
+require_once(dirname(__FILE__) . '/../encoding.php');
+Mock::generate('SimpleMultipartEncoding');
+
+class TestOfTag extends UnitTestCase {
+
+ function testStartValuesWithoutAdditionalContent() {
+ $tag = new SimpleTitleTag(array('a' => '1', 'b' => ''));
+ $this->assertEqual($tag->getTagName(), 'title');
+ $this->assertIdentical($tag->getAttribute('a'), '1');
+ $this->assertIdentical($tag->getAttribute('b'), '');
+ $this->assertIdentical($tag->getAttribute('c'), false);
+ $this->assertIdentical($tag->getContent(), '');
+ }
+
+ function testTitleContent() {
+ $tag = new SimpleTitleTag(array());
+ $this->assertTrue($tag->expectEndTag());
+ $tag->addContent('Hello');
+ $tag->addContent('World');
+ $this->assertEqual($tag->getText(), 'HelloWorld');
+ }
+
+ function testMessyTitleContent() {
+ $tag = new SimpleTitleTag(array());
+ $this->assertTrue($tag->expectEndTag());
+ $tag->addContent('<b>Hello</b>');
+ $tag->addContent('<em>World</em>');
+ $this->assertEqual($tag->getText(), 'HelloWorld');
+ }
+
+ function testTagWithNoEnd() {
+ $tag = new SimpleTextTag(array());
+ $this->assertFalse($tag->expectEndTag());
+ }
+
+ function testAnchorHref() {
+ $tag = new SimpleAnchorTag(array('href' => 'http://here/'));
+ $this->assertEqual($tag->getHref(), 'http://here/');
+
+ $tag = new SimpleAnchorTag(array('href' => ''));
+ $this->assertIdentical($tag->getAttribute('href'), '');
+ $this->assertIdentical($tag->getHref(), '');
+
+ $tag = new SimpleAnchorTag(array());
+ $this->assertIdentical($tag->getAttribute('href'), false);
+ $this->assertIdentical($tag->getHref(), '');
+ }
+
+ function testIsIdMatchesIdAttribute() {
+ $tag = new SimpleAnchorTag(array('href' => 'http://here/', 'id' => 7));
+ $this->assertIdentical($tag->getAttribute('id'), '7');
+ $this->assertTrue($tag->isId(7));
+ }
+}
+
+class TestOfWidget extends UnitTestCase {
+
+ function testTextEmptyDefault() {
+ $tag = new SimpleTextTag(array('type' => 'text'));
+ $this->assertIdentical($tag->getDefault(), '');
+ $this->assertIdentical($tag->getValue(), '');
+ }
+
+ function testSettingOfExternalLabel() {
+ $tag = new SimpleTextTag(array('type' => 'text'));
+ $tag->setLabel('it');
+ $this->assertTrue($tag->isLabel('it'));
+ }
+
+ function testTextDefault() {
+ $tag = new SimpleTextTag(array('value' => 'aaa'));
+ $this->assertEqual($tag->getDefault(), 'aaa');
+ $this->assertEqual($tag->getValue(), 'aaa');
+ }
+
+ function testSettingTextValue() {
+ $tag = new SimpleTextTag(array('value' => 'aaa'));
+ $tag->setValue('bbb');
+ $this->assertEqual($tag->getValue(), 'bbb');
+ $tag->resetValue();
+ $this->assertEqual($tag->getValue(), 'aaa');
+ }
+
+ function testFailToSetHiddenValue() {
+ $tag = new SimpleTextTag(array('value' => 'aaa', 'type' => 'hidden'));
+ $this->assertFalse($tag->setValue('bbb'));
+ $this->assertEqual($tag->getValue(), 'aaa');
+ }
+
+ function testSubmitDefaults() {
+ $tag = new SimpleSubmitTag(array('type' => 'submit'));
+ $this->assertIdentical($tag->getName(), false);
+ $this->assertEqual($tag->getValue(), 'Submit');
+ $this->assertFalse($tag->setValue('Cannot set this'));
+ $this->assertEqual($tag->getValue(), 'Submit');
+ $this->assertEqual($tag->getLabel(), 'Submit');
+
+ $encoding = new MockSimpleMultipartEncoding();
+ $encoding->expectNever('add');
+ $tag->write($encoding);
+ }
+
+ function testPopulatedSubmit() {
+ $tag = new SimpleSubmitTag(
+ array('type' => 'submit', 'name' => 's', 'value' => 'Ok!'));
+ $this->assertEqual($tag->getName(), 's');
+ $this->assertEqual($tag->getValue(), 'Ok!');
+ $this->assertEqual($tag->getLabel(), 'Ok!');
+
+ $encoding = new MockSimpleMultipartEncoding();
+ $encoding->expectOnce('add', array('s', 'Ok!'));
+ $tag->write($encoding);
+ }
+
+ function testImageSubmit() {
+ $tag = new SimpleImageSubmitTag(
+ array('type' => 'image', 'name' => 's', 'alt' => 'Label'));
+ $this->assertEqual($tag->getName(), 's');
+ $this->assertEqual($tag->getLabel(), 'Label');
+
+ $encoding = new MockSimpleMultipartEncoding();
+ $encoding->expectAt(0, 'add', array('s.x', 20));
+ $encoding->expectAt(1, 'add', array('s.y', 30));
+ $tag->write($encoding, 20, 30);
+ }
+
+ function testImageSubmitTitlePreferredOverAltForLabel() {
+ $tag = new SimpleImageSubmitTag(
+ array('type' => 'image', 'name' => 's', 'alt' => 'Label', 'title' => 'Title'));
+ $this->assertEqual($tag->getLabel(), 'Title');
+ }
+
+ function testButton() {
+ $tag = new SimpleButtonTag(
+ array('type' => 'submit', 'name' => 's', 'value' => 'do'));
+ $tag->addContent('I am a button');
+ $this->assertEqual($tag->getName(), 's');
+ $this->assertEqual($tag->getValue(), 'do');
+ $this->assertEqual($tag->getLabel(), 'I am a button');
+
+ $encoding = new MockSimpleMultipartEncoding();
+ $encoding->expectOnce('add', array('s', 'do'));
+ $tag->write($encoding);
+ }
+}
+
+class TestOfTextArea extends UnitTestCase {
+
+ function testDefault() {
+ $tag = new SimpleTextAreaTag(array('name' => 'a'));
+ $tag->addContent('Some text');
+ $this->assertEqual($tag->getName(), 'a');
+ $this->assertEqual($tag->getDefault(), 'Some text');
+ }
+
+ function testWrapping() {
+ $tag = new SimpleTextAreaTag(array('cols' => '10', 'wrap' => 'physical'));
+ $tag->addContent("Lot's of text that should be wrapped");
+ $this->assertEqual(
+ $tag->getDefault(),
+ "Lot's of\r\ntext that\r\nshould be\r\nwrapped");
+ $tag->setValue("New long text\r\nwith two lines");
+ $this->assertEqual(
+ $tag->getValue(),
+ "New long\r\ntext\r\nwith two\r\nlines");
+ }
+
+ function testWrappingRemovesLeadingcariageReturn() {
+ $tag = new SimpleTextAreaTag(array('cols' => '20', 'wrap' => 'physical'));
+ $tag->addContent("\rStuff");
+ $this->assertEqual($tag->getDefault(), 'Stuff');
+ $tag->setValue("\nNew stuff\n");
+ $this->assertEqual($tag->getValue(), "New stuff\r\n");
+ }
+
+ function testBreaksAreNewlineAndCarriageReturn() {
+ $tag = new SimpleTextAreaTag(array('cols' => '10'));
+ $tag->addContent("Some\nText\rwith\r\nbreaks");
+ $this->assertEqual($tag->getValue(), "Some\r\nText\r\nwith\r\nbreaks");
+ }
+}
+
+class TestOfCheckbox extends UnitTestCase {
+
+ function testCanSetCheckboxToNamedValueWithBooleanTrue() {
+ $tag = new SimpleCheckboxTag(array('name' => 'a', 'value' => 'A'));
+ $this->assertEqual($tag->getValue(), false);
+ $tag->setValue(true);
+ $this->assertIdentical($tag->getValue(), 'A');
+ }
+}
+
+class TestOfSelection extends UnitTestCase {
+
+ function testEmpty() {
+ $tag = new SimpleSelectionTag(array('name' => 'a'));
+ $this->assertIdentical($tag->getValue(), '');
+ }
+
+ function testSingle() {
+ $tag = new SimpleSelectionTag(array('name' => 'a'));
+ $option = new SimpleOptionTag(array());
+ $option->addContent('AAA');
+ $tag->addTag($option);
+ $this->assertEqual($tag->getValue(), 'AAA');
+ }
+
+ function testSingleDefault() {
+ $tag = new SimpleSelectionTag(array('name' => 'a'));
+ $option = new SimpleOptionTag(array('selected' => ''));
+ $option->addContent('AAA');
+ $tag->addTag($option);
+ $this->assertEqual($tag->getValue(), 'AAA');
+ }
+
+ function testSingleMappedDefault() {
+ $tag = new SimpleSelectionTag(array('name' => 'a'));
+ $option = new SimpleOptionTag(array('selected' => '', 'value' => 'aaa'));
+ $option->addContent('AAA');
+ $tag->addTag($option);
+ $this->assertEqual($tag->getValue(), 'aaa');
+ }
+
+ function testStartsWithDefault() {
+ $tag = new SimpleSelectionTag(array('name' => 'a'));
+ $a = new SimpleOptionTag(array());
+ $a->addContent('AAA');
+ $tag->addTag($a);
+ $b = new SimpleOptionTag(array('selected' => ''));
+ $b->addContent('BBB');
+ $tag->addTag($b);
+ $c = new SimpleOptionTag(array());
+ $c->addContent('CCC');
+ $tag->addTag($c);
+ $this->assertEqual($tag->getValue(), 'BBB');
+ }
+
+ function testSettingOption() {
+ $tag = new SimpleSelectionTag(array('name' => 'a'));
+ $a = new SimpleOptionTag(array());
+ $a->addContent('AAA');
+ $tag->addTag($a);
+ $b = new SimpleOptionTag(array('selected' => ''));
+ $b->addContent('BBB');
+ $tag->addTag($b);
+ $c = new SimpleOptionTag(array());
+ $c->addContent('CCC');
+ $tag->setValue('AAA');
+ $this->assertEqual($tag->getValue(), 'AAA');
+ }
+
+ function testSettingMappedOption() {
+ $tag = new SimpleSelectionTag(array('name' => 'a'));
+ $a = new SimpleOptionTag(array('value' => 'aaa'));
+ $a->addContent('AAA');
+ $tag->addTag($a);
+ $b = new SimpleOptionTag(array('value' => 'bbb', 'selected' => ''));
+ $b->addContent('BBB');
+ $tag->addTag($b);
+ $c = new SimpleOptionTag(array('value' => 'ccc'));
+ $c->addContent('CCC');
+ $tag->addTag($c);
+ $tag->setValue('AAA');
+ $this->assertEqual($tag->getValue(), 'aaa');
+ $tag->setValue('ccc');
+ $this->assertEqual($tag->getValue(), 'ccc');
+ }
+
+ function testSelectionDespiteSpuriousWhitespace() {
+ $tag = new SimpleSelectionTag(array('name' => 'a'));
+ $a = new SimpleOptionTag(array());
+ $a->addContent(' AAA ');
+ $tag->addTag($a);
+ $b = new SimpleOptionTag(array('selected' => ''));
+ $b->addContent(' BBB ');
+ $tag->addTag($b);
+ $c = new SimpleOptionTag(array());
+ $c->addContent(' CCC ');
+ $tag->addTag($c);
+ $this->assertEqual($tag->getValue(), ' BBB ');
+ $tag->setValue('AAA');
+ $this->assertEqual($tag->getValue(), ' AAA ');
+ }
+
+ function testFailToSetIllegalOption() {
+ $tag = new SimpleSelectionTag(array('name' => 'a'));
+ $a = new SimpleOptionTag(array());
+ $a->addContent('AAA');
+ $tag->addTag($a);
+ $b = new SimpleOptionTag(array('selected' => ''));
+ $b->addContent('BBB');
+ $tag->addTag($b);
+ $c = new SimpleOptionTag(array());
+ $c->addContent('CCC');
+ $tag->addTag($c);
+ $this->assertFalse($tag->setValue('Not present'));
+ $this->assertEqual($tag->getValue(), 'BBB');
+ }
+
+ function testNastyOptionValuesThatLookLikeFalse() {
+ $tag = new SimpleSelectionTag(array('name' => 'a'));
+ $a = new SimpleOptionTag(array('value' => '1'));
+ $a->addContent('One');
+ $tag->addTag($a);
+ $b = new SimpleOptionTag(array('value' => '0'));
+ $b->addContent('Zero');
+ $tag->addTag($b);
+ $this->assertIdentical($tag->getValue(), '1');
+ $tag->setValue('Zero');
+ $this->assertIdentical($tag->getValue(), '0');
+ }
+
+ function testBlankOption() {
+ $tag = new SimpleSelectionTag(array('name' => 'A'));
+ $a = new SimpleOptionTag(array());
+ $tag->addTag($a);
+ $b = new SimpleOptionTag(array());
+ $b->addContent('b');
+ $tag->addTag($b);
+ $this->assertIdentical($tag->getValue(), '');
+ $tag->setValue('b');
+ $this->assertIdentical($tag->getValue(), 'b');
+ $tag->setValue('');
+ $this->assertIdentical($tag->getValue(), '');
+ }
+
+ function testMultipleDefaultWithNoSelections() {
+ $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => ''));
+ $a = new SimpleOptionTag(array());
+ $a->addContent('AAA');
+ $tag->addTag($a);
+ $b = new SimpleOptionTag(array());
+ $b->addContent('BBB');
+ $tag->addTag($b);
+ $this->assertIdentical($tag->getDefault(), array());
+ $this->assertIdentical($tag->getValue(), array());
+ }
+
+ function testMultipleDefaultWithSelections() {
+ $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => ''));
+ $a = new SimpleOptionTag(array('selected' => ''));
+ $a->addContent('AAA');
+ $tag->addTag($a);
+ $b = new SimpleOptionTag(array('selected' => ''));
+ $b->addContent('BBB');
+ $tag->addTag($b);
+ $this->assertIdentical($tag->getDefault(), array('AAA', 'BBB'));
+ $this->assertIdentical($tag->getValue(), array('AAA', 'BBB'));
+ }
+
+ function testSettingMultiple() {
+ $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => ''));
+ $a = new SimpleOptionTag(array('selected' => ''));
+ $a->addContent('AAA');
+ $tag->addTag($a);
+ $b = new SimpleOptionTag(array());
+ $b->addContent('BBB');
+ $tag->addTag($b);
+ $c = new SimpleOptionTag(array('selected' => '', 'value' => 'ccc'));
+ $c->addContent('CCC');
+ $tag->addTag($c);
+ $this->assertIdentical($tag->getDefault(), array('AAA', 'ccc'));
+ $this->assertTrue($tag->setValue(array('BBB', 'ccc')));
+ $this->assertIdentical($tag->getValue(), array('BBB', 'ccc'));
+ $this->assertTrue($tag->setValue(array()));
+ $this->assertIdentical($tag->getValue(), array());
+ }
+
+ function testFailToSetIllegalOptionsInMultiple() {
+ $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => ''));
+ $a = new SimpleOptionTag(array('selected' => ''));
+ $a->addContent('AAA');
+ $tag->addTag($a);
+ $b = new SimpleOptionTag(array());
+ $b->addContent('BBB');
+ $tag->addTag($b);
+ $this->assertFalse($tag->setValue(array('CCC')));
+ $this->assertTrue($tag->setValue(array('AAA', 'BBB')));
+ $this->assertFalse($tag->setValue(array('AAA', 'CCC')));
+ }
+}
+
+class TestOfRadioGroup extends UnitTestCase {
+
+ function testEmptyGroup() {
+ $group = new SimpleRadioGroup();
+ $this->assertIdentical($group->getDefault(), false);
+ $this->assertIdentical($group->getValue(), false);
+ $this->assertFalse($group->setValue('a'));
+ }
+
+ function testReadingSingleButtonGroup() {
+ $group = new SimpleRadioGroup();
+ $group->addWidget(new SimpleRadioButtonTag(
+ array('value' => 'A', 'checked' => '')));
+ $this->assertIdentical($group->getDefault(), 'A');
+ $this->assertIdentical($group->getValue(), 'A');
+ }
+
+ function testReadingMultipleButtonGroup() {
+ $group = new SimpleRadioGroup();
+ $group->addWidget(new SimpleRadioButtonTag(
+ array('value' => 'A')));
+ $group->addWidget(new SimpleRadioButtonTag(
+ array('value' => 'B', 'checked' => '')));
+ $this->assertIdentical($group->getDefault(), 'B');
+ $this->assertIdentical($group->getValue(), 'B');
+ }
+
+ function testFailToSetUnlistedValue() {
+ $group = new SimpleRadioGroup();
+ $group->addWidget(new SimpleRadioButtonTag(array('value' => 'z')));
+ $this->assertFalse($group->setValue('a'));
+ $this->assertIdentical($group->getValue(), false);
+ }
+
+ function testSettingNewValueClearsTheOldOne() {
+ $group = new SimpleRadioGroup();
+ $group->addWidget(new SimpleRadioButtonTag(
+ array('value' => 'A')));
+ $group->addWidget(new SimpleRadioButtonTag(
+ array('value' => 'B', 'checked' => '')));
+ $this->assertTrue($group->setValue('A'));
+ $this->assertIdentical($group->getValue(), 'A');
+ }
+
+ function testIsIdMatchesAnyWidgetInSet() {
+ $group = new SimpleRadioGroup();
+ $group->addWidget(new SimpleRadioButtonTag(
+ array('value' => 'A', 'id' => 'i1')));
+ $group->addWidget(new SimpleRadioButtonTag(
+ array('value' => 'B', 'id' => 'i2')));
+ $this->assertFalse($group->isId('i0'));
+ $this->assertTrue($group->isId('i1'));
+ $this->assertTrue($group->isId('i2'));
+ }
+
+ function testIsLabelMatchesAnyWidgetInSet() {
+ $group = new SimpleRadioGroup();
+ $button1 = new SimpleRadioButtonTag(array('value' => 'A'));
+ $button1->setLabel('one');
+ $group->addWidget($button1);
+ $button2 = new SimpleRadioButtonTag(array('value' => 'B'));
+ $button2->setLabel('two');
+ $group->addWidget($button2);
+ $this->assertFalse($group->isLabel('three'));
+ $this->assertTrue($group->isLabel('one'));
+ $this->assertTrue($group->isLabel('two'));
+ }
+}
+
+class TestOfTagGroup extends UnitTestCase {
+
+ function testReadingMultipleCheckboxGroup() {
+ $group = new SimpleCheckboxGroup();
+ $group->addWidget(new SimpleCheckboxTag(array('value' => 'A')));
+ $group->addWidget(new SimpleCheckboxTag(
+ array('value' => 'B', 'checked' => '')));
+ $this->assertIdentical($group->getDefault(), 'B');
+ $this->assertIdentical($group->getValue(), 'B');
+ }
+
+ function testReadingMultipleUncheckedItems() {
+ $group = new SimpleCheckboxGroup();
+ $group->addWidget(new SimpleCheckboxTag(array('value' => 'A')));
+ $group->addWidget(new SimpleCheckboxTag(array('value' => 'B')));
+ $this->assertIdentical($group->getDefault(), false);
+ $this->assertIdentical($group->getValue(), false);
+ }
+
+ function testReadingMultipleCheckedItems() {
+ $group = new SimpleCheckboxGroup();
+ $group->addWidget(new SimpleCheckboxTag(
+ array('value' => 'A', 'checked' => '')));
+ $group->addWidget(new SimpleCheckboxTag(
+ array('value' => 'B', 'checked' => '')));
+ $this->assertIdentical($group->getDefault(), array('A', 'B'));
+ $this->assertIdentical($group->getValue(), array('A', 'B'));
+ }
+
+ function testSettingSingleValue() {
+ $group = new SimpleCheckboxGroup();
+ $group->addWidget(new SimpleCheckboxTag(array('value' => 'A')));
+ $group->addWidget(new SimpleCheckboxTag(array('value' => 'B')));
+ $this->assertTrue($group->setValue('A'));
+ $this->assertIdentical($group->getValue(), 'A');
+ $this->assertTrue($group->setValue('B'));
+ $this->assertIdentical($group->getValue(), 'B');
+ }
+
+ function testSettingMultipleValues() {
+ $group = new SimpleCheckboxGroup();
+ $group->addWidget(new SimpleCheckboxTag(array('value' => 'A')));
+ $group->addWidget(new SimpleCheckboxTag(array('value' => 'B')));
+ $this->assertTrue($group->setValue(array('A', 'B')));
+ $this->assertIdentical($group->getValue(), array('A', 'B'));
+ }
+
+ function testSettingNoValue() {
+ $group = new SimpleCheckboxGroup();
+ $group->addWidget(new SimpleCheckboxTag(array('value' => 'A')));
+ $group->addWidget(new SimpleCheckboxTag(array('value' => 'B')));
+ $this->assertTrue($group->setValue(false));
+ $this->assertIdentical($group->getValue(), false);
+ }
+
+ function testIsIdMatchesAnyIdInSet() {
+ $group = new SimpleCheckboxGroup();
+ $group->addWidget(new SimpleCheckboxTag(array('id' => 1, 'value' => 'A')));
+ $group->addWidget(new SimpleCheckboxTag(array('id' => 2, 'value' => 'B')));
+ $this->assertFalse($group->isId(0));
+ $this->assertTrue($group->isId(1));
+ $this->assertTrue($group->isId(2));
+ }
+}
+
+class TestOfUploadWidget extends UnitTestCase {
+
+ function testValueIsFilePath() {
+ $upload = new SimpleUploadTag(array('name' => 'a'));
+ $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt');
+ $this->assertEqual($upload->getValue(), dirname(__FILE__) . '/support/upload_sample.txt');
+ }
+
+ function testSubmitsFileContents() {
+ $encoding = new MockSimpleMultipartEncoding();
+ $encoding->expectOnce('attach', array(
+ 'a',
+ 'Sample for testing file upload',
+ 'upload_sample.txt'));
+ $upload = new SimpleUploadTag(array('name' => 'a'));
+ $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt');
+ $upload->write($encoding);
+ }
+}
+
+class TestOfLabelTag extends UnitTestCase {
+
+ function testLabelShouldHaveAnEndTag() {
+ $label = new SimpleLabelTag(array());
+ $this->assertTrue($label->expectEndTag());
+ }
+
+ function testContentIsTextOnly() {
+ $label = new SimpleLabelTag(array());
+ $label->addContent('Here <tag>are</tag> words');
+ $this->assertEqual($label->getText(), 'Here are words');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/test_with_parse_error.php b/3rdparty/simpletest/test/test_with_parse_error.php
new file mode 100755
index 00000000000..41a5832a5cb
--- /dev/null
+++ b/3rdparty/simpletest/test/test_with_parse_error.php
@@ -0,0 +1,8 @@
+<?php
+ // $Id: test_with_parse_error.php 901 2005-01-24 00:32:14Z lastcraft $
+
+ class TestCaseWithParseError extends UnitTestCase {
+ wibble
+ }
+
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/unit_tester_test.php b/3rdparty/simpletest/test/unit_tester_test.php
new file mode 100755
index 00000000000..ce9850f09ab
--- /dev/null
+++ b/3rdparty/simpletest/test/unit_tester_test.php
@@ -0,0 +1,61 @@
+<?php
+// $Id: unit_tester_test.php 1748 2008-04-14 01:50:41Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+
+class ReferenceForTesting {
+}
+
+class TestOfUnitTester extends UnitTestCase {
+
+ function testAssertTrueReturnsAssertionAsBoolean() {
+ $this->assertTrue($this->assertTrue(true));
+ }
+
+ function testAssertFalseReturnsAssertionAsBoolean() {
+ $this->assertTrue($this->assertFalse(false));
+ }
+
+ function testAssertEqualReturnsAssertionAsBoolean() {
+ $this->assertTrue($this->assertEqual(5, 5));
+ }
+
+ function testAssertIdenticalReturnsAssertionAsBoolean() {
+ $this->assertTrue($this->assertIdentical(5, 5));
+ }
+
+ function testCoreAssertionsDoNotThrowErrors() {
+ $this->assertIsA($this, 'UnitTestCase');
+ $this->assertNotA($this, 'WebTestCase');
+ }
+
+ function testReferenceAssertionOnObjects() {
+ $a = new ReferenceForTesting();
+ $b = $a;
+ $this->assertSame($a, $b);
+ }
+
+ function testReferenceAssertionOnScalars() {
+ $a = 25;
+ $b = &$a;
+ $this->assertReference($a, $b);
+ }
+
+ function testCloneOnObjects() {
+ $a = new ReferenceForTesting();
+ $b = new ReferenceForTesting();
+ $this->assertClone($a, $b);
+ }
+
+ function TODO_testCloneOnScalars() {
+ $a = 25;
+ $b = 25;
+ $this->assertClone($a, $b);
+ }
+
+ function testCopyOnScalars() {
+ $a = 25;
+ $b = 25;
+ $this->assertCopy($a, $b);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/unit_tests.php b/3rdparty/simpletest/test/unit_tests.php
new file mode 100755
index 00000000000..9e621293f9e
--- /dev/null
+++ b/3rdparty/simpletest/test/unit_tests.php
@@ -0,0 +1,49 @@
+<?php
+// $Id: unit_tests.php 1986 2010-04-02 10:02:42Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../unit_tester.php');
+require_once(dirname(__FILE__) . '/../shell_tester.php');
+require_once(dirname(__FILE__) . '/../mock_objects.php');
+require_once(dirname(__FILE__) . '/../web_tester.php');
+require_once(dirname(__FILE__) . '/../extensions/pear_test_case.php');
+
+class UnitTests extends TestSuite {
+ function UnitTests() {
+ $this->TestSuite('Unit tests');
+ $path = dirname(__FILE__);
+ $this->addFile($path . '/errors_test.php');
+ $this->addFile($path . '/exceptions_test.php');
+ $this->addFile($path . '/arguments_test.php');
+ $this->addFile($path . '/autorun_test.php');
+ $this->addFile($path . '/compatibility_test.php');
+ $this->addFile($path . '/simpletest_test.php');
+ $this->addFile($path . '/dumper_test.php');
+ $this->addFile($path . '/expectation_test.php');
+ $this->addFile($path . '/unit_tester_test.php');
+ $this->addFile($path . '/reflection_php5_test.php');
+ $this->addFile($path . '/mock_objects_test.php');
+ $this->addFile($path . '/interfaces_test.php');
+ $this->addFile($path . '/collector_test.php');
+ $this->addFile($path . '/recorder_test.php');
+ $this->addFile($path . '/adapter_test.php');
+ $this->addFile($path . '/socket_test.php');
+ $this->addFile($path . '/encoding_test.php');
+ $this->addFile($path . '/url_test.php');
+ $this->addFile($path . '/cookies_test.php');
+ $this->addFile($path . '/http_test.php');
+ $this->addFile($path . '/authentication_test.php');
+ $this->addFile($path . '/user_agent_test.php');
+ $this->addFile($path . '/php_parser_test.php');
+ $this->addFile($path . '/parsing_test.php');
+ $this->addFile($path . '/tag_test.php');
+ $this->addFile($path . '/form_test.php');
+ $this->addFile($path . '/page_test.php');
+ $this->addFile($path . '/frames_test.php');
+ $this->addFile($path . '/browser_test.php');
+ $this->addFile($path . '/web_tester_test.php');
+ $this->addFile($path . '/shell_tester_test.php');
+ $this->addFile($path . '/xml_test.php');
+ $this->addFile($path . '/../extensions/testdox/test.php');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/url_test.php b/3rdparty/simpletest/test/url_test.php
new file mode 100755
index 00000000000..80119afbdde
--- /dev/null
+++ b/3rdparty/simpletest/test/url_test.php
@@ -0,0 +1,515 @@
+<?php
+// $Id: url_test.php 1998 2010-07-27 09:55:55Z pp11 $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../url.php');
+
+class TestOfUrl extends UnitTestCase {
+
+ function testDefaultUrl() {
+ $url = new SimpleUrl('');
+ $this->assertEqual($url->getScheme(), '');
+ $this->assertEqual($url->getHost(), '');
+ $this->assertEqual($url->getScheme('http'), 'http');
+ $this->assertEqual($url->getHost('localhost'), 'localhost');
+ $this->assertEqual($url->getPath(), '');
+ }
+
+ function testBasicParsing() {
+ $url = new SimpleUrl('https://www.lastcraft.com/test/');
+ $this->assertEqual($url->getScheme(), 'https');
+ $this->assertEqual($url->getHost(), 'www.lastcraft.com');
+ $this->assertEqual($url->getPath(), '/test/');
+ }
+
+ function testRelativeUrls() {
+ $url = new SimpleUrl('../somewhere.php');
+ $this->assertEqual($url->getScheme(), false);
+ $this->assertEqual($url->getHost(), false);
+ $this->assertEqual($url->getPath(), '../somewhere.php');
+ }
+
+ function testParseBareParameter() {
+ $url = new SimpleUrl('?a');
+ $this->assertEqual($url->getPath(), '');
+ $this->assertEqual($url->getEncodedRequest(), '?a');
+ $url->addRequestParameter('x', 'X');
+ $this->assertEqual($url->getEncodedRequest(), '?a=&x=X');
+ }
+
+ function testParseEmptyParameter() {
+ $url = new SimpleUrl('?a=');
+ $this->assertEqual($url->getPath(), '');
+ $this->assertEqual($url->getEncodedRequest(), '?a=');
+ $url->addRequestParameter('x', 'X');
+ $this->assertEqual($url->getEncodedRequest(), '?a=&x=X');
+ }
+
+ function testParseParameterPair() {
+ $url = new SimpleUrl('?a=A');
+ $this->assertEqual($url->getPath(), '');
+ $this->assertEqual($url->getEncodedRequest(), '?a=A');
+ $url->addRequestParameter('x', 'X');
+ $this->assertEqual($url->getEncodedRequest(), '?a=A&x=X');
+ }
+
+ function testParseMultipleParameters() {
+ $url = new SimpleUrl('?a=A&b=B');
+ $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B');
+ $url->addRequestParameter('x', 'X');
+ $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&x=X');
+ }
+
+ function testParsingParameterMixture() {
+ $url = new SimpleUrl('?a=A&b=&c');
+ $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c');
+ $url->addRequestParameter('x', 'X');
+ $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c=&x=X');
+ }
+
+ function testAddParametersFromScratch() {
+ $url = new SimpleUrl('');
+ $url->addRequestParameter('a', 'A');
+ $this->assertEqual($url->getEncodedRequest(), '?a=A');
+ $url->addRequestParameter('b', 'B');
+ $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B');
+ $url->addRequestParameter('a', 'aaa');
+ $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&a=aaa');
+ }
+
+ function testClearingParameters() {
+ $url = new SimpleUrl('');
+ $url->addRequestParameter('a', 'A');
+ $url->clearRequest();
+ $this->assertIdentical($url->getEncodedRequest(), '');
+ }
+
+ function testEncodingParameters() {
+ $url = new SimpleUrl('');
+ $url->addRequestParameter('a', '?!"\'#~@[]{}:;<>,./|$%^&*()_+-=');
+ $this->assertIdentical(
+ $request = $url->getEncodedRequest(),
+ '?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%24%25%5E%26%2A%28%29_%2B-%3D');
+ }
+
+ function testDecodingParameters() {
+ $url = new SimpleUrl('?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%24%25%5E%26%2A%28%29_%2B-%3D');
+ $this->assertEqual(
+ $url->getEncodedRequest(),
+ '?a=' . urlencode('?!"\'#~@[]{}:;<>,./|$%^&*()_+-='));
+ }
+
+ function testUrlInQueryDoesNotConfuseParsing() {
+ $url = new SimpleUrl('wibble/login.php?url=http://www.google.com/moo/');
+ $this->assertFalse($url->getScheme());
+ $this->assertFalse($url->getHost());
+ $this->assertEqual($url->getPath(), 'wibble/login.php');
+ $this->assertEqual($url->getEncodedRequest(), '?url=http://www.google.com/moo/');
+ }
+
+ function testSettingCordinates() {
+ $url = new SimpleUrl('');
+ $url->setCoordinates('32', '45');
+ $this->assertIdentical($url->getX(), 32);
+ $this->assertIdentical($url->getY(), 45);
+ $this->assertEqual($url->getEncodedRequest(), '');
+ }
+
+ function testParseCordinates() {
+ $url = new SimpleUrl('?32,45');
+ $this->assertIdentical($url->getX(), 32);
+ $this->assertIdentical($url->getY(), 45);
+ }
+
+ function testClearingCordinates() {
+ $url = new SimpleUrl('?32,45');
+ $url->setCoordinates();
+ $this->assertIdentical($url->getX(), false);
+ $this->assertIdentical($url->getY(), false);
+ }
+
+ function testParsingParameterCordinateMixture() {
+ $url = new SimpleUrl('?a=A&b=&c?32,45');
+ $this->assertIdentical($url->getX(), 32);
+ $this->assertIdentical($url->getY(), 45);
+ $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c');
+ }
+
+ function testParsingParameterWithBadCordinates() {
+ $url = new SimpleUrl('?a=A&b=&c?32');
+ $this->assertIdentical($url->getX(), false);
+ $this->assertIdentical($url->getY(), false);
+ $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c?32');
+ }
+
+ function testPageSplitting() {
+ $url = new SimpleUrl('./here/../there/somewhere.php');
+ $this->assertEqual($url->getPath(), './here/../there/somewhere.php');
+ $this->assertEqual($url->getPage(), 'somewhere.php');
+ $this->assertEqual($url->getBasePath(), './here/../there/');
+ }
+
+ function testAbsolutePathPageSplitting() {
+ $url = new SimpleUrl("http://host.com/here/there/somewhere.php");
+ $this->assertEqual($url->getPath(), "/here/there/somewhere.php");
+ $this->assertEqual($url->getPage(), "somewhere.php");
+ $this->assertEqual($url->getBasePath(), "/here/there/");
+ }
+
+ function testSplittingUrlWithNoPageGivesEmptyPage() {
+ $url = new SimpleUrl('/here/there/');
+ $this->assertEqual($url->getPath(), '/here/there/');
+ $this->assertEqual($url->getPage(), '');
+ $this->assertEqual($url->getBasePath(), '/here/there/');
+ }
+
+ function testPathNormalisation() {
+ $url = new SimpleUrl();
+ $this->assertEqual(
+ $url->normalisePath('https://host.com/I/am/here/../there/somewhere.php'),
+ 'https://host.com/I/am/there/somewhere.php');
+ }
+
+ // regression test for #1535407
+ function testPathNormalisationWithSinglePeriod() {
+ $url = new SimpleUrl();
+ $this->assertEqual(
+ $url->normalisePath('https://host.com/I/am/here/./../there/somewhere.php'),
+ 'https://host.com/I/am/there/somewhere.php');
+ }
+
+ // regression test for #1852413
+ function testHostnameExtractedFromUContainingAtSign() {
+ $url = new SimpleUrl("http://localhost/name@example.com");
+ $this->assertEqual($url->getScheme(), "http");
+ $this->assertEqual($url->getUsername(), "");
+ $this->assertEqual($url->getPassword(), "");
+ $this->assertEqual($url->getHost(), "localhost");
+ $this->assertEqual($url->getPath(), "/name@example.com");
+ }
+
+ function testHostnameInLocalhost() {
+ $url = new SimpleUrl("http://localhost/name/example.com");
+ $this->assertEqual($url->getScheme(), "http");
+ $this->assertEqual($url->getUsername(), "");
+ $this->assertEqual($url->getPassword(), "");
+ $this->assertEqual($url->getHost(), "localhost");
+ $this->assertEqual($url->getPath(), "/name/example.com");
+ }
+
+ function testUsernameAndPasswordAreUrlDecoded() {
+ $url = new SimpleUrl('http://' . urlencode('test@test') .
+ ':' . urlencode('$!�@*&%') . '@www.lastcraft.com');
+ $this->assertEqual($url->getUsername(), 'test@test');
+ $this->assertEqual($url->getPassword(), '$!�@*&%');
+ }
+
+ function testBlitz() {
+ $this->assertUrl(
+ "https://username:password@www.somewhere.com:243/this/that/here.php?a=1&b=2#anchor",
+ array("https", "username", "password", "www.somewhere.com", 243, "/this/that/here.php", "com", "?a=1&b=2", "anchor"),
+ array("a" => "1", "b" => "2"));
+ $this->assertUrl(
+ "username:password@www.somewhere.com/this/that/here.php?a=1",
+ array(false, "username", "password", "www.somewhere.com", false, "/this/that/here.php", "com", "?a=1", false),
+ array("a" => "1"));
+ $this->assertUrl(
+ "username:password@somewhere.com:243?1,2",
+ array(false, "username", "password", "somewhere.com", 243, "/", "com", "", false),
+ array(),
+ array(1, 2));
+ $this->assertUrl(
+ "https://www.somewhere.com",
+ array("https", false, false, "www.somewhere.com", false, "/", "com", "", false));
+ $this->assertUrl(
+ "username@www.somewhere.com:243#anchor",
+ array(false, "username", false, "www.somewhere.com", 243, "/", "com", "", "anchor"));
+ $this->assertUrl(
+ "/this/that/here.php?a=1&b=2?3,4",
+ array(false, false, false, false, false, "/this/that/here.php", false, "?a=1&b=2", false),
+ array("a" => "1", "b" => "2"),
+ array(3, 4));
+ $this->assertUrl(
+ "username@/here.php?a=1&b=2",
+ array(false, "username", false, false, false, "/here.php", false, "?a=1&b=2", false),
+ array("a" => "1", "b" => "2"));
+ }
+
+ function testAmbiguousHosts() {
+ $this->assertUrl(
+ "tigger",
+ array(false, false, false, false, false, "tigger", false, "", false));
+ $this->assertUrl(
+ "/tigger",
+ array(false, false, false, false, false, "/tigger", false, "", false));
+ $this->assertUrl(
+ "//tigger",
+ array(false, false, false, "tigger", false, "/", false, "", false));
+ $this->assertUrl(
+ "//tigger/",
+ array(false, false, false, "tigger", false, "/", false, "", false));
+ $this->assertUrl(
+ "tigger.com",
+ array(false, false, false, "tigger.com", false, "/", "com", "", false));
+ $this->assertUrl(
+ "me.net/tigger",
+ array(false, false, false, "me.net", false, "/tigger", "net", "", false));
+ }
+
+ function testAsString() {
+ $this->assertPreserved('https://www.here.com');
+ $this->assertPreserved('http://me:secret@www.here.com');
+ $this->assertPreserved('http://here/there');
+ $this->assertPreserved('http://here/there?a=A&b=B');
+ $this->assertPreserved('http://here/there?a=1&a=2');
+ $this->assertPreserved('http://here/there?a=1&a=2?9,8');
+ $this->assertPreserved('http://host?a=1&a=2');
+ $this->assertPreserved('http://host#stuff');
+ $this->assertPreserved('http://me:secret@www.here.com/a/b/c/here.html?a=A?7,6');
+ $this->assertPreserved('http://www.here.com/?a=A__b=B');
+ $this->assertPreserved('http://www.example.com:8080/');
+ }
+
+ function testUrlWithTwoSlashesInPath() {
+ $url = new SimpleUrl('/article/categoryedit/insert//');
+ $this->assertEqual($url->getPath(), '/article/categoryedit/insert//');
+ }
+
+ function testUrlWithRequestKeyEncoded() {
+ $url = new SimpleUrl('/?foo%5B1%5D=bar');
+ $this->assertEqual($url->getEncodedRequest(), '?foo%5B1%5D=bar');
+ $url->addRequestParameter('a[1]', 'b[]');
+ $this->assertEqual($url->getEncodedRequest(), '?foo%5B1%5D=bar&a%5B1%5D=b%5B%5D');
+
+ $url = new SimpleUrl('/');
+ $url->addRequestParameter('a[1]', 'b[]');
+ $this->assertEqual($url->getEncodedRequest(), '?a%5B1%5D=b%5B%5D');
+ }
+
+ function testUrlWithRequestKeyEncodedAndParamNamLookingLikePair() {
+ $url = new SimpleUrl('/');
+ $url->addRequestParameter('foo[]=bar', '');
+ $this->assertEqual($url->getEncodedRequest(), '?foo%5B%5D%3Dbar=');
+ $url = new SimpleUrl('/?foo%5B%5D%3Dbar=');
+ $this->assertEqual($url->getEncodedRequest(), '?foo%5B%5D%3Dbar=');
+ }
+
+ function assertUrl($raw, $parts, $params = false, $coords = false) {
+ if (! is_array($params)) {
+ $params = array();
+ }
+ $url = new SimpleUrl($raw);
+ $this->assertIdentical($url->getScheme(), $parts[0], "[$raw] scheme -> %s");
+ $this->assertIdentical($url->getUsername(), $parts[1], "[$raw] username -> %s");
+ $this->assertIdentical($url->getPassword(), $parts[2], "[$raw] password -> %s");
+ $this->assertIdentical($url->getHost(), $parts[3], "[$raw] host -> %s");
+ $this->assertIdentical($url->getPort(), $parts[4], "[$raw] port -> %s");
+ $this->assertIdentical($url->getPath(), $parts[5], "[$raw] path -> %s");
+ $this->assertIdentical($url->getTld(), $parts[6], "[$raw] tld -> %s");
+ $this->assertIdentical($url->getEncodedRequest(), $parts[7], "[$raw] encoded -> %s");
+ $this->assertIdentical($url->getFragment(), $parts[8], "[$raw] fragment -> %s");
+ if ($coords) {
+ $this->assertIdentical($url->getX(), $coords[0], "[$raw] x -> %s");
+ $this->assertIdentical($url->getY(), $coords[1], "[$raw] y -> %s");
+ }
+ }
+
+ function assertPreserved($string) {
+ $url = new SimpleUrl($string);
+ $this->assertEqual($url->asString(), $string);
+ }
+}
+
+class TestOfAbsoluteUrls extends UnitTestCase {
+
+ function testDirectoriesAfterFilename() {
+ $string = '../../index.php/foo/bar';
+ $url = new SimpleUrl($string);
+ $this->assertEqual($url->asString(), $string);
+
+ $absolute = $url->makeAbsolute('http://www.domain.com/some/path/');
+ $this->assertEqual($absolute->asString(), 'http://www.domain.com/index.php/foo/bar');
+ }
+
+ function testMakingAbsolute() {
+ $url = new SimpleUrl('../there/somewhere.php');
+ $this->assertEqual($url->getPath(), '../there/somewhere.php');
+ $absolute = $url->makeAbsolute('https://host.com:1234/I/am/here/');
+ $this->assertEqual($absolute->getScheme(), 'https');
+ $this->assertEqual($absolute->getHost(), 'host.com');
+ $this->assertEqual($absolute->getPort(), 1234);
+ $this->assertEqual($absolute->getPath(), '/I/am/there/somewhere.php');
+ }
+
+ function testMakingAnEmptyUrlAbsolute() {
+ $url = new SimpleUrl('');
+ $this->assertEqual($url->getPath(), '');
+ $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html');
+ $this->assertEqual($absolute->getScheme(), 'http');
+ $this->assertEqual($absolute->getHost(), 'host.com');
+ $this->assertEqual($absolute->getPath(), '/I/am/here/page.html');
+ }
+
+ function testMakingAnEmptyUrlAbsoluteWithMissingPageName() {
+ $url = new SimpleUrl('');
+ $this->assertEqual($url->getPath(), '');
+ $absolute = $url->makeAbsolute('http://host.com/I/am/here/');
+ $this->assertEqual($absolute->getScheme(), 'http');
+ $this->assertEqual($absolute->getHost(), 'host.com');
+ $this->assertEqual($absolute->getPath(), '/I/am/here/');
+ }
+
+ function testMakingAShortQueryUrlAbsolute() {
+ $url = new SimpleUrl('?a#b');
+ $this->assertEqual($url->getPath(), '');
+ $absolute = $url->makeAbsolute('http://host.com/I/am/here/');
+ $this->assertEqual($absolute->getScheme(), 'http');
+ $this->assertEqual($absolute->getHost(), 'host.com');
+ $this->assertEqual($absolute->getPath(), '/I/am/here/');
+ $this->assertEqual($absolute->getEncodedRequest(), '?a');
+ $this->assertEqual($absolute->getFragment(), 'b');
+ }
+
+ function testMakingADirectoryUrlAbsolute() {
+ $url = new SimpleUrl('hello/');
+ $this->assertEqual($url->getPath(), 'hello/');
+ $this->assertEqual($url->getBasePath(), 'hello/');
+ $this->assertEqual($url->getPage(), '');
+ $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html');
+ $this->assertEqual($absolute->getPath(), '/I/am/here/hello/');
+ }
+
+ function testMakingARootUrlAbsolute() {
+ $url = new SimpleUrl('/');
+ $this->assertEqual($url->getPath(), '/');
+ $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html');
+ $this->assertEqual($absolute->getPath(), '/');
+ }
+
+ function testMakingARootPageUrlAbsolute() {
+ $url = new SimpleUrl('/here.html');
+ $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html');
+ $this->assertEqual($absolute->getPath(), '/here.html');
+ }
+
+ function testCarryAuthenticationFromRootPage() {
+ $url = new SimpleUrl('here.html');
+ $absolute = $url->makeAbsolute('http://test:secret@host.com/');
+ $this->assertEqual($absolute->getPath(), '/here.html');
+ $this->assertEqual($absolute->getUsername(), 'test');
+ $this->assertEqual($absolute->getPassword(), 'secret');
+ }
+
+ function testMakingCoordinateUrlAbsolute() {
+ $url = new SimpleUrl('?1,2');
+ $this->assertEqual($url->getPath(), '');
+ $absolute = $url->makeAbsolute('http://host.com/I/am/here/');
+ $this->assertEqual($absolute->getScheme(), 'http');
+ $this->assertEqual($absolute->getHost(), 'host.com');
+ $this->assertEqual($absolute->getPath(), '/I/am/here/');
+ $this->assertEqual($absolute->getX(), 1);
+ $this->assertEqual($absolute->getY(), 2);
+ }
+
+ function testMakingAbsoluteAppendedPath() {
+ $url = new SimpleUrl('./there/somewhere.php');
+ $absolute = $url->makeAbsolute('https://host.com/here/');
+ $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php');
+ }
+
+ function testMakingAbsoluteBadlyFormedAppendedPath() {
+ $url = new SimpleUrl('there/somewhere.php');
+ $absolute = $url->makeAbsolute('https://host.com/here/');
+ $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php');
+ }
+
+ function testMakingAbsoluteHasNoEffectWhenAlreadyAbsolute() {
+ $url = new SimpleUrl('https://test:secret@www.lastcraft.com:321/stuff/?a=1#f');
+ $absolute = $url->makeAbsolute('http://host.com/here/');
+ $this->assertEqual($absolute->getScheme(), 'https');
+ $this->assertEqual($absolute->getUsername(), 'test');
+ $this->assertEqual($absolute->getPassword(), 'secret');
+ $this->assertEqual($absolute->getHost(), 'www.lastcraft.com');
+ $this->assertEqual($absolute->getPort(), 321);
+ $this->assertEqual($absolute->getPath(), '/stuff/');
+ $this->assertEqual($absolute->getEncodedRequest(), '?a=1');
+ $this->assertEqual($absolute->getFragment(), 'f');
+ }
+
+ function testMakingAbsoluteCarriesAuthenticationWhenAlreadyAbsolute() {
+ $url = new SimpleUrl('https://www.lastcraft.com');
+ $absolute = $url->makeAbsolute('http://test:secret@host.com/here/');
+ $this->assertEqual($absolute->getHost(), 'www.lastcraft.com');
+ $this->assertEqual($absolute->getUsername(), 'test');
+ $this->assertEqual($absolute->getPassword(), 'secret');
+ }
+
+ function testMakingHostOnlyAbsoluteDoesNotCarryAnyOtherInformation() {
+ $url = new SimpleUrl('http://www.lastcraft.com');
+ $absolute = $url->makeAbsolute('https://host.com:81/here/');
+ $this->assertEqual($absolute->getScheme(), 'http');
+ $this->assertEqual($absolute->getHost(), 'www.lastcraft.com');
+ $this->assertIdentical($absolute->getPort(), false);
+ $this->assertEqual($absolute->getPath(), '/');
+ }
+}
+
+class TestOfFrameUrl extends UnitTestCase {
+
+ function testTargetAttachment() {
+ $url = new SimpleUrl('http://www.site.com/home.html');
+ $this->assertIdentical($url->getTarget(), false);
+ $url->setTarget('A frame');
+ $this->assertIdentical($url->getTarget(), 'A frame');
+ }
+}
+
+/**
+ * @note Based off of http://www.mozilla.org/quality/networking/testing/filetests.html
+ */
+class TestOfFileUrl extends UnitTestCase {
+
+ function testMinimalUrl() {
+ $url = new SimpleUrl('file:///');
+ $this->assertEqual($url->getScheme(), 'file');
+ $this->assertIdentical($url->getHost(), false);
+ $this->assertEqual($url->getPath(), '/');
+ }
+
+ function testUnixUrl() {
+ $url = new SimpleUrl('file:///fileInRoot');
+ $this->assertEqual($url->getScheme(), 'file');
+ $this->assertIdentical($url->getHost(), false);
+ $this->assertEqual($url->getPath(), '/fileInRoot');
+ }
+
+ function testDOSVolumeUrl() {
+ $url = new SimpleUrl('file:///C:/config.sys');
+ $this->assertEqual($url->getScheme(), 'file');
+ $this->assertIdentical($url->getHost(), false);
+ $this->assertEqual($url->getPath(), '/C:/config.sys');
+ }
+
+ function testDOSVolumePromotion() {
+ $url = new SimpleUrl('file://C:/config.sys');
+ $this->assertEqual($url->getScheme(), 'file');
+ $this->assertIdentical($url->getHost(), false);
+ $this->assertEqual($url->getPath(), '/C:/config.sys');
+ }
+
+ function testDOSBackslashes() {
+ $url = new SimpleUrl('file:///C:\config.sys');
+ $this->assertEqual($url->getScheme(), 'file');
+ $this->assertIdentical($url->getHost(), false);
+ $this->assertEqual($url->getPath(), '/C:/config.sys');
+ }
+
+ function testDOSDirnameAfterFile() {
+ $url = new SimpleUrl('file://C:\config.sys');
+ $this->assertEqual($url->getScheme(), 'file');
+ $this->assertIdentical($url->getHost(), false);
+ $this->assertEqual($url->getPath(), '/C:/config.sys');
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/user_agent_test.php b/3rdparty/simpletest/test/user_agent_test.php
new file mode 100755
index 00000000000..030abeb257d
--- /dev/null
+++ b/3rdparty/simpletest/test/user_agent_test.php
@@ -0,0 +1,348 @@
+<?php
+// $Id: user_agent_test.php 1788 2008-04-27 11:01:59Z pp11 $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../user_agent.php');
+require_once(dirname(__FILE__) . '/../authentication.php');
+require_once(dirname(__FILE__) . '/../http.php');
+require_once(dirname(__FILE__) . '/../encoding.php');
+Mock::generate('SimpleHttpRequest');
+Mock::generate('SimpleHttpResponse');
+Mock::generate('SimpleHttpHeaders');
+Mock::generatePartial('SimpleUserAgent', 'MockRequestUserAgent', array('createHttpRequest'));
+
+class TestOfFetchingUrlParameters extends UnitTestCase {
+
+ function setUp() {
+ $this->headers = new MockSimpleHttpHeaders();
+ $this->response = new MockSimpleHttpResponse();
+ $this->response->setReturnValue('isError', false);
+ $this->response->returns('getHeaders', new MockSimpleHttpHeaders());
+ $this->request = new MockSimpleHttpRequest();
+ $this->request->returns('fetch', $this->response);
+ }
+
+ function testGetRequestWithoutIncidentGivesNoErrors() {
+ $url = new SimpleUrl('http://test:secret@this.com/page.html');
+ $url->addRequestParameters(array('a' => 'A', 'b' => 'B'));
+
+ $agent = new MockRequestUserAgent();
+ $agent->returns('createHttpRequest', $this->request);
+ $agent->__construct();
+
+ $response = $agent->fetchResponse(
+ new SimpleUrl('http://test:secret@this.com/page.html'),
+ new SimpleGetEncoding(array('a' => 'A', 'b' => 'B')));
+ $this->assertFalse($response->isError());
+ }
+}
+
+class TestOfAdditionalHeaders extends UnitTestCase {
+
+ function testAdditionalHeaderAddedToRequest() {
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders());
+
+ $request = new MockSimpleHttpRequest();
+ $request->setReturnReference('fetch', $response);
+ $request->expectOnce(
+ 'addHeaderLine',
+ array('User-Agent: SimpleTest'));
+
+ $agent = new MockRequestUserAgent();
+ $agent->setReturnReference('createHttpRequest', $request);
+ $agent->__construct();
+ $agent->addHeader('User-Agent: SimpleTest');
+ $response = $agent->fetchResponse(new SimpleUrl('http://this.host/'), new SimpleGetEncoding());
+ }
+}
+
+class TestOfBrowserCookies extends UnitTestCase {
+
+ private function createStandardResponse() {
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue("isError", false);
+ $response->setReturnValue("getContent", "stuff");
+ $response->setReturnReference("getHeaders", new MockSimpleHttpHeaders());
+ return $response;
+ }
+
+ private function createCookieSite($header_lines) {
+ $headers = new SimpleHttpHeaders($header_lines);
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue("isError", false);
+ $response->setReturnReference("getHeaders", $headers);
+ $response->setReturnValue("getContent", "stuff");
+ $request = new MockSimpleHttpRequest();
+ $request->setReturnReference("fetch", $response);
+ return $request;
+ }
+
+ private function createMockedRequestUserAgent(&$request) {
+ $agent = new MockRequestUserAgent();
+ $agent->setReturnReference('createHttpRequest', $request);
+ $agent->__construct();
+ return $agent;
+ }
+
+ function testCookieJarIsSentToRequest() {
+ $jar = new SimpleCookieJar();
+ $jar->setCookie('a', 'A');
+
+ $request = new MockSimpleHttpRequest();
+ $request->returns('fetch', $this->createStandardResponse());
+ $request->expectOnce('readCookiesFromJar', array($jar, '*'));
+
+ $agent = $this->createMockedRequestUserAgent($request);
+ $agent->setCookie('a', 'A');
+ $agent->fetchResponse(
+ new SimpleUrl('http://this.com/this/path/page.html'),
+ new SimpleGetEncoding());
+ }
+
+ function testNoCookieJarIsSentToRequestWhenCookiesAreDisabled() {
+ $request = new MockSimpleHttpRequest();
+ $request->returns('fetch', $this->createStandardResponse());
+ $request->expectNever('readCookiesFromJar');
+
+ $agent = $this->createMockedRequestUserAgent($request);
+ $agent->setCookie('a', 'A');
+ $agent->ignoreCookies();
+ $agent->fetchResponse(
+ new SimpleUrl('http://this.com/this/path/page.html'),
+ new SimpleGetEncoding());
+ }
+
+ function testReadingNewCookie() {
+ $request = $this->createCookieSite('Set-cookie: a=AAAA');
+ $agent = $this->createMockedRequestUserAgent($request);
+ $agent->fetchResponse(
+ new SimpleUrl('http://this.com/this/path/page.html'),
+ new SimpleGetEncoding());
+ $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA");
+ }
+
+ function testIgnoringNewCookieWhenCookiesDisabled() {
+ $request = $this->createCookieSite('Set-cookie: a=AAAA');
+ $agent = $this->createMockedRequestUserAgent($request);
+ $agent->ignoreCookies();
+ $agent->fetchResponse(
+ new SimpleUrl('http://this.com/this/path/page.html'),
+ new SimpleGetEncoding());
+ $this->assertIdentical($agent->getCookieValue("this.com", "this/path/", "a"), false);
+ }
+
+ function testOverwriteCookieThatAlreadyExists() {
+ $request = $this->createCookieSite('Set-cookie: a=AAAA');
+ $agent = $this->createMockedRequestUserAgent($request);
+ $agent->setCookie('a', 'A');
+ $agent->fetchResponse(
+ new SimpleUrl('http://this.com/this/path/page.html'),
+ new SimpleGetEncoding());
+ $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA");
+ }
+
+ function testClearCookieBySettingExpiry() {
+ $request = $this->createCookieSite('Set-cookie: a=b');
+ $agent = $this->createMockedRequestUserAgent($request);
+
+ $agent->setCookie("a", "A", "this/path/", "Wed, 25-Dec-02 04:24:21 GMT");
+ $agent->fetchResponse(
+ new SimpleUrl('http://this.com/this/path/page.html'),
+ new SimpleGetEncoding());
+ $this->assertIdentical(
+ $agent->getCookieValue("this.com", "this/path/", "a"),
+ "b");
+ $agent->restart("Wed, 25-Dec-02 04:24:20 GMT");
+ $this->assertIdentical(
+ $agent->getCookieValue("this.com", "this/path/", "a"),
+ false);
+ }
+
+ function testAgeingAndClearing() {
+ $request = $this->createCookieSite('Set-cookie: a=A; expires=Wed, 25-Dec-02 04:24:21 GMT; path=/this/path');
+ $agent = $this->createMockedRequestUserAgent($request);
+
+ $agent->fetchResponse(
+ new SimpleUrl('http://this.com/this/path/page.html'),
+ new SimpleGetEncoding());
+ $agent->restart("Wed, 25-Dec-02 04:24:20 GMT");
+ $this->assertIdentical(
+ $agent->getCookieValue("this.com", "this/path/", "a"),
+ "A");
+ $agent->ageCookies(2);
+ $agent->restart("Wed, 25-Dec-02 04:24:20 GMT");
+ $this->assertIdentical(
+ $agent->getCookieValue("this.com", "this/path/", "a"),
+ false);
+ }
+
+ function testReadingIncomingAndSettingNewCookies() {
+ $request = $this->createCookieSite('Set-cookie: a=AAA');
+ $agent = $this->createMockedRequestUserAgent($request);
+
+ $this->assertNull($agent->getBaseCookieValue("a", false));
+ $agent->fetchResponse(
+ new SimpleUrl('http://this.com/this/path/page.html'),
+ new SimpleGetEncoding());
+ $agent->setCookie("b", "BBB", "this.com", "this/path/");
+ $this->assertEqual(
+ $agent->getBaseCookieValue("a", new SimpleUrl('http://this.com/this/path/page.html')),
+ "AAA");
+ $this->assertEqual(
+ $agent->getBaseCookieValue("b", new SimpleUrl('http://this.com/this/path/page.html')),
+ "BBB");
+ }
+}
+
+class TestOfHttpRedirects extends UnitTestCase {
+
+ function createRedirect($content, $redirect) {
+ $headers = new MockSimpleHttpHeaders();
+ $headers->setReturnValue('isRedirect', (boolean)$redirect);
+ $headers->setReturnValue('getLocation', $redirect);
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue('getContent', $content);
+ $response->setReturnReference('getHeaders', $headers);
+ $request = new MockSimpleHttpRequest();
+ $request->setReturnReference('fetch', $response);
+ return $request;
+ }
+
+ function testDisabledRedirects() {
+ $agent = new MockRequestUserAgent();
+ $agent->returns(
+ 'createHttpRequest',
+ $this->createRedirect('stuff', 'there.html'));
+ $agent->expectOnce('createHttpRequest');
+ $agent->__construct();
+ $agent->setMaximumRedirects(0);
+ $response = $agent->fetchResponse(new SimpleUrl('here.html'), new SimpleGetEncoding());
+ $this->assertEqual($response->getContent(), 'stuff');
+ }
+
+ function testSingleRedirect() {
+ $agent = new MockRequestUserAgent();
+ $agent->returnsAt(
+ 0,
+ 'createHttpRequest',
+ $this->createRedirect('first', 'two.html'));
+ $agent->returnsAt(
+ 1,
+ 'createHttpRequest',
+ $this->createRedirect('second', 'three.html'));
+ $agent->expectCallCount('createHttpRequest', 2);
+ $agent->__construct();
+
+ $agent->setMaximumRedirects(1);
+ $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding());
+ $this->assertEqual($response->getContent(), 'second');
+ }
+
+ function testDoubleRedirect() {
+ $agent = new MockRequestUserAgent();
+ $agent->returnsAt(
+ 0,
+ 'createHttpRequest',
+ $this->createRedirect('first', 'two.html'));
+ $agent->returnsAt(
+ 1,
+ 'createHttpRequest',
+ $this->createRedirect('second', 'three.html'));
+ $agent->returnsAt(
+ 2,
+ 'createHttpRequest',
+ $this->createRedirect('third', 'four.html'));
+ $agent->expectCallCount('createHttpRequest', 3);
+ $agent->__construct();
+
+ $agent->setMaximumRedirects(2);
+ $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding());
+ $this->assertEqual($response->getContent(), 'third');
+ }
+
+ function testSuccessAfterRedirect() {
+ $agent = new MockRequestUserAgent();
+ $agent->returnsAt(
+ 0,
+ 'createHttpRequest',
+ $this->createRedirect('first', 'two.html'));
+ $agent->returnsAt(
+ 1,
+ 'createHttpRequest',
+ $this->createRedirect('second', false));
+ $agent->returnsAt(
+ 2,
+ 'createHttpRequest',
+ $this->createRedirect('third', 'four.html'));
+ $agent->expectCallCount('createHttpRequest', 2);
+ $agent->__construct();
+
+ $agent->setMaximumRedirects(2);
+ $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding());
+ $this->assertEqual($response->getContent(), 'second');
+ }
+
+ function testRedirectChangesPostToGet() {
+ $agent = new MockRequestUserAgent();
+ $agent->returnsAt(
+ 0,
+ 'createHttpRequest',
+ $this->createRedirect('first', 'two.html'));
+ $agent->expectAt(0, 'createHttpRequest', array('*', new IsAExpectation('SimplePostEncoding')));
+ $agent->returnsAt(
+ 1,
+ 'createHttpRequest',
+ $this->createRedirect('second', 'three.html'));
+ $agent->expectAt(1, 'createHttpRequest', array('*', new IsAExpectation('SimpleGetEncoding')));
+ $agent->expectCallCount('createHttpRequest', 2);
+ $agent->__construct();
+ $agent->setMaximumRedirects(1);
+ $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimplePostEncoding());
+ }
+}
+
+class TestOfBadHosts extends UnitTestCase {
+
+ private function createSimulatedBadHost() {
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnValue('isError', true);
+ $response->setReturnValue('getError', 'Bad socket');
+ $response->setReturnValue('getContent', false);
+ $request = new MockSimpleHttpRequest();
+ $request->setReturnReference('fetch', $response);
+ return $request;
+ }
+
+ function testUntestedHost() {
+ $request = $this->createSimulatedBadHost();
+ $agent = new MockRequestUserAgent();
+ $agent->setReturnReference('createHttpRequest', $request);
+ $agent->__construct();
+ $response = $agent->fetchResponse(
+ new SimpleUrl('http://this.host/this/path/page.html'),
+ new SimpleGetEncoding());
+ $this->assertTrue($response->isError());
+ }
+}
+
+class TestOfAuthorisation extends UnitTestCase {
+
+ function testAuthenticateHeaderAdded() {
+ $response = new MockSimpleHttpResponse();
+ $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders());
+
+ $request = new MockSimpleHttpRequest();
+ $request->returns('fetch', $response);
+ $request->expectOnce(
+ 'addHeaderLine',
+ array('Authorization: Basic ' . base64_encode('test:secret')));
+
+ $agent = new MockRequestUserAgent();
+ $agent->returns('createHttpRequest', $request);
+ $agent->__construct();
+ $response = $agent->fetchResponse(
+ new SimpleUrl('http://test:secret@this.host'),
+ new SimpleGetEncoding());
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/visual_test.php b/3rdparty/simpletest/test/visual_test.php
new file mode 100755
index 00000000000..6b9d085d67f
--- /dev/null
+++ b/3rdparty/simpletest/test/visual_test.php
@@ -0,0 +1,495 @@
+<?php
+// $Id: visual_test.php 1884 2009-07-01 16:30:40Z lastcraft $
+
+// NOTE:
+// Some of these tests are designed to fail! Do not be alarmed.
+// ----------------
+
+// The following tests are a bit hacky. Whilst Kent Beck tried to
+// build a unit tester with a unit tester, I am not that brave.
+// Instead I have just hacked together odd test scripts until
+// I have enough of a tester to procede more formally.
+//
+// The proper tests start in all_tests.php
+require_once('../unit_tester.php');
+require_once('../shell_tester.php');
+require_once('../mock_objects.php');
+require_once('../reporter.php');
+require_once('../xml.php');
+
+class TestDisplayClass {
+ private $a;
+
+ function TestDisplayClass($a) {
+ $this->a = $a;
+ }
+}
+
+class PassingUnitTestCaseOutput extends UnitTestCase {
+
+ function testOfResults() {
+ $this->pass('Pass');
+ }
+
+ function testTrue() {
+ $this->assertTrue(true);
+ }
+
+ function testFalse() {
+ $this->assertFalse(false);
+ }
+
+ function testExpectation() {
+ $expectation = &new EqualExpectation(25, 'My expectation message: %s');
+ $this->assert($expectation, 25, 'My assert message : %s');
+ }
+
+ function testNull() {
+ $this->assertNull(null, "%s -> Pass");
+ $this->assertNotNull(false, "%s -> Pass");
+ }
+
+ function testType() {
+ $this->assertIsA("hello", "string", "%s -> Pass");
+ $this->assertIsA($this, "PassingUnitTestCaseOutput", "%s -> Pass");
+ $this->assertIsA($this, "UnitTestCase", "%s -> Pass");
+ }
+
+ function testTypeEquality() {
+ $this->assertEqual("0", 0, "%s -> Pass");
+ }
+
+ function testNullEquality() {
+ $this->assertNotEqual(null, 1, "%s -> Pass");
+ $this->assertNotEqual(1, null, "%s -> Pass");
+ }
+
+ function testIntegerEquality() {
+ $this->assertNotEqual(1, 2, "%s -> Pass");
+ }
+
+ function testStringEquality() {
+ $this->assertEqual("a", "a", "%s -> Pass");
+ $this->assertNotEqual("aa", "ab", "%s -> Pass");
+ }
+
+ function testHashEquality() {
+ $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> Pass");
+ }
+
+ function testWithin() {
+ $this->assertWithinMargin(5, 5.4, 0.5, "%s -> Pass");
+ }
+
+ function testOutside() {
+ $this->assertOutsideMargin(5, 5.6, 0.5, "%s -> Pass");
+ }
+
+ function testStringIdentity() {
+ $a = "fred";
+ $b = $a;
+ $this->assertIdentical($a, $b, "%s -> Pass");
+ }
+
+ function testTypeIdentity() {
+ $a = "0";
+ $b = 0;
+ $this->assertNotIdentical($a, $b, "%s -> Pass");
+ }
+
+ function testNullIdentity() {
+ $this->assertNotIdentical(null, 1, "%s -> Pass");
+ $this->assertNotIdentical(1, null, "%s -> Pass");
+ }
+
+ function testHashIdentity() {
+ }
+
+ function testObjectEquality() {
+ $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Pass");
+ $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Pass");
+ }
+
+ function testObjectIndentity() {
+ $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Pass");
+ $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Pass");
+ }
+
+ function testReference() {
+ $a = "fred";
+ $b = &$a;
+ $this->assertReference($a, $b, "%s -> Pass");
+ }
+
+ function testCloneOnDifferentObjects() {
+ $a = "fred";
+ $b = $a;
+ $c = "Hello";
+ $this->assertClone($a, $b, "%s -> Pass");
+ }
+
+ function testPatterns() {
+ $this->assertPattern('/hello/i', "Hello there", "%s -> Pass");
+ $this->assertNoPattern('/hello/', "Hello there", "%s -> Pass");
+ }
+
+ function testLongStrings() {
+ $text = "";
+ for ($i = 0; $i < 10; $i++) {
+ $text .= "0123456789";
+ }
+ $this->assertEqual($text, $text);
+ }
+}
+
+class FailingUnitTestCaseOutput extends UnitTestCase {
+
+ function testOfResults() {
+ $this->fail('Fail'); // Fail.
+ }
+
+ function testTrue() {
+ $this->assertTrue(false); // Fail.
+ }
+
+ function testFalse() {
+ $this->assertFalse(true); // Fail.
+ }
+
+ function testExpectation() {
+ $expectation = &new EqualExpectation(25, 'My expectation message: %s');
+ $this->assert($expectation, 24, 'My assert message : %s'); // Fail.
+ }
+
+ function testNull() {
+ $this->assertNull(false, "%s -> Fail"); // Fail.
+ $this->assertNotNull(null, "%s -> Fail"); // Fail.
+ }
+
+ function testType() {
+ $this->assertIsA(14, "string", "%s -> Fail"); // Fail.
+ $this->assertIsA(14, "TestOfUnitTestCaseOutput", "%s -> Fail"); // Fail.
+ $this->assertIsA($this, "TestReporter", "%s -> Fail"); // Fail.
+ }
+
+ function testTypeEquality() {
+ $this->assertNotEqual("0", 0, "%s -> Fail"); // Fail.
+ }
+
+ function testNullEquality() {
+ $this->assertEqual(null, 1, "%s -> Fail"); // Fail.
+ $this->assertEqual(1, null, "%s -> Fail"); // Fail.
+ }
+
+ function testIntegerEquality() {
+ $this->assertEqual(1, 2, "%s -> Fail"); // Fail.
+ }
+
+ function testStringEquality() {
+ $this->assertNotEqual("a", "a", "%s -> Fail"); // Fail.
+ $this->assertEqual("aa", "ab", "%s -> Fail"); // Fail.
+ }
+
+ function testHashEquality() {
+ $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "Z"), "%s -> Fail");
+ }
+
+ function testWithin() {
+ $this->assertWithinMargin(5, 5.6, 0.5, "%s -> Fail"); // Fail.
+ }
+
+ function testOutside() {
+ $this->assertOutsideMargin(5, 5.4, 0.5, "%s -> Fail"); // Fail.
+ }
+
+ function testStringIdentity() {
+ $a = "fred";
+ $b = $a;
+ $this->assertNotIdentical($a, $b, "%s -> Fail"); // Fail.
+ }
+
+ function testTypeIdentity() {
+ $a = "0";
+ $b = 0;
+ $this->assertIdentical($a, $b, "%s -> Fail"); // Fail.
+ }
+
+ function testNullIdentity() {
+ $this->assertIdentical(null, 1, "%s -> Fail"); // Fail.
+ $this->assertIdentical(1, null, "%s -> Fail"); // Fail.
+ }
+
+ function testHashIdentity() {
+ $this->assertIdentical(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> fail"); // Fail.
+ }
+
+ function testObjectEquality() {
+ $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Fail"); // Fail.
+ $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Fail"); // Fail.
+ }
+
+ function testObjectIndentity() {
+ $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Fail"); // Fail.
+ $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Fail"); // Fail.
+ }
+
+ function testReference() {
+ $a = "fred";
+ $b = &$a;
+ $this->assertClone($a, $b, "%s -> Fail"); // Fail.
+ }
+
+ function testCloneOnDifferentObjects() {
+ $a = "fred";
+ $b = $a;
+ $c = "Hello";
+ $this->assertClone($a, $c, "%s -> Fail"); // Fail.
+ }
+
+ function testPatterns() {
+ $this->assertPattern('/hello/', "Hello there", "%s -> Fail"); // Fail.
+ $this->assertNoPattern('/hello/i', "Hello there", "%s -> Fail"); // Fail.
+ }
+
+ function testLongStrings() {
+ $text = "";
+ for ($i = 0; $i < 10; $i++) {
+ $text .= "0123456789";
+ }
+ $this->assertEqual($text . $text, $text . "a" . $text); // Fail.
+ }
+}
+
+class Dummy {
+ function Dummy() {
+ }
+
+ function a() {
+ }
+}
+Mock::generate('Dummy');
+
+class TestOfMockObjectsOutput extends UnitTestCase {
+
+ function testCallCounts() {
+ $dummy = &new MockDummy();
+ $dummy->expectCallCount('a', 1, 'My message: %s');
+ $dummy->a();
+ $dummy->a();
+ }
+
+ function testMinimumCallCounts() {
+ $dummy = &new MockDummy();
+ $dummy->expectMinimumCallCount('a', 2, 'My message: %s');
+ $dummy->a();
+ $dummy->a();
+ }
+
+ function testEmptyMatching() {
+ $dummy = &new MockDummy();
+ $dummy->expect('a', array());
+ $dummy->a();
+ $dummy->a(null); // Fail.
+ }
+
+ function testEmptyMatchingWithCustomMessage() {
+ $dummy = &new MockDummy();
+ $dummy->expect('a', array(), 'My expectation message: %s');
+ $dummy->a();
+ $dummy->a(null); // Fail.
+ }
+
+ function testNullMatching() {
+ $dummy = &new MockDummy();
+ $dummy->expect('a', array(null));
+ $dummy->a(null);
+ $dummy->a(); // Fail.
+ }
+
+ function testBooleanMatching() {
+ $dummy = &new MockDummy();
+ $dummy->expect('a', array(true, false));
+ $dummy->a(true, false);
+ $dummy->a(true, true); // Fail.
+ }
+
+ function testIntegerMatching() {
+ $dummy = &new MockDummy();
+ $dummy->expect('a', array(32, 33));
+ $dummy->a(32, 33);
+ $dummy->a(32, 34); // Fail.
+ }
+
+ function testFloatMatching() {
+ $dummy = &new MockDummy();
+ $dummy->expect('a', array(3.2, 3.3));
+ $dummy->a(3.2, 3.3);
+ $dummy->a(3.2, 3.4); // Fail.
+ }
+
+ function testStringMatching() {
+ $dummy = &new MockDummy();
+ $dummy->expect('a', array('32', '33'));
+ $dummy->a('32', '33');
+ $dummy->a('32', '34'); // Fail.
+ }
+
+ function testEmptyMatchingWithCustomExpectationMessage() {
+ $dummy = &new MockDummy();
+ $dummy->expect(
+ 'a',
+ array(new EqualExpectation('A', 'My part expectation message: %s')),
+ 'My expectation message: %s');
+ $dummy->a('A');
+ $dummy->a('B'); // Fail.
+ }
+
+ function testArrayMatching() {
+ $dummy = &new MockDummy();
+ $dummy->expect('a', array(array(32), array(33)));
+ $dummy->a(array(32), array(33));
+ $dummy->a(array(32), array('33')); // Fail.
+ }
+
+ function testObjectMatching() {
+ $a = new Dummy();
+ $a->a = 'a';
+ $b = new Dummy();
+ $b->b = 'b';
+ $dummy = &new MockDummy();
+ $dummy->expect('a', array($a, $b));
+ $dummy->a($a, $b);
+ $dummy->a($a, $a); // Fail.
+ }
+
+ function testBigList() {
+ $dummy = &new MockDummy();
+ $dummy->expect('a', array(false, 0, 1, 1.0));
+ $dummy->a(false, 0, 1, 1.0);
+ $dummy->a(true, false, 2, 2.0); // Fail.
+ }
+}
+
+class TestOfPastBugs extends UnitTestCase {
+
+ function testMixedTypes() {
+ $this->assertEqual(array(), null, "%s -> Pass");
+ $this->assertIdentical(array(), null, "%s -> Fail"); // Fail.
+ }
+
+ function testMockWildcards() {
+ $dummy = &new MockDummy();
+ $dummy->expect('a', array('*', array(33)));
+ $dummy->a(array(32), array(33));
+ $dummy->a(array(32), array('33')); // Fail.
+ }
+}
+
+class TestOfVisualShell extends ShellTestCase {
+
+ function testDump() {
+ $this->execute('ls');
+ $this->dumpOutput();
+ $this->execute('dir');
+ $this->dumpOutput();
+ }
+
+ function testDumpOfList() {
+ $this->execute('ls');
+ $this->dump($this->getOutputAsList());
+ }
+}
+
+class PassesAsWellReporter extends HtmlReporter {
+
+ protected function getCss() {
+ return parent::getCss() . ' .pass { color: darkgreen; }';
+ }
+
+ function paintPass($message) {
+ parent::paintPass($message);
+ print "<span class=\"pass\">Pass</span>: ";
+ $breadcrumb = $this->getTestList();
+ array_shift($breadcrumb);
+ print implode(" -&gt; ", $breadcrumb);
+ print " -&gt; " . htmlentities($message) . "<br />\n";
+ }
+
+ function paintSignal($type, &$payload) {
+ print "<span class=\"fail\">$type</span>: ";
+ $breadcrumb = $this->getTestList();
+ array_shift($breadcrumb);
+ print implode(" -&gt; ", $breadcrumb);
+ print " -&gt; " . htmlentities(serialize($payload)) . "<br />\n";
+ }
+}
+
+class TestOfSkippingNoMatterWhat extends UnitTestCase {
+ function skip() {
+ $this->skipIf(true, 'Always skipped -> %s');
+ }
+
+ function testFail() {
+ $this->fail('This really shouldn\'t have happened');
+ }
+}
+
+class TestOfSkippingOrElse extends UnitTestCase {
+ function skip() {
+ $this->skipUnless(false, 'Always skipped -> %s');
+ }
+
+ function testFail() {
+ $this->fail('This really shouldn\'t have happened');
+ }
+}
+
+class TestOfSkippingTwiceOver extends UnitTestCase {
+ function skip() {
+ $this->skipIf(true, 'First reason -> %s');
+ $this->skipIf(true, 'Second reason -> %s');
+ }
+
+ function testFail() {
+ $this->fail('This really shouldn\'t have happened');
+ }
+}
+
+class TestThatShouldNotBeSkipped extends UnitTestCase {
+ function skip() {
+ $this->skipIf(false);
+ $this->skipUnless(true);
+ }
+
+ function testFail() {
+ $this->fail('We should see this message');
+ }
+
+ function testPass() {
+ $this->pass('We should see this message');
+ }
+}
+
+$test = &new TestSuite('Visual test with 46 passes, 47 fails and 0 exceptions');
+$test->add(new PassingUnitTestCaseOutput());
+$test->add(new FailingUnitTestCaseOutput());
+$test->add(new TestOfMockObjectsOutput());
+$test->add(new TestOfPastBugs());
+$test->add(new TestOfVisualShell());
+$test->add(new TestOfSkippingNoMatterWhat());
+$test->add(new TestOfSkippingOrElse());
+$test->add(new TestOfSkippingTwiceOver());
+$test->add(new TestThatShouldNotBeSkipped());
+
+if (isset($_GET['xml']) || in_array('xml', (isset($argv) ? $argv : array()))) {
+ $reporter = new XmlReporter();
+} elseif (TextReporter::inCli()) {
+ $reporter = new TextReporter();
+} else {
+ $reporter = new PassesAsWellReporter();
+}
+if (isset($_GET['dry']) || in_array('dry', (isset($argv) ? $argv : array()))) {
+ $reporter->makeDry();
+}
+exit ($test->run($reporter) ? 0 : 1);
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/web_tester_test.php b/3rdparty/simpletest/test/web_tester_test.php
new file mode 100755
index 00000000000..8c3bf1adf63
--- /dev/null
+++ b/3rdparty/simpletest/test/web_tester_test.php
@@ -0,0 +1,155 @@
+<?php
+// $Id: web_tester_test.php 1748 2008-04-14 01:50:41Z lastcraft $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../web_tester.php');
+
+class TestOfFieldExpectation extends UnitTestCase {
+
+ function testStringMatchingIsCaseSensitive() {
+ $expectation = new FieldExpectation('a');
+ $this->assertTrue($expectation->test('a'));
+ $this->assertTrue($expectation->test(array('a')));
+ $this->assertFalse($expectation->test('A'));
+ }
+
+ function testMatchesInteger() {
+ $expectation = new FieldExpectation('1');
+ $this->assertTrue($expectation->test('1'));
+ $this->assertTrue($expectation->test(1));
+ $this->assertTrue($expectation->test(array('1')));
+ $this->assertTrue($expectation->test(array(1)));
+ }
+
+ function testNonStringFailsExpectation() {
+ $expectation = new FieldExpectation('a');
+ $this->assertFalse($expectation->test(null));
+ }
+
+ function testUnsetFieldCanBeTestedFor() {
+ $expectation = new FieldExpectation(false);
+ $this->assertTrue($expectation->test(false));
+ }
+
+ function testMultipleValuesCanBeInAnyOrder() {
+ $expectation = new FieldExpectation(array('a', 'b'));
+ $this->assertTrue($expectation->test(array('a', 'b')));
+ $this->assertTrue($expectation->test(array('b', 'a')));
+ $this->assertFalse($expectation->test(array('a', 'a')));
+ $this->assertFalse($expectation->test('a'));
+ }
+
+ function testSingleItemCanBeArrayOrString() {
+ $expectation = new FieldExpectation(array('a'));
+ $this->assertTrue($expectation->test(array('a')));
+ $this->assertTrue($expectation->test('a'));
+ }
+}
+
+class TestOfHeaderExpectations extends UnitTestCase {
+
+ function testExpectingOnlyTheHeaderName() {
+ $expectation = new HttpHeaderExpectation('a');
+ $this->assertIdentical($expectation->test(false), false);
+ $this->assertIdentical($expectation->test('a: A'), true);
+ $this->assertIdentical($expectation->test('A: A'), true);
+ $this->assertIdentical($expectation->test('a: B'), true);
+ $this->assertIdentical($expectation->test(' a : A '), true);
+ }
+
+ function testHeaderValueAsWell() {
+ $expectation = new HttpHeaderExpectation('a', 'A');
+ $this->assertIdentical($expectation->test(false), false);
+ $this->assertIdentical($expectation->test('a: A'), true);
+ $this->assertIdentical($expectation->test('A: A'), true);
+ $this->assertIdentical($expectation->test('A: a'), false);
+ $this->assertIdentical($expectation->test('a: B'), false);
+ $this->assertIdentical($expectation->test(' a : A '), true);
+ $this->assertIdentical($expectation->test(' a : AB '), false);
+ }
+
+ function testHeaderValueWithColons() {
+ $expectation = new HttpHeaderExpectation('a', 'A:B:C');
+ $this->assertIdentical($expectation->test('a: A'), false);
+ $this->assertIdentical($expectation->test('a: A:B'), false);
+ $this->assertIdentical($expectation->test('a: A:B:C'), true);
+ $this->assertIdentical($expectation->test('a: A:B:C:D'), false);
+ }
+
+ function testMultilineSearch() {
+ $expectation = new HttpHeaderExpectation('a', 'A');
+ $this->assertIdentical($expectation->test("aa: A\r\nb: B\r\nc: C"), false);
+ $this->assertIdentical($expectation->test("aa: A\r\na: A\r\nb: B"), true);
+ }
+
+ function testMultilineSearchWithPadding() {
+ $expectation = new HttpHeaderExpectation('a', ' A ');
+ $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), false);
+ $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), true);
+ }
+
+ function testPatternMatching() {
+ $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/'));
+ $this->assertIdentical($expectation->test('a: A'), true);
+ $this->assertIdentical($expectation->test('A: A'), true);
+ $this->assertIdentical($expectation->test('A: a'), false);
+ $this->assertIdentical($expectation->test('a: B'), false);
+ $this->assertIdentical($expectation->test(' a : A '), true);
+ $this->assertIdentical($expectation->test(' a : AB '), true);
+ }
+
+ function testCaseInsensitivePatternMatching() {
+ $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/i'));
+ $this->assertIdentical($expectation->test('a: a'), true);
+ $this->assertIdentical($expectation->test('a: B'), false);
+ $this->assertIdentical($expectation->test(' a : A '), true);
+ $this->assertIdentical($expectation->test(' a : BAB '), true);
+ $this->assertIdentical($expectation->test(' a : bab '), true);
+ }
+
+ function testUnwantedHeader() {
+ $expectation = new NoHttpHeaderExpectation('a');
+ $this->assertIdentical($expectation->test(''), true);
+ $this->assertIdentical($expectation->test('stuff'), true);
+ $this->assertIdentical($expectation->test('b: B'), true);
+ $this->assertIdentical($expectation->test('a: A'), false);
+ $this->assertIdentical($expectation->test('A: A'), false);
+ }
+
+ function testMultilineUnwantedSearch() {
+ $expectation = new NoHttpHeaderExpectation('a');
+ $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), true);
+ $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), false);
+ }
+
+ function testLocationHeaderSplitsCorrectly() {
+ $expectation = new HttpHeaderExpectation('Location', 'http://here/');
+ $this->assertIdentical($expectation->test('Location: http://here/'), true);
+ }
+}
+
+class TestOfTextExpectations extends UnitTestCase {
+
+ function testMatchingSubString() {
+ $expectation = new TextExpectation('wanted');
+ $this->assertIdentical($expectation->test(''), false);
+ $this->assertIdentical($expectation->test('Wanted'), false);
+ $this->assertIdentical($expectation->test('wanted'), true);
+ $this->assertIdentical($expectation->test('the wanted text is here'), true);
+ }
+
+ function testNotMatchingSubString() {
+ $expectation = new NoTextExpectation('wanted');
+ $this->assertIdentical($expectation->test(''), true);
+ $this->assertIdentical($expectation->test('Wanted'), true);
+ $this->assertIdentical($expectation->test('wanted'), false);
+ $this->assertIdentical($expectation->test('the wanted text is here'), false);
+ }
+}
+
+class TestOfGenericAssertionsInWebTester extends WebTestCase {
+ function testEquality() {
+ $this->assertEqual('a', 'a');
+ $this->assertNotEqual('a', 'A');
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test/xml_test.php b/3rdparty/simpletest/test/xml_test.php
new file mode 100755
index 00000000000..f99e0dcd98b
--- /dev/null
+++ b/3rdparty/simpletest/test/xml_test.php
@@ -0,0 +1,187 @@
+<?php
+// $Id: xml_test.php 1787 2008-04-26 20:35:39Z pp11 $
+require_once(dirname(__FILE__) . '/../autorun.php');
+require_once(dirname(__FILE__) . '/../xml.php');
+Mock::generate('SimpleScorer');
+
+if (! function_exists('xml_parser_create')) {
+ SimpleTest::ignore('TestOfXmlStructureParsing');
+ SimpleTest::ignore('TestOfXmlResultsParsing');
+}
+
+class TestOfNestingTags extends UnitTestCase {
+ function testGroupSize() {
+ $nesting = new NestingGroupTag(array('SIZE' => 2));
+ $this->assertEqual($nesting->getSize(), 2);
+ }
+}
+
+class TestOfXmlStructureParsing extends UnitTestCase {
+ function testValidXml() {
+ $listener = new MockSimpleScorer();
+ $listener->expectNever('paintGroupStart');
+ $listener->expectNever('paintGroupEnd');
+ $listener->expectNever('paintCaseStart');
+ $listener->expectNever('paintCaseEnd');
+ $parser = new SimpleTestXmlParser($listener);
+ $this->assertTrue($parser->parse("<?xml version=\"1.0\"?>\n"));
+ $this->assertTrue($parser->parse("<run>\n"));
+ $this->assertTrue($parser->parse("</run>\n"));
+ }
+
+ function testEmptyGroup() {
+ $listener = new MockSimpleScorer();
+ $listener->expectOnce('paintGroupStart', array('a_group', 7));
+ $listener->expectOnce('paintGroupEnd', array('a_group'));
+ $parser = new SimpleTestXmlParser($listener);
+ $parser->parse("<?xml version=\"1.0\"?>\n");
+ $parser->parse("<run>\n");
+ $this->assertTrue($parser->parse("<group size=\"7\">\n"));
+ $this->assertTrue($parser->parse("<name>a_group</name>\n"));
+ $this->assertTrue($parser->parse("</group>\n"));
+ $parser->parse("</run>\n");
+ }
+
+ function testEmptyCase() {
+ $listener = new MockSimpleScorer();
+ $listener->expectOnce('paintCaseStart', array('a_case'));
+ $listener->expectOnce('paintCaseEnd', array('a_case'));
+ $parser = new SimpleTestXmlParser($listener);
+ $parser->parse("<?xml version=\"1.0\"?>\n");
+ $parser->parse("<run>\n");
+ $this->assertTrue($parser->parse("<case>\n"));
+ $this->assertTrue($parser->parse("<name>a_case</name>\n"));
+ $this->assertTrue($parser->parse("</case>\n"));
+ $parser->parse("</run>\n");
+ }
+
+ function testEmptyMethod() {
+ $listener = new MockSimpleScorer();
+ $listener->expectOnce('paintCaseStart', array('a_case'));
+ $listener->expectOnce('paintCaseEnd', array('a_case'));
+ $listener->expectOnce('paintMethodStart', array('a_method'));
+ $listener->expectOnce('paintMethodEnd', array('a_method'));
+ $parser = new SimpleTestXmlParser($listener);
+ $parser->parse("<?xml version=\"1.0\"?>\n");
+ $parser->parse("<run>\n");
+ $parser->parse("<case>\n");
+ $parser->parse("<name>a_case</name>\n");
+ $this->assertTrue($parser->parse("<test>\n"));
+ $this->assertTrue($parser->parse("<name>a_method</name>\n"));
+ $this->assertTrue($parser->parse("</test>\n"));
+ $parser->parse("</case>\n");
+ $parser->parse("</run>\n");
+ }
+
+ function testNestedGroup() {
+ $listener = new MockSimpleScorer();
+ $listener->expectAt(0, 'paintGroupStart', array('a_group', 7));
+ $listener->expectAt(1, 'paintGroupStart', array('b_group', 3));
+ $listener->expectCallCount('paintGroupStart', 2);
+ $listener->expectAt(0, 'paintGroupEnd', array('b_group'));
+ $listener->expectAt(1, 'paintGroupEnd', array('a_group'));
+ $listener->expectCallCount('paintGroupEnd', 2);
+
+ $parser = new SimpleTestXmlParser($listener);
+ $parser->parse("<?xml version=\"1.0\"?>\n");
+ $parser->parse("<run>\n");
+
+ $this->assertTrue($parser->parse("<group size=\"7\">\n"));
+ $this->assertTrue($parser->parse("<name>a_group</name>\n"));
+ $this->assertTrue($parser->parse("<group size=\"3\">\n"));
+ $this->assertTrue($parser->parse("<name>b_group</name>\n"));
+ $this->assertTrue($parser->parse("</group>\n"));
+ $this->assertTrue($parser->parse("</group>\n"));
+ $parser->parse("</run>\n");
+ }
+}
+
+class AnyOldSignal {
+ public $stuff = true;
+}
+
+class TestOfXmlResultsParsing extends UnitTestCase {
+
+ function sendValidStart(&$parser) {
+ $parser->parse("<?xml version=\"1.0\"?>\n");
+ $parser->parse("<run>\n");
+ $parser->parse("<case>\n");
+ $parser->parse("<name>a_case</name>\n");
+ $parser->parse("<test>\n");
+ $parser->parse("<name>a_method</name>\n");
+ }
+
+ function sendValidEnd(&$parser) {
+ $parser->parse("</test>\n");
+ $parser->parse("</case>\n");
+ $parser->parse("</run>\n");
+ }
+
+ function testPass() {
+ $listener = new MockSimpleScorer();
+ $listener->expectOnce('paintPass', array('a_message'));
+ $parser = new SimpleTestXmlParser($listener);
+ $this->sendValidStart($parser);
+ $this->assertTrue($parser->parse("<pass>a_message</pass>\n"));
+ $this->sendValidEnd($parser);
+ }
+
+ function testFail() {
+ $listener = new MockSimpleScorer();
+ $listener->expectOnce('paintFail', array('a_message'));
+ $parser = new SimpleTestXmlParser($listener);
+ $this->sendValidStart($parser);
+ $this->assertTrue($parser->parse("<fail>a_message</fail>\n"));
+ $this->sendValidEnd($parser);
+ }
+
+ function testException() {
+ $listener = new MockSimpleScorer();
+ $listener->expectOnce('paintError', array('a_message'));
+ $parser = new SimpleTestXmlParser($listener);
+ $this->sendValidStart($parser);
+ $this->assertTrue($parser->parse("<exception>a_message</exception>\n"));
+ $this->sendValidEnd($parser);
+ }
+
+ function testSkip() {
+ $listener = new MockSimpleScorer();
+ $listener->expectOnce('paintSkip', array('a_message'));
+ $parser = new SimpleTestXmlParser($listener);
+ $this->sendValidStart($parser);
+ $this->assertTrue($parser->parse("<skip>a_message</skip>\n"));
+ $this->sendValidEnd($parser);
+ }
+
+ function testSignal() {
+ $signal = new AnyOldSignal();
+ $signal->stuff = "Hello";
+ $listener = new MockSimpleScorer();
+ $listener->expectOnce('paintSignal', array('a_signal', $signal));
+ $parser = new SimpleTestXmlParser($listener);
+ $this->sendValidStart($parser);
+ $this->assertTrue($parser->parse(
+ "<signal type=\"a_signal\"><![CDATA[" .
+ serialize($signal) . "]]></signal>\n"));
+ $this->sendValidEnd($parser);
+ }
+
+ function testMessage() {
+ $listener = new MockSimpleScorer();
+ $listener->expectOnce('paintMessage', array('a_message'));
+ $parser = new SimpleTestXmlParser($listener);
+ $this->sendValidStart($parser);
+ $this->assertTrue($parser->parse("<message>a_message</message>\n"));
+ $this->sendValidEnd($parser);
+ }
+
+ function testFormattedMessage() {
+ $listener = new MockSimpleScorer();
+ $listener->expectOnce('paintFormattedMessage', array("\na\tmessage\n"));
+ $parser = new SimpleTestXmlParser($listener);
+ $this->sendValidStart($parser);
+ $this->assertTrue($parser->parse("<formatted><![CDATA[\na\tmessage\n]]></formatted>\n"));
+ $this->sendValidEnd($parser);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/test_case.php b/3rdparty/simpletest/test_case.php
new file mode 100644
index 00000000000..ba023c3b2ea
--- /dev/null
+++ b/3rdparty/simpletest/test_case.php
@@ -0,0 +1,658 @@
+<?php
+/**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: test_case.php 2012 2011-04-29 08:57:00Z pp11 $
+ */
+
+/**#@+
+ * Includes SimpleTest files and defined the root constant
+ * for dependent libraries.
+ */
+require_once(dirname(__FILE__) . '/invoker.php');
+require_once(dirname(__FILE__) . '/errors.php');
+require_once(dirname(__FILE__) . '/compatibility.php');
+require_once(dirname(__FILE__) . '/scorer.php');
+require_once(dirname(__FILE__) . '/expectation.php');
+require_once(dirname(__FILE__) . '/dumper.php');
+require_once(dirname(__FILE__) . '/simpletest.php');
+require_once(dirname(__FILE__) . '/exceptions.php');
+require_once(dirname(__FILE__) . '/reflection_php5.php');
+/**#@-*/
+if (! defined('SIMPLE_TEST')) {
+ /**
+ * @ignore
+ */
+ define('SIMPLE_TEST', dirname(__FILE__) . DIRECTORY_SEPARATOR);
+}
+
+/**
+ * Basic test case. This is the smallest unit of a test
+ * suite. It searches for
+ * all methods that start with the the string "test" and
+ * runs them. Working test cases extend this class.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleTestCase {
+ private $label = false;
+ protected $reporter;
+ private $observers;
+ private $should_skip = false;
+
+ /**
+ * Sets up the test with no display.
+ * @param string $label If no test name is given then
+ * the class name is used.
+ * @access public
+ */
+ function __construct($label = false) {
+ if ($label) {
+ $this->label = $label;
+ }
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->label ? $this->label : get_class($this);
+ }
+
+ /**
+ * This is a placeholder for skipping tests. In this
+ * method you place skipIf() and skipUnless() calls to
+ * set the skipping state.
+ * @access public
+ */
+ function skip() {
+ }
+
+ /**
+ * Will issue a message to the reporter and tell the test
+ * case to skip if the incoming flag is true.
+ * @param string $should_skip Condition causing the tests to be skipped.
+ * @param string $message Text of skip condition.
+ * @access public
+ */
+ function skipIf($should_skip, $message = '%s') {
+ if ($should_skip && ! $this->should_skip) {
+ $this->should_skip = true;
+ $message = sprintf($message, 'Skipping [' . get_class($this) . ']');
+ $this->reporter->paintSkip($message . $this->getAssertionLine());
+ }
+ }
+
+ /**
+ * Accessor for the private variable $_shoud_skip
+ * @access public
+ */
+ function shouldSkip() {
+ return $this->should_skip;
+ }
+
+ /**
+ * Will issue a message to the reporter and tell the test
+ * case to skip if the incoming flag is false.
+ * @param string $shouldnt_skip Condition causing the tests to be run.
+ * @param string $message Text of skip condition.
+ * @access public
+ */
+ function skipUnless($shouldnt_skip, $message = false) {
+ $this->skipIf(! $shouldnt_skip, $message);
+ }
+
+ /**
+ * Used to invoke the single tests.
+ * @return SimpleInvoker Individual test runner.
+ * @access public
+ */
+ function createInvoker() {
+ return new SimpleErrorTrappingInvoker(
+ new SimpleExceptionTrappingInvoker(new SimpleInvoker($this)));
+ }
+
+ /**
+ * Uses reflection to run every method within itself
+ * starting with the string "test" unless a method
+ * is specified.
+ * @param SimpleReporter $reporter Current test reporter.
+ * @return boolean True if all tests passed.
+ * @access public
+ */
+ function run($reporter) {
+ $context = SimpleTest::getContext();
+ $context->setTest($this);
+ $context->setReporter($reporter);
+ $this->reporter = $reporter;
+ $started = false;
+ foreach ($this->getTests() as $method) {
+ if ($reporter->shouldInvoke($this->getLabel(), $method)) {
+ $this->skip();
+ if ($this->should_skip) {
+ break;
+ }
+ if (! $started) {
+ $reporter->paintCaseStart($this->getLabel());
+ $started = true;
+ }
+ $invoker = $this->reporter->createInvoker($this->createInvoker());
+ $invoker->before($method);
+ $invoker->invoke($method);
+ $invoker->after($method);
+ }
+ }
+ if ($started) {
+ $reporter->paintCaseEnd($this->getLabel());
+ }
+ unset($this->reporter);
+ $context->setTest(null);
+ return $reporter->getStatus();
+ }
+
+ /**
+ * Gets a list of test names. Normally that will
+ * be all internal methods that start with the
+ * name "test". This method should be overridden
+ * if you want a different rule.
+ * @return array List of test names.
+ * @access public
+ */
+ function getTests() {
+ $methods = array();
+ foreach (get_class_methods(get_class($this)) as $method) {
+ if ($this->isTest($method)) {
+ $methods[] = $method;
+ }
+ }
+ return $methods;
+ }
+
+ /**
+ * Tests to see if the method is a test that should
+ * be run. Currently any method that starts with 'test'
+ * is a candidate unless it is the constructor.
+ * @param string $method Method name to try.
+ * @return boolean True if test method.
+ * @access protected
+ */
+ protected function isTest($method) {
+ if (strtolower(substr($method, 0, 4)) == 'test') {
+ return ! SimpleTestCompatibility::isA($this, strtolower($method));
+ }
+ return false;
+ }
+
+ /**
+ * Announces the start of the test.
+ * @param string $method Test method just started.
+ * @access public
+ */
+ function before($method) {
+ $this->reporter->paintMethodStart($method);
+ $this->observers = array();
+ }
+
+ /**
+ * Sets up unit test wide variables at the start
+ * of each test method. To be overridden in
+ * actual user test cases.
+ * @access public
+ */
+ function setUp() {
+ }
+
+ /**
+ * Clears the data set in the setUp() method call.
+ * To be overridden by the user in actual user test cases.
+ * @access public
+ */
+ function tearDown() {
+ }
+
+ /**
+ * Announces the end of the test. Includes private clean up.
+ * @param string $method Test method just finished.
+ * @access public
+ */
+ function after($method) {
+ for ($i = 0; $i < count($this->observers); $i++) {
+ $this->observers[$i]->atTestEnd($method, $this);
+ }
+ $this->reporter->paintMethodEnd($method);
+ }
+
+ /**
+ * Sets up an observer for the test end.
+ * @param object $observer Must have atTestEnd()
+ * method.
+ * @access public
+ */
+ function tell($observer) {
+ $this->observers[] = &$observer;
+ }
+
+ /**
+ * @deprecated
+ */
+ function pass($message = "Pass") {
+ if (! isset($this->reporter)) {
+ trigger_error('Can only make assertions within test methods');
+ }
+ $this->reporter->paintPass(
+ $message . $this->getAssertionLine());
+ return true;
+ }
+
+ /**
+ * Sends a fail event with a message.
+ * @param string $message Message to send.
+ * @access public
+ */
+ function fail($message = "Fail") {
+ if (! isset($this->reporter)) {
+ trigger_error('Can only make assertions within test methods');
+ }
+ $this->reporter->paintFail(
+ $message . $this->getAssertionLine());
+ return false;
+ }
+
+ /**
+ * Formats a PHP error and dispatches it to the
+ * reporter.
+ * @param integer $severity PHP error code.
+ * @param string $message Text of error.
+ * @param string $file File error occoured in.
+ * @param integer $line Line number of error.
+ * @access public
+ */
+ function error($severity, $message, $file, $line) {
+ if (! isset($this->reporter)) {
+ trigger_error('Can only make assertions within test methods');
+ }
+ $this->reporter->paintError(
+ "Unexpected PHP error [$message] severity [$severity] in [$file line $line]");
+ }
+
+ /**
+ * Formats an exception and dispatches it to the
+ * reporter.
+ * @param Exception $exception Object thrown.
+ * @access public
+ */
+ function exception($exception) {
+ $this->reporter->paintException($exception);
+ }
+
+ /**
+ * For user defined expansion of the available messages.
+ * @param string $type Tag for sorting the signals.
+ * @param mixed $payload Extra user specific information.
+ */
+ function signal($type, $payload) {
+ if (! isset($this->reporter)) {
+ trigger_error('Can only make assertions within test methods');
+ }
+ $this->reporter->paintSignal($type, $payload);
+ }
+
+ /**
+ * Runs an expectation directly, for extending the
+ * tests with new expectation classes.
+ * @param SimpleExpectation $expectation Expectation subclass.
+ * @param mixed $compare Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assert($expectation, $compare, $message = '%s') {
+ if ($expectation->test($compare)) {
+ return $this->pass(sprintf(
+ $message,
+ $expectation->overlayMessage($compare, $this->reporter->getDumper())));
+ } else {
+ return $this->fail(sprintf(
+ $message,
+ $expectation->overlayMessage($compare, $this->reporter->getDumper())));
+ }
+ }
+
+ /**
+ * Uses a stack trace to find the line of an assertion.
+ * @return string Line number of first assert*
+ * method embedded in format string.
+ * @access public
+ */
+ function getAssertionLine() {
+ $trace = new SimpleStackTrace(array('assert', 'expect', 'pass', 'fail', 'skip'));
+ return $trace->traceMethod();
+ }
+
+ /**
+ * Sends a formatted dump of a variable to the
+ * test suite for those emergency debugging
+ * situations.
+ * @param mixed $variable Variable to display.
+ * @param string $message Message to display.
+ * @return mixed The original variable.
+ * @access public
+ */
+ function dump($variable, $message = false) {
+ $dumper = $this->reporter->getDumper();
+ $formatted = $dumper->dump($variable);
+ if ($message) {
+ $formatted = $message . "\n" . $formatted;
+ }
+ $this->reporter->paintFormattedMessage($formatted);
+ return $variable;
+ }
+
+ /**
+ * Accessor for the number of subtests including myelf.
+ * @return integer Number of test cases.
+ * @access public
+ */
+ function getSize() {
+ return 1;
+ }
+}
+
+/**
+ * Helps to extract test cases automatically from a file.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleFileLoader {
+
+ /**
+ * Builds a test suite from a library of test cases.
+ * The new suite is composed into this one.
+ * @param string $test_file File name of library with
+ * test case classes.
+ * @return TestSuite The new test suite.
+ * @access public
+ */
+ function load($test_file) {
+ $existing_classes = get_declared_classes();
+ $existing_globals = get_defined_vars();
+ include_once($test_file);
+ $new_globals = get_defined_vars();
+ $this->makeFileVariablesGlobal($existing_globals, $new_globals);
+ $new_classes = array_diff(get_declared_classes(), $existing_classes);
+ if (empty($new_classes)) {
+ $new_classes = $this->scrapeClassesFromFile($test_file);
+ }
+ $classes = $this->selectRunnableTests($new_classes);
+ return $this->createSuiteFromClasses($test_file, $classes);
+ }
+
+ /**
+ * Imports new variables into the global namespace.
+ * @param hash $existing Variables before the file was loaded.
+ * @param hash $new Variables after the file was loaded.
+ * @access private
+ */
+ protected function makeFileVariablesGlobal($existing, $new) {
+ $globals = array_diff(array_keys($new), array_keys($existing));
+ foreach ($globals as $global) {
+ $GLOBALS[$global] = $new[$global];
+ }
+ }
+
+ /**
+ * Lookup classnames from file contents, in case the
+ * file may have been included before.
+ * Note: This is probably too clever by half. Figuring this
+ * out after a failed test case is going to be tricky for us,
+ * never mind the user. A test case should not be included
+ * twice anyway.
+ * @param string $test_file File name with classes.
+ * @access private
+ */
+ protected function scrapeClassesFromFile($test_file) {
+ preg_match_all('~^\s*class\s+(\w+)(\s+(extends|implements)\s+\w+)*\s*\{~mi',
+ file_get_contents($test_file),
+ $matches );
+ return $matches[1];
+ }
+
+ /**
+ * Calculates the incoming test cases. Skips abstract
+ * and ignored classes.
+ * @param array $candidates Candidate classes.
+ * @return array New classes which are test
+ * cases that shouldn't be ignored.
+ * @access public
+ */
+ function selectRunnableTests($candidates) {
+ $classes = array();
+ foreach ($candidates as $class) {
+ if (TestSuite::getBaseTestCase($class)) {
+ $reflection = new SimpleReflection($class);
+ if ($reflection->isAbstract()) {
+ SimpleTest::ignore($class);
+ } else {
+ $classes[] = $class;
+ }
+ }
+ }
+ return $classes;
+ }
+
+ /**
+ * Builds a test suite from a class list.
+ * @param string $title Title of new group.
+ * @param array $classes Test classes.
+ * @return TestSuite Group loaded with the new
+ * test cases.
+ * @access public
+ */
+ function createSuiteFromClasses($title, $classes) {
+ if (count($classes) == 0) {
+ $suite = new BadTestSuite($title, "No runnable test cases in [$title]");
+ return $suite;
+ }
+ SimpleTest::ignoreParentsIfIgnored($classes);
+ $suite = new TestSuite($title);
+ foreach ($classes as $class) {
+ if (! SimpleTest::isIgnored($class)) {
+ $suite->add($class);
+ }
+ }
+ return $suite;
+ }
+}
+
+/**
+ * This is a composite test class for combining
+ * test cases and other RunnableTest classes into
+ * a group test.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class TestSuite {
+ private $label;
+ private $test_cases;
+
+ /**
+ * Sets the name of the test suite.
+ * @param string $label Name sent at the start and end
+ * of the test.
+ * @access public
+ */
+ function TestSuite($label = false) {
+ $this->label = $label;
+ $this->test_cases = array();
+ }
+
+ /**
+ * Accessor for the test name for subclasses. If the suite
+ * wraps a single test case the label defaults to the name of that test.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ if (! $this->label) {
+ return ($this->getSize() == 1) ?
+ get_class($this->test_cases[0]) : get_class($this);
+ } else {
+ return $this->label;
+ }
+ }
+
+ /**
+ * Adds a test into the suite by instance or class. The class will
+ * be instantiated if it's a test suite.
+ * @param SimpleTestCase $test_case Suite or individual test
+ * case implementing the
+ * runnable test interface.
+ * @access public
+ */
+ function add($test_case) {
+ if (! is_string($test_case)) {
+ $this->test_cases[] = $test_case;
+ } elseif (TestSuite::getBaseTestCase($test_case) == 'testsuite') {
+ $this->test_cases[] = new $test_case();
+ } else {
+ $this->test_cases[] = $test_case;
+ }
+ }
+
+ /**
+ * Builds a test suite from a library of test cases.
+ * The new suite is composed into this one.
+ * @param string $test_file File name of library with
+ * test case classes.
+ * @access public
+ */
+ function addFile($test_file) {
+ $extractor = new SimpleFileLoader();
+ $this->add($extractor->load($test_file));
+ }
+
+ /**
+ * Delegates to a visiting collector to add test
+ * files.
+ * @param string $path Path to scan from.
+ * @param SimpleCollector $collector Directory scanner.
+ * @access public
+ */
+ function collect($path, $collector) {
+ $collector->collect($this, $path);
+ }
+
+ /**
+ * Invokes run() on all of the held test cases, instantiating
+ * them if necessary.
+ * @param SimpleReporter $reporter Current test reporter.
+ * @access public
+ */
+ function run($reporter) {
+ $reporter->paintGroupStart($this->getLabel(), $this->getSize());
+ for ($i = 0, $count = count($this->test_cases); $i < $count; $i++) {
+ if (is_string($this->test_cases[$i])) {
+ $class = $this->test_cases[$i];
+ $test = new $class();
+ $test->run($reporter);
+ unset($test);
+ } else {
+ $this->test_cases[$i]->run($reporter);
+ }
+ }
+ $reporter->paintGroupEnd($this->getLabel());
+ return $reporter->getStatus();
+ }
+
+ /**
+ * Number of contained test cases.
+ * @return integer Total count of cases in the group.
+ * @access public
+ */
+ function getSize() {
+ $count = 0;
+ foreach ($this->test_cases as $case) {
+ if (is_string($case)) {
+ if (! SimpleTest::isIgnored($case)) {
+ $count++;
+ }
+ } else {
+ $count += $case->getSize();
+ }
+ }
+ return $count;
+ }
+
+ /**
+ * Test to see if a class is derived from the
+ * SimpleTestCase class.
+ * @param string $class Class name.
+ * @access public
+ */
+ static function getBaseTestCase($class) {
+ while ($class = get_parent_class($class)) {
+ $class = strtolower($class);
+ if ($class == 'simpletestcase' || $class == 'testsuite') {
+ return $class;
+ }
+ }
+ return false;
+ }
+}
+
+/**
+ * This is a failing group test for when a test suite hasn't
+ * loaded properly.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class BadTestSuite {
+ private $label;
+ private $error;
+
+ /**
+ * Sets the name of the test suite and error message.
+ * @param string $label Name sent at the start and end
+ * of the test.
+ * @access public
+ */
+ function BadTestSuite($label, $error) {
+ $this->label = $label;
+ $this->error = $error;
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->label;
+ }
+
+ /**
+ * Sends a single error to the reporter.
+ * @param SimpleReporter $reporter Current test reporter.
+ * @access public
+ */
+ function run($reporter) {
+ $reporter->paintGroupStart($this->getLabel(), $this->getSize());
+ $reporter->paintFail('Bad TestSuite [' . $this->getLabel() .
+ '] with error [' . $this->error . ']');
+ $reporter->paintGroupEnd($this->getLabel());
+ return $reporter->getStatus();
+ }
+
+ /**
+ * Number of contained test cases. Always zero.
+ * @return integer Total count of cases in the group.
+ * @access public
+ */
+ function getSize() {
+ return 0;
+ }
+}
+?>
diff --git a/3rdparty/simpletest/tidy_parser.php b/3rdparty/simpletest/tidy_parser.php
new file mode 100755
index 00000000000..3d8b4b2ac7d
--- /dev/null
+++ b/3rdparty/simpletest/tidy_parser.php
@@ -0,0 +1,382 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: php_parser.php 1911 2009-07-29 16:38:04Z lastcraft $
+ */
+
+/**
+ * Builds the page object.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleTidyPageBuilder {
+ private $page;
+ private $forms = array();
+ private $labels = array();
+ private $widgets_by_id = array();
+
+ public function __destruct() {
+ $this->free();
+ }
+
+ /**
+ * Frees up any references so as to allow the PHP garbage
+ * collection from unset() to work.
+ */
+ private function free() {
+ unset($this->page);
+ $this->forms = array();
+ $this->labels = array();
+ }
+
+ /**
+ * This builder is only available if the 'tidy' extension is loaded.
+ * @return boolean True if available.
+ */
+ function can() {
+ return extension_loaded('tidy');
+ }
+
+ /**
+ * Reads the raw content the page using HTML Tidy.
+ * @param $response SimpleHttpResponse Fetched response.
+ * @return SimplePage Newly parsed page.
+ */
+ function parse($response) {
+ $this->page = new SimplePage($response);
+ $tidied = tidy_parse_string($input = $this->insertGuards($response->getContent()),
+ array('output-xml' => false, 'wrap' => '0', 'indent' => 'no'),
+ 'latin1');
+ $this->walkTree($tidied->html());
+ $this->attachLabels($this->widgets_by_id, $this->labels);
+ $this->page->setForms($this->forms);
+ $page = $this->page;
+ $this->free();
+ return $page;
+ }
+
+ /**
+ * Stops HTMLTidy stripping content that we wish to preserve.
+ * @param string The raw html.
+ * @return string The html with guard tags inserted.
+ */
+ private function insertGuards($html) {
+ return $this->insertEmptyTagGuards($this->insertTextareaSimpleWhitespaceGuards($html));
+ }
+
+ /**
+ * Removes the extra content added during the parse stage
+ * in order to preserve content we don't want stripped
+ * out by HTMLTidy.
+ * @param string The raw html.
+ * @return string The html with guard tags removed.
+ */
+ private function stripGuards($html) {
+ return $this->stripTextareaWhitespaceGuards($this->stripEmptyTagGuards($html));
+ }
+
+ /**
+ * HTML tidy strips out empty tags such as <option> which we
+ * need to preserve. This method inserts an additional marker.
+ * @param string The raw html.
+ * @return string The html with guards inserted.
+ */
+ private function insertEmptyTagGuards($html) {
+ return preg_replace('#<(option|textarea)([^>]*)>(\s*)</(option|textarea)>#is',
+ '<\1\2>___EMPTY___\3</\4>',
+ $html);
+ }
+
+ /**
+ * HTML tidy strips out empty tags such as <option> which we
+ * need to preserve. This method strips additional markers
+ * inserted by SimpleTest to the tidy output used to make the
+ * tags non-empty. This ensures their preservation.
+ * @param string The raw html.
+ * @return string The html with guards removed.
+ */
+ private function stripEmptyTagGuards($html) {
+ return preg_replace('#(^|>)(\s*)___EMPTY___(\s*)(</|$)#i', '\2\3', $html);
+ }
+
+ /**
+ * By parsing the XML output of tidy, we lose some whitespace
+ * information in textarea tags. We temporarily recode this
+ * data ourselves so as not to lose it.
+ * @param string The raw html.
+ * @return string The html with guards inserted.
+ */
+ private function insertTextareaSimpleWhitespaceGuards($html) {
+ return preg_replace_callback('#<textarea([^>]*)>(.*?)</textarea>#is',
+ array($this, 'insertWhitespaceGuards'),
+ $html);
+ }
+
+ /**
+ * Callback for insertTextareaSimpleWhitespaceGuards().
+ * @param array $matches Result of preg_replace_callback().
+ * @return string Guard tags now replace whitespace.
+ */
+ private function insertWhitespaceGuards($matches) {
+ return '<textarea' . $matches[1] . '>' .
+ str_replace(array("\n", "\r", "\t", ' '),
+ array('___NEWLINE___', '___CR___', '___TAB___', '___SPACE___'),
+ $matches[2]) .
+ '</textarea>';
+ }
+
+ /**
+ * Removes the whitespace preserving guards we added
+ * before parsing.
+ * @param string The raw html.
+ * @return string The html with guards removed.
+ */
+ private function stripTextareaWhitespaceGuards($html) {
+ return str_replace(array('___NEWLINE___', '___CR___', '___TAB___', '___SPACE___'),
+ array("\n", "\r", "\t", ' '),
+ $html);
+ }
+
+ /**
+ * Visits the given node and all children
+ * @param object $node Tidy XML node.
+ */
+ private function walkTree($node) {
+ if ($node->name == 'a') {
+ $this->page->addLink($this->tags()->createTag($node->name, (array)$node->attribute)
+ ->addContent($this->innerHtml($node)));
+ } elseif ($node->name == 'base' and isset($node->attribute['href'])) {
+ $this->page->setBase($node->attribute['href']);
+ } elseif ($node->name == 'title') {
+ $this->page->setTitle($this->tags()->createTag($node->name, (array)$node->attribute)
+ ->addContent($this->innerHtml($node)));
+ } elseif ($node->name == 'frameset') {
+ $this->page->setFrames($this->collectFrames($node));
+ } elseif ($node->name == 'form') {
+ $this->forms[] = $this->walkForm($node, $this->createEmptyForm($node));
+ } elseif ($node->name == 'label') {
+ $this->labels[] = $this->tags()->createTag($node->name, (array)$node->attribute)
+ ->addContent($this->innerHtml($node));
+ } else {
+ $this->walkChildren($node);
+ }
+ }
+
+ /**
+ * Helper method for traversing the XML tree.
+ * @param object $node Tidy XML node.
+ */
+ private function walkChildren($node) {
+ if ($node->hasChildren()) {
+ foreach ($node->child as $child) {
+ $this->walkTree($child);
+ }
+ }
+ }
+
+ /**
+ * Facade for forms containing preparsed widgets.
+ * @param object $node Tidy XML node.
+ * @return SimpleForm Facade for SimpleBrowser.
+ */
+ private function createEmptyForm($node) {
+ return new SimpleForm($this->tags()->createTag($node->name, (array)$node->attribute), $this->page);
+ }
+
+ /**
+ * Visits the given node and all children
+ * @param object $node Tidy XML node.
+ */
+ private function walkForm($node, $form, $enclosing_label = '') {
+ if ($node->name == 'a') {
+ $this->page->addLink($this->tags()->createTag($node->name, (array)$node->attribute)
+ ->addContent($this->innerHtml($node)));
+ } elseif (in_array($node->name, array('input', 'button', 'textarea', 'select'))) {
+ $this->addWidgetToForm($node, $form, $enclosing_label);
+ } elseif ($node->name == 'label') {
+ $this->labels[] = $this->tags()->createTag($node->name, (array)$node->attribute)
+ ->addContent($this->innerHtml($node));
+ if ($node->hasChildren()) {
+ foreach ($node->child as $child) {
+ $this->walkForm($child, $form, SimplePage::normalise($this->innerHtml($node)));
+ }
+ }
+ } elseif ($node->hasChildren()) {
+ foreach ($node->child as $child) {
+ $this->walkForm($child, $form);
+ }
+ }
+ return $form;
+ }
+
+ /**
+ * Tests a node for a "for" atribute. Used for
+ * attaching labels.
+ * @param object $node Tidy XML node.
+ * @return boolean True if the "for" attribute exists.
+ */
+ private function hasFor($node) {
+ return isset($node->attribute) and $node->attribute['for'];
+ }
+
+ /**
+ * Adds the widget into the form container.
+ * @param object $node Tidy XML node of widget.
+ * @param SimpleForm $form Form to add it to.
+ * @param string $enclosing_label The label of any label
+ * tag we might be in.
+ */
+ private function addWidgetToForm($node, $form, $enclosing_label) {
+ $widget = $this->tags()->createTag($node->name, $this->attributes($node));
+ if (! $widget) {
+ return;
+ }
+ $widget->setLabel($enclosing_label)
+ ->addContent($this->innerHtml($node));
+ if ($node->name == 'select') {
+ $widget->addTags($this->collectSelectOptions($node));
+ }
+ $form->addWidget($widget);
+ $this->indexWidgetById($widget);
+ }
+
+ /**
+ * Fills the widget cache to speed up searching.
+ * @param SimpleTag $widget Parsed widget to cache.
+ */
+ private function indexWidgetById($widget) {
+ $id = $widget->getAttribute('id');
+ if (! $id) {
+ return;
+ }
+ if (! isset($this->widgets_by_id[$id])) {
+ $this->widgets_by_id[$id] = array();
+ }
+ $this->widgets_by_id[$id][] = $widget;
+ }
+
+ /**
+ * Parses the options from inside an XML select node.
+ * @param object $node Tidy XML node.
+ * @return array List of SimpleTag options.
+ */
+ private function collectSelectOptions($node) {
+ $options = array();
+ if ($node->name == 'option') {
+ $options[] = $this->tags()->createTag($node->name, $this->attributes($node))
+ ->addContent($this->innerHtml($node));
+ }
+ if ($node->hasChildren()) {
+ foreach ($node->child as $child) {
+ $options = array_merge($options, $this->collectSelectOptions($child));
+ }
+ }
+ return $options;
+ }
+
+ /**
+ * Convenience method for collecting all the attributes
+ * of a tag. Not sure why Tidy does not have this.
+ * @param object $node Tidy XML node.
+ * @return array Hash of attribute strings.
+ */
+ private function attributes($node) {
+ if (! preg_match('|<[^ ]+\s(.*?)/?>|s', $node->value, $first_tag_contents)) {
+ return array();
+ }
+ $attributes = array();
+ preg_match_all('/\S+\s*=\s*\'[^\']*\'|(\S+\s*=\s*"[^"]*")|([^ =]+\s*=\s*[^ "\']+?)|[^ "\']+/', $first_tag_contents[1], $matches);
+ foreach($matches[0] as $unparsed) {
+ $attributes = $this->mergeAttribute($attributes, $unparsed);
+ }
+ return $attributes;
+ }
+
+ /**
+ * Overlay an attribute into the attributes hash.
+ * @param array $attributes Current attribute list.
+ * @param string $raw Raw attribute string with
+ * both key and value.
+ * @return array New attribute hash.
+ */
+ private function mergeAttribute($attributes, $raw) {
+ $parts = explode('=', $raw);
+ list($name, $value) = count($parts) == 1 ? array($parts[0], $parts[0]) : $parts;
+ $attributes[trim($name)] = html_entity_decode($this->dequote(trim($value)), ENT_QUOTES);
+ return $attributes;
+ }
+
+ /**
+ * Remove start and end quotes.
+ * @param string $quoted A quoted string.
+ * @return string Quotes are gone.
+ */
+ private function dequote($quoted) {
+ if (preg_match('/^(\'([^\']*)\'|"([^"]*)")$/', $quoted, $matches)) {
+ return isset($matches[3]) ? $matches[3] : $matches[2];
+ }
+ return $quoted;
+ }
+
+ /**
+ * Collects frame information inside a frameset tag.
+ * @param object $node Tidy XML node.
+ * @return array List of SimpleTag frame descriptions.
+ */
+ private function collectFrames($node) {
+ $frames = array();
+ if ($node->name == 'frame') {
+ $frames = array($this->tags()->createTag($node->name, (array)$node->attribute));
+ } else if ($node->hasChildren()) {
+ $frames = array();
+ foreach ($node->child as $child) {
+ $frames = array_merge($frames, $this->collectFrames($child));
+ }
+ }
+ return $frames;
+ }
+
+ /**
+ * Extracts the XML node text.
+ * @param object $node Tidy XML node.
+ * @return string The text only.
+ */
+ private function innerHtml($node) {
+ $raw = '';
+ if ($node->hasChildren()) {
+ foreach ($node->child as $child) {
+ $raw .= $child->value;
+ }
+ }
+ return $this->stripGuards($raw);
+ }
+
+ /**
+ * Factory for parsed content holders.
+ * @return SimpleTagBuilder Factory.
+ */
+ private function tags() {
+ return new SimpleTagBuilder();
+ }
+
+ /**
+ * Called at the end of a parse run. Attaches any
+ * non-wrapping labels to their form elements.
+ * @param array $widgets_by_id Cached SimpleTag hash.
+ * @param array $labels SimpleTag label elements.
+ */
+ private function attachLabels($widgets_by_id, $labels) {
+ foreach ($labels as $label) {
+ $for = $label->getFor();
+ if ($for and isset($widgets_by_id[$for])) {
+ $text = $label->getText();
+ foreach ($widgets_by_id[$for] as $widget) {
+ $widget->setLabel($text);
+ }
+ }
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/unit_tester.php b/3rdparty/simpletest/unit_tester.php
new file mode 100755
index 00000000000..ce82660afa2
--- /dev/null
+++ b/3rdparty/simpletest/unit_tester.php
@@ -0,0 +1,413 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: unit_tester.php 1882 2009-07-01 14:30:05Z lastcraft $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/test_case.php');
+require_once(dirname(__FILE__) . '/dumper.php');
+/**#@-*/
+
+/**
+ * Standard unit test class for day to day testing
+ * of PHP code XP style. Adds some useful standard
+ * assertions.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class UnitTestCase extends SimpleTestCase {
+
+ /**
+ * Creates an empty test case. Should be subclassed
+ * with test methods for a functional test case.
+ * @param string $label Name of test case. Will use
+ * the class name if none specified.
+ * @access public
+ */
+ function __construct($label = false) {
+ if (! $label) {
+ $label = get_class($this);
+ }
+ parent::__construct($label);
+ }
+
+ /**
+ * Called from within the test methods to register
+ * passes and failures.
+ * @param boolean $result Pass on true.
+ * @param string $message Message to display describing
+ * the test state.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertTrue($result, $message = '%s') {
+ return $this->assert(new TrueExpectation(), $result, $message);
+ }
+
+ /**
+ * Will be true on false and vice versa. False
+ * is the PHP definition of false, so that null,
+ * empty strings, zero and an empty array all count
+ * as false.
+ * @param boolean $result Pass on false.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertFalse($result, $message = '%s') {
+ return $this->assert(new FalseExpectation(), $result, $message);
+ }
+
+ /**
+ * Will be true if the value is null.
+ * @param null $value Supposedly null value.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNull($value, $message = '%s') {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ '[' . $dumper->describeValue($value) . '] should be null');
+ return $this->assertTrue(! isset($value), $message);
+ }
+
+ /**
+ * Will be true if the value is set.
+ * @param mixed $value Supposedly set value.
+ * @param string $message Message to display.
+ * @return boolean True on pass.
+ * @access public
+ */
+ function assertNotNull($value, $message = '%s') {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ '[' . $dumper->describeValue($value) . '] should not be null');
+ return $this->assertTrue(isset($value), $message);
+ }
+
+ /**
+ * Type and class test. Will pass if class
+ * matches the type name or is a subclass or
+ * if not an object, but the type is correct.
+ * @param mixed $object Object to test.
+ * @param string $type Type name as string.
+ * @param string $message Message to display.
+ * @return boolean True on pass.
+ * @access public
+ */
+ function assertIsA($object, $type, $message = '%s') {
+ return $this->assert(
+ new IsAExpectation($type),
+ $object,
+ $message);
+ }
+
+ /**
+ * Type and class mismatch test. Will pass if class
+ * name or underling type does not match the one
+ * specified.
+ * @param mixed $object Object to test.
+ * @param string $type Type name as string.
+ * @param string $message Message to display.
+ * @return boolean True on pass.
+ * @access public
+ */
+ function assertNotA($object, $type, $message = '%s') {
+ return $this->assert(
+ new NotAExpectation($type),
+ $object,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * the same value only. Otherwise a fail.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertEqual($first, $second, $message = '%s') {
+ return $this->assert(
+ new EqualExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * a different value. Otherwise a fail.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNotEqual($first, $second, $message = '%s') {
+ return $this->assert(
+ new NotEqualExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the if the first parameter
+ * is near enough to the second by the margin.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param mixed $margin Fuzziness of match.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertWithinMargin($first, $second, $margin, $message = '%s') {
+ return $this->assert(
+ new WithinMarginExpectation($first, $margin),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters differ
+ * by more than the margin.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param mixed $margin Fuzziness of match.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertOutsideMargin($first, $second, $margin, $message = '%s') {
+ return $this->assert(
+ new OutsideMarginExpectation($first, $margin),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * the same value and same type. Otherwise a fail.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertIdentical($first, $second, $message = '%s') {
+ return $this->assert(
+ new IdenticalExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * the different value or different type.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNotIdentical($first, $second, $message = '%s') {
+ return $this->assert(
+ new NotIdenticalExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if both parameters refer
+ * to the same object or value. Fail otherwise.
+ * This will cause problems testing objects under
+ * E_STRICT.
+ * TODO: Replace with expectation.
+ * @param mixed $first Reference to check.
+ * @param mixed $second Hopefully the same variable.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertReference(&$first, &$second, $message = '%s') {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ '[' . $dumper->describeValue($first) .
+ '] and [' . $dumper->describeValue($second) .
+ '] should reference the same object');
+ return $this->assertTrue(
+ SimpleTestCompatibility::isReference($first, $second),
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if both parameters refer
+ * to the same object. Fail otherwise. This has
+ * the same semantics at the PHPUnit assertSame.
+ * That is, if values are passed in it has roughly
+ * the same affect as assertIdentical.
+ * TODO: Replace with expectation.
+ * @param mixed $first Object reference to check.
+ * @param mixed $second Hopefully the same object.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertSame($first, $second, $message = '%s') {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ '[' . $dumper->describeValue($first) .
+ '] and [' . $dumper->describeValue($second) .
+ '] should reference the same object');
+ return $this->assertTrue($first === $second, $message);
+ }
+
+ /**
+ * Will trigger a pass if both parameters refer
+ * to different objects. Fail otherwise. The objects
+ * have to be identical though.
+ * @param mixed $first Object reference to check.
+ * @param mixed $second Hopefully not the same object.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertClone($first, $second, $message = '%s') {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ '[' . $dumper->describeValue($first) .
+ '] and [' . $dumper->describeValue($second) .
+ '] should not be the same object');
+ $identical = new IdenticalExpectation($first);
+ return $this->assertTrue(
+ $identical->test($second) && ! ($first === $second),
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if both parameters refer
+ * to different variables. Fail otherwise. The objects
+ * have to be identical references though.
+ * This will fail under E_STRICT with objects. Use
+ * assertClone() for this.
+ * @param mixed $first Object reference to check.
+ * @param mixed $second Hopefully not the same object.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertCopy(&$first, &$second, $message = "%s") {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ "[" . $dumper->describeValue($first) .
+ "] and [" . $dumper->describeValue($second) .
+ "] should not be the same object");
+ return $this->assertFalse(
+ SimpleTestCompatibility::isReference($first, $second),
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the Perl regex pattern
+ * is found in the subject. Fail otherwise.
+ * @param string $pattern Perl regex to look for including
+ * the regex delimiters.
+ * @param string $subject String to search in.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertPattern($pattern, $subject, $message = '%s') {
+ return $this->assert(
+ new PatternExpectation($pattern),
+ $subject,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the perl regex pattern
+ * is not present in subject. Fail if found.
+ * @param string $pattern Perl regex to look for including
+ * the regex delimiters.
+ * @param string $subject String to search in.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNoPattern($pattern, $subject, $message = '%s') {
+ return $this->assert(
+ new NoPatternExpectation($pattern),
+ $subject,
+ $message);
+ }
+
+ /**
+ * Prepares for an error. If the error mismatches it
+ * passes through, otherwise it is swallowed. Any
+ * left over errors trigger failures.
+ * @param SimpleExpectation/string $expected The error to match.
+ * @param string $message Message on failure.
+ * @access public
+ */
+ function expectError($expected = false, $message = '%s') {
+ $queue = SimpleTest::getContext()->get('SimpleErrorQueue');
+ $queue->expectError($this->coerceExpectation($expected), $message);
+ }
+
+ /**
+ * Prepares for an exception. If the error mismatches it
+ * passes through, otherwise it is swallowed. Any
+ * left over errors trigger failures.
+ * @param SimpleExpectation/Exception $expected The error to match.
+ * @param string $message Message on failure.
+ * @access public
+ */
+ function expectException($expected = false, $message = '%s') {
+ $queue = SimpleTest::getContext()->get('SimpleExceptionTrap');
+ $line = $this->getAssertionLine();
+ $queue->expectException($expected, $message . $line);
+ }
+
+ /**
+ * Tells SimpleTest to ignore an upcoming exception as not relevant
+ * to the current test. It doesn't affect the test, whether thrown or
+ * not.
+ * @param SimpleExpectation/Exception $ignored The error to ignore.
+ * @access public
+ */
+ function ignoreException($ignored = false) {
+ SimpleTest::getContext()->get('SimpleExceptionTrap')->ignoreException($ignored);
+ }
+
+ /**
+ * Creates an equality expectation if the
+ * object/value is not already some type
+ * of expectation.
+ * @param mixed $expected Expected value.
+ * @return SimpleExpectation Expectation object.
+ * @access private
+ */
+ protected function coerceExpectation($expected) {
+ if ($expected == false) {
+ return new TrueExpectation();
+ }
+ if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) {
+ return $expected;
+ }
+ return new EqualExpectation(
+ is_string($expected) ? str_replace('%', '%%', $expected) : $expected);
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/url.php b/3rdparty/simpletest/url.php
new file mode 100644
index 00000000000..11d70e745ee
--- /dev/null
+++ b/3rdparty/simpletest/url.php
@@ -0,0 +1,550 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: url.php 2011 2011-04-29 08:22:48Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/encoding.php');
+/**#@-*/
+
+/**
+ * URL parser to replace parse_url() PHP function which
+ * got broken in PHP 4.3.0. Adds some browser specific
+ * functionality such as expandomatics.
+ * Guesses a bit trying to separate the host from
+ * the path and tries to keep a raw, possibly unparsable,
+ * request string as long as possible.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleUrl {
+ private $scheme;
+ private $username;
+ private $password;
+ private $host;
+ private $port;
+ public $path;
+ private $request;
+ private $fragment;
+ private $x;
+ private $y;
+ private $target;
+ private $raw = false;
+
+ /**
+ * Constructor. Parses URL into sections.
+ * @param string $url Incoming URL.
+ * @access public
+ */
+ function __construct($url = '') {
+ list($x, $y) = $this->chompCoordinates($url);
+ $this->setCoordinates($x, $y);
+ $this->scheme = $this->chompScheme($url);
+ if ($this->scheme === 'file') {
+ // Unescaped backslashes not used in directory separator context
+ // will get caught by this, but they should have been urlencoded
+ // anyway so we don't care. If this ends up being a problem, the
+ // host regexp must be modified to match for backslashes when
+ // the scheme is file.
+ $url = str_replace('\\', '/', $url);
+ }
+ list($this->username, $this->password) = $this->chompLogin($url);
+ $this->host = $this->chompHost($url);
+ $this->port = false;
+ if (preg_match('/(.*?):(.*)/', $this->host, $host_parts)) {
+ if ($this->scheme === 'file' && strlen($this->host) === 2) {
+ // DOS drive was placed in authority; promote it to path.
+ $url = '/' . $this->host . $url;
+ $this->host = false;
+ } else {
+ $this->host = $host_parts[1];
+ $this->port = (integer)$host_parts[2];
+ }
+ }
+ $this->path = $this->chompPath($url);
+ $this->request = $this->parseRequest($this->chompRequest($url));
+ $this->fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false);
+ $this->target = false;
+ }
+
+ /**
+ * Extracts the X, Y coordinate pair from an image map.
+ * @param string $url URL so far. The coordinates will be
+ * removed.
+ * @return array X, Y as a pair of integers.
+ * @access private
+ */
+ protected function chompCoordinates(&$url) {
+ if (preg_match('/(.*)\?(\d+),(\d+)$/', $url, $matches)) {
+ $url = $matches[1];
+ return array((integer)$matches[2], (integer)$matches[3]);
+ }
+ return array(false, false);
+ }
+
+ /**
+ * Extracts the scheme part of an incoming URL.
+ * @param string $url URL so far. The scheme will be
+ * removed.
+ * @return string Scheme part or false.
+ * @access private
+ */
+ protected function chompScheme(&$url) {
+ if (preg_match('#^([^/:]*):(//)(.*)#', $url, $matches)) {
+ $url = $matches[2] . $matches[3];
+ return $matches[1];
+ }
+ return false;
+ }
+
+ /**
+ * Extracts the username and password from the
+ * incoming URL. The // prefix will be reattached
+ * to the URL after the doublet is extracted.
+ * @param string $url URL so far. The username and
+ * password are removed.
+ * @return array Two item list of username and
+ * password. Will urldecode() them.
+ * @access private
+ */
+ protected function chompLogin(&$url) {
+ $prefix = '';
+ if (preg_match('#^(//)(.*)#', $url, $matches)) {
+ $prefix = $matches[1];
+ $url = $matches[2];
+ }
+ if (preg_match('#^([^/]*)@(.*)#', $url, $matches)) {
+ $url = $prefix . $matches[2];
+ $parts = explode(":", $matches[1]);
+ return array(
+ urldecode($parts[0]),
+ isset($parts[1]) ? urldecode($parts[1]) : false);
+ }
+ $url = $prefix . $url;
+ return array(false, false);
+ }
+
+ /**
+ * Extracts the host part of an incoming URL.
+ * Includes the port number part. Will extract
+ * the host if it starts with // or it has
+ * a top level domain or it has at least two
+ * dots.
+ * @param string $url URL so far. The host will be
+ * removed.
+ * @return string Host part guess or false.
+ * @access private
+ */
+ protected function chompHost(&$url) {
+ if (preg_match('!^(//)(.*?)(/.*|\?.*|#.*|$)!', $url, $matches)) {
+ $url = $matches[3];
+ return $matches[2];
+ }
+ if (preg_match('!(.*?)(\.\./|\./|/|\?|#|$)(.*)!', $url, $matches)) {
+ $tlds = SimpleUrl::getAllTopLevelDomains();
+ if (preg_match('/[a-z0-9\-]+\.(' . $tlds . ')/i', $matches[1])) {
+ $url = $matches[2] . $matches[3];
+ return $matches[1];
+ } elseif (preg_match('/[a-z0-9\-]+\.[a-z0-9\-]+\.[a-z0-9\-]+/i', $matches[1])) {
+ $url = $matches[2] . $matches[3];
+ return $matches[1];
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Extracts the path information from the incoming
+ * URL. Strips this path from the URL.
+ * @param string $url URL so far. The host will be
+ * removed.
+ * @return string Path part or '/'.
+ * @access private
+ */
+ protected function chompPath(&$url) {
+ if (preg_match('/(.*?)(\?|#|$)(.*)/', $url, $matches)) {
+ $url = $matches[2] . $matches[3];
+ return ($matches[1] ? $matches[1] : '');
+ }
+ return '';
+ }
+
+ /**
+ * Strips off the request data.
+ * @param string $url URL so far. The request will be
+ * removed.
+ * @return string Raw request part.
+ * @access private
+ */
+ protected function chompRequest(&$url) {
+ if (preg_match('/\?(.*?)(#|$)(.*)/', $url, $matches)) {
+ $url = $matches[2] . $matches[3];
+ return $matches[1];
+ }
+ return '';
+ }
+
+ /**
+ * Breaks the request down into an object.
+ * @param string $raw Raw request.
+ * @return SimpleFormEncoding Parsed data.
+ * @access private
+ */
+ protected function parseRequest($raw) {
+ $this->raw = $raw;
+ $request = new SimpleGetEncoding();
+ foreach (explode("&", $raw) as $pair) {
+ if (preg_match('/(.*?)=(.*)/', $pair, $matches)) {
+ $request->add(urldecode($matches[1]), urldecode($matches[2]));
+ } elseif ($pair) {
+ $request->add(urldecode($pair), '');
+ }
+ }
+ return $request;
+ }
+
+ /**
+ * Accessor for protocol part.
+ * @param string $default Value to use if not present.
+ * @return string Scheme name, e.g "http".
+ * @access public
+ */
+ function getScheme($default = false) {
+ return $this->scheme ? $this->scheme : $default;
+ }
+
+ /**
+ * Accessor for user name.
+ * @return string Username preceding host.
+ * @access public
+ */
+ function getUsername() {
+ return $this->username;
+ }
+
+ /**
+ * Accessor for password.
+ * @return string Password preceding host.
+ * @access public
+ */
+ function getPassword() {
+ return $this->password;
+ }
+
+ /**
+ * Accessor for hostname and port.
+ * @param string $default Value to use if not present.
+ * @return string Hostname only.
+ * @access public
+ */
+ function getHost($default = false) {
+ return $this->host ? $this->host : $default;
+ }
+
+ /**
+ * Accessor for top level domain.
+ * @return string Last part of host.
+ * @access public
+ */
+ function getTld() {
+ $path_parts = pathinfo($this->getHost());
+ return (isset($path_parts['extension']) ? $path_parts['extension'] : false);
+ }
+
+ /**
+ * Accessor for port number.
+ * @return integer TCP/IP port number.
+ * @access public
+ */
+ function getPort() {
+ return $this->port;
+ }
+
+ /**
+ * Accessor for path.
+ * @return string Full path including leading slash if implied.
+ * @access public
+ */
+ function getPath() {
+ if (! $this->path && $this->host) {
+ return '/';
+ }
+ return $this->path;
+ }
+
+ /**
+ * Accessor for page if any. This may be a
+ * directory name if ambiguious.
+ * @return Page name.
+ * @access public
+ */
+ function getPage() {
+ if (! preg_match('/([^\/]*?)$/', $this->getPath(), $matches)) {
+ return false;
+ }
+ return $matches[1];
+ }
+
+ /**
+ * Gets the path to the page.
+ * @return string Path less the page.
+ * @access public
+ */
+ function getBasePath() {
+ if (! preg_match('/(.*\/)[^\/]*?$/', $this->getPath(), $matches)) {
+ return false;
+ }
+ return $matches[1];
+ }
+
+ /**
+ * Accessor for fragment at end of URL after the "#".
+ * @return string Part after "#".
+ * @access public
+ */
+ function getFragment() {
+ return $this->fragment;
+ }
+
+ /**
+ * Sets image coordinates. Set to false to clear
+ * them.
+ * @param integer $x Horizontal position.
+ * @param integer $y Vertical position.
+ * @access public
+ */
+ function setCoordinates($x = false, $y = false) {
+ if (($x === false) || ($y === false)) {
+ $this->x = $this->y = false;
+ return;
+ }
+ $this->x = (integer)$x;
+ $this->y = (integer)$y;
+ }
+
+ /**
+ * Accessor for horizontal image coordinate.
+ * @return integer X value.
+ * @access public
+ */
+ function getX() {
+ return $this->x;
+ }
+
+ /**
+ * Accessor for vertical image coordinate.
+ * @return integer Y value.
+ * @access public
+ */
+ function getY() {
+ return $this->y;
+ }
+
+ /**
+ * Accessor for current request parameters
+ * in URL string form. Will return teh original request
+ * if at all possible even if it doesn't make much
+ * sense.
+ * @return string Form is string "?a=1&b=2", etc.
+ * @access public
+ */
+ function getEncodedRequest() {
+ if ($this->raw) {
+ $encoded = $this->raw;
+ } else {
+ $encoded = $this->request->asUrlRequest();
+ }
+ if ($encoded) {
+ return '?' . preg_replace('/^\?/', '', $encoded);
+ }
+ return '';
+ }
+
+ /**
+ * Adds an additional parameter to the request.
+ * @param string $key Name of parameter.
+ * @param string $value Value as string.
+ * @access public
+ */
+ function addRequestParameter($key, $value) {
+ $this->raw = false;
+ $this->request->add($key, $value);
+ }
+
+ /**
+ * Adds additional parameters to the request.
+ * @param hash/SimpleFormEncoding $parameters Additional
+ * parameters.
+ * @access public
+ */
+ function addRequestParameters($parameters) {
+ $this->raw = false;
+ $this->request->merge($parameters);
+ }
+
+ /**
+ * Clears down all parameters.
+ * @access public
+ */
+ function clearRequest() {
+ $this->raw = false;
+ $this->request = new SimpleGetEncoding();
+ }
+
+ /**
+ * Gets the frame target if present. Although
+ * not strictly part of the URL specification it
+ * acts as similarily to the browser.
+ * @return boolean/string Frame name or false if none.
+ * @access public
+ */
+ function getTarget() {
+ return $this->target;
+ }
+
+ /**
+ * Attaches a frame target.
+ * @param string $frame Name of frame.
+ * @access public
+ */
+ function setTarget($frame) {
+ $this->raw = false;
+ $this->target = $frame;
+ }
+
+ /**
+ * Renders the URL back into a string.
+ * @return string URL in canonical form.
+ * @access public
+ */
+ function asString() {
+ $path = $this->path;
+ $scheme = $identity = $host = $port = $encoded = $fragment = '';
+ if ($this->username && $this->password) {
+ $identity = $this->username . ':' . $this->password . '@';
+ }
+ if ($this->getHost()) {
+ $scheme = $this->getScheme() ? $this->getScheme() : 'http';
+ $scheme .= '://';
+ $host = $this->getHost();
+ } elseif ($this->getScheme() === 'file') {
+ // Safest way; otherwise, file URLs on Windows have an extra
+ // leading slash. It might be possible to convert file://
+ // URIs to local file paths, but that requires more research.
+ $scheme = 'file://';
+ }
+ if ($this->getPort() && $this->getPort() != 80 ) {
+ $port = ':'.$this->getPort();
+ }
+
+ if (substr($this->path, 0, 1) == '/') {
+ $path = $this->normalisePath($this->path);
+ }
+ $encoded = $this->getEncodedRequest();
+ $fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
+ $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
+ return "$scheme$identity$host$port$path$encoded$fragment$coords";
+ }
+
+ /**
+ * Replaces unknown sections to turn a relative
+ * URL into an absolute one. The base URL can
+ * be either a string or a SimpleUrl object.
+ * @param string/SimpleUrl $base Base URL.
+ * @access public
+ */
+ function makeAbsolute($base) {
+ if (! is_object($base)) {
+ $base = new SimpleUrl($base);
+ }
+ if ($this->getHost()) {
+ $scheme = $this->getScheme();
+ $host = $this->getHost();
+ $port = $this->getPort() ? ':' . $this->getPort() : '';
+ $identity = $this->getIdentity() ? $this->getIdentity() . '@' : '';
+ if (! $identity) {
+ $identity = $base->getIdentity() ? $base->getIdentity() . '@' : '';
+ }
+ } else {
+ $scheme = $base->getScheme();
+ $host = $base->getHost();
+ $port = $base->getPort() ? ':' . $base->getPort() : '';
+ $identity = $base->getIdentity() ? $base->getIdentity() . '@' : '';
+ }
+ $path = $this->normalisePath($this->extractAbsolutePath($base));
+ $encoded = $this->getEncodedRequest();
+ $fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
+ $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
+ return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords");
+ }
+
+ /**
+ * Replaces unknown sections of the path with base parts
+ * to return a complete absolute one.
+ * @param string/SimpleUrl $base Base URL.
+ * @param string Absolute path.
+ * @access private
+ */
+ protected function extractAbsolutePath($base) {
+ if ($this->getHost()) {
+ return $this->path;
+ }
+ if (! $this->isRelativePath($this->path)) {
+ return $this->path;
+ }
+ if ($this->path) {
+ return $base->getBasePath() . $this->path;
+ }
+ return $base->getPath();
+ }
+
+ /**
+ * Simple test to see if a path part is relative.
+ * @param string $path Path to test.
+ * @return boolean True if starts with a "/".
+ * @access private
+ */
+ protected function isRelativePath($path) {
+ return (substr($path, 0, 1) != '/');
+ }
+
+ /**
+ * Extracts the username and password for use in rendering
+ * a URL.
+ * @return string/boolean Form of username:password or false.
+ * @access public
+ */
+ function getIdentity() {
+ if ($this->username && $this->password) {
+ return $this->username . ':' . $this->password;
+ }
+ return false;
+ }
+
+ /**
+ * Replaces . and .. sections of the path.
+ * @param string $path Unoptimised path.
+ * @return string Path with dots removed if possible.
+ * @access public
+ */
+ function normalisePath($path) {
+ $path = preg_replace('|/\./|', '/', $path);
+ return preg_replace('|/[^/]+/\.\./|', '/', $path);
+ }
+
+ /**
+ * A pipe seperated list of all TLDs that result in two part
+ * domain names.
+ * @return string Pipe separated list.
+ * @access public
+ */
+ static function getAllTopLevelDomains() {
+ return 'com|edu|net|org|gov|mil|int|biz|info|name|pro|aero|coop|museum';
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/user_agent.php b/3rdparty/simpletest/user_agent.php
new file mode 100644
index 00000000000..ea536020017
--- /dev/null
+++ b/3rdparty/simpletest/user_agent.php
@@ -0,0 +1,328 @@
+<?php
+/**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: user_agent.php 2039 2011-11-30 18:16:15Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/cookies.php');
+require_once(dirname(__FILE__) . '/http.php');
+require_once(dirname(__FILE__) . '/encoding.php');
+require_once(dirname(__FILE__) . '/authentication.php');
+/**#@-*/
+
+if (! defined('DEFAULT_MAX_REDIRECTS')) {
+ define('DEFAULT_MAX_REDIRECTS', 3);
+}
+if (! defined('DEFAULT_CONNECTION_TIMEOUT')) {
+ define('DEFAULT_CONNECTION_TIMEOUT', 15);
+}
+
+/**
+ * Fetches web pages whilst keeping track of
+ * cookies and authentication.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class SimpleUserAgent {
+ private $cookie_jar;
+ private $cookies_enabled = true;
+ private $authenticator;
+ private $max_redirects = DEFAULT_MAX_REDIRECTS;
+ private $proxy = false;
+ private $proxy_username = false;
+ private $proxy_password = false;
+ private $connection_timeout = DEFAULT_CONNECTION_TIMEOUT;
+ private $additional_headers = array();
+
+ /**
+ * Starts with no cookies, realms or proxies.
+ * @access public
+ */
+ function __construct() {
+ $this->cookie_jar = new SimpleCookieJar();
+ $this->authenticator = new SimpleAuthenticator();
+ }
+
+ /**
+ * Removes expired and temporary cookies as if
+ * the browser was closed and re-opened. Authorisation
+ * has to be obtained again as well.
+ * @param string/integer $date Time when session restarted.
+ * If omitted then all persistent
+ * cookies are kept.
+ * @access public
+ */
+ function restart($date = false) {
+ $this->cookie_jar->restartSession($date);
+ $this->authenticator->restartSession();
+ }
+
+ /**
+ * Adds a header to every fetch.
+ * @param string $header Header line to add to every
+ * request until cleared.
+ * @access public
+ */
+ function addHeader($header) {
+ $this->additional_headers[] = $header;
+ }
+
+ /**
+ * Ages the cookies by the specified time.
+ * @param integer $interval Amount in seconds.
+ * @access public
+ */
+ function ageCookies($interval) {
+ $this->cookie_jar->agePrematurely($interval);
+ }
+
+ /**
+ * 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->cookie_jar->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->cookie_jar->getCookieValue($host, $path, $name);
+ }
+
+ /**
+ * Reads the current cookies within the base URL.
+ * @param string $name Key of cookie to find.
+ * @param SimpleUrl $base Base URL to search from.
+ * @return string/boolean Null if there is no base URL, false
+ * if the cookie is not set.
+ * @access public
+ */
+ function getBaseCookieValue($name, $base) {
+ if (! $base) {
+ return null;
+ }
+ return $this->getCookieValue($base->getHost(), $base->getPath(), $name);
+ }
+
+ /**
+ * Switches off cookie sending and recieving.
+ * @access public
+ */
+ function ignoreCookies() {
+ $this->cookies_enabled = false;
+ }
+
+ /**
+ * Switches back on the cookie sending and recieving.
+ * @access public
+ */
+ function useCookies() {
+ $this->cookies_enabled = true;
+ }
+
+ /**
+ * Sets the socket timeout for opening a connection.
+ * @param integer $timeout Maximum time in seconds.
+ * @access public
+ */
+ function setConnectionTimeout($timeout) {
+ $this->connection_timeout = $timeout;
+ }
+
+ /**
+ * Sets the maximum number of redirects before
+ * a page will be loaded anyway.
+ * @param integer $max Most hops allowed.
+ * @access public
+ */
+ function setMaximumRedirects($max) {
+ $this->max_redirects = $max;
+ }
+
+ /**
+ * Sets proxy to use on all requests for when
+ * testing from behind a firewall. Set URL
+ * to false to disable.
+ * @param string $proxy Proxy URL.
+ * @param string $username Proxy username for authentication.
+ * @param string $password Proxy password for authentication.
+ * @access public
+ */
+ function useProxy($proxy, $username, $password) {
+ if (! $proxy) {
+ $this->proxy = false;
+ return;
+ }
+ if ((strncmp($proxy, 'http://', 7) != 0) && (strncmp($proxy, 'https://', 8) != 0)) {
+ $proxy = 'http://'. $proxy;
+ }
+ $this->proxy = new SimpleUrl($proxy);
+ $this->proxy_username = $username;
+ $this->proxy_password = $password;
+ }
+
+ /**
+ * Test to see if the redirect limit is passed.
+ * @param integer $redirects Count so far.
+ * @return boolean True if over.
+ * @access private
+ */
+ protected function isTooManyRedirects($redirects) {
+ return ($redirects > $this->max_redirects);
+ }
+
+ /**
+ * Sets the identity for the current realm.
+ * @param string $host Host to which realm applies.
+ * @param string $realm Full name of realm.
+ * @param string $username Username for realm.
+ * @param string $password Password for realm.
+ * @access public
+ */
+ function setIdentity($host, $realm, $username, $password) {
+ $this->authenticator->setIdentityForRealm($host, $realm, $username, $password);
+ }
+
+ /**
+ * Fetches a URL as a response object. Will keep trying if redirected.
+ * It will also collect authentication realm information.
+ * @param string/SimpleUrl $url Target to fetch.
+ * @param SimpleEncoding $encoding Additional parameters for request.
+ * @return SimpleHttpResponse Hopefully the target page.
+ * @access public
+ */
+ function fetchResponse($url, $encoding) {
+ if ($encoding->getMethod() != 'POST') {
+ $url->addRequestParameters($encoding);
+ $encoding->clear();
+ }
+ $response = $this->fetchWhileRedirected($url, $encoding);
+ if ($headers = $response->getHeaders()) {
+ if ($headers->isChallenge()) {
+ $this->authenticator->addRealm(
+ $url,
+ $headers->getAuthentication(),
+ $headers->getRealm());
+ }
+ }
+ return $response;
+ }
+
+ /**
+ * Fetches the page until no longer redirected or
+ * until the redirect limit runs out.
+ * @param SimpleUrl $url Target to fetch.
+ * @param SimpelFormEncoding $encoding Additional parameters for request.
+ * @return SimpleHttpResponse Hopefully the target page.
+ * @access private
+ */
+ protected function fetchWhileRedirected($url, $encoding) {
+ $redirects = 0;
+ do {
+ $response = $this->fetch($url, $encoding);
+ if ($response->isError()) {
+ return $response;
+ }
+ $headers = $response->getHeaders();
+ if ($this->cookies_enabled) {
+ $headers->writeCookiesToJar($this->cookie_jar, $url);
+ }
+ if (! $headers->isRedirect()) {
+ break;
+ }
+ $location = new SimpleUrl($headers->getLocation());
+ $url = $location->makeAbsolute($url);
+ $encoding = new SimpleGetEncoding();
+ } while (! $this->isTooManyRedirects(++$redirects));
+ return $response;
+ }
+
+ /**
+ * Actually make the web request.
+ * @param SimpleUrl $url Target to fetch.
+ * @param SimpleFormEncoding $encoding Additional parameters for request.
+ * @return SimpleHttpResponse Headers and hopefully content.
+ * @access protected
+ */
+ protected function fetch($url, $encoding) {
+ $request = $this->createRequest($url, $encoding);
+ return $request->fetch($this->connection_timeout);
+ }
+
+ /**
+ * Creates a full page request.
+ * @param SimpleUrl $url Target to fetch as url object.
+ * @param SimpleFormEncoding $encoding POST/GET parameters.
+ * @return SimpleHttpRequest New request.
+ * @access private
+ */
+ protected function createRequest($url, $encoding) {
+ $request = $this->createHttpRequest($url, $encoding);
+ $this->addAdditionalHeaders($request);
+ if ($this->cookies_enabled) {
+ $request->readCookiesFromJar($this->cookie_jar, $url);
+ }
+ $this->authenticator->addHeaders($request, $url);
+ return $request;
+ }
+
+ /**
+ * Builds the appropriate HTTP request object.
+ * @param SimpleUrl $url Target to fetch as url object.
+ * @param SimpleFormEncoding $parameters POST/GET parameters.
+ * @return SimpleHttpRequest New request object.
+ * @access protected
+ */
+ protected function createHttpRequest($url, $encoding) {
+ return new SimpleHttpRequest($this->createRoute($url), $encoding);
+ }
+
+ /**
+ * Sets up either a direct route or via a proxy.
+ * @param SimpleUrl $url Target to fetch as url object.
+ * @return SimpleRoute Route to take to fetch URL.
+ * @access protected
+ */
+ protected function createRoute($url) {
+ if ($this->proxy) {
+ return new SimpleProxyRoute(
+ $url,
+ $this->proxy,
+ $this->proxy_username,
+ $this->proxy_password);
+ }
+ return new SimpleRoute($url);
+ }
+
+ /**
+ * Adds additional manual headers.
+ * @param SimpleHttpRequest $request Outgoing request.
+ * @access private
+ */
+ protected function addAdditionalHeaders(&$request) {
+ foreach ($this->additional_headers as $header) {
+ $request->addHeaderLine($header);
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/web_tester.php b/3rdparty/simpletest/web_tester.php
new file mode 100644
index 00000000000..a17230e7b33
--- /dev/null
+++ b/3rdparty/simpletest/web_tester.php
@@ -0,0 +1,1532 @@
+<?php
+/**
+ * Base include file for SimpleTest.
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: web_tester.php 2013 2011-04-29 09:29:45Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/test_case.php');
+require_once(dirname(__FILE__) . '/browser.php');
+require_once(dirname(__FILE__) . '/page.php');
+require_once(dirname(__FILE__) . '/expectation.php');
+/**#@-*/
+
+/**
+ * Test for an HTML widget value match.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class FieldExpectation extends SimpleExpectation {
+ private $value;
+
+ /**
+ * Sets the field value to compare against.
+ * @param mixed $value Test value to match. Can be an
+ * expectation for say pattern matching.
+ * @param string $message Optiona message override. Can use %s as
+ * a placeholder for the original message.
+ * @access public
+ */
+ function __construct($value, $message = '%s') {
+ parent::__construct($message);
+ if (is_array($value)) {
+ sort($value);
+ }
+ $this->value = $value;
+ }
+
+ /**
+ * Tests the expectation. True if it matches
+ * a string value or an array value in any order.
+ * @param mixed $compare Comparison value. False for
+ * an unset field.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ if ($this->value === false) {
+ return ($compare === false);
+ }
+ if ($this->isSingle($this->value)) {
+ return $this->testSingle($compare);
+ }
+ if (is_array($this->value)) {
+ return $this->testMultiple($compare);
+ }
+ return false;
+ }
+
+ /**
+ * Tests for valid field comparisons with a single option.
+ * @param mixed $value Value to type check.
+ * @return boolean True if integer, string or float.
+ * @access private
+ */
+ protected function isSingle($value) {
+ return is_string($value) || is_integer($value) || is_float($value);
+ }
+
+ /**
+ * String comparison for simple field with a single option.
+ * @param mixed $compare String to test against.
+ * @returns boolean True if matching.
+ * @access private
+ */
+ protected function testSingle($compare) {
+ if (is_array($compare) && count($compare) == 1) {
+ $compare = $compare[0];
+ }
+ if (! $this->isSingle($compare)) {
+ return false;
+ }
+ return ($this->value == $compare);
+ }
+
+ /**
+ * List comparison for multivalue field.
+ * @param mixed $compare List in any order to test against.
+ * @returns boolean True if matching.
+ * @access private
+ */
+ protected function testMultiple($compare) {
+ if (is_string($compare)) {
+ $compare = array($compare);
+ }
+ if (! is_array($compare)) {
+ return false;
+ }
+ sort($compare);
+ return ($this->value === $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 (is_array($compare)) {
+ sort($compare);
+ }
+ if ($this->test($compare)) {
+ return "Field expectation [" . $dumper->describeValue($this->value) . "]";
+ } else {
+ return "Field expectation [" . $dumper->describeValue($this->value) .
+ "] fails with [" .
+ $dumper->describeValue($compare) . "] " .
+ $dumper->describeDifference($this->value, $compare);
+ }
+ }
+}
+
+/**
+ * Test for a specific HTTP header within a header block.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class HttpHeaderExpectation extends SimpleExpectation {
+ private $expected_header;
+ private $expected_value;
+
+ /**
+ * Sets the field and value to compare against.
+ * @param string $header Case insenstive trimmed header name.
+ * @param mixed $value Optional value to compare. If not
+ * given then any value will match. If
+ * an expectation object then that will
+ * be used instead.
+ * @param string $message Optiona message override. Can use %s as
+ * a placeholder for the original message.
+ */
+ function __construct($header, $value = false, $message = '%s') {
+ parent::__construct($message);
+ $this->expected_header = $this->normaliseHeader($header);
+ $this->expected_value = $value;
+ }
+
+ /**
+ * Accessor for aggregated object.
+ * @return mixed Expectation set in constructor.
+ * @access protected
+ */
+ protected function getExpectation() {
+ return $this->expected_value;
+ }
+
+ /**
+ * Removes whitespace at ends and case variations.
+ * @param string $header Name of header.
+ * @param string Trimmed and lowecased header
+ * name.
+ * @access private
+ */
+ protected function normaliseHeader($header) {
+ return strtolower(trim($header));
+ }
+
+ /**
+ * Tests the expectation. True if it matches
+ * a string value or an array value in any order.
+ * @param mixed $compare Raw header block to search.
+ * @return boolean True if header present.
+ * @access public
+ */
+ function test($compare) {
+ return is_string($this->findHeader($compare));
+ }
+
+ /**
+ * Searches the incoming result. Will extract the matching
+ * line as text.
+ * @param mixed $compare Raw header block to search.
+ * @return string Matching header line.
+ * @access protected
+ */
+ protected function findHeader($compare) {
+ $lines = explode("\r\n", $compare);
+ foreach ($lines as $line) {
+ if ($this->testHeaderLine($line)) {
+ return $line;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Compares a single header line against the expectation.
+ * @param string $line A single line to compare.
+ * @return boolean True if matched.
+ * @access private
+ */
+ protected function testHeaderLine($line) {
+ if (count($parsed = explode(':', $line, 2)) < 2) {
+ return false;
+ }
+ list($header, $value) = $parsed;
+ if ($this->normaliseHeader($header) != $this->expected_header) {
+ return false;
+ }
+ return $this->testHeaderValue($value, $this->expected_value);
+ }
+
+ /**
+ * Tests the value part of the header.
+ * @param string $value Value to test.
+ * @param mixed $expected Value to test against.
+ * @return boolean True if matched.
+ * @access protected
+ */
+ protected function testHeaderValue($value, $expected) {
+ if ($expected === false) {
+ return true;
+ }
+ if (SimpleExpectation::isExpectation($expected)) {
+ return $expected->test(trim($value));
+ }
+ return (trim($value) == trim($expected));
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Raw header block to search.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ if (SimpleExpectation::isExpectation($this->expected_value)) {
+ $message = $this->expected_value->overlayMessage($compare, $this->getDumper());
+ } else {
+ $message = $this->expected_header .
+ ($this->expected_value ? ': ' . $this->expected_value : '');
+ }
+ if (is_string($line = $this->findHeader($compare))) {
+ return "Searching for header [$message] found [$line]";
+ } else {
+ return "Failed to find header [$message]";
+ }
+ }
+}
+
+/**
+ * Test for a specific HTTP header within a header block that
+ * should not be found.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class NoHttpHeaderExpectation extends HttpHeaderExpectation {
+ private $expected_header;
+ private $expected_value;
+
+ /**
+ * Sets the field and value to compare against.
+ * @param string $unwanted Case insenstive trimmed header name.
+ * @param string $message Optiona message override. Can use %s as
+ * a placeholder for the original message.
+ */
+ function __construct($unwanted, $message = '%s') {
+ parent::__construct($unwanted, false, $message);
+ }
+
+ /**
+ * Tests that the unwanted header is not found.
+ * @param mixed $compare Raw header block to search.
+ * @return boolean True if header present.
+ * @access public
+ */
+ function test($compare) {
+ return ($this->findHeader($compare) === false);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Raw header block to search.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ $expectation = $this->getExpectation();
+ if (is_string($line = $this->findHeader($compare))) {
+ return "Found unwanted header [$expectation] with [$line]";
+ } else {
+ return "Did not find unwanted header [$expectation]";
+ }
+ }
+}
+
+/**
+ * Test for a text substring.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class TextExpectation extends SimpleExpectation {
+ private $substring;
+
+ /**
+ * Sets the value to compare against.
+ * @param string $substring Text to search for.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function __construct($substring, $message = '%s') {
+ parent::__construct($message);
+ $this->substring = $substring;
+ }
+
+ /**
+ * Accessor for the substring.
+ * @return string Text to match.
+ * @access protected
+ */
+ protected function getSubstring() {
+ return $this->substring;
+ }
+
+ /**
+ * Tests the expectation. True if the text contains the
+ * substring.
+ * @param string $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return (strpos($compare, $this->substring) !== false);
+ }
+
+ /**
+ * 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->describeTextMatch($this->getSubstring(), $compare);
+ } else {
+ $dumper = $this->getDumper();
+ return "Text [" . $this->getSubstring() .
+ "] not detected in [" .
+ $dumper->describeValue($compare) . "]";
+ }
+ }
+
+ /**
+ * Describes a pattern match including the string
+ * found and it's position.
+ * @param string $substring Text to search for.
+ * @param string $subject Subject to search.
+ * @access protected
+ */
+ protected function describeTextMatch($substring, $subject) {
+ $position = strpos($subject, $substring);
+ $dumper = $this->getDumper();
+ return "Text [$substring] detected at character [$position] in [" .
+ $dumper->describeValue($subject) . "] in region [" .
+ $dumper->clipString($subject, 100, $position) . "]";
+ }
+}
+
+/**
+ * Fail if a substring is detected within the
+ * comparison text.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class NoTextExpectation extends TextExpectation {
+
+ /**
+ * Sets the reject pattern
+ * @param string $substring Text to search for.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function __construct($substring, $message = '%s') {
+ parent::__construct($substring, $message);
+ }
+
+ /**
+ * Tests the expectation. False if the substring appears
+ * in the text.
+ * @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 "Text [" . $this->getSubstring() .
+ "] not detected in [" .
+ $dumper->describeValue($compare) . "]";
+ } else {
+ return $this->describeTextMatch($this->getSubstring(), $compare);
+ }
+ }
+}
+
+/**
+ * Test case for testing of web pages. Allows
+ * fetching of pages, parsing of HTML and
+ * submitting forms.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+class WebTestCase extends SimpleTestCase {
+ private $browser;
+ private $ignore_errors = false;
+
+ /**
+ * Creates an empty test case. Should be subclassed
+ * with test methods for a functional test case.
+ * @param string $label Name of test case. Will use
+ * the class name if none specified.
+ * @access public
+ */
+ function __construct($label = false) {
+ parent::__construct($label);
+ }
+
+ /**
+ * Announces the start of the test.
+ * @param string $method Test method just started.
+ * @access public
+ */
+ function before($method) {
+ parent::before($method);
+ $this->setBrowser($this->createBrowser());
+ }
+
+ /**
+ * Announces the end of the test. Includes private clean up.
+ * @param string $method Test method just finished.
+ * @access public
+ */
+ function after($method) {
+ $this->unsetBrowser();
+ parent::after($method);
+ }
+
+ /**
+ * Gets a current browser reference for setting
+ * special expectations or for detailed
+ * examination of page fetches.
+ * @return SimpleBrowser Current test browser object.
+ * @access public
+ */
+ function getBrowser() {
+ return $this->browser;
+ }
+
+ /**
+ * Gets a current browser reference for setting
+ * special expectations or for detailed
+ * examination of page fetches.
+ * @param SimpleBrowser $browser New test browser object.
+ * @access public
+ */
+ function setBrowser($browser) {
+ return $this->browser = $browser;
+ }
+
+ /**
+ * Sets the HTML parser to use within this browser.
+ * @param object The parser, one of SimplePHPPageBuilder or
+ * SimpleTidyPageBuilder.
+ */
+ function setParser($parser) {
+ $this->browser->setParser($parser);
+ }
+
+ /**
+ * Clears the current browser reference to help the
+ * PHP garbage collector.
+ * @access public
+ */
+ function unsetBrowser() {
+ unset($this->browser);
+ }
+
+ /**
+ * Creates a new default web browser object.
+ * Will be cleared at the end of the test method.
+ * @return TestBrowser New browser.
+ * @access public
+ */
+ function createBrowser() {
+ return new SimpleBrowser();
+ }
+
+ /**
+ * Gets the last response error.
+ * @return string Last low level HTTP error.
+ * @access public
+ */
+ function getTransportError() {
+ return $this->browser->getTransportError();
+ }
+
+ /**
+ * Accessor for the currently selected URL.
+ * @return string Current location or false if
+ * no page yet fetched.
+ * @access public
+ */
+ function getUrl() {
+ return $this->browser->getUrl();
+ }
+
+ /**
+ * Dumps the current request for debugging.
+ * @access public
+ */
+ function showRequest() {
+ $this->dump($this->browser->getRequest());
+ }
+
+ /**
+ * Dumps the current HTTP headers for debugging.
+ * @access public
+ */
+ function showHeaders() {
+ $this->dump($this->browser->getHeaders());
+ }
+
+ /**
+ * Dumps the current HTML source for debugging.
+ * @access public
+ */
+ function showSource() {
+ $this->dump($this->browser->getContent());
+ }
+
+ /**
+ * Dumps the visible text only for debugging.
+ * @access public
+ */
+ function showText() {
+ $this->dump(wordwrap($this->browser->getContentAsText(), 80));
+ }
+
+ /**
+ * Simulates the closing and reopening of the browser.
+ * Temporary cookies will be discarded and timed
+ * cookies will be expired if later than the
+ * specified time.
+ * @param string/integer $date Time when session restarted.
+ * If ommitted then all persistent
+ * cookies are kept. Time is either
+ * Cookie format string or timestamp.
+ * @access public
+ */
+ function restart($date = false) {
+ if ($date === false) {
+ $date = time();
+ }
+ $this->browser->restart($date);
+ }
+
+ /**
+ * Moves cookie expiry times back into the past.
+ * Useful for testing timeouts and expiries.
+ * @param integer $interval Amount to age in seconds.
+ * @access public
+ */
+ function ageCookies($interval) {
+ $this->browser->ageCookies($interval);
+ }
+
+ /**
+ * Disables frames support. Frames will not be fetched
+ * and the frameset page will be used instead.
+ * @access public
+ */
+ function ignoreFrames() {
+ $this->browser->ignoreFrames();
+ }
+
+ /**
+ * Switches off cookie sending and recieving.
+ * @access public
+ */
+ function ignoreCookies() {
+ $this->browser->ignoreCookies();
+ }
+
+ /**
+ * Skips errors for the next request only. You might
+ * want to confirm that a page is unreachable for
+ * example.
+ * @access public
+ */
+ function ignoreErrors() {
+ $this->ignore_errors = true;
+ }
+
+ /**
+ * Issues a fail if there is a transport error anywhere
+ * in the current frameset. Only one such error is
+ * reported.
+ * @param string/boolean $result HTML or failure.
+ * @return string/boolean $result Passes through result.
+ * @access private
+ */
+ protected function failOnError($result) {
+ if (! $this->ignore_errors) {
+ if ($error = $this->browser->getTransportError()) {
+ $this->fail($error);
+ }
+ }
+ $this->ignore_errors = false;
+ return $result;
+ }
+
+ /**
+ * Adds a header to every fetch.
+ * @param string $header Header line to add to every
+ * request until cleared.
+ * @access public
+ */
+ function addHeader($header) {
+ $this->browser->addHeader($header);
+ }
+
+ /**
+ * Sets the maximum number of redirects before
+ * the web page is loaded regardless.
+ * @param integer $max Maximum hops.
+ * @access public
+ */
+ function setMaximumRedirects($max) {
+ if (! $this->browser) {
+ trigger_error(
+ 'Can only set maximum redirects in a test method, setUp() or tearDown()');
+ }
+ $this->browser->setMaximumRedirects($max);
+ }
+
+ /**
+ * Sets the socket timeout for opening a connection and
+ * receiving at least one byte of information.
+ * @param integer $timeout Maximum time in seconds.
+ * @access public
+ */
+ function setConnectionTimeout($timeout) {
+ $this->browser->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->browser->useProxy($proxy, $username, $password);
+ }
+
+ /**
+ * Fetches a page into the page buffer. If
+ * there is no base for the URL then the
+ * current base URL is used. After the fetch
+ * the base URL reflects the new location.
+ * @param string $url URL to fetch.
+ * @param hash $parameters Optional additional GET data.
+ * @return boolean/string Raw page on success.
+ * @access public
+ */
+ function get($url, $parameters = false) {
+ return $this->failOnError($this->browser->get($url, $parameters));
+ }
+
+ /**
+ * Fetches a page by POST into the page buffer.
+ * If there is no base for the URL then the
+ * current base URL is used. After the fetch
+ * the base URL reflects the new location.
+ * @param string $url URL to fetch.
+ * @param mixed $parameters Optional POST parameters or content body to send
+ * @param string $content_type Content type of provided body
+ * @return boolean/string Raw page on success.
+ * @access public
+ */
+ function post($url, $parameters = false, $content_type = false) {
+ return $this->failOnError($this->browser->post($url, $parameters, $content_type));
+ }
+
+ /**
+ * Fetches a page by PUT into the page buffer.
+ * If there is no base for the URL then the
+ * current base URL is used. After the fetch
+ * the base URL reflects the new location.
+ * @param string $url URL to fetch.
+ * @param mixed $body Optional content body to send
+ * @param string $content_type Content type of provided body
+ * @return boolean/string Raw page on success.
+ * @access public
+ */
+ function put($url, $body = false, $content_type = false) {
+ return $this->failOnError($this->browser->put($url, $body, $content_type));
+ }
+
+ /**
+ * Fetches a page by a DELETE request
+ * @param string $url URL to fetch.
+ * @param hash $parameters Optional additional parameters.
+ * @return boolean/string Raw page on success.
+ * @access public
+ */
+ function delete($url, $parameters = false) {
+ return $this->failOnError($this->browser->delete($url, $parameters));
+ }
+
+
+ /**
+ * Does a HTTP HEAD fetch, fetching only the page
+ * headers. The current base URL is unchanged by this.
+ * @param string $url URL to fetch.
+ * @param hash $parameters Optional additional GET data.
+ * @return boolean True on success.
+ * @access public
+ */
+ function head($url, $parameters = false) {
+ return $this->failOnError($this->browser->head($url, $parameters));
+ }
+
+ /**
+ * Equivalent to hitting the retry button on the
+ * browser. Will attempt to repeat the page fetch.
+ * @return boolean True if fetch succeeded.
+ * @access public
+ */
+ function retry() {
+ return $this->failOnError($this->browser->retry());
+ }
+
+ /**
+ * Equivalent to hitting the back button on the
+ * browser.
+ * @return boolean True if history entry and
+ * fetch succeeded.
+ * @access public
+ */
+ function back() {
+ return $this->failOnError($this->browser->back());
+ }
+
+ /**
+ * Equivalent to hitting the forward button on the
+ * browser.
+ * @return boolean True if history entry and
+ * fetch succeeded.
+ * @access public
+ */
+ function forward() {
+ return $this->failOnError($this->browser->forward());
+ }
+
+ /**
+ * 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/string HTML on successful fetch. Note
+ * that authentication may still have
+ * failed.
+ * @access public
+ */
+ function authenticate($username, $password) {
+ return $this->failOnError(
+ $this->browser->authenticate($username, $password));
+ }
+
+ /**
+ * Gets the cookie value for the current browser context.
+ * @param string $name Name of cookie.
+ * @return string Value of cookie or false if unset.
+ * @access public
+ */
+ function getCookie($name) {
+ return $this->browser->getCurrentCookieValue($name);
+ }
+
+ /**
+ * Sets a cookie in the current browser.
+ * @param string $name Name of cookie.
+ * @param string $value Cookie value.
+ * @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->browser->setCookie($name, $value, $host, $path, $expiry);
+ }
+
+ /**
+ * 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->browser->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->browser->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->browser->setFrameFocus($name);
+ }
+
+ /**
+ * Clears the frame focus. All frames will be searched
+ * for content.
+ * @access public
+ */
+ function clearFrameFocus() {
+ return $this->browser->clearFrameFocus();
+ }
+
+ /**
+ * Clicks a visible text item. Will first try buttons,
+ * then links and then images.
+ * @param string $label Visible text or alt text.
+ * @return string/boolean Raw page or false.
+ * @access public
+ */
+ function click($label) {
+ return $this->failOnError($this->browser->click($label));
+ }
+
+ /**
+ * Checks for a click target.
+ * @param string $label Visible text or alt text.
+ * @return boolean True if click target.
+ * @access public
+ */
+ function assertClickable($label, $message = '%s') {
+ return $this->assertTrue(
+ $this->browser->isClickable($label),
+ sprintf($message, "Click target [$label] should exist"));
+ }
+
+ /**
+ * Clicks the submit button by label. The owning
+ * form will be submitted by this.
+ * @param string $label Button label. An unlabeled
+ * button can be triggered by 'Submit'.
+ * @param hash $additional Additional form values.
+ * @return boolean/string Page on success, else false.
+ * @access public
+ */
+ function clickSubmit($label = 'Submit', $additional = false) {
+ return $this->failOnError(
+ $this->browser->clickSubmit($label, $additional));
+ }
+
+ /**
+ * Clicks the submit button by name attribute. The owning
+ * form will be submitted by this.
+ * @param string $name Name attribute of button.
+ * @param hash $additional Additional form values.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickSubmitByName($name, $additional = false) {
+ return $this->failOnError(
+ $this->browser->clickSubmitByName($name, $additional));
+ }
+
+ /**
+ * Clicks the submit button by ID attribute. The owning
+ * form will be submitted by this.
+ * @param string $id ID attribute of button.
+ * @param hash $additional Additional form values.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickSubmitById($id, $additional = false) {
+ return $this->failOnError(
+ $this->browser->clickSubmitById($id, $additional));
+ }
+
+ /**
+ * Checks for a valid button label.
+ * @param string $label Visible text.
+ * @return boolean True if click target.
+ * @access public
+ */
+ function assertSubmit($label, $message = '%s') {
+ return $this->assertTrue(
+ $this->browser->isSubmit($label),
+ sprintf($message, "Submit button [$label] should exist"));
+ }
+
+ /**
+ * 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 Alt attribute of button.
+ * @param integer $x X-coordinate of imaginary click.
+ * @param integer $y Y-coordinate of imaginary click.
+ * @param hash $additional Additional form values.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickImage($label, $x = 1, $y = 1, $additional = false) {
+ return $this->failOnError(
+ $this->browser->clickImage($label, $x, $y, $additional));
+ }
+
+ /**
+ * 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 values.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickImageByName($name, $x = 1, $y = 1, $additional = false) {
+ return $this->failOnError(
+ $this->browser->clickImageByName($name, $x, $y, $additional));
+ }
+
+ /**
+ * 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 values.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickImageById($id, $x = 1, $y = 1, $additional = false) {
+ return $this->failOnError(
+ $this->browser->clickImageById($id, $x, $y, $additional));
+ }
+
+ /**
+ * Checks for a valid image with atht alt text or title.
+ * @param string $label Visible text.
+ * @return boolean True if click target.
+ * @access public
+ */
+ function assertImage($label, $message = '%s') {
+ return $this->assertTrue(
+ $this->browser->isImage($label),
+ sprintf($message, "Image with text [$label] should exist"));
+ }
+
+ /**
+ * Submits a form by the ID.
+ * @param string $id Form ID. No button information
+ * is submitted this way.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function submitFormById($id, $additional = false) {
+ return $this->failOnError($this->browser->submitFormById($id, $additional));
+ }
+
+ /**
+ * Follows a link by name. Will click the first link
+ * found with this link text by default, or a later
+ * one if an index is given. Match is case insensitive
+ * with normalised space.
+ * @param string $label Text between the anchor tags.
+ * @param integer $index Link position counting from zero.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickLink($label, $index = 0) {
+ return $this->failOnError($this->browser->clickLink($label, $index));
+ }
+
+ /**
+ * Follows a link by id attribute.
+ * @param string $id ID attribute value.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickLinkById($id) {
+ return $this->failOnError($this->browser->clickLinkById($id));
+ }
+
+ /**
+ * Tests for the presence of a link label. Match is
+ * case insensitive with normalised space.
+ * @param string $label Text between the anchor tags.
+ * @param mixed $expected Expected URL or expectation object.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if link present.
+ * @access public
+ */
+ function assertLink($label, $expected = true, $message = '%s') {
+ $url = $this->browser->getLink($label);
+ if ($expected === true || ($expected !== true && $url === false)) {
+ return $this->assertTrue($url !== false, sprintf($message, "Link [$label] should exist"));
+ }
+ if (! SimpleExpectation::isExpectation($expected)) {
+ $expected = new IdenticalExpectation($expected);
+ }
+ return $this->assert($expected, $url->asString(), sprintf($message, "Link [$label] should match"));
+ }
+
+ /**
+ * Tests for the non-presence of a link label. Match is
+ * case insensitive with normalised space.
+ * @param string/integer $label Text between the anchor tags
+ * or ID attribute.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if link missing.
+ * @access public
+ */
+ function assertNoLink($label, $message = '%s') {
+ return $this->assertTrue(
+ $this->browser->getLink($label) === false,
+ sprintf($message, "Link [$label] should not exist"));
+ }
+
+ /**
+ * Tests for the presence of a link id attribute.
+ * @param string $id Id attribute value.
+ * @param mixed $expected Expected URL or expectation object.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if link present.
+ * @access public
+ */
+ function assertLinkById($id, $expected = true, $message = '%s') {
+ $url = $this->browser->getLinkById($id);
+ if ($expected === true) {
+ return $this->assertTrue($url !== false, sprintf($message, "Link ID [$id] should exist"));
+ }
+ if (! SimpleExpectation::isExpectation($expected)) {
+ $expected = new IdenticalExpectation($expected);
+ }
+ return $this->assert($expected, $url->asString(), sprintf($message, "Link ID [$id] should match"));
+ }
+
+ /**
+ * Tests for the non-presence of a link label. Match is
+ * case insensitive with normalised space.
+ * @param string $id Id attribute value.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if link missing.
+ * @access public
+ */
+ function assertNoLinkById($id, $message = '%s') {
+ return $this->assertTrue(
+ $this->browser->getLinkById($id) === false,
+ sprintf($message, "Link ID [$id] should not exist"));
+ }
+
+ /**
+ * Sets all form fields with that label, or name if there
+ * is no label attached.
+ * @param string $name Name of field in forms.
+ * @param string $value New value of field.
+ * @return boolean True if field exists, otherwise false.
+ * @access public
+ */
+ function setField($label, $value, $position=false) {
+ return $this->browser->setField($label, $value, $position);
+ }
+
+ /**
+ * 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 setFieldByName($name, $value, $position=false) {
+ return $this->browser->setFieldByName($name, $value, $position);
+ }
+
+ /**
+ * Sets all form fields with that id.
+ * @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->browser->setFieldById($id, $value);
+ }
+
+ /**
+ * Confirms that the form element is currently set
+ * to the expected value. A missing form will always
+ * fail. If no value is given then only the existence
+ * of the field is checked.
+ * @param string $name Name of field in forms.
+ * @param mixed $expected Expected string/array value or
+ * false for unset fields.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertField($label, $expected = true, $message = '%s') {
+ $value = $this->browser->getField($label);
+ return $this->assertFieldValue($label, $value, $expected, $message);
+ }
+
+ /**
+ * Confirms that the form element is currently set
+ * to the expected value. A missing form element will always
+ * fail. If no value is given then only the existence
+ * of the field is checked.
+ * @param string $name Name of field in forms.
+ * @param mixed $expected Expected string/array value or
+ * false for unset fields.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertFieldByName($name, $expected = true, $message = '%s') {
+ $value = $this->browser->getFieldByName($name);
+ return $this->assertFieldValue($name, $value, $expected, $message);
+ }
+
+ /**
+ * Confirms that the form element is currently set
+ * to the expected value. A missing form will always
+ * fail. If no ID is given then only the existence
+ * of the field is checked.
+ * @param string/integer $id Name of field in forms.
+ * @param mixed $expected Expected string/array value or
+ * false for unset fields.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertFieldById($id, $expected = true, $message = '%s') {
+ $value = $this->browser->getFieldById($id);
+ return $this->assertFieldValue($id, $value, $expected, $message);
+ }
+
+ /**
+ * Tests the field value against the expectation.
+ * @param string $identifier Name, ID or label.
+ * @param mixed $value Current field value.
+ * @param mixed $expected Expected value to match.
+ * @param string $message Failure message.
+ * @return boolean True if pass
+ * @access protected
+ */
+ protected function assertFieldValue($identifier, $value, $expected, $message) {
+ if ($expected === true) {
+ return $this->assertTrue(
+ isset($value),
+ sprintf($message, "Field [$identifier] should exist"));
+ }
+ if (! SimpleExpectation::isExpectation($expected)) {
+ $identifier = str_replace('%', '%%', $identifier);
+ $expected = new FieldExpectation(
+ $expected,
+ "Field [$identifier] should match with [%s]");
+ }
+ return $this->assert($expected, $value, $message);
+ }
+
+ /**
+ * Checks the response code against a list
+ * of possible values.
+ * @param array $responses Possible responses for a pass.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertResponse($responses, $message = '%s') {
+ $responses = (is_array($responses) ? $responses : array($responses));
+ $code = $this->browser->getResponseCode();
+ $message = sprintf($message, "Expecting response in [" .
+ implode(", ", $responses) . "] got [$code]");
+ return $this->assertTrue(in_array($code, $responses), $message);
+ }
+
+ /**
+ * Checks the mime type against a list
+ * of possible values.
+ * @param array $types Possible mime types for a pass.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertMime($types, $message = '%s') {
+ $types = (is_array($types) ? $types : array($types));
+ $type = $this->browser->getMimeType();
+ $message = sprintf($message, "Expecting mime type in [" .
+ implode(", ", $types) . "] got [$type]");
+ return $this->assertTrue(in_array($type, $types), $message);
+ }
+
+ /**
+ * Attempt to match the authentication type within
+ * the security realm we are currently matching.
+ * @param string $authentication Usually basic.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertAuthentication($authentication = false, $message = '%s') {
+ if (! $authentication) {
+ $message = sprintf($message, "Expected any authentication type, got [" .
+ $this->browser->getAuthentication() . "]");
+ return $this->assertTrue(
+ $this->browser->getAuthentication(),
+ $message);
+ } else {
+ $message = sprintf($message, "Expected authentication [$authentication] got [" .
+ $this->browser->getAuthentication() . "]");
+ return $this->assertTrue(
+ strtolower($this->browser->getAuthentication()) == strtolower($authentication),
+ $message);
+ }
+ }
+
+ /**
+ * Checks that no authentication is necessary to view
+ * the desired page.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoAuthentication($message = '%s') {
+ $message = sprintf($message, "Expected no authentication type, got [" .
+ $this->browser->getAuthentication() . "]");
+ return $this->assertFalse($this->browser->getAuthentication(), $message);
+ }
+
+ /**
+ * Attempts to match the current security realm.
+ * @param string $realm Name of security realm.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertRealm($realm, $message = '%s') {
+ if (! SimpleExpectation::isExpectation($realm)) {
+ $realm = new EqualExpectation($realm);
+ }
+ return $this->assert(
+ $realm,
+ $this->browser->getRealm(),
+ "Expected realm -> $message");
+ }
+
+ /**
+ * Checks each header line for the required value. If no
+ * value is given then only an existence check is made.
+ * @param string $header Case insensitive header name.
+ * @param mixed $value Case sensitive trimmed string to
+ * match against. An expectation object
+ * can be used for pattern matching.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertHeader($header, $value = false, $message = '%s') {
+ return $this->assert(
+ new HttpHeaderExpectation($header, $value),
+ $this->browser->getHeaders(),
+ $message);
+ }
+
+ /**
+ * Confirms that the header type has not been received.
+ * Only the landing page is checked. If you want to check
+ * redirect pages, then you should limit redirects so
+ * as to capture the page you want.
+ * @param string $header Case insensitive header name.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoHeader($header, $message = '%s') {
+ return $this->assert(
+ new NoHttpHeaderExpectation($header),
+ $this->browser->getHeaders(),
+ $message);
+ }
+
+ /**
+ * Tests the text between the title tags.
+ * @param string/SimpleExpectation $title Expected title.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertTitle($title = false, $message = '%s') {
+ if (! SimpleExpectation::isExpectation($title)) {
+ $title = new EqualExpectation($title);
+ }
+ return $this->assert($title, $this->browser->getTitle(), $message);
+ }
+
+ /**
+ * Will trigger a pass if the text is found in the plain
+ * text form of the page.
+ * @param string $text Text to look for.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertText($text, $message = '%s') {
+ return $this->assert(
+ new TextExpectation($text),
+ $this->browser->getContentAsText(),
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the text is not found in the plain
+ * text form of the page.
+ * @param string $text Text to look for.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoText($text, $message = '%s') {
+ return $this->assert(
+ new NoTextExpectation($text),
+ $this->browser->getContentAsText(),
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the Perl regex pattern
+ * is found in the raw content.
+ * @param string $pattern Perl regex to look for including
+ * the regex delimiters.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertPattern($pattern, $message = '%s') {
+ return $this->assert(
+ new PatternExpectation($pattern),
+ $this->browser->getContent(),
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the perl regex pattern
+ * is not present in raw content.
+ * @param string $pattern Perl regex to look for including
+ * the regex delimiters.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoPattern($pattern, $message = '%s') {
+ return $this->assert(
+ new NoPatternExpectation($pattern),
+ $this->browser->getContent(),
+ $message);
+ }
+
+ /**
+ * Checks that a cookie is set for the current page
+ * and optionally checks the value.
+ * @param string $name Name of cookie to test.
+ * @param string $expected Expected value as a string or
+ * false if any value will do.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertCookie($name, $expected = false, $message = '%s') {
+ $value = $this->getCookie($name);
+ if (! $expected) {
+ return $this->assertTrue(
+ $value,
+ sprintf($message, "Expecting cookie [$name]"));
+ }
+ if (! SimpleExpectation::isExpectation($expected)) {
+ $expected = new EqualExpectation($expected);
+ }
+ return $this->assert($expected, $value, "Expecting cookie [$name] -> $message");
+ }
+
+ /**
+ * Checks that no cookie is present or that it has
+ * been successfully cleared.
+ * @param string $name Name of cookie to test.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoCookie($name, $message = '%s') {
+ return $this->assertTrue(
+ $this->getCookie($name) === null or $this->getCookie($name) === false,
+ sprintf($message, "Not expecting cookie [$name]"));
+ }
+
+ /**
+ * Called from within the test methods to register
+ * passes and failures.
+ * @param boolean $result Pass on true.
+ * @param string $message Message to display describing
+ * the test state.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertTrue($result, $message = '%s') {
+ return $this->assert(new TrueExpectation(), $result, $message);
+ }
+
+ /**
+ * Will be true on false and vice versa. False
+ * is the PHP definition of false, so that null,
+ * empty strings, zero and an empty array all count
+ * as false.
+ * @param boolean $result Pass on false.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertFalse($result, $message = '%s') {
+ return $this->assert(new FalseExpectation(), $result, $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * the same value only. Otherwise a fail. This
+ * is for testing hand extracted text, etc.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertEqual($first, $second, $message = '%s') {
+ return $this->assert(
+ new EqualExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * a different value. Otherwise a fail. This
+ * is for testing hand extracted text, etc.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNotEqual($first, $second, $message = '%s') {
+ return $this->assert(
+ new NotEqualExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Uses a stack trace to find the line of an assertion.
+ * @return string Line number of first assert*
+ * method embedded in format string.
+ * @access public
+ */
+ function getAssertionLine() {
+ $trace = new SimpleStackTrace(array('assert', 'click', 'pass', 'fail'));
+ return $trace->traceMethod();
+ }
+}
+?> \ No newline at end of file
diff --git a/3rdparty/simpletest/xml.php b/3rdparty/simpletest/xml.php
new file mode 100755
index 00000000000..54fb6f5b16d
--- /dev/null
+++ b/3rdparty/simpletest/xml.php
@@ -0,0 +1,647 @@
+<?php
+/**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: xml.php 1787 2008-04-26 20:35:39Z pp11 $
+ */
+
+/**#@+
+ * include other SimpleTest class files
+ */
+require_once(dirname(__FILE__) . '/scorer.php');
+/**#@-*/
+
+/**
+ * Creates the XML needed for remote communication
+ * by SimpleTest.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class XmlReporter extends SimpleReporter {
+ private $indent;
+ private $namespace;
+
+ /**
+ * Sets up indentation and namespace.
+ * @param string $namespace Namespace to add to each tag.
+ * @param string $indent Indenting to add on each nesting.
+ * @access public
+ */
+ function __construct($namespace = false, $indent = ' ') {
+ parent::__construct();
+ $this->namespace = ($namespace ? $namespace . ':' : '');
+ $this->indent = $indent;
+ }
+
+ /**
+ * Calculates the pretty printing indent level
+ * from the current level of nesting.
+ * @param integer $offset Extra indenting level.
+ * @return string Leading space.
+ * @access protected
+ */
+ protected function getIndent($offset = 0) {
+ return str_repeat(
+ $this->indent,
+ count($this->getTestList()) + $offset);
+ }
+
+ /**
+ * Converts character string to parsed XML
+ * entities string.
+ * @param string text Unparsed character data.
+ * @return string Parsed character data.
+ * @access public
+ */
+ function toParsedXml($text) {
+ return str_replace(
+ array('&', '<', '>', '"', '\''),
+ array('&amp;', '&lt;', '&gt;', '&quot;', '&apos;'),
+ $text);
+ }
+
+ /**
+ * Paints the start of a group test.
+ * @param string $test_name Name of test that is starting.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($test_name, $size) {
+ parent::paintGroupStart($test_name, $size);
+ print $this->getIndent();
+ print "<" . $this->namespace . "group size=\"$size\">\n";
+ print $this->getIndent(1);
+ print "<" . $this->namespace . "name>" .
+ $this->toParsedXml($test_name) .
+ "</" . $this->namespace . "name>\n";
+ }
+
+ /**
+ * Paints the end of a group test.
+ * @param string $test_name Name of test that is ending.
+ * @access public
+ */
+ function paintGroupEnd($test_name) {
+ print $this->getIndent();
+ print "</" . $this->namespace . "group>\n";
+ parent::paintGroupEnd($test_name);
+ }
+
+ /**
+ * Paints the start of a test case.
+ * @param string $test_name Name of test that is starting.
+ * @access public
+ */
+ function paintCaseStart($test_name) {
+ parent::paintCaseStart($test_name);
+ print $this->getIndent();
+ print "<" . $this->namespace . "case>\n";
+ print $this->getIndent(1);
+ print "<" . $this->namespace . "name>" .
+ $this->toParsedXml($test_name) .
+ "</" . $this->namespace . "name>\n";
+ }
+
+ /**
+ * Paints the end of a test case.
+ * @param string $test_name Name of test that is ending.
+ * @access public
+ */
+ function paintCaseEnd($test_name) {
+ print $this->getIndent();
+ print "</" . $this->namespace . "case>\n";
+ parent::paintCaseEnd($test_name);
+ }
+
+ /**
+ * Paints the start of a test method.
+ * @param string $test_name Name of test that is starting.
+ * @access public
+ */
+ function paintMethodStart($test_name) {
+ parent::paintMethodStart($test_name);
+ print $this->getIndent();
+ print "<" . $this->namespace . "test>\n";
+ print $this->getIndent(1);
+ print "<" . $this->namespace . "name>" .
+ $this->toParsedXml($test_name) .
+ "</" . $this->namespace . "name>\n";
+ }
+
+ /**
+ * Paints the end of a test method.
+ * @param string $test_name Name of test that is ending.
+ * @param integer $progress Number of test cases ending.
+ * @access public
+ */
+ function paintMethodEnd($test_name) {
+ print $this->getIndent();
+ print "</" . $this->namespace . "test>\n";
+ parent::paintMethodEnd($test_name);
+ }
+
+ /**
+ * Paints pass as XML.
+ * @param string $message Message to encode.
+ * @access public
+ */
+ function paintPass($message) {
+ parent::paintPass($message);
+ print $this->getIndent(1);
+ print "<" . $this->namespace . "pass>";
+ print $this->toParsedXml($message);
+ print "</" . $this->namespace . "pass>\n";
+ }
+
+ /**
+ * Paints failure as XML.
+ * @param string $message Message to encode.
+ * @access public
+ */
+ function paintFail($message) {
+ parent::paintFail($message);
+ print $this->getIndent(1);
+ print "<" . $this->namespace . "fail>";
+ print $this->toParsedXml($message);
+ print "</" . $this->namespace . "fail>\n";
+ }
+
+ /**
+ * Paints error as XML.
+ * @param string $message Message to encode.
+ * @access public
+ */
+ function paintError($message) {
+ parent::paintError($message);
+ print $this->getIndent(1);
+ print "<" . $this->namespace . "exception>";
+ print $this->toParsedXml($message);
+ print "</" . $this->namespace . "exception>\n";
+ }
+
+ /**
+ * Paints exception as XML.
+ * @param Exception $exception Exception to encode.
+ * @access public
+ */
+ function paintException($exception) {
+ parent::paintException($exception);
+ print $this->getIndent(1);
+ print "<" . $this->namespace . "exception>";
+ $message = 'Unexpected exception of type [' . get_class($exception) .
+ '] with message ['. $exception->getMessage() .
+ '] in ['. $exception->getFile() .
+ ' line ' . $exception->getLine() . ']';
+ print $this->toParsedXml($message);
+ print "</" . $this->namespace . "exception>\n";
+ }
+
+ /**
+ * Paints the skipping message and tag.
+ * @param string $message Text to display in skip tag.
+ * @access public
+ */
+ function paintSkip($message) {
+ parent::paintSkip($message);
+ print $this->getIndent(1);
+ print "<" . $this->namespace . "skip>";
+ print $this->toParsedXml($message);
+ print "</" . $this->namespace . "skip>\n";
+ }
+
+ /**
+ * Paints a simple supplementary message.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintMessage($message) {
+ parent::paintMessage($message);
+ print $this->getIndent(1);
+ print "<" . $this->namespace . "message>";
+ print $this->toParsedXml($message);
+ print "</" . $this->namespace . "message>\n";
+ }
+
+ /**
+ * Paints a formatted ASCII message such as a
+ * privateiable dump.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ parent::paintFormattedMessage($message);
+ print $this->getIndent(1);
+ print "<" . $this->namespace . "formatted>";
+ print "<![CDATA[$message]]>";
+ print "</" . $this->namespace . "formatted>\n";
+ }
+
+ /**
+ * Serialises the event object.
+ * @param string $type Event type as text.
+ * @param mixed $payload Message or object.
+ * @access public
+ */
+ function paintSignal($type, $payload) {
+ parent::paintSignal($type, $payload);
+ print $this->getIndent(1);
+ print "<" . $this->namespace . "signal type=\"$type\">";
+ print "<![CDATA[" . serialize($payload) . "]]>";
+ print "</" . $this->namespace . "signal>\n";
+ }
+
+ /**
+ * Paints the test document header.
+ * @param string $test_name First test top level
+ * to start.
+ * @access public
+ * @abstract
+ */
+ function paintHeader($test_name) {
+ if (! SimpleReporter::inCli()) {
+ header('Content-type: text/xml');
+ }
+ print "<?xml version=\"1.0\"";
+ if ($this->namespace) {
+ print " xmlns:" . $this->namespace .
+ "=\"www.lastcraft.com/SimpleTest/Beta3/Report\"";
+ }
+ print "?>\n";
+ print "<" . $this->namespace . "run>\n";
+ }
+
+ /**
+ * Paints the test document footer.
+ * @param string $test_name The top level test.
+ * @access public
+ * @abstract
+ */
+ function paintFooter($test_name) {
+ print "</" . $this->namespace . "run>\n";
+ }
+}
+
+/**
+ * Accumulator for incoming tag. Holds the
+ * incoming test structure information for
+ * later dispatch to the reporter.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class NestingXmlTag {
+ private $name;
+ private $attributes;
+
+ /**
+ * Sets the basic test information except
+ * the name.
+ * @param hash $attributes Name value pairs.
+ * @access public
+ */
+ function NestingXmlTag($attributes) {
+ $this->name = false;
+ $this->attributes = $attributes;
+ }
+
+ /**
+ * Sets the test case/method name.
+ * @param string $name Name of test.
+ * @access public
+ */
+ function setName($name) {
+ $this->name = $name;
+ }
+
+ /**
+ * Accessor for name.
+ * @return string Name of test.
+ * @access public
+ */
+ function getName() {
+ return $this->name;
+ }
+
+ /**
+ * Accessor for attributes.
+ * @return hash All attributes.
+ * @access protected
+ */
+ protected function getAttributes() {
+ return $this->attributes;
+ }
+}
+
+/**
+ * Accumulator for incoming method tag. Holds the
+ * incoming test structure information for
+ * later dispatch to the reporter.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class NestingMethodTag extends NestingXmlTag {
+
+ /**
+ * Sets the basic test information except
+ * the name.
+ * @param hash $attributes Name value pairs.
+ * @access public
+ */
+ function NestingMethodTag($attributes) {
+ $this->NestingXmlTag($attributes);
+ }
+
+ /**
+ * Signals the appropriate start event on the
+ * listener.
+ * @param SimpleReporter $listener Target for events.
+ * @access public
+ */
+ function paintStart(&$listener) {
+ $listener->paintMethodStart($this->getName());
+ }
+
+ /**
+ * Signals the appropriate end event on the
+ * listener.
+ * @param SimpleReporter $listener Target for events.
+ * @access public
+ */
+ function paintEnd(&$listener) {
+ $listener->paintMethodEnd($this->getName());
+ }
+}
+
+/**
+ * Accumulator for incoming case tag. Holds the
+ * incoming test structure information for
+ * later dispatch to the reporter.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class NestingCaseTag extends NestingXmlTag {
+
+ /**
+ * Sets the basic test information except
+ * the name.
+ * @param hash $attributes Name value pairs.
+ * @access public
+ */
+ function NestingCaseTag($attributes) {
+ $this->NestingXmlTag($attributes);
+ }
+
+ /**
+ * Signals the appropriate start event on the
+ * listener.
+ * @param SimpleReporter $listener Target for events.
+ * @access public
+ */
+ function paintStart(&$listener) {
+ $listener->paintCaseStart($this->getName());
+ }
+
+ /**
+ * Signals the appropriate end event on the
+ * listener.
+ * @param SimpleReporter $listener Target for events.
+ * @access public
+ */
+ function paintEnd(&$listener) {
+ $listener->paintCaseEnd($this->getName());
+ }
+}
+
+/**
+ * Accumulator for incoming group tag. Holds the
+ * incoming test structure information for
+ * later dispatch to the reporter.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class NestingGroupTag extends NestingXmlTag {
+
+ /**
+ * Sets the basic test information except
+ * the name.
+ * @param hash $attributes Name value pairs.
+ * @access public
+ */
+ function NestingGroupTag($attributes) {
+ $this->NestingXmlTag($attributes);
+ }
+
+ /**
+ * Signals the appropriate start event on the
+ * listener.
+ * @param SimpleReporter $listener Target for events.
+ * @access public
+ */
+ function paintStart(&$listener) {
+ $listener->paintGroupStart($this->getName(), $this->getSize());
+ }
+
+ /**
+ * Signals the appropriate end event on the
+ * listener.
+ * @param SimpleReporter $listener Target for events.
+ * @access public
+ */
+ function paintEnd(&$listener) {
+ $listener->paintGroupEnd($this->getName());
+ }
+
+ /**
+ * The size in the attributes.
+ * @return integer Value of size attribute or zero.
+ * @access public
+ */
+ function getSize() {
+ $attributes = $this->getAttributes();
+ if (isset($attributes['SIZE'])) {
+ return (integer)$attributes['SIZE'];
+ }
+ return 0;
+ }
+}
+
+/**
+ * Parser for importing the output of the XmlReporter.
+ * Dispatches that output to another reporter.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleTestXmlParser {
+ private $listener;
+ private $expat;
+ private $tag_stack;
+ private $in_content_tag;
+ private $content;
+ private $attributes;
+
+ /**
+ * Loads a listener with the SimpleReporter
+ * interface.
+ * @param SimpleReporter $listener Listener of tag events.
+ * @access public
+ */
+ function SimpleTestXmlParser(&$listener) {
+ $this->listener = &$listener;
+ $this->expat = &$this->createParser();
+ $this->tag_stack = array();
+ $this->in_content_tag = false;
+ $this->content = '';
+ $this->attributes = array();
+ }
+
+ /**
+ * Parses a block of XML sending the results to
+ * the listener.
+ * @param string $chunk Block of text to read.
+ * @return boolean True if valid XML.
+ * @access public
+ */
+ function parse($chunk) {
+ if (! xml_parse($this->expat, $chunk)) {
+ trigger_error('XML parse error with ' .
+ xml_error_string(xml_get_error_code($this->expat)));
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Sets up expat as the XML parser.
+ * @return resource Expat handle.
+ * @access protected
+ */
+ protected function &createParser() {
+ $expat = xml_parser_create();
+ xml_set_object($expat, $this);
+ xml_set_element_handler($expat, 'startElement', 'endElement');
+ xml_set_character_data_handler($expat, 'addContent');
+ xml_set_default_handler($expat, 'defaultContent');
+ return $expat;
+ }
+
+ /**
+ * Opens a new test nesting level.
+ * @return NestedXmlTag The group, case or method tag
+ * to start.
+ * @access private
+ */
+ protected function pushNestingTag($nested) {
+ array_unshift($this->tag_stack, $nested);
+ }
+
+ /**
+ * Accessor for current test structure tag.
+ * @return NestedXmlTag The group, case or method tag
+ * being parsed.
+ * @access private
+ */
+ protected function &getCurrentNestingTag() {
+ return $this->tag_stack[0];
+ }
+
+ /**
+ * Ends a nesting tag.
+ * @return NestedXmlTag The group, case or method tag
+ * just finished.
+ * @access private
+ */
+ protected function popNestingTag() {
+ return array_shift($this->tag_stack);
+ }
+
+ /**
+ * Test if tag is a leaf node with only text content.
+ * @param string $tag XML tag name.
+ * @return @boolean True if leaf, false if nesting.
+ * @private
+ */
+ protected function isLeaf($tag) {
+ return in_array($tag, array(
+ 'NAME', 'PASS', 'FAIL', 'EXCEPTION', 'SKIP', 'MESSAGE', 'FORMATTED', 'SIGNAL'));
+ }
+
+ /**
+ * Handler for start of event element.
+ * @param resource $expat Parser handle.
+ * @param string $tag Element name.
+ * @param hash $attributes Name value pairs.
+ * Attributes without content
+ * are marked as true.
+ * @access protected
+ */
+ protected function startElement($expat, $tag, $attributes) {
+ $this->attributes = $attributes;
+ if ($tag == 'GROUP') {
+ $this->pushNestingTag(new NestingGroupTag($attributes));
+ } elseif ($tag == 'CASE') {
+ $this->pushNestingTag(new NestingCaseTag($attributes));
+ } elseif ($tag == 'TEST') {
+ $this->pushNestingTag(new NestingMethodTag($attributes));
+ } elseif ($this->isLeaf($tag)) {
+ $this->in_content_tag = true;
+ $this->content = '';
+ }
+ }
+
+ /**
+ * End of element event.
+ * @param resource $expat Parser handle.
+ * @param string $tag Element name.
+ * @access protected
+ */
+ protected function endElement($expat, $tag) {
+ $this->in_content_tag = false;
+ if (in_array($tag, array('GROUP', 'CASE', 'TEST'))) {
+ $nesting_tag = $this->popNestingTag();
+ $nesting_tag->paintEnd($this->listener);
+ } elseif ($tag == 'NAME') {
+ $nesting_tag = &$this->getCurrentNestingTag();
+ $nesting_tag->setName($this->content);
+ $nesting_tag->paintStart($this->listener);
+ } elseif ($tag == 'PASS') {
+ $this->listener->paintPass($this->content);
+ } elseif ($tag == 'FAIL') {
+ $this->listener->paintFail($this->content);
+ } elseif ($tag == 'EXCEPTION') {
+ $this->listener->paintError($this->content);
+ } elseif ($tag == 'SKIP') {
+ $this->listener->paintSkip($this->content);
+ } elseif ($tag == 'SIGNAL') {
+ $this->listener->paintSignal(
+ $this->attributes['TYPE'],
+ unserialize($this->content));
+ } elseif ($tag == 'MESSAGE') {
+ $this->listener->paintMessage($this->content);
+ } elseif ($tag == 'FORMATTED') {
+ $this->listener->paintFormattedMessage($this->content);
+ }
+ }
+
+ /**
+ * Content between start and end elements.
+ * @param resource $expat Parser handle.
+ * @param string $text Usually output messages.
+ * @access protected
+ */
+ protected function addContent($expat, $text) {
+ if ($this->in_content_tag) {
+ $this->content .= $text;
+ }
+ return true;
+ }
+
+ /**
+ * XML and Doctype handler. Discards all such content.
+ * @param resource $expat Parser handle.
+ * @param string $default Text of default content.
+ * @access protected
+ */
+ protected function defaultContent($expat, $default) {
+ }
+}
+?>