From b2e97539e7af7712b04dd5c2610a454d09aa0333 Mon Sep 17 00:00:00 2001 From: wei <> Date: Fri, 7 Jul 2006 23:18:19 +0000 Subject: Update simpletest --- tests/test_tools/simpletest/CHANGELOG | 2 +- .../simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE | 119 ++- tests/test_tools/simpletest/LICENSE | 507 ++++++++++++- tests/test_tools/simpletest/README | 22 +- tests/test_tools/simpletest/VERSION | 2 +- tests/test_tools/simpletest/authentication.php | 23 +- tests/test_tools/simpletest/browser.php | 397 +++++----- tests/test_tools/simpletest/collector.php | 115 +++ tests/test_tools/simpletest/compatibility.php | 184 +++++ tests/test_tools/simpletest/cookies.php | 380 ++++++++++ tests/test_tools/simpletest/detached.php | 96 +++ .../docs/en/authentication_documentation.html | 48 +- .../simpletest/docs/en/browser_documentation.html | 27 +- .../docs/en/expectation_documentation.html | 40 +- .../docs/en/form_testing_documentation.html | 13 +- .../docs/en/group_test_documentation.html | 5 +- tests/test_tools/simpletest/docs/en/index.html | 48 +- .../docs/en/mock_objects_documentation.html | 272 +++---- tests/test_tools/simpletest/docs/en/overview.html | 154 ++-- .../docs/en/partial_mocks_documentation.html | 3 - .../simpletest/docs/en/reporter_documentation.html | 3 - .../docs/en/unit_test_documentation.html | 19 +- .../docs/en/web_tester_documentation.html | 31 +- .../docs/fr/authentication_documentation.html | 264 ------- .../simpletest/docs/fr/browser_documentation.html | 329 -------- tests/test_tools/simpletest/docs/fr/docs.css | 84 --- .../docs/fr/expectation_documentation.html | 263 ------- .../docs/fr/form_testing_documentation.html | 235 ------ .../docs/fr/group_test_documentation.html | 288 ------- tests/test_tools/simpletest/docs/fr/index.html | 343 --------- .../docs/fr/mock_objects_documentation.html | 492 ------------ tests/test_tools/simpletest/docs/fr/overview.html | 294 -------- .../docs/fr/partial_mocks_documentation.html | 333 --------- .../simpletest/docs/fr/reporter_documentation.html | 386 ---------- .../docs/fr/server_stubs_documentation.html | 279 ------- .../docs/fr/unit_test_documentation.html | 306 -------- .../docs/fr/web_tester_documentation.html | 397 ---------- tests/test_tools/simpletest/dumper.php | 54 +- tests/test_tools/simpletest/encoding.php | 493 ++++++++++-- tests/test_tools/simpletest/errors.php | 67 +- tests/test_tools/simpletest/exceptions.php | 46 ++ tests/test_tools/simpletest/expectation.php | 234 +++++- .../simpletest/extensions/pear_test_case.php | 199 ----- .../simpletest/extensions/phpunit_test_case.php | 108 --- tests/test_tools/simpletest/form.php | 395 ++-------- tests/test_tools/simpletest/frames.php | 241 ++---- tests/test_tools/simpletest/http.php | 365 ++------- tests/test_tools/simpletest/invoker.php | 139 ++++ tests/test_tools/simpletest/mock_objects.php | 832 ++++++++++----------- tests/test_tools/simpletest/page.php | 584 ++++++++------- tests/test_tools/simpletest/parser.php | 213 +++--- tests/test_tools/simpletest/reflection_php4.php | 115 +++ tests/test_tools/simpletest/reflection_php5.php | 275 +++++++ tests/test_tools/simpletest/remote.php | 8 +- tests/test_tools/simpletest/reporter.php | 178 ++++- tests/test_tools/simpletest/scorer.php | 507 +++++++++++-- tests/test_tools/simpletest/selector.php | 133 ++++ tests/test_tools/simpletest/shell_tester.php | 63 +- tests/test_tools/simpletest/simpletest.php | 282 +++++++ tests/test_tools/simpletest/socket.php | 28 +- tests/test_tools/simpletest/tag.php | 553 +++++++++----- tests/test_tools/simpletest/test_case.php | 684 +++++++++++++++++ tests/test_tools/simpletest/unit_tester.php | 182 +++-- tests/test_tools/simpletest/url.php | 105 +-- tests/test_tools/simpletest/user_agent.php | 297 ++------ tests/test_tools/simpletest/web_tester.php | 491 +++++++----- tests/test_tools/simpletest/xml.php | 107 ++- 67 files changed, 7001 insertions(+), 7780 deletions(-) create mode 100644 tests/test_tools/simpletest/collector.php create mode 100644 tests/test_tools/simpletest/compatibility.php create mode 100644 tests/test_tools/simpletest/cookies.php create mode 100644 tests/test_tools/simpletest/detached.php delete mode 100755 tests/test_tools/simpletest/docs/fr/authentication_documentation.html delete mode 100755 tests/test_tools/simpletest/docs/fr/browser_documentation.html delete mode 100755 tests/test_tools/simpletest/docs/fr/docs.css delete mode 100755 tests/test_tools/simpletest/docs/fr/expectation_documentation.html delete mode 100755 tests/test_tools/simpletest/docs/fr/form_testing_documentation.html delete mode 100755 tests/test_tools/simpletest/docs/fr/group_test_documentation.html delete mode 100755 tests/test_tools/simpletest/docs/fr/index.html delete mode 100755 tests/test_tools/simpletest/docs/fr/mock_objects_documentation.html delete mode 100755 tests/test_tools/simpletest/docs/fr/overview.html delete mode 100755 tests/test_tools/simpletest/docs/fr/partial_mocks_documentation.html delete mode 100755 tests/test_tools/simpletest/docs/fr/reporter_documentation.html delete mode 100755 tests/test_tools/simpletest/docs/fr/server_stubs_documentation.html delete mode 100755 tests/test_tools/simpletest/docs/fr/unit_test_documentation.html delete mode 100755 tests/test_tools/simpletest/docs/fr/web_tester_documentation.html create mode 100644 tests/test_tools/simpletest/exceptions.php delete mode 100755 tests/test_tools/simpletest/extensions/pear_test_case.php delete mode 100755 tests/test_tools/simpletest/extensions/phpunit_test_case.php create mode 100644 tests/test_tools/simpletest/invoker.php create mode 100644 tests/test_tools/simpletest/reflection_php4.php create mode 100644 tests/test_tools/simpletest/reflection_php5.php create mode 100644 tests/test_tools/simpletest/selector.php create mode 100644 tests/test_tools/simpletest/simpletest.php create mode 100644 tests/test_tools/simpletest/test_case.php (limited to 'tests/test_tools') diff --git a/tests/test_tools/simpletest/CHANGELOG b/tests/test_tools/simpletest/CHANGELOG index 961ce208..a7f890c5 100755 --- a/tests/test_tools/simpletest/CHANGELOG +++ b/tests/test_tools/simpletest/CHANGELOG @@ -2,5 +2,5 @@ June 7, 2005, by Qiang Xue (qiang.xue@gmail.com) ------------------------------------------------ - changed all class memeber declarations from 'var $varname' to 'private $varname'. - removed all reference usages, including creating new objects, returning and passing objects. -- modified expectation.php line 106 from 'function test($compare, &$nasty=false) {' to 'function test($compare) {'. +- modified expectation.php line 106 from 'function test($compare, $nasty=false) {' to 'function test($compare) {'. - added HtmlReporterWithCoverage.php \ No newline at end of file diff --git a/tests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE b/tests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE index 99c3be2d..4be59649 100755 --- a/tests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE +++ b/tests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE @@ -3,7 +3,116 @@ 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... +problems and their fixes... + +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 test case 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 ----------------------------------- @@ -29,7 +138,9 @@ 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. +that method to get the test case. Mock compatibility with other +unit testers is now deprecated as of 1.0.1alpha as PEAR::PHUnit2 +should soon have mock support of it's own. Broken code extending SimpleRunner ---------------------------------- @@ -142,13 +253,13 @@ test case expansion against the ease of writing user interfaces. Code such as... -$test = &new MyTestCase(); +$test = new MyTestCase(); $test->attachObserver(new TestHtmlDisplay()); $test->run(); ...should be rewritten as... -$test = &new MyTestCase(); +$test = new MyTestCase(); $test->run(new HtmlReporter()); If you previously attached multiple observers then the workaround diff --git a/tests/test_tools/simpletest/LICENSE b/tests/test_tools/simpletest/LICENSE index 93acab79..4a1f7201 100755 --- a/tests/test_tools/simpletest/LICENSE +++ b/tests/test_tools/simpletest/LICENSE @@ -1,49 +1,502 @@ -The Open Group Test Suite License + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 -Preamble + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin St, 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. -The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. +[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.] -Testing is essential for proper development and maintenance of standards-based products. + Preamble -For buyers: adequate conformance testing leads to reduced integration costs and protection of investments in applications, software and people. + 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. -For software developers: conformance testing of platforms and middleware greatly reduces the cost of developing and maintaining multi-platform application software. + 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. -For suppliers: In-depth testing increases customer satisfaction and keeps development and support costs in check. API conformance is highly measurable and suppliers who claim it must be able to substantiate that claim. + 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. -As such, since these are benchmark measures of conformance, we feel the integrity of test tools is of importance. In order to preserve the integrity of the existing conformance modes of this test package and to permit recipients of modified versions of this package to run the original test modes, this license requires that the original test modes be preserved. + 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. -If you find a bug in one of the standards mode test cases, please let us know so we can feed this back into the original, and also raise any specification issues with the appropriate bodies (for example the POSIX committees). + 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. -Definitions: + 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. - * "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - * "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - * "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. - * "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) -* "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. + 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. -1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. + 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. -2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. + 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. -3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least the following: + 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. -rename any non-standard executables and testcases so the names do not conflict with standard executables and testcases, which must also be provided, and provide a separate manual page for each non-standard executable and testcase that clearly documents how it differs from the Standard Version. + 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. -4. You may distribute the programs of this Package in object code or executable form, provided that you do at least the following: + 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. -accompany any non-standard executables and testcases with their corresponding Standard Version executables and testcases, giving the non-standard executables and testcases non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. + 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. -5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. + 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. -6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. + 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. -7.Subroutines supplied by you and linked into this Package shall not be considered part of this Package. + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION -8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. + 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". -9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + 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 End + 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. + + + Copyright (C) + + 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 St, 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. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/tests/test_tools/simpletest/README b/tests/test_tools/simpletest/README index 50fa4aaa..c2ff9b75 100755 --- a/tests/test_tools/simpletest/README +++ b/tests/test_tools/simpletest/README @@ -21,12 +21,6 @@ A web tester similar in concept to JWebUnit is also included. There is no JavaScript or tables support, but forms, authentication, cookies and frames are handled. -You are not tied to just using SimpleTest, though. The mocks and stubs -will work with other test frameworks and SimpleTest can use other -framework's (PHPUnit, PEAR::PhpUnit) test cases as it's own. The -web browser part of the web tester can also be used independently either -in other testers or as part of a scripting solution. - You can see a release schedule at http://www.lastcraft.com/overview.php which is also copied to the documentation folder with this release. A full PHPDocumenter API documentation exists at @@ -61,7 +55,7 @@ The full tests read some test data from the LastCraft site. If the site is down or has been modified for a later version then you will get spurious errors. A unit_tests.php failure on the other hand would be very serious. As far as we know we haven't yet managed to check in any -test failures so please correct us if you find one. +unit test failures so please correct us if you find one. Even if all of the tests run please verify that your existing test suites also function as expected. If they don't see the file... @@ -74,14 +68,18 @@ your current tests appear to run. There is a documentation folder which contains the core reference information in English and French, although this information is fairly basic. -You can find a tutorial on http://www.lastcraft.com/first_test_tutorial.php -to get you started and this material will eventually become included -with the project documentation. A French translation exists at +You can find a tutorial on... + +http://www.lastcraft.com/first_test_tutorial.php + +...to get you started and this material will eventually become included +with the project documentation. A French translation exists at... + http://www.onpk.net/index.php/2005/01/12/254-tutoriel-simpletest-decouvrir-les-tests-unitaires. If you download and use and possibly even extend this tool, please let us know. Any feedback, even bad, is always welcome and we will work to get -your suggestions into the version one release. Ideally please send your +your suggestions into the next release. Ideally please send your comments to... simpletest-support@lists.sourceforge.net @@ -105,6 +103,6 @@ really are invaluable, but sadly you are too many to mention in full. Thanks to all on the advanced PHP forum on SitePoint, especially Harry Feucks. Early adopters are always an inspiration. -yours Marcus Baker, Jason Sweat and Perrick Penet. +yours Marcus Baker, Jason Sweat, Travis Swicegood and Perrick Penet. -- marcus@lastcraft.com diff --git a/tests/test_tools/simpletest/VERSION b/tests/test_tools/simpletest/VERSION index d3827e75..9980c7df 100755 --- a/tests/test_tools/simpletest/VERSION +++ b/tests/test_tools/simpletest/VERSION @@ -1 +1 @@ -1.0 +1.0.1alpha3 \ No newline at end of file diff --git a/tests/test_tools/simpletest/authentication.php b/tests/test_tools/simpletest/authentication.php index 7b6ed4ba..bc413b2c 100644 --- a/tests/test_tools/simpletest/authentication.php +++ b/tests/test_tools/simpletest/authentication.php @@ -3,7 +3,7 @@ * Base include file for SimpleTest * @package SimpleTest * @subpackage WebTester - * @version $Id: authentication.php,v 1.9 2004/09/19 17:24:11 lastcraft Exp $ + * @version $Id: authentication.php,v 1.10 2005/07/26 01:27:18 lastcraft Exp $ */ /** * include http class @@ -100,7 +100,26 @@ * @access public */ function isWithin($url) { - return (strpos($url->getBasePath(), $this->_root) === 0); + if ($this->_isIn($this->_root, $url->getBasePath())) { + return true; + } + if ($this->_isIn($this->_root, $url->getBasePath() . $url->getPage() . '/')) { + return true; + } + return false; + } + + /** + * Tests to see if one string is a substring of + * another. + * @param string $part Small bit. + * @param string $whole Big bit. + * @return boolean True if the small bit is + * in the big bit. + * @access private + */ + function _isIn($part, $whole) { + return strpos($whole, $part) === 0; } } diff --git a/tests/test_tools/simpletest/browser.php b/tests/test_tools/simpletest/browser.php index 06e1b8d7..8e843b18 100644 --- a/tests/test_tools/simpletest/browser.php +++ b/tests/test_tools/simpletest/browser.php @@ -3,22 +3,25 @@ * Base include file for SimpleTest * @package SimpleTest * @subpackage WebTester - * @version $Id: browser.php,v 1.141 2005/02/22 02:39:21 lastcraft Exp $ + * @version $Id: browser.php,v 1.162 2006/02/05 01:07:49 lastcraft Exp $ */ - + /**#@+ * include other SimpleTest class files */ - require_once(dirname(__FILE__) . '/options.php'); + 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__) . '/selector.php'); require_once(dirname(__FILE__) . '/frames.php'); require_once(dirname(__FILE__) . '/user_agent.php'); /**#@-*/ - - define('DEFAULT_MAX_NESTED_FRAMES', 3); - + + if (!defined('DEFAULT_MAX_NESTED_FRAMES')) { + define('DEFAULT_MAX_NESTED_FRAMES', 3); + } + /** * Browser history list. * @package SimpleTest @@ -27,7 +30,7 @@ class SimpleBrowserHistory { protected $_sequence; protected $_position; - + /** * Starts empty. * @access public @@ -36,7 +39,7 @@ $this->_sequence = array(); $this->_position = -1; } - + /** * Test for no entries yet. * @return boolean True if empty. @@ -45,7 +48,7 @@ function _isEmpty() { return ($this->_position == -1); } - + /** * Test for being at the beginning. * @return boolean True if first. @@ -54,7 +57,7 @@ function _atBeginning() { return ($this->_position == 0) && ! $this->_isEmpty(); } - + /** * Test for being at the last entry. * @return boolean True if last. @@ -63,36 +66,21 @@ function _atEnd() { return ($this->_position + 1 >= count($this->_sequence)) && ! $this->_isEmpty(); } - + /** * Adds a successfully fetched page to the history. - * @param string $method GET or POST. * @param SimpleUrl $url URL of fetch. - * @param SimpleFormEncoding $parameters Any post data with the fetch. + * @param SimpleEncoding $parameters Any post data with the fetch. * @access public */ - function recordEntry($method, $url, $parameters) { + function recordEntry($url, $parameters) { $this->_dropFuture(); array_push( $this->_sequence, - array('method' => $method, 'url' => $url, 'parameters' => $parameters)); + array('url' => $url, 'parameters' => $parameters)); $this->_position++; } - - /** - * Last fetching method for current history - * position. - * @return string GET or POST for this point in - * the history. - * @access public - */ - function getMethod() { - if ($this->_isEmpty()) { - return false; - } - return $this->_sequence[$this->_position]['method']; - } - + /** * Last fully qualified URL for current history * position. @@ -105,7 +93,7 @@ } return $this->_sequence[$this->_position]['url']; } - + /** * Parameters of last fetch from current history * position. @@ -118,7 +106,7 @@ } return $this->_sequence[$this->_position]['parameters']; } - + /** * Step back one place in the history. Stops at * the first page. @@ -132,7 +120,7 @@ $this->_position--; return true; } - + /** * Step forward one place. If already at the * latest entry then nothing will happen. @@ -146,7 +134,7 @@ $this->_position++; return true; } - + /** * Ditches all future entries beyond the current * point. @@ -161,7 +149,7 @@ } } } - + /** * Simulated web browser. This is an aggregate of * the user agent, the HTML parsing, request history @@ -175,7 +163,7 @@ protected $_history; protected $_ignore_frames; protected $_maximum_nested_frames; - + /** * Starts with a fresh browser with no * cookie or any other state information. The @@ -186,33 +174,35 @@ function SimpleBrowser() { $this->_user_agent = $this->_createUserAgent(); $this->_user_agent->useProxy( - SimpleTestOptions::getDefaultProxy(), - SimpleTestOptions::getDefaultProxyUsername(), - SimpleTestOptions::getDefaultProxyPassword()); + 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 */ - function _createUserAgent() { - return new SimpleUserAgent(); + function &_createUserAgent() { + $user_agent = new SimpleUserAgent(); + return $user_agent; } - + /** * Creates a new empty history list. * @return SimpleBrowserHistory New list. * @access protected */ - function _createHistory() { - return new SimpleBrowserHistory(); + function &_createHistory() { + $history = new SimpleBrowserHistory(); + return $history; } - + /** * Disables frames support. Frames will not be fetched * and the frameset page will be used instead. @@ -221,7 +211,7 @@ function ignoreFrames() { $this->_ignore_frames = true; } - + /** * Enables frames support. Frames will be fetched from * now on. @@ -231,94 +221,123 @@ $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 protected + * @access private */ - function _parse($response, $depth = 0) { - $builder = new SimplePageBuilder(); - $page = $builder->parse($response); + 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('GET', $url, array(), $depth + 1); + $frame = $this->_fetch($url, new SimpleGetEncoding(), $depth + 1); $frameset->addFrame($frame, $key); } return $frameset; } /** - * Fetches a page. - * @param string $method GET or POST. - * @param string/SimpleUrl $url Target to fetch as string. - * @param SimpleFormEncoding $parameters POST parameters. - * @param integer $depth Nested frameset depth protection. - * @return SimplePage Parsed page. + * Assembles the parsing machinery and actually parses + * a single page. Frees all of the builder memory and so + * unjams the PHP memory management. + * @param SimpleHttpResponse $response Response from fetch. + * @return SimplePage Parsed top level page. + * @access protected + */ + function &_buildPage($response) { + $builder = new SimplePageBuilder(); + $page = $builder->parse($response); + $builder->free(); + unset($builder); + return $page; + } + + /** + * 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 */ - function _fetch($method, $url, $parameters, $depth = 0) { - $response = $this->_user_agent->fetchResponse($method, $url, $parameters); + function &_fetch($url, $encoding, $depth = 0) { + $response = $this->_user_agent->fetchResponse($url, $encoding); if ($response->isError()) { - return new SimplePage($response); + $page = new SimplePage($response); + } else { + $page = $this->_parse($response, $depth); } - return $this->_parse($response, $depth); + return $page; } - + /** * Fetches a page or a single frame if that is the current * focus. - * @param string $method GET or POST. - * @param string/SimpleUrl $url Target to fetch as string. - * @param SimpleFormEncoding $parameters POST parameters. + * @param SimpleUrl $url Target to fetch. + * @param SimpleEncoding $parameters GET/POST parameters. * @return string Raw content of page. * @access private */ - function _load($method, $url, $parameters = false) { + function _load($url, $parameters) { $frame = $url->getTarget(); if (! $frame || ! $this->_page->hasFrames() || (strtolower($frame) == '_top')) { - return $this->_loadPage($method, $url, $parameters); + return $this->_loadPage($url, $parameters); } - return $this->_loadFrame(array($frame), $method, $url, $parameters); + return $this->_loadFrame(array($frame), $url, $parameters); } - + /** * Fetches a page and makes it the current page/frame. - * @param string $method GET or POST. * @param string/SimpleUrl $url Target to fetch as string. - * @param SimpleFormEncoding $parameters POST parameters. + * @param SimplePostEncoding $parameters POST parameters. * @return string Raw content of page. * @access private */ - function _loadPage($method, $url, $parameters = false) { - $this->_page = $this->_fetch(strtoupper($method), $url, $parameters); + function _loadPage($url, $parameters) { + $this->_page = $this->_fetch($url, $parameters); $this->_history->recordEntry( - $this->_page->getMethod(), $this->_page->getUrl(), $this->_page->getRequestData()); return $this->_page->getRaw(); } - + /** * Fetches a frame into the existing frameset replacing the * original. * @param array $frames List of names to drill down. - * @param string $method GET or POST. * @param string/SimpleUrl $url Target to fetch as string. * @param SimpleFormEncoding $parameters POST parameters. * @return string Raw content of page. * @access private */ - function _loadFrame($frames, $method, $url, $parameters = false) { - $page = $this->_fetch(strtoupper($method), $url, $parameters); + function _loadFrame($frames, $url, $parameters) { + $page = $this->_fetch($url, $parameters); $this->_page->setFrame($frames, $page); } - + /** * Removes expired and temporary cookies as if * the browser was closed and re-opened. @@ -330,7 +349,7 @@ function restart($date = false) { $this->_user_agent->restart($date); } - + /** * Adds a header to every fetch. * @param string $header Header line to add to every @@ -340,7 +359,7 @@ function addHeader($header) { $this->_user_agent->addHeader($header); } - + /** * Ages the cookies by the specified time. * @param integer $interval Amount in seconds. @@ -349,7 +368,7 @@ function ageCookies($interval) { $this->_user_agent->ageCookies($interval); } - + /** * Sets an additional cookie. If a cookie has * the same name and path it is replaced. @@ -363,7 +382,7 @@ 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. @@ -377,7 +396,7 @@ 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. @@ -388,7 +407,7 @@ 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. @@ -398,7 +417,7 @@ function setMaximumRedirects($max) { $this->_user_agent->setMaximumRedirects($max); } - + /** * Sets the maximum number of nesting of framed pages * within a framed page to prevent loops. @@ -408,7 +427,7 @@ function setMaximumNestedFrames($max) { $this->_maximum_nested_frames = $max; } - + /** * Sets the socket timeout for opening a connection. * @param integer $timeout Maximum time in seconds. @@ -417,7 +436,7 @@ function setConnectionTimeout($timeout) { $this->_user_agent->setConnectionTimeout($timeout); } - + /** * Sets proxy to use on all requests for when * testing from behind a firewall. Set URL @@ -430,12 +449,12 @@ function useProxy($proxy, $username = false, $password = false) { $this->_user_agent->useProxy($proxy, $username, $password); } - + /** * Fetches the page content with a HEAD request. * Will affect cookies, but will not change the base URL. * @param string/SimpleUrl $url Target to fetch as string. - * @param hash/SimpleFormEncoding $parameters Additional parameters for + * @param hash/SimpleHeadEncoding $parameters Additional parameters for * HEAD request. * @return boolean True if successful. * @access public @@ -444,19 +463,13 @@ if (! is_object($url)) { $url = new SimpleUrl($url); } - if (is_array($parameters)) { - $parameters = new SimpleFormEncoding($parameters); - } if ($this->getUrl()) { $url = $url->makeAbsolute($this->getUrl()); } - $response = $this->_user_agent->fetchResponse( - 'HEAD', - $url, - $parameters); + $response = $this->_user_agent->fetchResponse($url, new SimpleHeadEncoding($parameters)); return ! $response->isError(); } - + /** * Fetches the page content with a simple GET request. * @param string/SimpleUrl $url Target to fetch. @@ -469,15 +482,12 @@ if (! is_object($url)) { $url = new SimpleUrl($url); } - if (is_array($parameters)) { - $parameters = new SimpleFormEncoding($parameters); - } if ($this->getUrl()) { $url = $url->makeAbsolute($this->getUrl()); } - return $this->_load('GET', $url, $parameters); + return $this->_load($url, new SimpleGetEncoding($parameters)); } - + /** * Fetches the page content with a POST request. * @param string/SimpleUrl $url Target to fetch as string. @@ -489,15 +499,12 @@ if (! is_object($url)) { $url = new SimpleUrl($url); } - if (is_array($parameters)) { - $parameters = new SimpleFormEncoding($parameters); - } if ($this->getUrl()) { $url = $url->makeAbsolute($this->getUrl()); } - return $this->_load('POST', $url, $parameters); + return $this->_load($url, new SimplePostEncoding($parameters)); } - + /** * Equivalent to hitting the retry button on the * browser. Will attempt to repeat the page fetch. If @@ -511,25 +518,22 @@ if (count($frames) > 0) { $this->_loadFrame( $frames, - $this->_page->getMethod(), $this->_page->getUrl(), $this->_page->getRequestData()); return $this->_page->getRaw(); } - if ($method = $this->_history->getMethod()) { - $this->_page = $this->_fetch( - $method, - $this->_history->getUrl(), - $this->_history->getParameters()); + 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. + * 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 @@ -544,11 +548,12 @@ } return $content; } - + /** * Equivalent to hitting the forward button on the * browser. The browser history is unchanged on - * failure. + * 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 @@ -563,7 +568,7 @@ } return $content; } - + /** * Retries a request after setting the authentication * for the current realm. @@ -589,7 +594,7 @@ $password); return $this->retry(); } - + /** * Accessor for a breakdown of the frameset. * @return array Hash tree of frames by name @@ -599,7 +604,7 @@ function getFrames() { return $this->_page->getFrames(); } - + /** * Accessor for current frame focus. Will be * false if no frame has focus. @@ -611,7 +616,7 @@ function getFrameFocus() { return $this->_page->getFrameFocus(); } - + /** * Sets the focus by index. The integer index starts from 1. * @param integer $choice Chosen frame. @@ -621,7 +626,7 @@ function setFrameFocusByIndex($choice) { return $this->_page->setFrameFocusByIndex($choice); } - + /** * Sets the focus by name. * @param string $name Chosen frame. @@ -631,7 +636,7 @@ function setFrameFocus($name) { return $this->_page->setFrameFocus($name); } - + /** * Clears the frame focus. All frames will be searched * for content. @@ -640,7 +645,7 @@ function clearFrameFocus() { return $this->_page->clearFrameFocus(); } - + /** * Accessor for last error. * @return string Error from last response. @@ -649,7 +654,7 @@ function getTransportError() { return $this->_page->getTransportError(); } - + /** * Accessor for current MIME type. * @return string MIME type as string; e.g. 'text/html' @@ -658,7 +663,7 @@ function getMimeType() { return $this->_page->getMimeType(); } - + /** * Accessor for last response code. * @return integer Last HTTP response code received. @@ -667,7 +672,7 @@ function getResponseCode() { return $this->_page->getResponseCode(); } - + /** * Accessor for last Authentication type. Only valid * straight after a challenge (401). @@ -677,7 +682,7 @@ function getAuthentication() { return $this->_page->getAuthentication(); } - + /** * Accessor for last Authentication realm. Only valid * straight after a challenge (401). @@ -687,7 +692,7 @@ function getRealm() { return $this->_page->getRealm(); } - + /** * Accessor for current URL of page or frame if * focused. @@ -698,7 +703,7 @@ $url = $this->_page->getUrl(); return $url ? $url->asString() : false; } - + /** * Accessor for raw bytes sent down the wire. * @return string Original text sent. @@ -725,7 +730,7 @@ function getContent() { return $this->_page->getRaw(); } - + /** * Accessor for plain text version of the page. * @return string Normalised text representation. @@ -734,7 +739,7 @@ function getContentAsText() { return $this->_page->getText(); } - + /** * Accessor for parsed title. * @return string Title or false if no title is present. @@ -743,7 +748,7 @@ function getTitle() { return $this->_page->getTitle(); } - + /** * Accessor for a list of all fixed links in current page. * @return array List of urls with scheme of @@ -753,7 +758,7 @@ function getAbsoluteUrls() { return $this->_page->getAbsoluteUrls(); } - + /** * Accessor for a list of all relative links. * @return array List of urls without hostname. @@ -762,18 +767,30 @@ function getRelativeUrls() { return $this->_page->getRelativeUrls(); } - + /** * 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) { + return $this->_page->setField(new SimpleByLabelOrName($label), $value); + } + + /** + * 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 setField($name, $value) { - return $this->_page->setField($name, $value); + function setFieldByName($name, $value) { + return $this->_page->setField(new SimpleByName($name), $value); } - + /** * Sets all form fields with that id attribute. * @param string/integer $id Id of field in forms. @@ -782,9 +799,22 @@ * @access public */ function setFieldById($id, $value) { - return $this->_page->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. @@ -794,10 +824,10 @@ * and null if missing. * @access public */ - function getField($name) { - return $this->_page->getField($name); + 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. @@ -807,9 +837,9 @@ * @access public */ function getFieldById($id) { - return $this->_page->getFieldById($id); + return $this->_page->getField(new SimpleById($id)); } - + /** * Clicks the submit button by label. The owning * form will be submitted by this. @@ -820,16 +850,15 @@ * @access public */ function clickSubmit($label = 'Submit', $additional = false) { - if (! ($form = $this->_page->getFormBySubmitLabel($label))) { + if (! ($form = $this->_page->getFormBySubmit(new SimpleByLabel($label)))) { return false; } $success = $this->_load( - $form->getMethod(), $form->getAction(), - $form->submitButtonByLabel($label, $additional)); + $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. @@ -839,16 +868,15 @@ * @access public */ function clickSubmitByName($name, $additional = false) { - if (! ($form = $this->_page->getFormBySubmitName($name))) { + if (! ($form = $this->_page->getFormBySubmit(new SimpleByName($name)))) { return false; } $success = $this->_load( - $form->getMethod(), $form->getAction(), - $form->submitButtonByName($name, $additional)); + $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. @@ -858,16 +886,15 @@ * @access public */ function clickSubmitById($id, $additional = false) { - if (! ($form = $this->_page->getFormBySubmitId($id))) { + if (! ($form = $this->_page->getFormBySubmit(new SimpleById($id)))) { return false; } $success = $this->_load( - $form->getMethod(), $form->getAction(), - $form->submitButtonById($id, $additional)); + $form->submitButton(new SimpleById($id), $additional)); return ($success ? $this->getContent() : $success); } - + /** * Clicks the submit image by some kind of label. Usually * the alt tag or the nearest equivalent. The owning @@ -882,16 +909,15 @@ * @access public */ function clickImage($label, $x = 1, $y = 1, $additional = false) { - if (! ($form = $this->_page->getFormByImageLabel($label))) { + if (! ($form = $this->_page->getFormByImage(new SimpleByLabel($label)))) { return false; } $success = $this->_load( - $form->getMethod(), $form->getAction(), - $form->submitImageByLabel($label, $x, $y, $additional)); + $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 @@ -906,16 +932,15 @@ * @access public */ function clickImageByName($name, $x = 1, $y = 1, $additional = false) { - if (! ($form = $this->_page->getFormByImageName($name))) { + if (! ($form = $this->_page->getFormByImage(new SimpleByName($name)))) { return false; } $success = $this->_load( - $form->getMethod(), $form->getAction(), - $form->submitImageByName($name, $x, $y, $additional)); + $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 @@ -929,16 +954,15 @@ * @access public */ function clickImageById($id, $x = 1, $y = 1, $additional = false) { - if (! ($form = $this->_page->getFormByImageId($id))) { + if (! ($form = $this->_page->getFormByImage(new SimpleById($id)))) { return false; } $success = $this->_load( - $form->getMethod(), $form->getAction(), - $form->submitImageById($id, $x, $y, $additional)); + $form->submitImage(new SimpleById($id), $x, $y, $additional)); return ($success ? $this->getContent() : $success); } - + /** * Submits a form by the ID. * @param string $id The form ID. No submit button value @@ -951,12 +975,11 @@ return false; } $success = $this->_load( - $form->getMethod(), $form->getAction(), $form->submit()); return ($success ? $this->getContent() : $success); } - + /** * Follows a link by label. Will click the first link * found with this link text by default, or a later @@ -975,10 +998,10 @@ if (count($urls) < $index + 1) { return false; } - $this->_load('GET', $urls[$index]); + $this->_load($urls[$index], new SimpleGetEncoding()); return $this->getContent(); } - + /** * Tests to see if a link is present by label. * @param string $label Text of value attribute. @@ -988,7 +1011,7 @@ function isLink($label) { return (count($this->_page->getUrlsByLabel($label)) > 0); } - + /** * Follows a link by id attribute. * @param string $id ID attribute value. @@ -999,10 +1022,10 @@ if (! ($url = $this->_page->getUrlById($id))) { return false; } - $this->_load('GET', $url); + $this->_load($url, new SimpleGetEncoding()); return $this->getContent(); } - + /** * Tests to see if a link is present by ID attribute. * @param string $id Text of id attribute. @@ -1012,5 +1035,23 @@ function isLinkById($id) { return (boolean)$this->_page->getUrlById($id); } + + /** + * 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; + } } ?> \ No newline at end of file diff --git a/tests/test_tools/simpletest/collector.php b/tests/test_tools/simpletest/collector.php new file mode 100644 index 00000000..f73193c7 --- /dev/null +++ b/tests/test_tools/simpletest/collector.php @@ -0,0 +1,115 @@ + + * @package SimpleTest + * @subpackage UnitTester + * @version $Id: collector.php,v 1.7 2005/09/10 21:09:34 tswicegood Exp $ + */ + +/** + * The basic collector for {@link GroupTest} + * + * @see collect(), GroupTest::collect() + * @package SimpleTest + * @subpackage UnitTester + */ +class SimpleCollector { + + /** + * Strips off any kind of slash at the end so as to normalise the path + * + * @param string $path Path to normalise. + */ + function _removeTrailingSlash($path) { + return preg_replace('|[\\/]$|', '', $path); + + /** + * @internal + * Try benchmarking the following. It's more code, but by not using the + * regex, it may be faster? Also, shouldn't be looking for + * DIRECTORY_SEPERATOR instead of a manual "/"? + */ + if (substr($path, -1) == DIRECTORY_SEPERATOR) { + return substr($path, 0, -1); + } else { + return $path; + } + } + + /** + * Scans the directory and adds what it can. + * @param object $test Group test with {@link GroupTest::addTestFile()} method. + * @param string $path Directory to scan. + * @see _attemptToAdd() + */ + function collect($test, $path) { + $path = $this->_removeTrailingSlash($path); + if ($handle = opendir($path)) { + while (($entry = readdir($handle)) !== false) { + $this->_handle($test, $path . DIRECTORY_SEPARATOR . $entry); + } + closedir($handle); + } + } + + /** + * This method determines what should be done with a given file and adds + * it via {@link GroupTest::addTestFile()} if necessary. + * + * This method should be overriden to provide custom matching criteria, + * such as pattern matching, recursive matching, etc. For an example, see + * {@link SimplePatternCollector::_handle()}. + * + * @param object $test Group test with {@link GroupTest::addTestFile()} method. + * @param string $filename A filename as generated by {@link collect()} + * @see collect() + * @access protected + */ + function _handle($test, $file) { + if (!is_dir($file)) { + $test->addTestFile($file); + } + } +} + +/** + * An extension to {@link SimpleCollector} that only adds files matching a + * given pattern. + * + * @package SimpleTest + * @subpackage UnitTester + * @see SimpleCollector + */ +class SimplePatternCollector extends SimpleCollector { + protected $_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 SimplePatternCollector($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 + */ + function _handle($test, $filename) { + if (preg_match($this->_pattern, $filename)) { + parent::_handle($test, $filename); + } + } +} +?> \ No newline at end of file diff --git a/tests/test_tools/simpletest/compatibility.php b/tests/test_tools/simpletest/compatibility.php new file mode 100644 index 00000000..36775194 --- /dev/null +++ b/tests/test_tools/simpletest/compatibility.php @@ -0,0 +1,184 @@ += 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 ($first != $second) { + return false; + } + if (version_compare(phpversion(), '5') >= 0) { + return SimpleTestCompatibility::_isIdenticalType($first, $second); + } + return ($first === $second); + } + + /** + * Recursive type test. + * @param mixed $first Test subject. + * @param mixed $second Comparison object. + * @return boolean True if same type. + * @access private + * @static + */ + function _isIdenticalType($first, $second) { + if (gettype($first) != gettype($second)) { + return false; + } + if (is_object($first) && is_object($second)) { + if (get_class($first) != get_class($second)) { + return false; + } + return SimpleTestCompatibility::_isArrayOfIdenticalTypes( + get_object_vars($first), + get_object_vars($second)); + } + if (is_array($first) && is_array($second)) { + return SimpleTestCompatibility::_isArrayOfIdenticalTypes($first, $second); + } + return true; + } + + /** + * Recursive type test for each element of an array. + * @param mixed $first Test subject. + * @param mixed $second Comparison object. + * @return boolean True if identical. + * @access private + * @static + */ + function _isArrayOfIdenticalTypes($first, $second) { + if (array_keys($first) != array_keys($second)) { + return false; + } + foreach (array_keys($first) as $key) { + $is_identical = SimpleTestCompatibility::_isIdenticalType( + $first[$key], + $second[$key]); + if (! $is_identical) { + return false; + } + } + return true; + } + + /** + * Test for two variables being aliases. + * @param mixed $first Test subject. + * @param mixed $second Comparison object. + * @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); + } + } + + /** + * Gets the current stack trace topmost first. + * @return array List of stack frames. + * @access public + * @static + */ + function getStackTrace() { + if (function_exists('debug_backtrace')) { + return array_reverse(debug_backtrace()); + } + return array(); + } + } +?> diff --git a/tests/test_tools/simpletest/cookies.php b/tests/test_tools/simpletest/cookies.php new file mode 100644 index 00000000..ecd2893c --- /dev/null +++ b/tests/test_tools/simpletest/cookies.php @@ -0,0 +1,380 @@ +_host = false; + $this->_name = $name; + $this->_value = $value; + $this->_path = ($path ? $this->_fixPath($path) : "/"); + $this->_expiry = false; + if (is_string($expiry)) { + $this->_expiry = strtotime($expiry); + } elseif (is_integer($expiry)) { + $this->_expiry = $expiry; + } + $this->_is_secure = $is_secure; + } + + /** + * Sets the host. The cookie rules determine + * that the first two parts are taken for + * certain TLDs and three for others. If the + * new host does not match these rules then the + * call will fail. + * @param string $host New hostname. + * @return boolean True if hostname is valid. + * @access public + */ + function setHost($host) { + if ($host = $this->_truncateHost($host)) { + $this->_host = $host; + return true; + } + return false; + } + + /** + * Accessor for the truncated host to which this + * cookie applies. + * @return string Truncated hostname. + * @access public + */ + function getHost() { + return $this->_host; + } + + /** + * Test for a cookie being valid for a host name. + * @param string $host Host to test against. + * @return boolean True if the cookie would be valid + * here. + */ + function isValidHost($host) { + return ($this->_truncateHost($host) === $this->getHost()); + } + + /** + * Extracts just the domain part that determines a + * cookie's host validity. + * @param string $host Host name to truncate. + * @return string Domain or false on a bad host. + * @access private + */ + function _truncateHost($host) { + $tlds = SimpleUrl::getAllTopLevelDomains(); + if (preg_match('/[a-z\-]+\.(' . $tlds . ')$/i', $host, $matches)) { + return $matches[0]; + } elseif (preg_match('/[a-z\-]+\.[a-z\-]+\.[a-z\-]+$/i', $host, $matches)) { + return $matches[0]; + } + return false; + } + + /** + * Accessor for name. + * @return string Cookie key. + * @access public + */ + function getName() { + return $this->_name; + } + + /** + * Accessor for value. A deleted cookie will + * have an empty string for this. + * @return string Cookie value. + * @access public + */ + function getValue() { + return $this->_value; + } + + /** + * Accessor for path. + * @return string Valid cookie path. + * @access public + */ + function getPath() { + return $this->_path; + } + + /** + * Tests a path to see if the cookie applies + * there. The test path must be longer or + * equal to the cookie path. + * @param string $path Path to test against. + * @return boolean True if cookie valid here. + * @access public + */ + function isValidPath($path) { + return (strncmp( + $this->_fixPath($path), + $this->getPath(), + strlen($this->getPath())) == 0); + } + + /** + * Accessor for expiry. + * @return string Expiry string. + * @access public + */ + function getExpiry() { + if (! $this->_expiry) { + return false; + } + return gmdate("D, d M Y H:i:s", $this->_expiry) . " GMT"; + } + + /** + * Test to see if cookie is expired against + * the cookie format time or timestamp. + * Will give true for a session cookie. + * @param integer/string $now Time to test against. Result + * will be false if this time + * is later than the cookie expiry. + * Can be either a timestamp integer + * or a cookie format date. + * @access public + */ + function isExpired($now) { + if (! $this->_expiry) { + return true; + } + if (is_string($now)) { + $now = strtotime($now); + } + return ($this->_expiry < $now); + } + + /** + * Ages the cookie by the specified number of + * seconds. + * @param integer $interval In seconds. + * @public + */ + function agePrematurely($interval) { + if ($this->_expiry) { + $this->_expiry -= $interval; + } + } + + /** + * Accessor for the secure flag. + * @return boolean True if cookie needs SSL. + * @access public + */ + function isSecure() { + return $this->_is_secure; + } + + /** + * Adds a trailing and leading slash to the path + * if missing. + * @param string $path Path to fix. + * @access private + */ + function _fixPath($path) { + if (substr($path, 0, 1) != '/') { + $path = '/' . $path; + } + if (substr($path, -1, 1) != '/') { + $path .= '/'; + } + return $path; + } + } + + /** + * Repository for cookies. This stuff is a + * tiny bit browser dependent. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleCookieJar { + protected $_cookies; + + /** + * Constructor. Jar starts empty. + * @access public + */ + function SimpleCookieJar() { + $this->_cookies = array(); + } + + /** + * Removes expired and temporary cookies as if + * the browser was closed and re-opened. + * @param string/integer $now Time to test expiry against. + * @access public + */ + 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 + */ + 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 + */ + 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/tests/test_tools/simpletest/detached.php b/tests/test_tools/simpletest/detached.php new file mode 100644 index 00000000..00f08880 --- /dev/null +++ b/tests/test_tools/simpletest/detached.php @@ -0,0 +1,96 @@ +_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 + */ + function &_createParser($reporter) { + return new SimpleTestXmlParser($reporter); + } + } +?> \ No newline at end of file diff --git a/tests/test_tools/simpletest/docs/en/authentication_documentation.html b/tests/test_tools/simpletest/docs/en/authentication_documentation.html index 0623023c..c90d61e5 100755 --- a/tests/test_tools/simpletest/docs/en/authentication_documentation.html +++ b/tests/test_tools/simpletest/docs/en/authentication_documentation.html @@ -21,9 +21,6 @@ Group tests
  • -Server stubs -
  • -
  • Mock objects
  • @@ -109,6 +106,19 @@ class AuthenticationTest extends WebTestCase { on the amount of detail you want to see.

    + One theme that runs through SimpleTest is the ability to use + SimpleExpectation objects wherever a simple + match is not enough. + If you want only an approximate match to the realm for + example, you can do this... +

    +class AuthenticationTest extends WebTestCase {
    +    function test401Header() {
    +        $this->get('http://www.lastcraft.com/protected/');
    +        $this->assertRealm(new PatternExpectation('/simpletest/i'));
    +    }
    +}
    +
    Most of the time we are not interested in testing the authentication itself, but want to get past it to test the pages underneath. @@ -116,7 +126,7 @@ class AuthenticationTest extends WebTestCase { an authentication response...
     class AuthenticationTest extends WebTestCase {
    -    function testAuthentication() {
    +    function testCanAuthenticate() {
             $this->get('http://www.lastcraft.com/protected/');
             $this->authenticate('Me', 'Secret');
             $this->assertTitle(...);
    @@ -208,9 +218,15 @@ class LogInTest extends WebTestCase {
     
    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. -

    -

    + really worth testing this with... +

    +class LogInTest extends WebTestCase {
    +    function testSessionCookieIsCorrectPattern() {
    +        $this->get('http://www.my-site.com/login.php');
    +        $this->assertCookie('SID', new PatternExpectation('/[a-f0-9]{32}/i'));
    +    }
    +}
    +
    The rest of the test would be the same as any other form, but we might want to confirm that we still have the same cookie after log-in as before we entered. @@ -224,8 +240,8 @@ class LogInTest extends WebTestCase { $session = $this->getCookie('SID'); $this->setField('u', 'Me'); $this->setField('p', 'Secret'); - $this->clickSubmit('Log in'); - $this->assertWantedPattern('/Welcome Me/'); + $this->click('Log in'); + $this->assertText('Welcome Me'); $this->assertCookie('SID', $session); } } @@ -243,7 +259,7 @@ class LogInTest extends WebTestCase { $this->get('http://www.my-site.com/login.php'); $this->setCookie('SID', 'Some other session'); $this->get('http://www.my-site.com/restricted.php'); - $this->assertWantedPattern('/Access denied/'); + $this->assertText('Access denied'); } } @@ -266,12 +282,12 @@ class LogInTest extends WebTestCase { $this->get('http://www.my-site.com/login.php'); $this->setField('u', 'Me'); $this->setField('p', 'Secret'); - $this->clickSubmit('Log in'); - $this->assertWantedPattern('/Welcome Me/'); + $this->click('Log in'); + $this->assertText('Welcome Me'); $this->restart(); $this->get('http://www.my-site.com/restricted.php'); - $this->assertWantedPattern('/Access denied/'); + $this->assertText('Access denied'); } } @@ -297,13 +313,13 @@ class LogInTest extends WebTestCase { $this->get('http://www.my-site.com/login.php'); $this->setField('u', 'Me'); $this->setField('p', 'Secret'); - $this->clickSubmit('Log in'); - $this->assertWantedPattern('/Welcome Me/'); + $this->click('Log in'); + $this->assertText('Welcome Me'); $this->ageCookies(3600); $this->restart(); $this->get('http://www.my-site.com/restricted.php'); - $this->assertWantedPattern('/Access denied/'); + $this->assertText('Access denied'); } } diff --git a/tests/test_tools/simpletest/docs/en/browser_documentation.html b/tests/test_tools/simpletest/docs/en/browser_documentation.html index ef54aaea..f6046a9d 100755 --- a/tests/test_tools/simpletest/docs/en/browser_documentation.html +++ b/tests/test_tools/simpletest/docs/en/browser_documentation.html @@ -21,9 +21,6 @@ Group tests
  • -Server stubs -
  • -
  • Mock objects
  • @@ -76,9 +73,9 @@ $browser = &new SimpleBrowser(); $browser->get('http://php.net/'); - $browser->clickLink('reporting bugs'); - $browser->clickLink('statistics'); - $page = $browser->clickLink('PHP 5 bugs only'); + $browser->click('reporting bugs'); + $browser->click('statistics'); + $page = $browser->click('PHP 5 bugs only'); preg_match('/status=Open.*?by=Any.*?(\d+)<\/a>/', $page, $matches); print $matches[1]; ?> @@ -297,14 +294,22 @@ useFrames()Enables frames support + + +ignoreCookies()Disables sending and receiving of cookies + + +useCookies()Enables cookie support The methods SimpleBrowser::setConnectionTimeout() SimpleBrowser::setMaximumRedirects(), SimpleBrowser::setMaximumNestedFrames(), - SimpleBrowser::ignoreFrames() and - SimpleBrowser::useFrames() continue to apply + SimpleBrowser::ignoreFrames(), + SimpleBrowser::useFrames(), + SimpleBrowser::ignoreCookies() and + SimpleBrowser::useCokies() 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 @@ -332,7 +337,7 @@ class TestOfRegistration extends UnitTestCase { $browser->get('http://my-site.com/register.php'); $browser->setField('email', 'me@here'); $browser->setField('password', 'Secret'); - $browser->clickSubmit('Register'); + $browser->click('Register'); $authenticator = &new Authenticator(); $member = &$authenticator->findByEmail('me@here'); @@ -361,14 +366,14 @@ class TestOfSecurity extends UnitTestCase { $first->get('http://my-site.com/login.php'); $first->setField('name', 'Me'); $first->setField('password', 'Secret'); - $first->clickSubmit('Enter'); + $first->click('Enter'); $this->assertEqual($first->getTitle(), 'Welcome'); $second = &new SimpleBrowser(); $second->get('http://my-site.com/login.php'); $second->setField('name', 'Me'); $second->setField('password', 'Secret'); - $second->clickSubmit('Enter'); + $second->click('Enter'); $this->assertEqual($second->getTitle(), 'Access Denied'); } } diff --git a/tests/test_tools/simpletest/docs/en/expectation_documentation.html b/tests/test_tools/simpletest/docs/en/expectation_documentation.html index 0165988c..bd189b94 100755 --- a/tests/test_tools/simpletest/docs/en/expectation_documentation.html +++ b/tests/test_tools/simpletest/docs/en/expectation_documentation.html @@ -23,9 +23,6 @@ Group tests
  • -Server stubs -
  • -
  • Mock objects
  • @@ -101,8 +98,8 @@
     class TestOfNewsService extends UnitTestCase {
         ...
    -    function testConnectionFailure() {
    -        $writer = &new MockWriter($this);
    +    function testConnectionFailure() {<strong>
    +        $writer = &new MockWriter();
             $writer->expectOnce('write', array(
                     'Cannot connect to news service ' .
                     '"BBC News" at this time. ' .
    @@ -110,8 +107,6 @@ class TestOfNewsService extends UnitTestCase {
             
             $service = &new NewsService('BBC News');
             $service->publish($writer);
    -        
    -        $writer->tally();
         }
     }
     
    @@ -129,15 +124,13 @@ class TestOfNewsService extends UnitTestCase { class TestOfNewsService extends UnitTestCase { ... function testConnectionFailure() { - $writer = &new MockWriter($this); + $writer = &new MockWriter(); $writer->expectOnce( 'write', - array(new WantedPatternExpectation('/cannot connect/i'))); + array(new PatternExpectation('/cannot connect/i'))); $service = &new NewsService('BBC News'); $service->publish($writer); - - $writer->tally(); } } @@ -179,10 +172,10 @@ class TestOfNewsService extends UnitTestCase { NotIndenticalExpectationInverts the mock object logic -WantedPatternExpectationUses a Perl Regex to match a string +PatternExpectationUses a Perl Regex to match a string -NoUnwantedPatternExpectationPasses only if failing a Perl Regex +NoPatternExpectationPasses only if failing a Perl Regex IsAExpectationChecks the type or class name only @@ -208,29 +201,26 @@ class TestOfNewsService extends UnitTestCase {

    The expectation classes can be used not just for sending assertions - from mock objects, but also for selecting behaviour for either - the - mock objects - or the - server stubs. + from mock objects, but also for selecting behaviour for the + mock objects. Anywhere a list of arguments is given, a list of expectation objects can be inserted instead.

    - Suppose we want an authorisation server stub to simulate a successful login + Suppose we want an authorisation server mock to simulate a successful login only if it receives a valid session object. We can do this as follows...

    -Stub::generate('Authorisation');
    +Mock::generate('Authorisation');
     
    -$authorisation = new StubAuthorisation();
    +$authorisation = new MockAuthorisation();
     $authorisation->setReturnValue(
             'isAllowed',
             true,
             array(new IsAExpectation('Session', 'Must be a session')));
     $authorisation->setReturnValue('isAllowed', false);
     
    - We have set the default stub behaviour to return false when + We have set the default mock behaviour to return false when isAllowed is called. When we call the method with a single parameter that is a Session object, it will return true. @@ -299,14 +289,14 @@ $authorisation->setReturnValue('isAllowed', false);

    The most crude way of doing this is to use the - SimpleTest::assertExpectation() method to + SimpleTest::assert() method to test against it directly...

     class TestOfNetworking extends UnitTestCase {
         ...
         function testGetValidIp() {
             $server = &new Server();
    -        $this->assertExpectation(
    +        $this->assert(
                     new ValidIp(),
                     $server->getIp(),
                     'Server IP address->%s');
    @@ -327,7 +317,7 @@ $authorisation->setReturnValue('isAllowed', false);
     class TestOfNetworking extends UnitTestCase {
         ...
         function assertValidIp($ip, $message = '%s') {
    -        $this->assertExpectation(new ValidIp(), $ip, $message);
    +        $this->assert(new ValidIp(), $ip, $message);
         }
         
         function testGetValidIp() {
    diff --git a/tests/test_tools/simpletest/docs/en/form_testing_documentation.html b/tests/test_tools/simpletest/docs/en/form_testing_documentation.html
    index b1e15b3d..50b634c0 100755
    --- a/tests/test_tools/simpletest/docs/en/form_testing_documentation.html
    +++ b/tests/test_tools/simpletest/docs/en/form_testing_documentation.html
    @@ -21,9 +21,6 @@
     Group tests
     
  • -Server stubs -
  • -
  • Mock objects
  • @@ -96,7 +93,9 @@ class SimpleFormTests extends WebTestCase { 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" + "A default". + As usual, we could use a pattern expectation instead if a fixed + string.

    We could submit the form straight away, but first we'll change @@ -108,7 +107,7 @@ class SimpleFormTests extends WebTestCase { $this->get('http://www.my-site.com/'); $this->assertField('a', 'A default'); $this->setField('a', 'New value'); - $this->clickSubmit('Go'); + $this->click('Go'); } } @@ -235,7 +234,7 @@ class SimpleFormTests extends WebTestCase { $this->get('http://www.lastcraft.com/form_testing_documentation.php'); $this->assertField('crud', array('c', 'r', 'u', 'd')); $this->setField('crud', array('r')); - $this->clickSubmit('Enable Privileges'); + $this->click('Enable Privileges'); } } @@ -261,7 +260,7 @@ class SimpleFormTests extends WebTestCase { $this->post( 'http://www.my-site.com/add_user.php', array('type' => 'superuser')); - $this->assertNoUnwantedPattern('/user created/i'); + $this->assertNoText('user created'); } } diff --git a/tests/test_tools/simpletest/docs/en/group_test_documentation.html b/tests/test_tools/simpletest/docs/en/group_test_documentation.html index adbc66ef..1e14d31e 100755 --- a/tests/test_tools/simpletest/docs/en/group_test_documentation.html +++ b/tests/test_tools/simpletest/docs/en/group_test_documentation.html @@ -21,9 +21,6 @@ Group tests

  • -Server stubs -
  • -
  • Mock objects
  • @@ -87,7 +84,7 @@ class MyFileTestCase extends UnitTestCase { ... } - SimpleTestOptions::ignore('MyFileTestCase'); + SimpleTest::ignore('MyFileTestCase'); class FileTester extends MyFileTestCase { ... diff --git a/tests/test_tools/simpletest/docs/en/index.html b/tests/test_tools/simpletest/docs/en/index.html index 04797272..c7183c49 100755 --- a/tests/test_tools/simpletest/docs/en/index.html +++ b/tests/test_tools/simpletest/docs/en/index.html @@ -24,9 +24,6 @@ Group tests
  • -Server stubs -
  • -
  • Mock objects
  • @@ -101,26 +98,22 @@ We start by creating a test script which we will call tests/log_test.php and populate it as follows...
    -<?php
    -require_once('simpletest/unit_tester.php');
    -require_once('simpletest/reporter.php');
    -require_once('../classes/log.php');
    -?>
    -
    - Here the simpletest folder is either local or in the path. - You would have to edit these locations depending on where you - placed the toolset. - Next we create a test case... -
    -<?php
    +<?php
     require_once('simpletest/unit_tester.php');
     require_once('simpletest/reporter.php');
     require_once('../classes/log.php');
    -
    +
     class TestOfLogging extends UnitTestCase {
     }
     ?>
     
    + Here the simpletest folder is either local or in the path. + You would have to edit these locations depending on where you + placed the toolset. + The TestOfLogging is our frst test case and it's + currently empty. +

    +

    Now we have five lines of scaffolding code and still no tests. However from this part on we get return on our investment very quickly. We'll assume that the Log class @@ -376,21 +369,15 @@ Mock::generate('Log'); class TestOfSessionLogging extends UnitTestCase { function testLogInIsLogged() { - $log = &new MockLog($this); + $log = &new MockLog(); $log->expectOnce('message', array('User fred logged in.')); $session_pool = &new SessionPool($log); - $session_pool->logIn('fred'); - $log->tally(); + $session_pool->logIn('fred'); } } ?> - The tally() call is needed to - tell the mock object that time is up for the expected call - count. - Without it the mock would wait forever for the method - call to come in without ever actually notifying the test case. - The other test will be triggered when the call to + The test will be triggered when the call to message() is invoked on the MockLog object. The mock call will trigger a parameter comparison and then send the @@ -398,6 +385,13 @@ class TestOfSessionLogging extends UnitTestCase { Wildcards can be included here too so as to prevent tests becoming too specific.

    +

    + If the mock reaches the end of the test case without the + method being called, the expectOnce() + expectation will trigger a test failure. + In other words the mocks can detect the absence of + behaviour as well as the presence. +

    The mock objects in the SimpleTest suite can have arbitrary return values set, sequences of returns, return values @@ -439,12 +433,12 @@ class TestOfAbout extends WebTestCase { function setUp() { $this->get('http://test-server/index.php'); - $this->clickLink('About'); + $this->click('About'); } function testSearchEngineOptimisations() { $this->assertTitle('A long title about us for search engines'); - $this->assertWantedPattern('/a popular keyphrase/i'); + $this->assertPattern('/a popular keyphrase/i'); } } $test = &new TestOfAbout(); diff --git a/tests/test_tools/simpletest/docs/en/mock_objects_documentation.html b/tests/test_tools/simpletest/docs/en/mock_objects_documentation.html index 2f8a1f90..eb32c619 100755 --- a/tests/test_tools/simpletest/docs/en/mock_objects_documentation.html +++ b/tests/test_tools/simpletest/docs/en/mock_objects_documentation.html @@ -21,9 +21,6 @@ Group tests

  • -Server stubs -
  • -
  • Mock objects
  • @@ -76,7 +73,17 @@

    If mock objects only behaved as actors they would simply be - known as server stubs. + known as server stubs. + This was originally a pattern named by Robert Binder (Testing + object-oriented systems: models, patterns, and tools, + Addison-Wesley) in 1999. +

    +

    + A server stub is a simulation of an object or component. + It should exactly replace a component in a system for test + or prototyping purposes, but remain lightweight. + This allows tests to run more quickly, or if the simulated + class has not been written, to run at all.

    However, the mock objects not only play a part (by supplying chosen @@ -87,6 +94,8 @@ If expectations are not met they save us the effort of writing a failed test assertion by performing that duty on our behalf. +

    +

    In the case of an imaginary database connection they can test that the query, say SQL, was correctly formed by the object that is using the connection. @@ -138,7 +147,7 @@ Mock::generate('DatabaseConnection'); class MyTestCase extends UnitTestCase { function testSomething() { - $connection = &new MockDatabaseConnection($this); + $connection = &new MockDatabaseConnection(); } } @@ -155,19 +164,27 @@ class MyTestCase extends UnitTestCase {

    - The mock version of a class has all the methods of the original + The mock version of a class has all the methods of the original, so that operations like $connection->query() are still legal. - As with stubs we can replace the default null return values... + The return value will be null, + but we can change that with...

    -$connection->setReturnValue('query', 37);
    +$connection->setReturnValue('query', 37)
     
    Now every time we call $connection->query() we get the result of 37. - As with the stubs we can set wildcards and we can overload the - wildcard parameter. + We can set the return value to anything, say a hash of + imaginary database results or a list of persistent objects. + Parameters are irrelevant here, we always get the same + values back each time once they have been set up this way. + That may not sound like a convincing replica of a + database connection, but for the half a dozen lines of + a test method it is usually all you need. +

    +

    We can also add extra methods to the mock when generating it and choose our own class name...

    @@ -180,8 +197,12 @@ class MyTestCase extends UnitTestCase {
                     You can create a special mock to simulate this situation.
                 

    - All of the patterns available with server stubs are available - to mock objects... + Things aren't always that simple though. + One common problem is iterators, where constantly returning + the same value could cause an endless loop in the object + being tested. + For these we need to set up sequences of values. + Let's say we have a simple iterator that looks like this...

     class Iterator {
         function Iterator() {
    @@ -191,7 +212,8 @@ class Iterator {
         }
     }
     
    - Again, assuming that this iterator only returns text until it + 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...
    @@ -200,7 +222,7 @@ Mock::generate('Iterator');
     class IteratorTest extends UnitTestCase() {
         
         function testASequence() {
    -        $iterator = &new MockIterator($this);
    +        $iterator = &new MockIterator();
             $iterator->setReturnValue('next', false);
             $iterator->setReturnValueAt(0, 'next', 'First string');
             $iterator->setReturnValueAt(1, 'next', 'Second string');
    @@ -218,7 +240,10 @@ class IteratorTest extends UnitTestCase() {
                     The constant one is a kind of default if you like.
                 

    - A repeat of the stubbed information holder with name/value pairs... + Another tricky situation is an overloaded + get() operation. + An example of this is an information holder with name/value pairs. + Say we have a configuration class like...

     class Configuration {
         function Configuration() {
    @@ -237,7 +262,7 @@ class Configuration {
                     we want different results for different keys.
                     Luckily the mocks have a filter system...
     
    -$config = &new MockConfiguration($this);
    +$config = &new MockConfiguration();
     $config->setReturnValue('getValue', 'primary', array('db_host'));
     $config->setReturnValue('getValue', 'admin', array('db_user'));
     $config->setReturnValue('getValue', 'secret', array('db_password'));
    @@ -257,10 +282,36 @@ $config->getValue('db_user')
                     to its list of returns one after another until
                     a complete match is found.
                 

    +

    + You can set a default argument argument like so... +

    +
    +$config->setReturnValue('getValue', false, array('*'));
    +
    + This is not the same as setting the return value without + any argument requirements like this... +
    +
    +$config->setReturnValue('getValue', false);
    +
    + In the first case it will accept any single argument, + but exactly one is required. + In the second case any number of arguments will do and + it acts as a catchall after all other matches. + Note that if we add further single parameter options after + the wildcard in the first case, they will be ignored as the wildcard + will match first. + With complex parameter lists the ordering could be important + or else desired matches could be masked by earlier wildcard + ones. + Declare the most specific matches first if you are not sure. +

    There are times when you want a specific object to be dished out by the mock rather than a copy. - Again this is identical to the server stubs mechanism... + The PHP4 copy semantics force us to use a different method + for this. + You might be simulating a container for example...

     class Thing {
     }
    @@ -276,14 +327,79 @@ class Vector {
                     In this case you can set a reference into the mock's
                     return list...
     
    -$thing = new Thing();
    -$vector = &new MockVector($this);
    +$thing = &new Thing();
    +$vector = &new MockVector();
     $vector->setReturnReference('get', $thing, array(12));
     
    With this arrangement you know that every time $vector->get(12) is called it will return the same $thing each time. + This is compatible with PHP5 as well. +

    +

    + These three factors, timing, parameters and whether to copy, + can be combined orthogonally. + For example... +

    +$complex = &new MockComplexThing();
    +$stuff = &new Stuff();
    +$complex->setReturnReferenceAt(3, 'get', $stuff, array('*', 1));
    +
    + This will return the $stuff only on the third + call and only if two parameters were set the second of + which must be the integer 1. + That should cover most simple prototyping situations. +

    +

    + A final tricky case is one object creating another, known + as a factory pattern. + Suppose that on a successful query to our imaginary + database, a result set is returned as an iterator with + each call to next() giving + one row until false. + This sounds like a simulation nightmare, but in fact it can all + be mocked using the mechanics above. +

    +

    + Here's how... +

    +Mock::generate('DatabaseConnection');
    +Mock::generate('ResultIterator');
    +
    +class DatabaseTest extends UnitTestCase {
    +    
    +    function testUserFinder() {
    +        $result = &new MockResultIterator();
    +        $result->setReturnValue('next', false);
    +        $result->setReturnValueAt(0, 'next', array(1, 'tom'));
    +        $result->setReturnValueAt(1, 'next', array(3, 'dick'));
    +        $result->setReturnValueAt(2, 'next', array(6, 'harry'));
    +        
    +        $connection = &new MockDatabaseConnection();
    +        $connection->setReturnValue('query', false);
    +        $connection->setReturnReference(
    +                'query',
    +                $result,
    +                array('select id, name from users'));
    +                
    +        $finder = &new UserFinder($connection);
    +        $this->assertIdentical(
    +                $finder->findNames(),
    +                array('tom', 'dick', 'harry'));
    +    }
    +}
    +
    + Now only if our + $connection is called with the correct + query() will the + $result be returned that is + itself exhausted after the third call to next(). + This should be enough + information for our UserFinder class, + the class actually + being tested here, to come up with goods. + A very precise test and not a real database in sight.

    @@ -388,18 +504,16 @@ Mock::generate('Log'); class LoggingSessionPoolTest extends UnitTestCase { ... function testFindSessionLogging() { - $session = &new MockSession($this); - $pool = &new MockSessionPool($this); + $session = &new MockSession(); + $pool = &new MockSessionPool(); $pool->setReturnReference('findSession', $session); $pool->expectOnce('findSession', array('abc')); - $log = &new MockLog($this); + $log = &new MockLog(); $log->expectOnce('message', array('Starting session abc')); $logging_pool = &new LoggingSessionPool($pool, $log); - $this->assertReference($logging_pool->findSession('abc'), $session); - $pool->tally(); - $log->tally(); + $this->assertReference($logging_pool->findSession('abc'), $session); } }

    @@ -426,15 +540,6 @@ class LoggingSessionPoolTest extends UnitTestCase { You can have wildcards and sequences and the order of evaluation is the same.

    -

    - If the call is never made then neither a pass nor a failure will - generated. - To get around this we must tell the mock when the test is over - so that the object can decide if the expectation has been met. - The unit tester assertion for this is triggered by the - tally() call at the end of - the test. -

    We use the same pattern to set up the mock logger. We tell it that it should have @@ -448,11 +553,6 @@ class LoggingSessionPoolTest extends UnitTestCase { LoggingSessionPool and feed it our preset mock objects. Everything is now under our control. - Finally we confirm that the - $session we gave our decorator - is the one that we get back and tell the mocks to run their - internal call count tests with the - tally() calls.

    This is still quite a bit of test code, but the code is very @@ -477,11 +577,11 @@ class LoggingSessionPoolTest extends UnitTestCase { - expectArguments($method, $args) + expect($method, $args) No - expectArgumentsAt($timing, $method, $args) + expectAt($timing, $method, $args) No @@ -589,8 +689,8 @@ class LoggingSessionPoolTest extends UnitTestCase { Mock::generate('Connection', 'BasicMockConnection'); class MockConnection extends BasicMockConnection { - function MockConnection(&$test, $wildcard = '*') { - $this->BasicMockConnection($test, $wildcard); + function MockConnection() { + $this->BasicMockConnection(); $this->setReturn('query', false); } } @@ -619,92 +719,6 @@ class LoggingSessionPoolTest extends UnitTestCase { stages of testing.

    -

    - -

    I think SimpleTest stinks!

    - -

    -

    - But at the time of writing it is the only one with mock objects, - so are you stuck with it? -

    -

    - No, not at all. - SimpleTest is a toolkit and one of those - tools is the mock objects which can be employed independently. - Suppose you have your own favourite unit tester and all your current - test cases are written using it. - Pretend that you have called your unit tester PHPUnit (everyone else has) - and the core test class looks like this... -

    -class PHPUnit {
    -    function PHPUnit() {
    -    }
    -    
    -    function assertion($message, $assertion) {
    -    }
    -    ...
    -}
    -
    - All the assertion() method does - is print some fancy output and the boolean assertion parameter determines - whether to print a pass or a failure. - Let's say that it is used like this... -
    -$unit_test = new PHPUnit();
    -$unit_test>assertion('I hope this file exists', file_exists('my_file'));
    -
    - How do you use mocks with this? -

    -

    - There is a protected method on the base mock class - SimpleMock called - _assertTrue() and - by overriding this method we can use our own assertion format. - We start with a subclass, in say my_mock.php... -

    -<?php
    -    require_once('simpletest/mock_objects.php');
    -    
    -    class MyMock extends SimpleMock() {
    -        function MyMock(&$test, $wildcard) {
    -            $this->SimpleMock($test, $wildcard);
    -        }
    -        
    -        function _assertTrue($assertion, $message) {
    -            $test = &$this->getTest();
    -            $test->assertion($message, $assertion);
    -        }
    -    }
    -?>
    -
    - Now instantiating MyMock will create - an object that speaks the same language as your tester. - The catch is of course that we never create such an object, the - code generator does. - We need just one more line of code to tell the generator to use - your mock instead... -
    -<?php
    -    require_once('simpletst/mock_objects.php');
    -    
    -    class MyMock extends SimpleMock() {
    -        function MyMock($test, $wildcard) {
    -            $this->SimpleMock(&$test, $wildcard);
    -        }
    -        
    -        function _assertTrue($assertion, $message , &$test) {
    -            $test->assertion($message, $assertion);
    -        }
    -    }
    -    SimpleTestOptions::setMockBaseClass('MyMock');
    -?>
    -
    - From now on you just include my_mock.php instead of the - default mock_objects.php version and you can introduce - mock objects into your existing test suite. -

    -
  • -Server stubs -
  • -
  • Mock objects
  • @@ -151,8 +148,7 @@ class MySiteTest extends WebTestCase { milestones rather depends on time available. Green stuff has been coded, but not necessarily released yet. If you have a pressing need for a green but unreleased feature - then you should check-out the code from sourceforge CVS directly. - A released feature is marked as "Done". + then you should check-out the code from Sourceforge CVS directly. @@ -163,12 +159,12 @@ class MySiteTest extends WebTestCase { - + - + @@ -176,41 +172,20 @@ class MySiteTest extends WebTestCase { Reading a file with test cases and loading them into a group test automatically - + - + - - - - - - - - - - - + - - - - - - + @@ -218,32 +193,32 @@ class MySiteTest extends WebTestCase { Mocking parts of a class for testing less than a class or for complex simulations - + - + - + - + - + - + @@ -251,25 +226,15 @@ class MySiteTest extends WebTestCase { Allows multi host testing and the integration of acceptance testing extensions - + - - - - - - - - - - - + - + @@ -277,31 +242,39 @@ class MySiteTest extends WebTestCase { Fetching protected web pages with basic authentication only - - - - - - + - + - + - + + + + + + + + + + + - - + + @@ -310,28 +283,43 @@ class MySiteTest extends WebTestCase { - - + + - - + + + + + + + - - + + + + + + + - - + + + + + + +
    Unit test case Core test case class and assertionsDone1.0
    Html display Simplest possible displayDone1.0
    Autoloading of test casesDone1.0
    Mock objects code generatorMock objects Objects capable of simulating other objects removing test dependencies Done
    Server stubs - Mocks without expectations to be used outside of test cases, - e.g. for prototyping - Done
    Integration of other unit testers - The ability to read and simulate test cases from PHPUnit - and PEAR::PhpUnit - Done1.0
    Web test caseBasic pattern matching of fetched pagesDone
    HTML parsing of pages Allows link following and title tag matchingDone1.0
    Partial mocksDone1.0
    Web cookie handling Correct handling of cookies when fetching pagesDone1.0
    Following redirects Page fetching automatically follows 300 redirectsDone1.0
    Form parsing Ability to submit simple forms and read default form valuesDone1.0
    Command line interface Test display without the need of a web browserDone1.0
    Exposure of expectation classes Can create precise tests with mocks as well as test casesDone1.0
    XML output and parsingDone1.0
    Command line test caseAllows testing of utilities and file handlingDone
    PHP Documentor compatibilityFully generated class level documentationDone
    Browser interfaceBrowser component Exposure of lower level web browser interface for more detailed test cases Done1.0
    HTTP authenticationDone
    Browser navigation buttonsBack, forward and retryDone1.0
    SSL support Can connect to https: pagesDone1.0
    Proxy support Can connect via. common proxiesDone1.0
    Frames support Handling of frames in web test casesDone1.0
    File upload testingCan simulate the input type file tag1.0.1
    Mocking interfaces + Can generate mock objects to interfaces as well as classes + and class interfaces are carried for type hints + 1.0.1
    Improved displayBetter web GUI with tree display of test casesReporting machinery enhancementsImproved message passing for better cooperation with IDEs 1.1
    1.1
    File upload testingCan simulate the input type file tagTesting exceptionsSimilar to testing PHP errors 1.1
    Mocking interfacesCan generate mock objects to interfaces as well as classesIFrame supportReads IFrame content that can be refreshed1.1
    Improved mock interfaceMore compact way of expressing mocks 2.0
    Testing exceptionsSimilar to testing PHP errorsHTML table assertionsCan match table elements to numerical assertions2.0
    XPath searching of HTML elementsMore flexible content matching 2.0
    XPath searching of elementsCan make use of HTML tidy for faster and more flexible content matchingAlternate HTML parsersCan detect compiled parsers for performance improvements 2.0
    Javascript suportUse of PECL module to add Javascript3.0
    - PHP5 migraton will start straight after the version 1.1 series, + PHP5 migraton will start straight after the version 1.0.1 series, whereupon PHP4 will no longer be supported. SimpleTest is currently compatible with PHP5, but will not make use of all of the new features until version 2. @@ -374,18 +362,6 @@ class MySiteTest extends WebTestCase { version at least has been upgraded for PHP5 and is recommended if you are porting existing JUnit test cases.

    -

    - Library writers don't seem to ship tests with their code very often - which is a shame. - Library code that includes tests can be more safely refactored and - the test code can act as additional documentation in a fairly standard - form. - This can save trawling the source code for clues when problems occour, - especially when upgrading such a library. - Libraries using SimpleTest for their unit testing include - WACT and - PEAR::XML_HTMLSax. -

    There is currently a sad lack of material on mock objects, which is a shame as unit testing without them is a lot more work. @@ -394,14 +370,15 @@ class MySiteTest extends WebTestCase { As a new technology there are plenty of discussions and debate on how to use mocks, often on Wikis such as Extreme Tuesday - or www.mockobjects.com + or www.mockobjects.com or the original C2 Wiki. Injecting mocks into a class is the main area of debate for which this paper on IBM makes a good starting point.

    - There are plenty of web testing tools, but most are written in Java and + There are plenty of web testing tools, but the scriptable ones + are mostly are written in Java and tutorials and advice are rather thin on the ground. The only hope is to look at the documentation for HTTPUnit, @@ -409,6 +386,13 @@ class MySiteTest extends WebTestCase { or JWebUnit and hope for clues. There are some XML driven test frameworks, but again most require Java to run. +

    +

    + A new generation of tools that run directly in the web browser + are now available. + These include + Selenium and + Watir. As SimpleTest does not support JavaScript you would probably have to look at these tools anyway if you have highly dynamic pages. diff --git a/tests/test_tools/simpletest/docs/en/partial_mocks_documentation.html b/tests/test_tools/simpletest/docs/en/partial_mocks_documentation.html index 20749415..6d7b6243 100755 --- a/tests/test_tools/simpletest/docs/en/partial_mocks_documentation.html +++ b/tests/test_tools/simpletest/docs/en/partial_mocks_documentation.html @@ -21,9 +21,6 @@ Group tests

  • -Server stubs -
  • -
  • Mock objects
  • diff --git a/tests/test_tools/simpletest/docs/en/reporter_documentation.html b/tests/test_tools/simpletest/docs/en/reporter_documentation.html index 44be8b1e..ead61175 100755 --- a/tests/test_tools/simpletest/docs/en/reporter_documentation.html +++ b/tests/test_tools/simpletest/docs/en/reporter_documentation.html @@ -21,9 +21,6 @@ Group tests
  • -Server stubs -
  • -
  • Mock objects
  • diff --git a/tests/test_tools/simpletest/docs/en/unit_test_documentation.html b/tests/test_tools/simpletest/docs/en/unit_test_documentation.html index 6aa8d8a7..47b61eca 100755 --- a/tests/test_tools/simpletest/docs/en/unit_test_documentation.html +++ b/tests/test_tools/simpletest/docs/en/unit_test_documentation.html @@ -21,9 +21,6 @@ Group tests
  • -Server stubs -
  • -
  • Mock objects
  • @@ -162,6 +159,12 @@ class FileTestCase extends UnitTestCase { assertNotEqual($x, $y)Fail if $x == $y is true + + +assertWithinMargin($x, $y, $m)Fail if abs($x - $y) < $m is false + + +assertOutsideMargin($x, $y, $m)Fail if abs($x - $y) < $m is true assertIdentical($x, $y)Fail if $x == $y is false or a type mismatch @@ -176,19 +179,19 @@ class FileTestCase extends UnitTestCase { assertCopy($x, $y)Fail if $x and $y are the same variable -assertWantedPattern($p, $x)Fail unless the regex $p matches $x +assertPattern($p, $x)Fail unless the regex $p matches $x -assertNoUnwantedPattern($p, $x)Fail if the regex $p matches $x +assertNoPattern($p, $x)Fail if the regex $p matches $x assertNoErrors()Fail if any PHP error occoured -assertError($x)Fail if no PHP error or incorrect message +assertError($x)Fail if no PHP error or incorrect message/expectation -assertErrorPattern($p)Fail unless the error matches the regex $p +assertExpectation($e)Fail on failed expectation object @@ -226,7 +229,7 @@ $this->assertReference($a, $b); Will fail as the variable $a is a copy of $b.
    -$this->assertWantedPattern('/hello/i', 'Hello world');
    +$this->assertPattern('/hello/i', 'Hello world');
     
    This will pass as using a case insensitive match the string hello is contained in Hello world. diff --git a/tests/test_tools/simpletest/docs/en/web_tester_documentation.html b/tests/test_tools/simpletest/docs/en/web_tester_documentation.html index 51f604be..99dacacc 100755 --- a/tests/test_tools/simpletest/docs/en/web_tester_documentation.html +++ b/tests/test_tools/simpletest/docs/en/web_tester_documentation.html @@ -21,9 +21,6 @@ Group tests
  • -Server stubs -
  • -
  • Mock objects
  • @@ -153,7 +150,7 @@ class TestOfLastcraft extends WebTestCase { function testHomepage() { $this->get('http://www.lastcraft.com/'); - $this->assertWantedPattern('/why the last craft/i'); + $this->assertTest('Why the last craft'); } } @@ -169,16 +166,16 @@ class TestOfLastcraft extends WebTestCase { assertTitle($title)Pass if title is an exact match -assertWantedPattern($pattern)A Perl pattern match against the page content +assertPattern($pattern)A Perl pattern match against the page content -assertNoUnwantedPattern($pattern)A Perl pattern match to not find content +assertNoPattern($pattern)A Perl pattern match to not find content -assertWantedText($text)Pass if matches visible and "alt" text +assertText($text)Pass if matches visible and "alt" text -assertNoUnwantedText($text)Pass if doesn't match visible and "alt" text +assertNoText($text)Pass if doesn't match visible and "alt" text assertLink($label)Pass if a link with this text is present @@ -217,10 +214,7 @@ class TestOfLastcraft extends WebTestCase { assertHeader($header, $content)Pass if a header was fetched matching this value -assertNoUnwantedHeader($header)Pass if a header was not fetched - - -assertHeaderPattern($header, $pattern)Pass if a header was fetched matching this Perl regex +assertNoHeader($header)Pass if a header was not fetched assertCookie($name, $value)Pass if there is currently a matching cookie @@ -240,6 +234,10 @@ class TestOfLastcraft extends WebTestCase { So now we could instead test against the title tag with...
     $this->assertTitle('The Last Craft? Web developer tutorials on PHP, Extreme programming and Object Oriented development');
    +
    + ...or, if that is too long and fragile... +
    +$this->assertTitle(new PatternExpectation('/The Last Craft/'));
     
    As well as the simple HTML content checks we can check that the MIME type is in a list of allowed types with... @@ -319,7 +317,7 @@ class TestOfLastcraft extends WebTestCase { function testContact() { $this->get('http://www.lastcraft.com/'); $this->clickLink('About'); - $this->assertTitle('About Last Craft'); + $this->assertTitle(new PatternExpectation('/About Last Craft/')); } } @@ -327,10 +325,15 @@ class TestOfLastcraft extends WebTestCase {

    If the target is a button rather than an anchor tag, then - clickSubmit() should be used + clickSubmit() can be used with the button title...

     $this->clickSubmit('Go!');
    +
    + If you are not sure or don't care, the usual case, then just + use the click() method... +
    +$this->click('Go!');
     

    diff --git a/tests/test_tools/simpletest/docs/fr/authentication_documentation.html b/tests/test_tools/simpletest/docs/fr/authentication_documentation.html deleted file mode 100755 index 08cc2349..00000000 --- a/tests/test_tools/simpletest/docs/fr/authentication_documentation.html +++ /dev/null @@ -1,264 +0,0 @@ - - - -Documentation Simple Test : tester l'authentification - - - -

    -

    Documentation sur l'authentification

    -
    - -

    - 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. -

    - -

    - -

    Authentification HTTP basique

    - -

    -

    - 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... -

    -class AuthenticationTest extends WebTestCase {
    -    function test401Header() {
    -        $this->get('http://www.lastcraft.com/protected/');
    -        $this->showHeaders();
    -    }
    -}
    -
    - Ce qui nous permet de voir les entêtes reçues... -
    -

    File test

    -
    -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
    -
    -
    1/1 test cases complete. - 0 passes, 0 fails and 0 exceptions.
    -
    - Sauf que nous voulons éviter l'inspection visuelle, on souhaite que SimpleTest puisse nous dire si oui ou non la page est protégée. Voici un test en profondeur sur nos entêtes... -
    -class AuthenticationTest extends WebTestCase {
    -    function test401Header() {
    -        $this->get('http://www.lastcraft.com/protected/');
    -        $this->assertAuthentication('Basic');
    -        $this->assertResponse(401);
    -        $this->assertRealm('SimpleTest basic authentication');
    -    }
    -}
    -
    - N'importe laquelle de ces assertions suffirait, tout dépend de la masse de détails que vous souhaitez voir. -

    -

    - La plupart du temps, nous ne souhaitons pas tester l'authentification en elle-même, mais plutôt les pages protégées par cette authentification. Dès que la tentative d'authentification est reçue, nous pouvons y répondre à l'aide d'une réponse d'authentification : -

    -class AuthenticationTest extends WebTestCase {
    -    function testAuthentication() {
    -        $this->get('http://www.lastcraft.com/protected/');
    -        $this->authenticate('Me', 'Secret');
    -        $this->assertTitle(...);
    -    }
    -}
    -
    - Le nom d'utilisateur et le mot de passe seront désormais envoyés à chaque requête vers ce répertoire et ses sous répertoires. En revanche vous devrez vous authentifier à nouveau si vous sortez de ce répertoire. -

    -

    - Vous pouvez gagner une ligne en définissant l'authentification au niveau de l'URL... -

    -class AuthenticationTest extends WebTestCase {
    -    function testCanReadAuthenticatedPages() {
    -        $this->get('http://Me:Secret@www.lastcraft.com/protected/');
    -        $this->assertTitle(...);
    -    }
    -}
    -
    - Si votre nom d'utilisateur ou mot de passe comporte des caractères spéciaux, alors n'oubliez pas de les encoder, sinon la requête ne sera pas analysée correctement. De plus cette entête ne sera pas envoyée aux sous requêtes si vous la définissez avec une URL absolue. Par contre si vous naviguez avec des URL relatives, l'information d'authentification sera préservée. -

    -

    - Pour l'instant, seule l'authentification de base est implémentée et elle n'est réellement fiable qu'en tandem avec une connexion HTTPS. C'est généralement suffisant pour protéger le serveur testé des regards malveillants. Les authentifications Digest et NTLM pourraient être ajoutées prochainement. -

    - -

    - -

    Cookies

    - -

    -

    - L'authentification de base ne donne pas assez de contrôle au développeur Web sur l'interface utilisateur. Il y a de forte chance pour que cette fonctionnalité soit codée directement dans l'architecture web à grand renfort de cookies et de timeouts compliqués. -

    -

    - Commençons par un simple formulaire de connexion... -

    -<form>
    -    Username:
    -    <input type="text" name="u" value="" /><br />
    -    Password:
    -    <input type="password" name="p" value="" /><br />
    -    <input type="submit" value="Log in" />
    -</form>
    -
    - Lequel doit ressembler à... -

    -

    -

    - Username: - -
    - Password: - -
    - -
    -

    -

    - 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... -

    -class LogInTest extends WebTestCase {
    -    function testSessionCookieSetBeforeForm() {
    -        $this->get('http://www.my-site.com/login.php');
    -        $this->assertCookie('SID');
    -    }
    -}
    -
    - Nous nous contentons ici de vérifier que le cookie a bien été défini. Etant donné que sa valeur est plutôt énigmatique, elle ne vaut pas la peine d'être testée. -

    -

    - Le reste du test est le même que dans n'importe quel autre formulaire, mais nous pourrions souhaiter nous assurer que le cookie n'a pas été modifié depuis la phase de connexion. Voici comment cela pourrait être testé : -

    -class LogInTest extends WebTestCase {
    -    ...
    -    function testSessionCookieSameAfterLogIn() {
    -        $this->get('http://www.my-site.com/login.php');
    -        $session = $this->getCookie('SID');
    -        $this->setField('u', 'Me');
    -        $this->setField('p', 'Secret');
    -        $this->clickSubmit('Log in');
    -        $this->assertWantedPattern('/Welcome Me/');
    -        $this->assertCookie('SID', $session);
    -    }
    -}
    -
    - Ceci confirme que l'identifiant de session est identique avant et après la connexion. -

    -

    - Nous pouvons même essayer de duper notre propre système en créant un cookie arbitraire pour se connecter... -

    -class LogInTest extends WebTestCase {
    -    ...
    -    function testSessionCookieSameAfterLogIn() {
    -        $this->get('http://www.my-site.com/login.php');
    -        $this->setCookie('SID', 'Some other session');
    -        $this->get('http://www.my-site.com/restricted.php');
    -        $this->assertWantedPattern('/Access denied/');
    -    }
    -}
    -
    - Votre site est-il protégé contre ce type d'attaque ? -

    - -

    - -

    Sessions de navigateur

    - -

    -

    - 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 : -

    -class LogInTest extends WebTestCase {
    -    ...
    -    function testLoseAuthenticationAfterBrowserClose() {
    -        $this->get('http://www.my-site.com/login.php');
    -        $this->setField('u', 'Me');
    -        $this->setField('p', 'Secret');
    -        $this->clickSubmit('Log in');
    -        $this->assertWantedPattern('/Welcome Me/');
    -        
    -        $this->restart();
    -        $this->get('http://www.my-site.com/restricted.php');
    -        $this->assertWantedPattern('/Access denied/');
    -    }
    -}
    -
    - La méthode WebTestCase::restart() préserve les cookies dont le timeout a expiré, mais conserve les cookies temporaires ou expirés. Vous pouvez spécifier l'heure et la date de leur réactivation. -

    -

    - L'expiration des cookies peut être un problème. Si vous avez un cookie qui doit expirer au bout d'une heure, nous n'allons pas mettre le test en veille en attendant que le cookie expire... -

    -

    - Afin de provoquer leur expiration, vous pouvez dater manuellement les cookies, avant le début de la session. -

    -class LogInTest extends WebTestCase {
    -    ...
    -    function testLoseAuthenticationAfterOneHour() {
    -        $this->get('http://www.my-site.com/login.php');
    -        $this->setField('u', 'Me');
    -        $this->setField('p', 'Secret');
    -        $this->clickSubmit('Log in');
    -        $this->assertWantedPattern('/Welcome Me/');
    -        
    -        $this->ageCookies(3600);
    -        $this->restart();
    -        $this->get('http://www.my-site.com/restricted.php');
    -        $this->assertWantedPattern('/Access denied/');
    -    }
    -}
    -
    - 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. -

    - -
    - - - diff --git a/tests/test_tools/simpletest/docs/fr/browser_documentation.html b/tests/test_tools/simpletest/docs/fr/browser_documentation.html deleted file mode 100755 index fa8ad1b6..00000000 --- a/tests/test_tools/simpletest/docs/fr/browser_documentation.html +++ /dev/null @@ -1,329 +0,0 @@ - - - -Documentation SimpleTest : le composant de navigation web scriptable - - - - -

    Documentation sur le navigateur scriptable

    -
    - -

    - Le composant de navigation web de SimpleTest peut être utilisé non seulement à l'extérieur de la classe WebTestCase, mais aussi indépendamment du frameword SimpleTest lui-même. -

    - -

    - -

    Le navigateur scriptable

    - -

    -

    - Vous pouvez utiliser le navigateur web dans des scripts PHP pour confirmer que des services marchent bien comme il faut ou pour extraire des informations à partir de ceux-ci de façon régulière. - Par exemple, voici un petit script pour extraire le nombre de bogues ouverts dans PHP 5 à partir du site web PHP... -

    -<?php
    -    require_once('simpletest/browser.php');
    -    
    -    $browser = &new SimpleBrowser();
    -    $browser->get('http://php.net/');
    -    $browser->clickLink('reporting bugs');
    -    $browser->clickLink('statistics');
    -    $browser->clickLink('PHP 5 bugs only');
    -    $page = $browser->getContent();
    -    preg_match('/status=Open.*?by=Any.*?(\d+)<\/a>/', $page, $matches);
    -    print $matches[1];
    -?>
    -
    - Bien sûr Il y a des méthodes plus simple pour réaliser cet exemple en PHP. Par exemple, vous pourriez juste utiliser la commande PHP file() sur ce qui est ici une page fixe. Cependant, en utilisant des scripts avec le navigateur web vous vous autorisez l'authentification, la gestion des cookies, le chargement automatique des fenêtres, les redirections, la transmission de formulaire et la capacité d'examiner les entêtes. De telles méthodes sont fragiles dans un site en constante évolution et vous voudrez employer une méthode plus directe pour accéder aux données de façon permanente, mais pour des tâches simples cette technique peut s'avérer une solution très rapide. -

    -

    - Toutes les méthode de navigation utilisées dans WebTestCase sont présente dans la classe SimpleBrowser, mais les assertions sont remplacées par de simples accesseurs. Voici une liste complète des méthodes de navigation de page à page... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    addHeader($header)Ajouter une entête à chaque téléchargement
    useProxy($proxy, $username, $password)Utilise ce proxy à partir de maintenant
    head($url, $parameters)Effectue une requête HEAD
    get($url, $parameters)Télécharge une page avec un GET
    post($url, $parameters)Télécharge une page avec un POST
    clickLink($label)Suit un lien par son étiquette
    isLink($label)Vérifie si un lien avec cette étiquette existe
    clickLinkById($id)Suit un lien par son attribut d'identification
    isLinkById($id)Vérifie si un lien avec cet attribut d'identification existe
    getUrl()La page ou la fenêtre URL en cours
    getTitle()Le titre de la page
    getContent()Le page ou la fenêtre brute
    getContentAsText()Sans code HTML à l'exception du text "alt"
    retry()Répète la dernière requête
    back()Utilise le bouton "précédent" du navigateur
    forward()Utilise le bouton "suivant" du navigateur
    authenticate($username, $password)Retente la page ou la fenêtre après une réponse 401
    restart($date)Relance le navigateur pour une nouvelle session
    ageCookies($interval)Change la date des cookies
    setCookie($name, $value)Lance un nouveau cookie
    getCookieValue($host, $path, $name)Lit le cookie le plus spécifique
    getCurrentCookieValue($name)Lit le contenue du cookie en cours
    - Les méthode SimpleBrowser::useProxy() et SimpleBrowser::addHeader() sont spéciales. Une fois appellées, elles continuent à s'appliquer sur les téléchargements suivants. -

    -

    - Naviguer dans les formulaires est similaire à la navigation des formulaires via WebTestCase... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    setField($name, $value)Modifie tous les champs avec ce nom
    setFieldById($id, $value)Modifie tous les champs avec cet identifiant
    getField($name)Accesseur de la valeur d'un élément de formulaire
    getFieldById($id)Accesseur de la valeur de l'élément de formulaire avec cet identifiant
    clickSubmit($label)Transmet le formulaire avec l'étiquette de son bouton
    clickSubmitByName($name)Transmet le formulaire avec l'attribut de son bouton
    clickSubmitById($id)Transmet le formulaire avec l'identifiant de son bouton
    clickImage($label, $x, $y)Clique sur l'image par son texte alternatif
    clickImageByName($name, $x, $y)Clique sur l'image par son attribut
    clickImageById($id, $x, $y)Clique sur l'image par son identifiant
    submitFormById($id)Transmet le formulaire par son identifiant propre
    - A aujourd'hui il n'existe aucune méthode pour lister les formulaires et les champs disponibles : ce sera probablement ajouté dans des versions successives de SimpleTest. -

    -

    - A l'intérieur d'une page, les fenêtres individuelles peuvent être sélectionnées. Si aucune sélection n'est réalisée alors toutes les fenêtres sont fusionnées ensemble dans un unique et grande page. Le contenu de la page en cours sera une concaténation des toutes les fenêtres dans l'ordre spécifié par les balises "frameset". - - - - - - - - - - - - - - - - - - -
    getFrames()Un déchargement de la structure de la fenêtre courante
    getFrameFocus()L'index ou l'étiquette de la fenêtre en courante
    setFrameFocusByIndex($choice)Sélectionne la fenêtre numérotée à partir de 1
    setFrameFocus($name)Sélectionne une fenêtre par son étiquette
    clearFrameFocus()Traite toutes les fenêtres comme une seule page
    - Lorsqu'on est focalisé sur une fenêtre unique, le contenu viendra de celle-ci uniquement. Cela comprend les liens à cliquer et les formulaires à transmettre. -

    - -

    - -

    Où sont les erreurs ?

    - -

    -

    - Toute cette masse de fonctionnalités est géniale lorsqu'on arrive à bien télécharger les pages, mais ce n'est pas toujours évident. Pour aider à découvrir les erreurs, le navigateur a aussi des méthodes pour aider au débogage. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    setConnectionTimeout($timeout)Ferme la socket avec un délai trop long
    getRequest()L'entête de la requête brute de la page ou de la fenêtre
    getHeaders()L'entête de réponse de la page ou de la fenêtre
    getTransportError()N'importe quel erreur au niveau de la socket dans le dernier téléchargement
    getResponseCode()La réponse HTTP de la page ou de la fenêtre
    getMimeType()Le type Mime de la page our de la fenêtre
    getAuthentication()Le type d'authenficiation dans l'entête d'une provocation 401
    getRealm()Le realm d'authentification dans l'entête d'une provocation 401
    setMaximumRedirects($max)Nombre de redirection avant que la page ne soit chargée automatiquement
    setMaximumNestedFrames($max)Protection contre des framesets récursifs
    ignoreFrames()Neutralise le support des fenêtres
    useFrames()Autorise le support des fenêtres
    - Les méthodes SimpleBrowser::setConnectionTimeout(), SimpleBrowser::setMaximumRedirects(),SimpleBrowser::setMaximumNestedFrames(), SimpleBrowser::ignoreFrames() et SimpleBrowser::useFrames() continuent à s'appliquer sur toutes les requêtes suivantes. Les autres méthodes tiennent compte des fenêtres. Cela veut dire que si une fenêtre individuel ne se charge pas, il suffit de se diriger vers elle avec SimpleBrowser::setFrameFocus() : ensuite on utilisera SimpleBrowser::getRequest(), etc. pour voir ce qui se passe. -

    - -

    - -

    Tests unitaires complexes avec des navigateurs multiples

    - -

    -

    - Tout ce qui peut être fait dans WebTestCase peut maintenant être fait dans un UnitTestCase. Ce qui revient à dire que nous pouvons librement mélanger des tests sur des objets de domaine avec l'interface web... -

    -class TestOfRegistration extends UnitTestCase {
    -    function testNewUserAddedToAuthenticator() {
    -        $browser = &new SimpleBrowser();
    -        $browser->get('http://my-site.com/register.php');
    -        $browser->setField('email', 'me@here');
    -        $browser->setField('password', 'Secret');
    -        $browser->clickSubmit('Register');
    -        
    -        $authenticator = &new Authenticator();
    -        $member = &$authenticator->findByEmail('me@here');
    -        $this->assertEqual($member->getPassword(), 'Secret');
    -    }
    -}
    -
    - Bien que ça puisse être utile par convenance temporaire, je ne suis pas fan de ce genre de test. Ce test s'applique à sur plusieurs couches de l'application, ça implique qu'il est plus que probable qu'il faudra le remanier lorsque le code change. -

    -

    - Un cas plus utile d'utilisation directe du navigateur est le moment où le WebTestCase ne peut plus suivre. Un exemple ? Quand deux navigateurs doivent être utilisés en même temps. -

    -

    - Par exemple, supposons que nous voulions interdire des usages simultanés d'un site avec le même login d'identification. Ce scénario de test le vérifie... -

    -class TestOfSecurity extends UnitTestCase {
    -    function testNoMultipleLoginsFromSameUser() {
    -        $first = &new SimpleBrowser();
    -        $first->get('http://my-site.com/login.php');
    -        $first->setField('name', 'Me');
    -        $first->setField('password', 'Secret');
    -        $first->clickSubmit('Enter');
    -        $this->assertEqual($first->getTitle(), 'Welcome');
    -        
    -        $second = &new SimpleBrowser();
    -        $second->get('http://my-site.com/login.php');
    -        $second->setField('name', 'Me');
    -        $second->setField('password', 'Secret');
    -        $second->clickSubmit('Enter');
    -        $this->assertEqual($second->getTitle(), 'Access Denied');
    -    }
    -}
    -
    - Vous pouvez aussi utiliser la classe SimpleBrowser quand vous souhaitez écrire des scénarios de test en utilisant un autre outil que SimpleTest. -

    - -
    - - - diff --git a/tests/test_tools/simpletest/docs/fr/docs.css b/tests/test_tools/simpletest/docs/fr/docs.css deleted file mode 100755 index 93226cd7..00000000 --- a/tests/test_tools/simpletest/docs/fr/docs.css +++ /dev/null @@ -1,84 +0,0 @@ -body { - padding-left: 3%; - padding-right: 3%; -} -pre { - font-family: 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/tests/test_tools/simpletest/docs/fr/expectation_documentation.html b/tests/test_tools/simpletest/docs/fr/expectation_documentation.html deleted file mode 100755 index ab9ef606..00000000 --- a/tests/test_tools/simpletest/docs/fr/expectation_documentation.html +++ /dev/null @@ -1,263 +0,0 @@ - - - -Documentation SimpleTest : étendre le testeur unitaire avec des classes d'attentes supplémentaires - - - - -

    Documentation sur les attentes

    -
    -

    - -

    Plus de contrôle sur les objets fantaisie

    - -

    -

    - Le comportement par défaut des objets fantaisie dans SimpleTest est soit une correspondance identique sur l'argument, soit l'acceptation de n'importe quel argument. Pour la plupart des tests, c'est suffisant. Cependant il est parfois nécessaire de ramollir un scénario de test. -

    -

    - Un des endroits où un test peut être trop serré est la reconnaissance textuelle. Prenons l'exemple d'un composant qui produirait un message d'erreur utile lorsque quelque chose plante. Il serait utile de tester que l'erreur correcte est renvoyée, mais le texte proprement dit risque d'être plutôt long. Si vous testez le texte dans son ensemble alors à chaque modification de ce même message -- même un point ou une virgule -- vous aurez à revenir sur la suite de test pour la modifier. -

    -

    - Voici un cas concret, nous avons un service d'actualités qui a échoué dans sa tentative de connexion à sa source distante. -

    -class NewsService {
    -    ...
    -    function publish(&$writer) {
    -        if (! $this->isConnected()) {
    -            $writer->write('Cannot connect to news service "' .
    -                    $this->_name . '" at this time. ' .
    -                    'Please try again later.');
    -        }
    -        ...
    -    }
    -}
    -
    - Là il envoie son contenu vers un classe Writer. Nous pourrions tester ce comportement avec un MockWriter... -
    -class TestOfNewsService extends UnitTestCase {
    -    ...
    -    function testConnectionFailure() {
    -        $writer = &new MockWriter($this);
    -        $writer->expectOnce('write', array(
    -                'Cannot connect to news service ' .
    -                '"BBC News" at this time. ' .
    -                'Please try again later.'));
    -        
    -        $service = &new NewsService('BBC News');
    -        $service->publish($writer);
    -        
    -        $writer->tally();
    -    }
    -}
    -
    - C'est un bon exemple d'un test fragile. Si nous décidons d'ajouter des instructions complémentaires, par exemple proposer une source d'actualités alternative, nous casserons nos tests par la même occasion sans pourtant avoir modifié une seule fonctionnalité. -

    -

    - Pour contourner ce problème, nous voudrions utiliser un test avec une expression rationnelle plutôt qu'une correspondance exacte. Nous pouvons y parvenir avec... -

    -class TestOfNewsService extends UnitTestCase {
    -    ...
    -    function testConnectionFailure() {
    -        $writer = &new MockWriter($this);
    -        $writer->expectOnce(
    -                'write',
    -                array(new WantedPatternExpectation('/cannot connect/i')));
    -        
    -        $service = &new NewsService('BBC News');
    -        $service->publish($writer);
    -        
    -        $writer->tally();
    -    }
    -}
    -
    - Plutôt que de transmettre le paramètre attendu au MockWriter, nous envoyons une classe d'attente appelée WantedPatternExpectation. L'objet fantaisie est suffisamment élégant pour reconnaître qu'il s'agit d'un truc spécial et pour le traiter différemment. Plutôt que de comparer l'argument entrant à cet objet, il utilise l'objet attente lui-même pour exécuter le test. -

    -

    - WantedPatternExpectation utilise l'expression rationnelle pour la comparaison avec son constructeur. A chaque fois q'une comparaison est fait à travers MockWriter par rapport à cette classe attente, elle fera un preg_match() avec ce motif. Dans notre scénario de test ci-dessus, aussi longtemps que la chaîne "cannot connect" apparaît dans le texte, la fantaisie transmettra un succès au testeur unitaire. Peu importe le reste du texte. -

    -

    - Les classes attente possibles sont... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    EqualExpectationUne égalité, plutôt que la plus forte comparaison à l'identique
    NotEqualExpectationUne comparaison sur la non-égalité
    IndenticalExpectationLa vérification par défaut de l'objet fantaisie qui doit correspondre exactement
    NotIndenticalExpectationInverse la logique de l'objet fantaisie
    WantedPatternExpectationUtilise une expression rationnelle Perl pour comparer une chaîne
    NoUnwantedPatternExpectationPasse seulement si l'expression rationnelle Perl échoue
    IsAExpectationVérifie le type ou le nom de la classe uniquement
    NotAExpectationL'opposé de IsAExpectation
    MethodExistsExpectationVérifie si la méthode est disponible sur un objet
    - La plupart utilisent la valeur attendue dans le constructeur. Les exceptions sont les vérifications sur motif, qui utilisent une expression rationnelle, ainsi que IsAExpectation et NotAExpectation, qui prennent un type ou un nom de classe comme chaîne. -

    - -

    - -

    Utiliser les attentes pour contrôler les bouchons serveur

    - -

    -

    - Les classes attente peuvent servir à autre chose que l'envoi d'assertions depuis les objets fantaisie, afin de choisir le comportement d'un objet fantaisie our celui d'un bouchon serveur. A chaque fois qu'une liste d'arguments est donnée, une liste d'objets attente peut être insérée à la place. -

    -

    - Mettons que nous voulons qu'un bouchon serveur d'autorisation simule une connexion réussie seulement si il reçoit un objet de session valide. Nous pouvons y arriver avec ce qui suit... -

    -Stub::generate('Authorisation');
    -
    -$authorisation = new StubAuthorisation();
    -$authorisation->setReturnValue(
    -        'isAllowed',
    -        true,
    -        array(new IsAExpectation('Session', 'Must be a session')));
    -$authorisation->setReturnValue('isAllowed', false);
    -
    - Le comportement par défaut du bouchon serveur est défini pour renvoyer false quand isAllowed est appelé. Lorsque nous appelons cette méthode avec un unique paramètre qui est un objet Session, il renverra true. Nous avons aussi ajouté un deuxième paramètre comme message. Il sera affiché dans le message d'erreur de l'objet fantaisie si l'attente est la cause de l'échec. -

    -

    - Ce niveau de sophistication est rarement utile : il n'est inclut que pour être complet. -

    - -

    - -

    Créer vos propres attentes

    - -

    -

    - Les classes d'attentes ont une structure très simple. Tellement simple qu'il devient très simple de créer vos propres version de logique pour des tests utilisés couramment. -

    -

    - Par exemple voici la création d'une classe pour tester la validité d'adresses IP. Pour fonctionner correctement avec les bouchons serveurs et les objets fantaisie, cette nouvelle classe d'attente devrait étendre SimpleExpectation... -

    -class ValidIp extends SimpleExpectation {
    -    
    -    function test($ip) {
    -        return (ip2long($ip) != -1);
    -    }
    -    
    -    function testMessage($ip) {
    -        return "Address [$ip] should be a valid IP address";
    -    }
    -}
    -
    - Il n'y a véritablement que deux méthodes à mettre en place. La méthode test() devrait renvoyer un true si l'attente doit passer, et une erreur false dans le cas contraire. La méthode testMessage() ne devrait renvoyer que du texte utile à la compréhension du test en lui-même. -

    -

    - Cette classe peut désormais être employée à la place des classes d'attente précédentes. -

    - -

    - -

    Sous le capot du testeur unitaire

    - -

    -

    - Le frameworkd de test unitaire SimpleTest utilise aussi dans son coeur des classes d'attente pour la classe UnitTestCase. Nous pouvons aussi tirer parti de ces mécanismes pour réutiliser nos propres classes attente à l'intérieur même des suites de test. -

    -

    - La méthode la plus directe est d'utiliser la méthode SimpleTest::assertExpectation() pour effectuer le test... -

    -class TestOfNetworking extends UnitTestCase {
    -    ...
    -    function testGetValidIp() {
    -        $server = &new Server();
    -        $this->assertExpectation(
    -                new ValidIp(),
    -                $server->getIp(),
    -                'Server IP address->%s');
    -    }
    -}
    -
    - C'est plutôt sale par rapport à notre syntaxe habituelle du type assert...(). -

    -

    - Pour un cas aussi simple, nous créons d'ordinaire une méthode d'assertion distincte en utilisant la classe d'attente. Supposons un instant que notre attente soit un peu plus compliquée et que par conséquent nous souhaitions la réutiliser, nous obtenons... -

    -class TestOfNetworking extends UnitTestCase {
    -    ...
    -    function assertValidIp($ip, $message = '%s') {
    -        $this->assertExpectation(new ValidIp(), $ip, $message);
    -    }
    -    
    -    function testGetValidIp() {
    -        $server = &new Server();
    -        $this->assertValidIp(
    -                $server->getIp(),
    -                'Server IP address->%s');
    -    }
    -}
    -
    - Il est peu probable que nous ayons besoin de ce niveau de contrôle sur la machinerie de test. Il est assez rare que le besoin d'une attente dépasse le stade de la reconnaissance d'un motif. De plus, les classes d'attente complexes peuvent rendre les tests difficiles à lire et à déboguer. Ces mécanismes sont véritablement là pour les auteurs de système qui étendront le framework de test pour leurs propres outils de test. -

    - -
    - - - diff --git a/tests/test_tools/simpletest/docs/fr/form_testing_documentation.html b/tests/test_tools/simpletest/docs/fr/form_testing_documentation.html deleted file mode 100755 index f9f5d0df..00000000 --- a/tests/test_tools/simpletest/docs/fr/form_testing_documentation.html +++ /dev/null @@ -1,235 +0,0 @@ - - - -Documentation SimpleTest : tester des formulaires HTML - - - - -

    Documentation sur les tests de formulaire

    -
    -

    - -

    Valider un formulaire simple

    - -

    -

    - Lorsqu'une page est téléchargée par WebTestCase en utilisant get() ou post() le contenu de la page est automatiquement analysé. De cette analyse découle le fait que toutes les commandes à l'intérieur de la balise <form> sont disponibles depuis l'intérieur du scénario de test. Prenons pas exemple cet extrait de code HTML... -

    -<form>
    -    <input type="text" name="a" value="A default" />
    -    <input type="submit" value="Go" />
    -</form>
    -
    - Il ressemble à... -

    -

    -

    - - -
    -

    -

    - Nous pouvons naviguer vers ce code, via le site LastCraft, avec le test suivant... -

    -class SimpleFormTests extends WebTestCase {
    -    
    -    function testDefaultValue() {
    -        $this->get('http://www.lastcraft.com/form_testing_documentation.php');
    -        $this->assertField('a', 'A default');
    -    }
    -}
    -
    - Directement après le chargement de la page toutes les commandes HTML sont initiées avec leur valeur par défaut, comme elles apparaîtraient dans un navigateur web. L'assertion teste qu'un objet HTML avec le nom "a" existe dans la page et qu'il contient la valeur "A default". -

    -

    - Nous pourrions retourner le formulaire tout de suite, mais d'abord nous allons changer la valeur du champ texte. Ce n'est qu'après que nous le transmettre... -

    -class SimpleFormTests extends WebTestCase {
    -
    -    function testDefaultValue() {
    -        $this->get('http://www.my-site.com/');
    -        $this->assertField('a', 'A default');
    -        $this->setField('a', 'New value');
    -        $this->clickSubmit('Go');
    -    }
    -}
    -
    - Parce que nous n'avons spécifié ni attribut "method" sur la balise form, ni attribut "action", le scénario de test suivra le comportement classique d'un navigateur : transmission des données avec une requête GET vers la même page. SimpleTest essaie d'émuler le comportement typique d'un navigateur autant que possible, plutôt que d'essayer d'attraper des attributs manquants sur les balises. La raison est simple : la cible d'un framework de test est la logique d'une application PHP, pas les erreurs -- de syntaxe ou autres -- du code HTML. Pour les erreurs HTML, d'autres outils tel HTMLTidy devraient être employés. -

    -

    - Si un champ manque dans n'importe que formulaire ou si une option est indisponible alors WebTestCase::setField() renverra false. Par exemple, supposons que nous souhaitons vérifier qu'une option "Superuser" n'est pas présente dans ce formulaire... -

    -<strong>Select type of user to add:</strong>
    -<select name="type">
    -    <option>Subscriber</option>
    -    <option>Author</option>
    -    <option>Administrator</option>
    -</select>
    -
    - Qui ressemble à... -

    -

    -

    - Select type of user to add: - -
    -

    -

    - Le test suivant le confirmera... -

    -class SimpleFormTests extends WebTestCase {
    -    ...
    -    function testNoSuperuserChoiceAvailable() {
    -        $this->get('http://www.lastcraft.com/form_testing_documentation.php');
    -        $this->assertFalse($this->setField('type', 'Superuser'));
    -    }
    -}
    -
    - La sélection ne sera pas changée suite à un échec d'initialisation d'une valeur sur un objet. -

    -

    - Voici la liste complète des objets supportés à aujourd'hui... -

      -
    • Champs texte, y compris les champs masqués (hidden) ou cryptés (password).
    • -
    • Boutons submit, en incluant aussi la balise button, mais pas encore les boutons reset
    • -
    • Aires texte (textarea) avec leur gestion des retours à la ligne (wrap).
    • -
    • Cases à cocher, y compris les cases à cocher multiples dans un même formulaire.
    • -
    • Listes à menu déroulant, y compris celles à sélections multiples.
    • -
    • Boutons radio.
    • -
    • Images.
    • -
    -

    -

    - Bien que la plupart des objets HTML standards soient couvert par le parseur de SimpleTest, il est peu probable que JavaScript soit implémenté dans un futur proche. -

    - -

    - -

    Champs à valeurs multiples

    - -

    -

    - 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... -

    -<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>
    -
    - Qui se traduit par... -

    -

    -

    - Create privileges allowed: - -
    - Retrieve privileges allowed: - -
    - Update privileges allowed: - -
    - Destroy privileges allowed: - -
    - -
    -

    -

    - 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... -

    -class SimpleFormTests extends WebTestCase {
    -    ...
    -    function testDisableNastyPrivileges() {
    -        $this->get('http://www.lastcraft.com/form_testing_documentation.php');
    -        $this->assertField('crud', array('c', 'r', 'u', 'd'));
    -        $this->setField('crud', array('r'));
    -        $this->clickSubmit('Enable Privileges');
    -    }
    -}
    -
    - Plutôt que d'initier le champ à une valeur unique, nous lui donnons une liste de valeurs. Nous faisons la même chose pour tester les valeurs attendues. Nous pouvons écrire d'autre code de test pour confirmer cet effet, peut-être en nous connectant comme utilisateur et en essayant d'effectuer une mise à jour. -

    -

    - -

    Envoi brut

    - -

    -

    - 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. -

    -class SimpleFormTests extends WebTestCase {
    -    ...    
    -    function testAttemptedHack() {
    -        $this->post(
    -                'http://www.my-site.com/add_user.php',
    -                array('type' => 'superuser'));
    -        $this->assertNoUnwantedPattern('/user created/i');
    -    }
    -}
    -
    - En ajoutant des données à la méthode WebTestCase::post(), nous essayons de télécharger la page via la transmission d'un formulaire. -

    - -
    - - - diff --git a/tests/test_tools/simpletest/docs/fr/group_test_documentation.html b/tests/test_tools/simpletest/docs/fr/group_test_documentation.html deleted file mode 100755 index 662f868e..00000000 --- a/tests/test_tools/simpletest/docs/fr/group_test_documentation.html +++ /dev/null @@ -1,288 +0,0 @@ - - - -Documentation SimpleTest : Grouper des tests - - - - -

    Documentation sur le groupement des tests

    -
    -

    - -

    Grouper des tests

    - -

    -

    - Pour lancer les scénarios de tests en tant que groupe, ils devraient être placés dans des fichiers sans le code du lanceur... -

    -<?php
    -    require_once('../classes/io.php');
    -
    -    class FileTester extends UnitTestCase {
    -        ...
    -    }
    -
    -    class SocketTester extends UnitTestCase {
    -        ...
    -    }
    -?>
    -
    - Autant de scénarios que nécessaires peuvent être mis dans un fichier unique. Ils doivent contenir tout le code nécessaire, entre autres la bibliothèque testée, mais aucune des bibliothèques de SimpleTest. -

    -

    - Si vous avez étendu l'un ou l'autre des scénarios de test, vous pouvez aussi les inclure. -

    -<?php
    -    require_once('../classes/io.php');
    -
    -    class MyFileTestCase extends UnitTestCase {
    -        ...
    -    }
    -    SimpleTestOptions::ignore('MyFileTestCase');
    -
    -    class FileTester extends MyFileTestCase {
    -        ...
    -    }
    -
    -    class SocketTester extends UnitTestCase {
    -        ...
    -    }
    -?>
    -
    - La classe FileTester ne contient aucun test véritable, il s'agit d'une classe de base pour d'autres scénarios de test. Pour cette raison nous utilisons la directive SimpleTestOptions::ignore() pour indiquer au prochain groupe de test de l'ignorer. Cette directive peut se placer n'importe où dans le fichier et fonctionne quand un fichier complet des scénarios de test est chargé (cf. ci-dessous). Nous l'appelons file_test.php. -

    -

    - Ensuite nous créons un fichier de groupe de test, disons group_test.php. Vous penserez à un nom plus convaincant, j'en suis sûr. Nous lui ajoutons le fichier de test avec une méthode sans risque... -

    -<?php
    -    require_once('simpletest/unit_tester.php');
    -    require_once('simpletest/reporter.php');
    -    require_once('file_test.php');
    -
    -    $test = &new GroupTest('All file tests');
    -    $test->addTestCase(new FileTestCase());
    -    $test->run(new HtmlReporter());
    -?>
    -
    - Ceci instancie le scénario de test avant que la suite de test ne soit lancée. Ça pourrait devenir assez onéreux avec un grand nombre de scénarios de test : il existe donc une autre méthode qui instancie la classe uniquement quand elle devient nécessaire... -
    -<?php
    -    require_once('simpletest/unit_tester.php');
    -    require_once('simpletest/reporter.php');
    -    require_once('file_test.php');
    -
    -    $test = &new GroupTest('All file tests');
    -    $test->addTestClass('FileTestCase');
    -    $test->run(new HtmlReporter());
    -?>
    -
    - Le problème de cette technique est que pour chaque scénario de test supplémentaire nous aurons à require_once() le fichier de code de test et à manuellement instancier chaque scénario de test. Nous pouvons nous épargner beaucoup de dactylographie avec... -
    -<?php
    -    require_once('simpletest/unit_tester.php');
    -    require_once('simpletest/reporter.php');
    -
    -    $test = &new GroupTest('All file tests');
    -    $test->addTestFile('file_test.php');
    -    $test->run(new HtmlReporter());
    -?&gt;
    -
    - Voici ce qui vient de se passer : la classe GroupTest a réalisé le require_once() pour nous. Ensuite elle vérifie si de nouvelles classes de scénario de test ont été créées par ce nouveau fichier et les ajoute automatiquement au groupe de test. Désormais tout ce qu'il nous reste à faire, c'est d'ajouter chaque nouveau fichier. -

    -

    - Il y a deux choses qui peuvent planter et qui demandent un minimum d'attention... -

      -
    1. - Le fichier peut déjà avoir été analysé par PHP et dans ce cas aucune classe ne sera ajoutée. Pensez à bien vérifier que les scénarios de test ne sont inclus que dans ce fichier et dans aucun autre. -
    2. -
    3. - Les nouvelles classes d'extension de scénario de test qui sont incluses seront placées dans le groupe de test et exécutées par la même occasion. Vous aurez à ajouter une directive SimpleTestOptions::ignore() pour ces classes ou alors pensez à les ajouter avant la ligne GroupTest::addTestFile(). -
    4. -
    -

    - -

    - -

    Groupements de plus haut niveau

    - -

    -

    - La technique ci-dessus place tous les scénarios de test dans un unique et grand groupe. Sauf que pour des projets plus conséquents, ce n'est probablement pas assez souple ; vous voudriez peut-être grouper les tests tout à fait différemment. -

    -

    - Pour obtenir un groupe de test plus souple nous pouvons sous classer GroupTest et ensuite l'instancier au cas par cas... -

    -<?php
    -    require_once('simpletest/unit_tester.php');
    -    require_once('simpletest/reporter.php');
    -    
    -    class FileGroupTest extends GroupTest {
    -        function FileGroupTest() {
    -            $this->GroupTest('All file tests');
    -            $this->addTestFile('file_test.php');
    -        }
    -    }
    -?>
    -
    - Ceci nomme le test dans le constructeur et ensuite ajoute à la fois nos scénarios de test et un unique groupe en dessous. Bien sûr nous pouvons ajouter plus d'un groupe à cet instant. Nous pouvons maintenant invoquer les tests à partir d'un autre fichier d'exécution... -
    -<?php
    -    require_once('file_group_test.php');
    -    
    -    $test = &new FileGroupTest();
    -    $test->run(new HtmlReporter());
    -?>
    -
    - ...ou alors nous pouvons les grouper dans un groupe de tests encore plus grand... -
    -<?php
    -    require_once('file_group_test.php');
    -    
    -    $test = &new BigGroupTest('Big group');
    -    $test->addTestCase(new FileGroupTest());
    -    $test->addTestCase(...);
    -    $test->run(new HtmlReporter());
    -?>
    -
    - Si nous souhaitons lancer le groupe de test original sans utiliser ses petits fichiers d'exécution, nous pouvons mettre le code du lanceur de test derrière des barreaux quand nous créons chaque groupe. -
    -<?php
    -    class FileGroupTest extends GroupTest {
    -        function FileGroupTest() {
    -            $this->GroupTest('All file tests');
    -            $test->addTestFile('file_test.php');
    -        }
    -    }
    -    
    -    if (! defined('RUNNER')) {
    -        define('RUNNER', true);
    -        $test = &new FileGroupTest();
    -        $test->run(new HtmlReporter());
    -    }
    -?>
    -
    - Cette approche exige aux barrières d'être activées à l'inclusion du fichier de groupe de test, mais c'est quand même moins de tracas que beaucoup de fichiers de lancement éparpillés. Reste à inclure des barreaux identiques au niveau supérieur afin de s'assurer que le run() ne sera lancé qu'une seule fois à partir du script de haut niveau qui l'a invoqué. -
    -<?php
    -    define('RUNNER', true);
    -
    -    require_once('file_group_test.php');
    -    $test = &new BigGroupTest('Big group');
    -    $test->addTestCase(new FileGroupTest());
    -    $test->addTestCase(...);
    -    $test->run(new HtmlReporter());
    -?>
    -
    - Comme les scénarios de test normaux, un GroupTest peut être chargé avec la méthode GroupTest::addTestFile(). -
    	
    -<?php	
    -    define('RUNNER', true);	
    - 	 	
    -    $test = &new BigGroupTest('Big group');	
    -    $test->addTestFile('file_group_test.php');	
    -    $test->addTestFile(...);	
    -    $test->run(new HtmlReporter());	
    -?>	
    -
    -

    - -

    - -

    Intégrer des scénarios de test hérités

    - -

    -

    - Si vous avez déjà des tests unitaires pour votre code ou alors si vous étendez des classes externes qui ont déjà leurs propres tests, il y a peu de chances pour que ceux-ci soient déjà au format SimpleTest. Heureusement il est possible d'incorporer ces scénarios de test en provenance d'autres testeurs unitaires directement dans des groupes de test SimpleTest. -

    -

    - Par exemple, supposons que nous ayons ce scénario de test prévu pour PhpUnitdans le fichier config_test.php... -

    -class ConfigFileTest extends TestCase {
    -    function ConfigFileTest() {
    -        $this->TestCase('Config file test');
    -    }
    -    
    -    function testContents() {
    -        $config = new ConfigFile('test.conf');
    -        $this->assertRegexp('/me/', $config->getValue('username'));
    -    }
    -}
    -
    - Le groupe de test peut le reconnaître à partir du moment où nous mettons l'adaptateur approprié avant d'ajouter le fichier de test... -
    -<?php
    -    require_once('simpletest/unit_tester.php');
    -    require_once('simpletest/reporter.php');
    -    require_once('simpletest/adapters/phpunit_test_case.php');
    -
    -    $test = &new GroupTest('All file tests');
    -    $test->addTestFile('config_test.php');
    -    $test->run(new HtmlReporter());
    -?>
    -
    - Il n'y a que deux adaptateurs, l'autre est pour le paquet testeur unitaire de PEAR... -
    -<?php
    -    require_once('simpletest/unit_tester.php');
    -    require_once('simpletest/reporter.php');
    -    require_once('simpletest/adapters/pear_test_case.php');
    -
    -    $test = &new GroupTest('All file tests');
    -    $test->addTestFile('some_pear_test_cases.php');
    -    $test->run(new HtmlReporter());
    -?>
    -
    - Les scénarios de test de PEAR peuvent être librement mélangés avec ceux de SimpleTest mais vous ne pouvez pas utiliser les assertions de SimpleTest au sein des versions héritées des scénarios de test. La raison ? Une simple vérification que vous ne rendez pas par accident vos scénarios de test complètement dépendants de SimpleTest. Peut-être que vous souhaitez publier votre bibliothèque sur PEAR par exemple : ça voudrait dire la livrer avec des scénarios de test compatibles avec PEAR::PhpUnit. -

    - -
    - - - diff --git a/tests/test_tools/simpletest/docs/fr/index.html b/tests/test_tools/simpletest/docs/fr/index.html deleted file mode 100755 index f4b2ad93..00000000 --- a/tests/test_tools/simpletest/docs/fr/index.html +++ /dev/null @@ -1,343 +0,0 @@ - - - - - Télécharger le framework de tests Simple Test - Tests unitaire et objets fantaisie pour PHP - - - - - -

    Simple Test pour PHP

    -
    - -

    - Le présent article présuppose que vous soyez familier avec le concept de tests unitaires ainsi que celui de développement web avec le langage PHP. Il s'agit d'un guide pour le nouvel et impatient utilisateur de SimpleTest. Pour une documentation plus complète, particulièrement si vous découvrez les tests unitaires, consultez la documentation en cours, et pour des exemples de scénarios de test, consultez le tutorial sur les tests unitaires. -

    - -

    - -

    Utiliser le testeur rapidement

    - -

    -

    - Parmi les outils de test pour logiciel, le testeur unitaire est le plus proche du développeur. Dans un contexte de développement agile, le code de test se place juste à côté du code source étant donné que tous les deux sont écrits simultanément. Dans ce contexte, SimpleTest aspire à être une solution complète de test pour un développeur PHP et s'appelle "Simple" parce qu'elle devrait être simple à utiliser et à étendre. Ce nom n'était pas vraiment un bon choix. Non seulement cette solution inclut toutes les fonctions classiques qu'on est en droit d'attendre de la part des portages de JUnit et des PHPUnit, mais elle inclut aussi les objets fantaisie ou "mock objects". Sans compter quelques fonctionnalités de JWebUnit : parmi celles-ci la navigation sur des pages web, les tests sur les cookies et l'envoi de formulaire. -

    -

    - La démonstration la plus rapide : l'exemple -

    -

    - Supposons que nous sommes en train de tester une simple classe de log dans un fichier : elle s'appelle Log dans classes/Log.php. Commençons par créer un script de test, appelé tests/log_test.php. Son contenu est le suivant... -

    -<?php
    -require_once('simpletest/unit_tester.php');
    -require_once('simpletest/reporter.php');
    -require_once('../classes/log.php');
    -?>
    -
    - Ici le répertoire simpletest est soit dans le dossier courant, soit dans les dossiers pour fichiers inclus. Vous auriez à éditer ces arborescences suivant l'endroit où vous avez installé SimpleTest. Ensuite créons un scénario de test... -
    -<?php
    -require_once('simpletest/unit_tester.php');
    -require_once('simpletest/reporter.php');
    -require_once('../classes/log.php');
    -
    -class TestOfLogging extends UnitTestCase {
    -}
    -?>
    -
    - A présent il y a 5 lignes de code d'échafaudage et toujours pas de test. Cependant à partir de cet instant le retour sur investissement arrive très rapidement. Supposons que la classe Log prenne le nom du fichier à écrire dans le constructeur et que nous ayons un répertoire temporaire dans lequel placer ce fichier... -
    -<?php
    -require_once('simpletest/unit_tester.php');
    -require_once('simpletest/reporter.php');
    -require_once('../classes/log.php');
    -
    -class TestOfLogging extends UnitTestCase {
    -    
    -    function testCreatingNewFile() {
    -        @unlink('/temp/test.log');
    -        $log = new Log('/temp/test.log');
    -        $this->assertFalse(file_exists('/temp/test.log'));
    -        $log->message('Should write this to a file');
    -        $this->assertTrue(file_exists('/temp/test.log'));
    -    }
    -}
    -?>
    -
    - Au lancement du scénario de test, toutes les méthodes qui commencent avec la chaîne test sont identifiées puis exécutées. D'ordinaire nous avons bien plusieurs méthodes de tests. Les assertions dans les méthodes de test envoient des messages vers le framework de test qui affiche immédiatement le résultat. Cette réponse immédiate est importante, non seulement lors d'un crash causé par le code, mais aussi de manière à rapprocher l'affichage de l'erreur au plus près du scénario de test concerné. -

    -

    - Pour voir ces résultats lançons effectivement les tests. S'il s'agit de l'unique scénario de test à lancer, on peut y arriver avec... -

    -<?php
    -require_once('simpletest/unit_tester.php');
    -require_once('simpletest/reporter.php');
    -require_once('../classes/log.php');
    -
    -class TestOfLogging extends UnitTestCase {
    -    
    -    function testCreatingNewFile() {
    -        @unlink('/temp/test.log');
    -        $log = new Log('/temp/test.log');
    -        $this->assertFalse(file_exists('/temp/test.log'));
    -        $log->message('Should write this to a file');
    -        $this->assertTrue(file_exists('/temp/test.log'));
    -    }
    -}
    -
    -$test = &new TestOfLogging();
    -$test->run(new HtmlReporter());
    -?>
    -
    -

    -

    - En cas échec, l'affichage ressemble à... -

    -

    testoflogging

    - Fail: testcreatingnewfile->True assertion failed.
    -
    1/1 test cases complete. - 1 passes and 1 fails.
    -
    - ...et si ça passe, on obtient... -
    -

    testoflogging

    -
    1/1 test cases complete. - 2 passes and 0 fails.
    -
    - Et si vous obtenez ça... -
    - Fatal error: Failed opening required '../classes/log.php' (include_path='') in /home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php on line 7 -
    - c'est qu'il vous manque le fichier classes/Log.php qui pourrait ressembler à : -
    -<?php
    -class Log {
    -    
    -        function Log($file_path) {
    -        }
    -}
    -?>;
    -
    -

    - -

    - -

    Construire des groupes de tests

    - -

    -

    - Il est peu probable que dans une véritable application on ait uniquement besoin de passer un seul scénario de test. Cela veut dire que nous avons besoin de grouper les scénarios dans un script de test qui peut, si nécessaire, lancer tous les tests de l'application. -

    -

    - Notre première étape est de supprimer les includes et de défaire notre hack précédent... -

    -<?php
    -require_once('../classes/log.php');
    -
    -class TestOfLogging extends UnitTestCase {
    -    
    -    function testCreatingNewFile() {
    -        @unlink('/temp/test.log');
    -        $log = new Log('/temp/test.log');
    -        $this->assertFalse(file_exists('/temp/test.log'));
    -        $log->message('Should write this to a file');
    -        $this->assertTrue(file_exists('/temp/test.log'));
    -    }
    -}
    -?>
    -
    - Ensuite nous créons un nouveau fichier appelé tests/all_tests.php. On y insert le code suivant... -
    -<?php
    -require_once('simpletest/unit_tester.php');
    -require_once('simpletest/reporter.php');
    -
    -$test = &new GroupTest('All tests');
    -$test->addTestFile('log_test.php');
    -$test->run(new HtmlReporter());
    -?>
    -
    - Cette méthode GroupTest::addTestFile() va inclure le fichier de scénarios de test et lire parmi toutes les nouvelles classes créées celles qui sont issues de TestCase. Dans un premier temps, seuls les noms sont stockés, de la sorte le lanceur de test peut instancier la classe au fur et à mesure qu'il exécute votre suite de tests. -

    -

    - Pour que ça puisse marcher proprement le fichier de suite de tests ne devrait pas inclure aveuglement d'autres extensions de scénarios de test qui n'exécuteraient pas effectivement de test. Le résultat pourrait être que des tests supplémentaires soient alors être comptabilisés pendant l'exécution des tests. Ce n'est pas un problème grave mais pour éviter ce désagrément, il suffit d'ajouter la commande SimpleTestOptions::ignore() quelque part dans le fichier de scénario de test. Par ailleurs le scénario de test ne devrait pas avoir été inclus ailleurs ou alors aucun scénario ne sera ajouté aux groupes de test. Il s'agirait là d'une erreur autrement sérieuse : si tous les classes de scénario de test sont chargées par PHP, alors la méthode GroupTest::addTestFile() ne pourra pas les détecter. -

    -

    - Pour afficher les résultats, il est seulement nécessaire d'invoquer tests/all_tests.php à partir du serveur web. -

    - -

    - -

    Utiliser les objets fantaisie

    - -

    -

    - Avançons un peu plus dans le futur. -

    -

    - Supposons que notre class logging soit testée et terminée. Supposons aussi que nous testons une autre classe qui ait besoin d'écrire des messages de log, disons SessionPool. Nous voulons tester une méthode qui ressemblera probablement à quelque chose comme... -

    -
    -class SessionPool {
    -    ...
    -    function logIn($username) {
    -        ...
    -        $this->_log->message('User $username logged in.');
    -        ...
    -    }
    -    ...
    -}
    -
    -
    - Avec le concept de "réutilisation de code" comme fil conducteur, nous utilisons notre class Log. Un scénario de test classique ressemblera peut-être à... -
    -
    -<?php
    -require_once('../classes/log.php');
    -require_once('../classes/session_pool.php');
    -
    -class TestOfSessionLogging extends UnitTestCase {
    -    
    -    function setUp() {
    -        @unlink('/temp/test.log');
    -    }
    -    
    -    function tearDown() {
    -        @unlink('/temp/test.log');
    -    }
    -    
    -    function testLogInIsLogged() {
    -        $log = new Log('/temp/test.log');
    -        $session_pool = &new SessionPool($log);
    -        $session_pool->logIn('fred');
    -        $messages = file('/temp/test.log');
    -        $this->assertEqual($messages[0], "User fred logged in.\n");
    -    }
    -}
    -?>
    -
    - Le design de ce scénario de test n'est pas complètement mauvais, mais on peut l'améliorer. Nous passons du temps à tripoter les fichiers de log qui ne font pas partie de notre test. Pire, nous avons créé des liens de proximité entre la classe Log et ce test. Que se passerait-il si nous n'utilisions plus de fichiers, mais la bibliothèque syslog à la place ? Avez-vous remarqué le retour chariot supplémentaire à la fin du message ? A-t-il été ajouté par le loggueur ? Et si il ajoutait aussi un timestamp ou d'autres données ? -

    -

    - L'unique partie à tester réellement est l'envoi d'un message précis au loggueur. Nous réduisons le couplage en créant une fausse classe de logging : elle ne fait qu'enregistrer le message pour le test, mais ne produit aucun résultat. Sauf qu'elle doit ressembler exactement à l'original. -

    -

    - Si l'objet fantaisie n'écrit pas dans un fichier alors nous nous épargnons la suppression du fichier avant et après le test. Nous pourrions même nous épargner quelques lignes de code supplémentaires si l'objet fantaisie pouvait exécuter l'assertion. -

    -

    - Trop beau pour être vrai ? Par chance on peut créer un tel objet très facilement... -
    -<?php
    -require_once('../classes/log.php');
    -require_once('../classes/session_pool.php');
    -Mock::generate('Log');
    -
    -class TestOfSessionLogging extends UnitTestCase {
    -    
    -    function testLogInIsLogged() {
    -        $log = &new MockLog($this);
    -        $log->expectOnce('message', array('User fred logged in.'));
    -        $session_pool = &new SessionPool($log);
    -        $session_pool->logIn('fred');
    -        $log->tally();
    -    }
    -}
    -?>
    -
    - L'appel tally() est nécessaire pour annoncer à l'objet fantaisie qu'il n'y aura plus d'appels ultérieurs. Sans ça l'objet fantaisie pourrait attendre pendant une éternité l'appel de la méthode sans jamais prévenir le scénario de test. Les autres tests sont déclenchés automatiquement quand l'appel à message() est invoqué sur l'objet MockLog. L'appel mock va déclencher une comparaison des paramètres et ensuite envoyer le message "pass" ou "fail" au test pour l'affichage. Des jokers peuvent être inclus ici aussi afin d'empêcher que les tests ne deviennent trop spécifiques. -

    -

    - Les objets fantaisie dans la suite SimpleTest peuvent avoir un ensemble de valeurs de sortie arbitraires, des séquences de sorties, des valeurs de sortie sélectionnées à partir des arguments d'entrée, des séquences de paramètres attendus et des limites sur le nombre de fois qu'une méthode peut être invoquée. -

    -

    - Pour que ce test fonctionne la librairie avec les objets fantaisie doit être incluse dans la suite de tests, par exemple dans all_tests.php. -

    - -

    - -

    Tester une page web

    - -

    -

    - Une des exigences des sites web, c'est qu'ils produisent des pages web. Si vous construisez un projet de A à Z et que vous voulez intégrer des tests au fur et à mesure alors vous voulez un outil qui puisse effectuer une navigation automatique et en examiner le résultat. C'est le boulot d'un testeur web. -

    -

    - Effectuer un test web via SimpleTest reste assez primitif : il n'y a pas de javascript par exemple. Pour vous donner une idée, voici un exemple assez trivial : aller chercher une page web, à partir de là naviguer vers la page "about" et finalement tester un contenu déterminé par le client. -

    -<?php
    -require_once('simpletest/web_tester.php');
    -require_once('simpletest/reporter.php');
    -
    -class TestOfAbout extends WebTestCase {
    -    
    -    function setUp() {
    -        $this->get('http://test-server/index.php');
    -        $this->clickLink('About');
    -    }
    -    
    -    function testSearchEngineOptimisations() {
    -        $this->assertTitle('A long title about us for search engines');
    -        $this->assertWantedPattern('/a popular keyphrase/i');
    -    }
    -}
    -$test = &new TestOfAbout();
    -$test->run(new HtmlReporter());
    -?>
    -
    - Avec ce code comme test de recette, vous pouvez vous assurer que le contenu corresponde toujours aux spécifications à la fois des développeurs et des autres parties prenantes au projet. -

    -

    - SourceForge.net Logo -

    - -
    - - - diff --git a/tests/test_tools/simpletest/docs/fr/mock_objects_documentation.html b/tests/test_tools/simpletest/docs/fr/mock_objects_documentation.html deleted file mode 100755 index 0ce48bc9..00000000 --- a/tests/test_tools/simpletest/docs/fr/mock_objects_documentation.html +++ /dev/null @@ -1,492 +0,0 @@ - - - -Documentation SimpleTest : les objets fantaise - - - - -

    Documentation sur les objets fantaisie

    -
    -

    - -

    Que sont les objets fantaisie ?

    - -

    -

    - Les objets fantaisie - ou "mock objects" en anglais - ont deux rôles pendant un scénario de test : acteur et critique. -

    -

    - Le comportement d'acteur est celui de simuler des objets difficiles à initialiser ou trop consommateurs en temps pendant un test. Le cas classique est celui de la connexion à une base de données. Mettre sur pied une base de données de test au lancement de chaque test ralentirait considérablement les tests et en plus exigerait l'installation d'un moteur de base de données ainsi que des données sur la machine de test. Si nous pouvons simuler la connexion et renvoyer des données à notre guise alors non seulement nous gagnons en pragmatisme sur les tests mais en sus nous pouvons nourrir notre base avec des données falsifiées et voir comment il répond. Nous pouvons simuler une base de données en suspens ou d'autres cas extrêmes sans avoir à créer une véritable panne de base de données. En d'autres termes nous pouvons gagner en contrôle sur l'environnement de test. -

    -

    - Si les objets fantaisie ne se comportaient que comme des acteurs alors on les connaîtrait sous le nom de bouchons serveur. -

    -

    - Cependant non seulement les objets fantaisie jouent un rôle (en fournissant à la demande les valeurs requises) mais en plus ils sont aussi sensibles aux messages qui leur sont envoyés (par le biais d'attentes). En posant les paramètres attendus d'une méthode ils agissent comme des gardiens : un appel sur eux doit être réalisé correctement. Si les attentes ne sont pas atteintes ils nous épargnent l'effort de l'écriture d'une assertion de test avec échec en réalisant cette tâche à notre place. Dans le cas d'une connexion à une base de données imaginaire ils peuvent tester si la requête, disons SQL, a bien été formé par l'objet qui utilise cette connexion. Mettez-les sur pied avec des attentes assez précises et vous verrez que vous n'aurez presque plus d'assertion à écrire manuellement. -

    - -

    - -

    Créer des objets fantaisie

    - -

    -

    - Comme pour la création des bouchons serveur, tout ce dont nous avons besoin c'est d'un classe existante. La fameuse connexion à une base de données qui ressemblerait à... -

    -class DatabaseConnection {
    -    function DatabaseConnection() {
    -    }
    -    
    -    function query() {
    -    }
    -    
    -    function selectQuery() {
    -    }
    -}
    -
    - Cette classe n'a pas encore besoin d'être implémentée. Pour en créer sa version fantaisie nous devons juste inclure la librairie d'objet fantaisie puis lancer le générateur... -
    -require_once('simpletest/unit_tester.php');
    -require_once('simpletest/mock_objects.php');
    -require_once('database_connection.php');
    -
    -Mock::generate('DatabaseConnection');
    -
    - Ceci génère une classe clone appelée MockDatabaseConnection. Nous pouvons désormais créer des instances de cette nouvelle classe à l'intérieur même de notre scénario de test... -
    -require_once('simpletest/unit_tester.php');
    -require_once('simpletest/mock_objects.php');
    -require_once('database_connection.php');
    -
    -Mock::generate('DatabaseConnection');
    -
    -class MyTestCase extends UnitTestCase {
    -    
    -    function testSomething() {
    -        $connection = &new MockDatabaseConnection($this);
    -    }
    -}
    -
    - Contrairement aux bouchons, le constructeur d'une classe fantaisie a besoin d'une référence au scénario de test pour pouvoir transmettre les succès et les échecs pendant qu'il vérifie les attentes. Concrètement ça veut dire que les objets fantaisie ne peuvent être utilisés qu'au sein d'un scénario de test. Malgré tout, cette puissance supplémentaire implique que les bouchons ne sont que rarement utilisés si des objets fantaisie sont disponibles. -

    -

    - -

    Objets fantaisie en action

    - -

    -

    - La version fantaisie d'une classe contient toutes les méthodes de l'originale. De la sorte une opération comme $connection->query() est encore possible. Tout comme avec les bouchons, nous pouvons remplacer la valeur nulle renvoyée par défaut... -

    -$connection->setReturnValue('query', 37);
    -
    - Désormais à chaque appel de $connection->query() nous recevons comme résultat 37. Tout comme avec les bouchons nous pouvons utiliser des jokers et surcharger le paramètre joker. Nous pouvons aussi ajouter des méthodes supplémentaires à l'objet fantaisie lors de sa génération et lui choisir un nom de classe qui lui soit propre... -
    -Mock::generate('DatabaseConnection', 'MyMockDatabaseConnection', array('setOptions'));
    -
    - Ici l'objet fantaisie se comportera comme si setOptions() existait dans la classe originale. C'est pratique si une classe a utilisé le mécanisme overload() de PHP pour ajouter des méthodes dynamiques. Vous pouvez créer des fantaisies spéciales pour simuler cette situation. -

    -

    - Tous les modèles disponibles avec les bouchons serveur le sont également avec les objets fantaisie... -

    -class Iterator {
    -    function Iterator() {
    -    }
    -    
    -    function next() {
    -    }
    -}
    -
    - Une nouvelle fois, supposons que cet itérateur ne retourne que du texte jusqu'au moment où il atteint son terme, quand il renvoie false. Nous pouvons le simuler avec... -
    -Mock::generate('Iterator');
    -
    -class IteratorTest extends UnitTestCase() {
    -    
    -    function testASequence() {
    -        $iterator = &new MockIterator($this);
    -        $iterator->setReturnValue('next', false);
    -        $iterator->setReturnValueAt(0, 'next', 'First string');
    -        $iterator->setReturnValueAt(1, 'next', 'Second string');
    -        ...
    -    }
    -}
    -
    - Au moment du premier appel à next() sur l'itérateur fantaisie il renverra tout d'abord "First string", puis ce sera au tour de "Second string" au deuxième appel et ensuite pour tout appel suivant false sera renvoyé. Ces valeurs renvoyées successivement sont prioritaires sur la valeur constante retournée. Cette dernière est un genre de valeur par défaut si vous voulez. -

    -

    - Reprenons aussi le conteneur d'information bouchonné avec des pairs clef / valeur... -

    -class Configuration {
    -    function Configuration() {
    -    }
    -    
    -    function getValue($key) {
    -    }
    -}
    -
    - Il s'agit là d'une situation classique d'utilisation d'objets fantaisie étant donné que la configuration peut varier grandement de machine à machine : ça contraint fortement la fiabilité de nos tests si nous l'utilisons directement. Le problème est que toutes les données nous parviennent à travers la méthode getValue() et que nous voulons des résultats différents pour des clefs différentes. Heureusement les objets fantaisie ont un système de filtrage... -
    -$config = &new MockConfiguration($this);
    -$config->setReturnValue('getValue', 'primary', array('db_host'));
    -$config->setReturnValue('getValue', 'admin', array('db_user'));
    -$config->setReturnValue('getValue', 'secret', array('db_password'));
    -
    - Le paramètre en plus est une liste d'arguments à faire correspondre. Dans ce cas nous essayons de faire correspondre un unique argument : en l'occurrence la clef recherchée. Maintenant que la méthode getValue() est invoquée sur l'objet fantaisie... -
    -$config->getValue('db_user')
    -
    - ...elle renverra "admin". Elle le trouve en essayant de faire correspondre les arguments entrants dans sa liste d'arguments sortants les uns après les autres jusqu'au moment où une correspondance exacte est atteinte. -

    -

    - Il y a des fois où vous souhaitez qu'un objet spécifique soit servi par la fantaisie plutôt qu'une copie. De nouveau c'est identique au mécanisme des bouchons serveur... -

    -class Thing {
    -}
    -
    -class Vector {
    -    function Vector() {
    -    }
    -    
    -    function get($index) {
    -    }
    -}
    -
    - Dans ce cas vous pouvez placer une référence dans la liste renvoyée par l'objet fantaisie... -
    -$thing = new Thing();
    -$vector = &new MockVector($this);
    -$vector->setReturnReference('get', $thing, array(12));
    -
    - Avec cet arrangement vous savez qu'à chaque appel de $vector->get(12) le même $thing sera renvoyé. -

    - -

    - -

    Objets fantaisie en critique

    - -

    -

    - Même si les bouchons serveur vous isolent du désordre du monde réel, il ne s'agit là que de la moitié du bénéfice potentiel. Vous pouvez avoir une classe de test recevant les messages ad hoc, mais est-ce que votre nouvelle classe renvoie bien les bons ? Le tester peut devenir cafouillis sans une librairie d'objets fantaisie. -

    -

    - Pour l'exemple, prenons une classe SessionPool à laquelle nous allons ajouter une fonction de log. Plutôt que de complexifier la classe originale, nous souhaitons ajouter ce comportement avec un décorateur (GOF). Pour l'instant le code de SessionPool ressemble à... -

    -class SessionPool {
    -    function SessionPool() {
    -        ...
    -    }
    -    
    -    function &findSession($cookie) {
    -        ...
    -    }
    -    ...
    -}
    -
    -class Session {
    -    ...
    -}
    -
    -
    - Alors que pour notre code de log, nous avons... -
    -
    -class Log {
    -    function Log() {
    -        ...
    -    }
    -    
    -    function message() {
    -        ...
    -    }
    -}
    -
    -class LoggingSessionPool {
    -    function LoggingSessionPool(&$session_pool, &$log) {
    -        ...
    -    }
    -    
    -    function &findSession(\$cookie) {
    -        ...
    -    }
    -    ...
    -}
    -
    - Dans tout ceci, la seule classe à tester est LoggingSessionPool. En particulier, nous voulons vérifier que la méthode findSession() est appelée avec le bon identifiant de session au sein du cookie et qu'elle renvoie bien le message "Starting session $cookie" au loggueur. -

    -

    - Bien que nous ne testions que quelques lignes de code de production, voici la liste des choses à faire dans un scénario de test conventionnel : -

      -
    1. Créer un objet de log.
    2. -
    3. Indiquer le répertoire d'écriture du fichier de log.
    4. -
    5. Modifier les droits sur le répertoire pour pouvoir y écrire le fichier.
    6. -
    7. Créer un objet SessionPool.
    8. -
    9. Lancer une session, ce qui demande probablement pas mal de choses.
    10. -
    11. Invoquer findSession().
    12. -
    13. Lire le nouvel identifiant de sessions (en espérant qu'il existe un accesseur !).
    14. -
    15. Lever une assertion de test pour vérifier que cet identifiant correspond bien au cookie.
    16. -
    17. Lire la dernière ligne du fichier de log.
    18. -
    19. Supprimer avec une (ou plusieurs) expression rationnelle les timestamps de log en trop, etc.
    20. -
    21. Vérifier que le message de session est bien dans le texte.
    22. -
    - Pas étonnant que les développeurs détestent écrire des tests quand ils sont aussi ingrats. Pour rendre les choses encore pire, à chaque fois que le format de log change ou bien que la méthode de création des sessions change, nous devons réécrire une partie des tests alors même qu'ils ne testent pas ces parties du système. Nous sommes en train de préparer le cauchemar pour les développeurs de ces autres classes. -

    -

    - A la place, voici la méthode complète pour le test avec un peu de magie via les objets fantaisie... -

    -Mock::generate('Session');
    -Mock::generate('SessionPool');
    -Mock::generate('Log');
    -
    -class LoggingSessionPoolTest extends UnitTestCase {
    -    ...
    -    function testFindSessionLogging() {
    -        $session = &new MockSession($this);
    -        $pool = &new MockSessionPool($this);
    -        $pool->setReturnReference('findSession', $session);
    -        $pool->expectOnce('findSession', array('abc'));
    -        
    -        $log = &new MockLog($this);
    -        $log->expectOnce('message', array('Starting session abc'));
    -        
    -        $logging_pool = &new LoggingSessionPool($pool, $log);
    -        $this->assertReference($logging_pool->findSession('abc'), $session);
    -        $pool->tally();
    -        $log->tally();
    -    }
    -}
    -
    - Commençons par écrire une session simulacre. Pas la peine d'être trop pointilleux avec celle-ci puisque la vérification de la session désirée est effectuée ailleurs. Nous avons juste besoin de vérifier qu'il s'agit de la même que celle qui vient du groupe commun des sessions. -

    -

    - findSession() est un méthode fabrique dont la simulation est décrite plus haut. Le point de départ vient avec le premier appel expectOnce(). Cette ligne indique qu'à chaque fois que findSession() est invoqué sur l'objet fantaisie, il vérifiera les arguments entrant. S'il ne reçoit que la chaîne "abc" en tant qu'argument alors un succès est envoyé au testeur unitaire, sinon c'est un échec qui est généré. Il s'agit là de la partie qui teste si nous avons bien la bonne session. La liste des arguments suit une format identique à celui qui précise les valeurs renvoyées. Vous pouvez avoir des jokers et des séquences et l'ordre de l'évaluation restera le même. -

    -

    - Si l'appel n'est jamais effectué alors n'est généré ni le succès, ni l'échec. Pour contourner cette limitation, nous devons dire à l'objet fantaisie que le test est terminé : il pourra alors décider si les attentes ont été répondues. L'assertion du testeur unitaire de ceci est déclenchée par l'appel tally() à la fin du test. -

    -

    - Nous utilisons le même modèle pour mettre sur pied le loggueur fantaisie. Nous lui indiquons que message() devrait être invoqué une fois et une fois seulement avec l'argument "Starting session abc". En testant les arguments d'appel, plutôt que ceux de sorite du loggueur, nous isolons le test de tout modification dans le loggueur. -

    -

    - Nous commençons le lancement nos tests à la création du nouveau LoggingSessionPool et nous l'alimentons avec nos objets fantaisie juste créés. Désormais tout est sous contrôle. Au final nous confirmons que le $session donné au décorateur est bien celui reçu et prions les objets fantaisie de lancer leurs tests de comptage d'appel interne avec les appels tally(). -

    -

    - Il y a encore pas mal de code de test, mais ce code est très strict. S'il vous semble encore terrifiant il l'est bien moins que si nous avions essayé sans les objets fantaisie et ce test en particulier, interactions plutôt que résultat, est toujours plus difficile à mettre en place. Le plus souvent vous aurez besoin de tester des situations plus complexes sans ce niveau ni cette précision. En outre une partie peut être remaniée avec la méthode de scénario de test setUp(). -

    -

    - Voici la liste complète des attentes que vous pouvez placer sur un objet fantaisie avec SimpleTest... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    AttenteNécessite tally()
    expectArguments($method, $args)Non
    expectArgumentsAt($timing, $method, $args)Non
    expectCallCount($method, $count)Oui
    expectMaximumCallCount($method, $count)Non
    expectMinimumCallCount($method, $count)Oui
    expectNever($method)Non
    expectOnce($method, $args)Oui
    expectAtLeastOnce($method, $args)Oui
    - Où les paramètres sont... -

    -
    $method
    -
    Le nom de la méthode, sous la forme d'une chaîne, à laquelle la condition doit être appliquée.
    -
    $args
    -
    - Les arguments sous la forme d'une liste. Les jokers peuvent être inclus de la même manière qu'avec setReturn(). Cet argument est optionel pour expectOnce() et expectAtLeastOnce(). -
    -
    $timing
    -
    - Le seul point dans le temps pour tester la condition. Le premier appel commence à zéro. -
    -
    $count
    -
    Le nombre d'appels attendu.
    -
    - La méthode expectMaximumCallCount() est légèrement différente dans le sens où elle ne pourra générer qu'un échec. Elle reste silencieuse si la limite n'est jamais atteinte. -

    -

    - Comme avec les assertions dans les scénarios de test, toutes ces attentes peuvent accepter une surcharge de message sous la forme d'un paramètre supplémentaire. Par ailleurs le message d'échec original peut être inclus dans le résultat avec "%s". -

    - -

    - -

    D'autres approches

    - -

    -

    - Il existe trois approches pour créer des objets fantaisie en comprenant celle utiliser par SimpleTest. Les coder à la main en utilisant une classe de base, les générer dans un fichier ou les générer dynamiquement à la volée. -

    -

    - Les objets fantaisie générés avec SimpleTest sont dynamiques. Ils sont créés à l'exécution dans la mémoire, grâce à eval(), plutôt qu'écrit dans un fichier. Cette opération les rend facile à créer, en une seule ligne, surtout par rapport à leur création à la main dans une hiérarchie de classe parallèle. Le problème avec ce comportement tient généralement dans la mise en place des tests proprement dits. Si les objets originaux changent les versions fantaisie sur lesquels reposent les tests, une désynchronisation peut subvenir. Cela peut aussi arriver avec l'approche en hiérarchie parallèle, mais c'est détecté beaucoup plus vite. -

    -

    - Bien sûr, la solution est d'ajouter de véritables tests d'intégration. Vous n'en avez pas besoin de beaucoup et le côté pratique des objets fantaisie fait plus que compenser la petite dose de test supplémentaire. Vous ne pouvez pas avoir confiance dans du code qui ne serait testé que par des objets fantaisie. -

    -

    - Si vous restez déterminé de construire des librairies statiques d'objets fantaisie parce que vous souhaitez émuler un comportement très spécifique, vous pouvez y parvenir grâce au générateur de classe de SimpleTest. Dans votre fichier librairie, par exemple mocks/connection.php pour une connexion à une base de données, créer un objet fantaisie et provoquer m'héritage pour hériter pour surcharger des méthodes spéciales ou ajouter des préréglages... -

    -<?php
    -    require_once('simpletest/mock_objects.php');
    -    require_once('../classes/connection.php');
    -
    -    Mock::generate('Connection', 'BasicMockConnection');
    -    class MockConnection extends BasicMockConnection {
    -        function MockConnection(&$test, $wildcard = '*') {
    -            $this->BasicMockConnection($test, $wildcard);
    -            $this->setReturn('query', false);
    -        }
    -    }
    -?>
    -
    - L'appel generate dit au générateur de classe d'en créer une appelée BasicMockConnection plutôt que la plus courante MockConnection. Ensuite nous héritons à partir de celle-ci pour obtenir notre version de MockConnection. En interceptant de cette manière nous pouvons ajouter un comportement, ici transformer la valeur par défaut de query() en "false". - En utilisant le nom par défaut nous garantissons que le générateur de classe fantaisie n'en recréera pas une autre différente si il est invoqué ailleurs dans les tests. Il ne créera jamais de classe si elle existe déjà. Aussi longtemps que le fichier ci-dessus est inclus avant alors tous les tests qui généraient MockConnection devraient utiliser notre version à présent. Par contre si nous avons une erreur dans l'ordre et que la librairie de fantaisie en crée une d'abord alors la création de la classe échouera tout simplement. -

    -

    - Utiliser cette astuce si vous vous trouvez avec beaucoup de comportement en commun sur les objets fantaisie ou si vous avez de fréquents problèmes d'intégration plus tard dans les étapes de test. -

    - -

    - -

    Je pense que SimpleTest pue !

    - -

    -

    - Mais au moment d'écrire ces lignes c'est le seul à gérer les objets fantaisie, donc vous êtes bloqué avec lui ? -

    -

    - Non, pas du tout. - SimpleTest est une boîte à outils et parmi ceux-ci on trouve les objets fantaisie qui peuvent être utilisés indépendamment. Supposons que vous avez votre propre testeur unitaire favori et que tous vos tests actuels l'utilisent. Prétendez que vous avez appelé votre tester unitaire PHPUnit (c'est ce que tout le monde a fait) et que la classe principale de test ressemble à... -

    -class PHPUnit {
    -    function PHPUnit() {
    -    }
    -    
    -    function assertion($message, $assertion) {
    -    }
    -    ...
    -}
    -
    - La seule chose que la méthode assertion() réalise, c'est de préparer une sortie embellie alors le paramètre boolien de l'assertion sert à déterminer s'il s'agit d'une erreur ou d'un succès. Supposons qu'elle est utilisée de la manière suivante... -
    -$unit_test = new PHPUnit();
    -$unit_test>assertion('I hope this file exists', file_exists('my_file'));
    -
    - Comment utiliser les objets fantaisie avec ceci ? -

    -

    - Il y a une méthode protégée sur la classe de base des objets fantaisie : elle s'appelle _assertTrue(). En surchargeant cette méthode nous pouvons utiliser notre propre format d'assertion. Nous commençons avec une sous-classe, dans my_mock.php... -

    -<?php
    -    require_once('simpletest/mock_objects.php');
    -    
    -    class MyMock extends SimpleMock() {
    -        function MyMock(&$test, $wildcard) {
    -            $this->SimpleMock($test, $wildcard);
    -        }
    -        
    -        function _assertTrue($assertion, $message) {
    -            $test = &$this->getTest();
    -            $test->assertion($message, $assertion);
    -        }
    -    }
    -?>
    -
    - Maintenant une instance de MyMock créera un objet qui parle le même langage que votre testeur. Bien sûr le truc c'est que nous créons jamais un tel objet : le générateur s'en chargera. Nous avons juste besoin d'une ligne de code supplémentaire pour dire au générateur d'utiliser vos nouveaux objets fantaisie... -
    -<?php
    -    require_once('simpletst/mock_objects.php');
    -    
    -    class MyMock extends SimpleMock() {
    -        function MyMock($test, $wildcard) {
    -            $this->SimpleMock(&$test, $wildcard);
    -        }
    -        
    -        function _assertTrue($assertion, $message , &$test) {
    -            $test->assertion($message, $assertion);
    -        }
    -    }
    -    SimpleTestOptions::setMockBaseClass('MyMock');
    -?>
    -
    - A partir de maintenant vous avez juste à inclure my_mock.php à la place de la version par défaut simple_mock.php et vous pouvez introduire des objets fantaisie dans votre suite de tests existants. -

    - -
    - - - diff --git a/tests/test_tools/simpletest/docs/fr/overview.html b/tests/test_tools/simpletest/docs/fr/overview.html deleted file mode 100755 index b6965753..00000000 --- a/tests/test_tools/simpletest/docs/fr/overview.html +++ /dev/null @@ -1,294 +0,0 @@ - - - - - Aperçu et liste des fonctionnalités des testeurs unitaires PHP et web de SimpleTest PHP - - - - - -

    Apercu de SimpleTest

    -
    -

    - -

    Qu'est-ce que SimpleTest ?

    - -

    -

    - Le coeur de SimpleTest est un framework de test construit autour de classes de scénarios de test. Celles-ci sont écrites comme des extensions des classes premières de scénarios de test, chacune élargie avec des méthodes qui contiennent le code de test effectif. Les scripts de test de haut niveau invoque la méthode run() à chaque scénario de test successivement. Chaque méthode de test est écrite pour appeler des assertions diverses que le développeur suppose être vraies, assertEqual() par exemple. Si l'assertion est correcte, alors un succès est expédié au rapporteur observant le test, mais toute erreur déclenche une alerte et une description de la dissension. -

    -

    - Un scénario de test ressemble à... -

    -class MyTestCase extends UnitTestCase {
    -    
    -    function testLog() {
    -        $log = &new Log('my.log');
    -        $log->message('Hello');
    -        $this->assertTrue(file_exists('my.log'));
    -    }
    -}
    -
    -

    -

    - Ces outils sont conçus pour le développeur. Les tests sont écrits en PHP directement, plus ou moins simultanément avec la construction de l'application elle-même. L'avantage d'utiliser PHP lui-même comme langage de test est qu'il n'y a pas de nouveau langage à apprendre, les tests peuvent commencer directement et le développeur peut tester n'importe quelle partie du code. Plus simplement, toutes les parties qui peuvent être accédées par le code de l'application peuvent aussi être accédées par le code de test si ils sont tous les deux dans le même langage. -

    -

    - Le type de scénario de test le plus simple est le UnitTestCase. Cette classe de scénario de test inclut les tests standards pour l'égalité, les références et l'appariement de motifs (via les expressions rationnelles). Ceux-ci testent ce que vous seriez en droit d'attendre du résultat d'une fonction ou d'une méthode. Il s'agit du type de test le plus commun pendant le quotidien du développeur, peut-être 95% des scénarios de test. -

    -

    - La tâche ultime d'une application web n'est cependant pas de produire une sortie correcte à partir de méthodes ou d'objets, mais plutôt de produire des pages web. La classe WebTestCase teste des pages web. Elle simule un navigateur web demandant une page, de façon exhaustive : cookies, proxies, connexions sécurisées, authentification, formulaires, cadres et la plupart des éléments de navigation. Avec ce type de scénario de test, le développeur peut garantir que telle ou telle information est présente dans la page et que les formulaires ainsi que les sessions sont gérés comme il faut. -

    -

    - Un scénario de test web ressemble à... -

    -class MySiteTest extends WebTestCase {
    -    
    -    function testHomePage() {
    -        $this->get('http://www.my-site.com/index.php');
    -        $this->assertTitle('My Home Page');
    -        $this->clickLink('Contact');
    -        $this->assertTitle('Contact me');
    -        $this->assertWantedPattern('/Email me at/');
    -    }
    -}
    -
    -

    - -

    - -

    Liste des fonctionnalites

    - -

    -

    - Ci-dessous vous trouverez un canevas assez brut des fonctionnalités à aujourd'hui et pour demain, sans oublier leur date approximative de publication. J'ai bien peur qu'il soit modifiable sans pré-avis étant donné que les jalons dépendent beaucoup sur le temps disponible. Les trucs en vert ont été codés, mais pas forcément déjà rendus public. Si vous avez une besoin pressant pour une fonctionnalité verte mais pas encore publique alors vous devriez retirer le code directement sur le CVS chez SourceFourge. Une fonctionnalitée publiée est indiqué par "Fini". - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    FonctionnalitéDescriptionPublication
    Scénariot de test unitaireLes classes de test et assertions de baseFini
    Affichage HTMLL'affichage le plus simple possibleFini
    Autochargement des scénarios de testLire un fichier avec des scénarios de test et les charger dans un groupe de test automatiquementFini
    Générateur de code d'objets fantaisieDes objets capable de simuler d'autres objets, supprimant les dépendances dans les testsFini
    Bouchons serveurDes objets fantaisie sans résultat attendu à utiliser à l'extérieur des scénarios de test, pour le prototypage par exemple.Fini
    Intégration d'autres testeurs unitaires - La capacité de lire et simuler d'autres scénarios de test en provenance de PHPUnit et de PEAR::Phpunit.Fini
    Scénario de test webAppariement basique de motifs dans une page téléchargée.Fini
    Analyse de page HTMLPermet de suivre les liens et de trouver la balise de titreFini
    Simulacre partielSimuler des parties d'une classe pour tester moins qu'une classe ou dans des cas complexes.Fini
    Gestion des cookies WebGestion correcte des cookies au téléchargement d'une page.Fini
    Suivi des redirectionsLe téléchargement d'une page suit automatiquement une redirection 300.Fini
    Analyse d'un formulaireLa capacité de valider un formulaire simple et d'en lire les valeurs par défaut.Fini
    Interface en ligne de commandeAffiche le résultat des tests sans navigateur web.Fini
    Mise à nu des attentes d'une classePeut créer des tests précis avec des simulacres ainsi que des scénarios de test.Fini
    Sortie et analyse XMLPermet de tester sur plusieurs hôtes et d'intégrer des extensions d'acceptation de test.Fini
    Scénario de test en ligne de commandePermet de tester des outils ou scripts en ligne de commande et de manier des fichiers.Fini
    Compatibilité avec PHP DocumentorGénération automatique et complète de la documentation au niveau des classes.Fini
    Interface navigateurMise à nu des niveaux bas de l'interface du navigateur web pour des scénarios de test plus précis.Fini
    Authentification HTTPTéléchargement des pages web protégées avec une authentification basique seulement.Fini
    Boutons de navigation d'un navigateurArrière, avant et recommencerFini
    Support de SSLPeut se connecter à des pages de type https.Fini
    Support de proxyPeut se connecter via des proxys communsFini
    Support des cadresGère les cadres dans les scénarios de test web.Fini
    Amélioration de l'affichage des testsUne meilleure interface graphique web, avec un arbre des scénarios de test.1.1
    LocalisationAbstraction des messages et génration du code à partir de fichiers XML.1.1
    Simulation d'interfacePeut générer des objets fantaisie tant vers des interfaces que vers des classes.2.0
    Test sur es exceptionsDans le même esprit que sur les tests des erreurs PHP.2.0
    Rercherche d'éléments avec XPathPeut utiliser Tidy HTML pour un appariement plus rapide et plus souple.2.0
    Test de l'upload de fichierPeut simuler la balise input de type file2.0
    - La migration vers PHP5 commencera juste après la série des 1.0, à partir de là PHP4 ne sera plus supporté. SimpleTest est actuellement compatible avec PHP5 mais n'utilisera aucune des nouvelles fonctionnalités avant la version 2. -

    - -

    - -

    Ressources sur le web pour les tests

    - -

    -

    - Le processus est au moins aussi important que les outils. Le type de procédure que fait un usage le plus intensif des outils de test pour développeur est bien sûr l'Extreme Programming. Il s'agit là d'une des méthodes agiles qui combinent plusieurs pratiques pour "lisser la courbe de coût" du développement logiciel. La plus extrème reste le développement piloté par les tests, où vous devez adhérer à la règle du pas de code avant d'avoir un test. Si vous êtes plutôt du genre planninficateur ou que vous estimez que l'expérience compte plus que l'évolution, vous préférerez peut-être l'approche RUP. Je ne l'ai pas testé mais je peux voir où vous aurez besoin d'outils de test (cf. illustration 9). -

    -

    - La plupart des testeurs unitaires sont dans une certaine mesure un clone de JUnit, au moins dans l'interface. Il y a énormément d'information sur le site de JUnit, à commencer par la FAQ quie contient pas mal de conseils généraux sur les tests. Une fois mordu par le bogue vous apprécierez sûrement la phrase infecté par les tests trouvée par Eric Gamma. Si vous êtes encore en train de tergiverser sur un testeur unitaire, sachez que les choix principaux sont PHPUnit et Pear PHP::PHPUnit. De nombreuses fonctionnalités de SimpleTest leurs font défaut, mais la version PEAR a d'ores et déjà été mise à jour pour PHP5. Elle est aussi recommandée si vous portez des scénarios de test existant depuis JUnit. -

    -

    - Les développeurs de bibliothèque n'ont pas l'air de livrer très souvent des tests avec leur code : c'est bien dommage. Le code d'une bibliothèque qui inclut des tests peut être remanié avec plus de sécurité et le code de test sert de documentation additionnelle dans un format assez standard. Ceci peut épargner la pêche aux indices dans le code source lorsque qu'un problème survient, en particulier lors de la mise à jour d'une telle bibliothèque. Parmi les bibliothèques utilisant SimpleTest comme testeur unitaire on retrouve WACT et PEAR::XML_HTMLSax. -

    -

    - Au jour d'aujourd'hui il manque tristement beaucoup de matière sur les objets fantaisie : dommage, surtout que tester unitairement sans eux représente pas mal de travail en plus. L'article original sur les objets fantaisie est très orienté Java, mais reste intéressant à lire. Etant donné qu'il s'agit d'une nouvelle technologie il y a beaucoup de discussions et de débats sur comment les utiliser, souvent sur des wikis comme Extreme Tuesday ou www.mockobjects.comou the original C2 Wiki. Injecter des objets fantaisie dans une classe est un des champs principaux du débat : cet article chez IBM en est un bon point de départ. -

    -

    - Il y a énormement d'outils de test web mais la plupart sont écrits en Java. De plus les tutoriels et autres conseils sont plutôt rares. Votre seul espoir est de regarder directement la documentation pour HTTPUnit, HTMLUnit ou JWebUnit et d'espérer y trouver pour des indices. Il y a aussi des frameworks basés sur XML, mais de nouveau la plupart ont besoin de Java pour tourner. -

    - -
    - - - diff --git a/tests/test_tools/simpletest/docs/fr/partial_mocks_documentation.html b/tests/test_tools/simpletest/docs/fr/partial_mocks_documentation.html deleted file mode 100755 index 4098ab45..00000000 --- a/tests/test_tools/simpletest/docs/fr/partial_mocks_documentation.html +++ /dev/null @@ -1,333 +0,0 @@ - - - -Documentation SimpleTest : les objets fantaisie partiels - - - - -

    Documentation sur les objets fantaisie partiels

    -
    - -

    - 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à. -

    - -

    - -

    Le problème de l'injection dans un objet fantaisie

    - -

    -

    - Quand un objet en utilise un autre il est très simple d'y faire circuler une version fantaisie déjà prête avec ses attentes. Les choses deviennent un peu plus délicates si un objet en crée un autre et que le créateur est celui que l'on souhaite tester. Cela revient à dire que l'objet créé devrait être une fantaisie, mais nous pouvons difficilement dire à notre classe sous test de créer un objet fantaisie plutôt qu'un "vrai" objet. La classe testée ne sait même pas qu'elle travaille dans un environnement de test. -

    -

    - Par exemple, supposons que nous sommes en train de construire un client telnet et qu'il a besoin de créer une socket réseau pour envoyer ses messages. La méthode de connexion pourrait ressemble à quelque chose comme... -

    -<?php
    -    require_once('socket.php');
    -    
    -    class Telnet {
    -        ...
    -        function &connect($ip, $port, $username, $password) {
    -            $socket = &new Socket($ip, $port);
    -            $socket->read( ... );
    -            ...
    -        }
    -    }
    -?>
    -
    - Nous voudrions vraiment avoir une version fantaisie de l'objet socket, que pouvons nous faire ? -

    -

    - La première solution est de passer la socket en tant que paramètre, ce qui force la création au niveau inférieur. Charger le client de cette tâche est effectivement une bonne approche si c'est possible et devrait conduire à un remaniement -- de la création à partir de l'action. En fait, c'est là une des manières avec lesquels tester en s'appuyant sur des objets fantaisie vous force à coder des solutions plus resserrées sur leur objectif. Ils améliorent votre programmation. -

    -

    - Voici ce que ça devrait être... -

    -<?php
    -    require_once('socket.php');
    -    
    -    class Telnet {
    -        ...
    -        function &connect(&$socket, $username, $password) {
    -            $socket->read( ... );
    -            ...
    -        }
    -    }
    -?>
    -
    - Sous-entendu, votre code de test est typique d'un cas de test avec un objet fantaisie. -
    -class TelnetTest extends UnitTestCase {
    -    ...
    -    function testConnection() {
    -        $socket = &new MockSocket($this);
    -        ...
    -        $telnet = &new Telnet();
    -        $telnet->connect($socket, 'Me', 'Secret');
    -        ...
    -    }
    -}
    -
    - C'est assez évident que vous ne pouvez descendre que d'un niveau. Vous ne voudriez pas que votre application de haut niveau crée tous les fichiers de bas niveau, sockets et autres connexions à la base de données dont elle aurait besoin. Elle ne connaîtrait pas les paramètres du constructeur de toute façon. -

    -

    - La solution suivante est de passer l'objet créé sous la forme d'un paramètre optionnel... -

    -<?php
    -    require_once('socket.php');
    -    
    -    class Telnet {
    -        ...
    -        function &connect($ip, $port, $username, $password, $socket = false) {
    -            if (!$socket) {
    -                $socket = &new Socket($ip, $port);
    -            }
    -            $socket->read( ... );
    -            ...
    -            return $socket;
    -        }
    -    }
    -?>
    -
    - 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... -
    -class TelnetTest extends UnitTestCase {
    -    ...
    -    function testConnection() {
    -        $socket = &new MockSocket($this);
    -        ...
    -        $telnet = &new Telnet();
    -        $telnet->connect('127.0.0.1', 21, 'Me', 'Secret', &$socket);
    -        ...
    -    }
    -}
    -
    - Le problème de cette approche tient dans son manque de netteté. Il y a du code de test dans la classe principale et aussi des paramètres transmis dans le scénario de test qui ne sont jamais utilisés. Il s'agit là d'une approche rapide et sale, mais qui ne reste pas moins efficace dans la plupart des situations. -

    -

    - Une autre solution encore est de laisser un objet fabrique s'occuper de la création... -

    -<?php
    -    require_once('socket.php');
    -    
    -    class Telnet {
    -        function Telnet(&$network) {
    -            $this->_network = &$network;
    -        }
    -        ...
    -        function &connect($ip, $port, $username, $password) {
    -            $socket = &$this->_network->createSocket($ip, $port);
    -            $socket->read( ... );
    -            ...
    -            return $socket;
    -        }
    -    }
    -?>
    -
    - 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... -
    -class TelnetTest extends UnitTestCase {
    -    ...
    -    function testConnection() {
    -        $socket = &new MockSocket($this);
    -        ...
    -        $network = &new MockNetwork($this);
    -        $network->setReturnReference('createSocket', $socket);
    -        $telnet = &new Telnet($network);
    -        $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
    -        ...
    -    }
    -}
    -
    - 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. -

    -

    - Peut-on trouver un juste milieu ? -

    - -

    - -

    Méthode fabrique protégée

    - -

    -

    - 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... -

    -<?php
    -    require_once('socket.php');
    -    
    -    class Telnet {
    -        ...
    -        function &connect($ip, $port, $username, $password) {
    -            $socket = &$this->_createSocket($ip, $port);
    -            $socket->read( ... );
    -            ...
    -        }
    -        
    -        function &_createSocket($ip, $port) {
    -            return new Socket($ip, $port);
    -        }
    -    }
    -?>
    -
    - Il s'agit là de la seule modification dans le code de l'application. -

    -

    - Pour le scénario de test, nous devons créer une sous-classe de manière à intercepter la création de la socket... -

    -class TelnetTestVersion extends Telnet {
    -    var $_mock;
    -    
    -    function TelnetTestVersion(&$mock) {
    -        $this->_mock = &$mock;
    -        $this->Telnet();
    -    }
    -    
    -    function &_createSocket() {
    -        return $this->_mock;
    -    }
    -}
    -
    - Ici j'ai déplacé la fantaisie dans le constructeur, mais un setter aurait fonctionné tout aussi bien. Notez bien que la fantaisie est placée dans une variable d'objet avant que le constructeur ne soit attaché. C'est nécessaire dans le cas où le constructeur appelle connect(). Autrement il pourrait donner un valeur nulle à partir de _createSocket(). -

    -

    - Après la réalisation de tout ce travail supplémentaire le scénario de test est assez simple. Nous avons juste besoin de tester notre nouvelle classe à la place... -

    -class TelnetTest extends UnitTestCase {
    -    ...
    -    function testConnection() {
    -        $socket = &new MockSocket($this);
    -        ...
    -        $telnet = &new TelnetTestVersion($socket);
    -        $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
    -        ...
    -    }
    -}
    -
    - 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 ? -

    - -

    - -

    Un objet fantaisie partiel

    - -

    -

    - Bien sûr la réponse est "oui" ou alors j'aurais arrêté d'écrire depuis quelques temps déjà ! Le test précédent a représenté beaucoup de travail, mais nous pouvons générer la sous-classe en utilisant une approche à celle des objets fantaisie. -

    -

    - Voici donc une version avec objet fantaisie partiel du test... -

    -Mock::generatePartial(
    -        'Telnet',
    -        'TelnetTestVersion',
    -        array('_createSocket'));
    -
    -class TelnetTest extends UnitTestCase {
    -    ...
    -    function testConnection() {
    -        $socket = &new MockSocket($this);
    -        ...
    -        $telnet = &new TelnetTestVersion($this);
    -        $telnet->setReturnReference('_createSocket', $socket);
    -        $telnet->Telnet();
    -        $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
    -        ...
    -    }
    -}
    -
    - La fantaisie partielle est une sous-classe de l'original dont on aurait "remplacé" les méthodes sélectionnées avec des versions de test. L'appel à generatePartial() nécessite trois paramètres : la classe à sous classer, le nom de la nouvelle classe et une liste des méthodes à simuler. -

    -

    - Instancier les objets qui en résultent est plutôt délicat. L'unique paramètre du constructeur d'un objet fantaisie partiel est la référence du testeur unitaire. Comme avec les objets fantaisie classiques c'est nécessaire pour l'envoi des résultats de test en réponse à la vérification des attentes. -

    -

    - Une nouvelle fois le constructeur original n'est pas lancé. Indispensable dans le cas où le constructeur aurait besoin des méthodes fantaisie : elles n'ont pas encore été initiées ! Nous initions les valeurs retournées à cet instant et ensuite lançons le constructeur avec ses paramètres normaux. Cette construction en trois étapes de "new", suivie par la mise en place des méthodes et ensuite par la lancement du constructeur proprement dit est ce qui distingue le code d'un objet fantaisie partiel. -

    -

    - A part pour leur construction, toutes ces méthodes fantaisie ont les mêmes fonctionnalités que dans le cas des objets fantaisie et toutes les méthodes non fantaisie se comportent comme avant. Nous pouvons mettre en place des attentes très facilement... -

    -class TelnetTest extends UnitTestCase {
    -    ...
    -    function testConnection() {
    -        $socket = &new MockSocket($this);
    -        ...
    -        $telnet = &new TelnetTestVersion($this);
    -        $telnet->setReturnReference('_createSocket', $socket);
    -        $telnet->expectOnce('_createSocket', array('127.0.0.1', 21));
    -        $telnet->Telnet();
    -        $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
    -        ...
    -        $telnet->tally();
    -    }
    -}
    -
    -

    - -

    - -

    Tester moins qu'une classe

    - -

    -

    - Les méthodes issues d'un objet fantaisie n'ont pas besoin d'être des méthodes fabrique, Il peut s'agir de n'importe quelle sorte de méthode. Ainsi les objets fantaisie partiels nous permettent de prendre le contrôle de n'importe quelle partie d'une classe, le constructeur excepté. Nous pourrions même aller jusqu'à créer des fantaisies sur toutes les méthode à part celle que nous voulons effectivement tester. -

    -

    - Cette situation est assez hypothétique, étant donné que je ne l'ai jamais essayée. Je suis ouvert à cette possibilité, mais je crains qu'en forçant la granularité d'un objet on n'obtienne pas forcément un code de meilleur qualité. Personnellement j'utilise les objets fantaisie partiels comme moyen de passer outre la création ou alors de temps en temps pour tester le modèle de conception TemplateMethod. -

    -

    - Pour choisir le mécanisme à utiliser, on en revient toujours aux standards de code de votre projet. -

    - -
    - - - diff --git a/tests/test_tools/simpletest/docs/fr/reporter_documentation.html b/tests/test_tools/simpletest/docs/fr/reporter_documentation.html deleted file mode 100755 index 4f927781..00000000 --- a/tests/test_tools/simpletest/docs/fr/reporter_documentation.html +++ /dev/null @@ -1,386 +0,0 @@ - - - -Documentation SimpleTest : le rapporteur de test - - - - -

    Documentation sur le rapporteur de test

    -
    - -

    - SimpleTest suit plutôt plus que moins le modèle MVC (Modèle-Vue-Contrôleur). Les classes "reporter" sont les vues et les modèles sont vos scénarios de test et leur hiérarchie. Le contrôleur est le plus souvent masqué à l'utilisateur de SimpleTest à moins de vouloir changer la façon dont les tests sont effectivement exécutés, auquel cas il est possible de surcharger les objets "runner" (ceux de l'exécuteur) depuis l'intérieur d'un scénario de test. Comme d'habitude avec MVC, le contrôleur est plutôt indéfini et il existe d'autres endroits pour contrôler l'exécution des tests. -

    - -

    - -

    Les résultats rapportés au format HTML

    - -

    -

    - L'affichage par défaut est minimal à l'extrême. Il renvoie le succès ou l'échec avec les barres conventionnelles - rouge et verte - et affichent une trace d'arborescence des groupes de test pour chaque assertion erronée. Voici un tel échec... -

    -

    File test

    - Fail: createnewfile->True assertion failed.
    -
    1/1 test cases complete. - 0 passes, 1 fails and 0 exceptions.
    -
    - Alors qu'ici tous les tests passent... -
    -

    File test

    -
    1/1 test cases complete. - 1 passes, 0 fails and 0 exceptions.
    -
    - La bonne nouvelle, c'est qu'il existe pas mal de points dans la hiérarchie de l'affichage pour créer des sous-classes. -

    -

    - Pour l'affichage basé sur des pages web, il y a la classe HtmlReporter avec la signature suivante... -

    -class HtmlReporter extends SimpleReporter {
    -    public HtmlReporter($encoding) { ... }
    -    public makeDry(boolean $is_dry) { ... }
    -    public void paintHeader(string $test_name) { ... }
    -    public void sendNoCacheHeaders() { ... }
    -    public void paintFooter(string $test_name) { ... }
    -    public void paintGroupStart(string $test_name, integer $size) { ... }
    -    public void paintGroupEnd(string $test_name) { ... }
    -    public void paintCaseStart(string $test_name) { ... }
    -    public void paintCaseEnd(string $test_name) { ... }
    -    public void paintMethodStart(string $test_name) { ... }
    -    public void paintMethodEnd(string $test_name) { ... }
    -    public void paintFail(string $message) { ... }
    -    public void paintPass(string $message) { ... }
    -    public void paintError(string $message) { ... }
    -    public void paintException(string $message) { ... }
    -    public void paintMessage(string $message) { ... }
    -    public void paintFormattedMessage(string $message) { ... }
    -    protected string _getCss() { ... }
    -    public array getTestList() { ... }
    -    public integer getPassCount() { ... }
    -    public integer getFailCount() { ... }
    -    public integer getExceptionCount() { ... }
    -    public integer getTestCaseCount() { ... }
    -    public integer getTestCaseProgress() { ... }
    -}
    -
    - Voici ce que certaines de ces méthodes veulent dire. Premièrement les méthodes d'affichage que vous voudrez probablement surcharger... -
      -
    • - HtmlReporter(string $encoding) -
      - est le constructeur. Notez que le test unitaire initie le lien à l'affichage plutôt que l'opposé. L'affichage est principalement un receveur passif des évènements de tests. Cela permet d'adapter facilement l'affichage pour d'autres systèmes en dehors des tests unitaires, tel le suivi de la charge de serveurs. L'"encoding" est le type d'encodage que vous souhaitez utiliser pour l'affichage du test. Pour pouvoir effectuer un rendu correct de la sortie de débogage quand on utilise le testeur web, il doit correspondre à l'encodage du site testé. Les chaînes de caractères disponibles sont indiquées dans la fonction PHP html_entities(). -
    • -
    • - void paintHeader(string $test_name) -
      - est appelé une fois, au début du test quand l'évènement de démarrage survient. Le premier évènement de démarrage est souvent délivré par le groupe de test du niveau le plus haut et donc c'est de là que le $test_name arrive. Il peint les titres de la page, CSS, la balise "body", etc. Il ne renvoie rien du tout (void). -
    • -
    • - void paintFooter(string $test_name) -
      - est appelé à la toute fin du test pour fermer les balises ouvertes par l'entête de la page. Par défaut il affiche aussi la barre rouge ou verte et le décompte final des résultats. En fait la fin des tests arrive quand l'évènement de fin de test arrive avec le même nom que celui qui l'a initié au même niveau. Le nid des tests en quelque sorte. Fermer le dernier test finit l'affichage. -
    • -
    • - void paintMethodStart(string $test_name) -
      - est appelé au début de chaque méthode de test. Normalement le nom vient de celui de la méthode. Les autres évènements de départ de test se comportent de la même manière sauf que celui du groupe de test indique au rapporteur le nombre de scénarios de test qu'il contient. De la sorte le rapporteur peut afficher une barre de progrès au fur et à mesure que l'exécuteur passe en revue les scénarios de test. -
    • -
    • - void paintMethodEnd(string $test_name) -
      - clôt le test lancé avec le même nom. -
    • -
    • - void paintFail(string $message) -
      - peint un échec. Par défait il ne fait qu'afficher le mot "fail", une trace d'arborescence affichant la position du test en cours et le message transmis par l'assertion. -
    • -
    • - void paintPass(string $message) -
      - ne fait rien, par défaut. -
    • -
    • - string _getCss() -
      - renvoie les styles CSS sous la forme d'une chaîne à l'attention de la méthode d'entêtes d'une page. Des styles additionnels peuvent être ajoutés ici si vous ne surchargez pas les entêtes de la page. Vous ne voudrez pas utiliser cette méthode dans des entêtes d'une page surchargée si vous souhaitez inclure le feuille de style CSS d'origine. -
    • -
    - Il y a aussi des accesseurs pour aller chercher l'information sur l'état courant de la suite de test. Vous les utiliserez pour enrichir l'affichage... -
      -
    • - array getTestList() -
      - est la première méthode très commode pour les sous-classes. Elle liste l'arborescence courante des tests sous la forme d'une liste de noms de tests. Le premier test -- celui le plus proche du coeur -- sera le premier dans la liste et la méthode de test en cours sera la dernière. -
    • -
    • - integer getPassCount() -
      - renvoie le nombre de succès atteint. Il est nécessaire pour l'affichage à la fin. -
    • -
    • - integer getFailCount() -
      - renvoie de la même manière le nombre d'échecs. -
    • -
    • - integer getExceptionCount() -
      - renvoie quant à lui le nombre d'erreurs. -
    • -
    • - integer getTestCaseCount() -
      - est le nombre total de scénarios lors de l'exécution des tests. Il comprend aussi les tests groupés. -
    • -
    • - integer getTestCaseProgress() -
      - est le nombre de scénarios réalisés jusqu'à présent. -
    • -
    - Une modification simple : demander à l'HtmlReporter d'afficher aussi bien les succès que les échecs et les erreurs... -
    -class ShowPasses extends HtmlReporter {
    -    
    -    function paintPass($message) {
    -        parent::paintPass($message);
    -        print "&<span class=\"pass\">Pass</span>: ";
    -        $breadcrumb = $this->getTestList();
    -        array_shift($breadcrumb);
    -        print implode("-&gt;", $breadcrumb);
    -        print "-&gt;$message<br />\n";
    -    }
    -    
    -    function _getCss() {
    -        return parent::_getCss() . ' .pass { color: green; }';
    -    }
    -}
    -
    -

    -

    - Une méthode qui a beaucoup fait jaser reste la méthode makeDry(). Si vous lancez cette méthode, sans paramètre, sur le rapporteur avant que la suite de test ne soit exécutée alors aucune méthode de test ne sera appelée. Vous continuerez à avoir les évènements entrants et sortants des méthodes et scénarios de test, mais aucun succès ni échec ou erreur, parce que le code de test ne sera pas exécuté. -

    -

    - La raison ? Pour permettre un affichage complexe d'une IHM (ou GUI) qui permettrait la sélection de scénarios de test individuels. Afin de construire une liste de tests possibles, ils ont besoin d'un rapport sur la structure du test pour, par exemple, l'affichage un vue en arbre de la suite de test. Avec un rapporteur lancé sur une exécution sèche qui ne renverrait que les évènements d'affichage, cela devient facilement réalisable. -

    - -

    - -

    Etendre le rapporteur

    - -

    -

    - Plutôt que de modifier l'affichage existant, vous voudrez peut-être produire une présentation HTML complètement différente, ou même générer une version texte ou XML. Plutôt que de surcharger chaque méthode dans HtmlReporter nous pouvons nous rendre une étape plus haut dans la hiérarchie de classe vers SimpleReporter dans le fichier source simple_test.php. -

    -

    - Un affichage sans rien, un canvas vierge pour votre propre création, serait... -

    -require_once('simpletest/simple_test.php');
    -
    -class MyDisplay extends SimpleReporter {
    -    
    -    function paintHeader($test_name) {
    -    }
    -    
    -    function paintFooter($test_name) {
    -    }
    -    
    -    function paintStart($test_name, $size) {
    -        parent::paintStart($test_name, $size);
    -    }
    -    
    -    function paintEnd($test_name, $size) {
    -        parent::paintEnd($test_name, $size);
    -    }
    -    
    -    function paintPass($message) {
    -        parent::paintPass($message);
    -    }
    -    
    -    function paintFail($message) {
    -        parent::paintFail($message);
    -    }
    -}
    -
    - Aucune sortie ne viendrait de cette classe jusqu'à un ajout de votre part. -

    - -

    - -

    Le rapporteur en ligne de commande

    - -

    -

    - SimpleTest est aussi livré avec un rapporteur en ligne de commande, minime lui aussi. L'interface imite celle de JUnit, sauf qu'elle envoie les messages d'erreur au fur et à mesure de leur arrivée. Pour utiliser le rapporteur en ligne de commande, il suffit de l'intervertir avec celui de la version HTML... -

    -<?php
    -    require_once('simpletest/unit_tester.php');
    -    require_once('simpletest/reporter.php');
    -
    -    $test = &new GroupTest('File test');
    -    $test->addTestFile('tests/file_test.php');
    -    $test->run(new TextReporter());
    -?>
    -
    - Et ensuite d'invoquer la suite de test à partir d'une ligne de commande... -
    -php file_test.php
    -
    - Bien sûr vous aurez besoin d'installer PHP en ligne de commande. Une suite de test qui passerait toutes ses assertions ressemble à... -
    -File test
    -OK
    -Test cases run: 1/1, Failures: 0, Exceptions: 0
    -
    - Un échec déclenche un affichage comme... -
    -File test
    -1) True assertion failed.
    -	in createnewfile
    -FAILURES!!!
    -Test cases run: 1/1, Failures: 1, Exceptions: 0
    -
    -

    -

    - Une des principales raisons pour utiliser une suite de test en ligne de commande tient dans l'utilisation possible du testeur avec un processus automatisé. Pour fonctionner comme il faut dans des scripts shell le script de test devrait renvoyer un code de sortie non-nul suite à un échec. Si une suite de test échoue la valeur false est renvoyée par la méthode SimpleTest::run(). Nous pouvons utiliser ce résultat pour terminer le script avec la bonne valeur renvoyée... -

    -<?php
    -    require_once('simpletest/unit_tester.php');
    -    require_once('simpletest/reporter.php');
    -
    -    $test = &new GroupTest('File test');
    -    $test->addTestFile('tests/file_test.php');
    -    exit ($test->run(new TextReporter()) ? 0 : 1);
    -?>
    -
    - Bien sûr l'objectif n'est pas de créer deux scripts de test, l'un en ligne de commande et l'autre pour un navigateur web, pour chaque suite de test. Le rapporteur en ligne de commande inclut une méthode pour déterminer l'environnement d'exécution... -
    -<?php
    -    require_once('simpletest/unit_tester.php');
    -    require_once('simpletest/reporter.php');
    -
    -    $test = &new GroupTest('File test');
    -    $test->addTestFile('tests/file_test.php');
    -    if (TextReporter::inCli()) {
    -        exit ($test->run(new TextReporter()) ? 0 : 1);
    -    }
    -    $test->run(new HtmlReporter());
    -?>
    -
    - Il s'agit là de la forme utilisée par SimpleTest lui-même. -

    - -

    - -

    Test distant

    - -

    -

    - SimpleTest est livré avec une classe XmlReporter utilisée pour de la communication interne. Lors de son exécution, le résultat ressemble à... -

    -<?xml version="1.0"?>
    -<run>
    -  <group size="4">
    -    <name>Remote tests</name>
    -    <group size="4">
    -      <name>Visual test with 48 passes, 48 fails and 4 exceptions</name>
    -      <case>
    -        <name>testofunittestcaseoutput</name>
    -        <test>
    -          <name>testofresults</name>
    -          <pass>This assertion passed</pass>
    -          <fail>This assertion failed</fail>
    -        </test>
    -        <test>
    -          ...
    -        </test>
    -      </case>
    -    </group>
    -  </group>
    -</run>
    -
    - Vous pouvez utiliser ce format avec le parseur fourni dans SimpleTest lui-même. Il s'agit de SimpleTestXmlParser et se trouve xml.php à l'intérieur du paquet SimpleTest... -
    -<?php
    -    require_once('simpletest/xml.php');
    -    
    -    ...
    -    $parser = &new SimpleTestXmlParser(new HtmlReporter());
    -    $parser->parse($test_output);
    -?>
    -
    - $test_output devrait être au format XML, à partir du rapporteur XML, et pourrait venir d'une exécution en ligne de commande d'un scénario de test. Le parseur envoie des évènements au rapporteur exactement comme tout autre exécution de test. Il y a des occasions bizarres dans lesquelles c'est en fait très utile. -

    -

    - Un problème des suites de test très grandes, c'est qu'elles peuvent venir à bout de la limite de mémoire par défaut d'un process PHP - 8Mb. En plaçant la sortie des groupes de test dans du XML et leur exécution dans des process différents, le résultat peut être parser à nouveau pour agrégrer les résultats avec moins d'impact sur le test au premier niveau. -

    -

    - Parce que la sortie XML peut venir de n'importe où, ça ouvre des possibilités d'agrégation d'exécutions de test depuis des serveur distants. Un scénario de test pour le réaliser existe déjà à l'intérieur du framework SimpleTest, mais il est encore expérimental... -

    -<?php
    -    require_once('../remote.php');
    -    require_once('../reporter.php');
    -    
    -    $test_url = ...;
    -    $dry_url = ...;
    -    
    -    $test = &new GroupTest('Remote tests');
    -    $test->addTestCase(new RemoteTestCase($test_url, $dry_url));
    -    $test->run(new HtmlReporter());
    -?>
    -
    - RemoteTestCase prend la localisation réelle du lanceur de test, tout simplement un page web au format XML. Il prend aussi l'URL d'un rapporteur initié pour effectuer une exécution sèche. Cette technique est employée pour que les progrès soient correctement rapportés vers le haut. RemoteTestCase peut être ajouté à une suite de test comme n'importe quel autre groupe de test. -

    - -
    - - - diff --git a/tests/test_tools/simpletest/docs/fr/server_stubs_documentation.html b/tests/test_tools/simpletest/docs/fr/server_stubs_documentation.html deleted file mode 100755 index 59085795..00000000 --- a/tests/test_tools/simpletest/docs/fr/server_stubs_documentation.html +++ /dev/null @@ -1,279 +0,0 @@ - - - -Documentation SimpleTest : les bouchons serveur - - - - -

    Documentation sur les bouchons serveur

    -
    -

    - -

    Que sont les bouchons serveur ?

    - -

    -

    - Au départ il s'agit d'un modèle de conception initié par Robert Binder (Testing object-oriented systems: models, patterns, and tools, Addison-Wesley) in 1999. Un bouchon serveur est une simulation d'un objet ou d'un composant. Il doit remplacer exactement un composant dans un système pour des raisons de testabilité ou de prototypage, tout en restant léger. Il permet aux tests de tourner plus rapidement ou alors, si la classe simulée n'a pas été écrite, juste de fonctionner. -

    - -

    - -

    Créer des bouchons serveur

    - -

    -

    - Nous avons juste besoin d'une classe préexistante, par exemple une connexion vers une base de données qui ressemblerait à... -

    -class DatabaseConnection {
    -    function DatabaseConnection() {
    -    }
    -    
    -    function query() {
    -    }
    -    
    -    function selectQuery() {
    -    }
    -}
    -
    - La classe n'a même pas encore besoin d'avoir été implémentée. Pour créer la version bouchonnée de cette classe, nous incluons la librairie de bouchon serveur et exécutons le générateur... -
    -require_once('simpletest/mock_objects.php');
    -require_once('database_connection.php');
    -Stub::generate('DatabaseConnection');
    -
    - Est généré un clone de la classe appelé StubDatabaseConnection. Nous pouvons alors créer des instances de cette nouvelle classe à l'intérieur de notre prototype de script... -
    -require_once('simpletest/mock_objects.php');
    -require_once('database_connection.php');
    -Stub::generate('DatabaseConnection');
    -
    -$connection = new StubDatabaseConnection();
    -
    -
    - La version bouchonnée de la classe contient toutes les méthodes de l'original de telle sorte qu'une opération comme $connection->query() soit encore légale. La valeur retournée sera null, Mais nous pouvons y remédier avec... -
    -$connection->setReturnValue('query', 37)
    -
    - Désormais à chaque appel de $connection->query() nous obtenons un résultat de 37. Nous pouvons choisir n'importe quelle valeur pour le résultat, par exemple un hash de résultats provenant d'un base de données imaginaire ou alors une liste d'objets persistants. Peu importe les paramètres, nous obtenons systématiquement les même valeurs chaque fois qu'ils ont été initialisés de la sorte : ça ne ressemble peut-être pas à une réponse convaincante venant d'une connexion vers une base de données. Mais pour la demi-douzaine de lignes d'une méthode de test c'est souvent largement suffisant. -

    - -

    - -

    Modèles de simulation

    - -

    -

    - Sauf que les choses ne sont que rarement aussi simples. Parmi les problèmes les plus courants on trouve les itérateurs : le renvoi d'une valeur constante peut causer une boucle infini dans l'objet testé. Pour ceux-ci nous avons besoin de mettre sur pied une suite de valeurs. Prenons par exemple un itérateur simple qui ressemble à... -

    -class Iterator {
    -    function Iterator() {
    -    }
    -    
    -    function next() {
    -    }
    -}
    -
    - C'est probablement le plus simple des itérateurs possibles. Supposons que cet itérateur ne retourne que du texte, jusqu'à la fin - quand il retourne false. Une simulation est possible avec... -
    -Stub::generate('Iterator');
    -
    -$iterator = new StubIterator();
    -$iterator->setReturnValue('next', false);
    -$iterator->setReturnValueAt(0, 'next', 'First string');
    -$iterator->setReturnValueAt(1, 'next', 'Second string');
    -
    - A l'appel de next() sur l'itérateur bouchonné il va d'abord renvoyer "First string", puis au second appel c'est "Second string" qui sera renvoyé. Finalement pour tous les autres appels, il s'agira d'un false. Les valeurs renvoyées successivement ont priorité sur la valeur constante renvoyé. Cette dernière est un genre de valeur par défaut. -

    -

    - Une autre situation délicate est une opération get() surchargée. Un exemple ? Un porteur d'information avec des pairs de clef / valeur. Prenons une classe de configuration... -

    -class Configuration {
    -    function Configuration() {
    -    }
    -    
    -    function getValue($key) {
    -    }
    -}
    -
    - Il s'agit d'une situation propice à l'utilisation d'objets bouchon, surtout que la configuration en production dépend invariablement de la machine : l'utiliser directement ne va pas nous aider à maintenir notre confiance dans nos tests. Sauf que le problème tient de ce que toutes les données proviennent de la méthode getValue() et que nous voulons des résultats différents suivant la clef. Par chance les bouchons ont un système de filtre... -
    -Stub::generate('Configuration');
    -
    -$config = &new StubConfiguration();
    -$config->setReturnValue('getValue', 'primary', array('db_host'));
    -$config->setReturnValue('getValue', 'admin', array('db_user'));
    -$config->setReturnValue('getValue', 'secret', array('db_password'));
    -
    - Ce paramètre supplémentaire est une liste d'arguments que l'on peut utiliser. Dans ce cas nous essayons d'utiliser un unique argument, à savoir la clef recherchée. Maintenant quand on invoque le bouchon serveur via la méthode getValue() avec... -
    -$config->getValue('db_user');
    -
    - ...il renvoie "admin". Il le trouve en essayant d'assortir successivement les arguments d'entrée avec sa liste de ceux de sortie jusqu'au moment où une correspondance exacte est trouvée. -

    -

    - Vous pouvez définir un argument par défaut avec... -

    -
    -$config->setReturnValue('getValue', false, array('*'));
    -
    - Attention ce n'est pas équivalent à initialiser la valeur retournée sans aucun argument. -
    -
    -$config->setReturnValue('getValue', false);
    -
    - Dans le premier cas il acceptera n'importe quel argument, mais exactement un -- pas plus -- est nécessaire. Dans le second cas n'importe quel nombre d'arguments fera l'affaire : il agit comme un catchall après tous les correspondances. Prenez garde à l'ordre : si nous ajoutons un autre paramètre après le joker ('*') il sera ignoré puisque le joker aura été trouvé auparavant. Avec des listes de paramètres complexes l'ordre peut devenir crucial, au risque de perdre des correspondances souhaitées, masquées par un joker antérieur. Pensez à mettre d'abord les cas les plus spécifiques si vous n'êtes pas sûr. -

    -

    - Il y a des fois où l'on souhaite qu'un objet spécifique soit servi par le bouchon plutôt qu'une simple copie. La sémantique de la copie en PHP nous force à utiliser une autre méthode pour cela. Vous êtes peut-être en train de simuler un conteneur par exemple... -

    -class Thing {
    -}
    -
    -class Vector {
    -    function Vector() {
    -    }
    -    
    -    function get($index) {
    -    }
    -}
    -
    - Dans ce cas vous pouvez mettre une référence dans la liste renvoyée par le bouchon... -
    -Stub::generate('Vector');
    -
    -$thing = new Thing();
    -$vector = &new StubVector();
    -$vector->setReturnReference('get', $thing, array(12));
    -
    - Avec ce petit arrangement vous vous assurez qu'à chaque fois que $vector->get(12) est appelé il renverra le même $thing. -

    -

    - Ces trois facteurs, ordre, paramètres et copie (ou référence), peuvent être combinés orthogonalement. Par exemple... -

    -$complex = &new StubComplexThing();
    -$stuff = new Stuff();
    -$complex->setReturnReferenceAt(3, 'get', $stuff, array('*', 1));
    -
    - Le $stuff ne sera renvoyé qu'au troisième appel et seulement si deux paramètres étaient indiqués, avec la contrainte que le second de ceux-ci soit l'entier 1. N'est-ce pas suffisant pour des situations de prototypage simple ? -

    -

    - Un dernier cas critique reste celle d'un objet en créant un autre, connu sous le nom du modèle factory - fabrique. Supposons qu'après une requête réussie à notre base de données imaginaire, un ensemble de résultats est retourné sous la forme d'un itérateur, chaque appel à next() donnant un ligne et à la fin un false. - Au premier abord, ça donne l'impression d'être cauchemardesque à simuler. Alors qu'en fait tout peut être bouchonné en utilisant les mécanismes ci-dessus. -

    -

    - Voici comment... -

    -Stub::generate('DatabaseConnection');
    -Stub::generate('ResultIterator');
    -
    -class DatabaseTest extends UnitTestCase {
    -    
    -    function testUserFinder() {
    -        $result = &new StubResultIterator();
    -        $result->setReturnValue('next', false);
    -        $result->setReturnValueAt(0, 'next', array(1, 'tom'));
    -        $result->setReturnValueAt(1, 'next', array(3, 'dick'));
    -        $result->setReturnValueAt(2, 'next', array(6, 'harry'));
    -        
    -        $connection = &new StubDatabaseConnection();
    -        $connection->setReturnValue('query', false);
    -        $connection->setReturnReference(
    -                'query',
    -                $result,
    -                array('select id, name from users'));
    -                
    -        $finder = &new UserFinder($connection);
    -        $this->assertIdentical(
    -                $finder->findNames(),
    -                array('tom', 'dick', 'harry'));
    -    }
    -}
    -
    - Désormais ce n'est que si notre $connection est appelé avec la bonne query() que le $result sera renvoyé après le troisième appel à next(). Cela devrait être suffisant pour que notre classe UserFinder, la classe effectivement testée à ce niveau, puisse s'exécuter comme il faut. Un test très précis et pas une seule base de données à l'horizon. -

    - -

    - -

    Options de création pour les bouchons

    - -

    -

    - Il y a d'autres options additionnelles à la création d'un bouchon. Au moment de la génération nous pouvons changer le nom de la classe... -

    -Stub::generate('Iterator', 'MyStubIterator');
    -$iterator = &new MyStubIterator();
    -
    -
    - Pris tout seul ce n'est pas très utile étant donné qu'il n'y aurait pas de différence entre cette classe et celle par défaut -- à part le nom bien entendu. Par contre nous pouvons aussi lui ajouter d'autres méthodes qui ne se trouveraient pas dans l'interface originale... -
    -class Iterator {
    -}
    -Stub::generate('Iterator', 'PrototypeIterator', array('next', 'isError'));
    -$iterator = &new PrototypeIterator();
    -$iterator->setReturnValue('next', 0);
    -
    -
    - Les méthodes next() et isError() peuvent maintenant renvoyer des ensembles de valeurs exactement comme si elles existaient dans la classe originale. -

    -

    - Un moyen encore plus ésotérique de modifier les bouchons est de changer le joker utiliser par défaut pour la correspondance des paramètres. -

    -Stub::generate('Connection');
    -$iterator = &new StubConnection('wild');
    -$iterator->setReturnValue('query', array('id' => 33), array('wild'));
    -
    -
    - L'unique raison valable pour effectuer cette opération, c'est quand vous souhaitez tester la chaîne "*" sans pour autant l'interpréter comme un "n'importe lequel". -

    - -
    - - - diff --git a/tests/test_tools/simpletest/docs/fr/unit_test_documentation.html b/tests/test_tools/simpletest/docs/fr/unit_test_documentation.html deleted file mode 100755 index 3dcfeca5..00000000 --- a/tests/test_tools/simpletest/docs/fr/unit_test_documentation.html +++ /dev/null @@ -1,306 +0,0 @@ - - - -Documenation SimpleTest pour les tests de régression en PHP - - - - -

    Documentation sur les tests unitaires en PHP

    -
    -

    - -

    Scénarios de tests unitaires

    - -

    -

    - Le coeur du système est un framework de test de régression construit autour des scénarios de test. Un exemple de scénario de test ressemble à... -

    -class FileTestCase extends UnitTestCase {
    -}
    -
    - Si aucun nom de test n'est fourni au moment de la liaison avec le constructeur alors le nom de la classe sera utilisé. Il s'agit du nom qui sera affiché dans les résultats du test. -

    -

    - Les véritables tests sont ajoutés en tant que méthode dans le scénario de test dont le nom par défaut commence par la chaîne "test" et quand le scénario de test est appelé toutes les méthodes de ce type sont exécutées dans l'ordre utilisé par l'introspection de PHP pour les trouver. Peuvent être ajoutées autant de méthodes de test que nécessaires. Par exemple... -

    -require_once('../classes/writer.php');
    -
    -class FileTestCase extends UnitTestCase {
    -    function FileTestCase() {
    -        $this->UnitTestCase('File test');
    -    }
    -    
    -    function setUp() {
    -        @unlink('../temp/test.txt');
    -    }
    -    
    -    function tearDown() {
    -        @unlink('../temp/test.txt');
    -    }
    -    
    -    function testCreation() {
    -        $writer = &new FileWriter('../temp/test.txt');
    -        $writer->write('Hello');
    -        $this->assertTrue(file_exists('../temp/test.txt'), 'File created');
    -    }
    -}
    -
    - Le constructeur est optionnel et souvent omis. Sans nom, le nom de la classe est utilisé comme nom pour le scénario de test. -

    -

    - Notre unique méthode de test pour le moment est testCreation() où nous vérifions qu'un fichier a bien été créé par notre objet Writer. Nous pourrions avoir mis le code unlink() dans cette méthode, mais en la plaçant dans setUp() et tearDown() nous pouvons l'utiliser pour nos autres méthodes de test que nous ajouterons. -

    -

    - La méthode setUp() est lancé juste avant chaque méthode de test. tearDown() est lancé après chaque méthode de test. -

    -

    - Vous pouvez placer une initialisation de scénario de test dans le constructeur afin qu'elle soit lancée pour toutes les méthodes dans le scénario de test mais dans un tel cas vous vous exposeriez à des interférences. Cette façon de faire est légèrement moins rapide, mais elle est plus sûre. Notez que si vous arrivez avec des notions de JUnit, il ne s'agit pas du comportement auquel vous êtes habitués. Bizarrement JUnit re-instancie le scénario de test pour chaque méthode de test pour se prévenir d'une telle interférence. SimpleTest demande à l'utilisateur final d'utiliser setUp(), mais fournit aux codeurs de bibliothèque d'autres crochets. -

    -

    - Pour rapporter les résultats de test, le passage par une classe d'affichage - notifiée par les différentes méthodes de type assert...() - est utilisée. En voici la liste complète pour la classe UnitTestCase, celle par défaut dans SimpleTest... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    assertTrue($x)Echoue si $x est faux
    assertFalse($x)Echoue si $x est vrai
    assertNull($x)Echoue si $x est initialisé
    assertNotNull($x)Echoue si $x n'est pas initialisé
    assertIsA($x, $t)Echoue si $x n'est pas de la classe ou du type $t
    assertEqual($x, $y)Echoue si $x == $y est faux
    assertNotEqual($x, $y)Echoue si $x == $y est vrai
    assertIdentical($x, $y)Echoue si $x === $y est faux
    assertNotIdentical($x, $y)Echoue si $x === $y est vrai
    assertReference($x, $y)Echoue sauf si $x et $y sont la même variable
    assertCopy($x, $y)Echoue si $x et $y sont la même variable
    assertWantedPattern($p, $x)Echoue sauf si l'expression rationnelle $p capture $x
    assertNoUnwantedPattern($p, $x)Echoue si l'expression rationnelle $p capture $x
    assertNoErrors()Echoue si une erreur PHP arrive
    assertError($x)Echoue si aucune erreur ou message incorrect de PHP n'arrive
    - Toutes les méthodes d'assertion peuvent recevoir une description optionnelle : cette description sert pour étiqueter le résultat. - Sans elle, une message par défaut est envoyée à la place : il est généralement suffisant. Ce message par défaut peut encore être encadré dans votre propre message si vous incluez "%s" dans la chaîne. Toutes les assertions renvoient vrai / true en cas de succès et faux / false en cas d'échec. -

    -

    - D'autres exemples... -

    -$variable = null;
    -$this->assertNull($variable, 'Should be cleared');
    -
    - ...passera et normalement n'affichera aucun message. Si vous avez configuré le testeur pour afficher aussi les succès alors le message sera affiché comme tel. -
    -$this->assertIdentical(0, false, 'Zero is not false [%s]');
    -
    - Ceci échouera étant donné qu'il effectue une vérification sur le type en plus d'une comparaison sur les deux valeurs. La partie "%s" est remplacée par le message d'erreur par défaut qui aurait été affiché si nous n'avions pas fourni le nôtre. Cela nous permet d'emboîter les messages de test. -
    -$a = 1;
    -$b = $a;
    -$this->assertReference($a, $b);
    -
    - Échouera étant donné que la variable $b est une copie de $a. -
    -$this->assertWantedPattern('/hello/i', 'Hello world');
    -
    - Là, ça passe puisque la recherche est insensible à la casse et que donc hello est bien repérable dans Hello world. -
    -trigger_error('Disaster');
    -trigger_error('Catastrophe');
    -$this->assertError();
    -$this->assertError('Catastrophe');
    -$this->assertNoErrors();
    -
    - Ici, il y a besoin d'une petite explication : toutes passent ! -

    -

    - Les erreurs PHP dans SimpleTest sont piégées et placées dans une queue. Ici la première vérification d'erreur attrape le message "Disaster" sans vérifier le texte et passe. Résultat : l'erreur est supprimée de la queue. La vérification suivante teste non seulement l'existence de l'erreur mais aussi le texte qui correspond : un autre succès. Désormais la queue est vide et le dernier test passe aussi. Si une autre erreur non vérifiée est encore dans la queue à la fin de notre méthode de test alors une exception sera rapportée dans le test. Notez que SimpleTest ne peut pas attraper les erreurs PHP à la compilation. -

    -

    - Les scénarios de test peuvent utiliser des méthodes bien pratiques pour déboguer le code ou pour étendre la suite... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    setUp()Est lancée avant chaque méthode de test
    tearDown()Est lancée après chaque méthode de test
    pass()Envoie un succès
    fail()Envoie un échec
    error()Envoi un évènement exception
    sendMessage()Envoie un message d'état aux systèmes d'affichage qui le supporte
    signal($type, $payload)Envoie un message défini par l'utilisateur au rapporteur du test
    dump($var)Effectue un print_r() formaté pour du déboguage rapide et grossier
    swallowErrors()Vide les erreurs de la queue
    -

    - -

    - -

    Etendre les scénarios de test

    - -

    -

    - 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... -

    -require_once('simpletest/unit_tester.php');
    -
    -class FileTester extends UnitTestCase {
    -    function FileTester($name = false) {
    -        $this->UnitTestCase($name);
    -    }
    -    
    -    function assertFileExists($filename, $message = '%s') {
    -        $this->assertTrue(
    -                file_exists($filename),
    -                sprintf($message, 'File [$filename] existence check'));
    -    }
    -}
    -
    - Ici la bibliothèque SimpleTest est localisée dans un répertoire local appelé simpletest. Pensez à le modifier pour votre propre environnement. -

    -

    - Ce nouveau scénario peut être hérité exactement comme un scénario de test classique... -

    -class FileTestCase extends FileTester {
    -    
    -    function setUp() {
    -        @unlink('../temp/test.txt');
    -    }
    -    
    -    function tearDown() {
    -        @unlink('../temp/test.txt');
    -    }
    -    
    -    function testCreation() {
    -        $writer = &new FileWriter('../temp/test.txt');
    -        $writer->write('Hello');
    -        $this->assertFileExists('../temp/test.txt');
    -    }
    -}
    -
    -

    -

    - Si vous souhaitez un scénario de test sans toutes les assertions de UnitTestCase mais uniquement avec les vôtres propres, vous aurez besoin d'étendre la classe SimpleTestCase à la place. Elle se trouve dans simple_test.php en lieu et place de unit_tester.php. A consulter plus tard si vous souhaitez incorporer les scénarios d'autres testeurs unitaires dans votre suite de test. -

    - -

    - -

    Lancer un unique scénario de test

    - -

    -

    - Ce n'est pas souvent qu'il faille lancer des scénarios avec un unique test. Sauf lorsqu'il s'agit de s'arracher les cheveux sur un module à problème sans pour autant désorganiser la suite de test principale. Voici l'échafaudage nécessaire pour lancer un scénario de test solitaire... -

    -<?php
    -    require_once('simpletest/unit_tester.php');
    -    require_once('simpletest/reporter.php');
    -    require_once('../classes/writer.php');
    -
    -    class FileTestCase extends UnitTestCase {
    -        function FileTestCase() {
    -            $this->UnitTestCase('File test');
    -        }
    -    }
    -    
    -    $test = &new FileTestCase();
    -    $test->run(new HtmlReporter());
    -?>
    -
    - 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. -

    - -
    - - - diff --git a/tests/test_tools/simpletest/docs/fr/web_tester_documentation.html b/tests/test_tools/simpletest/docs/fr/web_tester_documentation.html deleted file mode 100755 index 86044e5e..00000000 --- a/tests/test_tools/simpletest/docs/fr/web_tester_documentation.html +++ /dev/null @@ -1,397 +0,0 @@ - - - -Documentation SimpleTest : tester des scripts web - - - - -

    Documentation sur le testeur web

    -
    -

    - -

    Télécharger une page

    - -

    -

    - Tester des classes c'es très bien. Reste que PHP est avant tout un langage pour créer des fonctionnalités à l'intérieur de pages web. Comment pouvons tester la partie de devant -- celle de l'interface -- dans nos applications en PHP ? Etant donné qu'une page web n'est constituée que de texte, nous devrions pouvoir les examiner exactement comme n'importe quelle autre donnée de test. -

    -

    - Cela nous amène à une situation délicate. Si nous testons dans un niveau trop bas, vérifier des balises avec un motif ad hoc par exemple, nos tests seront trop fragiles. Le moindre changement dans la présentation pourrait casser un grand nombre de test. Si nos tests sont situés trop haut, en utilisant une version fantaisie du moteur de template pour donner un cas précis, alors nous perdons complètement la capacité à automatiser certaines classes de test. Par exemple, l'interaction entre des formulaires et la navigation devra être testé manuellement. Ces types de test sont extrêmement fastidieux et plutôt sensibles aux erreurs. -

    -

    - SimpleTest comprend une forme spéciale de scénario de test pour tester les actions d'une page web. WebTestCase inclut des facilités pour la navigation, des vérifications sur le contenu et les cookies ainsi que la gestion des formulaires. Utiliser ces scénarios de test ressemble fortement à UnitTestCase... -

    -class TestOfLastcraft extends WebTestCase {
    -}
    -
    - Ici nous sommes sur le point de tester le site de Last Craft. Si ce scénario de test est situé dans un fichier appelé lastcraft_test.php alors il peut être chargé dans un script de lancement tout comme des tests unitaires... -
    -<?php
    -    require_once('simpletest/web_tester.php');
    -    require_once('simpletest/reporter.php');
    -    
    -    $test = &new GroupTest('Web site tests');
    -    $test->addTestFile('lastcraft_test.php');
    -    exit ($test->run(new TextReporter()) ? 0 : 1);
    -?>
    -
    - J'utilise ici le rapporteur en mode texte pour mieux distinguer le contenu au format HTML du résultat du test proprement dit. -

    -

    - Rien n'est encore testé. Nous pouvons télécharger la page d'accueil en utilisant la méthode get()... -

    -class TestOfLastcraft extends WebTestCase {
    -    
    -    function testHomepage() {
    -        $this->assertTrue($this->get('http://www.lastcraft.com/'));
    -    }
    -}
    -
    - La méthode get() renverra "true" uniquement si le contenu de la page a bien été téléchargé. C'est un moyen simple, mais efficace pour vérifier qu'une page web a bien été délivré par le serveur web. Cependant le contenu peut révéler être une erreur 404 et dans ce cas notre méthode get() renverrait encore un succès. -

    -

    - En supposant que le serveur web pour le site Last Craft soit opérationnel (malheureusement ce n'est pas toujours le cas), nous devrions voir... -

    -Web site tests
    -OK
    -Test cases run: 1/1, Failures: 0, Exceptions: 0
    -
    - 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. -

    - -

    - -

    Tester le contenu d'une page

    - -

    -

    - Pour obtenir la confirmation que la page téléchargée est bien celle que nous attendions, nous devons vérifier son contenu. -

    -class TestOfLastcraft extends WebTestCase {
    -    
    -    function testHomepage() {
    -        $this->get('http://www.lastcraft.com/');
    -        $this->assertWantedPattern('/why the last craft/i');
    -    }
    -}
    -
    - La page obtenue par le dernier téléchargement est placée dans un buffer au sein même du scénario de test. Il n'est donc pas nécessaire de s'y référer directement. La correspondance du motif est toujours effectuée par rapport à ce buffer. -

    -

    - Voici une liste possible d'assertions sur le contenu... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    assertWantedPattern($pattern)Vérifier une correspondance sur le contenu via une expression rationnelle Perl
    assertNoUnwantedPattern($pattern)Une expression rationnelle Perl pour vérifier une absence
    assertTitle($title)Passe si le titre de la page correspond exactement
    assertLink($label)Passe si un lien avec ce texte est présent
    assertNoLink($label)Passe si aucun lien avec ce texte est présent
    assertLinkById($id)Passe si un lien avec cet attribut d'identification est présent
    assertField($name, $value)Passe si une balise input avec ce nom contient cette valeur
    assertFieldById($id, $value)Passe si une balise input avec cet identifiant contient cette valeur
    assertResponse($codes)Passe si la réponse HTTP trouve une correspondance dans la liste
    assertMime($types)Passe si le type MIME se retrouve dans cette liste
    assertAuthentication($protocol)Passe si l'authentification provoquée est de ce type de protocole
    assertNoAuthentication()Passe s'il n'y pas d'authentification provoquée en cours
    assertRealm($name)Passe si le domaine provoqué correspond
    assertHeader($header, $content)Passe si une entête téléchargée correspond à cette valeur
    assertNoUnwantedHeader($header)Passe si une entête n'a pas été téléchargé
    assertHeaderPattern($header, $pattern)Passe si une entête téléchargée correspond à cette expression rationnelle Perl
    assertCookie($name, $value)Passe s'il existe un cookie correspondant
    assertNoCookie($name)Passe s'il n'y a pas de cookie avec un tel nom
    - Comme d'habitude avec les assertions de SimpleTest, elles renvoient toutes "false" en cas d'échec et "true" si c'est un succès. Elles renvoient aussi un message de test optionnel : vous pouvez l'ajouter dans votre propre message en utilisant "%s". -

    -

    - A présent nous pourrions effectué le test sur le titre uniquement... -

    -$this->assertTitle('The Last Craft?');
    -
    - En plus d'une simple vérification sur le contenu HTML, nous pouvons aussi vérifier que le type MIME est bien d'un type acceptable... -
    -$this->assertMime(array('text/plain', 'text/html'));
    -
    - 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... -
    -class TestOfLastcraft extends WebTestCase {
    -    
    -    function testHomepage() {
    -        $this->get('http://simpletest.sourceforge.net/');
    -        $this->assertResponse(200);
    -    }
    -}
    -
    - Ici nous vérifions que le téléchargement s'est bien terminé en ne permettant qu'une réponse HTTP 200. Ce test passera, mais ce n'est pas la meilleure façon de procéder. Il n'existe aucune page sur http://simpletest.sourceforge.net/, à la place le serveur renverra une redirection vers http://www.lastcraft.com/simple_test.php. WebTestCase suit automatiquement trois de ces redirections. Les tests sont quelque peu plus robustes de la sorte. Surtout qu'on est souvent plus intéressé par l'interaction entre les pages que de leur simple livraison. Si les redirections se révèlent être digne d'intérêt, il reste possible de les supprimer... -
    -class TestOfLastcraft extends WebTestCase {
    -    
    -    function testHomepage() {
    -        $this->setMaximumRedirects(0);
    -        $this->get('http://simpletest.sourceforge.net/');
    -        $this->assertResponse(200);
    -    }
    -}
    -
    - Alors l'assertion échoue comme prévue... -
    -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
    -
    - Nous pouvons modifier le test pour accepter les redirections... -
    -class TestOfLastcraft extends WebTestCase {
    -    
    -    function testHomepage() {
    -        $this->setMaximumRedirects(0);
    -        $this->get('http://simpletest.sourceforge.net/');
    -        $this->assertResponse(array(301, 302, 303, 307));
    -    }
    -}
    -
    - Maitenant ça passe. -

    - -

    - -

    Navigeur dans un site web

    - -

    -

    - 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... -

    -class TestOfLastcraft extends WebTestCase {
    -    ...
    -    function testContact() {
    -        $this->get('http://www.lastcraft.com/');
    -        $this->clickLink('About');
    -        $this->assertTitle('About Last Craft');
    -    }
    -}
    -
    - Le paramètre est le texte du lien. -

    -

    - Il l'objectif est un bouton plutôt qu'une balise ancre, alors clickSubmit() doit être utilisé avec le titre du bouton... -

    -$this->clickSubmit('Go!');
    -
    -

    -

    - La liste des méthodes de navigation est... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    get($url, $parameters)Envoie une requête GET avec ces paramètres
    post($url, $parameters)Envoie une requête POST avec ces paramètres
    head($url, $parameters)Envoie une requête HEAD sans remplacer le contenu de la page
    retry()Relance la dernière requête
    back()Identique au bouton "Précédent" du navigateur
    forward()Identique au bouton "Suivant" du navigateur
    authenticate($name, $password)Re-essaye avec une tentative d'authentification
    getFrameFocus()Le nom de la fenêtre en cours d'utilisation
    setFrameFocusByIndex($choice)Change le focus d'une fenêtre en commençant par 1
    setFrameFocus($name)Change le focus d'une fenêtre en utilisant son nom
    clearFrameFocus()Revient à un traitement de toutes les fenêtres comme une seule
    clickSubmit($label)Clique sur le premier bouton avec cette étiquette
    clickSubmitByName($name)Clique sur le bouton avec cet attribut de nom
    clickSubmitById($id)Clique sur le bouton avec cet attribut d'identification
    clickImage($label, $x, $y)Clique sur une balise input de type image avec ce titre ou ce texte dans l'attribut alt
    clickImageByName($name, $x, $y)Clique sur une balise input de type image avec ce nom
    clickImageById($id, $x, $y)Clique sur une balise input de type image avec cet attribut d'identification
    submitFormById($id)Soumet un formulaire sans valeur de soumission
    clickLink($label, $index)Clique sur un ancre avec ce texte d'étiquette visible
    clickLinkById($id)Clique sur une ancre avec cet attribut d'identification
    -

    -

    - Les paramètres dans les méthodes get(), post() et head() sont optionnels. Le téléchargement via HTTP HEAD ne modifie pas le contexte du navigateur, il se limite au chargement des cookies. Cela peut être utilise lorsqu'une image ou une feuille de style initie un cookie pour bloquer un robot trop entreprenant. -

    -

    - Les commandes retry(), back() et forward() fonctionnent exactement comme dans un navigateur. Elles utilisent l'historique pour relancer les pages. Une technique bien pratique pour vérifier les effets d'un bouton retour sur vos formulaires. -

    -

    - Les méthodes sur les fenêtres méritent une petite explication. Par défaut, une page avec des fenêtres est traitée comme toutes les autres. Le contenu sera vérifié à travers l'ensemble de la "frameset", par conséquent un lien fonctionnera, peu importe la fenêtre qui contient la balise ancre. Vous pouvez outrepassé ce comportement en exigeant le focus sur une unique fenêtre. Si vous réalisez cela, toutes les recherches et toutes les actions se limiteront à cette unique fenêtre, y compris les demandes d'authentification. Si un lien ou un bouton n'est pas dans la fenêtre en focus alors il ne peut pas être cliqué. -

    -

    - Tester la navigation sur des pages fixes ne vous alerte que quand vous avez cassé un script entier. Pour des pages fortement dynamiques, un forum de discussion par exemple, ça peut être crucial pour vérifier l'état de l'application. Pour la plupart des applications cependant, la logique vraiment délicate se situe dans la gestion des formulaires et des sessions. Heureusement SimpleTest aussi inclut des outils pour tester des formulaires web. -

    - -

    - -

    Modifier la requête

    - -

    -

    - Bien que SimpleTest n'ait pas comme objectif de contrôler des erreurs réseau, il contient quand même des méthodes pour modifier et déboguer les requêtes qu'il lance. Voici une autre liste de méthode... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    getTransportError()La dernière erreur de socket
    getUrl()La localisation courante
    showRequest()Déverse la requête sortante
    showHeaders()Déverse les entêtes d'entrée
    showSource()Déverse le contenu brut de la page HTML
    ignoreFrames()Ne recharge pas les framesets
    setCookie($name, $value)Initie un cookie à partir de maintenant
    addHeader($header)Ajoute toujours cette entête à la requête
    setMaximumRedirects($max)S'arrête après autant de redirections
    setConnectionTimeout($timeout)Termine la connexion après autant de temps entre les bytes
    useProxy($proxy, $name, $password)Effectue les requêtes à travers ce proxy d'URL
    -

    - -
    - - - diff --git a/tests/test_tools/simpletest/dumper.php b/tests/test_tools/simpletest/dumper.php index f54140ca..956b8f00 100644 --- a/tests/test_tools/simpletest/dumper.php +++ b/tests/test_tools/simpletest/dumper.php @@ -3,12 +3,14 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage UnitTester - * @version $Id: dumper.php,v 1.22 2005/02/05 04:51:17 lastcraft Exp $ + * @version $Id: dumper.php,v 1.28 2006/01/03 01:17:07 lastcraft Exp $ */ /** * does type matter */ - define('TYPE_MATTERS', true); + if (! defined('TYPE_MATTERS')) { + define('TYPE_MATTERS', true); + } /** * Displays variables as text and does diffs. @@ -35,7 +37,7 @@ case "Object": return "Object: of " . get_class($value); case "String": - return "String: " . $this->clipString($value, 100); + return "String: " . $this->clipString($value, 200); default: return "$type: $value"; } @@ -184,8 +186,8 @@ $position = $this->_stringDiffersAt($first, $second); $message = "at character $position"; $message .= " with [" . - $this->clipString($first, 100, $position) . "] and [" . - $this->clipString($second, 100, $position) . "]"; + $this->clipString($first, 200, $position) . "] and [" . + $this->clipString($second, 200, $position) . "]"; return $message; } @@ -221,9 +223,10 @@ if (is_object($second) || is_array($second)) { return $this->_describeGenericDifference($first, $second); } - return "because " . $this->describeValue($first) . + return "because [" . $this->describeValue($first) . "] differs from [" . - $this->describeValue($second) . "]"; + $this->describeValue($second) . "] by " . + abs($first - $second); } /** @@ -331,7 +334,7 @@ $position = 0; $step = strlen($first); while ($step > 1) { - $step = (integer)(($step + 1)/2); + $step = (integer)(($step + 1) / 2); if (strncmp($first, $second, $position + $step) == 0) { $position += $step; } @@ -358,23 +361,42 @@ * Extracts the last assertion that was not within * Simpletest itself. The name must start with "assert". * @param array $stack List of stack frames. - * @param string $format String formatting. - * @param string $prefix Prefix of method to search for. * @access public * @static */ - function getFormattedAssertionLine($stack, $format = '%d', $prefix = 'assert') { + function getFormattedAssertionLine($stack) { foreach ($stack as $frame) { - if (isset($frame['file']) && strpos($frame['file'], 'simpletest') !== false) { // dirname() is a bit slow. - if (substr(dirname($frame['file']), -10) == 'simpletest') { - continue; + if (isset($frame['file'])) { + if (strpos($frame['file'], SIMPLE_TEST) !== false) { + if (dirname($frame['file']) . '/' == SIMPLE_TEST) { + continue; + } } } - if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) { - return sprintf($format, $frame['line']); + if (SimpleDumper::_stackFrameIsAnAssertion($frame)) { + return ' at [' . $frame['file'] . ' line ' . $frame['line'] . ']'; } } return ''; } + + /** + * Tries to determine if the method call is an assertion. + * @param array $frame PHP stack frame. + * @access private + * @static + */ + function _stackFrameIsAnAssertion($frame) { + if (($frame['function'] == 'fail') || ($frame['function'] == 'pass')) { + return true; + } + if (strncmp($frame['function'], 'assert', 6) == 0) { + return true; + } + if (strncmp($frame['function'], 'expect', 6) == 0) { + return true; + } + return false; + } } ?> \ No newline at end of file diff --git a/tests/test_tools/simpletest/encoding.php b/tests/test_tools/simpletest/encoding.php index 62ca2a1b..11a94df0 100644 --- a/tests/test_tools/simpletest/encoding.php +++ b/tests/test_tools/simpletest/encoding.php @@ -3,8 +3,184 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage WebTester - * @version $Id: encoding.php,v 1.6 2005/01/02 23:43:23 lastcraft Exp $ + * @version $Id: encoding.php,v 1.17 2005/07/20 13:41:40 lastcraft Exp $ */ + + /**#@+ + * include other SimpleTest class files + */ + require_once(dirname(__FILE__) . '/socket.php'); + /**#@-*/ + + /** + * Single post parameter. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleEncodedPair { + protected $_key; + protected $_value; + + /** + * Stashes the data for rendering later. + * @param string $key Form element name. + * @param string $value Data to send. + */ + function SimpleEncodedPair($key, $value) { + $this->_key = $key; + $this->_value = $value; + } + + /** + * The pair as a single string. + * @return string Encoded pair. + * @access public + */ + function asRequest() { + return $this->_key . '=' . urlencode($this->_value); + } + + /** + * The MIME part as a string. + * @return string MIME part encoding. + * @access public + */ + function asMime() { + $part = 'Content-Disposition: form-data; '; + $part .= "name=\"" . $this->_key . "\"\r\n"; + $part .= "\r\n" . $this->_value; + return $part; + } + + /** + * Is this the value we are looking for? + * @param string $key Identifier. + * @return boolean True if matched. + * @access public + */ + function isKey($key) { + return $key == $this->_key; + } + + /** + * Is this the value we are looking for? + * @return string Identifier. + * @access public + */ + function getKey() { + return $this->_key; + } + + /** + * Is this the value we are looking for? + * @return string Content. + * @access public + */ + function getValue() { + return $this->_value; + } + } + + /** + * Single post parameter. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleAttachment { + protected $_key; + protected $_content; + protected $_filename; + + /** + * Stashes the data for rendering later. + * @param string $key Key to add value to. + * @param string $content Raw data. + * @param hash $filename Original filename. + */ + function SimpleAttachment($key, $content, $filename) { + $this->_key = $key; + $this->_content = $content; + $this->_filename = $filename; + } + + /** + * The pair as a single string. + * @return string Encoded pair. + * @access public + */ + function asRequest() { + return ''; + } + + /** + * The MIME part as a string. + * @return string MIME part encoding. + * @access public + */ + function asMime() { + $part = 'Content-Disposition: form-data; '; + $part .= 'name="' . $this->_key . '"; '; + $part .= 'filename="' . $this->_filename . '"'; + $part .= "\r\nContent-Type: " . $this->_deduceMimeType(); + $part .= "\r\n\r\n" . $this->_content; + return $part; + } + + /** + * Attempts to figure out the MIME type from the + * file extension and the content. + * @return string MIME type. + * @access private + */ + function _deduceMimeType() { + if ($this->_isOnlyAscii($this->_content)) { + return 'text/plain'; + } + return 'application/octet-stream'; + } + + /** + * Tests each character is in the range 0-127. + * @param string $ascii String to test. + * @access private + */ + function _isOnlyAscii($ascii) { + for ($i = 0, $length = strlen($ascii); $i < $length; $i++) { + if (ord($ascii[$i]) > 127) { + return false; + } + } + return true; + } + + /** + * Is this the value we are looking for? + * @param string $key Identifier. + * @return boolean True if matched. + * @access public + */ + function isKey($key) { + return $key == $this->_key; + } + + /** + * Is this the value we are looking for? + * @return string Identifier. + * @access public + */ + function getKey() { + return $this->_key; + } + + /** + * Is this the value we are looking for? + * @return string Content. + * @access public + */ + function getValue() { + return $this->_filename; + } + } /** * Bundle of GET/POST parameters. Can include @@ -12,27 +188,32 @@ * @package SimpleTest * @subpackage WebTester */ - class SimpleFormEncoding { + class SimpleEncoding { protected $_request; - protected $_x; - protected $_y; /** * Starts empty. - * @param array $query/SimpleQueryString Hash of parameters. - * Multiple values are - * as lists on a single key. + * @param array $query Hash of parameters. + * Multiple values are + * as lists on a single key. * @access public */ - function SimpleFormEncoding($query = false) { + function SimpleEncoding($query = false) { if (! $query) { $query = array(); } - $this->_request = array(); - $this->setCoordinates(); + $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. @@ -43,18 +224,37 @@ if ($value === false) { return; } - if (! isset($this->_request[$key])) { - $this->_request[$key] = array(); - } if (is_array($value)) { foreach ($value as $item) { - $this->_request[$key][] = $item; + $this->_addPair($key, $item); } } else { - $this->_request[$key][] = $value; + $this->_addPair($key, $value); } } + /** + * Adds a new value into the request. + * @param string $key Key to add value to. + * @param string/array $value New data. + * @access private + */ + function _addPair($key, $value) { + $this->_request[] = new SimpleEncodedPair($key, $value); + } + + /** + * Adds a MIME part to the query. Does nothing for a + * form encoded packet. + * @param string $key Key to add value to. + * @param string $content Raw data. + * @param hash $filename Original filename. + * @access public + */ + function attach($key, $content, $filename) { + $this->_request[] = new SimpleAttachment($key, $content, $filename); + } + /** * Adds a set of parameters to this query. * @param array/SimpleQueryString $query Multiple values are @@ -63,12 +263,7 @@ */ function merge($query) { if (is_object($query)) { - foreach ($query->getKeys() as $key) { - $this->add($key, $query->getValue($key)); - } - if ($query->getX() !== false) { - $this->setCoordinates($query->getX(), $query->getY()); - } + $this->_request = array_merge($this->_request, $query->getAll()); } elseif (is_array($query)) { foreach ($query as $key => $value) { $this->add($key, $value); @@ -77,63 +272,234 @@ } /** - * Sets image coordinates. Set to false to clear - * them. - * @param integer $x Horizontal position. - * @param integer $y Vertical position. + * Accessor for single value. + * @return string/array False if missing, string + * if present and array if + * multiple entries. * @access public */ - function setCoordinates($x = false, $y = false) { - if (($x === false) || ($y === false)) { - $this->_x = $this->_y = false; - return; + 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; } - $this->_x = (integer)$x; - $this->_y = (integer)$y; } /** - * Accessor for horizontal image coordinate. - * @return integer X value. + * Accessor for listing of pairs. + * @return array All pair objects. * @access public */ - function getX() { - return $this->_x; + function getAll() { + return $this->_request; + } + + /** + * Renders the query string as a URL encoded + * request part. + * @return string Part of URL. + * @access protected + */ + function _encode() { + $statements = array(); + foreach ($this->_request as $pair) { + if ($statement = $pair->asRequest()) { + $statements[] = $statement; + } + } + return implode('&', $statements); } - + } + + /** + * Bundle of GET parameters. Can include + * repeated parameters. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleGetEncoding extends SimpleEncoding { + /** - * Accessor for vertical image coordinate. - * @return integer Y value. + * Starts empty. + * @param array $query Hash of parameters. + * Multiple values are + * as lists on a single key. * @access public */ - function getY() { - return $this->_y; + function SimpleGetEncoding($query = false) { + $this->SimpleEncoding($query); } /** - * Accessor for single value. - * @return string/array False if missing, string - * if present and array if - * multiple entries. + * HTTP request method. + * @return string Always GET. * @access public */ - function getValue($key) { - if (! isset($this->_request[$key])) { - return false; - } elseif (count($this->_request[$key]) == 1) { - return $this->_request[$key][0]; - } else { - return $this->_request[$key]; - } + function getMethod() { + return 'GET'; + } + + /** + * Writes no extra headers. + * @param SimpleSocket $socket Socket to write to. + * @access public + */ + function writeHeadersTo($socket) { + } + + /** + * No data is sent to the socket as the data is encoded into + * the URL. + * @param SimpleSocket $socket Socket to write to. + * @access public + */ + function writeTo($socket) { + } + + /** + * Renders the query string as a URL encoded + * request part for attaching to a URL. + * @return string Part of URL. + * @access public + */ + function asUrlRequest() { + return $this->_encode(); + } + } + + /** + * Bundle of URL parameters for a HEAD request. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleHeadEncoding extends SimpleGetEncoding { + + /** + * Starts empty. + * @param array $query Hash of parameters. + * Multiple values are + * as lists on a single key. + * @access public + */ + function SimpleHeadEncoding($query = false) { + $this->SimpleGetEncoding($query); + } + + /** + * HTTP request method. + * @return string Always HEAD. + * @access public + */ + function getMethod() { + return 'HEAD'; + } + } + + /** + * Bundle of POST parameters. Can include + * repeated parameters. + * @package SimpleTest + * @subpackage WebTester + */ + class SimplePostEncoding extends SimpleEncoding { + + /** + * Starts empty. + * @param array $query Hash of parameters. + * Multiple values are + * as lists on a single key. + * @access public + */ + function SimplePostEncoding($query = false) { + $this->SimpleEncoding($query); + } + + /** + * HTTP request method. + * @return string Always POST. + * @access public + */ + function getMethod() { + return 'POST'; + } + + /** + * Dispatches the form headers down the socket. + * @param SimpleSocket $socket Socket to write to. + * @access public + */ + function writeHeadersTo($socket) { + $socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n"); + $socket->write("Content-Type: application/x-www-form-urlencoded\r\n"); + } + + /** + * Dispatches the form data down the socket. + * @param SimpleSocket $socket Socket to write to. + * @access public + */ + function writeTo($socket) { + $socket->write($this->_encode()); + } + + /** + * Renders the query string as a URL encoded + * request part for attaching to a URL. + * @return string Part of URL. + * @access public + */ + function asUrlRequest() { + return ''; + } + } + + /** + * Bundle of POST parameters in the multipart + * format. Can include file uploads. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleMultipartEncoding extends SimplePostEncoding { + protected $_boundary; + + /** + * Starts empty. + * @param array $query Hash of parameters. + * Multiple values are + * as lists on a single key. + * @access public + */ + function SimpleMultipartEncoding($query = false, $boundary = false) { + $this->SimplePostEncoding($query); + $this->_boundary = ($boundary === false ? uniqid('st') : $boundary); } /** - * Accessor for key list. - * @return array List of keys present. + * Dispatches the form headers down the socket. + * @param SimpleSocket $socket Socket to write to. * @access public */ - function getKeys() { - return array_keys($this->_request); + 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()); } /** @@ -142,15 +508,14 @@ * @return string Part of URL. * @access public */ - function asString() { - $statements = array(); - foreach ($this->_request as $key => $values) { - foreach ($values as $value) { - $statements[] = "$key=" . urlencode($value); - } + function _encode() { + $stream = ''; + foreach ($this->_request as $pair) { + $stream .= "--" . $this->_boundary . "\r\n"; + $stream .= $pair->asMime() . "\r\n"; } - $coords = ($this->_x !== false) ? '?' . $this->_x . ',' . $this->_y : ''; - return implode('&', $statements) . $coords; + $stream .= "--" . $this->_boundary . "--\r\n"; + return $stream; } } ?> \ No newline at end of file diff --git a/tests/test_tools/simpletest/errors.php b/tests/test_tools/simpletest/errors.php index 70c6c338..0608de60 100644 --- a/tests/test_tools/simpletest/errors.php +++ b/tests/test_tools/simpletest/errors.php @@ -3,13 +3,54 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage UnitTester - * @version $Id: errors.php,v 1.13 2005/01/08 03:48:39 lastcraft Exp $ + * @version $Id: errors.php,v 1.14 2006/02/06 06:05:18 lastcraft Exp $ */ + /** @ignore - PHP5 compatibility fix. */ if (! defined('E_STRICT')) { define('E_STRICT', 2048); } - + + /**#@+ + * Includes SimpleTest files. + */ + require_once(dirname(__FILE__) . '/invoker.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 SimpleErrorTrappingInvoker($invoker) { + $this->SimpleInvokerDecorator($invoker); + } + + /** + * Invokes a test method and dispatches any + * untrapped errors. Called back from + * the visiting runner. + * @param string $method Test method to call. + * @access public + */ + function invoke($method) { + set_error_handler('simpleTestErrorHandler'); + parent::invoke($method); + $queue = &SimpleErrorQueue::instance(); + while (list($severity, $message, $file, $line, $globals) = $queue->extract()) { + $severity = SimpleErrorQueue::getSeverityAsString($severity); + $test_case = $this->getTestCase(); + $test_case->error($severity, $message, $file, $line); + } + restore_error_handler(); + } + } + /** * Singleton error queue used to record trapped * errors. @@ -18,7 +59,7 @@ */ class SimpleErrorQueue { protected $_queue; - + /** * Starts with an empty queue. * @access public @@ -26,7 +67,7 @@ function SimpleErrorQueue() { $this->clear(); } - + /** * Adds an error to the front of the queue. * @param $severity PHP error code. @@ -41,7 +82,7 @@ $this->_queue, array($severity, $message, $filename, $line, $super_globals)); } - + /** * Pulls the earliest error from the queue. * @return False if none, or a list of error @@ -57,7 +98,7 @@ } return false; } - + /** * Discards the contents of the error queue. * @access public @@ -65,7 +106,7 @@ function clear() { $this->_queue = array(); } - + /** * Tests to see if the queue is empty. * @return True if empty. @@ -73,21 +114,21 @@ function isEmpty() { return (count($this->_queue) == 0); } - + /** * Global access to a single error queue. * @return Global error queue object. * @access public * @static */ - static function instance() { + function &instance() { static $queue = false; if (! $queue) { $queue = new SimpleErrorQueue(); } return $queue; } - + /** * Converst an error code into it's string * representation. @@ -96,7 +137,7 @@ * @access public * @static */ - static function getSeverityAsString($severity) { + function getSeverityAsString($severity) { static $map = array( E_STRICT => 'E_STRICT', E_ERROR => 'E_ERROR', @@ -113,7 +154,7 @@ return $map[$severity]; } } - + /** * Error handler that simply stashes any errors into the global * error queue. Simulates the existing behaviour with respect to @@ -133,7 +174,7 @@ $label = SimpleErrorQueue::getSeverityAsString($severity); error_log("$label: $message in $filename on line $line"); } - $queue = SimpleErrorQueue::instance(); + $queue = &SimpleErrorQueue::instance(); $queue->add($severity, $message, $filename, $line, $super_globals); set_error_handler('simpleTestErrorHandler'); } diff --git a/tests/test_tools/simpletest/exceptions.php b/tests/test_tools/simpletest/exceptions.php new file mode 100644 index 00000000..949f2936 --- /dev/null +++ b/tests/test_tools/simpletest/exceptions.php @@ -0,0 +1,46 @@ +SimpleInvokerDecorator($invoker); + } + + /** + * Invokes a test method and dispatches any + * untrapped errors. + * @param string $method Test method to call. + * @access public + */ + function invoke($method) { + try { + parent::invoke($method); + } catch (Exception $exception) { + $test_case = $this->getTestCase(); + $test_case->exception($exception); + } + } + } +?> \ No newline at end of file diff --git a/tests/test_tools/simpletest/expectation.php b/tests/test_tools/simpletest/expectation.php index 355963b4..b2eca0d8 100644 --- a/tests/test_tools/simpletest/expectation.php +++ b/tests/test_tools/simpletest/expectation.php @@ -1,23 +1,23 @@ _dumper; } + + /** + * Test to see if a value is an expectation object. + * A useful utility method. + * @param mixed $expectation Hopefully an Epectation + * class. + * @return boolean True if descended from + * this class. + * @access public + * @static + */ + function isExpectation($expectation) { + return is_object($expectation) && + SimpleTestCompatibility::isA($expectation, 'SimpleExpectation'); + } } /** * Test for equality. - * @package SimpleTest - * @subpackage UnitTester + * @package SimpleTest + * @subpackage UnitTester */ class EqualExpectation extends SimpleExpectation { protected $_value; @@ -135,8 +150,8 @@ /** * Test for inequality. - * @package SimpleTest - * @subpackage UnitTester + * @package SimpleTest + * @subpackage UnitTester */ class NotEqualExpectation extends EqualExpectation { @@ -181,10 +196,131 @@ } } + /** + * Test for being within a range. + * @package SimpleTest + * @subpackage UnitTester + */ + class WithinMarginExpectation extends SimpleExpectation { + protected $_upper; + protected $_lower; + + /** + * Sets the value to compare against and the fuzziness of + * the match. Used for comparing floating point values. + * @param mixed $value Test value to match. + * @param mixed $margin Fuzziness of match. + * @param string $message Customised message on failure. + * @access public + */ + function WithinMarginExpectation($value, $margin, $message = '%s') { + $this->SimpleExpectation($message); + $this->_upper = $value + $margin; + $this->_lower = $value - $margin; + } + + /** + * Tests the expectation. True if it matches the + * held value. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return (($compare <= $this->_upper) && ($compare >= $this->_lower)); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if ($this->test($compare)) { + return $this->_withinMessage($compare); + } else { + return $this->_outsideMessage($compare); + } + } + + /** + * Creates a the message for being within the range. + * @param mixed $compare Value being tested. + * @access private + */ + function _withinMessage($compare) { + return "Within expectation [" . $this->_dumper->describeValue($this->_lower) . "] and [" . + $this->_dumper->describeValue($this->_upper) . "]"; + } + + /** + * Creates a the message for being within the range. + * @param mixed $compare Value being tested. + * @access private + */ + function _outsideMessage($compare) { + if ($compare > $this->_upper) { + return "Outside expectation " . + $this->_dumper->describeDifference($compare, $this->_upper); + } else { + return "Outside expectation " . + $this->_dumper->describeDifference($compare, $this->_lower); + } + } + } + + /** + * Test for being outside of a range. + * @package SimpleTest + * @subpackage UnitTester + */ + class OutsideMarginExpectation extends WithinMarginExpectation { + + /** + * Sets the value to compare against and the fuzziness of + * the match. Used for comparing floating point values. + * @param mixed $value Test value to not match. + * @param mixed $margin Fuzziness of match. + * @param string $message Customised message on failure. + * @access public + */ + function OutsideMarginExpectation($value, $margin, $message = '%s') { + $this->WithinMarginExpectation($value, $margin, $message); + } + + /** + * Tests the expectation. True if it matches the + * held value. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return ! parent::test($compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if (! $this->test($compare)) { + return $this->_withinMessage($compare); + } else { + return $this->_outsideMessage($compare); + } + } + } + /** * Test for identity. - * @package SimpleTest - * @subpackage UnitTester + * @package SimpleTest + * @subpackage UnitTester */ class IdenticalExpectation extends EqualExpectation { @@ -231,8 +367,8 @@ /** * Test for non-identity. - * @package SimpleTest - * @subpackage UnitTester + * @package SimpleTest + * @subpackage UnitTester */ class NotIdenticalExpectation extends IdenticalExpectation { @@ -277,10 +413,10 @@ /** * Test for a pattern using Perl regex rules. - * @package SimpleTest - * @subpackage UnitTester + * @package SimpleTest + * @subpackage UnitTester */ - class WantedPatternExpectation extends SimpleExpectation { + class PatternExpectation extends SimpleExpectation { protected $_pattern; /** @@ -289,7 +425,7 @@ * @param string $message Customised message on failure. * @access public */ - function WantedPatternExpectation($pattern, $message = '%s') { + function PatternExpectation($pattern, $message = '%s') { $this->SimpleExpectation($message); $this->_pattern = $pattern; } @@ -335,6 +471,8 @@ /** * Describes a pattern match including the string * found and it's position. + * @package SimpleTest + * @subpackage UnitTester * @param string $pattern Regex to match against. * @param string $subject Subject to search. * @access protected @@ -350,13 +488,19 @@ } } + /** + * @deprecated + */ + class WantedPatternExpectation extends PatternExpectation { + } + /** * Fail if a pattern is detected within the * comparison. - * @package SimpleTest - * @subpackage UnitTester + * @package SimpleTest + * @subpackage UnitTester */ - class UnwantedPatternExpectation extends WantedPatternExpectation { + class NoPatternExpectation extends PatternExpectation { /** * Sets the reject pattern @@ -364,8 +508,8 @@ * @param string $message Customised message on failure. * @access public */ - function UnwantedPatternExpectation($pattern, $message = '%s') { - $this->WantedPatternExpectation($pattern, $message); + function NoPatternExpectation($pattern, $message = '%s') { + $this->PatternExpectation($pattern, $message); } /** @@ -398,10 +542,18 @@ } } + /** + * @package SimpleTest + * @subpackage UnitTester + * @deprecated + */ + class UnwantedPatternExpectation extends NoPatternExpectation { + } + /** * Tests either type or class name if it's an object. - * @package SimpleTest - * @subpackage UnitTester + * @package SimpleTest + * @subpackage UnitTester */ class IsAExpectation extends SimpleExpectation { protected $_type; @@ -477,8 +629,8 @@ /** * Tests either type or class name if it's an object. * Will succeed if the type does not match. - * @package SimpleTest - * @subpackage UnitTester + * @package SimpleTest + * @subpackage UnitTester */ class NotAExpectation extends IsAExpectation { protected $_type; @@ -520,8 +672,8 @@ /** * Tests for existance of a method in an object - * @package SimpleTest - * @subpackage UnitTester + * @package SimpleTest + * @subpackage UnitTester */ class MethodExistsExpectation extends SimpleExpectation { protected $_method; @@ -556,13 +708,13 @@ * @access public */ function testMessage($compare) { - $dumper = $this->_getDumper(); - if (! is_object($compare)) { - return 'No method on non-object [' . $dumper->describeValue($compare) . ']'; - } - $method = $this->_method; - return "Object [" . $dumper->describeValue($compare) . - "] should contain method [$method]"; + $dumper = $this->_getDumper(); + if (! is_object($compare)) { + return 'No method on non-object [' . $dumper->describeValue($compare) . ']'; + } + $method = $this->_method; + return "Object [" . $dumper->describeValue($compare) . + "] should contain method [$method]"; } } -?> \ No newline at end of file +?> diff --git a/tests/test_tools/simpletest/extensions/pear_test_case.php b/tests/test_tools/simpletest/extensions/pear_test_case.php deleted file mode 100755 index 51727345..00000000 --- a/tests/test_tools/simpletest/extensions/pear_test_case.php +++ /dev/null @@ -1,199 +0,0 @@ -SimpleTestCase($label); - $this->_loosely_typed = false; - } - - /** - * Will test straight equality if set to loose - * typing, or identity if not. - * @param $first First value. - * @param $second Comparison value. - * @param $message Message to display. - * @public - */ - function assertEquals($first, $second, $message = "%s", $delta = 0) { - if ($this->_loosely_typed) { - $expectation = &new EqualExpectation($first); - } else { - $expectation = &new IdenticalExpectation($first); - } - $this->assertExpectation($expectation, $second, $message); - } - - /** - * Passes if the value tested is not null. - * @param $value Value to test against. - * @param $message Message to display. - * @public - */ - function assertNotNull($value, $message = "%s") { - parent::assertTrue(isset($value), $message); - } - - /** - * Passes if the value tested is null. - * @param $value Value to test against. - * @param $message Message to display. - * @public - */ - function assertNull($value, $message = "%s") { - parent::assertTrue(!isset($value), $message); - } - - /** - * In PHP5 the identity test tests for the same - * object. This is a reference test in PHP4. - * @param $first First object handle. - * @param $second Hopefully the same handle. - * @param $message Message to display. - * @public - */ - function assertSame(&$first, &$second, $message = "%s") { - $dumper = &new SimpleDumper(); - $message = sprintf( - $message, - "[" . $dumper->describeValue($first) . - "] and [" . $dumper->describeValue($second) . - "] should reference the same object"); - return $this->assertTrue( - SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * In PHP5 the identity test tests for the same - * object. This is a reference test in PHP4. - * @param $first First object handle. - * @param $second Hopefully a different handle. - * @param $message Message to display. - * @public - */ - function assertNotSame(&$first, &$second, $message = "%s") { - $dumper = &new SimpleDumper(); - $message = sprintf( - $message, - "[" . $dumper->describeValue($first) . - "] and [" . $dumper->describeValue($second) . - "] should not be the same object"); - return $this->assertFalse( - SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * Sends pass if the test condition resolves true, - * a fail otherwise. - * @param $condition Condition to test true. - * @param $message Message to display. - * @public - */ - function assertTrue($condition, $message = "%s") { - parent::assertTrue($condition, $message); - } - - /** - * Sends pass if the test condition resolves false, - * a fail otherwise. - * @param $condition Condition to test false. - * @param $message Message to display. - * @public - */ - function assertFalse($condition, $message = "%s") { - parent::assertTrue(!$condition, $message); - } - - /** - * Tests a regex match. Needs refactoring. - * @param $pattern Regex to match. - * @param $subject String to search in. - * @param $message Message to display. - * @public - */ - function assertRegExp($pattern, $subject, $message = "%s") { - $this->assertExpectation( - new WantedPatternExpectation($pattern), - $subject, - $message); - } - - /** - * Tests the type of a value. - * @param $value Value to take type of. - * @param $type Hoped for type. - * @param $message Message to display. - * @public - */ - function assertType($value, $type, $message = "%s") { - parent::assertTrue(gettype($value) == strtolower($type), $message); - } - - /** - * Sets equality operation to act as a simple equal - * comparison only, allowing a broader range of - * matches. - * @param $loosely_typed True for broader comparison. - * @public - */ - function setLooselyTyped($loosely_typed) { - $this->_loosely_typed = $loosely_typed; - } - - /** - * For progress indication during - * a test amongst other things. - * @return Usually one. - * @public - */ - function countTestCases() { - return $this->getSize(); - } - - /** - * Accessor for name, normally just the class - * name. - * @public - */ - function getName() { - return $this->getLabel(); - } - - /** - * Does nothing. For compatibility only. - * @param $name Dummy - * @public - */ - function setName($name) { - } - } -?> diff --git a/tests/test_tools/simpletest/extensions/phpunit_test_case.php b/tests/test_tools/simpletest/extensions/phpunit_test_case.php deleted file mode 100755 index a0954d8b..00000000 --- a/tests/test_tools/simpletest/extensions/phpunit_test_case.php +++ /dev/null @@ -1,108 +0,0 @@ -SimpleTestCase($label); - } - - /** - * Sends pass if the test condition resolves true, - * a fail otherwise. - * @param $condition Condition to test true. - * @param $message Message to display. - * @public - */ - function assert($condition, $message = false) { - parent::assertTrue($condition, $message); - } - - /** - * Will test straight equality if set to loose - * typing, or identity if not. - * @param $first First value. - * @param $second Comparison value. - * @param $message Message to display. - * @public - */ - function assertEquals($first, $second, $message = false) { - $this->assertExpectation( - new EqualExpectation($first), - $second, - $message); - } - - /** - * Will test straight equality if set to loose - * typing, or identity if not. - * @param $first First value. - * @param $second Comparison value. - * @param $message Message to display. - * @public - */ - function assertEqualsMultilineStrings($first, $second, $message = false) { - $this->assertExpectation( - new EqualExpectation($first), - $second, - $message); - } - - /** - * Tests a regex match. - * @param $pattern Regex to match. - * @param $subject String to search in. - * @param $message Message to display. - * @public - */ - function assertRegexp($pattern, $subject, $message = false) { - $this->assertExpectation( - new WantedPatternExpectation($pattern), - $subject, - $message); - } - - /** - * Sends an error which we interpret as a fail - * with a different message for compatibility. - * @param $message Message to display. - * @public - */ - function error($message) { - parent::assertTrue(false, "Error triggered [$message]"); - } - - /** - * Accessor for name. - * @public - */ - function name() { - return $this->getLabel(); - } - } -?> diff --git a/tests/test_tools/simpletest/form.php b/tests/test_tools/simpletest/form.php index 89b4948a..0d071105 100644 --- a/tests/test_tools/simpletest/form.php +++ b/tests/test_tools/simpletest/form.php @@ -3,7 +3,7 @@ * Base include file for SimpleTest. * @package SimpleTest * @subpackage WebTester - * @version $Id: form.php,v 1.16 2005/02/22 02:17:04 lastcraft Exp $ + * @version $Id: form.php,v 1.40 2006/01/24 01:11:55 lastcraft Exp $ */ /**#@+ @@ -11,90 +11,9 @@ */ require_once(dirname(__FILE__) . '/tag.php'); require_once(dirname(__FILE__) . '/encoding.php'); + require_once(dirname(__FILE__) . '/selector.php'); /**#@-*/ - /** - * Used to extract form elements for testing against. - * Searches by name attribute. - * @package SimpleTest - * @subpackage WebTester - */ - class SimpleNameSelector { - protected $_name; - - /** - * Stashes the name for later comparison. - * @param string $name Name attribute to match. - */ - function SimpleNameSelector($name) { - $this->_name = $name; - } - - /** - * Comparison. Compares with name attribute of - * widget. - * @param SimpleWidget $widget Control to compare. - * @access public - */ - function isMatch($widget) { - return ($widget->getName() == $this->_name); - } - } - - /** - * Used to extract form elements for testing against. - * Searches by visible label or alt text. - * @package SimpleTest - * @subpackage WebTester - */ - class SimpleLabelSelector { - protected $_label; - - /** - * Stashes the name for later comparison. - * @param string $label Visible text to match. - */ - function SimpleLabelSelector($label) { - $this->_label = $label; - } - - /** - * Comparison. Compares visible text of widget. - * @param SimpleWidget $widget Control to compare. - * @access public - */ - function isMatch($widget) { - return (trim($widget->getLabel()) == trim($this->_label)); - } - } - - /** - * Used to extract form elements for testing against. - * Searches dy id attribute. - * @package SimpleTest - * @subpackage WebTester - */ - class SimpleIdSelector { - protected $_id; - - /** - * Stashes the name for later comparison. - * @param string $id ID atribute to match. - */ - function SimpleIdSelector($id) { - $this->_id = $id; - } - - /** - * Comparison. Compares id attribute of widget. - * @param SimpleWidget $widget Control to compare. - * @access public - */ - function isMatch($widget) { - return $widget->isId($this->_id); - } - } - /** * Form tag class to hold widget values. * @package SimpleTest @@ -103,6 +22,7 @@ class SimpleForm { protected $_method; protected $_action; + protected $_encoding; protected $_default_target; protected $_id; protected $_buttons; @@ -119,6 +39,7 @@ function SimpleForm($tag, $url) { $this->_method = $tag->getAttribute('method'); $this->_action = $this->_createAction($tag->getAttribute('action'), $url); + $this->_encoding = $this->_setEncodingClass($tag); $this->_default_target = false; $this->_id = $tag->getAttribute('id'); $this->_buttons = array(); @@ -128,6 +49,22 @@ $this->_checkboxes = array(); } + /** + * Creates the request packet to be sent by the form. + * @param SimpleTag $tag Form tag to read. + * @return string Packet class. + * @access private + */ + function _setEncodingClass($tag) { + 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. @@ -138,7 +75,7 @@ } /** - * Accessor for form action. + * Accessor for method of form submission. * @return string Either get or post. * @access public */ @@ -154,14 +91,10 @@ * @return SimpleUrl Absolute form target. */ function _createAction($action, $base) { - if ($action === false) { + if (($action === '') || ($action === false)) { return $base; } - if ($action === true) { - $url = new SimpleUrl(''); - } else { - $url = new SimpleUrl($action); - } + $url = new SimpleUrl($action); return $url->makeAbsolute($base); } @@ -177,7 +110,22 @@ } return $url; } - + + /** + * Creates the encoding for the current values in the + * form. + * @return SimpleFormEncoding Request to submit. + * @access private + */ + function _encode() { + $class = $this->_encoding; + $encoding = new $class(); + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + $this->_widgets[$i]->write($encoding); + } + return $encoding; + } + /** * ID field of form for unique identification. * @return string Unique tag ID. @@ -258,7 +206,7 @@ * if not set. * @access public */ - function _getValueBySelector($selector) { + function getValue($selector) { for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { if ($selector->isMatch($this->_widgets[$i])) { return $this->_widgets[$i]->getValue(); @@ -272,28 +220,6 @@ return null; } - /** - * Extracts current value from form. - * @param string $name Keyed by widget name. - * @return string/array Value(s) or null - * if not set. - * @access public - */ - function getValue($name) { - return $this->_getValueBySelector(new SimpleNameSelector($name)); - } - - /** - * Extracts current value from form by the ID. - * @param string/integer $id Keyed by widget ID attribute. - * @return string/array Value(s) or null - * if not set. - * @access public - */ - function getValueById($id) { - return $this->_getValueBySelector(new SimpleIdSelector($id)); - } - /** * Sets a widget value within the form. * @param SimpleSelector $selector Criteria to apply. @@ -303,7 +229,7 @@ * present, nothing will be set. * @access public */ - function _setFieldBySelector($selector, $value) { + function setField($selector, $value) { $success = false; for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { if ($selector->isMatch($this->_widgets[$i])) { @@ -316,54 +242,29 @@ } /** - * Sets a widget value within the form. - * @param string $name Name of widget tag. - * @param string $value Value to input into the widget. - * @return boolean True if value is legal, false - * otherwise. If the field is not - * present, nothing will be set. - * @access public - */ - function setField($name, $value) { - return $this->_setFieldBySelector(new SimpleNameSelector($name), $value); - } - - /** - * Sets a widget value within the form by using the ID. - * @param string/integer $id Name of widget tag. - * @param string $value Value to input into the widget. - * @return boolean True if value is legal, false - * otherwise. If the field is not - * present, nothing will be set. + * Used by the page object to set widgets labels to + * external label tags. + * @param SimpleSelector $selector Criteria to apply. * @access public */ - function setFieldById($id, $value) { - return $this->_setFieldBySelector(new SimpleIdSelector($id), $value); - } - - /** - * Creates the encoding for the current values in the - * form. - * @return SimpleFormEncoding Request to submit. - * @access private - */ - function _getEncoding() { - $encoding = new SimpleFormEncoding(); + function attachLabelBySelector($selector, $label) { for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - $encoding->add( - $this->_widgets[$i]->getName(), - $this->_widgets[$i]->getValue()); + if ($selector->isMatch($this->_widgets[$i])) { + if (method_exists($this->_widgets[$i], 'setLabel')) { + $this->_widgets[$i]->setLabel($label); + return; + } + } } - return $encoding; } /** * Test to see if a form has a submit button. * @param SimpleSelector $selector Criteria to apply. * @return boolean True if present. - * @access private + * @access public */ - function _hasSubmitBySelector($selector) { + function hasSubmit($selector) { foreach ($this->_buttons as $button) { if ($selector->isMatch($button)) { return true; @@ -372,46 +273,13 @@ return false; } - /** - * Test to see if a form has a submit button with this - * name attribute. - * @param string $name Name to look for. - * @return boolean True if present. - * @access public - */ - function hasSubmitName($name) { - return $this->_hasSubmitBySelector(new SimpleNameSelector($name)); - } - - /** - * Test to see if a form has a submit button with this - * value attribute. - * @param string $label Button label to search for. - * @return boolean True if present. - * @access public - */ - function hasSubmitLabel($label) { - return $this->_hasSubmitBySelector(new SimpleLabelSelector($label)); - } - - /** - * Test to see if a form has a submit button with this - * ID attribute. - * @param string $id Button ID attribute to search for. - * @return boolean True if present. - * @access public - */ - function hasSubmitId($id) { - return $this->_hasSubmitBySelector(new SimpleIdSelector($id)); - } - /** * Test to see if a form has an image control. * @param SimpleSelector $selector Criteria to apply. * @return boolean True if present. * @access public */ - function _hasImageBySelector($selector) { + function hasImage($selector) { foreach ($this->_images as $image) { if ($selector->isMatch($image)) { return true; @@ -419,40 +287,6 @@ } return false; } - - /** - * Test to see if a form has a submit button with this - * name attribute. - * @param string $label Button alt attribute to search for - * or nearest equivalent. - * @return boolean True if present. - * @access public - */ - function hasImageLabel($label) { - return $this->_hasImageBySelector(new SimpleLabelSelector($label)); - } - - /** - * Test to see if a form has a submittable image with this - * field name. - * @param string $name Image name to search for. - * @return boolean True if present. - * @access public - */ - function hasImageName($name) { - return $this->_hasImageBySelector(new SimpleNameSelector($name)); - } - - /** - * Test to see if a form has a submittable image with this - * ID attribute. - * @param string $id Button ID attribute to search for. - * @return boolean True if present. - * @access public - */ - function hasImageId($id) { - return $this->_hasImageBySelector(new SimpleIdSelector($id)); - } /** * Gets the submit values for a selected button. @@ -463,11 +297,12 @@ * in the form. * @access public */ - function _submitButtonBySelector($selector, $additional) { + function submitButton($selector, $additional = false) { + $additional = $additional ? $additional : array(); foreach ($this->_buttons as $button) { if ($selector->isMatch($button)) { - $encoding = $this->_getEncoding(); - $encoding->merge($button->getSubmitValues()); + $encoding = $this->_encode(); + $button->write($encoding); if ($additional) { $encoding->merge($additional); } @@ -476,51 +311,6 @@ } return false; } - - /** - * Gets the submit values for a named button. - * @param string $name Button label to search for. - * @param hash $additional Additional data for the form. - * @return SimpleEncoding Submitted values or false - * if there is no such button in the - * form. - * @access public - */ - function submitButtonByName($name, $additional = false) { - return $this->_submitButtonBySelector( - new SimpleNameSelector($name), - $additional); - } - - /** - * Gets the submit values for a named button. - * @param string $label Button label to search for. - * @param hash $additional Additional data for the form. - * @return SimpleEncoding Submitted values or false - * if there is no such button in the - * form. - * @access public - */ - function submitButtonByLabel($label, $additional = false) { - return $this->_submitButtonBySelector( - new SimpleLabelSelector($label), - $additional); - } - - /** - * Gets the submit values for a button identified by the ID. - * @param string $id Button ID attribute to search for. - * @param hash $additional Additional data for the form. - * @return SimpleEncoding Submitted values or false - * if there is no such button in the - * form. - * @access public - */ - function submitButtonById($id, $additional = false) { - return $this->_submitButtonBySelector( - new SimpleIdSelector($id), - $additional); - } /** * Gets the submit values for an image. @@ -533,11 +323,12 @@ * form. * @access public */ - function _submitImageBySelector($selector, $x, $y, $additional) { + function submitImage($selector, $x, $y, $additional = false) { + $additional = $additional ? $additional : array(); foreach ($this->_images as $image) { if ($selector->isMatch($image)) { - $encoding = $this->_getEncoding(); - $encoding->merge($image->getSubmitValues($x, $y)); + $encoding = $this->_encode(); + $image->write($encoding, $x, $y); if ($additional) { $encoding->merge($additional); } @@ -546,64 +337,6 @@ } return false; } - - /** - * Gets the submit values for an image identified by the alt - * tag or nearest equivalent. - * @param string $label Button label to search for. - * @param integer $x X-coordinate of click. - * @param integer $y Y-coordinate of click. - * @param hash $additional Additional data for the form. - * @return SimpleEncoding Submitted values or false - * if there is no such button in the - * form. - * @access public - */ - function submitImageByLabel($label, $x, $y, $additional = false) { - return $this->_submitImageBySelector( - new SimpleLabelSelector($label), - $x, - $y, - $additional); - } - - /** - * Gets the submit values for an image identified by the ID. - * @param string $name Image name to search for. - * @param integer $x X-coordinate of click. - * @param integer $y Y-coordinate of click. - * @param hash $additional Additional data for the form. - * @return SimpleEncoding Submitted values or false - * if there is no such button in the - * form. - * @access public - */ - function submitImageByName($name, $x, $y, $additional = false) { - return $this->_submitImageBySelector( - new SimpleNameSelector($name), - $x, - $y, - $additional); - } - - /** - * Gets the submit values for an image identified by the ID. - * @param string/integer $id Button ID attribute to search for. - * @param integer $x X-coordinate of click. - * @param integer $y Y-coordinate of click. - * @param hash $additional Additional data for the form. - * @return SimpleEncoding Submitted values or false - * if there is no such button in the - * form. - * @access public - */ - function submitImageById($id, $x, $y, $additional = false) { - return $this->_submitImageBySelector( - new SimpleIdSelector($id), - $x, - $y, - $additional); - } /** * Simply submits the form without the submit button @@ -613,7 +346,7 @@ * @access public */ function submit() { - return $this->_getEncoding(); + return $this->_encode(); } } -?> \ No newline at end of file +?> diff --git a/tests/test_tools/simpletest/frames.php b/tests/test_tools/simpletest/frames.php index 75951476..8eefbe8d 100644 --- a/tests/test_tools/simpletest/frames.php +++ b/tests/test_tools/simpletest/frames.php @@ -3,7 +3,7 @@ * Base include file for SimpleTest * @package SimpleTest * @subpackage WebTester - * @version $Id: frames.php,v 1.29 2004/11/30 05:33:56 lastcraft Exp $ + * @version $Id: frames.php,v 1.39 2005/09/09 01:42:29 lastcraft Exp $ */ /**#@+ @@ -12,7 +12,7 @@ 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 @@ -26,7 +26,7 @@ protected $_frames; protected $_focus; protected $_names; - + /** * Stashes the frameset page. Will make use of the * browser to fetch the sub frames recursively. @@ -38,7 +38,7 @@ $this->_focus = false; $this->_names = array(); } - + /** * Adds a parsed page to the frameset. * @param SimplePage $page Frame page. @@ -51,7 +51,7 @@ $this->_names[$name] = count($this->_frames) - 1; } } - + /** * Replaces existing frame with another. If the * frame is nested, then the call is passed down @@ -73,7 +73,7 @@ } $this->_frames[$index]->setFrame($path, $page); } - + /** * Accessor for current frame focus. Will be * false if no frame has focus. Will have the nested @@ -89,7 +89,7 @@ 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 @@ -106,7 +106,7 @@ } return $subject + 1; } - + /** * Sets the focus by index. The integer index starts from 1. * If already focused and the target frame also has frames, @@ -127,7 +127,7 @@ $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 @@ -148,7 +148,7 @@ } return false; } - + /** * Clears the frame focus. * @access public @@ -157,7 +157,7 @@ $this->_focus = false; $this->_clearNestedFramesFocus(); } - + /** * Clears the frame focus for any nested frames. * @access private @@ -167,7 +167,7 @@ $this->_frames[$i]->clearFrameFocus(); } } - + /** * Test for the presence of a frameset. * @return boolean Always true. @@ -176,7 +176,7 @@ function hasFrames() { return true; } - + /** * Accessor for frames information. * @return array/string Recursive hash of frame URL strings. @@ -192,7 +192,7 @@ } return $report; } - + /** * Accessor for raw text of either all the pages or * the frame in focus. @@ -209,7 +209,7 @@ } return $raw; } - + /** * Accessor for plain text of either all the pages or * the frame in focus. @@ -226,7 +226,7 @@ } return trim($raw); } - + /** * Accessor for last error. * @return string Error from last response. @@ -238,7 +238,7 @@ } return $this->_frameset->getTransportError(); } - + /** * Request method used to fetch this frame. * @return string GET, POST or HEAD. @@ -250,7 +250,7 @@ } return $this->_frameset->getMethod(); } - + /** * Original resource name. * @return SimpleUrl Current url. @@ -265,7 +265,7 @@ } return $url; } - + /** * Original request data. * @return mixed Sent content. @@ -277,7 +277,7 @@ } return $this->_frameset->getRequestData(); } - + /** * Accessor for current MIME type. * @return string MIME type as string; e.g. 'text/html' @@ -289,7 +289,7 @@ } return $this->_frameset->getMimeType(); } - + /** * Accessor for last response code. * @return integer Last HTTP response code received. @@ -301,7 +301,7 @@ } return $this->_frameset->getResponseCode(); } - + /** * Accessor for last Authentication type. Only valid * straight after a challenge (401). @@ -314,7 +314,7 @@ } return $this->_frameset->getAuthentication(); } - + /** * Accessor for last Authentication realm. Only valid * straight after a challenge (401). @@ -327,7 +327,7 @@ } return $this->_frameset->getRealm(); } - + /** * Accessor for outgoing header information. * @return string Header block. @@ -339,7 +339,7 @@ } return $this->_frameset->getRequest(); } - + /** * Accessor for raw header information. * @return string Header block. @@ -351,7 +351,7 @@ } return $this->_frameset->getHeaders(); } - + /** * Accessor for parsed title. * @return string Title or false if no title is present. @@ -360,7 +360,7 @@ function getTitle() { return $this->_frameset->getTitle(); } - + /** * Accessor for a list of all fixed links. * @return array List of urls with scheme of @@ -377,7 +377,7 @@ } return array_values(array_unique($urls)); } - + /** * Accessor for a list of all relative links. * @return array List of urls without hostname. @@ -393,7 +393,7 @@ } return array_values(array_unique($urls)); } - + /** * Accessor for URLs by the link label. Label will match * regardess of whitespace issues and case. @@ -417,7 +417,7 @@ } return $urls; } - + /** * Accessor for a URL by the id attribute. If in a frameset * then the first link found with that ID attribute is @@ -438,7 +438,7 @@ } return false; } - + /** * Attaches the intended frame index to a list of URLs. * @param array $urls List of SimpleUrls. @@ -456,85 +456,35 @@ } return $tagged; } - - /** - * Finds a held form by button label. Will only - * search correctly built forms. The first form found - * either within the focused frame, or across frames, - * will be the one returned. - * @param string $label Button label, default 'Submit'. - * @return SimpleForm Form object containing the button. - * @access public - */ - function getFormBySubmitLabel($label) { - return $this->_findForm('getFormBySubmitLabel', $label); - } - + /** * Finds a held form by button label. Will only - * search correctly built forms. The first form found - * either within the focused frame, or across frames, - * will be the one returned. - * @param string $name Button name attribute. - * @return SimpleForm Form object containing the button. + * search correctly built forms. + * @param SimpleSelector $selector Button finder. + * @return SimpleForm Form object containing + * the button. * @access public */ - function getFormBySubmitName($name) { - return $this->_findForm('getFormBySubmitName', $name); - } - - /** - * Finds a held form by button id. Will only - * search correctly built forms. The first form found - * either within the focused frame, or across frames, - * will be the one returned. - * @param string $id Button ID attribute. - * @return SimpleForm Form object containing the button. - * @access public - */ - function getFormBySubmitId($id) { - return $this->_findForm('getFormBySubmitId', $id); - } - - /** - * Finds a held form by image label. Will only - * search correctly built forms. The first form found - * either within the focused frame, or across frames, - * will be the one returned. - * @param string $label Usually the alt attribute. - * @return SimpleForm Form object containing the image. - * @access public - */ - function getFormByImageLabel($label) { - return $this->_findForm('getFormByImageLabel', $label); - } - - /** - * Finds a held form by image button id. Will only - * search correctly built forms. The first form found - * either within the focused frame, or across frames, - * will be the one returned. - * @param string $name Image name. - * @return SimpleForm Form object containing the image. - * @access public - */ - function getFormByImageName($name) { - return $this->_findForm('getFormByImageName', $name); + function &getFormBySubmit($selector) { + $form = $this->_findForm('getFormBySubmit', $selector); + return $form; } - + /** - * Finds a held form by image button id. Will only - * search correctly built forms. The first form found - * either within the focused frame, or across frames, - * will be the one returned. - * @param string $id Image ID attribute. - * @return SimpleForm Form object containing the image. + * 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 getFormByImageId($id) { - return $this->_findForm('getFormByImageId', $id); + function &getFormByImage($selector) { + $form = $this->_findForm('getFormByImage', $selector); + return $form; } - + /** * Finds a held form by the form ID. A way of * identifying a specific form when we have control @@ -545,25 +495,27 @@ * @return SimpleForm Form object containing the matching ID. * @access public */ - function getFormById($id) { - return $this->_findForm('getFormById', $id); + function &getFormById($id) { + $form = $this->_findForm('getFormById', $id); + return $form; } - + /** * General form finder. Will search all the frames or * just the one in focus. * @param string $method Method to use to find in a page. * @param string $attribute Label, name or ID. * @return SimpleForm Form object containing the matching ID. - * @access protected + * @access private */ - function _findForm($method, $attribute) { + function &_findForm($method, $attribute) { if (is_integer($this->_focus)) { - return $this->_findFormInFrame( + $form = $this->_findFormInFrame( $this->_frames[$this->_focus], $this->_focus, $method, $attribute); + return $form; } for ($i = 0; $i < count($this->_frames); $i++) { $form = $this->_findFormInFrame( @@ -575,9 +527,10 @@ return $form; } } - return null; + $null = null; + return $null; } - + /** * Finds a form in a page using a form finding method. Will * also tag the form with the frame name it belongs in. @@ -586,83 +539,45 @@ * @param string $method Method to use to find in a page. * @param string $attribute Label, name or ID. * @return SimpleForm Form object containing the matching ID. - * @access protected + * @access private */ - function _findFormInFrame($page, $index, $method, $attribute) { + function &_findFormInFrame($page, $index, $method, $attribute) { $form = $this->_frames[$index]->$method($attribute); if (isset($form)) { $form->setDefaultTarget($this->_getPublicNameFromIndex($index)); } return $form; } - + /** * Sets a field on each form in which the field is * available. - * @param string $name Field name. - * @param string $value Value to set field to. - * @return boolean True if value is valid. - * @access public - */ - function setField($name, $value) { - if (is_integer($this->_focus)) { - $this->_frames[$this->_focus]->setField($name, $value); - } else { - for ($i = 0; $i < count($this->_frames); $i++) { - $this->_frames[$i]->setField($name, $value); - } - } - } - - /** - * Sets a field on the form in which the unique field is - * available. - * @param string/integer $id Field ID attribute. - * @param string $value Value to set field to. - * @return boolean True if value is valid. + * @param SimpleSelector $selector Field finder. + * @param string $value Value to set field to. + * @return boolean True if value is valid. * @access public */ - function setFieldById($id, $value) { + function setField($selector, $value) { if (is_integer($this->_focus)) { - $this->_frames[$this->_focus]->setFieldById($id, $value); + $this->_frames[$this->_focus]->setField($selector, $value); } else { for ($i = 0; $i < count($this->_frames); $i++) { - $this->_frames[$i]->setFieldById($id, $value); + $this->_frames[$i]->setField($selector, $value); } } } - - /** - * Accessor for a form element value within a frameset. - * Finds the first match amongst the frames. - * @param string $name Field name. - * @return string/boolean A string if the field is - * present, false if unchecked - * and null if missing. - * @access public - */ - function getField($name) { - for ($i = 0; $i < count($this->_frames); $i++) { - $value = $this->_frames[$i]->getField($name); - if (isset($value)) { - return $value; - } - } - return null; - } - + /** * Accessor for a form element value within a page. - * Finds the first match. - * @param string/integer $id Field ID attribute. - * @return string/boolean A string if the field is - * present, false if unchecked - * and null if missing. + * @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 getFieldById($id) { + function getField($selector) { for ($i = 0; $i < count($this->_frames); $i++) { - $value = $this->_frames[$i]->getFieldById($id); + $value = $this->_frames[$i]->getField($selector); if (isset($value)) { return $value; } diff --git a/tests/test_tools/simpletest/http.php b/tests/test_tools/simpletest/http.php index fa27de9c..965fac80 100644 --- a/tests/test_tools/simpletest/http.php +++ b/tests/test_tools/simpletest/http.php @@ -3,223 +3,17 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage WebTester - * @version $Id: http.php,v 1.98 2005/02/02 23:25:23 lastcraft Exp $ + * @version $Id: http.php,v 1.112 2005/12/07 18:04:58 lastcraft Exp $ */ /**#@+ * include other SimpleTest class files */ require_once(dirname(__FILE__) . '/socket.php'); + require_once(dirname(__FILE__) . '/cookies.php'); 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 { - protected $_host; - protected $_name; - protected $_value; - protected $_path; - protected $_expiry; - protected $_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 SimpleCookie($name, $value = false, $path = false, $expiry = false, $is_secure = false) { - $this->_host = false; - $this->_name = $name; - $this->_value = $value; - $this->_path = ($path ? $this->_fixPath($path) : "/"); - $this->_expiry = false; - if (is_string($expiry)) { - $this->_expiry = strtotime($expiry); - } elseif (is_integer($expiry)) { - $this->_expiry = $expiry; - } - $this->_is_secure = $is_secure; - } - - /** - * Sets the host. The cookie rules determine - * that the first two parts are taken for - * certain TLDs and three for others. If the - * new host does not match these rules then the - * call will fail. - * @param string $host New hostname. - * @return boolean True if hostname is valid. - * @access public - */ - function setHost($host) { - if ($host = $this->_truncateHost($host)) { - $this->_host = $host; - return true; - } - return false; - } - - /** - * Accessor for the truncated host to which this - * cookie applies. - * @return string Truncated hostname. - * @access public - */ - function getHost() { - return $this->_host; - } - - /** - * Test for a cookie being valid for a host name. - * @param string $host Host to test against. - * @return boolean True if the cookie would be valid - * here. - */ - function isValidHost($host) { - return ($this->_truncateHost($host) === $this->getHost()); - } - - /** - * Extracts just the domain part that determines a - * cookie's host validity. - * @param string $host Host name to truncate. - * @return string Domain or false on a bad host. - * @access private - */ - function _truncateHost($host) { - $tlds = SimpleUrl::getAllTopLevelDomains(); - if (preg_match('/[a-z\-]+\.(' . $tlds . ')$/i', $host, $matches)) { - return $matches[0]; - } elseif (preg_match('/[a-z\-]+\.[a-z\-]+\.[a-z\-]+$/i', $host, $matches)) { - return $matches[0]; - } - return false; - } - - /** - * Accessor for name. - * @return string Cookie key. - * @access public - */ - function getName() { - return $this->_name; - } - - /** - * Accessor for value. A deleted cookie will - * have an empty string for this. - * @return string Cookie value. - * @access public - */ - function getValue() { - return $this->_value; - } - - /** - * Accessor for path. - * @return string Valid cookie path. - * @access public - */ - function getPath() { - return $this->_path; - } - - /** - * Tests a path to see if the cookie applies - * there. The test path must be longer or - * equal to the cookie path. - * @param string $path Path to test against. - * @return boolean True if cookie valid here. - * @access public - */ - function isValidPath($path) { - return (strncmp( - $this->_fixPath($path), - $this->getPath(), - strlen($this->getPath())) == 0); - } - - /** - * Accessor for expiry. - * @return string Expiry string. - * @access public - */ - function getExpiry() { - if (! $this->_expiry) { - return false; - } - return gmdate("D, d M Y H:i:s", $this->_expiry) . " GMT"; - } - - /** - * Test to see if cookie is expired against - * the cookie format time or timestamp. - * Will give true for a session cookie. - * @param integer/string $now Time to test against. Result - * will be false if this time - * is later than the cookie expiry. - * Can be either a timestamp integer - * or a cookie format date. - * @access public - */ - function isExpired($now) { - if (! $this->_expiry) { - return true; - } - if (is_string($now)) { - $now = strtotime($now); - } - return ($this->_expiry < $now); - } - - /** - * Ages the cookie by the specified number of - * seconds. - * @param integer $interval In seconds. - * @public - */ - function agePrematurely($interval) { - if ($this->_expiry) { - $this->_expiry -= $interval; - } - } - - /** - * Accessor for the secure flag. - * @return boolean True if cookie needs SSL. - * @access public - */ - function isSecure() { - return $this->_is_secure; - } - - /** - * Adds a trailing and leading slash to the path - * if missing. - * @param string $path Path to fix. - * @access private - */ - function _fixPath($path) { - if (substr($path, 0, 1) != '/') { - $path = '/' . $path; - } - if (substr($path, -1, 1) != '/') { - $path .= '/'; - } - return $path; - } - } - /** * Creates HTTP headers for the end point of * a HTTP request. @@ -278,7 +72,7 @@ * @return SimpleSocket New socket. * @access public */ - function createConnection($method, $timeout) { + function &createConnection($method, $timeout) { $default_port = ('https' == $this->_url->getScheme()) ? 443 : 80; $socket = $this->_createSocket( $this->_url->getScheme() ? $this->_url->getScheme() : 'http', @@ -302,11 +96,13 @@ * @return SimpleSocket/SimpleSecureSocket New socket. * @access protected */ - function _createSocket($scheme, $host, $port, $timeout) { + function &_createSocket($scheme, $host, $port, $timeout) { if (in_array($scheme, array('https'))) { - return new SimpleSecureSocket($host, $port, $timeout); + $socket = new SimpleSecureSocket($host, $port, $timeout); + } else { + $socket = new SimpleSocket($host, $port, $timeout); } - return new SimpleSocket($host, $port, $timeout); + return $socket; } } @@ -370,22 +166,23 @@ * @return SimpleSocket New socket. * @access public */ - function createConnection($method, $timeout) { + function &createConnection($method, $timeout) { $socket = $this->_createSocket( $this->_proxy->getScheme() ? $this->_proxy->getScheme() : 'http', $this->_proxy->getHost(), $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080, $timeout); - if (! $socket->isError()) { - $socket->write($this->_getRequestLine($method) . "\r\n"); - $socket->write($this->_getHostLine() . "\r\n"); - if ($this->_username && $this->_password) { - $socket->write('Proxy-Authorization: Basic ' . - base64_encode($this->_username . ':' . $this->_password) . - "\r\n"); - } - $socket->write("Connection: close\r\n"); + 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; } } @@ -398,42 +195,41 @@ */ class SimpleHttpRequest { protected $_route; - protected $_method; protected $_encoding; protected $_headers; protected $_cookies; /** - * Saves the URL ready for fetching. - * @param SimpleRoute $route Request route. - * @param string $method HTTP request method, - * usually GET. + * 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 or false. + * request. * @access public */ - function SimpleHttpRequest($route, $method, $encoding = false) { + function SimpleHttpRequest($route, $encoding) { $this->_route = $route; - $this->_method = $method; $this->_encoding = $encoding; $this->_headers = array(); $this->_cookies = array(); } /** - * Fetches the content and parses the headers. + * Dispatches the content to the route's socket. * @param integer $timeout Connection timeout. * @return SimpleHttpResponse A response which may only have - * an error. + * an error, but hopefully has a + * complete web page. * @access public */ - function fetch($timeout) { - $socket = $this->_route->createConnection($this->_method, $timeout); - if ($socket->isError()) { - return $this->_createResponse($socket); + function &fetch($timeout) { + $socket = $this->_route->createConnection($this->_encoding->getMethod(), $timeout); + if (! $socket->isError()) { + $this->_dispatchRequest($socket, $this->_encoding); } - $this->_dispatchRequest($socket, $this->_method, $this->_encoding); - return $this->_createResponse($socket); + $response = $this->_createResponse($socket); + return $response; } /** @@ -444,38 +240,21 @@ * @param SimpleFormEncoding $encoding Content to send with request. * @access private */ - function _dispatchRequest($socket, $method, $encoding) { - if ($encoding || ($method == 'POST')) { - $socket->write("Content-Length: " . $this->_getContentLength($encoding) . "\r\n"); - $socket->write("Content-Type: application/x-www-form-urlencoded\r\n"); - } + function _dispatchRequest($socket, $encoding) { foreach ($this->_headers as $header_line) { $socket->write($header_line . "\r\n"); } if (count($this->_cookies) > 0) { - $socket->write("Cookie: " . $this->_marshallCookies($this->_cookies) . "\r\n"); + $socket->write("Cookie: " . implode(";", $this->_cookies) . "\r\n"); } + $encoding->writeHeadersTo($socket); $socket->write("\r\n"); - if ($encoding) { - $socket->write($encoding->asString()); - } - } - - /** - * Calculates the length of the encoded content. - * @param SimpleFormEncoding $encoding Content to send with - * request or false. - */ - function _getContentLength($encoding) { - if (! $encoding) { - return 0; - } - return (integer)strlen($encoding->asString()); + $encoding->writeTo($socket); } /** * Adds a header line to the request. - * @param string $header_line Text of header line. + * @param string $header_line Text of full header line. * @access public */ function addHeaderLine($header_line) { @@ -483,27 +262,14 @@ } /** - * Adds a cookie to the request. - * @param SimpleCookie $cookie Additional cookie. + * 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 setCookie($cookie) { - $this->_cookies[] = $cookie; - } - - /** - * Serialises the cookie hash ready for - * transmission. - * @param hash $cookies Parsed cookies. - * @return array Cookies in header form. - * @access private - */ - function _marshallCookies($cookies) { - $cookie_pairs = array(); - foreach ($cookies as $cookie) { - $cookie_pairs[] = $cookie->getName() . "=" . $cookie->getValue(); - } - return implode(";", $cookie_pairs); + function readCookiesFromJar($jar, $url) { + $this->_cookies = $jar->selectAsPairs($url); } /** @@ -512,12 +278,12 @@ * @return SimpleHttpResponse Parsed response object. * @access protected */ - function _createResponse($socket) { - return new SimpleHttpResponse( + function &_createResponse($socket) { + $response = new SimpleHttpResponse( $socket, - $this->_method, $this->_route->getUrl(), $this->_encoding); + return $response; } } @@ -642,12 +408,20 @@ } /** - * Accessor for any new cookies. - * @return array List of new cookies. + * 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 getNewCookies() { - return $this->_cookies; + function writeCookiesToJar($jar, $url) { + foreach ($this->_cookies as $cookie) { + $jar->setCookie( + $cookie->getName(), + $cookie->getValue(), + $url->getHost(), + $cookie->getPath(), + $cookie->getExpiry()); + } } /** @@ -657,7 +431,7 @@ * @access protected */ function _parseHeaderLine($header_line) { - if (preg_match('/HTTP\/(\d+\.\d+)\s+(.*?)\s/i', $header_line, $matches)) { + if (preg_match('/HTTP\/(\d+\.\d+)\s+(\d+)/i', $header_line, $matches)) { $this->_http_version = $matches[1]; $this->_response_code = $matches[2]; } @@ -705,9 +479,8 @@ * @subpackage WebTester */ class SimpleHttpResponse extends SimpleStickyError { - protected $_method; protected $_url; - protected $_request_data; + protected $_encoding; protected $_sent; protected $_content; protected $_headers; @@ -717,16 +490,14 @@ * content and headers. * @param SimpleSocket $socket Network connection to fetch * response text from. - * @param string $method HTTP request method. * @param SimpleUrl $url Resource name. - * @param mixed $request_data Record of content sent. + * @param mixed $encoding Record of content sent. * @access public */ - function SimpleHttpResponse($socket, $method, $url, $request_data = '') { + function SimpleHttpResponse($socket, $url, $encoding) { $this->SimpleStickyError(); - $this->_method = $method; $this->_url = $url; - $this->_request_data = $request_data; + $this->_encoding = $encoding; $this->_sent = $socket->getSent(); $this->_content = false; $raw = $this->_readAll($socket); @@ -747,7 +518,7 @@ $this->_setError('Nothing fetched'); $this->_headers = new SimpleHttpHeaders(''); } elseif (! strstr($raw, "\r\n\r\n")) { - $this->_setError('Could not parse headers'); + $this->_setError('Could not split headers from content'); $this->_headers = new SimpleHttpHeaders($raw); } else { list($headers, $this->_content) = split("\r\n\r\n", $raw, 2); @@ -761,7 +532,7 @@ * @access public */ function getMethod() { - return $this->_method; + return $this->_encoding->getMethod(); } /** @@ -779,7 +550,7 @@ * @access public */ function getRequestData() { - return $this->_request_data; + return $this->_encoding; } /** diff --git a/tests/test_tools/simpletest/invoker.php b/tests/test_tools/simpletest/invoker.php new file mode 100644 index 00000000..5274bf5e --- /dev/null +++ b/tests/test_tools/simpletest/invoker.php @@ -0,0 +1,139 @@ +_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 { + protected $_invoker; + + /** + * Stores the invoker to wrap. + * @param SimpleInvoker $invoker Test method runner. + */ + function SimpleInvokerDecorator($invoker) { + $this->_invoker = $invoker; + } + + /** + * Accessor for test case being run. + * @return SimpleTestCase Test case. + * @access public + */ + 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); + } + } +?> diff --git a/tests/test_tools/simpletest/mock_objects.php b/tests/test_tools/simpletest/mock_objects.php index d39eb84e..0b003491 100644 --- a/tests/test_tools/simpletest/mock_objects.php +++ b/tests/test_tools/simpletest/mock_objects.php @@ -3,37 +3,36 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage MockObjects - * @version $Id: mock_objects.php,v 1.61 2005/02/13 01:09:25 lastcraft Exp $ + * @version $Id: mock_objects.php,v 1.90 2006/02/05 19:35:31 lastcraft Exp $ */ /**#@+ * include SimpleTest files */ require_once(dirname(__FILE__) . '/expectation.php'); - require_once(dirname(__FILE__) . '/options.php'); + require_once(dirname(__FILE__) . '/simpletest.php'); require_once(dirname(__FILE__) . '/dumper.php'); + if (version_compare(phpversion(), '5') >= 0) { + require_once(dirname(__FILE__) . '/reflection_php5.php'); + } else { + require_once(dirname(__FILE__) . '/reflection_php4.php'); + } /**#@-*/ - + /** * Default character simpletest will substitute for any value */ - define('MOCK_WILDCARD', '*'); - + if (! defined('MOCK_ANYTHING')) { + define('MOCK_ANYTHING', '*'); + } + /** * A wildcard expectation always matches. * @package SimpleTest * @subpackage MockObjects */ - class WildcardExpectation extends SimpleExpectation { - - /** - * Chains constructor only. - * @access public - */ - function WildcardExpectation() { - $this->SimpleExpectation(); - } - + class AnythingExpectation extends SimpleExpectation { + /** * Tests the expectation. Always true. * @param mixed $compare Ignored. @@ -43,7 +42,7 @@ function test($compare) { return true; } - + /** * Returns a human readable test message. * @param mixed $compare Comparison value. @@ -53,10 +52,10 @@ */ function testMessage($compare) { $dumper = $this->_getDumper(); - return 'Wildcard always matches [' . $dumper->describeValue($compare) . ']'; + return 'Anything always matches [' . $dumper->describeValue($compare) . ']'; } } - + /** * Parameter comparison assertion. * @package SimpleTest @@ -64,7 +63,7 @@ */ class ParametersExpectation extends SimpleExpectation { protected $_expected; - + /** * Sets the expected parameter list. * @param array $parameters Array of parameters including @@ -80,7 +79,7 @@ $this->SimpleExpectation($message); $this->_expected = $expected; } - + /** * Tests the assertion. True if correct. * @param array $parameters Comparison values. @@ -101,7 +100,7 @@ } return true; } - + /** * Tests an individual parameter. * @param mixed $parameter Value to test. @@ -114,7 +113,7 @@ $comparison = $this->_coerceToExpectation($expected); return $comparison->test($parameter); } - + /** * Returns a human readable test message. * @param array $comparison Incoming parameter list. @@ -131,7 +130,7 @@ return $this->_describeDifference($this->_expected, $parameters); } } - + /** * Message to display if expectation differs from * the parameters actually received. @@ -157,7 +156,7 @@ } return "Parameter expectation differs at " . implode(" and ", $messages); } - + /** * Creates an identical expectation if the * object/value is not already some type @@ -167,12 +166,12 @@ * @access private */ function _coerceToExpectation($expected) { - if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) { + if (SimpleExpectation::isExpectation($expected)) { return $expected; } return new IdenticalExpectation($expected); } - + /** * Renders the argument list as a string for * messages. @@ -191,14 +190,14 @@ return implode(', ', $descriptions); } } - + /** * Confirms that the number of calls on a method is as expected. */ class CallCountExpectation extends SimpleExpectation { protected $_method; protected $_count; - + /** * Stashes the method and expected count for later * reporting. @@ -211,7 +210,7 @@ $this->_count = $count; $this->SimpleExpectation($message); } - + /** * Tests the assertion. True if correct. * @param integer $compare Measured call count. @@ -221,7 +220,7 @@ function test($compare) { return ($this->_count == $compare); } - + /** * Reports the comparison. * @param integer $compare Measured call count. @@ -234,14 +233,14 @@ '] got [' . $compare . ']'; } } - + /** * Confirms that the number of calls on a method is as expected. */ class MinimumCallCountExpectation extends SimpleExpectation { protected $_method; protected $_count; - + /** * Stashes the method and expected count for later * reporting. @@ -254,7 +253,7 @@ $this->_count = $count; $this->SimpleExpectation($message); } - + /** * Tests the assertion. True if correct. * @param integer $compare Measured call count. @@ -264,7 +263,7 @@ function test($compare) { return ($this->_count <= $compare); } - + /** * Reports the comparison. * @param integer $compare Measured call count. @@ -277,14 +276,14 @@ '] got [' . $compare . ']'; } } - + /** * Confirms that the number of calls on a method is as expected. */ class MaximumCallCountExpectation extends SimpleExpectation { protected $_method; protected $_count; - + /** * Stashes the method and expected count for later * reporting. @@ -297,7 +296,7 @@ $this->_count = $count; $this->SimpleExpectation($message); } - + /** * Tests the assertion. True if correct. * @param integer $compare Measured call count. @@ -307,7 +306,7 @@ function test($compare) { return ($this->_count >= $compare); } - + /** * Reports the comparison. * @param integer $compare Measured call count. @@ -329,7 +328,7 @@ */ class CallMap { protected $_map; - + /** * Creates an empty call map. * @access public @@ -337,7 +336,7 @@ function CallMap() { $this->_map = array(); } - + /** * Stashes a value against a method call. * @param array $parameters Arguments including wildcards. @@ -347,7 +346,7 @@ function addValue($parameters, $value) { $this->addReference($parameters, $value); } - + /** * Stashes a reference against a method call. * @param array $parameters Array of arguments (including wildcards). @@ -360,7 +359,7 @@ $this->_map[$place]["params"] = new ParametersExpectation($parameters); $this->_map[$place]["content"] = $reference; } - + /** * Searches the call list for a matching parameter * set. Returned by reference. @@ -370,14 +369,15 @@ * slot, otherwise null. * @access public */ - function findFirstMatch($parameters) { + function &findFirstMatch($parameters) { $slot = $this->_findFirstSlot($parameters); if (!isset($slot)) { - return null; + $null = null; + return $null; } return $slot["content"]; } - + /** * Searches the call list for a matching parameter * set. True if successful. @@ -389,7 +389,7 @@ function isMatch($parameters) { return ($this->_findFirstSlot($parameters) != null); } - + /** * Searches the map for a matching item. * @param array $parameters Parameters to search by @@ -397,78 +397,100 @@ * @return array Reference to slot or null. * @access private */ - function _findFirstSlot($parameters) { + function &_findFirstSlot($parameters) { $count = count($this->_map); for ($i = 0; $i < $count; $i++) { if ($this->_map[$i]["params"]->test($parameters)) { return $this->_map[$i]; } } - return null; + $null = null; + return $null; } } - + /** * An empty collection of methods that can have their - * return values set. Used for prototyping. + * return values set and expectations made of the + * calls upon them. The mock will assert the + * expectations against it's attached test case in + * addition to the server stub behaviour. * @package SimpleTest * @subpackage MockObjects */ - class SimpleStub { - protected $_wildcard; - protected $_is_strict; + class SimpleMock { + protected $_wildcard = MOCK_ANYTHING; + protected $_is_strict = true; protected $_returns; protected $_return_sequence; protected $_call_counts; - + protected $_expected_counts; + protected $_max_counts; + protected $_expected_args; + protected $_expected_args_at; + /** - * Sets up the wildcard and everything else empty. - * @param mixed $wildcard Parameter matching wildcard. - * @param boolean $is_strict Enables method name checks. - * @access public + * Creates an empty return list and expectation list. + * All call counts are set to zero. + * @param SimpleTestCase $test Test case to test expectations in. + * @param mixed $wildcard Parameter matching wildcard. + * @param boolean $is_strict Enables method name checks on + * expectations. */ - function SimpleStub($wildcard, $is_strict = true) { - $this->_wildcard = $wildcard; - $this->_is_strict = $is_strict; + function SimpleMock() { $this->_returns = array(); $this->_return_sequence = array(); $this->_call_counts = array(); + $test = $this->_getCurrentTestCase(); + $test->tell($this); + $this->_expected_counts = array(); + $this->_max_counts = array(); + $this->_expected_args = array(); + $this->_expected_args_at = array(); } - + /** - * Replaces wildcard matches with wildcard - * expectations in the argument list. - * @param array $args Raw argument list. - * @return array Argument list with - * expectations. - * @access private + * Disables a name check when setting expectations. + * This hack is needed for the partial mocks. + * @access public */ - function _replaceWildcards($args) { - if ($args === false) { - return false; - } - for ($i = 0; $i < count($args); $i++) { - if ($args[$i] === $this->_wildcard) { - $args[$i] = new WildcardExpectation(); - } - } - return $args; + function disableExpectationNameChecks() { + $this->_is_strict = false; } - + /** - * Returns the expected value for the method name. - * @param string $method Name of method to simulate. - * @param array $args Arguments as an array. - * @return mixed Stored return. + * Changes the default wildcard object. + * @param mixed $wildcard Parameter matching wildcard. + * @access public + */ + function setWildcard($wildcard) { + $this->_wildcard = $wildcard; + } + + /** + * Finds currently running test. + * @return SimpeTestCase Current test case. + * @access protected + */ + function &_getCurrentTestCase() { + return SimpleTest::getCurrent(); + } + + /** + * Die if bad arguments array is passed + * @param mixed $args The arguments value to be checked. + * @param string $task Description of task attempt. + * @return boolean Valid arguments * @access private */ - function _invoke($method, $args) { - $method = strtolower($method); - $step = $this->getCallCount($method); - $this->_addCall($method, $args); - return $this->_getReturn($method, $args, $step); + 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. @@ -477,13 +499,33 @@ * @access protected */ function _dieOnNoMethod($method, $task) { - if ($this->_is_strict && !method_exists($this, $method)) { + 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. + * @access private + */ + function _replaceWildcards($args) { + if ($args === false) { + return false; + } + for ($i = 0; $i < count($args); $i++) { + if ($args[$i] === $this->_wildcard) { + $args[$i] = new AnythingExpectation(); + } + } + return $args; + } + /** * Adds one to the call count of a method. * @param string $method Method called. @@ -496,7 +538,7 @@ } $this->_call_counts[$method]++; } - + /** * Fetches the call count of a method so far. * @param string $method Method name called. @@ -511,7 +553,7 @@ } return $this->_call_counts[$method]; } - + /** * Sets a return for a parameter list that will * be passed by value for all calls to this method. @@ -530,7 +572,7 @@ } $this->_returns[$method]->addValue($args, $value); } - + /** * Sets a return for a parameter list that will * be passed by value only when the required call count @@ -557,7 +599,7 @@ } $this->_return_sequence[$method][$timing]->addValue($args, $value); } - + /** * Sets a return for a parameter list that will * be passed by reference for all calls. @@ -576,7 +618,7 @@ } $this->_returns[$method]->addReference($args, $reference); } - + /** * Sets a return for a parameter list that will * be passed by value only when the required call count @@ -603,94 +645,7 @@ } $this->_return_sequence[$method][$timing]->addReference($args, $reference); } - - /** - * Finds the return value matching the incoming - * arguments. If there is no matching value found - * then an error is triggered. - * @param string $method Method name. - * @param array $args Calling arguments. - * @param integer $step Current position in the - * call history. - * @return mixed Stored return. - * @access protected - */ - function _getReturn($method, $args, $step) { - if (isset($this->_return_sequence[$method][$step])) { - if ($this->_return_sequence[$method][$step]->isMatch($args)) { - return $this->_return_sequence[$method][$step]->findFirstMatch($args); - } - } - if (isset($this->_returns[$method])) { - return $this->_returns[$method]->findFirstMatch($args); - } - return null; - } - } - - /** - * An empty collection of methods that can have their - * return values set and expectations made of the - * calls upon them. The mock will assert the - * expectations against it's attached test case in - * addition to the server stub behaviour. - * @package SimpleTest - * @subpackage MockObjects - */ - class SimpleMock extends SimpleStub { - protected $_test; - protected $_expected_counts; - protected $_max_counts; - protected $_expected_args; - protected $_expected_args_at; - - /** - * Creates an empty return list and expectation list. - * All call counts are set to zero. - * @param SimpleTestCase $test Test case to test expectations in. - * @param mixed $wildcard Parameter matching wildcard. - * @param boolean $is_strict Enables method name checks on - * expectations. - * @access public - */ - function SimpleMock($test, $wildcard, $is_strict = true) { - $this->SimpleStub($wildcard, $is_strict); - if (! $test) { - trigger_error('No unit tester for mock object', E_USER_ERROR); - return; - } - $this->_test = SimpleMock::registerTest($test); - $this->_expected_counts = array(); - $this->_max_counts = array(); - $this->_expected_args = array(); - $this->_expected_args_at = array(); - } - - /** - * Accessor for attached unit test so that when - * subclassed, new expectations can be added easily. - * @return SimpleTestCase Unit test passed in constructor. - * @access public - */ - function getTest() { - return $this->_test; - } - - /** - * Die if bad arguments array is passed - * @param mixed $args The arguments value to be checked. - * @param string $task Description of task attempt. - * @return boolean Valid arguments - * @access private - */ - function _checkArgumentsIsArray($args, $task) { - if (! is_array($args)) { - trigger_error( - "Cannot $task as \$args parameter is not an array", - E_USER_ERROR); - } - } - + /** * Sets up an expected call with a set of * expected parameters in that call. All @@ -702,15 +657,22 @@ * @param string $message Overridden message. * @access public */ - function expectArguments($method, $args, $message = '%s') { + function expect($method, $args, $message = '%s') { $this->_dieOnNoMethod($method, 'set expected arguments'); $this->_checkArgumentsIsArray($args, 'set expected arguments'); $args = $this->_replaceWildcards($args); - $message .= Mock::getExpectationLine(' at line [%d]'); + $message .= Mock::getExpectationLine(); $this->_expected_args[strtolower($method)] = new ParametersExpectation($args, $message); } - + + /** + * @deprecated + */ + function expectArguments($method, $args, $message = '%s') { + return $this->expect($method, $args, $message); + } + /** * Sets up an expected call with a set of * expected parameters in that call. The @@ -724,7 +686,7 @@ * @param string $message Overridden message. * @access public */ - function expectArgumentsAt($timing, $method, $args, $message = '%s') { + 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); @@ -732,11 +694,18 @@ $this->_expected_args_at[$timing] = array(); } $method = strtolower($method); - $message .= Mock::getExpectationLine(' at line [%d]'); + $message .= Mock::getExpectationLine(); $this->_expected_args_at[$timing][$method] = new ParametersExpectation($args, $message); } - + + /** + * @deprecated + */ + function expectArgumentsAt($timing, $method, $args, $message = '%s') { + return $this->expectAt($timing, $method, $args, $message); + } + /** * Sets an expectation for the number of times * a method will be called. The tally method @@ -749,11 +718,11 @@ */ function expectCallCount($method, $count, $message = '%s') { $this->_dieOnNoMethod($method, 'set expected call count'); - $message .= Mock::getExpectationLine(' at line [%d]'); + $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. @@ -765,11 +734,11 @@ */ function expectMaximumCallCount($method, $count, $message = '%s') { $this->_dieOnNoMethod($method, 'set maximum call count'); - $message .= Mock::getExpectationLine(' at line [%d]'); - $this->_max_counts[strtolower($method)] = + $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. @@ -781,11 +750,11 @@ */ function expectMinimumCallCount($method, $count, $message = '%s') { $this->_dieOnNoMethod($method, 'set minimum call count'); - $message .= Mock::getExpectationLine(' at line [%d]'); + $message .= Mock::getExpectationLine(); $this->_expected_counts[strtolower($method)] = new MinimumCallCountExpectation($method, $count, $message); } - + /** * Convenience method for barring a method * call. @@ -796,7 +765,7 @@ function expectNever($method, $message = '%s') { $this->expectMaximumCallCount($method, 0, $message); } - + /** * Convenience method for a single method * call. @@ -812,7 +781,7 @@ $this->expectArguments($method, $args, $message); } } - + /** * Convenience method for requiring a method * call. @@ -828,16 +797,22 @@ $this->expectArguments($method, $args, $message); } } - + /** - * Totals up the call counts and triggers a test - * assertion if a test is present for expected - * call counts. - * This method must be called explicitly for the call - * count assertions to be triggered. - * @access public + * @deprecated */ function tally() { + } + + /** + * 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 $method Current method name. + * @access public + */ + function atTestEnd($method) { foreach ($this->_expected_counts as $method => $expectation) { $this->_assertTrue( $expectation->test($this->getCallCount($method)), @@ -862,14 +837,40 @@ * @return mixed Stored return. * @access private */ - function _invoke($method, $args) { + function &_invoke($method, $args) { $method = strtolower($method); $step = $this->getCallCount($method); $this->_addCall($method, $args); $this->_checkExpectations($method, $args, $step); - return $this->_getReturn($method, $args, $step); + $result = $this->_getReturn($method, $args, $step); + 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. + * @access protected + */ + function &_getReturn($method, $args, $step) { + if (isset($this->_return_sequence[$method][$step])) { + if ($this->_return_sequence[$method][$step]->isMatch($args)) { + $result = $this->_return_sequence[$method][$step]->findFirstMatch($args); + return $result; + } + } + if (isset($this->_returns[$method])) { + $result = $this->_returns[$method]->findFirstMatch($args); + return $result; + } + $null = null; + return $null; } - + /** * Tests the arguments against expectations. * @param string $method Method to check. @@ -897,7 +898,7 @@ "Mock method [$method] -> " . $this->_expected_args[$method]->overlayMessage($args)); } } - + /** * Triggers an assertion on the held test case. * Should be overridden when using another test @@ -909,253 +910,173 @@ * @access protected */ function _assertTrue($assertion, $message) { - $test =SimpleMock::injectTest($this->_test); + $test = $this->_getCurrentTestCase(); $test->assertTrue($assertion, $message); } - - /** - * Stashes the test case for later recovery. - * @param SimpleTestCase $test Test case. - * @return string Key to find it again. - * @access public - * @static - */ - function registerTest($test) { - $registry =SimpleMock::_getRegistry(); - $registry[$class = get_class($test)] = $test; - return $class; - } - - /** - * Resolves the dependency on the test case. - * @param string $class Key to look up test case in. - * @return SimpleTestCase Test case to send results to. - * @access public - * @static - */ - function injectTest($key) { - $registry =SimpleMock::_getRegistry(); - return $registry[$key]; - } - - /** - * Registry for test cases. The reason for this is - * to break the reference between the test cases and - * the mocks. It was leading to a fatal error due to - * recursive dependencies during comparisons. See - * http://bugs.php.net/bug.php?id=31449 for the PHP - * bug. - * @return array List of references. - * @access private - * @static - */ - function _getRegistry() { - static $registry; - if (! isset($registry)) { - $registry = array(); - } - return $registry; - } } - + /** * Static methods only service class for code generation of - * server stubs. + * mock objects. * @package SimpleTest * @subpackage MockObjects */ - class Stub { - - /** - * Factory for server stub classes. - */ - function Stub() { - trigger_error('Stub factory methods are class only.'); - } - - /** - * Clones a class' interface and creates a stub version - * that can have return values set. - * @param string $class Class to clone. - * @param string $stub_class New class name. Default is - * the old name with "Stub" - * prepended. - * @param array $methods Additional methods to add beyond - * those in the cloned class. Use this - * to emulate the dynamic addition of - * methods in the cloned class or when - * the class hasn't been written yet. - * @static + class Mock { + + /** + * Factory for mock object classes. * @access public */ - function generate($class, $stub_class = false, $methods = false) { - if (! SimpleTestCompatibility::classExists($class)) { - return false; - } - if (! $stub_class) { - $stub_class = "Stub" . $class; - } - if (SimpleTestCompatibility::classExists($stub_class)) { - return false; - } - return eval(Stub::_createClassCode( - $class, - $stub_class, - $methods ? $methods : array()) . " return true;"); + function Mock() { + trigger_error('Mock factory methods are class only.'); } - + /** - * The new server stub class code in string form. - * @param string $class Class to clone. - * @param string $mock_class New class name. - * @param array $methods Additional methods. + * Clones a class' interface and creates a mock version + * that can have return values and expectations set. + * @param string $class Class to clone. + * @param string $mock_class New class name. Default is + * the old name with "Mock" + * prepended. + * @param array $methods Additional methods to add beyond + * those in th cloned class. Use this + * to emulate the dynamic addition of + * methods in the cloned class or when + * the class hasn't been written yet. * @static - * @access private + * @access public */ - function _createClassCode($class, $stub_class, $methods) { - $stub_base = SimpleTestOptions::getStubBaseClass(); - $code = "class $stub_class extends $stub_base {\n"; - $code .= " function $stub_class(\$wildcard = MOCK_WILDCARD) {\n"; - $code .= " \$this->$stub_base(\$wildcard);\n"; - $code .= " }\n"; - $code .= Stub::_createHandlerCode($class, $stub_base, $methods); - $code .= "}\n"; - return $code; + function generate($class, $mock_class = false, $methods = false) { + $generator = new MockGenerator($class, $mock_class); + return $generator->generate($methods); } - + /** - * Creates code within a class to generate replaced - * methods. All methods call the _invoke() handler - * with the method name and the arguments in an - * array. - * @param string $class Class to clone. - * @param string $base Base mock/stub class with methods that - * cannot be cloned. Otherwise you - * would be stubbing the accessors used - * to set the stubs. - * @param array $methods Additional methods. + * Generates a version of a class with selected + * methods mocked only. Inherits the old class + * and chains the mock methods of an aggregated + * mock object. + * @param string $class Class to clone. + * @param string $mock_class New class name. + * @param array $methods Methods to be overridden + * with mock versions. * @static - * @access private + * @access public */ - function _createHandlerCode($class, $base, $methods) { - $code = ""; - $methods = array_merge($methods, get_class_methods($class)); - foreach ($methods as $method) { - if (Stub::_isSpecialMethod($method)) { - continue; - } - if (in_array($method, get_class_methods($base))) { - continue; - } - $code .= " function $method() {\n"; - $code .= " \$args = func_get_args();\n"; - $code .= " return \$this->_invoke(\"$method\", \$args);\n"; - $code .= " }\n"; - } - return $code; + function generatePartial($class, $mock_class, $methods) { + $generator = new MockGenerator($class, $mock_class); + return $generator->generatePartial($methods); } - + /** - * Tests to see if a special PHP method is about to - * be stubbed by mistake. - * @param string $method Method name. - * @return boolean True if special. - * @access private + * Uses a stack trace to find the line of an assertion. + * @param array $stack Stack frames top most first. Only + * needed if not using the PHP + * backtrace function. + * @return string Location of first expect* + * method embedded in format string. + * @access public * @static */ - function _isSpecialMethod($method) { - return in_array( - strtolower($method), - array('__construct', '__clone', '__get', '__set', '__call')); + function getExpectationLine($stack = false) { + if ($stack === false) { + $stack = SimpleTestCompatibility::getStackTrace(); + } + return SimpleDumper::getFormattedAssertionLine($stack); } } - + /** - * Static methods only service class for code generation of - * mock objects. + * @deprecated + */ + class Stub extends Mock { + } + + /** + * Service class for code generation of mock objects. * @package SimpleTest * @subpackage MockObjects */ - class Mock { - - /** - * Factory for mock object classes. - * @access public - */ - function Mock() { - trigger_error("Mock factory methods are class only."); + class MockGenerator { + protected $_class; + protected $_mock_class; + protected $_mock_base; + protected $_reflection; + + function MockGenerator($class, $mock_class) { + $this->_class = $class; + $this->_mock_class = $mock_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 string $class Class to clone. - * @param string $mock_class New class name. Default is - * the old name with "Mock" - * prepended. * @param array $methods Additional methods to add beyond * those in th cloned class. Use this * to emulate the dynamic addition of * methods in the cloned class or when * the class hasn't been written yet. - * @static * @access public */ - function generate($class, $mock_class = false, $methods = false) { - if (! SimpleTestCompatibility::classExists($class)) { + function generate($methods) { + if (! $this->_reflection->classOrInterfaceExists()) { return false; } - if (! $mock_class) { - $mock_class = "Mock" . $class; + if (! $this->_mock_class) { + $this->_mock_class = 'Mock' . $this->_class; } - if (SimpleTestCompatibility::classExists($mock_class)) { + $mock_reflection = new SimpleReflection($this->_mock_class); + if ($mock_reflection->classExistsSansAutoload()) { return false; } - return eval(Mock::_createClassCode( - $class, - $mock_class, - $methods ? $methods : array()) . " return true;"); + return eval( + $this->_createClassCode($methods ? $methods : array()) . + " return true;"); } - + /** * Generates a version of a class with selected * methods mocked only. Inherits the old class * and chains the mock methods of an aggregated * mock object. - * @param string $class Class to clone. - * @param string $mock_class New class name. * @param array $methods Methods to be overridden * with mock versions. - * @static * @access public */ - function generatePartial($class, $mock_class, $methods) { - if (! SimpleTestCompatibility::classExists($class)) { + function generatePartial($methods) { + if (! $this->_reflection->classExists($this->_class)) { return false; } - if (SimpleTestCompatibility::classExists($mock_class)) { + $mock_reflection = new SimpleReflection($this->_mock_class); + if ($mock_reflection->classExistsSansAutoload()) { trigger_error("Partial mock class [$mock_class] already exists"); return false; } - return eval(Mock::_extendClassCode($class, $mock_class, $methods)); + return eval($this->_extendClassCode($methods)); } /** * The new mock class code as a string. - * @param string $class Class to clone. - * @param string $mock_class New class name. * @param array $methods Additional methods. * @return string Code for new mock class. - * @static * @access private */ - function _createClassCode($class, $mock_class, $methods) { - $mock_base = SimpleTestOptions::getMockBaseClass(); - $code = "class $mock_class extends $mock_base {\n"; - $code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n"; - $code .= " \$this->$mock_base(\$test, \$wildcard);\n"; + 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"; - $code .= Stub::_createHandlerCode($class, $mock_base, $methods); + $code .= $this->_createHandlerCode($methods); $code .= "}\n"; return $code; } @@ -1164,30 +1085,67 @@ * The extension class code as a string. The class * composites a mock object and chains mocked methods * to it. - * @param string $class Class to extend. - * @param string $mock_class New class name. * @param array $methods Mocked methods. * @return string Code for a new class. - * @static * @access private */ - function _extendClassCode($class, $mock_class, $methods) { - $mock_base = SimpleTestOptions::getMockBaseClass(); - $code = "class $mock_class extends $class {\n"; + function _extendClassCode($methods) { + $code = "class " . $this->_mock_class . " extends " . $this->_class . " {\n"; $code .= " var \$_mock;\n"; - $code .= Mock::_addMethodList($methods); + $code .= $this->_addMethodList($methods); $code .= "\n"; - $code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n"; - $code .= " \$this->_mock = new $mock_base(\$test, \$wildcard, false);\n"; + $code .= " function " . $this->_mock_class . "() {\n"; + $code .= " \$this->_mock = new " . $this->_mock_base . "();\n"; + $code .= " \$this->_mock->disableExpectationNameChecks();\n"; $code .= " }\n"; - $code .= Mock::_chainMockReturns(); - $code .= Mock::_chainMockExpectations(); - $code .= Mock::_overrideMethods($methods); - $code .= SimpleTestOptions::getPartialMockCode(); + $code .= $this->_chainMockReturns(); + $code .= $this->_chainMockExpectations(); + $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. + * @access private + */ + 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; + } + + /** + * Tests to see if a special PHP method is about to + * be stubbed by mistake. + * @param string $method Method name. + * @return boolean True if special. + * @access private + */ + function _isConstructor($method) { + return in_array( + strtolower($method), + array('__construct', '__destruct', '__clone')); + } + /** * Creates a list of mocked methods for error checking. * @param array $methods Mocked methods. @@ -1197,7 +1155,7 @@ function _addMethodList($methods) { return " var \$_mocked_methods = array('" . implode("', '", $methods) . "');\n"; } - + /** * Creates code to abandon the expectation if not mocked. * @param string $alias Parameter name of method name. @@ -1207,11 +1165,12 @@ function _bailOutIfNotMocked($alias) { $code = " if (! in_array($alias, \$this->_mocked_methods)) {\n"; $code .= " trigger_error(\"Method [$alias] is not mocked\");\n"; - $code .= " return;\n"; + $code .= " \$null = null;\n"; + $code .= " return \$null;\n"; $code .= " }\n"; return $code; } - + /** * Creates source code for chaining to the composited * mock object. @@ -1220,24 +1179,24 @@ */ function _chainMockReturns() { $code = " function setReturnValue(\$method, \$value, \$args = false) {\n"; - $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= $this->_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->setReturnValue(\$method, \$value, \$args);\n"; $code .= " }\n"; $code .= " function setReturnValueAt(\$timing, \$method, \$value, \$args = false) {\n"; - $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= $this->_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n"; $code .= " }\n"; $code .= " function setReturnReference(\$method, &\$ref, \$args = false) {\n"; - $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= $this->_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->setReturnReference(\$method, \$ref, \$args);\n"; $code .= " }\n"; $code .= " function setReturnReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n"; - $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= $this->_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. @@ -1245,36 +1204,44 @@ * @access private */ function _chainMockExpectations() { - $code = " function expectArguments(\$method, \$args = false) {\n"; - $code .= Mock::_bailOutIfNotMocked("\$method"); + $code = " function expect(\$method, \$args = false) {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expect(\$method, \$args);\n"; + $code .= " }\n"; + $code .= " function expectArguments(\$method, \$args = false) {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectArguments(\$method, \$args);\n"; $code .= " }\n"; + $code .= " function expectAt(\$timing, \$method, \$args = false) {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args);\n"; + $code .= " }\n"; $code .= " function expectArgumentsAt(\$timing, \$method, \$args = false) {\n"; - $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= $this->_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args);\n"; $code .= " }\n"; $code .= " function expectCallCount(\$method, \$count) {\n"; - $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= $this->_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectCallCount(\$method, \$count);\n"; $code .= " }\n"; $code .= " function expectMaximumCallCount(\$method, \$count) {\n"; - $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= $this->_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectMaximumCallCount(\$method, \$count);\n"; $code .= " }\n"; $code .= " function expectMinimumCallCount(\$method, \$count) {\n"; - $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= $this->_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectMinimumCallCount(\$method, \$count);\n"; $code .= " }\n"; $code .= " function expectNever(\$method) {\n"; - $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= $this->_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectNever(\$method);\n"; $code .= " }\n"; $code .= " function expectOnce(\$method, \$args = false) {\n"; - $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= $this->_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectOnce(\$method, \$args);\n"; $code .= " }\n"; $code .= " function expectAtLeastOnce(\$method, \$args = false) {\n"; - $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= $this->_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectAtLeastOnce(\$method, \$args);\n"; $code .= " }\n"; $code .= " function tally() {\n"; @@ -1282,7 +1249,7 @@ $code .= " }\n"; return $code; } - + /** * Creates source code to override a list of methods * with mock versions. @@ -1294,30 +1261,13 @@ function _overrideMethods($methods) { $code = ""; foreach ($methods as $method) { - $code .= " function $method() {\n"; + $code .= " " . $this->_reflection->getSignature($method) . " {\n"; $code .= " \$args = func_get_args();\n"; - $code .= " return \$this->_mock->_invoke(\"$method\", \$args);\n"; + $code .= " \$result = &\$this->_mock->_invoke(\"$method\", \$args);\n"; + $code .= " return \$result;\n"; $code .= " }\n"; } return $code; } - - /** - * Uses a stack trace to find the line of an assertion. - * @param string $format String formatting. - * @param array $stack Stack frames top most first. Only - * needed if not using the PHP - * backtrace function. - * @return string Line number of first expect* - * method embedded in format string. - * @access public - * @static - */ - function getExpectationLine($format = '%d', $stack = false) { - if ($stack === false) { - $stack = SimpleTestCompatibility::getStackTrace(); - } - return SimpleDumper::getFormattedAssertionLine($stack, $format, 'expect'); - } } ?> \ No newline at end of file diff --git a/tests/test_tools/simpletest/page.php b/tests/test_tools/simpletest/page.php index 843dedf5..a7dc3a78 100644 --- a/tests/test_tools/simpletest/page.php +++ b/tests/test_tools/simpletest/page.php @@ -3,7 +3,7 @@ * Base include file for SimpleTest * @package SimpleTest * @subpackage WebTester - * @version $Id: page.php,v 1.105 2005/02/04 05:32:16 lastcraft Exp $ + * @version $Id: page.php,v 1.131 2006/02/05 01:07:49 lastcraft Exp $ */ /**#@+ @@ -13,8 +13,103 @@ require_once(dirname(__FILE__) . '/parser.php'); require_once(dirname(__FILE__) . '/tag.php'); require_once(dirname(__FILE__) . '/form.php'); + require_once(dirname(__FILE__) . '/selector.php'); /**#@-*/ - + + /** + * Creates tags and widgets given HTML tag + * attributes. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleTagBuilder { + + /** + * Factory for the tag objects. Creates the + * appropriate tag object for the incoming tag name + * and attributes. + * @param string $name HTML tag name. + * @param hash $attributes Element attributes. + * @return SimpleTag Tag object. + * @access public + */ + function createTag($name, $attributes) { + static $map = array( + 'a' => 'SimpleAnchorTag', + 'title' => 'SimpleTitleTag', + 'button' => 'SimpleButtonTag', + 'textarea' => 'SimpleTextAreaTag', + 'option' => 'SimpleOptionTag', + 'label' => 'SimpleLabelTag', + 'form' => 'SimpleFormTag', + 'frame' => 'SimpleFrameTag'); + $attributes = $this->_keysToLowerCase($attributes); + if (array_key_exists($name, $map)) { + $tag_class = $map[$name]; + return new $tag_class($attributes); + } elseif ($name == 'select') { + return $this->_createSelectionTag($attributes); + } elseif ($name == 'input') { + return $this->_createInputTag($attributes); + } + return new SimpleTag($name, $attributes); + } + + /** + * Factory for selection fields. + * @param hash $attributes Element attributes. + * @return SimpleTag Tag object. + * @access protected + */ + function _createSelectionTag($attributes) { + if (isset($attributes['multiple'])) { + return new MultipleSelectionTag($attributes); + } + return new SimpleSelectionTag($attributes); + } + + /** + * Factory for input tags. + * @param hash $attributes Element attributes. + * @return SimpleTag Tag object. + * @access protected + */ + function _createInputTag($attributes) { + if (! isset($attributes['type'])) { + return new SimpleTextTag($attributes); + } + $type = strtolower(trim($attributes['type'])); + $map = array( + 'submit' => 'SimpleSubmitTag', + 'image' => 'SimpleImageSubmitTag', + 'checkbox' => 'SimpleCheckboxTag', + 'radio' => 'SimpleRadioButtonTag', + 'text' => 'SimpleTextTag', + 'hidden' => 'SimpleTextTag', + 'password' => 'SimpleTextTag', + 'file' => 'SimpleUploadTag'); + if (array_key_exists($type, $map)) { + $tag_class = $map[$type]; + return new $tag_class($attributes); + } + return false; + } + + /** + * Make the keys lower case for case insensitive look-ups. + * @param hash $map Hash to convert. + * @return hash Unchanged values, but keys lower case. + * @access private + */ + function _keysToLowerCase($map) { + $lower = array(); + foreach ($map as $key => $value) { + $lower[strtolower($key)] = $value; + } + return $lower; + } + } + /** * SAX event handler. Maintains a list of * open tags and dispatches them as they close. @@ -24,7 +119,8 @@ class SimplePageBuilder extends SimpleSaxListener { protected $_tags; protected $_page; - + protected $_private_content_tag; + /** * Sets the builder up empty. * @access public @@ -33,6 +129,17 @@ $this->SimpleSaxListener(); } + /** + * Frees up any references so as to allow the PHP garbage + * collection from unset() to work. + * @access public + */ + function free() { + unset($this->_tags); + unset($this->_page); + unset($this->_private_content_tags); + } + /** * Reads the raw content and send events * into the page to be built. @@ -40,7 +147,7 @@ * @return SimplePage Newly parsed page. * @access public */ - function parse($response) { + function &parse($response) { $this->_tags = array(); $this->_page = $this->_createPage($response); $parser = $this->_createParser($this); @@ -48,16 +155,17 @@ $this->_page->acceptPageEnd(); return $this->_page; } - + /** * Creates an empty page. * @return SimplePage New unparsed page. * @access protected */ - function _createPage($response) { - return new SimplePage($response); + function &_createPage($response) { + $page = new SimplePage($response); + return $page; } - + /** * Creates the parser used with the builder. * @param $listener SimpleSaxListener Target of parser. @@ -65,22 +173,9 @@ * events for the builder. * @access protected */ - function _createParser($listener) { - return new SimpleSaxParser($listener); - } - - /** - * Make the keys lower case for case insensitive look-ups. - * @param hash $map Hash to convert. - * @return hash Unchanged values, but keys lower case. - * @access private - */ - function _keysToLowerCase($map) { - $lower = array(); - foreach ($map as $key => $value) { - $lower[strtolower($key)] = $value; - } - return $lower; + function &_createParser($listener) { + $parser = new SimpleHtmlSaxParser($listener); + return $parser; } /** @@ -92,19 +187,31 @@ * @access public */ function startElement($name, $attributes) { - $tag = $this->_createTag($name, $this->_keysToLowerCase($attributes)); - if ($name == 'form') { + $factory = new SimpleTagBuilder(); + $tag = $factory->createTag($name, $attributes); + if (! $tag) { + return true; + } + if ($tag->getTagName() == 'label') { + $this->_page->acceptLabelStart($tag); + $this->_openTag($tag); + return true; + } + if ($tag->getTagName() == 'form') { $this->_page->acceptFormStart($tag); return true; - } - if ($name == 'frameset') { + } + if ($tag->getTagName() == 'frameset') { $this->_page->acceptFramesetStart($tag); return true; - } - if ($name == 'frame') { + } + if ($tag->getTagName() == 'frame') { $this->_page->acceptFrame($tag); return true; - } + } + if ($tag->isPrivateContent() && ! isset($this->_private_content_tag)) { + $this->_private_content_tag = $tag; + } if ($tag->expectEndTag()) { $this->_openTag($tag); return true; @@ -112,7 +219,7 @@ $this->_page->acceptTag($tag); return true; } - + /** * End of element event. * @param string $name Element name. @@ -120,23 +227,41 @@ * @access public */ function endElement($name) { + if ($name == 'label') { + $this->_page->acceptLabelEnd(); + return true; + } if ($name == 'form') { $this->_page->acceptFormEnd(); return true; - } + } if ($name == 'frameset') { $this->_page->acceptFramesetEnd(); return true; - } - if (isset($this->_tags[$name]) && (count($this->_tags[$name]) > 0)) { + } + if ($this->_hasNamedTagOnOpenTagStack($name)) { $tag = array_pop($this->_tags[$name]); + if ($tag->isPrivateContent() && $this->_private_content_tag->getTagName() == $name) { + unset($this->_private_content_tag); + } $this->_addContentTagToOpenTags($tag); $this->_page->acceptTag($tag); return true; } return true; } - + + /** + * Test to see if there are any open tags awaiting + * closure that match the tag name. + * @param string $name Element name. + * @return boolean True if any are still open. + * @access private + */ + function _hasNamedTagOnOpenTagStack($name) { + return isset($this->_tags[$name]) && (count($this->_tags[$name]) > 0); + } + /** * Unparsed, but relevant data. The data is added * to every open tag. @@ -145,18 +270,33 @@ * @access public */ function addContent($text) { + if (isset($this->_private_content_tag)) { + $this->_private_content_tag->addContent($text); + } else { + $this->_addContentToAllOpenTags($text); + } + return true; + } + + /** + * Any content fills all currently open tags unless it + * is part of an option tag. + * @param string $text May include unparsed tags. + * @access private + */ + function _addContentToAllOpenTags($text) { foreach (array_keys($this->_tags) as $name) { for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) { $this->_tags[$name][$i]->addContent($text); } } - return true; } - + /** - * Parsed relevant data. The parsed tag is added - * to every open tag. - * @param SimpleTag $tag May include unparsed tags. + * Parsed data in tag form. The parsed tag is added + * to every open tag. Used for adding options to select + * fields only. + * @param SimpleTag $tag Option tags only. * @access private */ function _addContentTagToOpenTags($tag) { @@ -169,7 +309,7 @@ } } } - + /** * Opens a tag for receiving content. Multiple tags * will be receiving input at the same time. @@ -181,78 +321,10 @@ if (! in_array($name, array_keys($this->_tags))) { $this->_tags[$name] = array(); } - array_push($this->_tags[$name], $tag); - } - - /** - * Factory for the tag objects. Creates the - * appropriate tag object for the incoming tag name. - * @param string $name HTML tag name. - * @param hash $attributes Element attributes. - * @return SimpleTag Tag object. - * @access protected - */ - function _createTag($name, $attributes) { - if ($name == 'a') { - return new SimpleAnchorTag($attributes); - } elseif ($name == 'title') { - return new SimpleTitleTag($attributes); - } elseif ($name == 'input') { - return $this->_createInputTag($attributes); - } elseif ($name == 'button') { - return new SimpleButtonTag($attributes); - } elseif ($name == 'textarea') { - return new SimpleTextAreaTag($attributes); - } elseif ($name == 'select') { - return $this->_createSelectionTag($attributes); - } elseif ($name == 'option') { - return new SimpleOptionTag($attributes); - } elseif ($name == 'form') { - return new SimpleFormTag($attributes); - } elseif ($name == 'frame') { - return new SimpleFrameTag($attributes); - } - return new SimpleTag($name, $attributes); - } - - /** - * Factory for selection fields. - * @param hash $attributes Element attributes. - * @return SimpleTag Tag object. - * @access protected - */ - function _createSelectionTag($attributes) { - if (isset($attributes['multiple'])) { - return new MultipleSelectionTag($attributes); - } - return new SimpleSelectionTag($attributes); - } - - /** - * Factory for input tags. - * @param hash $attributes Element attributes. - * @return SimpleTag Tag object. - * @access protected - */ - function _createInputTag($attributes) { - if (! isset($attributes['type'])) { - return new SimpleTextTag($attributes); - } - $type = strtolower($attributes['type']); - if ($type == 'submit') { - return new SimpleSubmitTag($attributes); - } elseif ($type == 'image') { - return new SimpleImageSubmitTag($attributes); - } elseif ($type == 'checkbox') { - return new SimpleCheckboxTag($attributes); - } elseif ($type == 'radio') { - return new SimpleRadioButtonTag($attributes); - } else { - return new SimpleTextTag($attributes); - } + $this->_tags[$name][] = $tag; } } - + /** * A wrapper for a web page. * @package SimpleTest @@ -261,6 +333,9 @@ class SimplePage { protected $_links; protected $_title; + protected $_last_widget; + protected $_label; + protected $_left_over_labels; protected $_open_forms; protected $_complete_forms; protected $_frameset; @@ -274,7 +349,7 @@ protected $_method; protected $_url; protected $_request_data; - + /** * Parses a page ready to access it's contents. * @param SimpleHttpResponse $response Result of HTTP fetch. @@ -283,6 +358,7 @@ function SimplePage($response = false) { $this->_links = array(); $this->_title = false; + $this->_left_over_labels = array(); $this->_open_forms = array(); $this->_complete_forms = array(); $this->_frameset = false; @@ -295,7 +371,7 @@ $this->_noResponse(); } } - + /** * Extracts all of the response information. * @param SimpleHttpResponse $response Response being parsed. @@ -310,7 +386,7 @@ $this->_url = $response->getUrl(); $this->_request_data = $response->getRequestData(); } - + /** * Sets up a missing response. * @access private @@ -324,7 +400,7 @@ $this->_url = false; $this->_request_data = false; } - + /** * Original request as bytes sent down the wire. * @return mixed Sent content. @@ -333,7 +409,7 @@ function getRequest() { return $this->_sent; } - + /** * Accessor for raw text of page. * @return string Raw unparsed content. @@ -342,7 +418,7 @@ function getRaw() { return $this->_raw; } - + /** * Accessor for plain text of page as a text browser * would see it. @@ -351,11 +427,11 @@ */ function getText() { if (! $this->_text) { - $this->_text = SimpleSaxParser::normalise($this->_raw); + $this->_text = SimpleHtmlSaxParser::normalise($this->_raw); } return $this->_text; } - + /** * Accessor for raw headers of page. * @return string Header block as text. @@ -367,7 +443,7 @@ } return false; } - + /** * Original request method. * @return string GET, POST or HEAD. @@ -376,7 +452,7 @@ function getMethod() { return $this->_method; } - + /** * Original resource name. * @return SimpleUrl Current url. @@ -385,7 +461,7 @@ function getUrl() { return $this->_url; } - + /** * Original request data. * @return mixed Sent content. @@ -394,7 +470,7 @@ function getRequestData() { return $this->_request_data; } - + /** * Accessor for last error. * @return string Error from last response. @@ -403,7 +479,7 @@ function getTransportError() { return $this->_transport_error; } - + /** * Accessor for current MIME type. * @return string MIME type as string; e.g. 'text/html' @@ -415,7 +491,7 @@ } return false; } - + /** * Accessor for HTTP response code. * @return integer HTTP response code received. @@ -427,7 +503,7 @@ } return false; } - + /** * Accessor for last Authentication type. Only valid * straight after a challenge (401). @@ -440,7 +516,7 @@ } return false; } - + /** * Accessor for last Authentication realm. Only valid * straight after a challenge (401). @@ -453,7 +529,7 @@ } return false; } - + /** * Accessor for current frame focus. Will be * false as no frames. @@ -463,7 +539,7 @@ function getFrameFocus() { return array(); } - + /** * Sets the focus by index. The integer index starts from 1. * @param integer $choice Chosen frame. @@ -473,7 +549,7 @@ function setFrameFocusByIndex($choice) { return false; } - + /** * Sets the focus by name. Always fails for a leaf page. * @param string $name Chosen frame. @@ -483,14 +559,14 @@ function setFrameFocus($name) { return false; } - + /** * Clears the frame focus. Does nothing for a leaf page. * @access public */ function clearFrameFocus() { } - + /** * Adds a tag to the page. * @param SimpleTag $tag Tag to accept. @@ -505,9 +581,36 @@ for ($i = 0; $i < count($this->_open_forms); $i++) { $this->_open_forms[$i]->addWidget($tag); } + $this->_last_widget = $tag; } } - + + /** + * Opens a label for a described widget. + * @param SimpleFormTag $tag Tag to accept. + * @access public + */ + function acceptLabelStart($tag) { + $this->_label = $tag; + unset($this->_last_widget); + } + + /** + * Closes the most recently opened label. + * @access public + */ + function acceptLabelEnd() { + if (isset($this->_label)) { + if (isset($this->_last_widget)) { + $this->_last_widget->setLabel($this->_label->getText()); + unset($this->_last_widget); + } else { + $this->_left_over_labels[] = SimpleTestCompatibility::copy($this->_label); + } + unset($this->_label); + } + } + /** * Tests to see if a tag is a possible form * element. @@ -518,7 +621,7 @@ 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. @@ -527,7 +630,7 @@ function acceptFormStart($tag) { $this->_open_forms[] = new SimpleForm($tag, $this->getUrl()); } - + /** * Closes the most recently opened form. * @access public @@ -537,7 +640,7 @@ $this->_complete_forms[] = array_pop($this->_open_forms); } } - + /** * Opens a frameset. A frameset may contain nested * frameset tags. @@ -550,7 +653,7 @@ } $this->_frameset_nesting_level++; } - + /** * Closes the most recently opened frameset. * @access public @@ -560,7 +663,7 @@ $this->_frameset_nesting_level--; } } - + /** * Takes a single frame tag and stashes it in * the current frame set. @@ -574,7 +677,7 @@ } } } - + /** * Test to see if in the middle of reading * a frameset. @@ -587,7 +690,7 @@ } return ($this->_frameset_nesting_level > 0); } - + /** * Test to see if link is an absolute one. * @param string $url Url to test. @@ -598,7 +701,7 @@ $parsed = new SimpleUrl($url); return (boolean)($parsed->getScheme() && $parsed->getHost()); } - + /** * Adds a link to the page. * @param SimpleAnchorTag $tag Link to accept. @@ -607,7 +710,7 @@ function _addLink($tag) { $this->_links[] = $tag; } - + /** * Marker for end of complete page. Any work in * progress can now be closed. @@ -617,8 +720,15 @@ 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()); + } + } } - + /** * Test for the presence of a frameset. * @return boolean True if frameset. @@ -627,7 +737,7 @@ function hasFrames() { return (boolean)$this->_frameset; } - + /** * Accessor for frame name and source URL for every frame that * will need to be loaded. Immediate children only. @@ -649,7 +759,7 @@ } return $urls; } - + /** * Fetches a list of loaded frames. * @return array/string Just the URL for a single page. @@ -659,7 +769,7 @@ $url = $this->getUrl(); return $url->asString(); } - + /** * Accessor for a list of all fixed links. * @return array List of urls with scheme of @@ -675,7 +785,7 @@ } return $all; } - + /** * Accessor for a list of all relative links. * @return array List of urls without hostname. @@ -690,7 +800,7 @@ } return $all; } - + /** * Accessor for URLs by the link label. Label will match * regardess of whitespace issues and case. @@ -707,7 +817,7 @@ } return $matches; } - + /** * Accessor for a URL by the id attribute. * @param string $id Id attribute of link. @@ -722,7 +832,7 @@ } return false; } - + /** * Converts a link into a target URL. * @param SimpleAnchor $link Parsed link. @@ -736,7 +846,7 @@ } return $url; } - + /** * Expands expandomatic URLs into fully qualified * URLs. @@ -750,7 +860,7 @@ } return $url->makeAbsolute($this->getUrl()); } - + /** * Sets the title tag contents. * @param SimpleTitleTag $tag Title of page. @@ -759,7 +869,7 @@ function _setTitle($tag) { $this->_title = $tag; } - + /** * Accessor for parsed title. * @return string Title or false if no title is present. @@ -771,103 +881,43 @@ } return false; } - - /** - * Finds a held form by button label. Will only - * search correctly built forms. - * @param string $label Button label, default 'Submit'. - * @return SimpleForm Form object containing the button. - * @access public - */ - function getFormBySubmitLabel($label) { - for ($i = 0; $i < count($this->_complete_forms); $i++) { - if ($this->_complete_forms[$i]->hasSubmitLabel($label)) { - return $this->_complete_forms[$i]; - } - } - return null; - } - + /** * Finds a held form by button label. Will only * search correctly built forms. - * @param string $name Button name attribute. - * @return SimpleForm Form object containing the button. - * @access public - */ - function getFormBySubmitName($name) { - for ($i = 0; $i < count($this->_complete_forms); $i++) { - if ($this->_complete_forms[$i]->hasSubmitName($name)) { - return $this->_complete_forms[$i]; - } - } - return null; - } - - /** - * Finds a held form by button id. Will only - * search correctly built forms. - * @param string $id Button ID attribute. - * @return SimpleForm Form object containing the button. + * @param SimpleSelector $selector Button finder. + * @return SimpleForm Form object containing + * the button. * @access public */ - function getFormBySubmitId($id) { + function &getFormBySubmit($selector) { for ($i = 0; $i < count($this->_complete_forms); $i++) { - if ($this->_complete_forms[$i]->hasSubmitId($id)) { + if ($this->_complete_forms[$i]->hasSubmit($selector)) { return $this->_complete_forms[$i]; } } - return null; + $null = null; + return $null; } - - /** - * Finds a held form by image label. Will only - * search correctly built forms. - * @param string $label Usually the alt attribute. - * @return SimpleForm Form object containing the image. - * @access public - */ - function getFormByImageLabel($label) { - for ($i = 0; $i < count($this->_complete_forms); $i++) { - if ($this->_complete_forms[$i]->hasImageLabel($label)) { - return $this->_complete_forms[$i]; - } - } - return null; - } - - /** - * Finds a held form by image button id. Will only - * search correctly built forms. - * @param string $name Image name. - * @return SimpleForm Form object containing the image. - * @access public - */ - function getFormByImageName($name) { - for ($i = 0; $i < count($this->_complete_forms); $i++) { - if ($this->_complete_forms[$i]->hasImageName($name)) { - return $this->_complete_forms[$i]; - } - } - return null; - } - + /** - * Finds a held form by image button id. Will only - * search correctly built forms. - * @param string $id Image ID attribute. - * @return SimpleForm Form object containing the image. + * 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 getFormByImageId($id) { + function &getFormByImage($selector) { for ($i = 0; $i < count($this->_complete_forms); $i++) { - if ($this->_complete_forms[$i]->hasImageId($id)) { + if ($this->_complete_forms[$i]->hasImage($selector)) { return $this->_complete_forms[$i]; } } - return null; + $null = null; + return $null; } - + /** * Finds a held form by the form ID. A way of * identifying a specific form when we have control @@ -876,81 +926,45 @@ * @return SimpleForm Form object containing the matching ID. * @access public */ - function getFormById($id) { + function &getFormById($id) { for ($i = 0; $i < count($this->_complete_forms); $i++) { if ($this->_complete_forms[$i]->getId() == $id) { return $this->_complete_forms[$i]; } } - return null; + $null = null; + return $null; } - + /** * Sets a field on each form in which the field is * available. - * @param string $name Field name. - * @param string $value Value to set field to. - * @return boolean True if value is valid. + * @param SimpleSelector $selector Field finder. + * @param string $value Value to set field to. + * @return boolean True if value is valid. * @access public */ - function setField($name, $value) { + function setField($selector, $value) { $is_set = false; for ($i = 0; $i < count($this->_complete_forms); $i++) { - if ($this->_complete_forms[$i]->setField($name, $value)) { + if ($this->_complete_forms[$i]->setField($selector, $value)) { $is_set = true; } } return $is_set; } - - /** - * Sets a field on the form in which the unique field is - * available. - * @param string/integer $id Field ID attribute. - * @param string $value Value to set field to. - * @return boolean True if value is valid. - * @access public - */ - function setFieldById($id, $value) { - for ($i = 0; $i < count($this->_complete_forms); $i++) { - if ($this->_complete_forms[$i]->setFieldById($id, $value)) { - return true; - } - } - return false; - } - - /** - * Accessor for a form element value within a page. - * Finds the first match. - * @param string $name Field name. - * @return string/boolean A string if the field is - * present, false if unchecked - * and null if missing. - * @access public - */ - function getField($name) { - for ($i = 0; $i < count($this->_complete_forms); $i++) { - $value = $this->_complete_forms[$i]->getValue($name); - if (isset($value)) { - return $value; - } - } - return null; - } - + /** * Accessor for a form element value within a page. - * Finds the first match. - * @param string/integer $id Field ID attribute. - * @return string/boolean A string if the field is - * present, false if unchecked - * and null if missing. + * @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 getFieldById($id) { + function getField($selector) { for ($i = 0; $i < count($this->_complete_forms); $i++) { - $value = $this->_complete_forms[$i]->getValueById($id); + $value = $this->_complete_forms[$i]->getValue($selector); if (isset($value)) { return $value; } diff --git a/tests/test_tools/simpletest/parser.php b/tests/test_tools/simpletest/parser.php index 7dc56a58..3f58e7e9 100644 --- a/tests/test_tools/simpletest/parser.php +++ b/tests/test_tools/simpletest/parser.php @@ -3,23 +3,33 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage MockObjects - * @version $Id: parser.php,v 1.66 2005/02/06 04:03:27 lastcraft Exp $ + * @version $Id: parser.php,v 1.72 2006/01/04 03:15:05 lastcraft Exp $ */ /**#@+ * Lexer mode stack constants */ - define("LEXER_ENTER", 1); - define("LEXER_MATCHED", 2); - define("LEXER_UNMATCHED", 3); - define("LEXER_EXIT", 4); - define("LEXER_SPECIAL", 5); + if (! defined('LEXER_ENTER')) { + define('LEXER_ENTER', 1); + } + if (! defined('LEXER_MATCHED')) { + define('LEXER_MATCHED', 2); + } + if (! defined('LEXER_UNMATCHED')) { + define('LEXER_UNMATCHED', 3); + } + if (! defined('LEXER_EXIT')) { + define('LEXER_EXIT', 4); + } + if (! defined('LEXER_SPECIAL')) { + define('LEXER_SPECIAL', 5); + } /**#@-*/ /** * Compounded regular expression. Any of * the contained patterns could match and - * when one does it's label is returned. + * when one does, it's label is returned. * @package SimpleTest * @subpackage WebTester */ @@ -441,57 +451,27 @@ } /** - * Converts HTML tokens into selected SAX events. + * Breas HTML into SAX events. * @package SimpleTest * @subpackage WebTester */ - class SimpleSaxParser { - protected $_lexer; - protected $_listener; - protected $_tag; - protected $_attributes; - protected $_current_attribute; - - /** - * Sets the listener. - * @param SimpleSaxListener $listener SAX event handler. - * @access public - */ - function SimpleSaxParser($listener) { - $this->_listener = $listener; - $this->_lexer = $this->createLexer($this); - $this->_tag = ''; - $this->_attributes = array(); - $this->_current_attribute = ''; - } - - /** - * Runs the content through the lexer which - * should call back to the acceptors. - * @param string $raw Page text to parse. - * @return boolean False if parse error. - * @access public - */ - function parse($raw) { - return $this->_lexer->parse($raw); - } + class SimpleHtmlLexer extends SimpleLexer { /** - * Sets up the matching lexer. Starts in 'text' mode. - * @param SimpleSaxParser $parser Event generator, usually $self. - * @return SimpleLexer Lexer suitable for this parser. + * Sets up the lexer with case insensitive matching + * and adds the HTML handlers. + * @param SimpleSaxParser $parser Handling strategy by + * reference. * @access public - * @static */ - function createLexer($parser) { - $lexer = new SimpleLexer($parser, 'text'); - $lexer->mapHandler('text', 'acceptTextToken'); - SimpleSaxParser::_addSkipping($lexer); - foreach (SimpleSaxParser::_getParsedTags() as $tag) { - SimpleSaxParser::_addTag($lexer, $tag); + function SimpleHtmlLexer($parser) { + $this->SimpleLexer($parser, 'text'); + $this->mapHandler('text', 'acceptTextToken'); + $this->_addSkipping(); + foreach ($this->_getParsedTags() as $tag) { + $this->_addTag($tag); } - SimpleSaxParser::_addInTagTokens($lexer); - return $lexer; + $this->_addInTagTokens(); } /** @@ -501,72 +481,114 @@ */ function _getParsedTags() { return array('a', 'title', 'form', 'input', 'button', 'textarea', 'select', - 'option', 'frameset', 'frame'); + 'option', 'frameset', 'frame', 'label'); } /** * The lexer has to skip certain sections such * as server code, client code and styles. - * @param SimpleLexer $lexer Lexer to add patterns to. * @access private - * @static */ - function _addSkipping($lexer) { - $lexer->mapHandler('css', 'ignore'); - $lexer->addEntryPattern('addExitPattern('', 'css'); - $lexer->mapHandler('js', 'ignore'); - $lexer->addEntryPattern('addExitPattern('', 'js'); - $lexer->mapHandler('comment', 'ignore'); - $lexer->addEntryPattern('', 'comment'); + function _addSkipping() { + $this->mapHandler('css', 'ignore'); + $this->addEntryPattern('addExitPattern('', 'css'); + $this->mapHandler('js', 'ignore'); + $this->addEntryPattern('addExitPattern('', 'js'); + $this->mapHandler('comment', 'ignore'); + $this->addEntryPattern('', 'comment'); } /** * Pattern matches to start and end a tag. - * @param SimpleLexer $lexer Lexer to add patterns to. * @param string $tag Name of tag to scan for. * @access private - * @static */ - function _addTag($lexer, $tag) { - $lexer->addSpecialPattern("", 'text', 'acceptEndToken'); - $lexer->addEntryPattern("<$tag", 'text', 'tag'); + function _addTag($tag) { + $this->addSpecialPattern("", 'text', 'acceptEndToken'); + $this->addEntryPattern("<$tag", 'text', 'tag'); } /** * Pattern matches to parse the inside of a tag * including the attributes and their quoting. - * @param SimpleLexer $lexer Lexer to add patterns to. * @access private - * @static */ - function _addInTagTokens($lexer) { - $lexer->mapHandler('tag', 'acceptStartToken'); - $lexer->addSpecialPattern('\s+', 'tag', 'ignore'); - SimpleSaxParser::_addAttributeTokens($lexer); - $lexer->addExitPattern('>', 'tag'); + 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. - * @param SimpleLexer $lexer Lexer to add patterns to. * @access private + */ + 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 { + protected $_lexer; + protected $_listener; + protected $_tag; + protected $_attributes; + protected $_current_attribute; + + /** + * Sets the listener. + * @param SimpleSaxListener $listener SAX event handler. + * @access public + */ + function SimpleHtmlSaxParser($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 _addAttributeTokens($lexer) { - $lexer->mapHandler('dq_attribute', 'acceptAttributeToken'); - $lexer->addEntryPattern('=\s*"', 'tag', 'dq_attribute'); - $lexer->addPattern("\\\\\"", 'dq_attribute'); - $lexer->addExitPattern('"', 'dq_attribute'); - $lexer->mapHandler('sq_attribute', 'acceptAttributeToken'); - $lexer->addEntryPattern("=\s*'", 'tag', 'sq_attribute'); - $lexer->addPattern("\\\\'", 'sq_attribute'); - $lexer->addExitPattern("'", 'sq_attribute'); - $lexer->mapHandler('uq_attribute', 'acceptAttributeToken'); - $lexer->addSpecialPattern('=\s*[^>\s]*', 'tag', 'uq_attribute'); + function &createLexer($parser) { + $lexer = new SimpleHtmlLexer($parser); + return $lexer; } /** @@ -589,13 +611,13 @@ $success = $this->_listener->startElement( $this->_tag, $this->_attributes); - $this->_tag = ""; + $this->_tag = ''; $this->_attributes = array(); return $success; } - if ($token != "=") { - $this->_current_attribute = strtolower(SimpleSaxParser::decodeHtml($token)); - $this->_attributes[$this->_current_attribute] = ""; + if ($token != '=') { + $this->_current_attribute = strtolower(SimpleHtmlSaxParser::decodeHtml($token)); + $this->_attributes[$this->_current_attribute] = ''; } return true; } @@ -625,11 +647,11 @@ function acceptAttributeToken($token, $event) { if ($event == LEXER_UNMATCHED) { $this->_attributes[$this->_current_attribute] .= - SimpleSaxParser::decodeHtml($token); + SimpleHtmlSaxParser::decodeHtml($token); } if ($event == LEXER_SPECIAL) { $this->_attributes[$this->_current_attribute] .= - preg_replace('/^=\s*/' , '', SimpleSaxParser::decodeHtml($token)); + preg_replace('/^=\s*/' , '', SimpleHtmlSaxParser::decodeHtml($token)); } return true; } @@ -692,11 +714,12 @@ * @static */ function normalise($html) { - $text = preg_replace('||', ' \1 ', $html); + $text = preg_replace('||', '', $html); + $text = preg_replace('||', ' \1 ', $text); $text = preg_replace('||', ' \1 ', $text); $text = preg_replace('||', ' \1 ', $text); $text = preg_replace('|<.*?>|', '', $text); - $text = SimpleSaxParser::decodeHtml($text); + $text = SimpleHtmlSaxParser::decodeHtml($text); $text = preg_replace('|\s+|', ' ', $text); return trim($text); } diff --git a/tests/test_tools/simpletest/reflection_php4.php b/tests/test_tools/simpletest/reflection_php4.php new file mode 100644 index 00000000..acd0d32d --- /dev/null +++ b/tests/test_tools/simpletest/reflection_php4.php @@ -0,0 +1,115 @@ +_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; + } + + /** + * 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/tests/test_tools/simpletest/reflection_php5.php b/tests/test_tools/simpletest/reflection_php5.php new file mode 100644 index 00000000..70419f7d --- /dev/null +++ b/tests/test_tools/simpletest/reflection_php5.php @@ -0,0 +1,275 @@ +_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 + */ + 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. Needs to recursively look at all of + * the interfaces included. + * @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 + */ + 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; + } + + /** + * Determines if the class is abstract. + * @returns boolean True if abstract. + * @access public + */ + function isAbstract() { + $reflection = new ReflectionClass($this->_interface); + return $reflection->isAbstract(); + } + + /** + * Wittles a list of interfaces down to only the top + * level parents. + * @param array $interfaces Reflection API interfaces + * to reduce. + * @returns array List of parent interface names. + * @access private + */ + function _onlyParents($interfaces) { + $parents = array(); + foreach ($interfaces as $interface) { + foreach($interfaces as $possible_parent) { + if ($interface->getName() == $possible_parent->getName()) { + continue; + } + if ($interface->isSubClassOf($possible_parent)) { + break; + } + } + $parents[] = $interface->getName(); + } + return $parents; + } + + /** + * Gets 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 == '__get') { + return 'function __get($key)'; + } + if ($name == '__set') { + return 'function __set($key, $value)'; + } + if (! is_callable(array($this->_interface, $name))) { + return "function $name()"; + } + if ($this->_isInterfaceMethod($name)) { + return $this->_getFullSignature($name); + } + return "function $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 + */ + function _getFullSignature($name) { + $interface = new ReflectionClass($this->_interface); + $method = $interface->getMethod($name); + $reference = $method->returnsReference() ? '&' : ''; + return "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 + */ + function _getParameterSignatures($method) { + $signatures = array(); + foreach ($method->getParameters() as $parameter) { + $type = $parameter->getClass(); + $signatures[] = + (! is_null($type) ? $type->getName() . ' ' : '') . + ($parameter->isPassedByReference() ? '&' : '') . + '$' . $this->_suppressSpurious($parameter->getName()) . + ($this->_isOptional($parameter) ? ' = null' : ''); + } + 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 + */ + 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 + */ + function _isOptional($parameter) { + if (method_exists($parameter, 'isOptional')) { + return $parameter->isOptional(); + } + return false; + } + } +?> \ No newline at end of file diff --git a/tests/test_tools/simpletest/remote.php b/tests/test_tools/simpletest/remote.php index 5a5f2d32..adb020a9 100644 --- a/tests/test_tools/simpletest/remote.php +++ b/tests/test_tools/simpletest/remote.php @@ -3,7 +3,7 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage UnitTester - * @version $Id: remote.php,v 1.11 2004/08/04 22:09:39 lastcraft Exp $ + * @version $Id: remote.php,v 1.12 2005/08/03 17:26:55 lastcraft Exp $ */ /**#@+ @@ -11,7 +11,7 @@ */ require_once(dirname(__FILE__) . '/browser.php'); require_once(dirname(__FILE__) . '/xml.php'); - require_once(dirname(__FILE__) . '/simple_test.php'); + require_once(dirname(__FILE__) . '/test_case.php'); /**#@-*/ /** @@ -74,7 +74,7 @@ * @return SimpleBrowser New browser. * @access protected */ - function _createBrowser() { + function &_createBrowser() { return new SimpleBrowser(); } @@ -84,7 +84,7 @@ * @return SimpleTestXmlListener XML reader. * @access protected */ - function _createParser($reporter) { + function &_createParser($reporter) { return new SimpleTestXmlParser($reporter); } diff --git a/tests/test_tools/simpletest/reporter.php b/tests/test_tools/simpletest/reporter.php index 32125c9b..ea3895e3 100644 --- a/tests/test_tools/simpletest/reporter.php +++ b/tests/test_tools/simpletest/reporter.php @@ -3,7 +3,7 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage UnitTester - * @version $Id: reporter.php,v 1.33 2004/11/29 04:35:49 lastcraft Exp $ + * @version $Id: reporter.php,v 1.36 2006/02/06 06:05:18 lastcraft Exp $ */ /**#@+ @@ -11,7 +11,7 @@ */ require_once(dirname(__FILE__) . '/scorer.php'); /**#@-*/ - + /** * Sample minimal test displayer. Generates only * failure messages and a pass count. @@ -20,7 +20,7 @@ */ class HtmlReporter extends SimpleReporter { protected $_character_set; - + /** * Does nothing yet. The first output will * be sent on the first test start. For use @@ -31,7 +31,7 @@ $this->SimpleReporter(); $this->_character_set = $character_set; } - + /** * Paints the top of the web page setting the * title to the name of the starting test. @@ -50,7 +50,7 @@ print "

    $test_name

    \n"; flush(); } - + /** * Send the headers necessary to ensure the page is * reloaded on every request. Otherwise you could be @@ -67,7 +67,7 @@ header("Pragma: no-cache"); } } - + /** * Paints the CSS. Add additional styles here. * @return string CSS code as text. @@ -76,7 +76,7 @@ function _getCss() { return ".fail { color: red; } pre { background-color: lightgray; }"; } - + /** * Paints the end of the test with a summary of * the passes and failures. @@ -96,7 +96,7 @@ print "\n"; print "\n\n"; } - + /** * Paints the test failure with a breadcrumbs * trail of the nesting test suites below the @@ -113,22 +113,22 @@ print implode(" -> ", $breadcrumb); print " -> " . $this->_htmlEntities($message) . "
    \n"; } - + /** * Paints a PHP error or exception. * @param string $message Message is ignored. * @access public * @abstract */ - function paintException($message) { - parent::paintException($message); + function paintError($message) { + parent::paintError($message); print "Exception: "; $breadcrumb = $this->getTestList(); array_shift($breadcrumb); print implode(" -> ", $breadcrumb); print " -> " . $this->_htmlEntities($message) . "
    \n"; } - + /** * Paints formatted text such as dumped variables. * @param string $message Text to show. @@ -137,7 +137,7 @@ function paintFormattedMessage($message) { print '
    ' . $this->_htmlEntities($message) . '
    '; } - + /** * Character set adjusted entity conversion. * @param string $message Plain text or Unicode message. @@ -148,7 +148,7 @@ return htmlentities($message, ENT_COMPAT, $this->_character_set); } } - + /** * Sample minimal test displayer. Generates only * failure messages and a pass count. For command @@ -159,7 +159,7 @@ * @subpackage UnitTester */ class TextReporter extends SimpleReporter { - + /** * Does nothing yet. The first output will * be sent on the first test start. @@ -168,7 +168,7 @@ function TextReporter() { $this->SimpleReporter(); } - + /** * Paints the title only. * @param string $test_name Name class of test. @@ -181,7 +181,7 @@ print "$test_name\n"; flush(); } - + /** * Paints the end of the test with a summary of * the passes and failures. @@ -199,13 +199,12 @@ ", 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. + * @param string $message Failure message displayed in + * the context of the other tests. * @access public */ function paintFail($message) { @@ -216,18 +215,18 @@ print "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); print "\n"; } - + /** * Paints a PHP error or exception. * @param string $message Message is ignored. * @access public * @abstract */ - function paintException($message) { - parent::paintException($message); + function paintError($message) { + parent::paintError($message); print "Exception " . $this->getExceptionCount() . "!\n$message\n"; } - + /** * Paints formatted text such as dumped variables. * @param string $message Text to show. @@ -238,4 +237,131 @@ 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 { + protected $_just_this_case =false; + protected $_just_this_test = false; + protected $_within_test_case = true; + + /** + * 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 SelectiveReporter($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->_within_test_case = false; + } + if (isset($just_this_test) && $just_this_test) { + $this->_just_this_test = strtolower($just_this_test); + } + $this->SimpleReporterDecorator($reporter); + } + + /** + * Compares criteria to actual the case/group name. + * @param string $test_case The incoming test. + * @return boolean True if matched. + * @access protected + */ + function _isCaseMatch($test_case) { + if ($this->_just_this_case) { + return $this->_just_this_case == strtolower($test_case); + } + return false; + } + + /** + * Compares criteria to actual the test name. + * @param string $method The incoming test method. + * @return boolean True if matched. + * @access protected + */ + function _isTestMatch($method) { + if ($this->_just_this_test) { + return $this->_just_this_test == strtolower($method); + } + return true; + } + + /** + * 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->_within_test_case && $this->_isTestMatch($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->_isCaseMatch($test_case)) { + $this->_within_test_case = true; + } + if ($this->_within_test_case) { + $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) { + if ($this->_within_test_case) { + $this->_reporter->paintGroupEnd($test_case); + } + if ($this->_isCaseMatch($test_case)) { + $this->_within_test_case = false; + } + } + + /** + * Paints the start of a test case. + * @param string $test_case Name of test or other label. + * @access public + */ + function paintCaseStart($test_case) { + if ($this->_isCaseMatch($test_case)) { + $this->_within_test_case = true; + } + if ($this->_within_test_case) { + $this->_reporter->paintCaseStart($test_case); + } + } + + /** + * Paints the end of a test case. + * @param string $test_case Name of test or other label. + * @access public + */ + function paintCaseEnd($test_case) { + if ($this->_within_test_case) { + $this->_reporter->paintCaseEnd($test_case); + } + if ($this->_isCaseMatch($test_case)) { + $this->_within_test_case = false; + } + } + } +?> \ No newline at end of file diff --git a/tests/test_tools/simpletest/scorer.php b/tests/test_tools/simpletest/scorer.php index 6c321f8c..e9cff6a6 100644 --- a/tests/test_tools/simpletest/scorer.php +++ b/tests/test_tools/simpletest/scorer.php @@ -3,9 +3,13 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage UnitTester - * @version $Id: scorer.php,v 1.4 2005/01/11 04:03:46 lastcraft Exp $ + * @version $Id: scorer.php,v 1.12 2006/02/06 06:05:18 lastcraft Exp $ */ - + + /**#@+*/ + require_once(dirname(__FILE__) . '/invoker.php'); + /**#@-*/ + /** * Can recieve test events and display them. Display * is achieved by making display methods available @@ -19,7 +23,7 @@ protected $_fails; protected $_exceptions; protected $_is_dry_run; - + /** * Starts the test run with no results. * @access public @@ -30,16 +34,18 @@ $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. @@ -50,6 +56,17 @@ 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. @@ -63,23 +80,24 @@ } return true; } - + /** - * Paints the start of a test method. + * 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 paintMethodStart($test_name) { + function paintGroupStart($test_name, $size) { } - + /** - * Paints the end of a test method. + * Paints the end of a group test. * @param string $test_name Name of test or other label. * @access public */ - function paintMethodEnd($test_name) { + function paintGroupEnd($test_name) { } - + /** * Paints the start of a test case. * @param string $test_name Name of test or other label. @@ -87,7 +105,7 @@ */ function paintCaseStart($test_name) { } - + /** * Paints the end of a test case. * @param string $test_name Name of test or other label. @@ -95,24 +113,23 @@ */ function paintCaseEnd($test_name) { } - + /** - * Paints the start of a group test. + * Paints the start of a test method. * @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) { + function paintMethodStart($test_name) { } - + /** - * Paints the end of a group test. + * Paints the end of a test method. * @param string $test_name Name of test or other label. * @access public */ - function paintGroupEnd($test_name) { + function paintMethodEnd($test_name) { } - + /** * Increments the pass count. * @param string $message Message is ignored. @@ -121,7 +138,7 @@ function paintPass($message) { $this->_passes++; } - + /** * Increments the fail count. * @param string $message Message is ignored. @@ -130,27 +147,18 @@ function paintFail($message) { $this->_fails++; } - + /** - * Deals with PHP 4 throwing an error. + * Deals with PHP 4 throwing an error or PHP 5 + * throwing an exception. * @param string $message Text of error formatted by * the test case. * @access public */ function paintError($message) { - $this->paintException($message); - } - - /** - * Deals with PHP 5 throwing an exception - * This isn't really implemented yet. - * @param Exception $exception Object thrown. - * @access public - */ - function paintException($exception) { $this->_exceptions++; } - + /** * Accessor for the number of passes so far. * @return integer Number of passes. @@ -159,7 +167,7 @@ function getPassCount() { return $this->_passes; } - + /** * Accessor for the number of fails so far. * @return integer Number of fails. @@ -168,7 +176,7 @@ function getFailCount() { return $this->_fails; } - + /** * Accessor for the number of untrapped errors * so far. @@ -178,7 +186,7 @@ function getExceptionCount() { return $this->_exceptions; } - + /** * Paints a simple supplementary message. * @param string $message Text to display. @@ -186,7 +194,7 @@ */ function paintMessage($message) { } - + /** * Paints a formatted ASCII message such as a * variable dump. @@ -195,7 +203,7 @@ */ function paintFormattedMessage($message) { } - + /** * By default just ignores user generated events. * @param string $type Event type as text. @@ -218,7 +226,7 @@ protected $_test_stack; protected $_size; protected $_progress; - + /** * Starts the display with no results in. * @access public @@ -229,7 +237,7 @@ $this->_size = null; $this->_progress = 0; } - + /** * Paints the start of a group test. Will also paint * the page header and footer if this is the @@ -248,7 +256,7 @@ } $this->_test_stack[] = $test_name; } - + /** * Paints the end of a group test. Will paint the page * footer if the stack of tests has unwound. @@ -262,7 +270,7 @@ $this->paintFooter($test_name); } } - + /** * Paints the start of a test case. Will also paint * the page header and footer if this is the @@ -280,7 +288,7 @@ } $this->_test_stack[] = $test_name; } - + /** * Paints the end of a test case. Will paint the page * footer if the stack of tests has unwound. @@ -294,7 +302,7 @@ $this->paintFooter($test_name); } } - + /** * Paints the start of a test method. * @param string $test_name Name of test that is starting. @@ -303,7 +311,7 @@ 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. @@ -313,7 +321,7 @@ function paintMethodEnd($test_name) { array_pop($this->_test_stack); } - + /** * Paints the test document header. * @param string $test_name First test top level @@ -323,7 +331,7 @@ */ function paintHeader($test_name) { } - + /** * Paints the test document footer. * @param string $test_name The top level test. @@ -332,7 +340,7 @@ */ function paintFooter($test_name) { } - + /** * Accessor for internal test stack. For * subclasses that need to see the whole test @@ -343,7 +351,7 @@ function getTestList() { return $this->_test_stack; } - + /** * Accessor for total test size in number * of test cases. Null until the first @@ -354,7 +362,7 @@ function getTestCaseCount() { return $this->_size; } - + /** * Accessor for the number of test cases * completed so far. @@ -364,15 +372,406 @@ function getTestCaseProgress() { return $this->_progress; } - + /** * Static check for running in the comand line. * @return boolean True if CLI. * @access public * @static */ - static function inCli() { + 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 teh reporter and the test case. + * @param SimpleScorer $reporter Reporter to receive events. + */ + function SimpleReporterDecorator($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 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 preperation 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); + } + + /** + * 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 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 { + protected $_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; + } + + /** + * 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 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/tests/test_tools/simpletest/selector.php b/tests/test_tools/simpletest/selector.php new file mode 100644 index 00000000..78ee0fef --- /dev/null +++ b/tests/test_tools/simpletest/selector.php @@ -0,0 +1,133 @@ +_name = $name; + } + + /** + * Compares with name attribute of widget. + * @param SimpleWidget $widget Control to compare. + * @access public + */ + function isMatch($widget) { + return ($widget->getName() == $this->_name); + } + } + + /** + * Used to extract form elements for testing against. + * Searches by visible label or alt text. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleByLabel { + protected $_label; + + /** + * Stashes the name for later comparison. + * @param string $label Visible text to match. + */ + function SimpleByLabel($label) { + $this->_label = $label; + } + + /** + * Comparison. Compares visible text of widget or + * related label. + * @param SimpleWidget $widget Control to compare. + * @access public + */ + function isMatch($widget) { + if (! method_exists($widget, 'isLabel')) { + return false; + } + return $widget->isLabel($this->_label); + } + } + + /** + * Used to extract form elements for testing against. + * Searches dy id attribute. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleById { + protected $_id; + + /** + * Stashes the name for later comparison. + * @param string $id ID atribute to match. + */ + function SimpleById($id) { + $this->_id = $id; + } + + /** + * Comparison. Compares id attribute of widget. + * @param SimpleWidget $widget Control to compare. + * @access public + */ + function isMatch($widget) { + return $widget->isId($this->_id); + } + } + + /** + * Used to extract form elements for testing against. + * Searches by visible label, name or alt text. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleByLabelOrName { + protected $_label; + + /** + * Stashes the name/label for later comparison. + * @param string $label Visible text to match. + */ + function SimpleByLabelOrName($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/tests/test_tools/simpletest/shell_tester.php b/tests/test_tools/simpletest/shell_tester.php index 7bab8ce0..572d4121 100644 --- a/tests/test_tools/simpletest/shell_tester.php +++ b/tests/test_tools/simpletest/shell_tester.php @@ -3,13 +3,13 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage UnitTester - * @version $Id: shell_tester.php,v 1.14 2004/08/17 18:18:32 lastcraft Exp $ + * @version $Id: shell_tester.php,v 1.19 2005/08/03 17:26:55 lastcraft Exp $ */ /**#@+ * include other SimpleTest class files */ - require_once(dirname(__FILE__) . '/simple_test.php'); + require_once(dirname(__FILE__) . '/test_case.php'); /**#@-*/ /** @@ -127,6 +127,40 @@ $shell = $this->_getShell(); return $shell->getOutputAsList(); } + + /** + * Will trigger a pass if the two parameters have + * the same value only. Otherwise a fail. This + * is for testing hand extracted text, etc. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertEqual($first, $second, $message = "%s") { + return $this->assert( + new EqualExpectation($first), + $second, + $message); + } + + /** + * Will trigger a pass if the two parameters have + * a different value. Otherwise a fail. This + * is for testing hand extracted text, etc. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertNotEqual($first, $second, $message = "%s") { + return $this->assert( + new NotEqualExpectation($first), + $second, + $message); + } /** * Tests the last status code from the shell. @@ -153,7 +187,7 @@ */ function assertOutput($expected, $message = "%s") { $shell = $this->_getShell(); - return $this->assertExpectation( + return $this->assert( new EqualExpectation($expected), $shell->getOutput(), $message); @@ -169,8 +203,8 @@ */ function assertOutputPattern($pattern, $message = "%s") { $shell = $this->_getShell(); - return $this->assertExpectation( - new WantedPatternExpectation($pattern), + return $this->assert( + new PatternExpectation($pattern), $shell->getOutput(), $message); } @@ -185,8 +219,8 @@ */ function assertNoOutputPattern($pattern, $message = "%s") { $shell = $this->_getShell(); - return $this->assertExpectation( - new UnwantedPatternExpectation($pattern), + return $this->assert( + new NoPatternExpectation($pattern), $shell->getOutput(), $message); } @@ -226,8 +260,8 @@ */ function assertFilePattern($pattern, $path, $message = "%s") { $shell = $this->_getShell(); - return $this->assertExpectation( - new WantedPatternExpectation($pattern), + return $this->assert( + new PatternExpectation($pattern), implode('', file($path)), $message); } @@ -243,8 +277,8 @@ */ function assertNoFilePattern($pattern, $path, $message = "%s") { $shell = $this->_getShell(); - return $this->assertExpectation( - new UnwantedPatternExpectation($pattern), + return $this->assert( + new NoPatternExpectation($pattern), implode('', file($path)), $message); } @@ -255,7 +289,7 @@ * @return Shell Current shell. * @access protected */ - function _getShell() { + function &_getShell() { return $this->_current_shell; } @@ -264,8 +298,9 @@ * @return Shell New shell object. * @access protected */ - function _createShell() { - return new SimpleShell(); + function &_createShell() { + $shell = new SimpleShell(); + return $shell; } } ?> \ No newline at end of file diff --git a/tests/test_tools/simpletest/simpletest.php b/tests/test_tools/simpletest/simpletest.php new file mode 100644 index 00000000..ca0d4e86 --- /dev/null +++ b/tests/test_tools/simpletest/simpletest.php @@ -0,0 +1,282 @@ += 0) { + require_once(dirname(__FILE__) . '/reflection_php5.php'); + } else { + require_once(dirname(__FILE__) . '/reflection_php4.php'); + } + /**#@-*/ + + /** + * Static global directives and options. I hate this + * class. It's a mixture of reference hacks, configuration + * and previous design screw-ups that I have to maintain + * to keep backward compatibility. + * @package SimpleTest + */ + class SimpleTest { + + /** + * Reads the SimpleTest version from the release file. + * @return string Version string. + * @static + * @access public + */ + function getVersion() { + $content = file(dirname(__FILE__) . '/VERSION'); + return trim($content[0]); + } + + /** + * Sets the name of a test case to ignore, usually + * because the class is an abstract case that should + * not be run. Once PHP4 is dropped this will disappear + * as a public method and "abstract" will rule. + * @param string $class Add a class to ignore. + * @static + * @access public + */ + function ignore($class) { + $registry = &SimpleTest::_getRegistry(); + $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 nice to havethe ignore() + * calls at the top of teh file. + * @param array $classes Class names of interest. + * @static + * @access public + */ + 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); + } + } + } + } + + /** + * 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. + * @access public + * @static + */ + function isIgnored($class) { + $registry = &SimpleTest::_getRegistry(); + return isset($registry['IgnoreList'][strtolower($class)]); + } + + /** + * @deprecated + */ + function setMockBaseClass($mock_base) { + $registry = &SimpleTest::_getRegistry(); + $registry['MockBaseClass'] = $mock_base; + } + + /** + * @deprecated + */ + function getMockBaseClass() { + $registry = &SimpleTest::_getRegistry(); + return $registry['MockBaseClass']; + } + + /** + * Sets proxy to use on all requests for when + * testing from behind a firewall. Set host + * to false to disable. This will take effect + * if there are no other proxy settings. + * @param string $proxy Proxy host as URL. + * @param string $username Proxy username for authentication. + * @param string $password Proxy password for authentication. + * @access public + */ + function useProxy($proxy, $username = false, $password = false) { + $registry = &SimpleTest::_getRegistry(); + $registry['DefaultProxy'] = $proxy; + $registry['DefaultProxyUsername'] = $username; + $registry['DefaultProxyPassword'] = $password; + } + + /** + * Accessor for default proxy host. + * @return string Proxy URL. + * @access public + */ + function getDefaultProxy() { + $registry = &SimpleTest::_getRegistry(); + return $registry['DefaultProxy']; + } + + /** + * Accessor for default proxy username. + * @return string Proxy username for authentication. + * @access public + */ + function getDefaultProxyUsername() { + $registry = &SimpleTest::_getRegistry(); + return $registry['DefaultProxyUsername']; + } + + /** + * Accessor for default proxy password. + * @return string Proxy password for authentication. + * @access public + */ + function getDefaultProxyPassword() { + $registry = &SimpleTest::_getRegistry(); + return $registry['DefaultProxyPassword']; + } + + /** + * 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. + * @access public + * @static + */ + function setCurrent($test) { + $registry = &SimpleTest::_getRegistry(); + $registry['CurrentTestCase'] = $test; + } + + /** + * Accessor for current test instance. + * @return SimpleTEstCase Currently running test. + * @access public + * @static + */ + function &getCurrent() { + $registry = &SimpleTest::_getRegistry(); + return $registry['CurrentTestCase']; + } + + /** + * Accessor for global registry of options. + * @return hash All stored values. + * @access private + * @static + */ + function &_getRegistry() { + static $registry = false; + if (! $registry) { + $registry = SimpleTest::_getDefaults(); + } + return $registry; + } + + /** + * Constant default values. + * @return hash All registry defaults. + * @access private + * @static + */ + function _getDefaults() { + return array( + 'StubBaseClass' => 'SimpleStub', + 'MockBaseClass' => 'SimpleMock', + 'IgnoreList' => array(), + 'DefaultProxy' => false, + 'DefaultProxyUsername' => false, + 'DefaultProxyPassword' => false); + } + } + + /** + * @deprecated + */ + class SimpleTestOptions extends SimpleTest { + + /** + * @deprecated + */ + function getVersion() { + return Simpletest::getVersion(); + } + + /** + * @deprecated + */ + function ignore($class) { + return Simpletest::ignore($class); + } + + /** + * @deprecated + */ + function isIgnored($class) { + return Simpletest::isIgnored($class); + } + + /** + * @deprecated + */ + function setMockBaseClass($mock_base) { + return Simpletest::setMockBaseClass($mock_base); + } + + /** + * @deprecated + */ + function getMockBaseClass() { + return Simpletest::getMockBaseClass(); + } + + /** + * @deprecated + */ + function useProxy($proxy, $username = false, $password = false) { + return Simpletest::useProxy($proxy, $username, $password); + } + + /** + * @deprecated + */ + function getDefaultProxy() { + return Simpletest::getDefaultProxy(); + } + + /** + * @deprecated + */ + function getDefaultProxyUsername() { + return Simpletest::getDefaultProxyUsername(); + } + + /** + * @deprecated + */ + function getDefaultProxyPassword() { + return Simpletest::getDefaultProxyPassword(); + } + } +?> \ No newline at end of file diff --git a/tests/test_tools/simpletest/socket.php b/tests/test_tools/simpletest/socket.php index 4c3c592d..b627a169 100644 --- a/tests/test_tools/simpletest/socket.php +++ b/tests/test_tools/simpletest/socket.php @@ -3,13 +3,13 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage MockObjects - * @version $Id: socket.php,v 1.23 2004/09/30 16:46:31 lastcraft Exp $ + * @version $Id: socket.php,v 1.26 2005/08/29 00:57:48 lastcraft Exp $ */ /**#@+ * include SimpleTest files */ - require_once(dirname(__FILE__) . '/options.php'); + require_once(dirname(__FILE__) . '/compatibility.php'); /**#@-*/ /** @@ -73,25 +73,26 @@ */ class SimpleSocket extends SimpleStickyError { protected $_handle; - protected $_is_open; - protected $_sent; + protected $_is_open = false; + protected $_sent = ''; + public $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 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 SimpleSocket($host, $port, $timeout) { + function SimpleSocket($host, $port, $timeout, $block_size = 255) { $this->SimpleStickyError(); - $this->_is_open = false; - $this->_sent = ''; 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); } @@ -122,16 +123,15 @@ * Reads data from the socket. The error suppresion * is a workaround for PHP4 always throwing a warning * with a secure socket. - * @param integer $block_size Size of chunk to read. - * @return integer Incoming bytes. False + * @return integer/boolean Incoming bytes. False * on error. * @access public */ - function read($block_size = 255) { + function read() { if ($this->isError() || ! $this->isOpen()) { return false; } - $raw = @fread($this->_handle, $block_size); + $raw = @fread($this->_handle, $this->_block_size); if ($raw === false) { $this->_setError('Cannot read from socket'); $this->close(); diff --git a/tests/test_tools/simpletest/tag.php b/tests/test_tools/simpletest/tag.php index 9386712a..060265d2 100644 --- a/tests/test_tools/simpletest/tag.php +++ b/tests/test_tools/simpletest/tag.php @@ -3,13 +3,14 @@ * Base include file for SimpleTest. * @package SimpleTest * @subpackage WebTester - * @version $Id: tag.php,v 1.73 2005/02/02 22:49:36 lastcraft Exp $ + * @version $Id: tag.php,v 1.95 2006/02/05 00:34:29 lastcraft Exp $ */ /**#@+ * include SimpleTest files */ require_once(dirname(__FILE__) . '/parser.php'); + require_once(dirname(__FILE__) . '/encoding.php'); /**#@-*/ /** @@ -31,7 +32,7 @@ * converted to lower case. */ function SimpleTag($name, $attributes) { - $this->_name = $name; + $this->_name = strtolower(trim($name)); $this->_attributes = $attributes; $this->_content = ''; } @@ -46,6 +47,19 @@ 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. @@ -73,7 +87,7 @@ } /** - * List oflegal child elements. + * List of legal child elements. * @return array List of element names. * @access public */ @@ -92,9 +106,6 @@ if (! isset($this->_attributes[$label])) { return false; } - if ($this->_attributes[$label] === '') { - return true; - } return (string)$this->_attributes[$label]; } @@ -125,7 +136,7 @@ * @access public */ function getText() { - return SimpleSaxParser::normalise($this->_content); + return SimpleHtmlSaxParser::normalise($this->_content); } /** @@ -193,6 +204,7 @@ */ class SimpleWidget extends SimpleTag { protected $_value; + protected $_label; protected $_is_set; /** @@ -204,6 +216,7 @@ function SimpleWidget($name, $attributes) { $this->SimpleTag($name, $attributes); $this->_value = false; + $this->_label = false; $this->_is_set = false; } @@ -223,14 +236,7 @@ * @access public */ function getDefault() { - $default = $this->getAttribute('value'); - if ($default === true) { - $default = ''; - } - if ($default === false) { - $default = ''; - } - return $default; + return $this->getAttribute('value'); } /** @@ -267,6 +273,37 @@ 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); + } + + /** + * 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()); + } + } } /** @@ -326,9 +363,6 @@ */ function SimpleSubmitTag($attributes) { $this->SimpleWidget('input', $attributes); - if ($this->getAttribute('name') === false) { - $this->_setAttribute('name', 'submit'); - } if ($this->getAttribute('value') === false) { $this->_setAttribute('value', 'Submit'); } @@ -363,12 +397,13 @@ } /** - * Gets the values submitted as a form. - * @return array Hash of name and values. + * Test for a label match when searching. + * @param string $label Label to test. + * @return boolean True on match. * @access public */ - function getSubmitValues() { - return array($this->getName() => $this->getValue()); + function isLabel($label) { + return trim($label) == trim($this->getLabel()); } } @@ -420,14 +455,30 @@ } /** - * Gets the values submitted as a form. - * @return array Hash of name and values. + * Test for a label match when searching. + * @param string $label Label to test. + * @return boolean True on match. * @access public */ - function getSubmitValues($x, $y) { - return array( - $this->getName() . '.x' => $x, - $this->getName() . '.y' => $y); + 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, $y) { + if ($this->getName()) { + $encoding->add($this->getName() . '.x', $x); + $encoding->add($this->getName() . '.y', $y); + } else { + $encoding->add('x', $x); + $encoding->add('y', $y); + } } } @@ -478,19 +529,13 @@ } /** - * Gets the values submitted as a form. Gone - * for the Mozilla defaults values. - * @return array Hash of name and values. + * Test for a label match when searching. + * @param string $label Label to test. + * @return boolean True on match. * @access public */ - function getSubmitValues() { - if ($this->getAttribute('name') === false) { - return array(); - } - if ($this->getAttribute('value') === false) { - return array($this->getName() => ''); - } - return array($this->getName() => $this->getValue()); + function isLabel($label) { + return trim($label) == trim($this->getLabel()); } } @@ -516,13 +561,7 @@ * @access public */ function getDefault() { - if ($this->_wrapIsEnabled()) { - return wordwrap( - $this->getContent(), - (integer)$this->getAttribute('cols'), - "\n"); - } - return $this->getContent(); + return $this->_wrap(SimpleHtmlSaxParser::decodeHtml($this->getContent())); } /** @@ -532,13 +571,7 @@ * @access public */ function setValue($value) { - if ($this->_wrapIsEnabled()) { - $value = wordwrap( - $value, - (integer)$this->getAttribute('cols'), - "\n"); - } - return parent::setValue($value); + return parent::setValue($this->_wrap($value)); } /** @@ -555,25 +588,56 @@ } 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 + */ + 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; + } } /** - * Checkbox widget. + * File upload widget. * @package SimpleTest * @subpackage WebTester */ - class SimpleCheckboxTag extends SimpleWidget { + class SimpleUploadTag extends SimpleWidget { /** * Starts with attributes only. * @param hash $attributes Attribute names and * string values. */ - function SimpleCheckboxTag($attributes) { + function SimpleUploadTag($attributes) { $this->SimpleWidget('input', $attributes); - if ($this->getAttribute('value') === false) { - $this->_setAttribute('value', 'on'); - } } /** @@ -586,34 +650,18 @@ } /** - * The only allowed value in the one in the - * "value" attribute. The default for this - * attribute is "on". - * @param string $value New value. - * @return boolean True if allowed. + * Dispatches the value into the form encoded packet. + * @param SimpleEncoding $encoding Form packet. * @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. The default - * value is "on". - * @return string Parsed value. - * @access public - */ - function getDefault() { - if ($this->getAttribute('checked')) { - return $this->getAttribute('value'); + function write($encoding) { + if (! file_exists($this->getValue())) { + return; } - return false; + $encoding->attach( + $this->getName(), + implode('', file($this->getValue())), + basename($this->getValue())); } } @@ -664,7 +712,7 @@ */ function getDefault() { for ($i = 0, $count = count($this->_options); $i < $count; $i++) { - if ($this->_options[$i]->getAttribute('selected')) { + if ($this->_options[$i]->getAttribute('selected') !== false) { return $this->_options[$i]->getDefault(); } } @@ -682,7 +730,7 @@ */ function setValue($value) { for ($i = 0, $count = count($this->_options); $i < $count; $i++) { - if (trim($this->_options[$i]->getContent()) == trim($value)) { + if ($this->_options[$i]->isValue($value)) { $this->_choice = $i; return true; } @@ -752,7 +800,7 @@ function getDefault() { $default = array(); for ($i = 0, $count = count($this->_options); $i < $count; $i++) { - if ($this->_options[$i]->getAttribute('selected')) { + if ($this->_options[$i]->getAttribute('selected') !== false) { $default[] = $this->_options[$i]->getDefault(); } } @@ -760,25 +808,29 @@ } /** - * Can only set allowed values. - * @param array $values New choices. - * @return boolean True if allowed. + * 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($values) { - foreach ($values as $value) { - $is_option = false; + function setValue($desired) { + $achieved = array(); + foreach ($desired as $value) { + $success = false; for ($i = 0, $count = count($this->_options); $i < $count; $i++) { - if (trim($this->_options[$i]->getContent()) == trim($value)) { - $is_option = true; + if ($this->_options[$i]->isValue($value)) { + $achieved[] = $this->_options[$i]->getValue(); + $success = true; break; } } - if (! $is_option) { + if (! $success) { return false; } } - $this->_values = $values; + $this->_values = $achieved; return true; } @@ -819,6 +871,20 @@ 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($this->getContent()) == $compare; + } + /** * Accessor for starting value. Will be set to * the option label if no value exists. @@ -831,6 +897,15 @@ } return $this->getAttribute('value'); } + + /** + * The content of options is not part of the page. + * @return boolean True. + * @access public + */ + function isPrivateContent() { + return true; + } } /** @@ -861,7 +936,7 @@ } /** - * The only allowed value in the one in the + * The only allowed value sn the one in the * "value" attribute. * @param string $value New value. * @return boolean True if allowed. @@ -871,7 +946,7 @@ if ($value === false) { return parent::setValue($value); } - if ($value != $this->getAttribute('value')) { + if ($value !== $this->getAttribute('value')) { return false; } return parent::setValue($value); @@ -883,27 +958,101 @@ * @access public */ function getDefault() { - if ($this->getAttribute('checked')) { + if ($this->getAttribute('checked') !== false) { return $this->getAttribute('value'); } return false; } } - + /** - * A group of tags with the same name within a form. + * Checkbox widget. * @package SimpleTest * @subpackage WebTester */ - class SimpleCheckboxGroup { - protected $_widgets; + class SimpleCheckboxTag extends SimpleWidget { /** - * Starts empty. + * Starts with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleCheckboxTag($attributes) { + $this->SimpleWidget('input', $attributes); + if ($this->getAttribute('value') === false) { + $this->_setAttribute('value', 'on'); + } + } + + /** + * Tag contains no content. + * @return boolean False. * @access public */ - function SimpleCheckboxGroup() { - $this->_widgets = array(); + 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 { + protected $_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 + */ + function &_getWidgets() { + return $this->_widgets; } /** @@ -917,7 +1066,19 @@ } /** - * Scans the checkboxes for one with the appropriate + * 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. @@ -931,27 +1092,39 @@ } return false; } - + /** - * Adds a tag to the group. - * @param SimpleWidget $widget + * 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 addWidget($widget) { - $this->_widgets[] = $widget; + function isLabel($label) { + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($this->_widgets[$i]->isLabel($label)) { + return true; + } + } + return false; } /** - * Fetches the name for the widget from the first - * member. - * @return string Name of widget. + * Dispatches the value into the form encoded packet. + * @param SimpleEncoding $encoding Form packet. * @access public */ - function getName() { - if (count($this->_widgets) > 0) { - return $this->_widgets[0]->getName(); - } + 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 @@ -961,9 +1134,10 @@ */ function getValue() { $values = array(); - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - if ($this->_widgets[$i]->getValue()) { - $values[] = $this->_widgets[$i]->getValue(); + $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); @@ -976,9 +1150,10 @@ */ function getDefault() { $values = array(); - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - if ($this->_widgets[$i]->getDefault()) { - $values[] = $this->_widgets[$i]->getDefault(); + $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); @@ -996,12 +1171,13 @@ if (! $this->_valuesArePossible($values)) { return false; } - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - $possible = $this->_widgets[$i]->getAttribute('value'); - if (in_array($this->_widgets[$i]->getAttribute('value'), $values)) { - $this->_widgets[$i]->setValue($possible); + $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 { - $this->_widgets[$i]->setValue(false); + $widgets[$i]->setValue(false); } } return true; @@ -1017,8 +1193,9 @@ */ function _valuesArePossible($values) { $matches = array(); - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - $possible = $this->_widgets[$i]->getAttribute('value'); + $widgets = $this->_getWidgets(); + for ($i = 0, $count = count($widgets); $i < $count; $i++) { + $possible = $widgets[$i]->getAttribute('value'); if (in_array($possible, $values)) { $matches[] = $possible; } @@ -1070,63 +1247,7 @@ * @package SimpleTest * @subpackage WebTester */ - class SimpleRadioGroup { - protected $_widgets; - - /** - * Starts empty. - * @access public - */ - function SimpleRadioGroup() { - $this->_widgets = array(); - } - - /** - * Accessor for an attribute. - * @param string $label Attribute name. - * @return boolean Always false. - * @access public - */ - function getAttribute($label) { - return false; - } - - /** - * Scans the checkboxes 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; - } - - /** - * Adds a tag to the group. - * @param SimpleWidget $widget - * @access public - */ - function addWidget($widget) { - $this->_widgets[] = $widget; - } - - /** - * 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(); - } - } + class SimpleRadioGroup extends SimpleTagGroup { /** * Each tag is tried in turn until one is @@ -1141,9 +1262,10 @@ return false; } $index = false; - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - if (! $this->_widgets[$i]->setValue($value)) { - $this->_widgets[$i]->setValue(false); + $widgets = $this->_getWidgets(); + for ($i = 0, $count = count($widgets); $i < $count; $i++) { + if (! $widgets[$i]->setValue($value)) { + $widgets[$i]->setValue(false); } } return true; @@ -1156,8 +1278,9 @@ * @access private */ function _valueIsPossible($value) { - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - if ($this->_widgets[$i]->getAttribute('value') == $value) { + $widgets = $this->_getWidgets(); + for ($i = 0, $count = count($widgets); $i < $count; $i++) { + if ($widgets[$i]->getAttribute('value') == $value) { return true; } } @@ -1172,9 +1295,10 @@ * @access public */ function getValue() { - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - if ($this->_widgets[$i]->getValue()) { - return $this->_widgets[$i]->getValue(); + $widgets = $this->_getWidgets(); + for ($i = 0, $count = count($widgets); $i < $count; $i++) { + if ($widgets[$i]->getValue() !== false) { + return $widgets[$i]->getValue(); } } return false; @@ -1187,15 +1311,42 @@ * @access public */ function getDefault() { - for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { - if ($this->_widgets[$i]->getDefault()) { - return $this->_widgets[$i]->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 SimpleLabelTag($attributes) { + $this->SimpleTag('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 diff --git a/tests/test_tools/simpletest/test_case.php b/tests/test_tools/simpletest/test_case.php new file mode 100644 index 00000000..e3a1aff5 --- /dev/null +++ b/tests/test_tools/simpletest/test_case.php @@ -0,0 +1,684 @@ += 0) { + require_once(dirname(__FILE__) . '/exceptions.php'); + require_once(dirname(__FILE__) . '/reflection_php5.php'); + } else { + require_once(dirname(__FILE__) . '/reflection_php4.php'); + } + if (! defined('SIMPLE_TEST')) { + /** + * @ignore + */ + define('SIMPLE_TEST', dirname(__FILE__) . '/'); + } + /**#@-*/ + + /** + * Basic test case. This is the smallest unit of a test + * suite. It searches for + * all methods that start with the the string "test" and + * runs them. Working test cases extend this class. + * @package SimpleTest + * @subpackage UnitTester + */ + class SimpleTestCase { + protected $_label = false; + protected $_reporter; + protected $_observers; + + /** + * Sets up the test with no display. + * @param string $label If no test name is given then + * the class name is used. + * @access public + */ + function SimpleTestCase($label = false) { + 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); + } + + /** + * Used to invoke the single tests. + * @return SimpleInvoker Individual test runner. + * @access public + */ + function createInvoker() { + $invoker = new SimpleErrorTrappingInvoker(new SimpleInvoker($this)); + if (version_compare(phpversion(), '5') >= 0) { + $invoker = new SimpleExceptionTrappingInvoker($invoker); + } + return $invoker; + } + + /** + * Uses reflection to run every method within itself + * starting with the string "test" unless a method + * is specified. + * @param SimpleReporter $reporter Current test reporter. + * @access public + */ + function run($reporter) { + SimpleTest::setCurrent($this); + $this->_reporter = $reporter; + $this->_reporter->paintCaseStart($this->getLabel()); + foreach ($this->getTests() as $method) { + if ($this->_reporter->shouldInvoke($this->getLabel(), $method)) { + $invoker = $this->_reporter->createInvoker($this->createInvoker()); + $invoker->before($method); + $invoker->invoke($method); + $invoker->after($method); + } + } + $this->_reporter->paintCaseEnd($this->getLabel()); + unset($this->_reporter); + 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 + */ + 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->_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; + } + + /** + * Sends a pass event with a message. + * @param string $message Message to send. + * @access public + */ + 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->paintError( + 'Unexpected exception of type [' . get_class($exception) . + '] with message ['. $exception->getMessage() . + '] in ['. $exception->getFile() . + '] line [' . $exception->getLine() . ']'); + } + + /** + * Sends a user defined event to the test reporter. + * This is for small scale extension where + * both the test case and either the reporter or + * display are subclassed. + * @param string $type Type of event. + * @param mixed $payload Object or message to deliver. + * @access public + */ + function signal($type, $payload) { + if (! isset($this->_reporter)) { + trigger_error('Can only make assertions within test methods'); + } + $this->_reporter->paintSignal($type, $payload); + } + + /** + * Cancels any outstanding errors. + * @access public + */ + function swallowErrors() { + $queue = &SimpleErrorQueue::instance(); + $queue->clear(); + } + + /** + * Runs an expectation directly, for extending the + * tests with new expectation classes. + * @param SimpleExpectation $expectation Expectation subclass. + * @param mixed $compare Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assert($expectation, $compare, $message = '%s') { + return $this->assertTrue( + $expectation->test($compare), + sprintf($message, $expectation->overlayMessage($compare))); + } + + /** + * @deprecated + */ + function assertExpectation($expectation, $compare, $message = '%s') { + return $this->assert($expectation, $compare, $message); + } + + /** + * Called from within the test methods to register + * passes and failures. + * @param boolean $result Pass on true. + * @param string $message Message to display describing + * the test state. + * @return boolean True on pass + * @access public + */ + function assertTrue($result, $message = false) { + if (! $message) { + $message = 'True assertion got ' . ($result ? 'True' : 'False'); + } + if ($result) { + return $this->pass($message); + } else { + return $this->fail($message); + } + } + + /** + * Will be true on false and vice versa. False + * is the PHP definition of false, so that null, + * empty strings, zero and an empty array all count + * as false. + * @param boolean $result Pass on false. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertFalse($result, $message = false) { + if (! $message) { + $message = 'False assertion got ' . ($result ? 'True' : 'False'); + } + return $this->assertTrue(! $result, $message); + } + + /** + * Uses a stack trace to find the line of an assertion. + * @param string $format String formatting. + * @param array $stack Stack frames top most first. Only + * needed if not using the PHP + * backtrace function. + * @return string Line number of first assert* + * method embedded in format string. + * @access public + */ + function getAssertionLine($stack = false) { + if ($stack === false) { + $stack = SimpleTestCompatibility::getStackTrace(); + } + return SimpleDumper::getFormattedAssertionLine($stack); + } + + /** + * Sends a formatted dump of a variable to the + * test suite for those emergency debugging + * situations. + * @param mixed $variable Variable to display. + * @param string $message Message to display. + * @return mixed The original variable. + * @access public + */ + function dump($variable, $message = false) { + $formatted = SimpleDumper::dump($variable); + if ($message) { + $formatted = $message . "\n" . $formatted; + } + $this->_reporter->paintFormattedMessage($formatted); + return $variable; + } + + /** + * Dispatches a text message straight to the + * test suite. Useful for status bar displays. + * @param string $message Message to show. + * @access public + */ + function sendMessage($message) { + $this->_reporter->PaintMessage($message); + } + + /** + * Accessor for the number of subtests. + * @return integer Number of test cases. + * @access public + * @static + */ + function getSize() { + return 1; + } + } + + /** + * This is a composite test class for combining + * test cases and other RunnableTest classes into + * a group test. + * @package SimpleTest + * @subpackage UnitTester + */ + class GroupTest { + protected $_label; + protected $_test_cases; + protected $_old_track_errors; + protected $_xdebug_is_enabled; + + /** + * Sets the name of the test suite. + * @param string $label Name sent at the start and end + * of the test. + * @access public + */ + function GroupTest($label = false) { + $this->_label = $label ? $label : get_class($this); + $this->_test_cases = array(); + $this->_old_track_errors = ini_get('track_errors'); + $this->_xdebug_is_enabled = function_exists('xdebug_is_enabled') ? + xdebug_is_enabled() : false; + } + + /** + * Accessor for the test name for subclasses. + * @return string Name of the test. + * @access public + */ + function getLabel() { + return $this->_label; + } + + /** + * Adds a test into the suite. Can be either a group + * test or some other unit test. + * @param SimpleTestCase $test_case Suite or individual test + * case implementing the + * runnable test interface. + * @access public + */ + function addTestCase($test_case) { + $this->_test_cases[] = $test_case; + } + + /** + * Adds a test into the suite by class name. The class will + * be instantiated as needed. + * @param SimpleTestCase $test_case Suite or individual test + * case implementing the + * runnable test interface. + * @access public + */ + function addTestClass($class) { + if ($this->_getBaseTestCase($class) == 'grouptest') { + $this->_test_cases[] = new $class(); + } else { + $this->_test_cases[] = $class; + } + } + + /** + * Builds a group test from a library of test cases. + * The new group is composed into this one. + * @param string $test_file File name of library with + * test case classes. + * @access public + */ + function addTestFile($test_file) { + $existing_classes = get_declared_classes(); + if ($error = $this->_requireWithError($test_file)) { + $this->addTestCase(new BadGroupTest($test_file, $error)); + return; + } + $classes = $this->_selectRunnableTests($existing_classes, get_declared_classes()); + if (count($classes) == 0) { + $this->addTestCase(new BadGroupTest($test_file, "No runnable test cases in [$test_file]")); + return; + } + $group = $this->_createGroupFromClasses($test_file, $classes); + $this->addTestCase($group); + } + + /** + * Requires a source file recording any syntax errors. + * @param string $file File name to require in. + * @return string/boolean An error message on failure or false + * if no errors. + * @access private + */ + function _requireWithError($file) { + $this->_enableErrorReporting(); + include($file); + $error = isset($php_errormsg) ? $php_errormsg : false; + $this->_disableErrorReporting(); + $self_inflicted_errors = array( + 'Assigning the return value of new by reference is deprecated', + 'var: Deprecated. Please use the public/private/protected modifiers'); + if (in_array($error, $self_inflicted_errors)) { + return false; + } + return $error; + } + + /** + * Sets up detection of parse errors. Note that XDebug + * interferes with this and has to be disabled. This is + * to make sure the correct error code is returned + * from unattended scripts. + * @access private + */ + function _enableErrorReporting() { + if ($this->_xdebug_is_enabled) { + xdebug_disable(); + } + ini_set('track_errors', true); + } + + /** + * Resets detection of parse errors to their old values. + * This is to make sure the correct error code is returned + * from unattended scripts. + * @access private + */ + function _disableErrorReporting() { + ini_set('track_errors', $this->_old_track_errors); + if ($this->_xdebug_is_enabled) { + xdebug_enable(); + } + } + + /** + * Calculates the incoming test cases from a before + * and after list of loaded classes. Skips abstract + * classes. + * @param array $existing_classes Classes before require(). + * @param array $new_classes Classes after require(). + * @return array New classes which are test + * cases that shouldn't be ignored. + * @access private + */ + function _selectRunnableTests($existing_classes, $new_classes) { + $classes = array(); + foreach ($new_classes as $class) { + if (in_array($class, $existing_classes)) { + continue; + } + if ($this->_getBaseTestCase($class)) { + $reflection = new SimpleReflection($class); + if ($reflection->isAbstract()) { + SimpleTest::ignore($class); + } + $classes[] = $class; + } + } + return $classes; + } + + /** + * Builds a group test from a class list. + * @param string $title Title of new group. + * @param array $classes Test classes. + * @return GroupTest Group loaded with the new + * test cases. + * @access private + */ + function &_createGroupFromClasses($title, $classes) { + SimpleTest::ignoreParentsIfIgnored($classes); + $group = new GroupTest($title); + foreach ($classes as $class) { + if (! SimpleTest::isIgnored($class)) { + $group->addTestClass($class); + } + } + return $group; + } + + /** + * Test to see if a class is derived from the + * SimpleTestCase class. + * @param string $class Class name. + * @access private + */ + function _getBaseTestCase($class) { + while ($class = get_parent_class($class)) { + $class = strtolower($class); + if ($class == "simpletestcase" || $class == "grouptest") { + return $class; + } + } + return false; + } + + /** + * Delegates to a visiting collector to add test + * files. + * @param string $path Path to scan from. + * @param SimpleCollector $collector Directory scanner. + * @access public + */ + function collect($path, $collector) { + $collector->collect($this, $path); + } + + /** + * Invokes run() on all of the held test cases, instantiating + * them if necessary. + * @param SimpleReporter $reporter Current test reporter. + * @access public + */ + 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); + } 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)) { + $count++; + } else { + $count += $case->getSize(); + } + } + return $count; + } + } + + /** + * This is a failing group test for when a test suite hasn't + * loaded properly. + * @package SimpleTest + * @subpackage UnitTester + */ + class BadGroupTest { + protected $_label; + protected $_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 BadGroupTest($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 GroupTest [' . $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/tests/test_tools/simpletest/unit_tester.php b/tests/test_tools/simpletest/unit_tester.php index fa5e28b4..88e10b14 100644 --- a/tests/test_tools/simpletest/unit_tester.php +++ b/tests/test_tools/simpletest/unit_tester.php @@ -3,17 +3,16 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage UnitTester - * @version $Id: unit_tester.php,v 1.24 2005/01/13 01:31:53 lastcraft Exp $ + * @version $Id: unit_tester.php,v 1.31 2006/02/06 06:05:18 lastcraft Exp $ */ /**#@+ * include other SimpleTest class files */ - require_once(dirname(__FILE__) . '/simple_test.php'); - require_once(dirname(__FILE__) . '/errors.php'); + 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 @@ -22,7 +21,7 @@ * @subpackage UnitTester */ class UnitTestCase extends SimpleTestCase { - + /** * Creates an empty test case. Should be subclassed * with test methods for a functional test case. @@ -36,7 +35,7 @@ } $this->SimpleTestCase($label); } - + /** * Will be true if the value is null. * @param null $value Supposedly null value. @@ -51,7 +50,7 @@ "[" . $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. @@ -66,7 +65,7 @@ "[" . $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 @@ -78,12 +77,12 @@ * @access public */ function assertIsA($object, $type, $message = "%s") { - return $this->assertExpectation( + return $this->assert( new IsAExpectation($type), $object, $message); } - + /** * Type and class mismatch test. Will pass if class * name or underling type does not match the one @@ -95,12 +94,12 @@ * @access public */ function assertNotA($object, $type, $message = "%s") { - return $this->assertExpectation( + return $this->assert( new NotAExpectation($type), $object, $message); } - + /** * Will trigger a pass if the two parameters have * the same value only. Otherwise a fail. @@ -111,12 +110,12 @@ * @access public */ function assertEqual($first, $second, $message = "%s") { - return $this->assertExpectation( + return $this->assert( new EqualExpectation($first), $second, $message); } - + /** * Will trigger a pass if the two parameters have * a different value. Otherwise a fail. @@ -127,12 +126,46 @@ * @access public */ function assertNotEqual($first, $second, $message = "%s") { - return $this->assertExpectation( + return $this->assert( new NotEqualExpectation($first), $second, $message); } - + + /** + * Will trigger a pass if the 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. @@ -143,12 +176,12 @@ * @access public */ function assertIdentical($first, $second, $message = "%s") { - return $this->assertExpectation( + return $this->assert( new IdenticalExpectation($first), $second, $message); } - + /** * Will trigger a pass if the two parameters have * the different value or different type. @@ -159,12 +192,12 @@ * @access public */ function assertNotIdentical($first, $second, $message = "%s") { - return $this->assertExpectation( + return $this->assert( new NotIdenticalExpectation($first), $second, $message); } - + /** * Will trigger a pass if both parameters refer * to the same object. Fail otherwise. @@ -185,16 +218,34 @@ SimpleTestCompatibility::isReference($first, $second), $message); } - + /** * Will trigger a pass if both parameters refer - * to different objects. Fail otherwise. + * 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) && + ! SimpleTestCompatibility::isReference($first, $second), + $message); + } + + /** + * @deprecated + */ function assertCopy($first, $second, $message = "%s") { $dumper = new SimpleDumper(); $message = sprintf( @@ -206,7 +257,7 @@ SimpleTestCompatibility::isReference($first, $second), $message); } - + /** * Will trigger a pass if the Perl regex pattern * is found in the subject. Fail otherwise. @@ -217,13 +268,20 @@ * @return boolean True on pass * @access public */ - function assertWantedPattern($pattern, $subject, $message = "%s") { - return $this->assertExpectation( - new WantedPatternExpectation($pattern), + function assertPattern($pattern, $subject, $message = "%s") { + return $this->assert( + new PatternExpectation($pattern), $subject, $message); } - + + /** + * @deprecated + */ + function assertWantedPattern($pattern, $subject, $message = "%s") { + return $this->assertPattern($pattern, $subject, $message); + } + /** * Will trigger a pass if the perl regex pattern * is not present in subject. Fail if found. @@ -234,13 +292,20 @@ * @return boolean True on pass * @access public */ - function assertNoUnwantedPattern($pattern, $subject, $message = "%s") { - return $this->assertExpectation( - new UnwantedPatternExpectation($pattern), + function assertNoPattern($pattern, $subject, $message = "%s") { + return $this->assert( + new NoPatternExpectation($pattern), $subject, $message); } - + + /** + * @deprecated + */ + function assertNoUnwantedPattern($pattern, $subject, $message = "%s") { + return $this->assertNoPattern($pattern, $subject, $message); + } + /** * Confirms that no errors have occoured so * far in the test method. @@ -249,12 +314,12 @@ * @access public */ function assertNoErrors($message = "%s") { - $queue =SimpleErrorQueue::instance(); + $queue = &SimpleErrorQueue::instance(); return $this->assertTrue( $queue->isEmpty(), sprintf($message, "Should be no errors")); } - + /** * Confirms that an error has occoured and * optionally that the error text matches exactly. @@ -265,39 +330,44 @@ * @access public */ function assertError($expected = false, $message = "%s") { - $queue =SimpleErrorQueue::instance(); + $queue = &SimpleErrorQueue::instance(); if ($queue->isEmpty()) { $this->fail(sprintf($message, "Expected error not found")); return; } list($severity, $content, $file, $line, $globals) = $queue->extract(); $severity = SimpleErrorQueue::getSeverityAsString($severity); - return $this->assertTrue( - ! $expected || ($expected == $content), - "Expected [$expected] in PHP error [$content] severity [$severity] in [$file] line [$line]"); + if (! $expected) { + return $this->pass( + "Captured a PHP error of [$content] severity [$severity] in [$file] line [$line] -> %s"); + } + $expected = $this->_coerceToExpectation($expected); + return $this->assert( + $expected, + $content, + "Expected PHP error [$content] severity [$severity] in [$file] line [$line] -> %s"); } - + /** - * Confirms that an error has occoured and - * that the error text matches a Perl regular - * expression. - * @param string $pattern Perl regular expresion to - * match against. - * @param string $message Message to display. - * @return boolean True on pass - * @access public + * Creates an equality expectation if the + * object/value is not already some type + * of expectation. + * @param mixed $expected Expected value. + * @return SimpleExpectation Expectation object. + * @access private */ - function assertErrorPattern($pattern, $message = "%s") { - $queue =SimpleErrorQueue::instance(); - if ($queue->isEmpty()) { - $this->fail(sprintf($message, "Expected error not found")); - return; + function _coerceToExpectation($expected) { + if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) { + return $expected; } - list($severity, $content, $file, $line, $globals) = $queue->extract(); - $severity = SimpleErrorQueue::getSeverityAsString($severity); - return $this->assertTrue( - (boolean)preg_match($pattern, $content), - "Expected pattern match [$pattern] in PHP error [$content] severity [$severity] in [$file] line [$line]"); + return new EqualExpectation($expected); + } + + /** + * @deprecated + */ + function assertErrorPattern($pattern, $message = "%s") { + return $this->assertError(new PatternExpectation($pattern), $message); } } ?> diff --git a/tests/test_tools/simpletest/url.php b/tests/test_tools/simpletest/url.php index 03902ed0..5bfceb14 100644 --- a/tests/test_tools/simpletest/url.php +++ b/tests/test_tools/simpletest/url.php @@ -3,7 +3,7 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage WebTester - * @version $Id: url.php,v 1.22 2005/02/02 23:25:23 lastcraft Exp $ + * @version $Id: url.php,v 1.29 2006/01/14 02:45:34 lastcraft Exp $ */ /**#@+ @@ -17,7 +17,8 @@ * 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. + * the path and tries to keep a raw, possibly unparsable, + * request string as long as possible. * @package SimpleTest * @subpackage WebTester */ @@ -30,7 +31,10 @@ protected $_path; protected $_request; protected $_fragment; + protected $_x; + protected $_y; protected $_target; + protected $_raw = false; /** * Constructor. Parses URL into sections. @@ -39,6 +43,7 @@ */ function SimpleUrl($url) { list($x, $y) = $this->_chompCoordinates($url); + $this->setCoordinates($x, $y); $this->_scheme = $this->_chompScheme($url); list($this->_username, $this->_password) = $this->_chompLogin($url); $this->_host = $this->_chompHost($url); @@ -49,7 +54,6 @@ } $this->_path = $this->_chompPath($url); $this->_request = $this->_parseRequest($this->_chompRequest($url)); - $this->_request->setCoordinates($x, $y); $this->_fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false); $this->_target = false; } @@ -96,7 +100,7 @@ */ function _chompLogin($url) { $prefix = ''; - if (preg_match('/(\/\/)(.*)/', $url, $matches)) { + if (preg_match('/^(\/\/)(.*)/', $url, $matches)) { $prefix = $matches[1]; $url = $matches[2]; } @@ -123,7 +127,7 @@ * @access private */ function _chompHost($url) { - if (preg_match('/(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) { + if (preg_match('/^(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) { $url = $matches[3]; return $matches[2]; } @@ -178,7 +182,8 @@ * @access private */ function _parseRequest($raw) { - $request = new SimpleFormEncoding(); + $this->_raw = $raw; + $request = new SimpleGetEncoding(); foreach (split("&", $raw) as $pair) { if (preg_match('/(.*?)=(.*)/', $pair, $matches)) { $request->add($matches[1], urldecode($matches[2])); @@ -292,13 +297,29 @@ 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->_request->getX(); + return $this->_x; } /** @@ -307,17 +328,23 @@ * @access public */ function getY() { - return $this->_request->getY(); + return $this->_y; } /** * Accessor for current request parameters - * in URL string form + * in URL string form. Will return teh original request + * if at all possible even if it doesn't make much + * sense. * @return string Form is string "?a=1&b=2", etc. * @access public */ function getEncodedRequest() { - $encoded = $this->_request->asString(); + if ($this->_raw) { + $encoded = $this->_raw; + } else { + $encoded = $this->_request->asUrlRequest(); + } if ($encoded) { return '?' . preg_replace('/^\?/', '', $encoded); } @@ -331,6 +358,7 @@ * @access public */ function addRequestParameter($key, $value) { + $this->_raw = false; $this->_request->add($key, $value); } @@ -341,6 +369,7 @@ * @access public */ function addRequestParameters($parameters) { + $this->_raw = false; $this->_request->merge($parameters); } @@ -349,18 +378,8 @@ * @access public */ function clearRequest() { - $this->_request = new SimpleFormEncoding(); - } - - /** - * Sets image coordinates. Set to flase to clear - * them. - * @param integer $x Horizontal position. - * @param integer $y Vertical position. - * @access public - */ - function setCoordinates($x = false, $y = false) { - $this->_request->setCoordinates($x, $y); + $this->_raw = false; + $this->_request = new SimpleGetEncoding(); } /** @@ -380,6 +399,7 @@ * @access public */ function setTarget($frame) { + $this->_raw = false; $this->_target = $frame; } @@ -402,7 +422,8 @@ } $encoded = $this->getEncodedRequest(); $fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; - return "$scheme://$identity$host$path$encoded$fragment"; + $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); + return "$scheme://$identity$host$path$encoded$fragment$coords"; } /** @@ -417,27 +438,23 @@ $base = new SimpleUrl($base); } $scheme = $this->getScheme() ? $this->getScheme() : $base->getScheme(); - $host = $this->getHost() ? $this->getHost() : $base->getHost(); - $port = $this->_extractAbsolutePort($base); + if ($this->getHost()) { + $host = $this->getHost(); + $port = $this->getPort() ? ':' . $this->getPort() : ''; + $identity = $this->getIdentity() ? $this->getIdentity() . '@' : ''; + if (! $identity) { + $identity = $base->getIdentity() ? $base->getIdentity() . '@' : ''; + } + } else { + $host = $base->getHost(); + $port = $base->getPort() ? ':' . $base->getPort() : ''; + $identity = $base->getIdentity() ? $base->getIdentity() . '@' : ''; + } $path = $this->normalisePath($this->_extractAbsolutePath($base)); - $identity = $this->_getIdentity() ? $this->_getIdentity() . '@' : ''; $encoded = $this->getEncodedRequest(); $fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; - return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment"); - } - - /** - * Extracts the port from the base URL if it's needed, but - * not present, in the current URL. - * @param string/SimpleUrl $base Base URL. - * @param string Absolute port number. - * @access private - */ - function _extractAbsolutePort($base) { - if ($this->getHost()) { - return ($this->getPort() ? ':' . $this->getPort() : ''); - } - return ($base->getPort() ? ':' . $base->getPort() : ''); + $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); + return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords"); } /** @@ -473,10 +490,10 @@ /** * Extracts the username and password for use in rendering * a URL. - * @return string/boolean Form of username:password@ or false. - * @access private + * @return string/boolean Form of username:password or false. + * @access public */ - function _getIdentity() { + function getIdentity() { if ($this->_username && $this->_password) { return $this->_username . ':' . $this->_password; } diff --git a/tests/test_tools/simpletest/user_agent.php b/tests/test_tools/simpletest/user_agent.php index c65d5110..7216cbd1 100644 --- a/tests/test_tools/simpletest/user_agent.php +++ b/tests/test_tools/simpletest/user_agent.php @@ -3,153 +3,24 @@ * Base include file for SimpleTest * @package SimpleTest * @subpackage WebTester - * @version $Id: user_agent.php,v 1.43 2005/01/02 22:46:08 lastcraft Exp $ + * @version $Id: user_agent.php,v 1.55 2005/12/07 18:04:58 lastcraft Exp $ */ /**#@+ * 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'); /**#@-*/ - define('DEFAULT_MAX_REDIRECTS', 3); - define('DEFAULT_CONNECTION_TIMEOUT', 15); + if (! defined('DEFAULT_MAX_REDIRECTS')) { + define('DEFAULT_MAX_REDIRECTS', 3); + } - /** - * Repository for cookies. This stuff is a - * tiny bit browser dependent. - * @package SimpleTest - * @subpackage WebTester - */ - class SimpleCookieJar { - protected $_cookies; - - /** - * Constructor. Jar starts empty. - * @access public - */ - function SimpleCookieJar() { - $this->_cookies = array(); - } - - /** - * Removes expired and temporary cookies as if - * the browser was closed and re-opened. - * @param string/integer $now Time to test expiry against. - * @access public - */ - 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); - } - } - - /** - * Adds a cookie to the jar. This will overwrite - * cookies with matching host, paths and keys. - * @param SimpleCookie $cookie New cookie. - * @access public - */ - function setCookie($cookie) { - for ($i = 0; $i < count($this->_cookies); $i++) { - $is_match = $this->_isMatch( - $cookie, - $this->_cookies[$i]->getHost(), - $this->_cookies[$i]->getPath(), - $this->_cookies[$i]->getName()); - if ($is_match) { - $this->_cookies[$i] = $cookie; - return; - } - } - $this->_cookies[] = $cookie; - } - - /** - * Fetches a hash of all valid cookies filtered - * by host, path and keyed by name - * Any cookies with missing categories will not - * be filtered out by that category. Expired - * cookies must be cleared by restarting the session. - * @param string $host Host name requirement. - * @param string $path Path encompassing cookies. - * @return hash Valid cookie objects keyed - * on the cookie name. - * @access public - */ - function getValidCookies($host = false, $path = "/") { - $valid_cookies = array(); - foreach ($this->_cookies as $cookie) { - if ($this->_isMatch($cookie, $host, $path, $cookie->getName())) { - $valid_cookies[] = $cookie; - } - } - return $valid_cookies; - } - - /** - * Tests cookie for matching against search - * criteria. - * @param SimpleTest $cookie Cookie to test. - * @param string $host Host must match. - * @param string $path Cookie path must be shorter than - * this path. - * @param string $name Name must match. - * @return boolean True if matched. - * @access private - */ - 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; - } - - /** - * Adds the current cookies to a request. - * @param SimpleHttpRequest $request Request to modify. - * @param SimpleUrl $url Cookie selector. - * @access private - */ - function addHeaders($request, $url) { - $cookies = $this->getValidCookies($url->getHost(), $url->getPath()); - foreach ($cookies as $cookie) { - $request->setCookie($cookie); - } - } + if (! defined('DEFAULT_CONNECTION_TIMEOUT')) { + define('DEFAULT_CONNECTION_TIMEOUT', 15); } /** @@ -160,13 +31,14 @@ */ class SimpleUserAgent { protected $_cookie_jar; + protected $_cookies_enabled = true; protected $_authenticator; - protected $_max_redirects; - protected $_proxy; - protected $_proxy_username; - protected $_proxy_password; - protected $_connection_timeout; - protected $_additional_headers; + protected $_max_redirects = DEFAULT_MAX_REDIRECTS; + protected $_proxy = false; + protected $_proxy_username = false; + protected $_proxy_password = false; + protected $_connection_timeout = DEFAULT_CONNECTION_TIMEOUT; + protected $_additional_headers = array(); /** * Starts with no cookies, realms or proxies. @@ -175,12 +47,6 @@ function SimpleUserAgent() { $this->_cookie_jar = new SimpleCookieJar(); $this->_authenticator = new SimpleAuthenticator(); - $this->setMaximumRedirects(DEFAULT_MAX_REDIRECTS); - $this->_proxy = false; - $this->_proxy_username = false; - $this->_proxy_password = false; - $this->setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT); - $this->_additional_headers = array(); } /** @@ -227,11 +93,7 @@ * @access public */ function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { - $cookie = new SimpleCookie($name, $value, $path, $expiry); - if ($host) { - $cookie->setHost($host); - } - $this->_cookie_jar->setCookie($cookie); + $this->_cookie_jar->setCookie($name, $value, $host, $path, $expiry); } /** @@ -245,23 +107,14 @@ * @access public */ function getCookieValue($host, $path, $name) { - $longest_path = ''; - foreach ($this->_cookie_jar->getValidCookies($host, $path) as $cookie) { - if ($name == $cookie->getName()) { - if (strlen($cookie->getPath()) > strlen($longest_path)) { - $value = $cookie->getValue(); - $longest_path = $cookie->getPath(); - } - } - } - return (isset($value) ? $value : false); + 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 Null if there is no base URL, false + * @return string/boolean Null if there is no base URL, false * if the cookie is not set. * @access public */ @@ -272,6 +125,22 @@ 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. @@ -305,7 +174,7 @@ $this->_proxy = false; return; } - if (strncmp($proxy, 'http://', 7) != 0) { + if ((strncmp($proxy, 'http://', 7) != 0) && (strncmp($proxy, 'https://', 8) != 0)) { $proxy = 'http://'. $proxy; } $this->_proxy = new SimpleUrl($proxy); @@ -338,18 +207,17 @@ /** * Fetches a URL as a response object. Will keep trying if redirected. * It will also collect authentication realm information. - * @param string $method GET, POST, etc. - * @param string/SimpleUrl $url Target to fetch. - * @param SimpleFormEncoding $parameters Additional parameters for request. - * @return SimpleHttpResponse Hopefully the target page. + * @param string/SimpleUrl $url Target to fetch. + * @param SimpleEncoding $encoding Additional parameters for request. + * @return SimpleHttpResponse Hopefully the target page. * @access public */ - function fetchResponse($method, $url, $parameters = false) { - if ($method != 'POST') { - $url->addRequestParameters($parameters); - $parameters = false; + function &fetchResponse($url, $encoding) { + if ($encoding->getMethod() != 'POST') { + $url->addRequestParameters($encoding); + $encoding->clear(); } - $response = $this->_fetchWhileRedirected($method, $url, $parameters); + $response = $this->_fetchWhileRedirected($url, $encoding); if ($headers = $response->getHeaders()) { if ($headers->isChallenge()) { $this->_authenticator->addRealm( @@ -364,84 +232,72 @@ /** * Fetches the page until no longer redirected or * until the redirect limit runs out. - * @param string $method GET, POST, etc. * @param SimpleUrl $url Target to fetch. - * @param SimpelFormEncoding $parameters Additional parameters for request. + * @param SimpelFormEncoding $encoding Additional parameters for request. * @return SimpleHttpResponse Hopefully the target page. * @access private */ - function _fetchWhileRedirected($method, $url, $parameters) { + function &_fetchWhileRedirected($url, $encoding) { $redirects = 0; do { - $response = $this->_fetch($method, $url, $parameters); + $response = $this->_fetch($url, $encoding); if ($response->isError()) { return $response; } $headers = $response->getHeaders(); $location = new SimpleUrl($headers->getLocation()); $url = $location->makeAbsolute($url); - $this->_addCookiesToJar($url, $headers->getNewCookies()); + if ($this->_cookies_enabled) { + $headers->writeCookiesToJar($this->_cookie_jar, $url); + } if (! $headers->isRedirect()) { break; } - $method = 'GET'; - $parameters = false; + $encoding = new SimpleGetEncoding(); } while (! $this->_isTooManyRedirects(++$redirects)); return $response; } /** * Actually make the web request. - * @param string $method GET, POST, etc. * @param SimpleUrl $url Target to fetch. - * @param SimpleFormEncoding $parameters Additional parameters for request. + * @param SimpleFormEncoding $encoding Additional parameters for request. * @return SimpleHttpResponse Headers and hopefully content. * @access protected */ - function _fetch($method, $url, $parameters) { - if (! $parameters) { - $parameters = new SimpleFormEncoding(); - } - $request = $this->_createRequest($method, $url, $parameters); - return $request->fetch($this->_connection_timeout); + function &_fetch($url, $encoding) { + $request = $this->_createRequest($url, $encoding); + $response = $request->fetch($this->_connection_timeout); + return $response; } /** * Creates a full page request. - * @param string $method Fetching method. - * @param SimpleUrl $url Target to fetch as url object. - * @param SimpleFormEncoding $parameters POST/GET parameters. - * @return SimpleHttpRequest New request. + * @param SimpleUrl $url Target to fetch as url object. + * @param SimpleFormEncoding $encoding POST/GET parameters. + * @return SimpleHttpRequest New request. * @access private */ - function _createRequest($method, $url, $parameters) { - $request = $this->_createHttpRequest($method, $url, $parameters); + function &_createRequest($url, $encoding) { + $request = $this->_createHttpRequest($url, $encoding); $this->_addAdditionalHeaders($request); - $this->_cookie_jar->addHeaders($request, $url); + if ($this->_cookies_enabled) { + $request->readCookiesFromJar($this->_cookie_jar, $url); + } $this->_authenticator->addHeaders($request, $url); return $request; } /** * Builds the appropriate HTTP request object. - * @param string $method Fetching method. * @param SimpleUrl $url Target to fetch as url object. * @param SimpleFormEncoding $parameters POST/GET parameters. * @return SimpleHttpRequest New request object. * @access protected */ - function _createHttpRequest($method, $url, $parameters) { - if ($method == 'POST') { - $request = new SimpleHttpRequest( - $this->_createRoute($url), - 'POST', - $parameters); - return $request; - } - if ($parameters) { - $url->addRequestParameters($parameters); - } - return new SimpleHttpRequest($this->_createRoute($url), $method); + function &_createHttpRequest($url, $encoding) { + $request = new SimpleHttpRequest($this->_createRoute($url), $encoding); + return $request; } /** @@ -450,15 +306,17 @@ * @return SimpleRoute Route to take to fetch URL. * @access protected */ - function _createRoute($url) { + function &_createRoute($url) { if ($this->_proxy) { - return new SimpleProxyRoute( + $route = new SimpleProxyRoute( $url, $this->_proxy, $this->_proxy_username, $this->_proxy_password); + } else { + $route = new SimpleRoute($url); } - return new SimpleRoute($url); + return $route; } /** @@ -471,20 +329,5 @@ $request->addHeaderLine($header); } } - - /** - * Extracts new cookies into the cookie jar. - * @param SimpleUrl $url Target to fetch as url object. - * @param array $cookies New cookies. - * @access private - */ - function _addCookiesToJar($url, $cookies) { - foreach ($cookies as $cookie) { - if ($url->getHost()) { - $cookie->setHost($url->getHost()); - } - $this->_cookie_jar->setCookie($cookie); - } - } } ?> \ No newline at end of file diff --git a/tests/test_tools/simpletest/web_tester.php b/tests/test_tools/simpletest/web_tester.php index 4981d25a..203f729b 100644 --- a/tests/test_tools/simpletest/web_tester.php +++ b/tests/test_tools/simpletest/web_tester.php @@ -3,13 +3,13 @@ * Base include file for SimpleTest. * @package SimpleTest * @subpackage WebTester - * @version $Id: web_tester.php,v 1.92 2005/02/22 02:39:22 lastcraft Exp $ + * @version $Id: web_tester.php,v 1.114 2006/02/05 02:04:24 lastcraft Exp $ */ /**#@+ * include other SimpleTest class files */ - require_once(dirname(__FILE__) . '/simple_test.php'); + 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'); @@ -25,11 +25,14 @@ /** * Sets the field value to compare against. - * @param mixed $value Test value to match. + * @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 FieldExpectation($value) { - $this->SimpleExpectation(); + function FieldExpectation($value, $message = '%s') { + $this->SimpleExpectation($message); if (is_array($value)) { sort($value); } @@ -135,16 +138,21 @@ /** * Sets the field and value to compare against. * @param string $header Case insenstive trimmed header name. - * @param string $value Optional value to compare. If not - * given then any value will match. - */ - function HttpHeaderExpectation($header, $value = false) { + * @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 HttpHeaderExpectation($header, $value = false, $message = '%s') { + $this->SimpleExpectation($message); $this->_expected_header = $this->_normaliseHeader($header); $this->_expected_value = $value; } /** - * Accessor for subclases. + * Accessor for aggregated object. * @return mixed Expectation set in constructor. * @access protected */ @@ -198,7 +206,7 @@ * @access private */ function _testHeaderLine($line) { - if (count($parsed = split(':', $line)) < 2) { + if (count($parsed = split(':', $line, 2)) < 2) { return false; } list($header, $value) = $parsed; @@ -219,6 +227,9 @@ if ($expected === false) { return true; } + if (SimpleExpectation::isExpectation($expected)) { + return $expected->test(trim($value)); + } return (trim($value) == trim($expected)); } @@ -230,14 +241,16 @@ * @access public */ function testMessage($compare) { - $expectation = $this->_expected_header; - if ($this->_expected_value) { - $expectation .= ': ' . $this->_expected_header; + if (SimpleExpectation::isExpectation($this->_expected_value)) { + $message = $this->_expected_value->testMessage($compare); + } else { + $message = $this->_expected_header . + ($this->_expected_value ? ': ' . $this->_expected_value : ''); } if (is_string($line = $this->_findHeader($compare))) { - return "Searching for header [$expectation] found [$line]"; + return "Searching for header [$message] found [$line]"; } else { - return "Failed to find header [$expectation]"; + return "Failed to find header [$message]"; } } } @@ -248,16 +261,18 @@ * @package SimpleTest * @subpackage WebTester */ - class HttpUnwantedHeaderExpectation extends HttpHeaderExpectation { + class NoHttpHeaderExpectation extends HttpHeaderExpectation { protected $_expected_header; protected $_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 HttpUnwantedHeaderExpectation($unwanted) { - $this->HttpHeaderExpectation($unwanted); + function NoHttpHeaderExpectation($unwanted, $message = '%s') { + $this->HttpHeaderExpectation($unwanted, false, $message); } /** @@ -286,42 +301,13 @@ } } } - - /** - * Test for a specific HTTP header within a header block. - * @package SimpleTest - * @subpackage WebTester - */ - class HttpHeaderPatternExpectation extends HttpHeaderExpectation { - - /** - * Sets the field and value to compare against. - * @param string $header Case insenstive header name. - * @param string $pattern Pattern to compare value against. - * @access public - */ - function HttpHeaderPatternExpectation($header, $pattern) { - $this->HttpHeaderExpectation($header, $pattern); - } - - /** - * Tests the value part of the header. - * @param string $value Value to test. - * @param mixed $pattern Pattern to test against. - * @return boolean True if matched. - * @access protected - */ - function _testHeaderValue($value, $expected) { - return (boolean)preg_match($expected, trim($value)); - } - } /** * Test for a text substring. * @package SimpleTest * @subpackage UnitTester */ - class WantedTextExpectation extends SimpleExpectation { + class TextExpectation extends SimpleExpectation { protected $_substring; /** @@ -330,7 +316,7 @@ * @param string $message Customised message on failure. * @access public */ - function WantedTextExpectation($substring, $message = '%s') { + function TextExpectation($substring, $message = '%s') { $this->SimpleExpectation($message); $this->_substring = $substring; } @@ -395,7 +381,7 @@ * @package SimpleTest * @subpackage UnitTester */ - class UnwantedTextExpectation extends WantedTextExpectation { + class NoTextExpectation extends TextExpectation { /** * Sets the reject pattern @@ -403,8 +389,8 @@ * @param string $message Customised message on failure. * @access public */ - function UnwantedTextExpectation($substring, $message = '%s') { - $this->WantedTextExpectation($substring, $message); + function NoTextExpectation($substring, $message = '%s') { + $this->TextExpectation($substring, $message); } /** @@ -437,36 +423,6 @@ } } - /** - * Extension that builds a web browser at the start of each - * test. - * @package SimpleTest - * @subpackage WebTester - */ - class WebTestCaseInvoker extends SimpleInvokerDecorator { - - /** - * Takes in the test case and reporter to mediate between. - * @param SimpleTestCase $test_case Test case to run. - * @param SimpleScorer $scorer Reporter to receive events. - */ - function WebTestCaseInvoker($invoker) { - $this->SimpleInvokerDecorator($invoker); - } - - /** - * Builds the browser and runs the test. - * @param string $method Test method to call. - * @access public - */ - function invoke($method) { - $test = $this->getTestCase(); - $test->setBrowser($test->createBrowser()); - parent::invoke($method); - $test->unsetBrowser(); - } - } - /** * Test case for testing of web pages. Allows * fetching of pages, parsing of HTML and @@ -476,6 +432,7 @@ */ class WebTestCase extends SimpleTestCase { protected $_browser; + protected $_ignore_errors = false; /** * Creates an empty test case. Should be subclassed @@ -489,13 +446,23 @@ } /** - * Sets the invoker to one that restarts the browser on - * each request. - * @return SimpleInvoker Invoker for each method. + * Announces the start of the test. + * @param string $method Test method just started. * @access public */ - function createInvoker() { - return new WebTestCaseInvoker(parent::createInvoker()); + 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); } /** @@ -505,7 +472,7 @@ * @return SimpleBrowser Current test browser object. * @access public */ - function getBrowser() { + function &getBrowser() { return $this->_browser; } @@ -535,8 +502,9 @@ * @return TestBrowser New browser. * @access public */ - function createBrowser() { - return new SimpleBrowser(); + function &createBrowser() { + $browser = new SimpleBrowser(); + return $browser; } /** @@ -581,6 +549,14 @@ 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. @@ -618,6 +594,42 @@ 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 + */ + 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. @@ -673,15 +685,11 @@ * the base URL reflects the new location. * @param string $url URL to fetch. * @param hash $parameters Optional additional GET data. - * @return boolean True on success. + * @return boolean/string Raw page on success. * @access public */ function get($url, $parameters = false) { - $content = $this->_browser->get($url, $parameters); - if ($content === false) { - return false; - } - return true; + return $this->_failOnError($this->_browser->get($url, $parameters)); } /** @@ -691,15 +699,11 @@ * the base URL reflects the new location. * @param string $url URL to fetch. * @param hash $parameters Optional additional GET data. - * @return boolean True on success. + * @return boolean/string Raw page on success. * @access public */ function post($url, $parameters = false) { - $content = $this->_browser->post($url, $parameters); - if ($content === false) { - return false; - } - return true; + return $this->_failOnError($this->_browser->post($url, $parameters)); } /** @@ -711,7 +715,7 @@ * @access public */ function head($url, $parameters = false) { - return $this->_browser->head($url, $parameters); + return $this->_failOnError($this->_browser->head($url, $parameters)); } /** @@ -721,7 +725,7 @@ * @access public */ function retry() { - return $this->_browser->retry(); + return $this->_failOnError($this->_browser->retry()); } /** @@ -732,7 +736,7 @@ * @access public */ function back() { - return $this->_browser->back(); + return $this->_failOnError($this->_browser->back()); } /** @@ -743,7 +747,7 @@ * @access public */ function forward() { - return $this->_browser->forward(); + return $this->_failOnError($this->_browser->forward()); } /** @@ -751,13 +755,14 @@ * for the current realm. * @param string $username Username for realm. * @param string $password Password for realm. - * @return boolean True if successful fetch. Note + * @return boolean/string HTML on successful fetch. Note * that authentication may still have * failed. * @access public */ function authenticate($username, $password) { - return $this->_browser->authenticate($username, $password); + return $this->_failOnError( + $this->_browser->authenticate($username, $password)); } /** @@ -824,17 +829,29 @@ 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)); + } + /** * 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. + * @return boolean/string Page on success, else false. * @access public */ function clickSubmit($label = 'Submit', $additional = false) { - return $this->_browser->clickSubmit($label, $additional); + return $this->_failOnError( + $this->_browser->clickSubmit($label, $additional)); } /** @@ -846,7 +863,8 @@ * @access public */ function clickSubmitByName($name, $additional = false) { - return $this->_browser->clickSubmitByName($name, $additional); + return $this->_failOnError( + $this->_browser->clickSubmitByName($name, $additional)); } /** @@ -858,7 +876,8 @@ * @access public */ function clickSubmitById($id, $additional = false) { - return $this->_browser->clickSubmitById($id, $additional); + return $this->_failOnError( + $this->_browser->clickSubmitById($id, $additional)); } /** @@ -875,7 +894,8 @@ * @access public */ function clickImage($label, $x = 1, $y = 1, $additional = false) { - return $this->_browser->clickImage($label, $x, $y, $additional); + return $this->_failOnError( + $this->_browser->clickImage($label, $x, $y, $additional)); } /** @@ -892,7 +912,8 @@ * @access public */ function clickImageByName($name, $x = 1, $y = 1, $additional = false) { - return $this->_browser->clickImageByName($name, $x, $y, $additional); + return $this->_failOnError( + $this->_browser->clickImageByName($name, $x, $y, $additional)); } /** @@ -908,7 +929,8 @@ * @access public */ function clickImageById($id, $x = 1, $y = 1, $additional = false) { - return $this->_browser->clickImageById($id, $x, $y, $additional); + return $this->_failOnError( + $this->_browser->clickImageById($id, $x, $y, $additional)); } /** @@ -919,7 +941,7 @@ * @access public */ function submitFormById($id) { - return $this->_browser->submitFormById($id); + return $this->_failOnError($this->_browser->submitFormById($id)); } /** @@ -933,7 +955,7 @@ * @access public */ function clickLink($label, $index = 0) { - return $this->_browser->clickLink($label, $index); + return $this->_failOnError($this->_browser->clickLink($label, $index)); } /** @@ -943,7 +965,41 @@ * @access public */ function clickLinkById($id) { - return $this->_browser->clickLinkById($id); + return $this->_failOnError($this->_browser->clickLinkById($id)); + } + + /** + * 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); } /** @@ -1006,6 +1062,18 @@ 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) { + return $this->_browser->setField($label, $value); + } + /** * Sets all form fields with that name. * @param string $name Name of field in forms. @@ -1013,8 +1081,8 @@ * @return boolean True if field exists, otherwise false. * @access public */ - function setField($name, $value) { - return $this->_browser->setField($name, $value); + function setFieldByName($name, $value) { + return $this->_browser->setFieldByName($name, $value); } /** @@ -1041,18 +1109,27 @@ * @return boolean True if pass. * @access public */ - function assertField($name, $expected = true, $message = "%s") { - $value = $this->_browser->getField($name); - if ($expected === true) { - return $this->assertTrue( - isset($value), - sprintf($message, "Field [$name] should exist")); - } else { - return $this->assertExpectation( - new FieldExpectation($expected), - $value, - sprintf($message, "Field [$name] should match with [%s]")); - } + 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); } /** @@ -1068,18 +1145,33 @@ * @return boolean True if pass. * @access public */ - function assertFieldById($id, $expected = true, $message = "%s") { + 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 + */ + function _assertFieldValue($identifier, $value, $expected, $message) { if ($expected === true) { return $this->assertTrue( isset($value), - sprintf($message, "Field of ID [$id] should exist")); - } else { - return $this->assertExpectation( - new FieldExpectation($expected), - $value, - sprintf($message, "Field of ID [$id] should match with [%s]")); + 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); } /** @@ -1160,39 +1252,38 @@ * @access public */ function assertRealm($realm, $message = '%s') { - $message = sprintf($message, "Expected realm [$realm] got [" . - $this->_browser->getRealm() . "]"); - return $this->assertTrue( - strtolower($this->_browser->getRealm()) == strtolower($realm), - $message); + 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 string $value Case sensitive trimmed string to - * match against. + * @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->assertExpectation( + return $this->assert( new HttpHeaderExpectation($header, $value), $this->_browser->getHeaders(), $message); } /** - * Checks each header line for the required pattern. - * @param string $header Case insensitive header name. - * @param string $pattern Pattern to match value against. - * @return boolean True if pass. - * @access public + * @deprecated */ function assertHeaderPattern($header, $pattern, $message = '%s') { - return $this->assertExpectation( - new HttpHeaderPatternExpectation($header, $pattern), + return $this->assert( + new HttpHeaderExpectation($header, new PatternExpectation($pattern)), $this->_browser->getHeaders(), $message); } @@ -1206,26 +1297,32 @@ * @return boolean True if pass. * @access public */ - function assertNoUnwantedHeader($header, $message = '%s') { - return $this->assertExpectation( - new HttpUnwantedHeaderExpectation($header), + function assertNoHeader($header, $message = '%s') { + return $this->assert( + new NoHttpHeaderExpectation($header), $this->_browser->getHeaders(), $message); } + + /** + * @deprecated + */ + function assertNoUnwantedHeader($header, $message = '%s') { + return $this->assertNoHeader($header, $message); + } /** * Tests the text between the title tags. - * @param string $title Expected title or empty - * if expecting no title. - * @param string $message Message to display. - * @return boolean True if pass. + * @param string $title Expected title. + * @param string $message Message to display. + * @return boolean True if pass. * @access public */ function assertTitle($title = false, $message = '%s') { - return $this->assertTrue( - $title === $this->_browser->getTitle(), - sprintf($message, "Expecting title [$title] got [" . - $this->_browser->getTitle() . "]")); + if (! SimpleExpectation::isExpectation($title)) { + $title = new EqualExpectation($title); + } + return $this->assert($title, $this->_browser->getTitle(), $message); } /** @@ -1236,13 +1333,20 @@ * @return boolean True if pass. * @access public */ - function assertWantedText($text, $message = '%s') { - return $this->assertExpectation( - new WantedTextExpectation($text), + function assertText($text, $message = '%s') { + return $this->assert( + new TextExpectation($text), $this->_browser->getContentAsText(), $message); } + /** + * @deprecated + */ + function assertWantedText($text, $message = '%s') { + return $this->assertText($text, $message); + } + /** * Will trigger a pass if the text is not found in the plain * text form of the page. @@ -1251,13 +1355,20 @@ * @return boolean True if pass. * @access public */ - function assertNoUnwantedText($text, $message = '%s') { - return $this->assertExpectation( - new UnwantedTextExpectation($text), + function assertNoText($text, $message = '%s') { + return $this->assert( + new NoTextExpectation($text), $this->_browser->getContentAsText(), $message); } + /** + * @deprecated + */ + function assertNoUnwantedText($text, $message = '%s') { + return $this->assertNoText($text, $message); + } + /** * Will trigger a pass if the Perl regex pattern * is found in the raw content. @@ -1267,13 +1378,20 @@ * @return boolean True if pass. * @access public */ - function assertWantedPattern($pattern, $message = '%s') { - return $this->assertExpectation( - new WantedPatternExpectation($pattern), + function assertPattern($pattern, $message = '%s') { + return $this->assert( + new PatternExpectation($pattern), $this->_browser->getContent(), $message); } + /** + * @deprecated + */ + function assertWantedPattern($pattern, $message = '%s') { + return $this->assertPattern($pattern, $message); + } + /** * Will trigger a pass if the perl regex pattern * is not present in raw content. @@ -1283,13 +1401,20 @@ * @return boolean True if pass. * @access public */ - function assertNoUnwantedPattern($pattern, $message = '%s') { - return $this->assertExpectation( - new UnwantedPatternExpectation($pattern), + function assertNoPattern($pattern, $message = '%s') { + return $this->assert( + new NoPatternExpectation($pattern), $this->_browser->getContent(), $message); } + /** + * @deprecated + */ + function assertNoUnwantedPattern($pattern, $message = '%s') { + return $this->assertNoPattern($pattern, $message); + } + /** * Checks that a cookie is set for the current page * and optionally checks the value. @@ -1302,15 +1427,15 @@ */ function assertCookie($name, $expected = false, $message = '%s') { $value = $this->getCookie($name); - if ($expected) { - return $this->assertTrue($value === $expected, sprintf( - $message, - "Expecting cookie [$name] value [$expected], got [$value]")); - } else { + 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"); } /** diff --git a/tests/test_tools/simpletest/xml.php b/tests/test_tools/simpletest/xml.php index dd007d41..0d578751 100644 --- a/tests/test_tools/simpletest/xml.php +++ b/tests/test_tools/simpletest/xml.php @@ -3,7 +3,7 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage UnitTester - * @version $Id: xml.php,v 1.20 2004/08/04 22:09:39 lastcraft Exp $ + * @version $Id: xml.php,v 1.22 2006/02/06 06:05:18 lastcraft Exp $ */ /**#@+ @@ -11,7 +11,7 @@ */ require_once(dirname(__FILE__) . '/scorer.php'); /**#@-*/ - + /** * Creates the XML needed for remote communication * by SimpleTest. @@ -21,7 +21,7 @@ class XmlReporter extends SimpleReporter { protected $_indent; protected $_namespace; - + /** * Does nothing yet. * @access public @@ -31,7 +31,7 @@ $this->_namespace = ($namespace ? $namespace . ':' : ''); $this->_indent = $indent; } - + /** * Calculates the pretty printing indent level * from the current level of nesting. @@ -44,7 +44,7 @@ $this->_indent, count($this->getTestList()) + $offset); } - + /** * Converts character string to parsed XML * entities string. @@ -58,7 +58,7 @@ array('&', '<', '>', '"', '''), $text); } - + /** * Paints the start of a group test. * @param string $test_name Name of test that is starting. @@ -74,7 +74,7 @@ $this->toParsedXml($test_name) . "_namespace . "name>\n"; } - + /** * Paints the end of a group test. * @param string $test_name Name of test that is ending. @@ -85,7 +85,7 @@ print "_namespace . "group>\n"; parent::paintGroupEnd($test_name); } - + /** * Paints the start of a test case. * @param string $test_name Name of test that is starting. @@ -100,7 +100,7 @@ $this->toParsedXml($test_name) . "_namespace . "name>\n"; } - + /** * Paints the end of a test case. * @param string $test_name Name of test that is ending. @@ -111,7 +111,7 @@ print "_namespace . "case>\n"; parent::paintCaseEnd($test_name); } - + /** * Paints the start of a test method. * @param string $test_name Name of test that is starting. @@ -126,7 +126,7 @@ $this->toParsedXml($test_name) . "_namespace . "name>\n"; } - + /** * Paints the end of a test method. * @param string $test_name Name of test that is ending. @@ -138,7 +138,7 @@ print "_namespace . "test>\n"; parent::paintMethodEnd($test_name); } - + /** * Increments the pass count. * @param string $message Message is ignored. @@ -151,7 +151,7 @@ print $this->toParsedXml($message); print "_namespace . "pass>\n"; } - + /** * Increments the fail count. * @param string $message Message is ignored. @@ -164,15 +164,15 @@ print $this->toParsedXml($message); print "_namespace . "fail>\n"; } - + /** * Paints a PHP error or exception. * @param string $message Message is ignored. * @access public * @abstract */ - function paintException($message) { - parent::paintException($message); + function paintError($message) { + parent::paintError($message); print $this->_getIndent(1); print "<" . $this->_namespace . "exception>"; print $this->toParsedXml($message); @@ -191,7 +191,7 @@ print $this->toParsedXml($message); print "_namespace . "message>\n"; } - + /** * Paints a formatted ASCII message such as a * variable dump. @@ -239,7 +239,7 @@ print "?>\n"; print "<" . $this->_namespace . "run>\n"; } - + /** * Paints the test document footer. * @param string $test_name The top level test. @@ -250,7 +250,7 @@ print "_namespace . "run>\n"; } } - + /** * Accumulator for incoming tag. Holds the * incoming test structure information for @@ -261,7 +261,7 @@ class NestingXmlTag { protected $_name; protected $_attributes; - + /** * Sets the basic test information except * the name. @@ -272,7 +272,7 @@ $this->_name = false; $this->_attributes = $attributes; } - + /** * Sets the test case/method name. * @param string $name Name of test. @@ -281,7 +281,7 @@ function setName($name) { $this->_name = $name; } - + /** * Accessor for name. * @return string Name of test. @@ -290,7 +290,7 @@ function getName() { return $this->_name; } - + /** * Accessor for attributes. * @return hash All attributes. @@ -300,7 +300,7 @@ return $this->_attributes; } } - + /** * Accumulator for incoming method tag. Holds the * incoming test structure information for @@ -309,7 +309,7 @@ * @subpackage UnitTester */ class NestingMethodTag extends NestingXmlTag { - + /** * Sets the basic test information except * the name. @@ -319,7 +319,7 @@ function NestingMethodTag($attributes) { $this->NestingXmlTag($attributes); } - + /** * Signals the appropriate start event on the * listener. @@ -328,8 +328,8 @@ */ function paintStart($listener) { $listener->paintMethodStart($this->getName()); - } - + } + /** * Signals the appropriate end event on the * listener. @@ -340,7 +340,7 @@ $listener->paintMethodEnd($this->getName()); } } - + /** * Accumulator for incoming case tag. Holds the * incoming test structure information for @@ -349,7 +349,7 @@ * @subpackage UnitTester */ class NestingCaseTag extends NestingXmlTag { - + /** * Sets the basic test information except * the name. @@ -359,7 +359,7 @@ function NestingCaseTag($attributes) { $this->NestingXmlTag($attributes); } - + /** * Signals the appropriate start event on the * listener. @@ -368,8 +368,8 @@ */ function paintStart($listener) { $listener->paintCaseStart($this->getName()); - } - + } + /** * Signals the appropriate end event on the * listener. @@ -380,7 +380,7 @@ $listener->paintCaseEnd($this->getName()); } } - + /** * Accumulator for incoming group tag. Holds the * incoming test structure information for @@ -389,7 +389,7 @@ * @subpackage UnitTester */ class NestingGroupTag extends NestingXmlTag { - + /** * Sets the basic test information except * the name. @@ -409,7 +409,7 @@ function paintStart($listener) { $listener->paintGroupStart($this->getName(), $this->getSize()); } - + /** * Signals the appropriate end event on the * listener. @@ -419,7 +419,7 @@ function paintEnd($listener) { $listener->paintGroupEnd($this->getName()); } - + /** * The size in the attributes. * @return integer Value of size attribute or zero. @@ -433,7 +433,7 @@ return 0; } } - + /** * Parser for importing the output of the XmlReporter. * Dispatches that output to another reporter. @@ -447,7 +447,7 @@ protected $_in_content_tag; protected $_content; protected $_attributes; - + /** * Loads a listener with the SimpleReporter * interface. @@ -462,7 +462,7 @@ $this->_content = ''; $this->_attributes = array(); } - + /** * Parses a block of XML sending the results to * the listener. @@ -478,13 +478,13 @@ } return true; } - + /** * Sets up expat as the XML parser. * @return resource Expat handle. * @access protected */ - function _createParser() { + function &_createParser() { $expat = xml_parser_create(); xml_set_object($expat, $this); xml_set_element_handler($expat, '_startElement', '_endElement'); @@ -492,7 +492,7 @@ xml_set_default_handler($expat, '_default'); return $expat; } - + /** * Opens a new test nesting level. * @return NestedXmlTag The group, case or method tag @@ -502,17 +502,17 @@ 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 */ - function _getCurrentNestingTag() { + function &_getCurrentNestingTag() { return $this->_tag_stack[0]; } - + /** * Ends a nesting tag. * @return NestedXmlTag The group, case or method tag @@ -522,7 +522,7 @@ 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. @@ -530,9 +530,8 @@ * @private */ function _isLeaf($tag) { - return in_array( - $tag, - array('NAME', 'PASS', 'FAIL', 'EXCEPTION', 'MESSAGE', 'FORMATTED', 'SIGNAL')); + return in_array($tag, array( + 'NAME', 'PASS', 'FAIL', 'EXCEPTION', 'MESSAGE', 'FORMATTED', 'SIGNAL')); } /** @@ -557,7 +556,7 @@ $this->_content = ''; } } - + /** * End of element event. * @param resource $expat Parser handle. @@ -578,7 +577,7 @@ } elseif ($tag == 'FAIL') { $this->_listener->paintFail($this->_content); } elseif ($tag == 'EXCEPTION') { - $this->_listener->paintException($this->_content); + $this->_listener->paintError($this->_content); } elseif ($tag == 'SIGNAL') { $this->_listener->paintSignal( $this->_attributes['TYPE'], @@ -589,7 +588,7 @@ $this->_listener->paintFormattedMessage($this->_content); } } - + /** * Content between start and end elements. * @param resource $expat Parser handle. @@ -602,7 +601,7 @@ } return true; } - + /** * XML and Doctype handler. Discards all such content. * @param resource $expat Parser handle. -- cgit v1.2.3