From 9ee45c69c8721c507cd3ed8b10e458d095723d96 Mon Sep 17 00:00:00 2001 From: David Goodwin Date: Sun, 15 Mar 2009 21:24:56 +0000 Subject: [PATCH] tests: add initial simpletest unit tests for the xmlrpc stuff git-svn-id: https://svn.code.sf.net/p/postfixadmin/code/trunk@581 a1433add-5e2c-0410-b055-b7f2511e0802 --- tests/RemoteTest.php | 82 + tests/RemoteVacationTest.php | 81 + tests/common.php | 4 + tests/run.php | 15 + tests/simpletest/BACKLOG | 37 + .../HELP_MY_TESTS_DONT_WORK_ANYMORE | 340 ++++ tests/simpletest/LICENSE | 502 ++++++ tests/simpletest/README | 108 ++ tests/simpletest/TODO | 32 + tests/simpletest/VERSION | 1 + tests/simpletest/authentication.php | 238 +++ tests/simpletest/browser.php | 1097 ++++++++++++ tests/simpletest/collector.php | 107 ++ tests/simpletest/compatibility.php | 173 ++ tests/simpletest/cookies.php | 380 ++++ tests/simpletest/detached.php | 96 + .../docs/en/authentication_documentation.html | 336 ++++ .../docs/en/browser_documentation.html | 391 +++++ tests/simpletest/docs/en/docs.css | 121 ++ .../docs/en/expectation_documentation.html | 346 ++++ .../docs/en/form_testing_documentation.html | 276 +++ .../docs/en/group_test_documentation.html | 354 ++++ tests/simpletest/docs/en/index.html | 461 +++++ .../docs/en/mock_objects_documentation.html | 727 ++++++++ tests/simpletest/docs/en/overview.html | 406 +++++ .../docs/en/partial_mocks_documentation.html | 423 +++++ .../docs/en/reporter_documentation.html | 512 ++++++ .../docs/en/unit_test_documentation.html | 390 +++++ .../docs/en/web_tester_documentation.html | 511 ++++++ tests/simpletest/docs/fr/docs.css | 84 + tests/simpletest/docs/lastcraft/README | 1 + tests/simpletest/docs/onpk/README | 1 + tests/simpletest/docs/pkg/README | 1 + tests/simpletest/docs/simpletest.org/README | 1 + .../images/book-domain-driven-design.jpg | Bin 0 -> 6599 bytes .../book-guide-to-php-design-patterns.jpg | Bin 0 -> 5657 bytes ...nthology-object-oriented-php-solutions.jpg | Bin 0 -> 43265 bytes .../docs/simpletest.org/images/quote.png | Bin 0 -> 620 bytes .../images/simpletest-download.png | Bin 0 -> 4895 bytes .../simpletest.org/images/simpletest-logo.png | Bin 0 -> 6892 bytes .../images/simpletest-start-testing.png | Bin 0 -> 5866 bytes .../images/simpletest-support.png | Bin 0 -> 5476 bytes .../simpletest.org/images/test-in-cli.png | Bin 0 -> 46023 bytes .../images/test-with-1-fail.png | Bin 0 -> 25562 bytes .../images/test-with-1-pass.png | Bin 0 -> 10213 bytes .../simpletest/docs/simpletest.org/index.html | 174 ++ .../docs/simpletest.org/simpletest.css | 44 + tests/simpletest/docs/source/en/about.xml | 115 ++ .../en/authentication_documentation.xml | 316 ++++ .../docs/source/en/books_website.xml | 72 + .../source/en/boundary_classes_tutorial.xml | 408 +++++ .../docs/source/en/browser_documentation.xml | 264 +++ .../source/en/display_subclass_tutorial.xml | 273 +++ .../docs/source/en/download_website.xml | 98 ++ .../source/en/expectation_documentation.xml | 338 ++++ .../docs/source/en/first_test_tutorial.xml | 458 +++++ .../source/en/form_testing_documentation.xml | 254 +++ .../docs/source/en/gain_control_tutorial.xml | 299 ++++ .../source/en/group_test_documentation.xml | 330 ++++ .../docs/source/en/group_test_tutorial.xml | 237 +++ .../source/en/improving_design_tutorial.xml | 197 +++ tests/simpletest/docs/source/en/index.xml | 219 +++ tests/simpletest/docs/source/en/intro.xml | 54 + .../source/en/mock_objects_documentation.xml | 698 ++++++++ .../docs/source/en/mock_objects_tutorial.xml | 361 ++++ tests/simpletest/docs/source/en/overview.xml | 420 +++++ .../source/en/partial_mocks_documentation.xml | 401 +++++ .../docs/source/en/reporter_documentation.xml | 470 +++++ .../simpletest/docs/source/en/simple_test.xml | 466 +++++ .../docs/source/en/subclass_tutorial.xml | 256 +++ .../docs/source/en/support_website.xml | 53 + .../source/en/unit_test_documentation.xml | 305 ++++ .../source/en/web_tester_documentation.xml | 374 ++++ .../fr/authentication_documentation.xml | 252 +++ .../docs/source/fr/books_website.xml | 75 + .../source/fr/boundary_classes_tutorial.xml | 268 +++ .../docs/source/fr/browser_documentation.xml | 199 +++ .../source/fr/display_subclass_tutorial.xml | 214 +++ .../docs/source/fr/download_website.xml | 100 ++ .../source/fr/expectation_documentation.xml | 213 +++ .../docs/source/fr/first_test_tutorial.xml | 285 +++ .../source/fr/form_testing_documentation.xml | 207 +++ .../docs/source/fr/gain_control_tutorial.xml | 215 +++ .../source/fr/group_test_documentation.xml | 255 +++ .../docs/source/fr/group_test_tutorial.xml | 198 +++ .../source/fr/improving_design_tutorial.xml | 137 ++ tests/simpletest/docs/source/fr/index.xml | 68 + tests/simpletest/docs/source/fr/intro.xml | 36 + .../source/fr/mock_objects_documentation.xml | 458 +++++ .../docs/source/fr/mock_objects_tutorial.xml | 269 +++ tests/simpletest/docs/source/fr/overview.xml | 295 ++++ .../source/fr/partial_mocks_documentation.xml | 306 ++++ .../docs/source/fr/reporter_documentation.xml | 341 ++++ .../source/fr/server_stubs_documentation.xml | 251 +++ .../simpletest/docs/source/fr/simple_test.xml | 339 ++++ .../docs/source/fr/subclass_tutorial.xml | 195 +++ .../docs/source/fr/support_website.xml | 43 + .../source/fr/unit_test_documentation.xml | 225 +++ .../source/fr/web_tester_documentation.xml | 266 +++ tests/simpletest/dumper.php | 360 ++++ tests/simpletest/eclipse.php | 183 ++ tests/simpletest/encoding.php | 521 ++++++ tests/simpletest/errors.php | 250 +++ tests/simpletest/exceptions.php | 192 ++ tests/simpletest/expectation.php | 811 +++++++++ .../simpletest/extensions/pear_test_case.php | 198 +++ .../extensions/phpunit_test_case.php | 96 + tests/simpletest/form.php | 352 ++++ tests/simpletest/frames.php | 588 +++++++ tests/simpletest/http.php | 624 +++++++ tests/simpletest/invoker.php | 139 ++ tests/simpletest/mock_objects.php | 1312 ++++++++++++++ tests/simpletest/packages/README | 26 + tests/simpletest/packages/build_tarball.sh | 122 ++ tests/simpletest/packages/bundled_docs.xslt | 246 +++ tests/simpletest/packages/bundled_map.xml | 14 + .../simpletest/packages/generate_package.php | 136 ++ tests/simpletest/packages/lastcraft.xslt | 302 ++++ .../simpletest/packages/make_bundled_docs.sh | 26 + .../packages/make_bundled_docs_with_xalan.sh | 26 + .../packages/make_lastcraft_docs.sh | 2 + tests/simpletest/packages/make_phpdoc_docs.sh | 42 + tests/simpletest/packages/onpk/map_onpk.xml | 26 + tests/simpletest/packages/onpk/onpk.xslt | 227 +++ .../packages/onpk/transform_all_onpk.php | 32 + tests/simpletest/packages/package.xml | 710 ++++++++ .../packages/pear_package_create.php | 170 ++ tests/simpletest/packages/phpdoc_docs.xslt | 127 ++ tests/simpletest/packages/simpletest.ini | 92 + .../packages/simpletest.org/index.php | 46 + .../packages/simpletest.org/map.xml | 67 + .../packages/simpletest.org/package.php | 259 +++ .../packages/simpletest.org/template.html | 42 + .../test/package/content_without_section.xml | 91 + .../test/package/here_download.xml | 91 + .../test/package/here_overview.xml | 91 + .../test/package/here_simpletest.xml | 91 + .../test/package/here_start_testing.xml | 91 + .../test/package/here_support.xml | 91 + .../test/package/here_unit-tester.xml | 91 + .../simpletest.org/test/package/map.xml | 20 + .../package/one_section_with_php_code.xml | 93 + .../simpletest.org/test/package_test.php | 89 + tests/simpletest/packages/site_map.xml | 33 + .../packages/transform_all_lastcraft.php | 17 + tests/simpletest/page.php | 975 +++++++++++ tests/simpletest/parser.php | 775 +++++++++ tests/simpletest/reflection_php4.php | 126 ++ tests/simpletest/reflection_php5.php | 293 ++++ tests/simpletest/remote.php | 117 ++ tests/simpletest/reporter.php | 426 +++++ tests/simpletest/scorer.php | 863 +++++++++ tests/simpletest/selector.php | 133 ++ tests/simpletest/shell_tester.php | 333 ++++ tests/simpletest/simpletest.php | 436 +++++ tests/simpletest/socket.php | 216 +++ tests/simpletest/tag.php | 1392 +++++++++++++++ tests/simpletest/test/acceptance_test.php | 1511 ++++++++++++++++ tests/simpletest/test/adapter_test.php | 74 + tests/simpletest/test/all_tests.php | 15 + tests/simpletest/test/authentication_test.php | 144 ++ tests/simpletest/test/browser_test.php | 791 +++++++++ tests/simpletest/test/collector_test.php | 50 + tests/simpletest/test/compatibility_test.php | 96 + tests/simpletest/test/cookies_test.php | 225 +++ tests/simpletest/test/detached_test.php | 15 + tests/simpletest/test/dumper_test.php | 87 + tests/simpletest/test/eclipse_test.php | 32 + tests/simpletest/test/encoding_test.php | 191 ++ tests/simpletest/test/errors_test.php | 235 +++ tests/simpletest/test/exceptions_test.php | 118 ++ tests/simpletest/test/expectation_test.php | 205 +++ tests/simpletest/test/form_test.php | 328 ++++ tests/simpletest/test/frames_test.php | 575 ++++++ tests/simpletest/test/http_test.php | 427 +++++ tests/simpletest/test/interfaces_test.php | 119 ++ tests/simpletest/test/live_test.php | 47 + tests/simpletest/test/mock_objects_test.php | 666 +++++++ tests/simpletest/test/page_test.php | 885 ++++++++++ tests/simpletest/test/parse_error_test.php | 10 + tests/simpletest/test/parser_test.php | 520 ++++++ .../simpletest/test/reflection_php4_test.php | 60 + .../simpletest/test/reflection_php5_test.php | 194 +++ tests/simpletest/test/remote_test.php | 20 + tests/simpletest/test/shell_test.php | 38 + tests/simpletest/test/shell_tester_test.php | 41 + tests/simpletest/test/simpletest_test.php | 57 + tests/simpletest/test/site/1.html | 6 + tests/simpletest/test/site/2.html | 6 + tests/simpletest/test/site/3.html | 6 + .../test/site/base_change_redirect.php | 6 + .../test/site/cookie_based_counter.php | 10 + .../test/site/counting_frameset.html | 10 + .../test/site/double_base_change_redirect.php | 6 + tests/simpletest/test/site/form.html | 47 + .../test/site/form_data_encoded_form.html | 47 + .../test/site/form_with_false_defaults.html | 40 + .../site/form_with_mixed_post_and_get.html | 15 + .../test/site/form_with_tricky_defaults.html | 35 + .../test/site/form_with_unnamed_submit.html | 12 + .../test/site/form_without_action.php | 11 + tests/simpletest/test/site/frame_a.html | 6 + tests/simpletest/test/site/frame_b.html | 6 + tests/simpletest/test/site/frame_links.html | 7 + tests/simpletest/test/site/frameset.html | 10 + .../site/front_controller_style/a_page.php | 37 + .../site/front_controller_style/index.php | 44 + .../front_controller_style/show_request.php | 49 + tests/simpletest/test/site/link_confirm.php | 17 + tests/simpletest/test/site/local_redirect.php | 6 + .../simpletest/test/site/messy_frameset.html | 16 + .../test/site/multiple_widget_form.html | 59 + .../simpletest/test/site/nested_frameset.html | 10 + .../simpletest/test/site/network_confirm.php | 77 + .../test/site/one_page_frameset.html | 9 + tests/simpletest/test/site/page_request.php | 63 + .../test/site/path/base_change_redirect.php | 6 + .../test/site/path/network_confirm.php | 71 + .../test/site/path/show_cookies.php | 18 + .../simpletest/test/site/protected/.htaccess | 5 + .../simpletest/test/site/protected/.htpasswd | 1 + tests/simpletest/test/site/protected/1.html | 6 + tests/simpletest/test/site/protected/2.html | 6 + tests/simpletest/test/site/protected/3.html | 6 + tests/simpletest/test/site/protected/htaccess | 4 + .../test/site/protected/local_redirect.php | 6 + .../test/site/protected/network_confirm.php | 71 + tests/simpletest/test/site/redirect.php | 6 + .../test/site/savant_style_form.html | 20 + tests/simpletest/test/site/search.png | Bin 0 -> 1260 bytes tests/simpletest/test/site/self_form.php | 21 + tests/simpletest/test/site/set_cookies.php | 18 + tests/simpletest/test/site/slow_page.php | 6 + tests/simpletest/test/site/timestamp.php | 3 + tests/simpletest/test/site/upload_form.html | 11 + tests/simpletest/test/site/upload_handler.php | 18 + tests/simpletest/test/socket_test.php | 26 + .../test/support/collector/collectable.1 | 0 .../test/support/collector/collectable.2 | 0 tests/simpletest/test/support/latin1_sample | 1 + .../simpletest/test/support/spl_examples.php | 15 + .../support/supplementary_upload_sample.txt | 1 + tests/simpletest/test/support/test1.php | 7 + .../simpletest/test/support/upload_sample.txt | 1 + tests/simpletest/test/tag_test.php | 555 ++++++ tests/simpletest/test/test_groups.php | 67 + .../simpletest/test/test_with_parse_error.php | 8 + tests/simpletest/test/unit_tester_test.php | 54 + tests/simpletest/test/unit_tests.php | 17 + tests/simpletest/test/url_test.php | 407 +++++ tests/simpletest/test/user_agent_test.php | 358 ++++ tests/simpletest/test/visual_test.php | 566 ++++++ tests/simpletest/test/web_tester_test.php | 154 ++ tests/simpletest/test/xml_test.php | 187 ++ tests/simpletest/test_case.php | 684 ++++++++ tests/simpletest/ui/array_reporter.php | 66 + .../ui/array_reporter/sample_test.php | 15 + tests/simpletest/ui/array_reporter/test.php | 38 + tests/simpletest/ui/colortext_reporter.php | 86 + tests/simpletest/ui/css/webunit.css | 78 + tests/simpletest/ui/img/wait.gif | Bin 0 -> 1426 bytes .../ui/js/tests/TestOfWebunit.js.html | 34 + tests/simpletest/ui/js/webunit.js | 194 +++ tests/simpletest/ui/js/x.js | 423 +++++ tests/simpletest/ui/webunit_reporter.php | 286 +++ tests/simpletest/unit_tester.php | 419 +++++ tests/simpletest/url.php | 525 ++++++ tests/simpletest/user_agent.php | 333 ++++ tests/simpletest/web_tester.php | 1541 +++++++++++++++++ tests/simpletest/xml.php | 647 +++++++ 270 files changed, 54184 insertions(+) create mode 100644 tests/RemoteTest.php create mode 100644 tests/RemoteVacationTest.php create mode 100644 tests/common.php create mode 100644 tests/run.php create mode 100644 tests/simpletest/BACKLOG create mode 100644 tests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE create mode 100644 tests/simpletest/LICENSE create mode 100644 tests/simpletest/README create mode 100644 tests/simpletest/TODO create mode 100644 tests/simpletest/VERSION create mode 100644 tests/simpletest/authentication.php create mode 100644 tests/simpletest/browser.php create mode 100644 tests/simpletest/collector.php create mode 100644 tests/simpletest/compatibility.php create mode 100644 tests/simpletest/cookies.php create mode 100644 tests/simpletest/detached.php create mode 100644 tests/simpletest/docs/en/authentication_documentation.html create mode 100644 tests/simpletest/docs/en/browser_documentation.html create mode 100644 tests/simpletest/docs/en/docs.css create mode 100644 tests/simpletest/docs/en/expectation_documentation.html create mode 100644 tests/simpletest/docs/en/form_testing_documentation.html create mode 100644 tests/simpletest/docs/en/group_test_documentation.html create mode 100644 tests/simpletest/docs/en/index.html create mode 100644 tests/simpletest/docs/en/mock_objects_documentation.html create mode 100644 tests/simpletest/docs/en/overview.html create mode 100644 tests/simpletest/docs/en/partial_mocks_documentation.html create mode 100644 tests/simpletest/docs/en/reporter_documentation.html create mode 100644 tests/simpletest/docs/en/unit_test_documentation.html create mode 100644 tests/simpletest/docs/en/web_tester_documentation.html create mode 100644 tests/simpletest/docs/fr/docs.css create mode 100644 tests/simpletest/docs/lastcraft/README create mode 100644 tests/simpletest/docs/onpk/README create mode 100644 tests/simpletest/docs/pkg/README create mode 100644 tests/simpletest/docs/simpletest.org/README create mode 100644 tests/simpletest/docs/simpletest.org/images/book-domain-driven-design.jpg create mode 100644 tests/simpletest/docs/simpletest.org/images/book-guide-to-php-design-patterns.jpg create mode 100644 tests/simpletest/docs/simpletest.org/images/book-the-php-anthology-object-oriented-php-solutions.jpg create mode 100644 tests/simpletest/docs/simpletest.org/images/quote.png create mode 100644 tests/simpletest/docs/simpletest.org/images/simpletest-download.png create mode 100644 tests/simpletest/docs/simpletest.org/images/simpletest-logo.png create mode 100644 tests/simpletest/docs/simpletest.org/images/simpletest-start-testing.png create mode 100644 tests/simpletest/docs/simpletest.org/images/simpletest-support.png create mode 100644 tests/simpletest/docs/simpletest.org/images/test-in-cli.png create mode 100644 tests/simpletest/docs/simpletest.org/images/test-with-1-fail.png create mode 100644 tests/simpletest/docs/simpletest.org/images/test-with-1-pass.png create mode 100644 tests/simpletest/docs/simpletest.org/index.html create mode 100644 tests/simpletest/docs/simpletest.org/simpletest.css create mode 100644 tests/simpletest/docs/source/en/about.xml create mode 100644 tests/simpletest/docs/source/en/authentication_documentation.xml create mode 100644 tests/simpletest/docs/source/en/books_website.xml create mode 100644 tests/simpletest/docs/source/en/boundary_classes_tutorial.xml create mode 100644 tests/simpletest/docs/source/en/browser_documentation.xml create mode 100644 tests/simpletest/docs/source/en/display_subclass_tutorial.xml create mode 100644 tests/simpletest/docs/source/en/download_website.xml create mode 100644 tests/simpletest/docs/source/en/expectation_documentation.xml create mode 100644 tests/simpletest/docs/source/en/first_test_tutorial.xml create mode 100644 tests/simpletest/docs/source/en/form_testing_documentation.xml create mode 100644 tests/simpletest/docs/source/en/gain_control_tutorial.xml create mode 100644 tests/simpletest/docs/source/en/group_test_documentation.xml create mode 100644 tests/simpletest/docs/source/en/group_test_tutorial.xml create mode 100644 tests/simpletest/docs/source/en/improving_design_tutorial.xml create mode 100644 tests/simpletest/docs/source/en/index.xml create mode 100644 tests/simpletest/docs/source/en/intro.xml create mode 100644 tests/simpletest/docs/source/en/mock_objects_documentation.xml create mode 100644 tests/simpletest/docs/source/en/mock_objects_tutorial.xml create mode 100644 tests/simpletest/docs/source/en/overview.xml create mode 100644 tests/simpletest/docs/source/en/partial_mocks_documentation.xml create mode 100644 tests/simpletest/docs/source/en/reporter_documentation.xml create mode 100644 tests/simpletest/docs/source/en/simple_test.xml create mode 100644 tests/simpletest/docs/source/en/subclass_tutorial.xml create mode 100644 tests/simpletest/docs/source/en/support_website.xml create mode 100644 tests/simpletest/docs/source/en/unit_test_documentation.xml create mode 100644 tests/simpletest/docs/source/en/web_tester_documentation.xml create mode 100644 tests/simpletest/docs/source/fr/authentication_documentation.xml create mode 100644 tests/simpletest/docs/source/fr/books_website.xml create mode 100644 tests/simpletest/docs/source/fr/boundary_classes_tutorial.xml create mode 100644 tests/simpletest/docs/source/fr/browser_documentation.xml create mode 100644 tests/simpletest/docs/source/fr/display_subclass_tutorial.xml create mode 100644 tests/simpletest/docs/source/fr/download_website.xml create mode 100644 tests/simpletest/docs/source/fr/expectation_documentation.xml create mode 100644 tests/simpletest/docs/source/fr/first_test_tutorial.xml create mode 100644 tests/simpletest/docs/source/fr/form_testing_documentation.xml create mode 100644 tests/simpletest/docs/source/fr/gain_control_tutorial.xml create mode 100644 tests/simpletest/docs/source/fr/group_test_documentation.xml create mode 100644 tests/simpletest/docs/source/fr/group_test_tutorial.xml create mode 100644 tests/simpletest/docs/source/fr/improving_design_tutorial.xml create mode 100644 tests/simpletest/docs/source/fr/index.xml create mode 100644 tests/simpletest/docs/source/fr/intro.xml create mode 100644 tests/simpletest/docs/source/fr/mock_objects_documentation.xml create mode 100644 tests/simpletest/docs/source/fr/mock_objects_tutorial.xml create mode 100644 tests/simpletest/docs/source/fr/overview.xml create mode 100644 tests/simpletest/docs/source/fr/partial_mocks_documentation.xml create mode 100644 tests/simpletest/docs/source/fr/reporter_documentation.xml create mode 100644 tests/simpletest/docs/source/fr/server_stubs_documentation.xml create mode 100644 tests/simpletest/docs/source/fr/simple_test.xml create mode 100644 tests/simpletest/docs/source/fr/subclass_tutorial.xml create mode 100644 tests/simpletest/docs/source/fr/support_website.xml create mode 100644 tests/simpletest/docs/source/fr/unit_test_documentation.xml create mode 100644 tests/simpletest/docs/source/fr/web_tester_documentation.xml create mode 100644 tests/simpletest/dumper.php create mode 100644 tests/simpletest/eclipse.php create mode 100644 tests/simpletest/encoding.php create mode 100644 tests/simpletest/errors.php create mode 100644 tests/simpletest/exceptions.php create mode 100644 tests/simpletest/expectation.php create mode 100644 tests/simpletest/extensions/pear_test_case.php create mode 100644 tests/simpletest/extensions/phpunit_test_case.php create mode 100644 tests/simpletest/form.php create mode 100644 tests/simpletest/frames.php create mode 100644 tests/simpletest/http.php create mode 100644 tests/simpletest/invoker.php create mode 100644 tests/simpletest/mock_objects.php create mode 100644 tests/simpletest/packages/README create mode 100755 tests/simpletest/packages/build_tarball.sh create mode 100644 tests/simpletest/packages/bundled_docs.xslt create mode 100644 tests/simpletest/packages/bundled_map.xml create mode 100644 tests/simpletest/packages/generate_package.php create mode 100644 tests/simpletest/packages/lastcraft.xslt create mode 100755 tests/simpletest/packages/make_bundled_docs.sh create mode 100755 tests/simpletest/packages/make_bundled_docs_with_xalan.sh create mode 100755 tests/simpletest/packages/make_lastcraft_docs.sh create mode 100755 tests/simpletest/packages/make_phpdoc_docs.sh create mode 100644 tests/simpletest/packages/onpk/map_onpk.xml create mode 100644 tests/simpletest/packages/onpk/onpk.xslt create mode 100644 tests/simpletest/packages/onpk/transform_all_onpk.php create mode 100644 tests/simpletest/packages/package.xml create mode 100755 tests/simpletest/packages/pear_package_create.php create mode 100644 tests/simpletest/packages/phpdoc_docs.xslt create mode 100755 tests/simpletest/packages/simpletest.ini create mode 100644 tests/simpletest/packages/simpletest.org/index.php create mode 100644 tests/simpletest/packages/simpletest.org/map.xml create mode 100644 tests/simpletest/packages/simpletest.org/package.php create mode 100644 tests/simpletest/packages/simpletest.org/template.html create mode 100644 tests/simpletest/packages/simpletest.org/test/package/content_without_section.xml create mode 100644 tests/simpletest/packages/simpletest.org/test/package/here_download.xml create mode 100644 tests/simpletest/packages/simpletest.org/test/package/here_overview.xml create mode 100644 tests/simpletest/packages/simpletest.org/test/package/here_simpletest.xml create mode 100644 tests/simpletest/packages/simpletest.org/test/package/here_start_testing.xml create mode 100644 tests/simpletest/packages/simpletest.org/test/package/here_support.xml create mode 100644 tests/simpletest/packages/simpletest.org/test/package/here_unit-tester.xml create mode 100644 tests/simpletest/packages/simpletest.org/test/package/map.xml create mode 100644 tests/simpletest/packages/simpletest.org/test/package/one_section_with_php_code.xml create mode 100644 tests/simpletest/packages/simpletest.org/test/package_test.php create mode 100644 tests/simpletest/packages/site_map.xml create mode 100644 tests/simpletest/packages/transform_all_lastcraft.php create mode 100644 tests/simpletest/page.php create mode 100644 tests/simpletest/parser.php create mode 100644 tests/simpletest/reflection_php4.php create mode 100644 tests/simpletest/reflection_php5.php create mode 100644 tests/simpletest/remote.php create mode 100644 tests/simpletest/reporter.php create mode 100644 tests/simpletest/scorer.php create mode 100644 tests/simpletest/selector.php create mode 100644 tests/simpletest/shell_tester.php create mode 100644 tests/simpletest/simpletest.php create mode 100644 tests/simpletest/socket.php create mode 100644 tests/simpletest/tag.php create mode 100644 tests/simpletest/test/acceptance_test.php create mode 100644 tests/simpletest/test/adapter_test.php create mode 100644 tests/simpletest/test/all_tests.php create mode 100644 tests/simpletest/test/authentication_test.php create mode 100644 tests/simpletest/test/browser_test.php create mode 100644 tests/simpletest/test/collector_test.php create mode 100644 tests/simpletest/test/compatibility_test.php create mode 100644 tests/simpletest/test/cookies_test.php create mode 100644 tests/simpletest/test/detached_test.php create mode 100644 tests/simpletest/test/dumper_test.php create mode 100644 tests/simpletest/test/eclipse_test.php create mode 100644 tests/simpletest/test/encoding_test.php create mode 100644 tests/simpletest/test/errors_test.php create mode 100644 tests/simpletest/test/exceptions_test.php create mode 100644 tests/simpletest/test/expectation_test.php create mode 100644 tests/simpletest/test/form_test.php create mode 100644 tests/simpletest/test/frames_test.php create mode 100644 tests/simpletest/test/http_test.php create mode 100644 tests/simpletest/test/interfaces_test.php create mode 100644 tests/simpletest/test/live_test.php create mode 100644 tests/simpletest/test/mock_objects_test.php create mode 100644 tests/simpletest/test/page_test.php create mode 100644 tests/simpletest/test/parse_error_test.php create mode 100644 tests/simpletest/test/parser_test.php create mode 100644 tests/simpletest/test/reflection_php4_test.php create mode 100644 tests/simpletest/test/reflection_php5_test.php create mode 100644 tests/simpletest/test/remote_test.php create mode 100644 tests/simpletest/test/shell_test.php create mode 100644 tests/simpletest/test/shell_tester_test.php create mode 100644 tests/simpletest/test/simpletest_test.php create mode 100644 tests/simpletest/test/site/1.html create mode 100644 tests/simpletest/test/site/2.html create mode 100644 tests/simpletest/test/site/3.html create mode 100644 tests/simpletest/test/site/base_change_redirect.php create mode 100644 tests/simpletest/test/site/cookie_based_counter.php create mode 100644 tests/simpletest/test/site/counting_frameset.html create mode 100644 tests/simpletest/test/site/double_base_change_redirect.php create mode 100644 tests/simpletest/test/site/form.html create mode 100644 tests/simpletest/test/site/form_data_encoded_form.html create mode 100644 tests/simpletest/test/site/form_with_false_defaults.html create mode 100644 tests/simpletest/test/site/form_with_mixed_post_and_get.html create mode 100644 tests/simpletest/test/site/form_with_tricky_defaults.html create mode 100644 tests/simpletest/test/site/form_with_unnamed_submit.html create mode 100644 tests/simpletest/test/site/form_without_action.php create mode 100644 tests/simpletest/test/site/frame_a.html create mode 100644 tests/simpletest/test/site/frame_b.html create mode 100644 tests/simpletest/test/site/frame_links.html create mode 100644 tests/simpletest/test/site/frameset.html create mode 100644 tests/simpletest/test/site/front_controller_style/a_page.php create mode 100644 tests/simpletest/test/site/front_controller_style/index.php create mode 100644 tests/simpletest/test/site/front_controller_style/show_request.php create mode 100644 tests/simpletest/test/site/link_confirm.php create mode 100644 tests/simpletest/test/site/local_redirect.php create mode 100644 tests/simpletest/test/site/messy_frameset.html create mode 100644 tests/simpletest/test/site/multiple_widget_form.html create mode 100644 tests/simpletest/test/site/nested_frameset.html create mode 100644 tests/simpletest/test/site/network_confirm.php create mode 100644 tests/simpletest/test/site/one_page_frameset.html create mode 100644 tests/simpletest/test/site/page_request.php create mode 100644 tests/simpletest/test/site/path/base_change_redirect.php create mode 100644 tests/simpletest/test/site/path/network_confirm.php create mode 100644 tests/simpletest/test/site/path/show_cookies.php create mode 100644 tests/simpletest/test/site/protected/.htaccess create mode 100644 tests/simpletest/test/site/protected/.htpasswd create mode 100644 tests/simpletest/test/site/protected/1.html create mode 100644 tests/simpletest/test/site/protected/2.html create mode 100644 tests/simpletest/test/site/protected/3.html create mode 100644 tests/simpletest/test/site/protected/htaccess create mode 100644 tests/simpletest/test/site/protected/local_redirect.php create mode 100644 tests/simpletest/test/site/protected/network_confirm.php create mode 100644 tests/simpletest/test/site/redirect.php create mode 100644 tests/simpletest/test/site/savant_style_form.html create mode 100644 tests/simpletest/test/site/search.png create mode 100644 tests/simpletest/test/site/self_form.php create mode 100644 tests/simpletest/test/site/set_cookies.php create mode 100644 tests/simpletest/test/site/slow_page.php create mode 100644 tests/simpletest/test/site/timestamp.php create mode 100644 tests/simpletest/test/site/upload_form.html create mode 100644 tests/simpletest/test/site/upload_handler.php create mode 100644 tests/simpletest/test/socket_test.php create mode 100644 tests/simpletest/test/support/collector/collectable.1 create mode 100644 tests/simpletest/test/support/collector/collectable.2 create mode 100644 tests/simpletest/test/support/latin1_sample create mode 100644 tests/simpletest/test/support/spl_examples.php create mode 100644 tests/simpletest/test/support/supplementary_upload_sample.txt create mode 100644 tests/simpletest/test/support/test1.php create mode 100644 tests/simpletest/test/support/upload_sample.txt create mode 100644 tests/simpletest/test/tag_test.php create mode 100644 tests/simpletest/test/test_groups.php create mode 100644 tests/simpletest/test/test_with_parse_error.php create mode 100644 tests/simpletest/test/unit_tester_test.php create mode 100644 tests/simpletest/test/unit_tests.php create mode 100644 tests/simpletest/test/url_test.php create mode 100644 tests/simpletest/test/user_agent_test.php create mode 100644 tests/simpletest/test/visual_test.php create mode 100644 tests/simpletest/test/web_tester_test.php create mode 100644 tests/simpletest/test/xml_test.php create mode 100644 tests/simpletest/test_case.php create mode 100644 tests/simpletest/ui/array_reporter.php create mode 100644 tests/simpletest/ui/array_reporter/sample_test.php create mode 100644 tests/simpletest/ui/array_reporter/test.php create mode 100644 tests/simpletest/ui/colortext_reporter.php create mode 100644 tests/simpletest/ui/css/webunit.css create mode 100644 tests/simpletest/ui/img/wait.gif create mode 100644 tests/simpletest/ui/js/tests/TestOfWebunit.js.html create mode 100644 tests/simpletest/ui/js/webunit.js create mode 100644 tests/simpletest/ui/js/x.js create mode 100644 tests/simpletest/ui/webunit_reporter.php create mode 100644 tests/simpletest/unit_tester.php create mode 100644 tests/simpletest/url.php create mode 100644 tests/simpletest/user_agent.php create mode 100644 tests/simpletest/web_tester.php create mode 100644 tests/simpletest/xml.php diff --git a/tests/RemoteTest.php b/tests/RemoteTest.php new file mode 100644 index 00000000..b0dbf10c --- /dev/null +++ b/tests/RemoteTest.php @@ -0,0 +1,82 @@ +username); + $password = escape_string(pacrypt($this->password)); + + db_query("DELETE FROM $table_vacation WHERE email = '$username'"); + db_query("DELETE FROM $table_alias WHERE domain = 'example.com'"); + db_query("DELETE FROM $table_mailbox WHERE domain = 'example.com'"); + db_query("DELETE FROM $table_domain WHERE domain = 'example.com'"); + + // create new db records.. + $result = db_query("INSERT INTO $table_domain (domain, aliases, mailboxes) VALUES ('example.com', 100, 100)"); + if($result['rows'] != 1) { + die("Failed to add domain to db...."); + } + + $result = db_query("INSERT INTO $table_mailbox (username, password, name, local_part, domain) VALUES ('$username', '$password', 'test user', 'roger', 'example.com')"); + if($result['rows'] != 1) { + die("Failed to add user to db...."); + } + + $result = db_query("INSERT INTO $table_alias (address, goto, domain) VALUES ('$username', '$username', 'example.com')"); + if($result['rows'] != 1) { + die("Failed to add alias to db...."); + } + + try { + $this->xmlrpc_client = new Zend_XmlRpc_Client($this->server_url); + $http_client = $this->xmlrpc_client->getHttpClient(); + $http_client->setCookieJar(); + + $login_object = $this->xmlrpc_client->getProxy('login'); + $success = $login_object->login($this->username, $this->password); + + if(!$success) { + var_dump($success); + die("Failed to login to xmlrpc interface"); + } + + $this->user = $this->xmlrpc_client->getProxy('user'); + $this->alias = $this->xmlrpc_client->getProxy('alias'); + $this->vacation = $this->xmlrpc_client->getProxy('vacation'); + } + catch(Exception $e) { + var_dump($e); + var_dump($this->xmlrpc_client->getHttpClient()->getLastResponse()->getBody()); + die("Error setting up.."); + } + } +} diff --git a/tests/RemoteVacationTest.php b/tests/RemoteVacationTest.php new file mode 100644 index 00000000..89de4822 --- /dev/null +++ b/tests/RemoteVacationTest.php @@ -0,0 +1,81 @@ +assertTrue($this->vacation->isVacationSupported()); + } + catch(Exception $e){ + var_dump($e); + var_dump($this->xmlrpc_client->getHttpClient()->getLastResponse()->getBody()); + die("fail.."); + } + } + + public function testCheckVacation() { + $this->assertFalse($this->vacation->checkVacation()); + } + + + public function testGetDetails() { + $details = $this->vacation->getDetails(); + $this->assertFalse($details); // empty by default (thansk to tearDown/setUp); + } + + public function testSetAway() { + try { + $this->assertFalse($this->vacation->checkVacation()); + $this->assertTrue($this->vacation->setAway('zzzz', 'aaaa')); + $this->assertTrue($this->vacation->checkVacation()); + } + catch(Exception $e) { + var_dump($this->xmlrpc_client->getHttpClient()->getLastResponse()->getBody()); + } + $details = $this->vacation->getDetails(); + $this->assertEqual($details['subject'], 'zzzz'); + $this->assertEqual($details['body'], 'aaaa'); + + $this->vacation->remove(); + $details = $this->vacation->getDetails(); + $this->assertEqual($details['subject'], 'zzzz'); + $this->assertEqual($details['body'], 'aaaa'); + + $this->vacation->setAway('subject', 'body'); + $details = $this->vacation->getDetails(); + $this->assertEqual($details['subject'], 'subject'); + $this->assertEqual($details['body'], 'body'); + } + +} diff --git a/tests/common.php b/tests/common.php new file mode 100644 index 00000000..987b79ca --- /dev/null +++ b/tests/common.php @@ -0,0 +1,4 @@ +addTestFile('./RemoteVacationTest.php'); + +exit($test->run(new TextReporter()) ? 0 : 1); diff --git a/tests/simpletest/BACKLOG b/tests/simpletest/BACKLOG new file mode 100644 index 00000000..42fbb45b --- /dev/null +++ b/tests/simpletest/BACKLOG @@ -0,0 +1,37 @@ +BACKLOG +This is backed up stuff that defines the 1.0.1 release. + +$Id: BACKLOG,v 1.10 2006/11/20 23:44:36 lastcraft Exp $ + +Unit tester +----------- + +Reporter +-------- + +Mock objects +------------ +Fix new type hinting bug in PHP 5.0.2 and above (1). + +Parser +------ +Add U flag to regexes to allow unicode (3). + +Browser +------- +Add a file() loading command (4). +Change getUrls() to return more information (2). + +Web tester +---------- + +Documentation +------------- +Extension docs (1). +Integrate SpikeSource docs (4). +Write Eclipse plug-in guide (4). +Add page for projects that use or extend SimpleTest (2). + +Build +----- +Integrate German documentation (2). diff --git a/tests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE b/tests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE new file mode 100644 index 00000000..6cbd1346 --- /dev/null +++ b/tests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE @@ -0,0 +1,340 @@ +Simple Test interface changes +============================= +Because the SimpleTest tool set is still evolving it is likely that tests +written with earlier versions will fail with the newest ones. The most +dramatic changes are in the alpha releases. Here is a list of possible +problems and their fixes... + +Method setWildcard() removed in mocks +------------------------------------- +Even setWildcard() has been removed in 1.0.1beta now. +If you want to test explicitely for a '*' string, then +simply pass in new IdenticalExpectation('*') instead. + +No method _getTest() on mocks +----------------------------- +This has finally been removed. It was a pretty esoteric +flex point anyway. It was there to allow the mocks to +work with other test tools, but no one does this. + +No method assertError(), assertNoErrors(), swallowErrors() +---------------------------------------------------------- +These have been deprecated in 1.0.1beta in favour of +expectError() and expectException(). assertNoErrors() is +redundant if you use expectError() as failures are now reported +immediately. + +No method TestCase::signal() +---------------------------- +This has been deprecated in favour of triggering an error or +throwing an exception. Deprecated as of 1.0.1beta. + +No method TestCase::sendMessage() +--------------------------------- +This has been deprecated as of 1.0.1beta. + +Failure to connect now emits failures +------------------------------------- +It used to be that you would have to use the +getTransferError() call on the web tester to see if +there was a socket level error in a fetch. This check +is now always carried out by the WebTestCase unless +the fetch is prefaced with WebTestCase::ignoreErrors(). +The ignore directive only lasts for 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 +----------------------------------- +This behaviour has been switched to using plain text as if it +were seen by the user of the browser. This means that HTML tags +are suppressed, entities are converted and whitespace is +normalised. This should make it easier to match items in forms. +Also images are replaced with their "alt" text so that they +can be matched as well. + +No method SimpleRunner::_getTestCase() +-------------------------------------- +This was made public as getTestCase() in 1.0RC2. + +No method restartSession() +-------------------------- +This was renamed to restart() in the WebTestCase, SimpleBrowser +and the underlying SimpleUserAgent in 1.0RC2. Because it was +undocumented anyway, no attempt was made at backward +compatibility. + +My custom test case ignored by tally() +-------------------------------------- +The _assertTrue method has had it's signature changed due to a bug +in the PHP 5.0.1 release. You must now use getTest() from within +that method to get the test case. Mock compatibility with other +unit testers is now deprecated as of 1.0.1alpha as PEAR::PHPUnit2 +should soon have mock support of it's own. + +Broken code extending SimpleRunner +---------------------------------- +This was replaced with SimpleScorer so that I could use the runner +name in another class. This happened in RC1 development and there +is no easy backward compatibility fix. The solution is simply to +extend SimpleScorer instead. + +Missing method getBaseCookieValue() +----------------------------------- +This was renamed getCurrentCookieValue() in RC1. + +Missing files from the SimpleTest suite +--------------------------------------- +Versions of SimpleTest prior to Beta6 required a SIMPLE_TEST constant +to point at the SimpleTest folder location before any of the toolset +was loaded. This is no longer documented as it is now unnecessary +for later versions. If you are using an earlier version you may +need this constant. Consult the documentation that was bundled with +the release that you are using or upgrade to Beta6 or later. + +No method SimpleBrowser::getCurrentUrl() +-------------------------------------- +This is replaced with the more versatile showRequest() for +debugging. It only existed in this context for version Beta5. +Later versions will have SimpleBrowser::getHistory() for tracking +paths through pages. It is renamed as getUrl() since 1.0RC1. + +No method Stub::setStubBaseClass() +---------------------------------- +This method has finally been removed in 1.0RC1. Use +SimpleTestOptions::setStubBaseClass() instead. + +No class CommandLineReporter +---------------------------- +This was renamed to TextReporter in Beta3 and the deprecated version +was removed in 1.0RC1. + +No method requireReturn() +------------------------- +This was deprecated in Beta3 and is now removed. + +No method expectCookie() +------------------------ +This method was abruptly removed in Beta4 so as to simplify the internals +until another mechanism can replace it. As a workaround it is necessary +to assert that the cookie has changed by setting it before the page +fetch and then assert the desired value. + +No method clickSubmitByFormId() +------------------------------- +This method had an incorrect name as no button was involved. It was +renamed to submitByFormId() in Beta4 and the old version deprecated. +Now removed. + +No method paintStart() or paintEnd() +------------------------------------ +You should only get this error if you have subclassed the lower level +reporting and test runner machinery. These methods have been broken +down into events for test methods, events for test cases and events +for group tests. The new methods are... + +paintStart() --> paintMethodStart(), paintCaseStart(), paintGroupStart() +paintEnd() --> paintMethodEnd(), paintCaseEnd(), paintGroupEnd() + +This change was made in Beta3, ironically to make it easier to subclass +the inner machinery. Simply duplicating the code you had in the previous +methods should provide a temporary fix. + +No class TestDisplay +-------------------- +This has been folded into SimpleReporter in Beta3 and is now deprecated. +It was removed in RC1. + +No method WebTestCase::fetch() +------------------------------ +This was renamed get() in Alpha8. It is removed in Beta3. + +No method submit() +------------------ +This has been renamed clickSubmit() in Beta1. The old method was +removed in Beta2. + +No method clearHistory() +------------------------ +This method is deprecated in Beta2 and removed in RC1. + +No method getCallCount() +------------------------ +This method has been deprecated since Beta1 and has now been +removed. There are now more ways to set expectations on counts +and so this method should be unecessery. Removed in RC1. + +Cannot find file * +------------------ +The following public name changes have occoured... + +simple_html_test.php --> reporter.php +simple_mock.php --> mock_objects.php +simple_unit.php --> unit_tester.php +simple_web.php --> web_tester.php + +The old names were deprecated in Alpha8 and removed in Beta1. + +No method attachObserver() +-------------------------- +Prior to the Alpha8 release the old internal observer pattern was +gutted and replaced with a visitor. This is to trade flexibility of +test case expansion against the ease of writing user interfaces. + +Code such as... + +$test = &new MyTestCase(); +$test->attachObserver(new TestHtmlDisplay()); +$test->run(); + +...should be rewritten as... + +$test = &new MyTestCase(); +$test->run(new HtmlReporter()); + +If you previously attached multiple observers then the workaround +is to run the tests twice, once with each, until they can be combined. +For one observer the old method is simulated in Alpha 8, but is +removed in Beta1. + +No class TestHtmlDisplay +------------------------ +This class has been renamed to HtmlReporter in Alpha8. It is supported, +but deprecated in Beta1 and removed in Beta2. If you have subclassed +the display for your own design, then you will have to extend this +class (HtmlReporter) instead. + +If you have accessed the event queue by overriding the notify() method +then I am afraid you are in big trouble :(. The reporter is now +carried around the test suite by the runner classes and the methods +called directly. In the unlikely event that this is a problem and +you don't want to upgrade the test tool then simplest is to write your +own runner class and invoke the tests with... + +$test->accept(new MyRunner(new MyReporter())); + +...rather than the run method. This should be easier to extend +anyway and gives much more control. Even this method is overhauled +in Beta3 where the runner class can be set within the test case. Really +the best thing to do is to upgrade to this version as whatever you were +trying to achieve before should now be very much easier. + +Missing set options method +-------------------------- +All test suite options are now in one class called SimpleTestOptions. +This means that options are set differently... + +GroupTest::ignore() --> SimpleTestOptions::ignore() +Mock::setMockBaseClass() --> SimpleTestOptions::setMockBaseClass() + +These changed in Alpha8 and the old versions are now removed in RC1. + +No method setExpected*() +------------------------ +The mock expectations changed their names in Alpha4 and the old names +ceased to be supported in Alpha8. The changes are... + +setExpectedArguments() --> expectArguments() +setExpectedArgumentsSequence() --> expectArgumentsAt() +setExpectedCallCount() --> expectCallCount() +setMaximumCallCount() --> expectMaximumCallCount() + +The parameters remained the same. diff --git a/tests/simpletest/LICENSE b/tests/simpletest/LICENSE new file mode 100644 index 00000000..09f465ab --- /dev/null +++ b/tests/simpletest/LICENSE @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/tests/simpletest/README b/tests/simpletest/README new file mode 100644 index 00000000..b8d19792 --- /dev/null +++ b/tests/simpletest/README @@ -0,0 +1,108 @@ +SimpleTest +========== +You probably got this package from... +http://simpletest.sourceforge.net/projects/simpletest/ + +If there is no licence agreement with this package please download +a version from the location above. You must read and accept that +licence to use this software. The file is titled simply LICENSE. + +What is it? It's a framework for unit testing, web site testing and +mock objects for PHP 4.2.0+. + +If you have used JUnit you will find this PHP unit testing version very +similar. Also included is a mock objects and server stubs generator. +The stubs can have return values set for different arguments, can have +sequences set also by arguments and can return items by reference. +The mocks inherit all of this functionality and can also have +expectations set, again in sequences and for different arguments. + +A web tester similar in concept to JWebUnit is also included. There is no +JavaScript or tables support, but forms, authentication, cookies and +frames are handled. + +You can see a release schedule at http://www.lastcraft.com/overview.php +which is also copied to the documentation folder with this release. +A full PHPDocumenter API documentation exists at +http://simpletest.sourceforge.net/. + +The user interface is minimal +in the extreme, but a lot of information flows from the test suite. +After version 1.0 we will release a better web UI, but we are leaving XUL +and GTk versions to volunteers as everybody has their own opinion +on a good GUI, and we don't want to discourage development by shipping +one with the toolkit. + +You are looking at a first full release. The unit tests for SimpleTest +itself can be run here... + +simpletest/test/unit_tests.php + +And tests involving live network connections as well are here... + +simpletest/test/all_tests.php + +The full tests will typically overrun the 8Mb limit usually allowed +to a PHP process. A workaround is to run the tests on the command +with a custom php.ini file if you do not have access to your server +version. + +You will have to edit the all_tests.php file if you are accesssing +the internet through a proxy server. See the comments in all_tests.php +for instructions. + +The full tests read some test data from the LastCraft site. If the site +is down or has been modified for a later version then you will get +spurious errors. A unit_tests.php failure on the other hand would be +very serious. As far as we know we haven't yet managed to check in any +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... + +HELP_MY_TESTS_DONT_WORK_ANYMORE + +This contains information on interface changes. It also points out +deprecated interfaces so you should read this even if all of +your current tests appear to run. + +There is a documentation folder which contains the core reference information +in English and French, although this information is fairly basic. +You can find a tutorial on... + +http://www.lastcraft.com/first_test_tutorial.php + +...to get you started and this material will eventually become included +with the project documentation. A French translation exists at... + +http://www.onpk.net/index.php/2005/01/12/254-tutoriel-simpletest-decouvrir-les-tests-unitaires. + +If you download and use and possibly even extend this tool, please let us +know. Any feedback, even bad, is always welcome and we will work to get +your suggestions into the next release. Ideally please send your +comments to... + +simpletest-support@lists.sourceforge.net + +...so that others can read them too. We usually try to respond within 48 +hours. + +There is no change log as yet except at Sourceforge. You can visit the +release notes to see the completed TODO list after each cycle and also the +status of any bugs, but if the bug is recent then it will be fixed in CVS only. +The CVS check-ins always have all the tests passing and so CVS snapshots should +be pretty usable, although the code may not look so good internally. + +Oh, yes. It is called "Simple" because it should be simple to +use. We intend to add a complete set of tools for a test first +and "test as you code" type of development. "Simple" does not +mean "Lite" in this context. + +Thanks to everyone who has sent comments and offered suggestions. They +really are invaluable, but sadly you are too many to mention in full. +Thanks to all on the advanced PHP forum on SitePoint, especially Harry +Feucks. Early adopters are always an inspiration. + +yours Marcus Baker, Jason Sweat, Travis Swicegood and Perrick Penet. +-- +marcus@lastcraft.com diff --git a/tests/simpletest/TODO b/tests/simpletest/TODO new file mode 100644 index 00000000..859575d9 --- /dev/null +++ b/tests/simpletest/TODO @@ -0,0 +1,32 @@ +TODO +This is immediate stuff only for this iteration (1.0.1beta2) of 15 hours. + +$Id: TODO,v 1.508 2007/01/16 23:35:21 lastcraft Exp $ + +Unit tester +----------- +Fix errors_test.php in PHP 5.2+ (2). + +Reporter +-------- +Dumper should be passed in testMessage() call to expectation (3). + +Mock objects +------------ +Mocks should inherit mocked class (9/4). + +Parser +------ + +Browser +------- + +Web tester +---------- + +Documentation +------------- +Update roadmap (1). + +Build +----- diff --git a/tests/simpletest/VERSION b/tests/simpletest/VERSION new file mode 100644 index 00000000..5f05a2a0 --- /dev/null +++ b/tests/simpletest/VERSION @@ -0,0 +1 @@ +1.0.1beta2 \ No newline at end of file diff --git a/tests/simpletest/authentication.php b/tests/simpletest/authentication.php new file mode 100644 index 00000000..dcfee8ac --- /dev/null +++ b/tests/simpletest/authentication.php @@ -0,0 +1,238 @@ +_type = $type; + $this->_root = $url->getBasePath(); + $this->_username = false; + $this->_password = false; + } + + /** + * Adds another location to the realm. + * @param SimpleUrl $url Somewhere in realm. + * @access public + */ + function stretch($url) { + $this->_root = $this->_getCommonPath($this->_root, $url->getPath()); + } + + /** + * Finds the common starting path. + * @param string $first Path to compare. + * @param string $second Path to compare. + * @return string Common directories. + * @access private + */ + function _getCommonPath($first, $second) { + $first = explode('/', $first); + $second = explode('/', $second); + for ($i = 0; $i < min(count($first), count($second)); $i++) { + if ($first[$i] != $second[$i]) { + return implode('/', array_slice($first, 0, $i)) . '/'; + } + } + return implode('/', $first) . '/'; + } + + /** + * Sets the identity to try within this realm. + * @param string $username Username in authentication dialog. + * @param string $username Password in authentication dialog. + * @access public + */ + function setIdentity($username, $password) { + $this->_username = $username; + $this->_password = $password; + } + + /** + * Accessor for current identity. + * @return string Last succesful username. + * @access public + */ + function getUsername() { + return $this->_username; + } + + /** + * Accessor for current identity. + * @return string Last succesful password. + * @access public + */ + function getPassword() { + return $this->_password; + } + + /** + * Test to see if the URL is within the directory + * tree of the realm. + * @param SimpleUrl $url URL to test. + * @return boolean True if subpath. + * @access public + */ + function isWithin($url) { + if ($this->_isIn($this->_root, $url->getBasePath())) { + return true; + } + if ($this->_isIn($this->_root, $url->getBasePath() . $url->getPage() . '/')) { + return true; + } + return false; + } + + /** + * Tests to see if one string is a substring of + * another. + * @param string $part Small bit. + * @param string $whole Big bit. + * @return boolean True if the small bit is + * in the big bit. + * @access private + */ + function _isIn($part, $whole) { + return strpos($whole, $part) === 0; + } + } + + /** + * Manages security realms. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleAuthenticator { + var $_realms; + + /** + * Clears the realms. + * @access public + */ + function SimpleAuthenticator() { + $this->restartSession(); + } + + /** + * Starts with no realms set up. + * @access public + */ + function restartSession() { + $this->_realms = array(); + } + + /** + * Adds a new realm centered the current URL. + * Browsers vary wildly on their behaviour in this + * regard. Mozilla ignores the realm and presents + * only when challenged, wasting bandwidth. IE + * just carries on presenting until a new challenge + * occours. SimpleTest tries to follow the spirit of + * the original standards committee and treats the + * base URL as the root of a file tree shaped realm. + * @param SimpleUrl $url Base of realm. + * @param string $type Authentication type for this + * realm. Only Basic authentication + * is currently supported. + * @param string $realm Name of realm. + * @access public + */ + function addRealm($url, $type, $realm) { + $this->_realms[$url->getHost()][$realm] = new SimpleRealm($type, $url); + } + + /** + * Sets the current identity to be presented + * against that realm. + * @param string $host Server hosting realm. + * @param string $realm Name of realm. + * @param string $username Username for realm. + * @param string $password Password for realm. + * @access public + */ + function setIdentityForRealm($host, $realm, $username, $password) { + if (isset($this->_realms[$host][$realm])) { + $this->_realms[$host][$realm]->setIdentity($username, $password); + } + } + + /** + * Finds the name of the realm by comparing URLs. + * @param SimpleUrl $url URL to test. + * @return SimpleRealm Name of realm. + * @access private + */ + function _findRealmFromUrl($url) { + if (! isset($this->_realms[$url->getHost()])) { + return false; + } + foreach ($this->_realms[$url->getHost()] as $name => $realm) { + if ($realm->isWithin($url)) { + return $realm; + } + } + return false; + } + + /** + * Presents the appropriate headers for this location. + * @param SimpleHttpRequest $request Request to modify. + * @param SimpleUrl $url Base of realm. + * @access public + */ + function addHeaders(&$request, $url) { + if ($url->getUsername() && $url->getPassword()) { + $username = $url->getUsername(); + $password = $url->getPassword(); + } elseif ($realm = $this->_findRealmFromUrl($url)) { + $username = $realm->getUsername(); + $password = $realm->getPassword(); + } else { + return; + } + $this->addBasicHeaders($request, $username, $password); + } + + /** + * Presents the appropriate headers for this + * location for basic authentication. + * @param SimpleHttpRequest $request Request to modify. + * @param string $username Username for realm. + * @param string $password Password for realm. + * @access public + * @static + */ + function addBasicHeaders(&$request, $username, $password) { + if ($username && $password) { + $request->addHeaderLine( + 'Authorization: Basic ' . base64_encode("$username:$password")); + } + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/browser.php b/tests/simpletest/browser.php new file mode 100644 index 00000000..e1d61fb8 --- /dev/null +++ b/tests/simpletest/browser.php @@ -0,0 +1,1097 @@ +_sequence = array(); + $this->_position = -1; + } + + /** + * Test for no entries yet. + * @return boolean True if empty. + * @access private + */ + function _isEmpty() { + return ($this->_position == -1); + } + + /** + * Test for being at the beginning. + * @return boolean True if first. + * @access private + */ + function _atBeginning() { + return ($this->_position == 0) && ! $this->_isEmpty(); + } + + /** + * Test for being at the last entry. + * @return boolean True if last. + * @access private + */ + function _atEnd() { + return ($this->_position + 1 >= count($this->_sequence)) && ! $this->_isEmpty(); + } + + /** + * Adds a successfully fetched page to the history. + * @param SimpleUrl $url URL of fetch. + * @param SimpleEncoding $parameters Any post data with the fetch. + * @access public + */ + function recordEntry($url, $parameters) { + $this->_dropFuture(); + array_push( + $this->_sequence, + array('url' => $url, 'parameters' => $parameters)); + $this->_position++; + } + + /** + * Last fully qualified URL for current history + * position. + * @return SimpleUrl URL for this position. + * @access public + */ + function getUrl() { + if ($this->_isEmpty()) { + return false; + } + return $this->_sequence[$this->_position]['url']; + } + + /** + * Parameters of last fetch from current history + * position. + * @return SimpleFormEncoding Post parameters. + * @access public + */ + function getParameters() { + if ($this->_isEmpty()) { + return false; + } + return $this->_sequence[$this->_position]['parameters']; + } + + /** + * Step back one place in the history. Stops at + * the first page. + * @return boolean True if any previous entries. + * @access public + */ + function back() { + if ($this->_isEmpty() || $this->_atBeginning()) { + return false; + } + $this->_position--; + return true; + } + + /** + * Step forward one place. If already at the + * latest entry then nothing will happen. + * @return boolean True if any future entries. + * @access public + */ + function forward() { + if ($this->_isEmpty() || $this->_atEnd()) { + return false; + } + $this->_position++; + return true; + } + + /** + * Ditches all future entries beyond the current + * point. + * @access private + */ + function _dropFuture() { + if ($this->_isEmpty()) { + return; + } + while (! $this->_atEnd()) { + array_pop($this->_sequence); + } + } + } + + /** + * Simulated web browser. This is an aggregate of + * the user agent, the HTML parsing, request history + * and the last header set. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleBrowser { + var $_user_agent; + var $_page; + var $_history; + var $_ignore_frames; + var $_maximum_nested_frames; + + /** + * Starts with a fresh browser with no + * cookie or any other state information. The + * exception is that a default proxy will be + * set up if specified in the options. + * @access public + */ + function SimpleBrowser() { + $this->_user_agent = &$this->_createUserAgent(); + $this->_user_agent->useProxy( + 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() { + $user_agent = &new SimpleUserAgent(); + return $user_agent; + } + + /** + * Creates a new empty history list. + * @return SimpleBrowserHistory New list. + * @access protected + */ + function &_createHistory() { + $history = &new SimpleBrowserHistory(); + return $history; + } + + /** + * Disables frames support. Frames will not be fetched + * and the frameset page will be used instead. + * @access public + */ + function ignoreFrames() { + $this->_ignore_frames = true; + } + + /** + * Enables frames support. Frames will be fetched from + * now on. + * @access public + */ + function useFrames() { + $this->_ignore_frames = false; + } + + /** + * Switches off cookie sending and recieving. + * @access public + */ + function ignoreCookies() { + $this->_user_agent->ignoreCookies(); + } + + /** + * Switches back on the cookie sending and recieving. + * @access public + */ + function useCookies() { + $this->_user_agent->useCookies(); + } + + /** + * Parses the raw content into a page. Will load further + * frame pages unless frames are disabled. + * @param SimpleHttpResponse $response Response from fetch. + * @param integer $depth Nested frameset depth. + * @return SimplePage Parsed HTML. + * @access private + */ + function &_parse($response, $depth = 0) { + $page = &$this->_buildPage($response); + if ($this->_ignore_frames || ! $page->hasFrames() || ($depth > $this->_maximum_nested_frames)) { + return $page; + } + $frameset = &new SimpleFrameset($page); + foreach ($page->getFrameset() as $key => $url) { + $frame = &$this->_fetch($url, new SimpleGetEncoding(), $depth + 1); + $frameset->addFrame($frame, $key); + } + return $frameset; + } + + /** + * Assembles the parsing machinery and actually parses + * a single page. Frees all of the builder memory and so + * unjams the PHP memory management. + * @param SimpleHttpResponse $response Response from fetch. + * @return SimplePage Parsed top level page. + * @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($url, $encoding, $depth = 0) { + $response = &$this->_user_agent->fetchResponse($url, $encoding); + if ($response->isError()) { + $page = &new SimplePage($response); + } else { + $page = &$this->_parse($response, $depth); + } + return $page; + } + + /** + * Fetches a page or a single frame if that is the current + * focus. + * @param SimpleUrl $url Target to fetch. + * @param SimpleEncoding $parameters GET/POST parameters. + * @return string Raw content of page. + * @access private + */ + function _load($url, $parameters) { + $frame = $url->getTarget(); + if (! $frame || ! $this->_page->hasFrames() || (strtolower($frame) == '_top')) { + return $this->_loadPage($url, $parameters); + } + return $this->_loadFrame(array($frame), $url, $parameters); + } + + /** + * Fetches a page and makes it the current page/frame. + * @param string/SimpleUrl $url Target to fetch as string. + * @param SimplePostEncoding $parameters POST parameters. + * @return string Raw content of page. + * @access private + */ + function _loadPage($url, $parameters) { + $this->_page = &$this->_fetch($url, $parameters); + $this->_history->recordEntry( + $this->_page->getUrl(), + $this->_page->getRequestData()); + return $this->_page->getRaw(); + } + + /** + * Fetches a frame into the existing frameset replacing the + * original. + * @param array $frames List of names to drill down. + * @param string/SimpleUrl $url Target to fetch as string. + * @param SimpleFormEncoding $parameters POST parameters. + * @return string Raw content of page. + * @access private + */ + 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. + * @param string/integer $date Time when session restarted. + * If omitted then all persistent + * cookies are kept. + * @access public + */ + function restart($date = false) { + $this->_user_agent->restart($date); + } + + /** + * Adds a header to every fetch. + * @param string $header Header line to add to every + * request until cleared. + * @access public + */ + function addHeader($header) { + $this->_user_agent->addHeader($header); + } + + /** + * Ages the cookies by the specified time. + * @param integer $interval Amount in seconds. + * @access public + */ + function ageCookies($interval) { + $this->_user_agent->ageCookies($interval); + } + + /** + * Sets an additional cookie. If a cookie has + * the same name and path it is replaced. + * @param string $name Cookie key. + * @param string $value Value of cookie. + * @param string $host Host upon which the cookie is valid. + * @param string $path Cookie path if not host wide. + * @param string $expiry Expiry date. + * @access public + */ + function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { + $this->_user_agent->setCookie($name, $value, $host, $path, $expiry); + } + + /** + * Reads the most specific cookie value from the + * browser cookies. + * @param string $host Host to search. + * @param string $path Applicable path. + * @param string $name Name of cookie to read. + * @return string False if not present, else the + * value as a string. + * @access public + */ + function getCookieValue($host, $path, $name) { + return $this->_user_agent->getCookieValue($host, $path, $name); + } + + /** + * Reads the current cookies for the current URL. + * @param string $name Key of cookie to find. + * @return string Null if there is no current URL, false + * if the cookie is not set. + * @access public + */ + function getCurrentCookieValue($name) { + return $this->_user_agent->getBaseCookieValue($name, $this->_page->getUrl()); + } + + /** + * Sets the maximum number of redirects before + * a page will be loaded anyway. + * @param integer $max Most hops allowed. + * @access public + */ + function setMaximumRedirects($max) { + $this->_user_agent->setMaximumRedirects($max); + } + + /** + * Sets the maximum number of nesting of framed pages + * within a framed page to prevent loops. + * @param integer $max Highest depth allowed. + * @access public + */ + function setMaximumNestedFrames($max) { + $this->_maximum_nested_frames = $max; + } + + /** + * Sets the socket timeout for opening a connection. + * @param integer $timeout Maximum time in seconds. + * @access public + */ + function setConnectionTimeout($timeout) { + $this->_user_agent->setConnectionTimeout($timeout); + } + + /** + * Sets proxy to use on all requests for when + * testing from behind a firewall. Set URL + * to false to disable. + * @param string $proxy Proxy URL. + * @param string $username Proxy username for authentication. + * @param string $password Proxy password for authentication. + * @access public + */ + function useProxy($proxy, $username = false, $password = false) { + $this->_user_agent->useProxy($proxy, $username, $password); + } + + /** + * Fetches the page content with a HEAD request. + * Will affect cookies, but will not change the base URL. + * @param string/SimpleUrl $url Target to fetch as string. + * @param hash/SimpleHeadEncoding $parameters Additional parameters for + * HEAD request. + * @return boolean True if successful. + * @access public + */ + function head($url, $parameters = false) { + if (! is_object($url)) { + $url = new SimpleUrl($url); + } + if ($this->getUrl()) { + $url = $url->makeAbsolute($this->getUrl()); + } + $response = &$this->_user_agent->fetchResponse($url, new SimpleHeadEncoding($parameters)); + return ! $response->isError(); + } + + /** + * Fetches the page content with a simple GET request. + * @param string/SimpleUrl $url Target to fetch. + * @param hash/SimpleFormEncoding $parameters Additional parameters for + * GET request. + * @return string Content of page or false. + * @access public + */ + function get($url, $parameters = false) { + if (! is_object($url)) { + $url = new SimpleUrl($url); + } + if ($this->getUrl()) { + $url = $url->makeAbsolute($this->getUrl()); + } + return $this->_load($url, new SimpleGetEncoding($parameters)); + } + + /** + * Fetches the page content with a POST request. + * @param string/SimpleUrl $url Target to fetch as string. + * @param hash/SimpleFormEncoding $parameters POST parameters. + * @return string Content of page. + * @access public + */ + function post($url, $parameters = false) { + if (! is_object($url)) { + $url = new SimpleUrl($url); + } + if ($this->getUrl()) { + $url = $url->makeAbsolute($this->getUrl()); + } + return $this->_load($url, new SimplePostEncoding($parameters)); + } + + /** + * Equivalent to hitting the retry button on the + * browser. Will attempt to repeat the page fetch. If + * there is no history to repeat it will give false. + * @return string/boolean Content if fetch succeeded + * else false. + * @access public + */ + function retry() { + $frames = $this->_page->getFrameFocus(); + if (count($frames) > 0) { + $this->_loadFrame( + $frames, + $this->_page->getUrl(), + $this->_page->getRequestData()); + return $this->_page->getRaw(); + } + if ($url = $this->_history->getUrl()) { + $this->_page = &$this->_fetch($url, $this->_history->getParameters()); + return $this->_page->getRaw(); + } + return false; + } + + /** + * Equivalent to hitting the back button on the + * browser. The browser history is unchanged on + * failure. The page content is refetched as there + * is no concept of content caching in SimpleTest. + * @return boolean True if history entry and + * fetch succeeded + * @access public + */ + function back() { + if (! $this->_history->back()) { + return false; + } + $content = $this->retry(); + if (! $content) { + $this->_history->forward(); + } + return $content; + } + + /** + * Equivalent to hitting the forward button on the + * browser. The browser history is unchanged on + * failure. The page content is refetched as there + * is no concept of content caching in SimpleTest. + * @return boolean True if history entry and + * fetch succeeded + * @access public + */ + function forward() { + if (! $this->_history->forward()) { + return false; + } + $content = $this->retry(); + if (! $content) { + $this->_history->back(); + } + return $content; + } + + /** + * Retries a request after setting the authentication + * for the current realm. + * @param string $username Username for realm. + * @param string $password Password for realm. + * @return boolean True if successful fetch. Note + * that authentication may still have + * failed. + * @access public + */ + function authenticate($username, $password) { + if (! $this->_page->getRealm()) { + return false; + } + $url = $this->_page->getUrl(); + if (! $url) { + return false; + } + $this->_user_agent->setIdentity( + $url->getHost(), + $this->_page->getRealm(), + $username, + $password); + return $this->retry(); + } + + /** + * Accessor for a breakdown of the frameset. + * @return array Hash tree of frames by name + * or index if no name. + * @access public + */ + function getFrames() { + return $this->_page->getFrames(); + } + + /** + * Accessor for current frame focus. Will be + * false if no frame has focus. + * @return integer/string/boolean Label if any, otherwise + * the position in the frameset + * or false if none. + * @access public + */ + function getFrameFocus() { + return $this->_page->getFrameFocus(); + } + + /** + * Sets the focus by index. The integer index starts from 1. + * @param integer $choice Chosen frame. + * @return boolean True if frame exists. + * @access public + */ + function setFrameFocusByIndex($choice) { + return $this->_page->setFrameFocusByIndex($choice); + } + + /** + * Sets the focus by name. + * @param string $name Chosen frame. + * @return boolean True if frame exists. + * @access public + */ + function setFrameFocus($name) { + return $this->_page->setFrameFocus($name); + } + + /** + * Clears the frame focus. All frames will be searched + * for content. + * @access public + */ + function clearFrameFocus() { + return $this->_page->clearFrameFocus(); + } + + /** + * Accessor for last error. + * @return string Error from last response. + * @access public + */ + function getTransportError() { + return $this->_page->getTransportError(); + } + + /** + * Accessor for current MIME type. + * @return string MIME type as string; e.g. 'text/html' + * @access public + */ + function getMimeType() { + return $this->_page->getMimeType(); + } + + /** + * Accessor for last response code. + * @return integer Last HTTP response code received. + * @access public + */ + function getResponseCode() { + return $this->_page->getResponseCode(); + } + + /** + * Accessor for last Authentication type. Only valid + * straight after a challenge (401). + * @return string Description of challenge type. + * @access public + */ + function getAuthentication() { + return $this->_page->getAuthentication(); + } + + /** + * Accessor for last Authentication realm. Only valid + * straight after a challenge (401). + * @return string Name of security realm. + * @access public + */ + function getRealm() { + return $this->_page->getRealm(); + } + + /** + * Accessor for current URL of page or frame if + * focused. + * @return string Location of current page or frame as + * a string. + */ + function getUrl() { + $url = $this->_page->getUrl(); + return $url ? $url->asString() : false; + } + + /** + * Accessor for raw bytes sent down the wire. + * @return string Original text sent. + * @access public + */ + function getRequest() { + return $this->_page->getRequest(); + } + + /** + * Accessor for raw header information. + * @return string Header block. + * @access public + */ + function getHeaders() { + return $this->_page->getHeaders(); + } + + /** + * Accessor for raw page information. + * @return string Original text content of web page. + * @access public + */ + function getContent() { + return $this->_page->getRaw(); + } + + /** + * Accessor for plain text version of the page. + * @return string Normalised text representation. + * @access public + */ + function getContentAsText() { + return $this->_page->getText(); + } + + /** + * Accessor for parsed title. + * @return string Title or false if no title is present. + * @access public + */ + function getTitle() { + return $this->_page->getTitle(); + } + + /** + * Accessor for a list of all fixed links in current page. + * @return array List of urls with scheme of + * http or https and hostname. + * @access public + */ + function getAbsoluteUrls() { + return $this->_page->getAbsoluteUrls(); + } + + /** + * Accessor for a list of all relative links. + * @return array List of urls without hostname. + * @access public + */ + function getRelativeUrls() { + return $this->_page->getRelativeUrls(); + } + + /** + * Sets all form fields with that name. + * @param string $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 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. + * @param string $value New value of field. + * @return boolean True if field exists, otherwise false. + * @access public + */ + function setFieldById($id, $value) { + return $this->_page->setField(new SimpleById($id), $value); + } + + /** + * Accessor for a form element value within the page. + * Finds the first match. + * @param string $label Field label. + * @return string/boolean A value if the field is + * present, false if unchecked + * and null if missing. + * @access public + */ + function getField($label) { + return $this->_page->getField(new SimpleByLabelOrName($label)); + } + + /** + * Accessor for a form element value within the page. + * Finds the first match. + * @param string $name Field name. + * @return string/boolean A string if the field is + * present, false if unchecked + * and null if missing. + * @access public + */ + function getFieldByName($name) { + return $this->_page->getField(new SimpleByName($name)); + } + + /** + * Accessor for a form element value within the page. + * @param string/integer $id Id of field in forms. + * @return string/boolean A string if the field is + * present, false if unchecked + * and null if missing. + * @access public + */ + function getFieldById($id) { + return $this->_page->getField(new SimpleById($id)); + } + + /** + * Clicks the submit button by label. The owning + * form will be submitted by this. + * @param string $label Button label. An unlabeled + * button can be triggered by 'Submit'. + * @param hash $additional Additional form data. + * @return string/boolean Page on success. + * @access public + */ + function clickSubmit($label = 'Submit', $additional = false) { + if (! ($form = &$this->_page->getFormBySubmit(new SimpleByLabel($label)))) { + return false; + } + $success = $this->_load( + $form->getAction(), + $form->submitButton(new SimpleByLabel($label), $additional)); + return ($success ? $this->getContent() : $success); + } + + /** + * Clicks the submit button by name attribute. The owning + * form will be submitted by this. + * @param string $name Button name. + * @param hash $additional Additional form data. + * @return string/boolean Page on success. + * @access public + */ + function clickSubmitByName($name, $additional = false) { + if (! ($form = &$this->_page->getFormBySubmit(new SimpleByName($name)))) { + return false; + } + $success = $this->_load( + $form->getAction(), + $form->submitButton(new SimpleByName($name), $additional)); + return ($success ? $this->getContent() : $success); + } + + /** + * Clicks the submit button by ID attribute of the button + * itself. The owning form will be submitted by this. + * @param string $id Button ID. + * @param hash $additional Additional form data. + * @return string/boolean Page on success. + * @access public + */ + function clickSubmitById($id, $additional = false) { + if (! ($form = &$this->_page->getFormBySubmit(new SimpleById($id)))) { + return false; + } + $success = $this->_load( + $form->getAction(), + $form->submitButton(new SimpleById($id), $additional)); + return ($success ? $this->getContent() : $success); + } + + /** + * Tests to see if a submit button exists with this + * label. + * @param string $label Button label. + * @return boolean True if present. + * @access public + */ + function isSubmit($label) { + return (boolean)$this->_page->getFormBySubmit(new SimpleByLabel($label)); + } + + /** + * Clicks the submit image by some kind of label. Usually + * the alt tag or the nearest equivalent. The owning + * form will be submitted by this. Clicking outside of + * the boundary of the coordinates will result in + * a failure. + * @param string $label ID attribute of button. + * @param integer $x X-coordinate of imaginary click. + * @param integer $y Y-coordinate of imaginary click. + * @param hash $additional Additional form data. + * @return string/boolean Page on success. + * @access public + */ + function clickImage($label, $x = 1, $y = 1, $additional = false) { + if (! ($form = &$this->_page->getFormByImage(new SimpleByLabel($label)))) { + return false; + } + $success = $this->_load( + $form->getAction(), + $form->submitImage(new SimpleByLabel($label), $x, $y, $additional)); + return ($success ? $this->getContent() : $success); + } + + /** + * Clicks the submit image by the name. Usually + * the alt tag or the nearest equivalent. The owning + * form will be submitted by this. Clicking outside of + * the boundary of the coordinates will result in + * a failure. + * @param string $name Name attribute of button. + * @param integer $x X-coordinate of imaginary click. + * @param integer $y Y-coordinate of imaginary click. + * @param hash $additional Additional form data. + * @return string/boolean Page on success. + * @access public + */ + function clickImageByName($name, $x = 1, $y = 1, $additional = false) { + if (! ($form = &$this->_page->getFormByImage(new SimpleByName($name)))) { + return false; + } + $success = $this->_load( + $form->getAction(), + $form->submitImage(new SimpleByName($name), $x, $y, $additional)); + return ($success ? $this->getContent() : $success); + } + + /** + * Clicks the submit image by ID attribute. The owning + * form will be submitted by this. Clicking outside of + * the boundary of the coordinates will result in + * a failure. + * @param integer/string $id ID attribute of button. + * @param integer $x X-coordinate of imaginary click. + * @param integer $y Y-coordinate of imaginary click. + * @param hash $additional Additional form data. + * @return string/boolean Page on success. + * @access public + */ + function clickImageById($id, $x = 1, $y = 1, $additional = false) { + if (! ($form = &$this->_page->getFormByImage(new SimpleById($id)))) { + return false; + } + $success = $this->_load( + $form->getAction(), + $form->submitImage(new SimpleById($id), $x, $y, $additional)); + return ($success ? $this->getContent() : $success); + } + + /** + * Tests to see if an image exists with this + * title or alt text. + * @param string $label Image text. + * @return boolean True if present. + * @access public + */ + function isImage($label) { + return (boolean)$this->_page->getFormByImage(new SimpleByLabel($label)); + } + + /** + * Submits a form by the ID. + * @param string $id The form ID. No submit button value + * will be sent. + * @return string/boolean Page on success. + * @access public + */ + function submitFormById($id) { + if (! ($form = &$this->_page->getFormById($id))) { + return false; + } + $success = $this->_load( + $form->getAction(), + $form->submit()); + return ($success ? $this->getContent() : $success); + } + + /** + * Finds a URL by label. Will find the first link + * found with this link text by default, or a later + * one if an index is given. The match ignores case and + * white space issues. + * @param string $label Text between the anchor tags. + * @param integer $index Link position counting from zero. + * @return string/boolean URL on success. + * @access public + */ + function getLink($label, $index = 0) { + $urls = $this->_page->getUrlsByLabel($label); + if (count($urls) == 0) { + return false; + } + if (count($urls) < $index + 1) { + return false; + } + return $urls[$index]; + } + + /** + * Follows a link by label. Will click the first link + * found with this link text by default, or a later + * one if an index is given. The match ignores case and + * white space issues. + * @param string $label Text between the anchor tags. + * @param integer $index Link position counting from zero. + * @return string/boolean Page on success. + * @access public + */ + function clickLink($label, $index = 0) { + $url = $this->getLink($label, $index); + if ($url === false) { + return false; + } + $this->_load($url, new SimpleGetEncoding()); + return $this->getContent(); + } + + /** + * Finds a link by id attribute. + * @param string $id ID attribute value. + * @return string/boolean URL on success. + * @access public + */ + function getLinkById($id) { + return $this->_page->getUrlById($id); + } + + /** + * Follows a link by id attribute. + * @param string $id ID attribute value. + * @return string/boolean Page on success. + * @access public + */ + function clickLinkById($id) { + if (! ($url = $this->getLinkById($id))) { + return false; + } + $this->_load($url, new SimpleGetEncoding()); + return $this->getContent(); + } + + /** + * Clicks a visible text item. Will first try buttons, + * then links and then images. + * @param string $label Visible text or alt text. + * @return string/boolean Raw page or false. + * @access public + */ + function click($label) { + $raw = $this->clickSubmit($label); + if (! $raw) { + $raw = $this->clickLink($label); + } + if (! $raw) { + $raw = $this->clickImage($label); + } + return $raw; + } + + /** + * Tests to see if a click target exists. + * @param string $label Visible text or alt text. + * @return boolean True if target present. + * @access public + */ + function isClickable($label) { + return $this->isSubmit($label) || ($this->getLink($label) !== false) || $this->isImage($label); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/collector.php b/tests/simpletest/collector.php new file mode 100644 index 00000000..5adf1165 --- /dev/null +++ b/tests/simpletest/collector.php @@ -0,0 +1,107 @@ + + * @package SimpleTest + * @subpackage UnitTester + * @version $Id: collector.php,v 1.11 2006/11/21 00:26:55 lastcraft 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. + * @return string Path without trailing slash. + */ + function _removeTrailingSlash($path) { + if (substr($path, -1) == DIRECTORY_SEPARATOR) { + return substr($path, 0, -1); + } elseif (substr($path, -1) == '/') { + return substr($path, 0, -1); + } else { + return $path; + } + } + + /** + * Scans the directory and adds what it can. + * @param object $test Group test with {@link GroupTest::addTestFile()} method. + * @param string $path Directory to scan. + * @see _attemptToAdd() + */ + function collect(&$test, $path) { + $path = $this->_removeTrailingSlash($path); + if ($handle = opendir($path)) { + while (($entry = readdir($handle)) !== false) { + $this->_handle($test, $path . DIRECTORY_SEPARATOR . $entry); + } + closedir($handle); + } + } + + /** + * This method determines what should be done with a given file and adds + * it via {@link GroupTest::addTestFile()} if necessary. + * + * This method should be overriden to provide custom matching criteria, + * such as pattern matching, recursive matching, etc. For an example, see + * {@link SimplePatternCollector::_handle()}. + * + * @param object $test Group test with {@link GroupTest::addTestFile()} method. + * @param string $filename A filename as generated by {@link collect()} + * @see collect() + * @access protected + */ + function _handle(&$test, $file) { + if (! is_dir($file)) { + $test->addTestFile($file); + } + } + } + + /** + * An extension to {@link SimpleCollector} that only adds files matching a + * given pattern. + * + * @package SimpleTest + * @subpackage UnitTester + * @see SimpleCollector + */ + class SimplePatternCollector extends SimpleCollector { + var $_pattern; + + /** + * + * @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/simpletest/compatibility.php b/tests/simpletest/compatibility.php new file mode 100644 index 00000000..ceb8b8ae --- /dev/null +++ b/tests/simpletest/compatibility.php @@ -0,0 +1,173 @@ += 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); + } + if ($first !== $second) { + return false; + } + return true; + } + + /** + * Recursive type test for each element of an array. + * @param mixed $first Test subject. + * @param mixed $second Comparison object. + * @return boolean True if identical. + * @access private + * @static + */ + function _isArrayOfIdenticalTypes($first, $second) { + if (array_keys($first) != array_keys($second)) { + return false; + } + foreach (array_keys($first) as $key) { + $is_identical = SimpleTestCompatibility::_isIdenticalType( + $first[$key], + $second[$key]); + if (! $is_identical) { + return false; + } + } + return true; + } + + /** + * Test for two variables being aliases. + * @param mixed $first Test subject. + * @param mixed $second Comparison object. + * @return boolean True if same. + * @access public + * @static + */ + function isReference(&$first, &$second) { + if (version_compare(phpversion(), '5', '>=') && is_object($first)) { + return ($first === $second); + } + if (is_object($first) && is_object($second)) { + $id = uniqid("test"); + $first->$id = true; + $is_ref = isset($second->$id); + unset($first->$id); + return $is_ref; + } + $temp = $first; + $first = uniqid("test"); + $is_ref = ($first === $second); + $first = $temp; + return $is_ref; + } + + /** + * Test to see if an object is a member of a + * class hiearchy. + * @param object $object Object to test. + * @param string $class Root name of hiearchy. + * @return boolean True if class in hiearchy. + * @access public + * @static + */ + function isA($object, $class) { + if (version_compare(phpversion(), '5') >= 0) { + if (! class_exists($class, false)) { + if (function_exists('interface_exists')) { + if (! interface_exists($class, false)) { + return false; + } + } + } + eval("\$is_a = \$object instanceof $class;"); + return $is_a; + } + if (function_exists('is_a')) { + return is_a($object, $class); + } + return ((strtolower($class) == get_class($object)) + or (is_subclass_of($object, $class))); + } + + /** + * Sets a socket timeout for each chunk. + * @param resource $handle Socket handle. + * @param integer $timeout Limit in seconds. + * @access public + * @static + */ + function setTimeout($handle, $timeout) { + if (function_exists('stream_set_timeout')) { + stream_set_timeout($handle, $timeout, 0); + } elseif (function_exists('socket_set_timeout')) { + socket_set_timeout($handle, $timeout, 0); + } elseif (function_exists('set_socket_timeout')) { + set_socket_timeout($handle, $timeout, 0); + } + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/cookies.php b/tests/simpletest/cookies.php new file mode 100644 index 00000000..b4c076d0 --- /dev/null +++ b/tests/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 { + var $_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/simpletest/detached.php b/tests/simpletest/detached.php new file mode 100644 index 00000000..3f5ff952 --- /dev/null +++ b/tests/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/simpletest/docs/en/authentication_documentation.html b/tests/simpletest/docs/en/authentication_documentation.html new file mode 100644 index 00000000..c90d61e5 --- /dev/null +++ b/tests/simpletest/docs/en/authentication_documentation.html @@ -0,0 +1,336 @@ + + + +SimpleTest documentation for testing log-in and authentication + + + + +

Authentication documentation

+
+ +

+ One of the trickiest, and yet most important, areas + of testing web sites is the security. + Testing these schemes is one of the core goals of + the SimpleTest web tester. +

+ +

+ +

Basic HTTP authentication

+ +

+

+ If you fetch a page protected by basic authentication then + rather than receiving content, you will instead get a 401 + header. + We can illustrate this with this test... +

+class AuthenticationTest extends WebTestCase {
+    function test401Header() {
+        $this->get('http://www.lastcraft.com/protected/');
+        $this->showHeaders();
+    }
+}
+
+ This allows us to see the challenge header... +
+

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.
+
+ We are trying to get away from visual inspection though, and so SimpleTest + allows to make automated assertions against the challenge. + Here is a thorough test of our header... +
+class AuthenticationTest extends WebTestCase {
+    function test401Header() {
+        $this->get('http://www.lastcraft.com/protected/');
+        $this->assertAuthentication('Basic');
+        $this->assertResponse(401);
+        $this->assertRealm('SimpleTest basic authentication');
+    }
+}
+
+ Any one of these tests would normally do on it's own depending + 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. + As soon as the challenge has been issued we can reply with + an authentication response... +
+class AuthenticationTest extends WebTestCase {
+    function testCanAuthenticate() {
+        $this->get('http://www.lastcraft.com/protected/');
+        $this->authenticate('Me', 'Secret');
+        $this->assertTitle(...);
+    }
+}
+
+ The username and password will now be sent with every + subsequent request to that directory and subdirectories. + You will have to authenticate again if you step outside + the authenticated directory, but SimpleTest is smart enough + to merge subdirectories into a common realm. +

+

+ You can shortcut this step further by encoding the log in + details straight into the URL... +

+class AuthenticationTest extends WebTestCase {
+    function testCanReadAuthenticatedPages() {
+        $this->get('http://Me:Secret@www.lastcraft.com/protected/');
+        $this->assertTitle(...);
+    }
+}
+
+ If your username or password has special characters, then you + will have to URL encode them or the request will not be parsed + correctly. + Also this header will not be sent on subsequent requests if + you request a page with a fully qualified URL. + If you navigate with relative URLs though, the authentication + information will be preserved. +

+

+ Only basic authentication is currently supported and this is + only really secure in tandem with HTTPS connections. + This is usually enough to protect test server from prying eyes, + however. + Digest authentication and NTLM authentication may be added + in the future. +

+ +

+ +

Cookies

+ +

+

+ Basic authentication doesn't give enough control over the + user interface for web developers. + More likely this functionality will be coded directly into + the web architecture using cookies and complicated timeouts. +

+

+ Starting with a simple log-in form... +

+<form>
+    Username:
+    <input type="text" name="u" value="" /><br />
+    Password:
+    <input type="password" name="p" value="" /><br />
+    <input type="submit" value="Log in" />
+</form>
+
+ Which looks like... +

+

+

+ Username: + +
+ Password: + +
+ +
+

+

+ Let's suppose that in fetching this page a cookie has been + set with a session ID. + We are not going to fill the form in yet, just test that + we are tracking the user. + Here is the test... +

+class LogInTest extends WebTestCase {
+    function testSessionCookieSetBeforeForm() {
+        $this->get('http://www.my-site.com/login.php');
+        $this->assertCookie('SID');
+    }
+}
+
+ All we are doing is confirming that the cookie is set. + As the value is likely to be rather cryptic it's not + really worth testing this with... +
+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. + We wouldn't want to lose track of this after all. + Here is a possible test for this... +
+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->click('Log in');
+        $this->assertText('Welcome Me');
+        $this->assertCookie('SID', $session);
+    }
+}
+
+ This confirms that the session identifier is maintained + afer log-in. +

+

+ We could even attempt to spoof our own system by setting + arbitrary cookies to gain access... +

+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->assertText('Access denied');
+    }
+}
+
+ Is your site protected from this attack? +

+ +

+ +

Browser sessions

+ +

+

+ If you are testing an authentication system a critical piece + of behaviour is what happens when a user logs back in. + We would like to simulate closing and reopening a browser... +

+class LogInTest extends WebTestCase {
+    ...
+    function testLoseAuthenticationAfterBrowserClose() {
+        $this->get('http://www.my-site.com/login.php');
+        $this->setField('u', 'Me');
+        $this->setField('p', 'Secret');
+        $this->click('Log in');
+        $this->assertText('Welcome Me');
+        
+        $this->restart();
+        $this->get('http://www.my-site.com/restricted.php');
+        $this->assertText('Access denied');
+    }
+}
+
+ The WebTestCase::restart() method will + preserve cookies that have unexpired timeouts, but throw away + those that are temporary or expired. + You can optionally specify the time and date that the restart + happened. +

+

+ Expiring cookies can be a problem. + After all, if you have a cookie that expires after an hour, + you don't want to stall the test for an hour while the + cookie passes it's timeout. +

+

+ To push the cookies over the hour limit you can age them + before you restart the session... +

+class LogInTest extends WebTestCase {
+    ...
+    function testLoseAuthenticationAfterOneHour() {
+        $this->get('http://www.my-site.com/login.php');
+        $this->setField('u', 'Me');
+        $this->setField('p', 'Secret');
+        $this->click('Log in');
+        $this->assertText('Welcome Me');
+        
+        $this->ageCookies(3600);
+        $this->restart();
+        $this->get('http://www.my-site.com/restricted.php');
+        $this->assertText('Access denied');
+    }
+}
+
+ After the restart it will appear that cookies are an + hour older and any that pass their expiry will have + disappeared. +

+ +
+ + + diff --git a/tests/simpletest/docs/en/browser_documentation.html b/tests/simpletest/docs/en/browser_documentation.html new file mode 100644 index 00000000..f6046a9d --- /dev/null +++ b/tests/simpletest/docs/en/browser_documentation.html @@ -0,0 +1,391 @@ + + + +SimpleTest documentation for the scriptable web browser component + + + + +

PHP Scriptable Web Browser

+
+ +

+ SimpleTest's web browser component can be used not just + outside of the WebTestCase class, but also + independently of the SimpleTest framework itself. +

+ +

+ +

The Scriptable Browser

+ +

+

+ You can use the web browser in PHP scripts to confirm + services are up and running, or to extract information + from them at a regular basis. + For example, here is a small script to extract the current number of + open PHP 5 bugs from the PHP web site... +

+<?php
+    require_once('simpletest/browser.php');
+    
+    $browser = &new SimpleBrowser();
+    $browser->get('http://php.net/');
+    $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];
+?>
+
+ There are simpler methods to do this particular example in PHP + of course. + For example you can just use the PHP file() + command against what here is a pretty fixed page. + However, using the web browser for scripts allows authentication, + correct handling of cookies, automatic loading of frames, redirects, + form submission and the ability to examine the page headers. + Such methods are fragile against a site that is constantly + evolving and you would want a more direct way of accessing + data in a permanent set up, but for simple tasks this can provide + a very rapid solution. +

+

+ All of the navigation methods used in the + WebTestCase + are present in the SimpleBrowser class, but + the assertions are replaced with simpler accessors. + Here is a full list of the page navigation methods... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
addHeader($header)Adds a header to every fetch
useProxy($proxy, $username, $password)Use this proxy from now on
head($url, $parameters)Perform a HEAD request
get($url, $parameters)Fetch a page with GET
post($url, $parameters)Fetch a page with POST
clickLink($label)Follows a link by label
isLink($label)See if a link is present by label
clickLinkById($id)Follows a link by attribute
isLinkById($id)See if a link is present by attribut
getUrl()Current URL of page or frame
getTitle()Page title
getContent()Raw page or frame
getContentAsText()HTML removed except for alt text
retry()Repeat the last request
back()Use the browser back button
forward()Use the browser forward button
authenticate($username, $password)Retry page or frame after a 401 response
restart($date)Restarts the browser for a new session
ageCookies($interval)Ages the cookies by the specified time
setCookie($name, $value)Sets an additional cookie
getCookieValue($host, $path, $name)Reads the most specific cookie
getCurrentCookieValue($name)Reads cookie for the current context
+ The methods SimpleBrowser::useProxy() and + SimpleBrowser::addHeader() are special. + Once called they continue to apply to all subsequent fetches. +

+

+ Navigating forms is similar to the + WebTestCase form navigation... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
setField($name, $value)Sets all form fields with that name
setFieldById($id, $value)Sets all form fields with that id
getField($name)Accessor for a form element value
getFieldById($id)Accessor for a form element value
clickSubmit($label)Submits form by button label
clickSubmitByName($name)Submits form by button attribute
clickSubmitById($id)Submits form by button attribute
clickImage($label, $x, $y)Clicks the image by alt text
clickImageByName($name, $x, $y)Clicks the image by attribute
clickImageById($id, $x, $y)Clicks the image by attribute
submitFormById($id)Submits by the form tag attribute
+ At the moment there aren't any methods to list available forms + and fields. + This will probably be added to later versions of SimpleTest. +

+

+ Within a page, individual frames can be selected. + If no selection is made then all the frames are merged together + in one large conceptual page. + The content of the current page will be a concatenation of all of the + frames in the order that they were specified in the "frameset" + tags. + + + + + + + + + + + + + + + + + + +
getFrames()A dump of the current frame structure
getFrameFocus()Current frame label or index
setFrameFocusByIndex($choice)Select a frame numbered from 1
setFrameFocus($name)Select frame by label
clearFrameFocus()Treat all the frames as a single page
+ When focused on a single frame, the content will come from + that frame only. + This includes links to click and forms to submit. +

+ +

+ +

What went wrong?

+ +

+

+ All of this functionality is great when we actually manage to fetch pages, + but that doesn't always happen. + To help figure out what went wrong, the browser has some methods to + aid in debugging... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
setConnectionTimeout($timeout)Close the socket on overrun
getRequest()Raw request header of page or frame
getHeaders()Raw response header of page or frame
getTransportError()Any socket level errors in the last fetch
getResponseCode()HTTP response of page or frame
getMimeType()Mime type of page or frame
getAuthentication()Authentication type in 401 challenge header
getRealm()Authentication realm in 401 challenge header
setMaximumRedirects($max)Number of redirects before page is loaded anyway
setMaximumNestedFrames($max)Protection against recursive framesets
ignoreFrames()Disables frames support
useFrames()Enables frames support
ignoreCookies()Disables sending and receiving of cookies
useCookies()Enables cookie support
+ The methods SimpleBrowser::setConnectionTimeout() + SimpleBrowser::setMaximumRedirects(), + SimpleBrowser::setMaximumNestedFrames(), + 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 + loading, navigate to it using SimpleBrowser::setFrameFocus() + and you can then use SimpleBrowser::getRequest(), etc to + see what happened. +

+ +

+ +

Complex unit tests with multiple browsers

+ +

+

+ Anything that could be done in a + WebTestCase can + now be done in a UnitTestCase. + This means that we can freely mix domain object testing with the + web interface... +

+
+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->click('Register');
+        
+        $authenticator = &new Authenticator();
+        $member = &$authenticator->findByEmail('me@here');
+        $this->assertEqual($member->getPassword(), 'Secret');
+    }
+}
+
+ While this may be a useful temporary expediency, I am not a fan + of this type of testing. + The testing has cut across application layers, make it twice as + likely it will need refactoring when the code changes. +

+

+ A more useful case of where using the browser directly can be helpful + is where the WebTestCase cannot cope. + An example is where two browsers are needed at the same time. +

+

+ For example, say we want to disallow multiple simultaneous + usage of a site with the same username. + This test case will do the job... +

+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->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->click('Enter');
+        $this->assertEqual($second->getTitle(), 'Access Denied');
+    }
+}
+
+ You can also use the SimpleBrowser class + directly when you want to write test cases using a different + test tool than SimpleTest. +

+ +
+ + + diff --git a/tests/simpletest/docs/en/docs.css b/tests/simpletest/docs/en/docs.css new file mode 100644 index 00000000..6ee7160d --- /dev/null +++ b/tests/simpletest/docs/en/docs.css @@ -0,0 +1,121 @@ +body { + padding-left: 3%; + padding-right: 3%; +} +h1, h2, h3 { + font-family: sans-serif; +} +h1 { + text-align: center; +} +pre { + font-family: courier, typewriter, monospace; + font-size: 90%; + border: 1px solid; + border-color: #999966; + background-color: #ffffcc; + padding: 5px; + margin-left: 20px; + margin-right: 40px; +} +.code, .new_code, pre.new_code { + font-family: courier, typewriter, monospace; + font-weight: bold; +} +div.copyright { + font-size: 80%; + color: gray; +} +div.copyright a { + margin-top: 1em; + color: gray; +} +ul.api { + border: 2px outset; + border-color: gray; + background-color: white; + margin: 5px; + margin-left: 5%; + margin-right: 5%; +} +ul.api li { + margin-top: 0.2em; + margin-bottom: 0.2em; + list-style: none; + text-indent: -3em; + padding-left: 1em; +} +div.demo { + border: 4px ridge; + border-color: gray; + padding: 10px; + margin: 5px; + margin-left: 20px; + margin-right: 40px; + background-color: white; +} +div.demo span.fail { + color: red; +} +div.demo span.pass { + color: green; +} +div.demo h1 { + font-size: 12pt; + text-align: left; + font-weight: bold; +} +div.menu { + text-align: center; +} +table { + border: 2px outset; + border-color: gray; + background-color: white; + margin: 5px; + margin-left: 5%; + margin-right: 5%; +} +td { + font-size: 90%; +} +.shell { + color: white; +} +pre.shell { + border: 4px ridge; + border-color: gray; + padding: 10px; + margin: 5px; + margin-left: 20px; + margin-right: 40px; + background-color: #000100; + color: #99ff99; + font-size: 90%; +} +pre.file { + color: black; + border: 1px solid; + border-color: black; + padding: 10px; + margin: 5px; + margin-left: 20px; + margin-right: 40px; + background-color: white; + font-size: 90%; +} +form.demo { + background-color: lightgray; + border: 4px outset; + border-color: lightgray; + padding: 10px; + margin-right: 40%; +} +dl, dd { + margin: 10px; + margin-left: 30px; +} +em { + font-weight: bold; + font-family: courier, typewriter, monospace; +} diff --git a/tests/simpletest/docs/en/expectation_documentation.html b/tests/simpletest/docs/en/expectation_documentation.html new file mode 100644 index 00000000..bd189b94 --- /dev/null +++ b/tests/simpletest/docs/en/expectation_documentation.html @@ -0,0 +1,346 @@ + + + + + Extending the SimpleTest unit tester with additional expectation classes + + + + + +

Expectation documentation

+
+

+ +

More control over mock objects

+ +

+

+ The default behaviour of the + mock objects + in + SimpleTest + is either an identical match on the argument or to allow any argument at all. + For almost all tests this is sufficient. + Sometimes, though, you want to weaken a test case. +

+

+ One place where a test can be too tightly coupled is with + text matching. + Suppose we have a component that outputs a helpful error + message when something goes wrong. + You want to test that the correct error was sent, but the actual + text may be rather long. + If you test for the text exactly, then every time the exact wording + of the message changes, you will have to go back and edit the test suite. +

+

+ For example, suppose we have a news service that has failed + to connect to its remote source. +

+class NewsService {
+    ...
+    function publish(&$writer) {
+        if (! $this->isConnected()) {
+            $writer->write('Cannot connect to news service "' .
+                    $this->_name . '" at this time. ' .
+                    'Please try again later.');
+        }
+        ...
+    }
+}
+
+ Here it is sending its content to a + Writer class. + We could test this behaviour with a + MockWriter like so... +
+class TestOfNewsService extends UnitTestCase {
+    ...
+    function testConnectionFailure() {<strong>
+        $writer = &new MockWriter();
+        $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);
+    }
+}
+
+ This is a good example of a brittle test. + If we decide to add additional instructions, such as + suggesting an alternative news source, we will break + our tests even though no underlying functionality + has been altered. +

+

+ To get around this, we would like to do a regular expression + test rather than an exact match. + We can actually do this with... +

+class TestOfNewsService extends UnitTestCase {
+    ...
+    function testConnectionFailure() {
+        $writer = &new MockWriter();
+        $writer->expectOnce(
+                'write',
+                array(new PatternExpectation('/cannot connect/i')));
+        
+        $service = &new NewsService('BBC News');
+        $service->publish($writer);
+    }
+}
+
+ Instead of passing in the expected parameter to the + MockWriter we pass an + expectation class called + WantedPatternExpectation. + The mock object is smart enough to recognise this as special + and to treat it differently. + Rather than simply comparing the incoming argument to this + object, it uses the expectation object itself to + perform the test. +

+

+ The WantedPatternExpectation takes + the regular expression to match in its constructor. + Whenever a comparison is made by the MockWriter + against this expectation class, it will do a + preg_match() with this pattern. + With our test case above, as long as "cannot connect" + appears in the text of the string, the mock will issue a pass + to the unit tester. + The rest of the text does not matter. +

+

+ The possible expectation classes are... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EqualExpectationAn equality, rather than the stronger identity comparison
NotEqualExpectationAn inequality comparison
IndenticalExpectationThe default mock object check which must match exactly
NotIndenticalExpectationInverts the mock object logic
PatternExpectationUses a Perl Regex to match a string
NoPatternExpectationPasses only if failing a Perl Regex
IsAExpectationChecks the type or class name only
NotAExpectationOpposite of the IsAExpectation
MethodExistsExpectationChecks a method is available on an object
+ Most take the expected value in the constructor. + The exceptions are the pattern matchers, which take a regular expression, + and the IsAExpectation and NotAExpectation which takes a type + or class name as a string. +

+ +

+ +

Using expectations to control stubs

+ +

+

+ The expectation classes can be used not just for sending assertions + 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 mock to simulate a successful login + only if it receives a valid session object. + We can do this as follows... +

+Mock::generate('Authorisation');
+
+$authorisation = new MockAuthorisation();
+$authorisation->setReturnValue(
+        'isAllowed',
+        true,
+        array(new IsAExpectation('Session', 'Must be a session')));
+$authorisation->setReturnValue('isAllowed', false);
+
+ 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. + We have also added a second parameter as a message. + This will be displayed as part of the mock object + failure message if this expectation is the cause of + a failure. +

+

+ This kind of sophistication is rarely useful, but is included for + completeness. +

+ +

+ +

Creating your own expectations

+ +

+

+ The expectation classes have a very simple structure. + So simple that it is easy to create your own versions for + commonly used test logic. +

+

+ As an example here is the creation of a class to test for + valid IP addresses. + In order to work correctly with the stubs and mocks the new + expectation class should extend + SimpleExpectation... +

+class ValidIp extends SimpleExpectation {
+    
+    function test($ip) {
+        return (ip2long($ip) != -1);
+    }
+    
+    function testMessage($ip) {
+        return "Address [$ip] should be a valid IP address";
+    }
+}
+
+ There are only two methods to implement. + The test() method should + evaluate to true if the expectation is to pass, and + false otherwise. + The testMessage() method + should simply return some helpful text explaining the test + that was carried out. +

+

+ This class can now be used in place of the earlier expectation + classes. +

+ +

+ +

Under the bonnet of the unit tester

+ +

+

+ The SimpleTest unit testing framework + also uses the expectation classes internally for the + UnitTestCase class. + We can also take advantage of these mechanisms to reuse our + homebrew expectation classes within the test suites directly. +

+

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

+class TestOfNetworking extends UnitTestCase {
+    ...
+    function testGetValidIp() {
+        $server = &new Server();
+        $this->assert(
+                new ValidIp(),
+                $server->getIp(),
+                'Server IP address->%s');
+    }
+}
+
+ This is a little untidy compared with our usual + assert...() syntax. +

+

+ For such a simple case we would normally create a + separate assertion method on our test case rather + than bother using the expectation class. + If we pretend that our expectation is a little more + complicated for a moment, so that we want to reuse it, + we get... +

+class TestOfNetworking extends UnitTestCase {
+    ...
+    function assertValidIp($ip, $message = '%s') {
+        $this->assert(new ValidIp(), $ip, $message);
+    }
+    
+    function testGetValidIp() {
+        $server = &new Server();
+        $this->assertValidIp(
+                $server->getIp(),
+                'Server IP address->%s');
+    }
+}
+
+ It is unlikely we would ever need this degree of control + over the testing machinery. + It is rare to need the expectations for more than pattern + matching. + Also, complex expectation classes could make the tests + harder to read and debug. + These mechanisms are really of most use to authors of systems + that will extend the test framework to create their own tool set. +

+ +
+ + + diff --git a/tests/simpletest/docs/en/form_testing_documentation.html b/tests/simpletest/docs/en/form_testing_documentation.html new file mode 100644 index 00000000..50b634c0 --- /dev/null +++ b/tests/simpletest/docs/en/form_testing_documentation.html @@ -0,0 +1,276 @@ + + + +Simple Test documentation for testing HTML forms + + + + +

Form testing documentation

+
+

+ +

Submitting a simple form

+ +

+

+ When a page is fetched by the WebTestCase + using get() or + post() the page content is + automatically parsed. + This results in any form controls that are inside <form> tags + being available from within the test case. + For example, if we have this snippet of HTML... +

+<form>
+    <input type="text" name="a" value="A default" />
+    <input type="submit" value="Go" />
+</form>
+
+ Which looks like this... +

+

+

+ + +
+

+

+ We can navigate to this code, via the + LastCraft + site, with the following test... +

+class SimpleFormTests extends WebTestCase {
+    
+    function testDefaultValue() {
+        $this->get('http://www.lastcraft.com/form_testing_documentation.php');
+        $this->assertField('a', 'A default');
+    }
+}
+
+ Immediately after loading the page all of the HTML controls are set at + their default values just as they would appear in the web browser. + The assertion tests that a HTML widget exists in the page with the + name "a" and that it is currently set to the value + "A default". + 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 + the value of the text field and only then submit it... +

+class SimpleFormTests extends WebTestCase {
+
+    function testDefaultValue() {
+        $this->get('http://www.my-site.com/');
+        $this->assertField('a', 'A default');
+        $this->setField('a', 'New value');
+        $this->click('Go');
+    }
+}
+
+ Because we didn't specify a method attribute on the form tag, and + didn't specify an action either, the test case will follow + the usual browser behaviour of submitting the form data as a GET + request back to the same location. + SimpleTest tries to emulate typical browser behaviour as much as possible, + rather than attempting to catch missing attributes on tags. + This is because the target of the testing framework is the PHP application + logic, not syntax or other errors in the HTML code. + For HTML errors, other tools such as + HTMLTidy should be used. +

+

+ If a field is not present in any form, or if an option is unavailable, + then WebTestCase::setField() will return + false. + For example, suppose we wish to verify that a "Superuser" + option is not present in this form... +

+<strong>Select type of user to add:</strong>
+<select name="type">
+    <option>Subscriber</option>
+    <option>Author</option>
+    <option>Administrator</option>
+</select>
+
+ Which looks like... +

+

+

+ Select type of user to add: + +
+

+

+ The following test will confirm it... +

+class SimpleFormTests extends WebTestCase {
+    ...
+    function testNoSuperuserChoiceAvailable() {
+        $this->get('http://www.lastcraft.com/form_testing_documentation.php');
+        $this->assertFalse($this->setField('type', 'Superuser'));
+    }
+}
+
+ The selection will not be changed on a failure to set + a widget value. +

+

+ Here is the full list of widgets currently supported... +

    +
  • Text fields, including hidden and password fields.
  • +
  • Submit buttons including the button tag, although not yet reset buttons
  • +
  • Text area. This includes text wrapping behaviour.
  • +
  • Checkboxes, including multiple checkboxes in the same form.
  • +
  • Drop down selections, including multiple selects.
  • +
  • Radio buttons.
  • +
  • Images.
  • +
+

+

+ Although most standard HTML widgets are catered for by SimpleTest's + built in parser, it is unlikely that JavaScript will be implemented + anytime soon. +

+ +

+ +

Fields with multiple values

+ +

+

+ SimpleTest can cope with two types of multivalue controls: Multiple + selection drop downs, and multiple checkboxes with the same name + within a form. + The multivalue nature of these means that setting and testing + are slightly different. + Using checkboxes as an example... +

+<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>
+
+ Which renders as... +

+

+

+ Create privileges allowed: + +
+ Retrieve privileges allowed: + +
+ Update privileges allowed: + +
+ Destroy privileges allowed: + +
+ +
+

+

+ If we wish to disable all but the retrieval privileges and + submit this information we can do it like this... +

+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->click('Enable Privileges');
+    }
+}
+
+ Instead of setting the field to a single value, we give it a list + of values. + We do the same when testing expected values. + We can then write other test code to confirm the effect of this, perhaps + by logging in as that user and attempting an update. +

+

+ +

Raw posting

+ +

+

+ If you want to test a form handler, but have not yet written + or do not have access to the form itself, you can create a + form submission by hand. +

+class SimpleFormTests extends WebTestCase {
+    ...    
+    function testAttemptedHack() {
+        $this->post(
+                'http://www.my-site.com/add_user.php',
+                array('type' => 'superuser'));
+        $this->assertNoText('user created');
+    }
+}
+
+ By adding data to the WebTestCase::post() + method, we are attempting to fetch the page as a form submission. +

+ +
+ + + diff --git a/tests/simpletest/docs/en/group_test_documentation.html b/tests/simpletest/docs/en/group_test_documentation.html new file mode 100644 index 00000000..1e14d31e --- /dev/null +++ b/tests/simpletest/docs/en/group_test_documentation.html @@ -0,0 +1,354 @@ + + + +SimpleTest for PHP group test documentation + + + + +

Group Test documentation

+
+

+ +

Grouping tests

+ +

+

+ To run test cases as part of a group the test cases should really + be placed in files without the runner code... +

+<?php
+    require_once('../classes/io.php');
+
+    class FileTester extends UnitTestCase {
+        ...
+    }
+
+    class SocketTester extends UnitTestCase {
+        ...
+    }
+?>
+
+ As many cases as needed can appear in a single file. + They should include any code they need, such as the library + being tested, but none of the simple test libraries. +

+

+ If you have extended any test cases, you can include them + as well. +

+<?php
+    require_once('../classes/io.php');
+
+    class MyFileTestCase extends UnitTestCase {
+        ...
+    }
+    SimpleTest::ignore('MyFileTestCase');
+
+    class FileTester extends MyFileTestCase {
+        ...
+    }
+
+    class SocketTester extends UnitTestCase {
+        ...
+    }
+?>
+
+ The FileTester class does + not contain any actual tests, but is a base class for other + test cases. + For this reason we use the + SimpleTestOptions::ignore() directive + to tell the upcoming group test to ignore it. + This directive can appear anywhere in the file and works + when a whole file of test cases is loaded (see below). + We will call this sample file_test.php. +

+

+ Next we create a group test file, called say group_test.php. + You will think of a better name I am sure. + We will add the test file using a safe method... +

+<?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());
+?>
+
+ This instantiates the test case before the test suite is + run. + This could get a little expensive with a large number of test + cases, so another method is provided that will only + instantiate the class when it is needed... +
+<?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());
+?>
+
+ The problem with this method is that for every test case + that we add we will have + to require_once() the test code + file and manually instantiate each and every test case. + We can save a lot of typing with... +
+<?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;
+
+ What happens here is that the GroupTest + class has done the require_once() + for us. + It then checks to see if any new test case classes + have been created by the new file and automatically adds + them to the group test. + Now all we have to do is add each new file. +

+

+ There are two things that could go wrong and which require care... +

    +
  1. + The file could already have been parsed by PHP and so no + new classes will have been added. You should make + sure that the test cases are only included in this file + and no others. +
  2. +
  3. + New test case extension classes that get included will be + placed in the group test and run also. + You will need to add a SimpleTestOptions::ignore() + directive for these classes or make sure that they are included + before the GroupTest::addTestFile() + line. +
  4. +
+

+ +

+ +

Higher groupings

+ +

+

+ The above method places all of the test cases into one large group. + For larger projects though this may not be flexible enough; you + may want to group the tests in all sorts of ways. +

+

+ To get a more flexible group test we can subclass + GroupTest and then instantiate it as needed... +

+<?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');
+        }
+    }
+?>
+
+ This effectively names the test in the constructor and then + adds our test cases and a single group below. + Of course we can add more than one group at this point. + We can now invoke the tests from a separate runner file... +
+<?php
+    require_once('file_group_test.php');
+    
+    $test = &new FileGroupTest();
+    $test->run(new HtmlReporter());
+?>
+
+ ...or we can group them into even larger group tests... +
+<?php
+    require_once('file_group_test.php');
+    
+    $test = &new BigGroupTest('Big group');
+    $test->addTestCase(new FileGroupTest());
+    $test->addTestCase(...);
+    $test->run(new HtmlReporter());
+?>
+
+ If we still wish to run the original group test and we + don't want all of these little runner files, we can + put the test runner code around guard bars when we create + each group. +
+<?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());
+    }
+?>
+
+ This approach requires the guard to be set when including + the group test file, but this is still less hassle than + lots of separate runner files. + You include the same guard on the top level tests to make sure + that run() will run once only + from the top level script that has been invoked. +
+<?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());
+?>
+
+ As with the normal test cases, a GroupTest can + be loaded with the GroupTest::addTestFile() method. +
+<?php
+    define('RUNNER', true);
+
+    $test = &new BigGroupTest('Big group');
+    $test->addTestFile('file_group_test.php');
+    $test->addTestFile(...);
+    $test->run(new HtmlReporter());
+?>
+
+

+ +

+ +

Integrating legacy test cases

+ +

+

+ If you already have unit tests for your code or are extending external + classes that have tests, it is unlikely that all of the test cases + are in SimpleTest format. + Fortunately it is possible to incorporate test cases from other + unit testers directly into SimpleTest group tests. +

+

+ Say we have the following + PhpUnit + test case in the file config_test.php... +

+class ConfigFileTest extends TestCase {
+    function ConfigFileTest() {
+        $this->TestCase('Config file test');
+    }
+    
+    function testContents() {
+        $config = new ConfigFile('test.conf');
+        $this->assertRegexp('/me/', $config->getValue('username'));
+    }
+}
+
+ The group test can recognise this as long as we include + the appropriate adapter class before we add the test + file... +
+<?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());
+?>
+
+ There are only two adapters, the other is for the + PEAR + 1.0 unit tester... +
+<?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());
+?>
+
+ The PEAR test cases can be freely mixed with SimpleTest + ones even in the same test file, + but you cannot use SimpleTest assertions in the legacy + test case versions. + This is done as a check that you are not accidently making + your test cases completely dependent on SimpleTest. + You may want to do a PEAR release of your library for example + which would mean shipping it with valid PEAR::PhpUnit test + cases. +

+ +
+ + + diff --git a/tests/simpletest/docs/en/index.html b/tests/simpletest/docs/en/index.html new file mode 100644 index 00000000..c7183c49 --- /dev/null +++ b/tests/simpletest/docs/en/index.html @@ -0,0 +1,461 @@ + + + + + Download the Simple Test testing framework - + Unit tests and mock objects for PHP + + + + + +

Simple Test for PHP

+
+ + +

+ The following assumes that you are familiar with the concept + of unit testing as well as the PHP web development language. + It is a guide for the impatient new user of + SimpleTest. + For fuller documentation, especially if you are new + to unit testing see the ongoing + documentation, and for + example test cases see the + unit testing tutorial. +

+ +

+ +

Using the tester quickly

+ +

+

+ Amongst software testing tools, a unit tester is the one + closest to the developer. + In the context of agile development the test code sits right + next to the source code as both are written simultaneously. + In this context SimpleTest aims to be a complete PHP developer + test solution and is called "Simple" because it + should be easy to use and extend. + It wasn't a good choice of name really. + It includes all of the typical functions you would expect from + JUnit and the + PHPUnit + ports, but also adds + mock objects. + It has some JWebUnit + functionality as well. + This includes web page navigation, cookie testing and form submission. +

+

+ The quickest way to demonstrate is with an example. +

+

+ Let us suppose we are testing a simple file logging class called + Log in classes/log.php. + We start by creating a test script which we will call + tests/log_test.php and populate it as follows... +

+<?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 + takes the file name to write to in the constructor and we have + a temporary folder in which to place this file... +

+<?php
+require_once('simpletest/unit_tester.php');
+require_once('simpletest/reporter.php');
+require_once('../classes/log.php');
+
+class TestOfLogging extends UnitTestCase {
+    
+    function testCreatingNewFile() {
+        @unlink('/temp/test.log');
+        $log = new Log('/temp/test.log');
+        $this->assertFalse(file_exists('/temp/test.log'));
+        $log->message('Should write this to a file');
+        $this->assertTrue(file_exists('/temp/test.log'));
+    }
+}
+?>
+
+ When a test case runs it will search for any method that + starts with the string test + and execute that method. + We would normally have more than one test method of course. + Assertions within the test methods trigger messages to the + test framework which displays the result immediately. + This immediate response is important, not just in the event + of the code causing a crash, but also so that + print statements can display + their content right next to the test case concerned. +

+

+ To see these results we have to actually run the tests. + If this is the only test case we wish to run we can achieve + it with... +

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

+

+ On failure the display looks like this... +

+

testoflogging

+ Fail: testcreatingnewfile->True assertion failed.
+
1/1 test cases complete. + 1 passes and 1 fails.
+
+ ...and if it passes like this... +
+

testoflogging

+
1/1 test cases complete. + 2 passes and 0 fails.
+
+ And if you get this... +
+ Fatal error: Failed opening required '../classes/log.php' (include_path='') in /home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php on line 7 +
+ it means you're missing the classes/Log.php file that could look like... +
+<?php
+class Log {
+    
+        function Log($file_path) {
+        }
+
+		function message() {
+		}
+}
+?>;
+
+

+ +

+ +

Building group tests

+ +

+

+ It is unlikely in a real application that we will only ever run + one test case. + This means that we need a way of grouping cases into a test + script that can, if need be, run every test in the application. +

+

+ Our first step is to strip the includes and to undo our + previous hack... +

+<?php
+require_once('../classes/log.php');
+
+class TestOfLogging extends UnitTestCase {
+    
+    function testCreatingNewFile() {
+        @unlink('/temp/test.log');
+        $log = new Log('/temp/test.log');
+        $this->assertFalse(file_exists('/temp/test.log'));
+        $log->message('Should write this to a file');
+        $this->assertTrue(file_exists('/temp/test.log'));
+    }
+}
+?>
+
+ Next we create a new file called tests/all_tests.php + and insert the following code... +
+<?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());
+?>
+
+ The method GroupTest::addTestFile() + will include the test case file and read any new classes created + that are descended from SimpleTestCase, of which + UnitTestCase is one example. + Just the class names are stored for now, so that the test runner + can instantiate the class when it works its way + through your test suite. +

+

+ For this to work properly the test case file should not blindly include + any other test case extensions that do not actually run tests. + This could result in extra test cases being counted during the test + run. + Hardly a major problem, but to avoid this inconvenience simply add + a SimpleTestOptions::ignore() directive + somewhere in the test case file. + Also the test case file should not have been included + elsewhere or no cases will be added to this group test. + This would be a more serious error as if the test case classes are + already loaded by PHP the GroupTest::addTestFile() + method will not detect them. +

+

+ To display the results it is necessary only to invoke + tests/all_tests.php from the web server. +

+ +

+ +

Using mock objects

+ +

+

+ Let's move further into the future. +

+

+ Assume that our logging class is tested and completed. + Assume also that we are testing another class that is + required to write log messages, say a + SessionPool. + We want to test a method that will probably end up looking + like this... +

+
+class SessionPool {
+    ...
+    function logIn($username) {
+        ...
+        $this->_log->message("User $username logged in.");
+        ...
+    }
+    ...
+}
+
+
+ In the spirit of reuse we are using our + Log class. + A conventional test case might look like this... +
+
+<?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");
+    }
+}
+?>
+
+ This test case design is not all bad, but it could be improved. + We are spending time fiddling with log files which are + not part of our test. Worse, we have created close ties + with the Log class and + this test. + What if we don't use files any more, but use ths + syslog library instead? + Did you notice the extra carriage return in the message? + Was that added by the logger? + What if it also added a time stamp or other data? +

+

+ The only part that we really want to test is that a particular + message was sent to the logger. + We reduce coupling if we can pass in a fake logging class + that simply records the message calls for testing, but + takes no action. + It would have to look exactly like our original though. +

+

+ If the fake object doesn't write to a file then we save on deleting + the file before and after each test. We could save even more + test code if the fake object would kindly run the assertion for us. +

+

+ Too good to be true? + Luckily we can create such an object easily... +
+<?php
+require_once('../classes/log.php');
+require_once('../classes/session_pool.php');
+Mock::generate('Log');
+
+class TestOfSessionLogging extends UnitTestCase {
+    
+    function testLogInIsLogged() {
+        $log = &new MockLog();
+        $log->expectOnce('message', array('User fred logged in.'));
+        $session_pool = &new SessionPool($log);
+        $session_pool->logIn('fred');
+    }
+}
+?>
+
+ 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 + resulting pass or fail event to the test display. + 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 + selected according to the incoming arguments, sequences of + parameter expectations and limits on the number of times + a method is to be invoked. +

+

+ For this test to run the mock objects library must have been + included in the test suite, say in all_tests.php. +

+ +

+ +

Web page testing

+ +

+

+ One of the requirements of web sites is that they produce web + pages. + If you are building a project top-down and you want to fully + integrate testing along the way then you will want a way of + automatically navigating a site and examining output for + correctness. + This is the job of a web tester. +

+

+ The web testing in SimpleTest is fairly primitive, there is + no JavaScript for example. + To give an idea here is a trivial example where a home + page is fetched, from which we navigate to an "about" + page and then test some client determined content. +

+<?php
+require_once('simpletest/web_tester.php');
+require_once('simpletest/reporter.php');
+
+class TestOfAbout extends WebTestCase {
+    
+    function setUp() {
+        $this->get('http://test-server/index.php');
+        $this->click('About');
+    }
+    
+    function testSearchEngineOptimisations() {
+        $this->assertTitle('A long title about us for search engines');
+        $this->assertPattern('/a popular keyphrase/i');
+    }
+}
+$test = &new TestOfAbout();
+$test->run(new HtmlReporter());
+?>
+
+ With this code as an acceptance test you can ensure that + the content always meets the specifications of both the + developers and the other project stakeholders. +

+

+ SourceForge.net Logo +

+ +
+ + + diff --git a/tests/simpletest/docs/en/mock_objects_documentation.html b/tests/simpletest/docs/en/mock_objects_documentation.html new file mode 100644 index 00000000..eb32c619 --- /dev/null +++ b/tests/simpletest/docs/en/mock_objects_documentation.html @@ -0,0 +1,727 @@ + + + +SimpleTest for PHP mock objects documentation + + + + +

Mock objects documentation

+
+

+ +

What are mock objects?

+ +

+

+ Mock objects have two roles during a test case: actor and critic. +

+

+ The actor behaviour is to simulate objects that are difficult to + set up or time consuming to set up for a test. + The classic example is a database connection. + Setting up a test database at the start of each test would slow + testing to a crawl and would require the installation of the + database engine and test data on the test machine. + If we can simulate the connection and return data of our + choosing we not only win on the pragmatics of testing, but can + also feed our code spurious data to see how it responds. + We can simulate databases being down or other extremes + without having to create a broken database for real. + In other words, we get greater control of the test environment. +

+

+ If mock objects only behaved as actors they would simply be + known as server stubs. + 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 + return values on demand) they are also sensitive to the + messages sent to them (via expectations). + By setting expected parameters for a method call they act + as a guard that the calls upon them are made correctly. + If expectations are not met they save us the effort of + writing a failed test assertion by performing that duty on our + behalf. +

+

+ In the case of an imaginary database connection they can + test that the query, say SQL, was correctly formed by + the object that is using the connection. + Set them up with fairly tight expectations and you will + hardly need manual assertions at all. +

+ +

+ +

Creating mock objects

+ +

+

+ In the same way that we create server stubs, all we need is an + existing class, say a database connection that looks like this... +

+class DatabaseConnection {
+    function DatabaseConnection() {
+    }
+    
+    function query() {
+    }
+    
+    function selectQuery() {
+    }
+}
+
+ The class does not need to have been implemented yet. + To create a mock version of the class we need to include the + mock object library and run the generator... +
+require_once('simpletest/unit_tester.php');
+require_once('simpletest/mock_objects.php');
+require_once('database_connection.php');
+
+Mock::generate('DatabaseConnection');
+
+ This generates a clone class called + MockDatabaseConnection. + We can now create instances of the new class within + our test case... +
+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();
+    }
+}
+
+ Unlike the generated stubs the mock constructor needs a reference + to the test case so that it can dispatch passes and failures while + checking its expectations. + This means that mock objects can only be used within test cases. + Despite this their extra power means that stubs are hardly ever used + if mocks are available. +

+

+ +

Mocks as actors

+ +

+

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

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

+

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

+Mock::generate('DatabaseConnection', 'MyMockDatabaseConnection', array('setOptions'));
+
+ Here the mock will behave as if the setOptions() + existed in the original class. + This is handy if a class has used the PHP overload() + mechanism to add dynamic methods. + You can create a special mock to simulate this situation. +

+

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

+class Iterator {
+    function Iterator() {
+    }
+    
+    function next() {
+    }
+}
+
+ This is about the simplest iterator you could have. + Assuming that this iterator only returns text until it + reaches the end, when it returns false, we can simulate it + with... +
+Mock::generate('Iterator');
+
+class IteratorTest extends UnitTestCase() {
+    
+    function testASequence() {
+        $iterator = &new MockIterator();
+        $iterator->setReturnValue('next', false);
+        $iterator->setReturnValueAt(0, 'next', 'First string');
+        $iterator->setReturnValueAt(1, 'next', 'Second string');
+        ...
+    }
+}
+
+ When next() is called on the + mock iterator it will first return "First string", + on the second call "Second string" will be returned + and on any other call false will + be returned. + The sequenced return values take precedence over the constant + return value. + The constant one is a kind of default if you like. +

+

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

+class Configuration {
+    function Configuration() {
+    }
+    
+    function getValue($key) {
+    }
+}
+
+ This is a classic situation for using mock objects as + actual configuration will vary from machine to machine, + hardly helping the reliability of our tests if we use it + directly. + The problem though is that all the data comes through the + getValue() method and yet + we want different results for different keys. + Luckily the mocks have a filter system... +
+$config = &new MockConfiguration();
+$config->setReturnValue('getValue', 'primary', array('db_host'));
+$config->setReturnValue('getValue', 'admin', array('db_user'));
+$config->setReturnValue('getValue', 'secret', array('db_password'));
+
+ The extra parameter is a list of arguments to attempt + to match. + In this case we are trying to match only one argument which + is the look up key. + Now when the mock object has the + getValue() method invoked + like this... +
+$config->getValue('db_user')
+
+ ...it will return "admin". + It finds this by attempting to match the calling arguments + to its list of returns one after another until + a complete match is found. +

+

+ 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. + The PHP4 copy semantics force us to use a different method + for this. + You might be simulating a container for example... +

+class Thing {
+}
+
+class Vector {
+    function Vector() {
+    }
+    
+    function get($index) {
+    }
+}
+
+ In this case you can set a reference into the mock's + return list... +
+$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. +

+ +

+ +

Mocks as critics

+ +

+

+ Although the server stubs approach insulates your tests from + real world disruption, it is only half the benefit. + You can have the class under test receiving the required + messages, but is your new class sending correct ones? + Testing this can get messy without a mock objects library. +

+

+ By way of example, suppose we have a + SessionPool class that we + want to add logging to. + Rather than grow the original class into something more + complicated, we want to add this behaviour with a decorator (GOF). + The SessionPool code currently looks + like this... +

+class SessionPool {
+    function SessionPool() {
+        ...
+    }
+    
+    function &findSession($cookie) {
+        ...
+    }
+    ...
+}
+
+class Session {
+    ...
+}
+</php>
+                While our logging code looks like this...
+<php>
+class Log {
+    function Log() {
+        ...
+    }
+    
+    function message() {
+        ...
+    }
+}
+
+class LoggingSessionPool {
+    function LoggingSessionPool(&$session_pool, &$log) {
+        ...
+    }
+    
+    function &findSession(\$cookie) {
+        ...
+    }
+    ...
+}
+
+ Out of all of this, the only class we want to test here + is the LoggingSessionPool. + In particular we would like to check that the + findSession() method is + called with the correct session ID in the cookie and that + it sent the message "Starting session $cookie" + to the logger. +

+

+ Despite the fact that we are testing only a few lines of + production code, here is what we would have to do in a + conventional test case: +

    +
  1. Create a log object.
  2. +
  3. Set a directory to place the log file.
  4. +
  5. Set the directory permissions so we can write the log.
  6. +
  7. Create a SessionPool object.
  8. +
  9. Hand start a session, which probably does lot's of things.
  10. +
  11. Invoke findSession().
  12. +
  13. Read the new Session ID (hope there is an accessor!).
  14. +
  15. Raise a test assertion to confirm that the ID matches the cookie.
  16. +
  17. Read the last line of the log file.
  18. +
  19. Pattern match out the extra logging timestamps, etc.
  20. +
  21. Assert that the session message is contained in the text.
  22. +
+ It is hardly surprising that developers hate writing tests + when they are this much drudgery. + To make things worse, every time the logging format changes or + the method of creating new sessions changes, we have to rewrite + parts of this test even though this test does not officially + test those parts of the system. + We are creating headaches for the writers of these other classes. +

+

+ Instead, here is the complete test method using mock object magic... +

+Mock::generate('Session');
+Mock::generate('SessionPool');
+Mock::generate('Log');
+
+class LoggingSessionPoolTest extends UnitTestCase {
+    ...
+    function testFindSessionLogging() {
+        $session = &new MockSession();
+        $pool = &new MockSessionPool();
+        $pool->setReturnReference('findSession', $session);
+        $pool->expectOnce('findSession', array('abc'));
+        
+        $log = &new MockLog();
+        $log->expectOnce('message', array('Starting session abc'));
+        
+        $logging_pool = &new LoggingSessionPool($pool, $log);
+        $this->assertReference($logging_pool->findSession('abc'), $session);
+    }
+}
+
+ We start by creating a dummy session. + We don't have to be too fussy about this as the check + for which session we want is done elsewhere. + We only need to check that it was the same one that came + from the session pool. +

+

+ findSession() is a factory + method the simulation of which is described above. + The point of departure comes with the first + expectOnce() call. + This line states that whenever + findSession() is invoked on the + mock, it will test the incoming arguments. + If it receives the single argument of a string "abc" + then a test pass is sent to the unit tester, otherwise a fail is + generated. + This was the part where we checked that the right session was asked for. + The argument list follows the same format as the one for setting + return values. + You can have wildcards and sequences and the order of + evaluation is the same. +

+

+ We use the same pattern to set up the mock logger. + We tell it that it should have + message() invoked + once only with the argument "Starting session abc". + By testing the calling arguments, rather than the logger output, + we insulate the test from any display changes in the logger. +

+

+ We start to run our tests when we create the new + LoggingSessionPool and feed + it our preset mock objects. + Everything is now under our control. +

+

+ This is still quite a bit of test code, but the code is very + strict. + If it still seems rather daunting there is a lot less of it + than if we tried this without mocks and this particular test, + interactions rather than output, is always more work to set + up. + More often you will be testing more complex situations without + needing this level or precision. + Also some of this can be refactored into a test case + setUp() method. +

+

+ Here is the full list of expectations you can set on a mock object + in SimpleTest... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExpectationNeeds tally()
expect($method, $args)No
expectAt($timing, $method, $args)No
expectCallCount($method, $count)Yes
expectMaximumCallCount($method, $count)No
expectMinimumCallCount($method, $count)Yes
expectNever($method)No
expectOnce($method, $args)Yes
expectAtLeastOnce($method, $args)Yes
+ Where the parameters are... +

+
$method
+
The method name, as a string, to apply the condition to.
+
$args
+
+ The arguments as a list. Wildcards can be included in the same + manner as for setReturn(). + This argument is optional for expectOnce() + and expectAtLeastOnce(). +
+
$timing
+
+ The only point in time to test the condition. + The first call starts at zero. +
+
$count
+
The number of calls expected.
+
+ The method expectMaximumCallCount() + is slightly different in that it will only ever generate a failure. + It is silent if the limit is never reached. +

+

+ Like the assertions within test cases, all of the expectations + can take a message override as an extra parameter. + Also the original failure message can be embedded in the output + as "%s". +

+ +

+ +

Other approaches

+ +

+

+ There are three approaches to creating mocks including the one + that SimpleTest employs. + Coding them by hand using a base class, generating them to + a file and dynamically generating them on the fly. +

+

+ Mock objects generated with SimpleTest + are dynamic. + They are created at run time in memory, using + eval(), rather than written + out to a file. + This makes the mocks easy to create, a one liner, + especially compared with hand + crafting them in a parallel class hierarchy. + The problem is that the behaviour is usually set up in the tests + themselves. + If the original objects change the mock versions + that the tests rely on can get out of sync. + This can happen with the parallel hierarchy approach as well, + but is far more quickly detected. +

+

+ The solution, of course, is to add some real integration + tests. + You don't need very many and the convenience gained + from the mocks more than outweighs the small amount of + extra testing. + You cannot trust code that was only tested with mocks. +

+

+ If you are still determined to build static libraries of mocks + because you want to simulate very specific behaviour, you can + achieve the same effect using the SimpleTest class generator. + In your library file, say mocks/connection.php for a + database connection, create a mock and inherit to override + special methods or add presets... +

+<?php
+    require_once('simpletest/mock_objects.php');
+    require_once('../classes/connection.php');
+
+    Mock::generate('Connection', 'BasicMockConnection');
+    class MockConnection extends BasicMockConnection {
+        function MockConnection() {
+            $this->BasicMockConnection();
+            $this->setReturn('query', false);
+        }
+    }
+?>
+
+ The generate call tells the class generator to create + a class called BasicMockConnection + rather than the usual MockConnection. + We then inherit from this to get our version of + MockConnection. + By intercepting in this way we can add behaviour, here setting + the default value of query() to be false. + By using the default name we make sure that the mock class + generator will not recreate a different one when invoked elsewhere in the + tests. + It never creates a class if it already exists. + As long as the above file is included first then all tests + that generated MockConnection should + now be using our one instead. + If we don't get the order right and the mock library + creates one first then the class creation will simply fail. +

+

+ Use this trick if you find you have a lot of common mock behaviour + or you are getting frequent integration problems at later + stages of testing. +

+ +
+ + + diff --git a/tests/simpletest/docs/en/overview.html b/tests/simpletest/docs/en/overview.html new file mode 100644 index 00000000..5d4e80e2 --- /dev/null +++ b/tests/simpletest/docs/en/overview.html @@ -0,0 +1,406 @@ + + + + + Overview and feature list for the SimpleTest PHP unit tester and web tester + + + + + +

Overview of SimpleTest

+
+

+ +

What is SimpleTest?

+ +

+

+ The heart of SimpleTest is a testing framework built around + test case classes. + These are written as extensions of base test case classes, + each extended with methods that actually contain test code. + Top level test scripts then invoke the run() + methods on every one of these test cases in order. + Each test method is written to invoke various assertions that + the developer expects to be true such as + assertEqual(). + If the expectation is correct, then a successful result is dispatched to the + observing test reporter, but any failure triggers an alert + and a description of the mismatch. +

+

+ A test case looks like this... +

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

+

+ These tools are designed for the developer. + Tests are written in the PHP language itself more or less + as the application itself is built. + The advantage of using PHP itself as the testing language is that + there are no new languages to learn, testing can start straight away, + and the developer can test any part of the code. + Basically, all parts that can be accessed by the application code can also be + accessed by the test code if they are in the same language. +

+

+ The simplest type of test case is the + UnitTestCase. + This class of test case includes standard tests for equality, + references and pattern matching. + All these test the typical expectations of what you would + expect the result of a function or method to be. + This is by far the most common type of test in the daily + routine of development, making up about 95% of test cases. +

+

+ The top level task of a web application though is not to + produce correct output from its methods and objects, but + to generate web pages. + The WebTestCase class tests web + pages. + It simulates a web browser requesting a page, complete with + cookies, proxies, secure connections, authentication, forms, frames and most + navigation elements. + With this type of test case, the developer can assert that + information is present in the page and that forms and + sessions are handled correctly. +

+

+ A WebTestCase looks like this... +

+<?php
+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/');
+    }
+}
+?>
+
+

+ +

+ +

Feature list

+ +

+

+ The following is a very rough outline of past and future features + and their expected point of release. + I am afraid it is liable to change without warning as meeting the + milestones rather depends on time available. + Green stuff has been coded, but not necessarily released yet. + If you have a pressing need for a green but unreleased feature + then you should check-out the code from Sourceforge CVS directly. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureDescriptionRelease
Unit test caseCore test case class and assertions1.0
Html displaySimplest possible display1.0
Autoloading of test cases + Reading a file with test cases and loading them into a + group test automatically + 1.0
Mock objects + Objects capable of simulating other objects removing + test dependencies + 1.0
Web test caseAllows link following and title tag matching1.0
Partial mocks + Mocking parts of a class for testing less than a class + or for complex simulations + 1.0
Web cookie handlingCorrect handling of cookies when fetching pages1.0
Following redirectsPage fetching automatically follows 300 redirects1.0
Form parsingAbility to submit simple forms and read default form values1.0
Command line interfaceTest display without the need of a web browser1.0
Exposure of expectation classesCan create precise tests with mocks as well as test cases1.0
XML output and parsing + Allows multi host testing and the integration of acceptance + testing extensions + 1.0
Browser component + Exposure of lower level web browser interface for more + detailed test cases + 1.0
HTTP authentication + Fetching protected web pages with basic authentication + only + 1.0
SSL supportCan connect to https: pages1.0
Proxy supportCan connect via. common proxies1.0
Frames supportHandling of frames in web test cases1.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
Reporting machinery enhancementsImproved message passing for better cooperation with IDEs1.1
LocalisationMessages abstracted and code generated from XML1.1
Testing exceptionsSimilar to testing PHP errors1.1
IFrame supportReads IFrame content that can be refreshed1.1
Improved mock interfaceMore compact way of expressing mocks2.0
HTML table assertionsCan match table elements to numerical assertions2.0
XPath searching of HTML elementsMore flexible content matching2.0
Alternate HTML parsersCan detect compiled parsers for performance improvements2.0
Javascript suportUse of PECL module to add Javascript3.0
+ 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. +

+ +

+ +

Web resources for testing

+ +

+

+ Process is at least as important as tools. + The type of process that makes the heaviest use of a developer's + testing tool is of course + Extreme Programming. + This is one of the + Agile Methodologies + which combine various practices to "flatten the cost curve" of software development. + More extreme still is Test Driven Development, + where you very strictly adhere to the rule of no coding until you have a test. + If you're more of a planner or believe that experience trumps evolution, + you may prefer the + RUP approach. + I haven't tried it, but even I can see that you will need test tools (see figure 9). +

+

+ Most unit testers clone JUnit to some degree, + as far as the interface at least. There is a wealth of information on the + JUnit site including the + FAQ + which contains plenty of general advice on testing. + Once you get bitten by the bug you will certainly appreciate the phrase + test infected + coined by Eric Gamma. + If you are still reviewing which unit tester to use the main choices + are PHPUnit + and Pear PHP::PHPUnit. + They currently lack a lot of features found in + SimpleTest, but the PEAR + version at least has been upgraded for PHP5 and is recommended if you are porting + existing JUnit test cases. +

+

+ There is currently a sad lack of material on mock objects, which is a shame + as unit testing without them is a lot more work. + The original mock objects paper + is very Java focused, but still worth a read. + As a new technology there are plenty of discussions and debate on how to use mocks, + often on Wikis such as + Extreme Tuesday + or www.mockobjects.com + or the original C2 Wiki. + Injecting mocks into a class is the main area of debate for which this + paper on IBM + makes a good starting point. +

+

+ There are plenty of web testing tools, but 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, + HTMLUnit + 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/simpletest/docs/en/partial_mocks_documentation.html b/tests/simpletest/docs/en/partial_mocks_documentation.html new file mode 100644 index 00000000..6d7b6243 --- /dev/null +++ b/tests/simpletest/docs/en/partial_mocks_documentation.html @@ -0,0 +1,423 @@ + + + +SimpleTest for PHP partial mocks documentation + + + + +

Partial mock objects documentation

+
+ +

+ A partial mock is simply a pattern to alleviate a specific problem + in testing with mock objects, + that of getting mock objects into tight corners. + It's quite a limited tool and possibly not even a good idea. + It is included with SimpleTest because I have found it useful + on more than one occasion and has saved a lot of work at that point. +

+ +

+ +

The mock injection problem

+ +

+

+ When one object uses another it is very simple to just pass a mock + version in already set up with its expectations. + Things are rather tricker if one object creates another and the + creator is the one you want to test. + This means that the created object should be mocked, but we can + hardly tell our class under test to create a mock instead. + The tested class doesn't even know it is running inside a test + after all. +

+

+ For example, suppose we are building a telnet client and it + needs to create a network socket to pass its messages. + The connection method might look something like... +

+<?php
+    require_once('socket.php');
+    
+    class Telnet {
+        ...
+        function &connect($ip, $port, $username, $password) {
+            $socket = &new Socket($ip, $port);
+            $socket->read( ... );
+            ...
+        }
+    }
+?>
+
+ We would really like to have a mock object version of the socket + here, what can we do? +

+

+ The first solution is to pass the socket in as a parameter, + forcing the creation up a level. + Having the client handle this is actually a very good approach + if you can manage it and should lead to factoring the creation from + the doing. + In fact, this is one way in which testing with mock objects actually + forces you to code more tightly focused solutions. + They improve your programming. +

+

+ Here this would be... +

+<?php
+    require_once('socket.php');
+    
+    class Telnet {
+        ...
+        function &connect(&$socket, $username, $password) {
+            $socket->read( ... );
+            ...
+        }
+    }
+?>
+
+ This means that the test code is typical for a test involving + mock objects. +
+class TelnetTest extends UnitTestCase {
+    ...
+    function testConnection() {
+        $socket = &new MockSocket($this);
+        ...
+        $telnet = &new Telnet();
+        $telnet->connect($socket, 'Me', 'Secret');
+        ...
+    }
+}
+
+ It is pretty obvious though that one level is all you can go. + You would hardly want your top level application creating + every low level file, socket and database connection ever + needed. + It wouldn't know the constructor parameters anyway. +

+

+ The next simplest compromise is to have the created object passed + in as an optional parameter... +

+<?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;
+        }
+    }
+?>
+
+ For a quick solution this is usually good enough. + The test now looks almost the same as if the parameter + was formally passed... +
+class TelnetTest extends UnitTestCase {
+    ...
+    function testConnection() {
+        $socket = &new MockSocket($this);
+        ...
+        $telnet = &new Telnet();
+        $telnet->connect('127.0.0.1', 21, 'Me', 'Secret', &$socket);
+        ...
+    }
+}
+
+ The problem with this approach is its untidiness. + There is test code in the main class and parameters passed + in the test case that are never used. + This is a quick and dirty approach, but nevertheless effective + in most situations. +

+

+ The next method is to pass in a factory object to do the creation... +

+<?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;
+        }
+    }
+?>
+
+ This is probably the most highly factored answer as creation + is now moved into a small specialist class. + The networking factory can now be tested separately, but mocked + easily when we are testing the telnet class... +
+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');
+        ...
+    }
+}
+
+ The downside is that we are adding a lot more classes to the + library. + Also we are passing a lot of factories around which will + make the code a little less intuitive. + The most flexible solution, but the most complex. +

+

+ Is there a middle ground? +

+ +

+ +

Protected factory method

+ +

+

+ There is a way we can circumvent the problem without creating + any new application classes, but it involves creating a subclass + when we do the actual testing. + Firstly we move the socket creation into its own method... +

+<?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);
+        }
+    }
+?>
+
+ This is the only change we make to the application code. +

+

+ For the test case we have to create a subclass so that + we can intercept the socket creation... +

+class TelnetTestVersion extends Telnet {
+    var $_mock;
+    
+    function TelnetTestVersion(&$mock) {
+        $this->_mock = &$mock;
+        $this->Telnet();
+    }
+    
+    function &_createSocket() {
+        return $this->_mock;
+    }
+}
+
+ Here I have passed the mock in the constructor, but a + setter would have done just as well. + Note that the mock was set into the object variable + before the constructor was chained. + This is necessary in case the constructor calls + connect(). + Otherwise it could get a null value from + _createSocket(). +

+

+ After the completion of all of this extra work the + actual test case is fairly easy. + We just test our new class instead... +

+class TelnetTest extends UnitTestCase {
+    ...
+    function testConnection() {
+        $socket = &new MockSocket($this);
+        ...
+        $telnet = &new TelnetTestVersion($socket);
+        $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
+        ...
+    }
+}
+
+ The new class is very simple of course. + It just sets up a return value, rather like a mock. + It would be nice if it also checked the incoming parameters + as well. + Just like a mock. + It seems we are likely to do this often, can + we automate the subclass creation? +

+ +

+ +

A partial mock

+ +

+

+ Of course the answer is "yes" or I would have stopped writing + this by now! + The previous test case was a lot of work, but we can + generate the subclass using a similar approach to the mock objects. +

+

+ Here is the partial mock version of the test... +

+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');
+        ...
+    }
+}
+
+ The partial mock is a subclass of the original with + selected methods "knocked out" with test + versions. + The generatePartial() call + takes three parameters: the class to be subclassed, + the new test class name and a list of methods to mock. +

+

+ Instantiating the resulting objects is slightly tricky. + The only constructor parameter of a partial mock is + the unit tester reference. + As with the normal mock objects this is needed for sending + test results in response to checked expectations. +

+

+ The original constructor is not run yet. + This is necessary in case the constructor is going to + make use of the as yet unset mocked methods. + We set any return values at this point and then run the + constructor with its normal parameters. + This three step construction of "new", followed + by setting up the methods, followed by running the constructor + proper is what distinguishes the partial mock code. +

+

+ Apart from construction, all of the mocked methods have + the same features as mock objects and all of the unmocked + methods behave as before. + We can set expectations very easily... +

+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();
+    }
+}
+
+

+ +

+ +

Testing less than a class

+ +

+

+ The mocked out methods don't have to be factory methods, + they could be any sort of method. + In this way partial mocks allow us to take control of any part of + a class except the constructor. + We could even go as far as to mock every method + except one we actually want to test. +

+

+ This last situation is all rather hypothetical, as I haven't + tried it. + I am open to the possibility, but a little worried that + forcing object granularity may be better for the code quality. + I personally use partial mocks as a way of overriding creation + or for occasional testing of the TemplateMethod pattern. +

+

+ It's all going to come down to the coding standards of your + project to decide which mechanism you use. +

+ +
+ + + diff --git a/tests/simpletest/docs/en/reporter_documentation.html b/tests/simpletest/docs/en/reporter_documentation.html new file mode 100644 index 00000000..ead61175 --- /dev/null +++ b/tests/simpletest/docs/en/reporter_documentation.html @@ -0,0 +1,512 @@ + + + +SimpleTest for PHP test runner and display documentation + + + + +

Test reporter documentation

+
+ +

+ SimpleTest pretty much follows the MVC pattern + (Model-View-Controller). + The reporter classes are the view and the model is your + test cases and their hiearchy. + The controller is mostly hidden from the user of + SimpleTest unless you want to change how the test cases + are actually run, in which case it is possible to + override the runner objects from within the test case. + As usual with MVC, the controller is mostly undefined + and there are other places to control the test run. +

+ +

+ +

Reporting results in HTML

+ +

+

+ The default test display is minimal in the extreme. + It reports success and failure with the conventional red and + green bars and shows a breadcrumb trail of test groups + for every failed assertion. + Here's a fail... +

+

File test

+ Fail: createnewfile->True assertion failed.
+
1/1 test cases complete. + 0 passes, 1 fails and 0 exceptions.
+
+ And here all tests passed... +
+

File test

+
1/1 test cases complete. + 1 passes, 0 fails and 0 exceptions.
+
+ The good news is that there are several points in the display + hiearchy for subclassing. +

+

+ For web page based displays there is the + HtmlReporter class with the following + signature... +

+class HtmlReporter extends SimpleReporter {
+    public HtmlReporter($encoding) { ... }
+    public makeDry(boolean $is_dry) { ... }
+    public void paintHeader(string $test_name) { ... }
+    public void sendNoCacheHeaders() { ... }
+    public void paintFooter(string $test_name) { ... }
+    public void paintGroupStart(string $test_name, integer $size) { ... }
+    public void paintGroupEnd(string $test_name) { ... }
+    public void paintCaseStart(string $test_name) { ... }
+    public void paintCaseEnd(string $test_name) { ... }
+    public void paintMethodStart(string $test_name) { ... }
+    public void paintMethodEnd(string $test_name) { ... }
+    public void paintFail(string $message) { ... }
+    public void paintPass(string $message) { ... }
+    public void paintError(string $message) { ... }
+    public void paintException(string $message) { ... }
+    public void paintMessage(string $message) { ... }
+    public void paintFormattedMessage(string $message) { ... }
+    protected string _getCss() { ... }
+    public array getTestList() { ... }
+    public integer getPassCount() { ... }
+    public integer getFailCount() { ... }
+    public integer getExceptionCount() { ... }
+    public integer getTestCaseCount() { ... }
+    public integer getTestCaseProgress() { ... }
+}
+
+ Here is what some of these methods mean. First the display methods + that you will probably want to override... +
    +
  • + HtmlReporter(string $encoding) +
    + is the constructor. + Note that the unit test sets up the link to the display + rather than the other way around. + The display is a mostly passive receiver of test events. + This allows easy adaption of the display for other test + systems beside unit tests, such as monitoring servers. + The encoding is the character encoding you wish to + display the test output in. + In order to correctly render debug output when + using the web tester, this should match the encoding + of the site you are trying to test. + The available character set strings are described in + the PHP html_entities() + function. +
  • +
  • + void paintHeader(string $test_name) +
    + is called once at the very start of the test when the first + start event arrives. + The first start event is usually delivered by the top level group + test and so this is where $test_name + comes from. + It paints the page titles, CSS, body tag, etc. + It returns nothing (void). +
  • +
  • + void paintFooter(string $test_name) +
    + Called at the very end of the test to close any tags opened + by the page header. + By default it also displays the red/green bar and the final + count of results. + Actually the end of the test happens when a test end event + comes in with the same name as the one that started it all + at the same level. + The tests nest you see. + Closing the last test finishes the display. +
  • +
  • + void paintMethodStart(string $test_name) +
    + is called at the start of each test method. + The name normally comes from method name. + The other test start events behave the same way except + that the group test one tells the reporter how large + it is in number of held test cases. + This is so that the reporter can display a progress bar + as the runner churns through the test cases. +
  • +
  • + void paintMethodEnd(string $test_name) +
    + backs out of the test started with the same name. +
  • +
  • + void paintFail(string $message) +
    + paints a failure. + By default it just displays the word fail, a breadcrumbs trail + showing the current test nesting and the message issued by + the assertion. +
  • +
  • + void paintPass(string $message) +
    + by default does nothing. +
  • +
  • + string _getCss() +
    + Returns the CSS styles as a string for the page header + method. + Additional styles have to be appended here if you are + not overriding the page header. + You will want to use this method in an overriden page header + if you want to include the original CSS. +
  • +
+ There are also some accessors to get information on the current + state of the test suite. + Use these to enrich the display... +
    +
  • + array getTestList() +
    + is the first convenience method for subclasses. + Lists the current nesting of the tests as a list + of test names. + The first, most deeply nested test, is first in the + list and the current test method will be last. +
  • +
  • + integer getPassCount() +
    + returns the number of passes chalked up so far. + Needed for the display at the end. +
  • +
  • + integer getFailCount() +
    + is likewise the number of fails so far. +
  • +
  • + integer getExceptionCount() +
    + is likewise the number of errors so far. +
  • +
  • + integer getTestCaseCount() +
    + is the total number of test cases in the test run. + This includes the grouping tests themselves. +
  • +
  • + integer getTestCaseProgress() +
    + is the number of test cases completed so far. +
  • +
+ One simple modification is to get the HtmlReporter to display + the passes as well as the failures and errors... +
+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; }';
+    }
+}
+
+

+

+ One method that was glossed over was the makeDry() + method. + If you run this method, with no parameters, on the reporter + before the test suite is run no actual test methods + will be called. + You will still get the events of entering and leaving the + test methods and test cases, but no passes or failures etc, + because the test code will not actually be executed. +

+

+ The reason for this is to allow for more sophistcated + GUI displays that allow the selection of individual test + cases. + In order to build a list of possible tests they need a + report on the test structure for drawing, say a tree view + of the test suite. + With a reporter set to dry run that just sends drawing events + this is easily accomplished. +

+ +

+ +

Extending the reporter

+ +

+

+ Rather than simply modifying the existing display, you might want to + produce a whole new HTML look, or even generate text or XML. + Rather than override every method in + HtmlReporter we can take one + step up the class hiearchy to SimpleReporter + in the simple_test.php source file. +

+

+ A do nothing display, a blank canvas for your own creation, would + be... +

+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);
+    }
+}
+
+ No output would come from this class until you add it. +

+ +

+ +

The command line reporter

+ +

+

+ SimpleTest also ships with a minimal command line reporter. + The interface mimics JUnit to some extent, but paints the + failure messages as they arrive. + To use the command line reporter simply substitute it + for the HTML version... +

+<?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());
+?>
+
+ Then invoke the test suite from the command line... +
+php file_test.php
+
+ You will need the command line version of PHP installed + of course. + A passing test suite looks like this... +
+File test
+OK
+Test cases run: 1/1, Failures: 0, Exceptions: 0
+
+ A failure triggers a display like this... +
+File test
+1) True assertion failed.
+	in createnewfile
+FAILURES!!!
+Test cases run: 1/1, Failures: 1, Exceptions: 0
+
+

+

+ One of the main reasons for using a command line driven + test suite is of using the tester as part of some automated + process. + To function properly in shell scripts the test script should + return a non-zero exit code on failure. + If a test suite fails the value false + is returned from the SimpleTest::run() + method. + We can use that result to exit the script with the desired return + code... +

+<?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);
+?>
+
+ Of course we don't really want to create two test scripts, + a command line one and a web browser one, for each test suite. + The command line reporter includes a method to sniff out the + run time environment... +
+<?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());
+?>
+
+ This is the form used within SimpleTest itself. +

+ +

+ +

Remote testing

+ +

+

+ SimpleTest ships with an XmlReporter class + used for internal communication. + When run the output looks like... +

+<?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>
+
+ You can make use of this format with the parser + supplied as part of SimpleTest itself. + This is called SimpleTestXmlParser and + resides in xml.php within the SimpleTest package... +
+<?php
+    require_once('simpletest/xml.php');
+    
+    ...
+    $parser = &new SimpleTestXmlParser(new HtmlReporter());
+    $parser->parse($test_output);
+?>
+
+ The $test_output should be the XML format + from the XML reporter, and could come from say a command + line run of a test case. + The parser sends events to the reporter just like any + other test run. + There are some odd occasions where this is actually useful. +

+

+ A problem with large test suites is thet they can exhaust + the default 8Mb memory limit on a PHP process. + By having the test groups output in XML and run in + separate processes, the output can be reparsed to + aggregate the results into a much smaller footprint top level + test. +

+

+ Because the XML output can come from anywhere, this opens + up the possibility of aggregating test runs from remote + servers. + A test case already exists to do this within the SimpleTest + framework, but it is currently experimental... +

+<?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());
+?>
+
+ The RemoteTestCase takes the actual location + of the test runner, basically a web page in XML format. + It also takes the URL of a reporter set to do a dry run. + This is so that progress can be reported upward correctly. + The RemoteTestCase can be added to test suites + just like any other group test. +

+ +
+ + + diff --git a/tests/simpletest/docs/en/unit_test_documentation.html b/tests/simpletest/docs/en/unit_test_documentation.html new file mode 100644 index 00000000..47b61eca --- /dev/null +++ b/tests/simpletest/docs/en/unit_test_documentation.html @@ -0,0 +1,390 @@ + + + +SimpleTest for PHP regression test documentation + + + + +

PHP Unit Test documentation

+
+

+ +

Unit test cases

+ +

+

+ The core system is a regression testing framework built around + test cases. + A sample test case looks like this... +

+class FileTestCase extends UnitTestCase {
+}
+
+ If no test name is supplied when chaining the constructor then + the class name will be taken instead. + This will be the name displayed in the test results. +

+

+ Actual tests are added as methods in the test case whose names + by default start with the string "test" and + when the test case is invoked all such methods are run in + the order that PHP introspection finds them. + As many test methods can be added as needed. + For example... +

+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');
+    }
+}
+
+ The constructor is optional and usually omitted. + Without a name, the class name is taken as the name of the test case. +

+

+ Our only test method at the moment is testCreation() + where we check that a file has been created by our + Writer object. + We could have put the unlink() + code into this method as well, but by placing it in + setUp() and + tearDown() we can use it with + other test methods that we add. +

+

+ The setUp() method is run + just before each and every test method. + tearDown() is run just after + each and every test method. +

+

+ You can place some test case set up into the constructor to + be run once for all the methods in the test case, but + you risk test inteference that way. + This way is slightly slower, but it is safer. + Note that if you come from a JUnit background this will not + be the behaviour you are used to. + JUnit surprisingly reinstantiates the test case for each test + method to prevent such interference. + SimpleTest requires the end user to use setUp(), but + supplies additional hooks for library writers. +

+

+ The means of reporting test results (see below) are by a + visiting display class + that is notified by various assert...() + methods. + Here is the full list for the UnitTestCase + class, the default for SimpleTest... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
assertTrue($x)Fail if $x is false
assertFalse($x)Fail if $x is true
assertNull($x)Fail if $x is set
assertNotNull($x)Fail if $x not set
assertIsA($x, $t)Fail if $x is not the class or type $t
assertNotA($x, $t)Fail if $x is of the class or type $t
assertEqual($x, $y)Fail if $x == $y is false
assertNotEqual($x, $y)Fail if $x == $y is true
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
assertNotIdentical($x, $y)Fail if $x == $y is true and types match
assertReference($x, $y)Fail unless $x and $y are the same variable
assertCopy($x, $y)Fail if $x and $y are the same variable
assertPattern($p, $x)Fail unless 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/expectation
assertExpectation($e)Fail on failed expectation object
+ All assertion methods can take an optional description to + label the displayed result with. + If omitted a default message is sent instead which is usually + sufficient. + This default message can still be embedded in your own message + if you include "%s" within the string. + All the assertions return true on a pass or false on failure. +

+

+ Some examples... +

+$variable = null;
+$this->assertNull($variable, 'Should be cleared');
+
+ ...will pass and normally show no message. + If you have + set up the tester to display passes + as well then the message will be displayed as is. +
+$this->assertIdentical(0, false, 'Zero is not false [%s]');
+
+ This will fail as it performs a type + check as well as a comparison between the two values. + The "%s" part is replaced by the default + error message that would have been shown if we had not + supplied our own. + This also allows us to nest test messages. +
+$a = 1;
+$b = $a;
+$this->assertReference($a, $b);
+
+ Will fail as the variable $a is a copy of $b. +
+$this->assertPattern('/hello/i', 'Hello world');
+
+ This will pass as using a case insensitive match the string + hello is contained in Hello world. +
+trigger_error('Disaster');
+trigger_error('Catastrophe');
+$this->assertError();
+$this->assertError('Catastrophe');
+$this->assertNoErrors();
+
+ This one takes some explanation as in fact they all pass! +

+

+ PHP errors in SimpleTest are trapped and placed in a queue. + Here the first error check catches the "Disaster" + message without checking the text and passes. + This removes the error from the queue. + The next error check tests not only the existence of the error, + but also the text which here matches so another pass. + With the queue now empty the last test will pass as well. + If any unchecked errors are left at the end of a test method then + an exception will be reported in the test. + Note that SimpleTest cannot catch compile time PHP errors. +

+

+ The test cases also have some convenience methods for debugging + code or extending the suite... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
setUp()Runs this before each test method
tearDown()Runs this after each test method
pass()Sends a test pass
fail()Sends a test failure
error()Sends an exception event
sendMessage()Sends a status message to those displays that support it
signal($type, $payload)Sends a user defined message to the test reporter
dump($var)Does a formatted print_r() for quick and dirty debugging
swallowErrors()Clears the error queue
+

+ +

+ +

Extending test cases

+ +

+

+ Of course additional test methods can be added to create + specific types of test case too so as to extend 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'));
+    }
+}
+
+ Here the SimpleTest library is held in a folder called + simpletest that is local. + Substitute your own path for this. +

+

+ This new case can be now be inherited just like + a normal test case... +

+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');
+    }
+}
+
+

+

+ If you want a test case that does not have all of the + UnitTestCase assertions, + only your own and assertTrue(), + you need to extend the SimpleTestCase + class instead. + It is found in simple_test.php rather than + unit_tester.php. + See later if you + want to incorporate other unit tester's + test cases in your test suites. +

+ +

+ +

Running a single test case

+ +

+

+ You won't often run single test cases except when bashing + away at a module that is having difficulty and you don't + want to upset the main test suite. + Here is the scaffolding needed to run the a lone test case... +

+<?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());
+?>
+
+ This script will run as is, but will output zero passes + and zero failures until test methods are added. +

+ +
+ + + diff --git a/tests/simpletest/docs/en/web_tester_documentation.html b/tests/simpletest/docs/en/web_tester_documentation.html new file mode 100644 index 00000000..99dacacc --- /dev/null +++ b/tests/simpletest/docs/en/web_tester_documentation.html @@ -0,0 +1,511 @@ + + + +Simple Test for PHP web script testing documentation + + + + +

Web tester documentation

+
+

+ +

Fetching a page

+ +

+

+ Testing classes is all very well, but PHP is predominately + a language for creating functionality within web pages. + How do we test the front end presentation role of our PHP + applications? + Well the web pages are just text, so we should be able to + examine them just like any other test data. +

+

+ This leads to a tricky issue. + If we test at too low a level, testing for matching tags + in the page with pattern matching for example, our tests will + be brittle. + The slightest change in layout could break a large number of + tests. + If we test at too high a level, say using mock versions of a + template engine, then we lose the ability to automate some classes + of test. + For example, the interaction of forms and navigation will + have to be tested manually. + These types of test are extremely repetitive and error prone. +

+

+ SimpleTest includes a special form of test case for the testing + of web page actions. + The WebTestCase includes facilities + for navigation, content and cookie checks and form handling. + Usage of these test cases is similar to the + UnitTestCase... +

+class TestOfLastcraft extends WebTestCase {
+}
+
+ Here we are about to test the + Last Craft site itself. + If this test case is in a file called lastcraft_test.php + then it can be loaded in a runner script just like unit tests... +
+<?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);
+?>
+
+ I am using the text reporter here to more clearly + distinguish the web content from the test output. +

+

+ Nothing is being tested yet. + We can fetch the home page by using the + get() method... +

+class TestOfLastcraft extends WebTestCase {
+    
+    function testHomepage() {
+        $this->assertTrue($this->get('http://www.lastcraft.com/'));
+    }
+}
+
+ The get() method will + return true only if page content was successfully + loaded. + It is a simple, but crude way to check that a web page + was actually delivered by the web server. + However that content may be a 404 response and yet + our get() method will still return true. +

+

+ Assuming that the web server for the Last Craft site is up + (sadly not always the case), we should see... +

+Web site tests
+OK
+Test cases run: 1/1, Failures: 0, Exceptions: 0
+
+ All we have really checked is that any kind of page was + returned. + We don't yet know if it was the right one. +

+ +

+ +

Testing page content

+ +

+

+ To confirm that the page we think we are on is actually the + page we are on, we need to verify the page content. +

+class TestOfLastcraft extends WebTestCase {
+    
+    function testHomepage() {
+        $this->get('http://www.lastcraft.com/');
+        $this->assertTest('Why the last craft');
+    }
+}
+
+ The page from the last fetch is held in a buffer in + the test case, so there is no need to refer to it directly. + The pattern match is always made against the buffer. +

+

+ Here is the list of possible content assertions... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
assertTitle($title)Pass if title is an exact match
assertPattern($pattern)A Perl pattern match against the page content
assertNoPattern($pattern)A Perl pattern match to not find content
assertText($text)Pass if matches 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
assertNoLink($label)Pass if no link with this text is present
assertLinkById($id)Pass if a link with this id attribute is present
assertNoLinkById($id)Pass if no link with this id attribute is present
assertField($name, $value)Pass if an input tag with this name has this value
assertFieldById($id, $value)Pass if an input tag with this id has this value
assertResponse($codes)Pass if HTTP response matches this list
assertMime($types)Pass if MIME type is in this list
assertAuthentication($protocol)Pass if the current challenge is this protocol
assertNoAuthentication()Pass if there is no current challenge
assertRealm($name)Pass if the current challenge realm matches
assertHeader($header, $content)Pass if a header was fetched matching this value
assertNoHeader($header)Pass if a header was not fetched
assertCookie($name, $value)Pass if there is currently a matching cookie
assertNoCookie($name)Pass if there is currently no cookie of this name
+ As usual with the SimpleTest assertions, they all return + false on failure and true on pass. + They also allow an optional test message and you can embed + the original test message inside using "%s" inside + your custom message. +

+

+ So now we could instead test against the title tag with... +

+$this->assertTitle('The Last Craft? Web developer tutorials on PHP, Extreme programming and Object Oriented development');
+
+ ...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... +
+$this->assertMime(array('text/plain', 'text/html'));
+
+ More interesting is checking the HTTP response code. + Like the MIME type, we can assert that the response code + is in a list of allowed values... +
+class TestOfLastcraft extends WebTestCase {
+    
+    function testRedirects() {
+        $this->get('http://www.lastcraft.com/test/redirect.php');
+        $this->assertResponse(200);</strong>
+    }
+}
+
+ Here we are checking that the fetch is successful by + allowing only a 200 HTTP response. + This test will pass, but it is not actually correct to do so. + There is no page, instead the server issues a redirect. + The WebTestCase will + automatically follow up to three such redirects. + The tests are more robust this way and we are usually + interested in the interaction with the pages rather + than their delivery. + If the redirects are of interest then this ability must + be disabled... +
+class TestOfLastcraft extends WebTestCase {
+    
+    function testHomepage() {
+        $this->setMaximumRedirects(0);
+        $this->get('http://www.lastcraft.com/test/redirect.php');
+        $this->assertResponse(200);
+    }
+}
+
+ The assertion now fails as expected... +
+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
+
+ We can modify the test to correctly assert redirects with... +
+class TestOfLastcraft extends WebTestCase {
+    
+    function testHomepage() {
+        $this->setMaximumRedirects(0);
+        $this->get('http://www.lastcraft.com/test/redirect.php');
+        $this->assertResponse(array(301, 302, 303, 307));
+    }
+}
+
+ This now passes. +

+ +

+ +

Navigating a web site

+ +

+

+ Users don't often navigate sites by typing in URLs, but by + clicking links and buttons. + Here we confirm that the contact details can be reached + from the home page... +

+class TestOfLastcraft extends WebTestCase {
+    ...
+    function testContact() {
+        $this->get('http://www.lastcraft.com/');
+        $this->clickLink('About');
+        $this->assertTitle(new PatternExpectation('/About Last Craft/'));
+    }
+}
+
+ The parameter is the text of the link. +

+

+ If the target is a button rather than an anchor tag, then + 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!');
+
+

+

+ The list of navigation methods is... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
getUrl()The current location
get($url, $parameters)Send a GET request with these parameters
post($url, $parameters)Send a POST request with these parameters
head($url, $parameters)Send a HEAD request without replacing the page content
retry()Reload the last request
back()Like the browser back button
forward()Like the browser forward button
authenticate($name, $password)Retry after a challenge
restart()Restarts the browser as if a new session
getCookie($name)Gets the cookie value for the current context
ageCookies($interval)Ages current cookies prior to a restart
clearFrameFocus()Go back to treating all frames as one page
clickSubmit($label)Click the first button with this label
clickSubmitByName($name)Click the button with this name attribute
clickSubmitById($id)Click the button with this ID attribute
clickImage($label, $x, $y)Click an input tag of type image by title or alt text
clickImageByName($name, $x, $y)Click an input tag of type image by name
clickImageById($id, $x, $y)Click an input tag of type image by ID attribute
submitFormById($id)Submit a form without the submit value
clickLink($label, $index)Click an anchor by the visible label text
clickLinkById($id)Click an anchor by the ID attribute
getFrameFocus()The name of the currently selected frame
setFrameFocusByIndex($choice)Focus on a frame counting from 1
setFrameFocus($name)Focus on a frame by name
+

+

+ The parameters in the get(), post() or + head() methods are optional. + The HTTP HEAD fetch does not change the browser context, only loads + cookies. + This can be useful for when an image or stylesheet sets a cookie + for crafty robot blocking. +

+

+ The retry(), back() and + forward() commands work as they would on + your web browser. + They use the history to retry pages. + This can be handy for checking the effect of hitting the + back button on your forms. +

+

+ The frame methods need a little explanation. + By default a framed page is treated just like any other. + Content will be searced for throughout the entire frameset, + so clicking a link will work no matter which frame + the anchor tag is in. + You can override this behaviour by focusing on a single + frame. + If you do that, all searches and actions will apply to that + frame alone, such as authentication and retries. + If a link or button is not in a focused frame then it cannot + be clicked. +

+

+ Testing navigation on fixed pages only tells you when you + have broken an entire script. + For highly dynamic pages, such as for bulletin boards, this can + be crucial for verifying the correctness of the application. + For most applications though, the really tricky logic is usually in + the handling of forms and sessions. + Fortunately SimpleTest includes + tools for testing web forms + as well. +

+ +

+ +

Modifying the request

+ +

+

+ Although SimpleTest does not have the goal of testing networking + problems, it does include some methods to modify and debug + the requests it makes. + Here is another method list... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
getTransportError()The last socket error
showRequest()Dump the outgoing request
showHeaders()Dump the incoming headers
showSource()Dump the raw HTML page content
ignoreFrames()Do not load framesets
setCookie($name, $value)Set a cookie from now on
addHeader($header)Always add this header to the request
setMaximumRedirects($max)Stop after this many redirects
setConnectionTimeout($timeout)Kill the connection after this time between bytes
useProxy($proxy, $name, $password)Make requests via this proxy URL
+ These methods are principally for debugging. +

+ +
+ + + diff --git a/tests/simpletest/docs/fr/docs.css b/tests/simpletest/docs/fr/docs.css new file mode 100644 index 00000000..93226cd7 --- /dev/null +++ b/tests/simpletest/docs/fr/docs.css @@ -0,0 +1,84 @@ +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/simpletest/docs/lastcraft/README b/tests/simpletest/docs/lastcraft/README new file mode 100644 index 00000000..488198a5 --- /dev/null +++ b/tests/simpletest/docs/lastcraft/README @@ -0,0 +1 @@ +Output folder for Lastcraft site versions of documentation. \ No newline at end of file diff --git a/tests/simpletest/docs/onpk/README b/tests/simpletest/docs/onpk/README new file mode 100644 index 00000000..fc1dd627 --- /dev/null +++ b/tests/simpletest/docs/onpk/README @@ -0,0 +1 @@ +Répertoire utilisé pour l'extraction de la documentation au format du site onpk.net \ No newline at end of file diff --git a/tests/simpletest/docs/pkg/README b/tests/simpletest/docs/pkg/README new file mode 100644 index 00000000..821b4f63 --- /dev/null +++ b/tests/simpletest/docs/pkg/README @@ -0,0 +1 @@ +Files here are generated from make_phpdoc_docs.sh \ No newline at end of file diff --git a/tests/simpletest/docs/simpletest.org/README b/tests/simpletest/docs/simpletest.org/README new file mode 100644 index 00000000..41269559 --- /dev/null +++ b/tests/simpletest/docs/simpletest.org/README @@ -0,0 +1 @@ +Output folder for SimpleTest.org site versions of content, documentation & tutorial. \ No newline at end of file diff --git a/tests/simpletest/docs/simpletest.org/images/book-domain-driven-design.jpg b/tests/simpletest/docs/simpletest.org/images/book-domain-driven-design.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3bebb8ec681ea19cfb018fc97c9dab57693781c9 GIT binary patch literal 6599 zcmbW4bx<45m%tM&NPz|`nv_CIace0~f#L;Jl#C2a3I>x?(LW)lprr(ZsTrwh85p2YDEX6T%+Daq z^bjcIUzY$Mj)L$&B>4Cw5DG8_1qNb+f%iQC=!2iQz<(FO ze+m!_8|T4Gd;&tE2ZQ>@04yLjHr9jx4*(C=z7P8V955~!Bd;VLxta;+nG*$HKwJ(! zlT>vlrTWAXGry^GAORuO6KWdT=Py`Zva-E;E$~KANLc!vjI5lzf})0|mbQ+r-bXX@ zPZpL|);2D#ZtidoPp_chkkGI%U&G@Q5|ffsQqvIMbMx{G3X6(MYHI818ycIMTe`Y? zdi#+51A~)O(=({qUvu*-t843jHa54mcQD5%r)TFEmsi*S;sOG&{{!nm{|DIr-~vBz zVLgNe2lOv4AQt>#VuNvT8F}%@B-KDBPUO${0`MuM;&Q4x37GiRk0?!@CkUySU#&dH z{0r^h$^Lg>f&VYE{{s7Ou6e*CY~Vxiu)zQcz!s%%@%o4M>9z1X{M)?XXfKT!E5Q*V zC)8)!uEdyAw{w^4fWH*wD%lvV`)(qxfdiz7yk^Lw&{i ztP-m!1LFa2ha#~$@{X$aMW34pb&q;(e|nq*>CGtTo7s@Cw%hugF;$`VxK`@SoG4rj zdTKa0)*Ki3K(n`O`i2hjO=b^I2@BOmMxxBs#Dd;h_Xws<#wZi<3XU)p)0l}8i zhO(O~4p6INxQ(WPH1j7~vfpq&{Xb)NXZuFhmm1ftoY4l$80>Ss#Y{swD z=(SN?dM3i|kbmPMK}w8*ptH z|E0=mmL?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oKa4L^Ge8jl5VA8ASS;>}<2V!Aqq4>zM0u!I*XrH)Ypg8{umB3=DHHj`$8) zb?-QR&4fXZpDlgws0}e^NKGvIt~DOTYvYR~LiKc`E-9K&7&D7{SxgD!Jqda&53aR& zd}cJt`(a>SL;JkO6cH` zse)FkpU&D;r_uqPoAmF36y|FJU3-Af*>r+MzCcl_M}(tZ`R@Jb2CoYf&==DpN7qbP z7+msk`CDh{R)Nil+&C}l;AacZlI3jH-9%X^^t$o=jo=rb*@>je3fTAw!qU|k7+BdS zz}Ab=e+u`Uw|G?yQk;Z7OiV^u3;gJkEY-+fqgVNGRF?d3Y8WM;ZGKu+Zi0wP?2AmM zkf~})b9s;~6RE~2DrO!&k(Kc(Rvx!j^DT>H<;*;k*0TXud9eBnYx7oC_%ozx^8FKo zZL-92^VI?|0+_ZopYzvsJ&WeU*HtB{5Y&%L16(oA8qm`xINpfZXr=W)MBBRz^XCs+ zHZ1vSc=hJ)=RXENGVAqNUlE)mTsO)-r)f z?VMWxUtZfSz~1;(!!c8IHGx^*1}Gu08?>ggk%KbD?z{_^Hx#{(` zGH3_`K1YGUbY2F~4Y54fc(q26MVO#P8I$6OChPD-MGd(M4f9WDed6{aCDD_3gx1^B z^tY4}T~?IPkxr_IloAs}%?uJ2x~8(VEmDiZQDDY7?>naR?W7PPhWr6YWU7z&< z-#xX{Hp%17CknAAMrMq4ThpH`M+p}D$wXX81RSrFt1vh`O>g{f>YQG^AIZ~HJsrjH zAD*lnBu7Mvis~#rR0dlsR8`5r0H?(xCHFA_;msDOEL-Kb9kX4Kpp<1g{)x+YoS}P-u6*xVX2f4J zTh1R7(qr_}{GO$7wpaiosx zl&Zu&+xew6HH%m_YcjySiBS{V#fZ(8yAP4#%3=gh?0_ Dj{TPW literal 0 HcmV?d00001 diff --git a/tests/simpletest/docs/simpletest.org/images/book-the-php-anthology-object-oriented-php-solutions.jpg b/tests/simpletest/docs/simpletest.org/images/book-the-php-anthology-object-oriented-php-solutions.jpg new file mode 100644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Ta?AWNch~{QCdu;*uGU z@d)1~Y`^5Q=?%*)td4~RVDWt+nU>eB;oT>yRW-_OY9YtyLsD%fnn^VI?Cu!!V^r_; z0ZB7o^NAj-@!5hP`_B5i%sTh@@-?2TX-tOR+dXFsXP1*A3)!_r&Fg>&=)t(YXZp|<|@zsP1%w>W4X`gQj| zfV)%Md=7#{j%JmrC0pido2dJC*z%~jV~DrmX5T}z&`jETXv{G;#YZTQDYL)7{}l@h z$ASt{`SxMhbP!&__c=SHF0igj;Gv#svbNtf88_tG%hhO%=4kWFXM5Lfr>vNNdjv>W zR|Fu(_pbzOML_0~>g(&Bly-jn#}x8srg;oL7hk%q&99gF!^-*Iy?c{v`IHVXU)_P< zMwmm{Gr_mBM*Etf!YM1-=Z14YJA;>29+2`nro-`L7rqT&w-g=w)!6BZNDnN6mP^S^ znTt33%+em?f-7DP=PWjg1E~epEt~NZ(Q-?6>992dpOE&J?*b&JsJM7}YYUpIYOG`G z7Z@ljQ|gUi1^9;mIM;Q8PV4@kEvv?4yTboI$ttA}w75_C1qUbEHxMb3S&I=<{@lL~ zm5q#yrZ)nMKB}l3&CJYbjW{TL{0(M`n}FxJE;eb&yt|WK)kPj;!JniOTjBYyO(T@Gf8PVre>WEbd(5}v#eEd*cDu3| z(p3#SIU`qMmnfqFw|nwR{{6(+a;I2eBSD^#^)RH8CBbvgApYsUG0wClAV#r_}P9BoAa literal 0 HcmV?d00001 diff --git a/tests/simpletest/docs/simpletest.org/images/simpletest-start-testing.png b/tests/simpletest/docs/simpletest.org/images/simpletest-start-testing.png new file mode 100644 index 0000000000000000000000000000000000000000..9ba2c29f4c7c7969570f6387d219c1f2458cf40d GIT binary patch literal 5866 zcmW+)1yodB7ab6AkQzD!h7JJ%K{_M_>FyfhqZztGItP$aQbf9uRA4|_Vh9n2PU(VN)kt^4YpcTerJ?|LUrQ~fo;6PhO=5QsooNnRTS!r%w)UBEcNdB|K}6S!b`$|~!E zfg=cP6AL`!!j+6XK_EPme*xvUh?wu^Y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p9>qM{L; zcyRUdUH5-dPBB`05s0+zXq1*Gw70h(JmK$nk_3(;0br_A6%dVFbwsyP$ zxJj$u8v*l}O8{~K9H)YUTYw1GP5%0%gD`A2(UuiP{ciy8bMKR|ftmz5;Pfn6>L4IC zh1!X7m&ngp{?mKc40`Pj5=Lt=kC|j1Jz9zw!%*~%|K0ZwK&g1l1h3}Ap-_%Yu`hrZ z+@GT;%hp;)B=f(iTW)E^#fXLxyyRT?epQrp@^sJ|@J^tIJZaOe9>DN`{Q)mQg#+)- zq)fbi>p!^nO2TR&*6s=Ln8he>hnFbPH%<1_C0>?mycCu&;H{~n*+7ul-QE4UkPg6UG@tOw{75#)bQTdf}o0Tmj8Fb$Jl zv+l54*Ir-lGx;a#<@7+z4ahcHS`@IC?@4{ou7U^ft;!zca;n~I5<^eW;pJmBxRxowwh`z{r5jzNYNS#|4P?qs|Ies799ahX``aybzg;>lty1Z$rTn{+ZYv`+3MPz;M##3k dwe%3L3OnvDDM&0gxZDS&t8J(S)p+vq{{g#nGaLW_ literal 0 HcmV?d00001 diff --git a/tests/simpletest/docs/simpletest.org/images/test-with-1-fail.png b/tests/simpletest/docs/simpletest.org/images/test-with-1-fail.png new file mode 100644 index 0000000000000000000000000000000000000000..74834deae0b6a7d40217101304f1d9be0b23de9a GIT binary patch literal 25562 zcmb@uhdY<=-v_L%Nohz*11Z^~gh(NjjIs*Jp4lU_QYoQ~kdT!mJA{m~Lb4LF$=-YO zyw30MK91-410Kiyz3;o?cQquWM7L9tWn%4G!#igiQy{|zWN zr$6x;WZ|JK#Ex-8=_8LY)stQGI+S=(t@ z>QY?O(zd*3s;gtDbyUL8QrGUDrLon~bLj@P_7oJN6jGNj-mrf=9O@u?v;Ob6tGQdD zP!%ONCHJHCUH&J2?R>B2r)Q|DdNwCmPw&yCnBLzV%5l2SV+1z67r4&yD3Y7yI3)|u z4Rv)Cz(S@b|xv-=<09d=-%Xf_(jS_WtxqSBHF!TIuMr{qK9jPp}#vBwxWx^s1^AKg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oH)x{IlLVn|8n0s=_f95YFwW$ucGo}P+ zeDZ#rNKyFKgFPq=v@h-)-;$bdYpI7oY?-*X67cNGt80Q~egN(fl@~(F-4Lm$x!9z{ z7p{DSJGXdwb#5D3T`dmq&?fRH;$)_QpbpiWWi~9SE_6pQI5X!#cl9ciS|1~*MSwWS3IG|geP%wj8`deU;f$2F<0_12ac@V_zTM5qiH zx|_U-`E{6j%B|o&!cU>oz}!7M*|WgR8oBv!OXHZKi7btFZ6PxUwzRT1U&_l|PfFr^ z*0(+mxYTahJCGObQ0#)U8mk)vD0RYS@OBg}FE%D~ok6$fOCM$JoC74Qd2^?HGki>^ z&*>sGRSct?_Q&Wt^Wkvp4?v;xc7q4l)*->E`p=*uUXUW;4|e9-2#$Tj^ry?tWFUJs z(=#ZJU9Y1B(fl`p@A>-Z!lduyP&$JI6A$}f72>;Ov8er@WgAok)V98jnqFuOZwq-A zi|>*}&ex{4!?nHY)eQ5&*Jaz0}_FlTW zSlNc(ZR%+Zy9%VfZb!??k;*;};x2qAz|)}KAtJ)O3P?~Z5;4=!1z&46dID)W7FY`& zSntlqItOCehs#)=1$oM7@JT2PoMyW*`y&DWzRS+}QnrJ;gL5{nx>t|b*sZgJ@iEp5 zlFLwSPyYu#$u3Qm;lZ@mR97d>l^b+ks*PrSj6di!y(~_cD1iUUBCA~@UHij literal 0 HcmV?d00001 diff --git a/tests/simpletest/docs/simpletest.org/images/test-with-1-pass.png b/tests/simpletest/docs/simpletest.org/images/test-with-1-pass.png new file mode 100644 index 0000000000000000000000000000000000000000..dbbce1a2eec1e99b028ea9736c1f6733a41c8a46 GIT binary patch literal 10213 zcmeHt^;c9~`0t>A3R0qUycl#NT?*1jNl1663_}l6(jg__(B0iB-Q7cjbT^WB^Ii8J zxOd$jFKYqkoH=LjeV+Y%;&~uYK~4e-g9HNtfnZ5Veo}%!Pdm`|9w;*2KX{-`*JVS>Mp!*4o&} zT>n3Db9-YaTYF3Be>|0Dqs|Zrjh57>kIK#od-E>N$`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ciOizDm9qjalTi*vP!QhB8qBh4@zeUI1kM#tBo9(LC_U2ysb2)CpKkQaP5FCPeo`a z4fx$){nhRk%^uUQsyr`nBG`YM{?v^HSn=2*ZnM{ePOp8^uN~hN5$foDRn%o6bq0ZyMkivk!(R?>7HW)VWG~R@Kd^we?b5a^)V>P?JQ>-?3a+ z)5>agfouD)hecR_VbUdm2cA}$h#)^7;lHue^(us#mH(o^shu(@LM{S6nwypVVCs~dS|cq)8mJ{R`bpD^Yt-SxL#T=Q(9rMBW=5gLK=$vEi4~f1)(&`vPH=ZO3 ze-^r#wV4LQ5p$AG(l}yAvwHTVY-6m}f9_v{t`zt)dh4@p88H+Gy{h<`nCAR5^n1g~ zpr$jI^}-p=S+{C6wu5^j*KWE2s%)NYPS!r%0DO@fM3mm%X7;8!Y`--4K%z*Cs{Q-V zU>ldpb&Z^R-k{eH?E-&GMAhz%B2?U5=W09}!Ug#Ul~|0o)B_b9^dn(#^{v<&bsc@QZvxlctR HdfxvF-at|1 literal 0 HcmV?d00001 diff --git a/tests/simpletest/docs/simpletest.org/index.html b/tests/simpletest/docs/simpletest.org/index.html new file mode 100644 index 00000000..9e4819ca --- /dev/null +++ b/tests/simpletest/docs/simpletest.org/index.html @@ -0,0 +1,174 @@ + + + +SimpleTest - Unit Testing for PHP + + + + + + + + diff --git a/tests/simpletest/docs/simpletest.org/simpletest.css b/tests/simpletest/docs/simpletest.org/simpletest.css new file mode 100644 index 00000000..b08512fc --- /dev/null +++ b/tests/simpletest/docs/simpletest.org/simpletest.css @@ -0,0 +1,44 @@ +/* SimpleTest - Unit Testing for PHP */ +body { font-family : georgia, serif; } +img { border : 0; } +h1 { color : #009933; } +blockquote { background: transparent url('images/quote.png') left top no-repeat; font-style : italic; padding-left : 40px; margin-left : 10px; } + +#logo { margin-bottom : 20px; } +#credits { margin-top : 40px; } +#actions { position : absolute; top : 20px; left : 40px; width : 335px; } +#actions div { width : 305px; } +#content { position : absolute; top : 20px; left : 400px; padding-bottom : 50px; width : 491px; } +#news { border : 2px solid #009933; padding : 20px; font-weight : bold; font-size : 18pt; width : 451px; } +#news a { color : #009933; } + +.screenshot { border : 1px solid #cccccc;} + +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 { + color: black; font-size: 12pt; + text-align: left; + font-weight: bold; +} +pre { + font-family: monospaced; + border-left: 1px solid #999999; + background-color: white; + padding: 5px; + margin-left: 5px; + font-size : 10pt; +} \ No newline at end of file diff --git a/tests/simpletest/docs/source/en/about.xml b/tests/simpletest/docs/source/en/about.xml new file mode 100644 index 00000000..0e311192 --- /dev/null +++ b/tests/simpletest/docs/source/en/about.xml @@ -0,0 +1,115 @@ + + + About Last Craft + +
+

+ + At the moment this site is maintained by myself, + Marcus Baker + and I am an Object Oriented web developer + and father of two. + I am currently a freelancer working as a senior developer for + Wordtracker + and as a consultant to various smaller companies. + Wordtracker is an internet statistics company with a huge database + of search engine keyword popularity. + The company software development is eXtreme Programming based. +

+

+ My wife Aviva Racher is a + microbiologist and Mother of the same two. +

+

+ Bryn was born on the 30th of July 2004. + He is doing very well. +

+
+
+

+ Read the interview + Who's really being protected? on the + O'Reilly network if you have an interest in software patents. +

+
+
+

+ Besides working for Wordtracker, I also act as an independent + consultant. + Usually in relation to bringing agile development practices into an + organisation. + Clients include Waterscape and Amnesty International. +

+

+ I did a quick site for a graphic designer and illustrator friend of mine, + Dylan Beck. + He has a very unique style. +

+

+ The Ambassadors of Om are a Jazz-Funk + fusion (?) band with an internet presence going back over five + years. Site includes samples, videos and links. The band is + managed by guitarist and lead singer Paul Grimes who is a friend of ours. +

+

+ + Mark Eichner is Aviva's uncle and run's the + + Leisure Pursuits + off-road driving school. Lots of wheels and mud! +

+
+
+ + + Last Craft people + Myself and friends and relations. + + + Issues that I care about. + + + Associated companies + and people. + + + + + + Extreme Tuesday + Club is an informal meeting in London to promote + Extreme programming. + + + PHPLondon + is a user group that meets the first thursday of every month. + + + Wordtracker + crunches internet search data for web marketing. + + + + + software development, + computer programmer, + php programming, + programming php, + software development company, + software development uk, + php tutorial, + bespoke software development uk, + corporate web development, + architecture, + freelancer, + php resources, + wordtracker, + web marketing, + serach engines, + web positioning, + internet marketing + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/authentication_documentation.xml b/tests/simpletest/docs/source/en/authentication_documentation.xml new file mode 100644 index 00000000..66d4c9ae --- /dev/null +++ b/tests/simpletest/docs/source/en/authentication_documentation.xml @@ -0,0 +1,316 @@ + + + SimpleTest documentation for testing log-in and authentication + + +

+ One of the trickiest, and yet most important, areas + of testing web sites is the security. + Testing these schemes is one of the core goals of + the SimpleTest web tester. +

+
+
+

+ If you fetch a page protected by basic authentication then + rather than receiving content, you will instead get a 401 + header. + We can illustrate this with this test... + + function test401Header() { + $this->get('http://www.lastcraft.com/protected/'); + $this->showHeaders(); + } +} +]]> + This allows us to see the challenge header... +

+

File test

+
+
1/1 test cases complete. + 0 passes, 0 fails and 0 exceptions.
+
+ We are trying to get away from visual inspection though, and so SimpleTest + allows to make automated assertions against the challenge. + Here is a thorough test of our header... +get('http://www.lastcraft.com/protected/'); + $this->assertAuthentication('Basic'); + $this->assertResponse(401); + $this->assertRealm('SimpleTest basic authentication'); + } +} +]]> + Any one of these tests would normally do on it's own depending + 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... +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. + As soon as the challenge has been issued we can reply with + an authentication response... +get('http://www.lastcraft.com/protected/'); + $this->authenticate('Me', 'Secret'); + $this->assertTitle(...); + } +} +]]> + The username and password will now be sent with every + subsequent request to that directory and subdirectories. + You will have to authenticate again if you step outside + the authenticated directory, but SimpleTest is smart enough + to merge subdirectories into a common realm. +

+

+ You can shortcut this step further by encoding the log in + details straight into the URL... +get('http://Me:Secret@www.lastcraft.com/protected/'); + $this->assertTitle(...); + } +} +]]> + If your username or password has special characters, then you + will have to URL encode them or the request will not be parsed + correctly. + Also this header will not be sent on subsequent requests if + you request a page with a fully qualified URL. + If you navigate with relative URLs though, the authentication + information will be preserved. +

+

+ Only basic authentication is currently supported and this is + only really secure in tandem with HTTPS connections. + This is usually enough to protect test server from prying eyes, + however. + Digest authentication and NTLM authentication may be added + in the future. +

+
+
+

+ Basic authentication doesn't give enough control over the + user interface for web developers. + More likely this functionality will be coded directly into + the web architecture using cookies and complicated timeouts. +

+

+ Starting with a simple log-in form... +


+    Username:
+    
+ Password: +
+ + +]]>
+ Which looks like... +

+

+

+ Username: +
+ Password: +
+ +
+

+

+ Let's suppose that in fetching this page a cookie has been + set with a session ID. + We are not going to fill the form in yet, just test that + we are tracking the user. + Here is the test... +get('http://www.my-site.com/login.php'); + $this->assertCookie('SID'); + } +} +]]> + All we are doing is confirming that the cookie is set. + As the value is likely to be rather cryptic it's not + really worth testing this with... +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. + We wouldn't want to lose track of this after all. + Here is a possible test for this... +get('http://www.my-site.com/login.php'); + $session = $this->getCookie('SID'); + $this->setField('u', 'Me'); + $this->setField('p', 'Secret'); + $this->click('Log in'); + $this->assertText('Welcome Me'); + $this->assertCookie('SID', $session); + } +} +]]> + This confirms that the session identifier is maintained + afer log-in. +

+

+ We could even attempt to spoof our own system by setting + arbitrary cookies to gain access... +get('http://www.my-site.com/login.php'); + $this->setCookie('SID', 'Some other session'); + $this->get('http://www.my-site.com/restricted.php'); + $this->assertText('Access denied'); + } +} +]]> + Is your site protected from this attack? +

+
+
+

+ If you are testing an authentication system a critical piece + of behaviour is what happens when a user logs back in. + We would like to simulate closing and reopening a browser... +get('http://www.my-site.com/login.php'); + $this->setField('u', 'Me'); + $this->setField('p', 'Secret'); + $this->click('Log in'); + $this->assertText('Welcome Me'); + + $this->restart(); + $this->get('http://www.my-site.com/restricted.php'); + $this->assertText('Access denied'); + } +} +]]> + The WebTestCase::restart() method will + preserve cookies that have unexpired timeouts, but throw away + those that are temporary or expired. + You can optionally specify the time and date that the restart + happened. +

+

+ Expiring cookies can be a problem. + After all, if you have a cookie that expires after an hour, + you don't want to stall the test for an hour while the + cookie passes it's timeout. +

+

+ To push the cookies over the hour limit you can age them + before you restart the session... +get('http://www.my-site.com/login.php'); + $this->setField('u', 'Me'); + $this->setField('p', 'Secret'); + $this->click('Log in'); + $this->assertText('Welcome Me'); + + $this->ageCookies(3600); + $this->restart(); + $this->get('http://www.my-site.com/restricted.php'); + $this->assertText('Access denied'); + } +} +]]> + After the restart it will appear that cookies are an + hour older and any that pass their expiry will have + disappeared. +

+
+
+ + + Getting through Basic HTTP authentication + + + Testing cookie based authentication + + + Managing browser sessions and timeouts + + + + + SimpleTest project page on SourceForge. + + + SimpleTest download page on LastCraft. + + + The developer's API for SimpleTest + gives full detail on the classes and assertions available. + + + + + software development, + php programming for clients, + customer focused php, + software development tools, + acceptance testing framework, + free php scripts, + log in boxes, + unit testing authentication systems, + php resources, + HTMLUnit, + JWebUnit, + php testing, + unit test resource, + web testing, + HTTP authentication, + testing log in, + authentication testing, + security tests + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/books_website.xml b/tests/simpletest/docs/source/en/books_website.xml new file mode 100644 index 00000000..98e08bce --- /dev/null +++ b/tests/simpletest/docs/source/en/books_website.xml @@ -0,0 +1,72 @@ + + + Books in and around SimpleTest + +
+

+ From time to time a book is recommanded on the mailing-list, you can find it here + with the original comments ! +

+

+ Domain-Driven Design: Tackling Complexity in the Heart of Software +

+
+ TDD is a lot about the mechanics of coding, but it says you are done + when there is no duplication. DDD considers the code in constant churn, + always renaming as the domain becomes clear and also feeding terms back + into the domain as the code evolves.
+
+ Anyways, it's a great book :) [source] +
+
+
+

+ Two of SimpleTest contributors have written books about PHP. Both have a lot + of examples with the SimpleTest Unit testing framework. +

+

+ PHP|Architect's Guide to PHP Design Patterns +
+ PHP|Architect's Guide to PHP Design Patterns
+ by Jason E. Sweat
+ (get it from : PHP|Architect | + Amazon ) +

+

+ The PHP Anthology: Object Oriented PHP Solutions +
+ The PHP Anthology: Object Oriented PHP Solutions
+ by Harry Fuecks
+ (get it from : SitePoint | + Amazon | + review on Slashdot ) +

+
+
+

+ One way to help the team of contributors is to buy books from this page through + Amazon (with the simpletest-21 tag). We all love reading stuff that's + both interesting and challenging. +

+
+
+ + + Latest recommandation + + + Books by contributors + + + Buying books + + + + + + + + + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/boundary_classes_tutorial.xml b/tests/simpletest/docs/source/en/boundary_classes_tutorial.xml new file mode 100644 index 00000000..0e902407 --- /dev/null +++ b/tests/simpletest/docs/source/en/boundary_classes_tutorial.xml @@ -0,0 +1,408 @@ + + + + PHP unit testing tutorial - Organising unit tests and boundary + class test cases + + +

+ You are probably thinking that we have well and truly exhausted + the Log class by now and that there is + really nothing more to add. + Things are never that simple with object oriented programming, though. + You think you understand a problem and then something comes a long + that challenges your perspective and leads to an even deeper appreciation. + I thought I understood the logging class and that only the first page + of the tutorial would use it. + After that I would move on to something more complicated. + No one is more surprised than me that I still haven't got to + the bottom of it. + In fact I think I have only just figured out what a logger does. +

+

+

Log variations

+

+

+ Supposing that we do not want to log to a file at all. + Perhaps we want to print to the screen, write the messages to a + socket or send them to the Unix(tm) syslog daemon for + dispatching across the network. + How do we incorporate this variation? +

+

+ Simplest is to subclass the Log + overriding the message() method + with new versions. + This will work in the short term, but there is actually something + subtle, but deeply wrong with this. + Suppose we do subclass and have loggers that write to files, + the screen and the network. + Three classes , but that is OK. + Now suppose that we want a new logging class that adds message + filtering by priority, letting only certain types of messages + through according to some configuration file. +

+

+ We are stuck. If we subclass again, we have to do it for all + three classes, giving us six classes. + The amount of duplication is horrible. +

+

+ So are you now wishing that PHP had multiple inheritence? + Well, here that would reduce the short term workload, but + complicate what should be a very simple class. + Multiple inheritance, even when supported, should be used + extremely carefully as all sorts of complicated entanglements + can result. + Treat it as a loaded gun. + In fact, our sudden need for it is telling us something else - perhaps + that we have gone wrong on the conceptual level. +

+

+ What does a logger do? + Does it send messages to a file? + Does it send messages to a network? + Does it send messages to a screen? + Nope. + It just sends messages (full stop). + The target of those messages can be chosen when setting + up the log, but after that the + logger should be left to combine and format the message + elements as that is its real job. + We restricted ourselves by assuming that target was a filename. +

+

+

Abstracting a file to a writer

+

+

+ The solution to this plight is a real classic. + First we encapsulate the variation in a class as this will + add a level of indirection. + Instead of passing in the file name as a string we + will pass the "thing that we will write to" + which we will call a Writer. + Back to the tests... + + require_once('../classes/writer.php'); + Mock::generate('Clock'); + + class TestOfLogging extends UnitTestCase { + function TestOfLogging() { + $this->UnitTestCase('Log class test'); + } + function setUp() { + @unlink('../temp/test.log'); + } + function tearDown() { + @unlink('../temp/test.log'); + } + function getFileLine($filename, $index) { + $messages = file($filename); + return $messages[$index]; + } + function testCreatingNewFile() { + $log = new Log(new FileWriter('../temp/test.log')); + $this->assertFalse(file_exists('../temp/test.log'), 'Created before message'); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('../temp/test.log'), 'File created'); + } + function testAppendingToFile() { + $log = new Log(new FileWriter('../temp/test.log')); + $log->message('Test line 1'); + $this->assertWantedPattern( + '/Test line 1/', + $this->getFileLine('../temp/test.log', 0)); + $log->message('Test line 2'); + $this->assertWantedPattern( + '/Test line 2/', + $this->getFileLine('../temp/test.log', 1)); + } + function testTimestamps() { + $clock = &new MockClock($this); + $clock->setReturnValue('now', 'Timestamp'); + $log = new Log(new FileWriter('../temp/test.log')); + $log->message('Test line', &$clock); + $this->assertWantedPattern( + '/Timestamp/', + $this->getFileLine('../temp/test.log', 0), + 'Found timestamp'); + } + } +?> +]]> + I am going to do this one step at a time so as not to get + confused. + I have replaced the file names with an imaginary + FileWriter class from + a file classes/writer.php. + This will cause the tests to crash as we have not written + the writer yet. + Should we do that now? +

+

+ We could, but we don't have to. + We do need to create the interface, though, or we won't be + able to mock it. + This makes classes/writer.php looks like... + +]]> + We need to modify the Log class + as well... + + require_once('../classes/writer.php'); + + class Log { + var $_writer; + + function Log(&$writer) { + $this->_writer = &$writer; + } + + function message($message, $clock = false) { + if (! is_object($clock)) { + $clock = new Clock(); + } + $this->_writer->write("[" . $clock->now() . "] $message"); + } + } +?> +]]> + There is not much that hasn't changed in our now even smaller + class. + The tests run, but fail at this point unless we add code to + the writer. + What do we do now? +

+

+ We could start writing tests and code the + FileWriter class alongside, but + while we were doing this our Log + tests would be failing and disturbing our focus. + In fact we do not have to. +

+

+ Part of our plan is to free the logging class from the file + system and there is a way to do this. + First we add a tests/writer_test.php so that + we have somewhere to place our test code from log_test.php + that we are going to shuffle around. + I won't yet add it to the all_tests.php file + though as it is the logging aspect we are tackling right now. +

+

+ Now I have done that (honest) we remove any + tests from log_test.php that are not strictly logging + related and move them to writer_test.php for later. + We will also mock the writer so that it does not write + out to real files... + + Mock::generate('FileWriter'); + + class TestOfLogging extends UnitTestCase { + function TestOfLogging() { + $this->UnitTestCase('Log class test'); + } + function testWriting() { + $clock = &new MockClock(); + $clock->setReturnValue('now', 'Timestamp'); + $writer = &new MockFileWriter($this); + $writer->expectArguments('write', array('[Timestamp] Test line')); + $writer->expectCallCount('write', 1); + $log = &new Log(\$writer); + $log->message('Test line', &$clock); + } + } +?> +]]> + Yes that really is the whole test case and it really is that short. + A lot has happened here... +

    +
  1. + The requirement to create the file only when needed has + moved to the FileWriter. +
  2. +
  3. + As we are dealing with mocks, no files are actually + created and so I moved the + setUp() and + tearDown() off into the + writing tests. +
  4. +
  5. + The test now consists of sending a sample message and + testing the format. +
  6. +
+ Hang on a minute, where are the assertions? +

+

+ The mock objects do much more than simply behave like other + objects, they also run tests. + The expectArguments() + call told the mock to expect a single parameter of + the string "[Timestamp] Test line" when + the mock write() method is + called. + When that method is called the expected parameters are + compared with this and either a pass or a fail is sent + to the unit test as a result. +

+

+ The other expectation is that write() + will be called only once. + Simply setting this up is not enough. + We can see all this in action by running the tests... +

+

All tests

+ Pass: log_test.php->Log class test->testwriting->Arguments for [write] were [String: [Timestamp] Test line]
+ Pass: log_test.php->Log class test->testwriting->Expected call count for [write] was [1], but got [1]
+ + Pass: clock_test.php->Clock class test->testclockadvance->Advancement
+ Pass: clock_test.php->Clock class test->testclocktellstime->Now is the right time
+
3/3 test cases complete. + 4 passes and 0 fails.
+
+

+

+ We can actually shorten our test slightly more. + The mock object expectation expectOnce() + can actually combine the two seperate expectations... +setReturnValue('now', 'Timestamp'); + $writer = &new MockFileWriter($this); + $writer->expectOnce('write', array('[Timestamp] Test line')); + $log = &new Log($writer); + $log->message('Test line', &$clock); +} +]]> + This can be an effective shorthand. +

+

+

Boundary classes

+

+

+ Something very nice has happened to the logger besides merely + getting smaller. +

+

+ The only things it depends on now are classes that we have written + ourselves and + in the tests these are mocked and so there are no dependencies + on anything other than our own PHP code. + No writing to files or waiting for clocks to tick over. + This means that the log_test.php test case will + run as fast as the processor will carry it. + By contrast the FileWriter + and Clock classes are very + close to the system. + This makes them harder to test as real data must be moved + around and painstakingly confirmed, often by ad hoc tricks. +

+

+ Our last refactoring has helped a lot. + The hard to test classes on the boundary of the application + and the system are now smaller as the I/O code has + been further separated from the application logic. + They are direct mappings to PHP operations: + FileWriter::write() maps + to PHP fwrite() with the + file opened for appending and + Clock::now() maps to + PHP time(). + This makes debugging easier. + It also means that these classes will change less often. +

+

+ If they don't change a lot then there is no reason to + keep running the tests for them. + This means that tests for the boundary classes can be moved + off into there own test suite leaving the other unit tests + to run at full speed. + In fact this is what I tend to do and the test cases + in SimpleTest itself are + divided this way. +

+

+ That may not sound like much with one unit test and two + boundary tests, but typical applications can have + twenty boundary classes and two hundred application + classes. + To keep these running at full speed you will want + to keep them separate. +

+

+ Besides, separating off decisions of which system components + to use is good development. + Perhaps all this mocking is + improving our design? +

+
+ + + + Handling variation in our logger. + + + Abstracting further with a mock Writer class. + + + Separating Boundary class tests + cleans things up. + + + + + This tutorial follows the Mock objects introduction. + + + Next is test driven design. + + + You will need the SimpleTest testing framework + to try these examples. + + + + + software development, + php programming, + programming php, + software development tools, + php tutorial, + free php scripts, + organizing unit tests, + testing tips, + development tricks, + software architecture for testing, + php example code, + mock objects, + junit port, + test case examples, + php testing, + unit test tool, + php test suite + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/browser_documentation.xml b/tests/simpletest/docs/source/en/browser_documentation.xml new file mode 100644 index 00000000..ed76e77e --- /dev/null +++ b/tests/simpletest/docs/source/en/browser_documentation.xml @@ -0,0 +1,264 @@ + + + SimpleTest documentation for the scriptable web browser component + + +

+ SimpleTest's web browser component can be used not just + outside of the WebTestCase class, but also + independently of the SimpleTest framework itself. +

+
+
+

+ You can use the web browser in PHP scripts to confirm + services are up and running, or to extract information + from them at a regular basis. + For example, here is a small script to extract the current number of + open PHP 5 bugs from the PHP web site... +get('http://php.net/'); + $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]; +?> +]]> + There are simpler methods to do this particular example in PHP + of course. + For example you can just use the PHP file() + command against what here is a pretty fixed page. + However, using the web browser for scripts allows authentication, + correct handling of cookies, automatic loading of frames, redirects, + form submission and the ability to examine the page headers. + Such methods are fragile against a site that is constantly + evolving and you would want a more direct way of accessing + data in a permanent set up, but for simple tasks this can provide + a very rapid solution. +

+

+ All of the navigation methods used in the + WebTestCase + are present in the SimpleBrowser class, but + the assertions are replaced with simpler accessors. + Here is a full list of the page navigation methods... + + + + + + + + + + + + + + + + + + + + + + + +
addHeader($header)Adds a header to every fetch
useProxy($proxy, $username, $password)Use this proxy from now on
head($url, $parameters)Perform a HEAD request
get($url, $parameters)Fetch a page with GET
post($url, $parameters)Fetch a page with POST
clickLink($label)Follows a link by label
isLink($label)See if a link is present by label
clickLinkById($id)Follows a link by attribute
isLinkById($id)See if a link is present by attribut
getUrl()Current URL of page or frame
getTitle()Page title
getContent()Raw page or frame
getContentAsText()HTML removed except for alt text
retry()Repeat the last request
back()Use the browser back button
forward()Use the browser forward button
authenticate($username, $password)Retry page or frame after a 401 response
restart($date)Restarts the browser for a new session
ageCookies($interval)Ages the cookies by the specified time
setCookie($name, $value)Sets an additional cookie
getCookieValue($host, $path, $name)Reads the most specific cookie
getCurrentCookieValue($name)Reads cookie for the current context
+ The methods SimpleBrowser::useProxy() and + SimpleBrowser::addHeader() are special. + Once called they continue to apply to all subsequent fetches. +

+

+ Navigating forms is similar to the + WebTestCase form navigation... + + + + + + + + + + + + +
setField($name, $value)Sets all form fields with that name
setFieldById($id, $value)Sets all form fields with that id
getField($name)Accessor for a form element value
getFieldById($id)Accessor for a form element value
clickSubmit($label)Submits form by button label
clickSubmitByName($name)Submits form by button attribute
clickSubmitById($id)Submits form by button attribute
clickImage($label, $x, $y)Clicks the image by alt text
clickImageByName($name, $x, $y)Clicks the image by attribute
clickImageById($id, $x, $y)Clicks the image by attribute
submitFormById($id)Submits by the form tag attribute
+ At the moment there aren't any methods to list available forms + and fields. + This will probably be added to later versions of SimpleTest. +

+

+ Within a page, individual frames can be selected. + If no selection is made then all the frames are merged together + in one large conceptual page. + The content of the current page will be a concatenation of all of the + frames in the order that they were specified in the "frameset" + tags. + + + + + + +
getFrames()A dump of the current frame structure
getFrameFocus()Current frame label or index
setFrameFocusByIndex($choice)Select a frame numbered from 1
setFrameFocus($name)Select frame by label
clearFrameFocus()Treat all the frames as a single page
+ When focused on a single frame, the content will come from + that frame only. + This includes links to click and forms to submit. +

+
+
+

+ All of this functionality is great when we actually manage to fetch pages, + but that doesn't always happen. + To help figure out what went wrong, the browser has some methods to + aid in debugging... + + + + + + + + + + + + + + + +
setConnectionTimeout($timeout)Close the socket on overrun
getRequest()Raw request header of page or frame
getHeaders()Raw response header of page or frame
getTransportError()Any socket level errors in the last fetch
getResponseCode()HTTP response of page or frame
getMimeType()Mime type of page or frame
getAuthentication()Authentication type in 401 challenge header
getRealm()Authentication realm in 401 challenge header
setMaximumRedirects($max)Number of redirects before page is loaded anyway
setMaximumNestedFrames($max)Protection against recursive framesets
ignoreFrames()Disables frames support
useFrames()Enables frames support
ignoreCookies()Disables sending and receiving of cookies
useCookies()Enables cookie support
+ The methods SimpleBrowser::setConnectionTimeout() + SimpleBrowser::setMaximumRedirects(), + SimpleBrowser::setMaximumNestedFrames(), + 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 + loading, navigate to it using SimpleBrowser::setFrameFocus() + and you can then use SimpleBrowser::getRequest(), etc to + see what happened. +

+
+
+

+ Anything that could be done in a + WebTestCase can + now be done in a UnitTestCase. + This means that we can freely mix domain object testing with the + web interface... + +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->click('Register'); + + $authenticator = &new Authenticator(); + $member = &$authenticator->findByEmail('me@here'); + $this->assertEqual($member->getPassword(), 'Secret'); + } +} +]]> + While this may be a useful temporary expediency, I am not a fan + of this type of testing. + The testing has cut across application layers, make it twice as + likely it will need refactoring when the code changes. +

+

+ A more useful case of where using the browser directly can be helpful + is where the WebTestCase cannot cope. + An example is where two browsers are needed at the same time. +

+

+ For example, say we want to disallow multiple simultaneous + usage of a site with the same username. + This test case will do the job... + + $first = &new SimpleBrowser(); + $first->get('http://my-site.com/login.php'); + $first->setField('name', 'Me'); + $first->setField('password', 'Secret'); + $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->click('Enter'); + $this->assertEqual($second->getTitle(), 'Access Denied'); + } +} +]]> + You can also use the SimpleBrowser class + directly when you want to write test cases using a different + test tool than SimpleTest. +

+
+
+ + + Using the bundled web browser in scripts + + + Debugging failed pages + + + Complex tests with multiple web browsers + + + + + SimpleTest project page on SourceForge. + + + SimpleTest download page on LastCraft. + + + The developer's API for SimpleTest + gives full detail on the classes and assertions available. + + + + + user agent, + web browser php, + fetching pages, + spider scripts, + software development, + php programming for clients, + customer focused php, + software development tools, + acceptance testing framework, + free php scripts, + log in boxes, + unit testing authentication systems, + php resources, + HTMLUnit, + JWebUnit, + php testing, + unit test resource, + web testing, + HTTP authentication, + testing log in, + authentication testing, + security tests + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/display_subclass_tutorial.xml b/tests/simpletest/docs/source/en/display_subclass_tutorial.xml new file mode 100644 index 00000000..38d2a608 --- /dev/null +++ b/tests/simpletest/docs/source/en/display_subclass_tutorial.xml @@ -0,0 +1,273 @@ + + + PHP unit testing tutorial - Subclassing the test display + +

+ The display component of SimpleTest is actually the part + to be developed last. + Some of the following section will change in the future + and hopefully more sophisticated display components will + be written, but + in the meantime if a minimal display is not enough, here + is how to roll your own. +

+

+

I want to see the passes!

+

+

+ Oh all right then, here's how. +

+

+ We have to subclass the attached display, which in our case + is currently HtmlReporter. + The HtmlReporter class is in + the file simpletest/reporter.php and currently has + the following interface... + + Here is what the relevant methods mean. + You can see the + whole list here + if you are interested. +

    +
  • + HtmlReporter()
    + is the constructor. + Note that the unit test sets up the link to the display + rather than the other way around. + The display is a passive receiver of test events. + This allows easy adaption of the display for other test + systems beside unit tests, such as monitoring servers. + It also means that the unit test can write to more than + one display at a time. +
  • +
  • + void paintFail(string $message)
    + paints a failure. + See below. +
  • +
  • + void paintPass(string $message)
    + by default does nothing. + This is the method we will modify. +
  • +
  • + string _getCss()
    + returns the CSS styles as a string for the page header + method. + Additional styles have to be appended here. +
  • +
  • + array getTestList()
    + is a convenience method for subclasses. + Lists the current nesting of the tests as a list + of test names. + The first, most deeply nested test, is first in the + list and the current test method will be last. +
  • +
+

+

+ To show the passes we just need the + paintPass() method to behave + just like paintFail(). + Of course we won't modify the original. + We'll subclass. +

+

+

A display subclass

+

+

+ Firstly we'll create a tests/show_passes.php file + in our logging project and then place in it this empty class... +HtmlReporter(); + } + } +?> +]]> + A quick peruse of the + SimpleTest code base shows the + paintFail() implementation + at the time of writing to look like this... +Fail: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode("->", $breadcrumb); + print "->$message
\n"; +} +]]>
+ Essentially it chains to the parent's version, which we + have to do also to preserve house keeping, and then + prints a breadcrumbs trail calculated from the current test + list. + It drops the top level tests name, though. + As it is the same on every test that would be a little bit too + much information. + Transposing this to our new class... +HtmlReporter(); + } + + function paintPass($message) { + parent::paintPass($message); + print "Pass: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode("->", $breadcrumb); + print "->$message
\n"; + }
+} +]]>
+ So far so good. + Now to make use of our new class we have to modify our + tests/all_tests.php file... + + require_once('show_passes.php'); + + $test = &new TestSuite('All tests'); + $test->addTestFile('log_test.php'); + $test->addTestFile('clock_test.php'); + $test->run(new ShowPasses()); +?> +]]> + We can run this to see the results of our handywork... +

+

All tests

+ Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]
+ Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]
+ Pass: log_test.php->Log class test->testcreatingnewfile->Created before message
+ Pass: log_test.php->Log class test->testcreatingnewfile->File created
+ Pass: clock_test.php->Clock class test->testclockadvance->Advancement
+ Pass: clock_test.php->Clock class test->testclocktellstime->Now is the right time
+
3/3 test cases complete. + 6 passes and 0 fails.
+
+ Nice, but no gold star. + We have lost a little formatting here. + The display does not have a CSS style for + span.pass, but we can add this + easily by overriding one more method... +HtmlReporter(); + } + + function paintPass($message) { + parent::paintPass($message); + print "Pass: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode("->", $breadcrumb); + print "->$message
\n"; + } + + function _getCss() { + return parent::_getCss() . ' .pass { color: green; }'; + } +} +]]>
+ If you are adding the code as you go, you will see the style + appended when you do view source on the test results page in your browser. + To the eye the display itself should now look like this... +
+

All tests

+ Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]
+ Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]
+ Pass: log_test.php->Log class test->testcreatingnewfile->Created before message
+ Pass: log_test.php->Log class test->testcreatingnewfile->File created
+ Pass: clock_test.php->Clock class test->testclockadvance->Advancement
+ Pass: clock_test.php->Clock class test->testclocktellstime->Now is the right time
+
3/3 test cases complete. + 6 passes and 0 fails.
+
+ Some people definitely prefer to see the passes being added + as they are working on code; the feeling that you are getting + work done is nice after all. + Once you have to scroll up and down the page to find failures + though, you soon come to realise its dark side. +

+

+ Try it both ways and see which you prefer. + We'll leave it in for a bit anyhow when looking at the + mock objects coming up. + This is the first test tool that generates additional tests + and it will be useful to see what is happening behind the scenes. +

+
+ + + How to Change the display to show test passes. + + + Subclassing the HtmlReporter class. + + + + + The previous tutorial section was + subclassing the test case. + + + This section is very specific to + SimpleTest. + If you use another tool you will want to skip this. + + + + + software development test first, + php general programming advice, + programming php, + software development tools, + php tutorial, + free php sample code, + architecture, + sample test cases, + php simple test framework, + php resources, + php test case examples, + phpunit, + simpletest, + unit test, + php testing + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/download_website.xml b/tests/simpletest/docs/source/en/download_website.xml new file mode 100644 index 00000000..e8aa3042 --- /dev/null +++ b/tests/simpletest/docs/source/en/download_website.xml @@ -0,0 +1,98 @@ + + + Downloading SimpleTest + +
+

+ The current release is : SimpleTest v1.0.1beta. +

+

+ You can download this version from + SourceForget.net + and your local mirror. You may also want to look at + the current changelog. +

+

+ By the way, don't be scared away by the beta tag : + quite a few users actually use SimpleTest straight from CVS. +

+
+
+

+ If eclipse is your IDE / editor of choice, you might consider + the Eclipse plugin. +

+

+ For automatic "find and install", the URL is : +

http://simpletest.org/eclipse/
+

+
+
+

+ SimpleTest has been packaged by the community to different flavours. +

+ +

+ Note : careful, some versions are not always up-to-date. +

+
+
+

+ The source code is hosted on Sourceforge as well : you can browse + the CVS repository there. +

+
+
+ +
+
+ + + Current release + + + Eclipse release + + + Packages + + + Source + + + Older stable releases + + + + + + + + + SimpleTest, + download, + source code, + stable release, + eclipse release, + eclipse plugin, + debian package, + drupal module, + pear channel, + pearified package + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/expectation_documentation.xml b/tests/simpletest/docs/source/en/expectation_documentation.xml new file mode 100644 index 00000000..d3ddc9ba --- /dev/null +++ b/tests/simpletest/docs/source/en/expectation_documentation.xml @@ -0,0 +1,338 @@ + + + + Extending the SimpleTest unit tester with additional expectation classes + + +
+

+ The default behaviour of the + mock objects + in + SimpleTest + is either an identical match on the argument or to allow any argument at all. + For almost all tests this is sufficient. + Sometimes, though, you want to weaken a test case. +

+

+ One place where a test can be too tightly coupled is with + text matching. + Suppose we have a component that outputs a helpful error + message when something goes wrong. + You want to test that the correct error was sent, but the actual + text may be rather long. + If you test for the text exactly, then every time the exact wording + of the message changes, you will have to go back and edit the test suite. +

+

+ For example, suppose we have a news service that has failed + to connect to its remote source. +class NewsService { + ... + function publish(&$writer) { + if (! $this->isConnected()) { + $writer->write('Cannot connect to news service "' . + $this->_name . '" at this time. ' . + 'Please try again later.'); + } + ... + } +} +]]> + Here it is sending its content to a + Writer class. + We could test this behaviour with a + MockWriter like so... + + $writer = &new MockWriter(); + $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); + } +} +]]> + This is a good example of a brittle test. + If we decide to add additional instructions, such as + suggesting an alternative news source, we will break + our tests even though no underlying functionality + has been altered. +

+

+ To get around this, we would like to do a regular expression + test rather than an exact match. + We can actually do this with... + + $writer->expectOnce( + 'write', + array(new PatternExpectation('/cannot connect/i'))); + + $service = &new NewsService('BBC News'); + $service->publish($writer); + } +} +]]> + Instead of passing in the expected parameter to the + MockWriter we pass an + expectation class called + WantedPatternExpectation. + The mock object is smart enough to recognise this as special + and to treat it differently. + Rather than simply comparing the incoming argument to this + object, it uses the expectation object itself to + perform the test. +

+

+ The WantedPatternExpectation takes + the regular expression to match in its constructor. + Whenever a comparison is made by the MockWriter + against this expectation class, it will do a + preg_match() with this pattern. + With our test case above, as long as "cannot connect" + appears in the text of the string, the mock will issue a pass + to the unit tester. + The rest of the text does not matter. +

+

+ The possible expectation classes are... + + + + + + + + + + + + + +
AnythingExpectationWill always match
EqualExpectationAn equality, rather than the stronger identity comparison
NotEqualExpectationAn inequality comparison
IndenticalExpectationThe default mock object check which must match exactly
NotIndenticalExpectationInverts the mock object logic
WithinMarginExpectationCompares a value to within a margin
OutsideMarginExpectationChecks that a value is out side the margin
PatternExpectationUses a Perl Regex to match a string
NoPatternExpectationPasses only if failing a Perl Regex
IsAExpectationChecks the type or class name only
NotAExpectationOpposite of the IsAExpectation
MethodExistsExpectationChecks a method is available on an object
+ Most take the expected value in the constructor. + The exceptions are the pattern matchers, which take a regular expression, + and the IsAExpectation and NotAExpectation which takes a type + or class name as a string. +

+

+ Some examples... +

+

+expectOnce('method', array(new IdenticalExpectation(14))); +]]> + This is the same as $mock->expectOnce('method', array(14)). +expectOnce('method', array(new EqualExpectation(14))); +]]> + This is different from the previous version in that the string + "14" as a parameter will also pass. + Sometimes the additional type checks of SimpleTest are too restrictive. +expectOnce('method', array(new AnythingExpectation(14))); +]]> + This is the same as $mock->expectOnce('method', array('*')). +expectOnce('method', array(new IdenticalExpectation('*'))); +]]> + This is handy if you want to assert a literal "*". + + This matches on anything other than integer 14. + Even the string "14" would pass. + + This will accept any value from 13.999 to 14.001 inclusive. +

+
+
+

+ The expectation classes can be used not just for sending assertions + 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 a mock authorisation server to simulate a successful login, + but only if it receives a valid session object. + We can do this as follows... + +$authorisation = new MockAuthorisation(); +$authorisation->setReturnValue( + 'isAllowed', + true, + array(new IsAExpectation('Session', 'Must be a session'))); +$authorisation->setReturnValue('isAllowed', false); +]]> + 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. + We have also added a second parameter as a message. + This will be displayed as part of the mock object + failure message if this expectation is the cause of + a failure. +

+

+ This kind of sophistication is rarely useful, but is included for + completeness. +

+
+
+

+ The expectation classes have a very simple structure. + So simple that it is easy to create your own versions for + commonly used test logic. +

+

+ As an example here is the creation of a class to test for + valid IP addresses. + In order to work correctly with the stubs and mocks the new + expectation class should extend + SimpleExpectation... +class ValidIp extends SimpleExpectation { + + function test($ip) { + return (ip2long($ip) != -1); + } + + function testMessage($ip) { + return "Address [$ip] should be a valid IP address"; + } +} +]]> + There are only two methods to implement. + The test() method should + evaluate to true if the expectation is to pass, and + false otherwise. + The testMessage() method + should simply return some helpful text explaining the test + that was carried out. +

+

+ This class can now be used in place of the earlier expectation + classes. +

+
+
+

+ The SimpleTest unit testing framework + also uses the expectation classes internally for the + UnitTestCase class. + We can also take advantage of these mechanisms to reuse our + homebrew expectation classes within the test suites directly. +

+

+ The most crude way of doing this is to use the + SimpleTest::assert() method to + test against it directly... +class TestOfNetworking extends UnitTestCase { + ... + function testGetValidIp() { + $server = &new Server(); + $this->assert( + new ValidIp(), + $server->getIp(), + 'Server IP address->%s'); + } +} +]]> + This is a little untidy compared with our usual + assert...() syntax. +

+

+ For such a simple case we would normally create a + separate assertion method on our test case rather + than bother using the expectation class. + If we pretend that our expectation is a little more + complicated for a moment, so that we want to reuse it, + we get... + + function assertValidIp($ip, $message = '%s') { + $this->assert(new ValidIp(), $ip, $message); + } + + function testGetValidIp() { + $server = &new Server(); + $this->assertValidIp( + $server->getIp(), + 'Server IP address->%s'); + } +} +]]> + It is unlikely we would ever need this degree of control + over the testing machinery. + It is rare to need the expectations for more than pattern + matching. + Also, complex expectation classes could make the tests + harder to read and debug. + These mechanisms are really of most use to authors of systems + that will extend the test framework to create their own tool set. +

+
+
+ + + Using expectations for + more precise testing with mock objects + + + Changing mock object behaviour with expectations + + + Extending the expectations + + + Underneath SimpleTest uses expectation classes + + + + + SimpleTest project page on SourceForge. + + + SimpleTest download page on LastCraft. + + + The expectations mimic the constraints in JMock. + + + Full API for SimpleTest + from the PHPDoc. + + + + + mock objects, + test driven development, + inheritance of expectations, + mock object constraints, + advanced PHP unit testing, + test first, + test framework architecture + expectations in simpletest + test cases + server stubs + + +
diff --git a/tests/simpletest/docs/source/en/first_test_tutorial.xml b/tests/simpletest/docs/source/en/first_test_tutorial.xml new file mode 100644 index 00000000..0c6bdc3b --- /dev/null +++ b/tests/simpletest/docs/source/en/first_test_tutorial.xml @@ -0,0 +1,458 @@ + + + PHP unit testing tutorial - Creating an example test case in PHP + +

+ If you are new to unit testing it is recommended that you + actually try the code out as we go. + There is actually not very much to type and you will get + a feel for the rhythm of test first programming. +

+

+ To run the examples as is, you need an empty directory with the folders + classes, tests and temp. + Unpack the SimpleTest framework + into the tests folder and make sure your web server + can reach these locations. +

+

+

A new test case

+

+

+ The quick introductory example + featured the unit testing of a simple log class. + In this tutorial on Simple Test I am going to try to + tell the whole story of developing this class. + This PHP class is small and simple and in the course of + this introduction will receive far more attention than + it probably would in production. + Yet even this tiny class contains some surprisingly difficult + design decisions. +

+

+ Maybe they are too difficult? + Rather than trying to design the whole thing up front + I'll start with a known requirement, namely + we want to write messages to a file. + These messages must be appended to the file if it exists. + Later we will want priorities and filters and things, but + for now we will place the file writing requirement in + the forefront of our thoughts. + We will think of nothing else for fear of getting confused. + OK, let's make a test... +UnitTestCase(); + } + function testCreatingNewFile() { + } + } + + $test = &new TestOfLogging(); + $test->run(new HtmlReporter()); +?> +]]> + Piece by piece here is what it all means. +

+

+ The SIMPLE_TEST constant + is the path from this file to the Simple Test classes. + The classes could be placed into the path in the + php.ini file, but if you are using a shared + hosting account you do not have access to this. + To keep everybody happy this path is declared explicitely + in the test script. + Later we will see how it eventually ends up in only one + place. +

+

+ Requiring the unit_tester.php library is pretty + clear, but what is this reporter.php + file? + The Simple Test libraries are a toolkit for creating + your own standardised test suite. + They can be used "as is" without trouble, but consist + of separate components that have to be assembled. + reporter.php has a display component. + It is probable that you will eventually write your own + and so including the default set is optional. + Simple test includes a usable, but basic, test display class + called HtmlReporter. + It can record test starts, ends, errors, passes and fails. + It displays this information as quickly as possible in case + the test code crashes the script and obscures the point of + failure. +

+

+ The tests themselves are gathered in test case classes. + This one is typical in extending + UnitTestCase. + When the test is run it will search for any method within + that starts with the name "test" and run it. + Our only test method at present is called + testCreatingNewFile(). + There is nothing in it yet. +

+

+ Now the empty method definition on its own does not do anything. + We need to actually place some code inside it. + The UnitTestCase class + will typically generate test events when run and these events are + sent to an observer. + The UnitTestCase::run() + method runs all of the tests in the class. +

+

+ Now to add test code... + + require_once('../classes/log.php'); + + class TestOfLogging extends UnitTestCase { + function TestOfLogging() { + $this->UnitTestCase(); + } + function testCreatingNewFile() { + @unlink('../temp/test.log'); + $log = new Log('../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()); +?> +]]> +

+

+ You are probably thinking that that is a lot of test code for + just one test and I would agree. + Don't worry. + This is a fixed cost and from now on we can add tests + pretty much as one liners. + Even less when using some of the test artifacts that we + will use later. +

+

+ Now comes the first of our decisions. + Our test file is called log_test.php (any name + is fine) and is in a folder called tests (anywhere is fine). + We have called our code file log.php and this is + the code we are going to test. + I have placed it into a folder called classes, so that means + we are building a class, yes? +

+

+ For this example I am, but the unit tester is not restricted + to testing classes. + It is just that object oriented code is easier to break + down and redesign for testing. + It is no accident that the fine grain testing style of unit + tests has arisen from the object community. +

+

+ The test itself is minimal. + It first deletes any previous test file that may have + been left lying around. + Design decisions now come in thick and fast. + Our class is called Log + and takes the file path in the constructor. + We create a log and immediately send a message to + it using a method named + message(). + Sadly, original naming is not a desirable characteristic + of a software developer. +

+

+ The smallest unit of a...er...unit test is the assertion. + Here we want to assert that the log file we just sent + a message to was indeed created. + UnitTestCase::assertTrue() + will send a pass event if the condition evaluates to + true and a fail event otherwise. + We can have a variety of different assertions and even more + if we extend our base test cases. + Here is the base list... + + + + + + + + + + + + + + + + +
assertTrue(\$x)Fail if \$x is false
assertFalse(\$x)Fail if \$x is true
assertNull(\$x)Fail if \$x is set
assertNotNull(\$x)Fail if \$x not set
assertIsA(\$x, \$t)Fail if \$x is not the class or type \$t
assertEqual(\$x, \$y)Fail if \$x == \$y is false
assertNotEqual(\$x, \$y)Fail if \$x == \$y is true
assertIdentical(\$x, \$y)Fail if \$x === \$y is false
assertNotIdentical(\$x, \$y)Fail if \$x === \$y is true
assertReference(\$x, \$y)Fail unless \$x and \$y are the same variable
assertCopy(\$x, \$y)Fail if \$x and \$y are the same variable
assertWantedPattern(\$p, \$x)Fail unless the regex \$p matches \$x
assertNoUnwantedPattern(\$p, \$x)Fail if the regex \$p matches \$x
assertNoErrors()Fail if any PHP error occoured
assertError(\$x)Fail if no PHP error or incorrect message
+

+

+ We are now ready to execute our test script by pointing the + browser at it. + What happens? + It should crash... +

+ 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 +
+ The reason is that we have not yet created log.php. +

+

+ Hang on, that's silly! + You aren't going to build a test without creating any of the + code you are testing, surely...? +

+

+

Test Driven Development

+

+

+ Co-inventor of + Extreme Programming, + Kent Beck, has come up with another manifesto. + The book is called + Test driven development + or TDD and raises unit testing to a senior position in design. + In a nutshell you write a small test first and + then only get this passing by writing code. + Any code. + Just get it working. +

+

+ You write another test and get that passing. + What you will now have is some duplication and generally lousy + code. + You re-arrange + (refactor) + that code while the tests are passing and thus while you cannot break + anything. + Once the code is as clean as possible you are ready to add more + functionality. + In turn you only achieve this by adding another test and starting the + cycle again. +

+

+ This is a radical approach and one that I feel is incomplete. + However it makes for a great way to explain a unit tester! + We happen to have a failing, not to say crashing, test right now so + let's write some code into log.php... + +]]> + This is the minimum to avoid a PHP fatal error. + We now get the respones... +

+

testoflogging

+ Fail: testcreatingnewfile->True assertion failed.
+
1/1 test cases complete. + 0 passes and 1 fails.
+
+ And "testoflogging" has failed. + PHP has this really annoying effect of reducing class and method + names to lower case internally. + SimpleTest uses these names by default to describe the tests, but + we can replace them with our own... + + $this->UnitTestCase('Log class test'); + } + function testCreatingNewFile() { + @unlink('../temp/test.log'); + $log = new Log('../temp/test.log'); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('../temp/test.log'), 'File created'); + } +} +]]> + Giving... +
+

Log class test

+ Fail: testcreatingnewfile->File created.
+
1/1 test cases complete. + 0 passes and 1 fails.
+
+ There is not much we can do about the method name I am afraid. +

+

+ Test messages like this are a bit like code comments. + Some organisations insist on them while others ban them as clutter + and a waste of good typing. + I am somewhere in the middle. +

+

+ To get the test passing we could just create the file in the + Log constructor. + This "faking it" technique is very useful for checking + that your tests work when the going gets tough. + This is especially so if you have had a run of test failures + and just want to confirm that you haven't just missed something + stupid. + We are not going that slow, so... + + var $_file_path; + + function Log($file_path) { + $this->_file_path = $file_path; + } + + function message($message) { + $file = fopen($this->_file_path, 'a'); + fwrite($file, $message . "\n"); + fclose($file); + } + } +?> +]]> + It took me no less than four failures to get to the next step. + I had not created the temporary directory, I had not made it + publicly writeable, I had one typo and I did not check in the + new directory to CVS. + Any one of these could have kept me busy for several hours if + they had come to light later, but then that is what testing is for. + With the necessary fixes we get... +

+

Log class test

+
1/1 test cases complete. + 1 passes and 0 fails.
+
+ Success! +

+

+ You may not like the rather minimal style of the display. + Passes are not shown by default because generally you do + not need more information when you actually understand what is + going on. + If you do not know what is going on then you should write another test. +

+

+ OK, this is a little strict. + If you want to see the passes as well then you + can subclass the + HtmlReporter class + and attach that to the test instead. + Even I like the comfort factor sometimes. +

+

+

Tests as Documentation

+

+

+ There is a subtlety here. + We don't want the file created until we actually send + a message. + Rather than think about this too deeply we will just add + another test for it... +UnitTestCase('Log class test'); + } + function testCreatingNewFile() { + @unlink('../temp/test.log'); + $log = new Log('../temp/test.log'); + $this->assertFalse(file_exists('../temp/test.log'), 'No file created before first message'); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('../temp/test.log'), 'File created'); + } +} +]]> + ...and find it already works... +

+

Log class test

+
1/1 test cases complete. + 2 passes and 0 fails.
+
+ Actually I knew it would. + I am putting this test in to confirm this partly for peace of mind, but + also to document the behaviour. + That little extra test line says more in this context than + a dozen lines of use case or a whole UML activity diagram. + That the test suite acts as a source of documentation is a pleasant + side effect of all these tests. +

+

+ Should we clean up the temporary file at the end of the test? + I usually do this once I am finished with a test method + and it is working. + I don't want to check in code that leaves remnants of + test files lying around after a test. + I don't do it while I am writing the code, though. + I probably should, but sometimes I need to see what is + going on and there is that comfort thing again. +

+

+ In a real life project we usually have more than one test case, + so we next have to look at + grouping tests into test suites. +

+
+ + Creating a new test case. + Test driven development in PHP. + Tests as documentation is one of many side effects. + + + + The JUnit FAQ + has plenty of useful testing advice. + + + Next is grouping test + cases together. + + + You will need the SimpleTest testing framework + for these examples. + + + + + software development, + php programming, + programming php, + software development tools, + php tutorial, + free php scripts, + architecture, + php resources, + mock objects, + junit, + php testing, + unit test, + automated php testing, + test cases tutorial, + explain unit test case, + unit test example, + unit test + + +
diff --git a/tests/simpletest/docs/source/en/form_testing_documentation.xml b/tests/simpletest/docs/source/en/form_testing_documentation.xml new file mode 100644 index 00000000..1a99f711 --- /dev/null +++ b/tests/simpletest/docs/source/en/form_testing_documentation.xml @@ -0,0 +1,254 @@ + + + Simple Test documentation for testing HTML forms + +
+

+ When a page is fetched by the WebTestCase + using get() or + post() the page content is + automatically parsed. + This results in any form controls that are inside <form> tags + being available from within the test case. + For example, if we have this snippet of HTML... +


+    
+    
+
+]]>
+ Which looks like this... +

+

+

+ + +
+

+

+ We can navigate to this code, via the + LastCraft + site, with the following test... + + function testDefaultValue() { + $this->get('http://www.lastcraft.com/form_testing_documentation.php'); + $this->assertField('a', 'A default'); + } +} +]]> + Immediately after loading the page all of the HTML controls are set at + their default values just as they would appear in the web browser. + The assertion tests that a HTML widget exists in the page with the + name "a" and that it is currently set to the value + "A default". + 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 + the value of the text field and only then submit it... +get('http://www.my-site.com/'); + $this->assertField('a', 'A default'); + $this->setField('a', 'New value'); + $this->click('Go'); + } +} +]]> + Because we didn't specify a method attribute on the form tag, and + didn't specify an action either, the test case will follow + the usual browser behaviour of submitting the form data as a GET + request back to the same location. + SimpleTest tries to emulate typical browser behaviour as much as possible, + rather than attempting to catch missing attributes on tags. + This is because the target of the testing framework is the PHP application + logic, not syntax or other errors in the HTML code. + For HTML errors, other tools such as + HTMLTidy should be used. +

+

+ If a field is not present in any form, or if an option is unavailable, + then WebTestCase::setField() will return + false. + For example, suppose we wish to verify that a "Superuser" + option is not present in this form... +

Select type of user to add:
+
+]]>
+ Which looks like... +

+

+

+ Select type of user to add: + +
+

+

+ The following test will confirm it... + + $this->get('http://www.lastcraft.com/form_testing_documentation.php'); + $this->assertFalse($this->setField('type', 'Superuser')); + } +} +]]> + The selection will not be changed on a failure to set + a widget value. +

+

+ Here is the full list of widgets currently supported... +

    +
  • Text fields, including hidden and password fields.
  • +
  • Submit buttons including the button tag, although not yet reset buttons
  • +
  • Text area. This includes text wrapping behaviour.
  • +
  • Checkboxes, including multiple checkboxes in the same form.
  • +
  • Drop down selections, including multiple selects.
  • +
  • Radio buttons.
  • +
  • Images.
  • +
+

+

+ Although most standard HTML widgets are catered for by SimpleTest's + built in parser, it is unlikely that JavaScript will be implemented + anytime soon. +

+
+
+

+ SimpleTest can cope with two types of multivalue controls: Multiple + selection drop downs, and multiple checkboxes with the same name + within a form. + The multivalue nature of these means that setting and testing + are slightly different. + Using checkboxes as an example... +


+    Create privileges allowed:
+    
+ Retrieve privileges allowed: +
+ Update privileges allowed: +
+ Destroy privileges allowed: +
+ + +]]>
+ Which renders as... +

+

+

+ Create privileges allowed: +
+ Retrieve privileges allowed: +
+ Update privileges allowed: +
+ Destroy privileges allowed: +
+ +
+

+

+ If we wish to disable all but the retrieval privileges and + submit this information we can do it like this... + + 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->click('Enable Privileges'); + } +} +]]> + Instead of setting the field to a single value, we give it a list + of values. + We do the same when testing expected values. + We can then write other test code to confirm the effect of this, perhaps + by logging in as that user and attempting an update. +

+

+

Raw posting

+

+

+ If you want to test a form handler, but have not yet written + or do not have access to the form itself, you can create a + form submission by hand. + + function testAttemptedHack() { + $this->post( + 'http://www.my-site.com/add_user.php', + array('type' => 'superuser')); + $this->assertNoText('user created'); + } +} +]]> + By adding data to the WebTestCase::post() + method, we are attempting to fetch the page as a form submission. +

+
+
+ + + Changing form values and successfully + Submitting a simple form + + + Handling widgets with multiple values + by setting lists. + + + Raw posting when you don't have a button + to click. + + + + + SimpleTest project page on SourceForge. + + + SimpleTest download page on LastCraft. + + + The developer's API for SimpleTest + gives full detail on the classes and assertions available. + + + + + software development, + php programming for clients, + customer focused php, + software development tools, + acceptance testing framework, + free php scripts, + architecture, + php resources, + HTMLUnit, + JWebUnit, + php testing, + unit test resource, + web testing + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/gain_control_tutorial.xml b/tests/simpletest/docs/source/en/gain_control_tutorial.xml new file mode 100644 index 00000000..ddc7c067 --- /dev/null +++ b/tests/simpletest/docs/source/en/gain_control_tutorial.xml @@ -0,0 +1,299 @@ + + + PHP unit testing tutorial - Isolating variables when testing + +

+ In order to test a code module you need very tight control + of its environment. + If anything can vary behind the scenes, for example a + configuration file, then this could cause the tests + to fail unexpectedly. + This would not be a fair test of the code and could + cause you to spend fruitless hours examining code that + is actually working, rather than dealing with the configuration issue + that actually failed the test. + At the very least your test cases get more complicated in + taking account the possible variations. +

+

+

Controlling time

+

+

+ There are often a lot of obvious variables that could affect + a unit test case, especially in the web development + environment in which PHP usually operates. + These include database set up, file permissions, network + resources and configuration amongst others. + The failure or misinstall of one of these components will + break the test suite. + Do we add tests to confirm these components are installed? + This is a good idea, but if you place them into code module + tests you will start to clutter you test code with detail + that is irrelavent to the immediate task. + They should be placed in their own test group. +

+

+ Another problem, though, is that our development machines + must have every system component installed to be able + to run the test suite. + Your tests run slower too. +

+

+ When faced with this while coding we will often create wrapper + versions of classes that deal with these resources. + Ugly details of these resources are then coded once only. + I like to call these classes "boundary classes" + as they exist at the edges of the application, + the interface of your application with the rest of the + system. + These boundary classes are best simulated during testing + by simulated versions. + These run faster as well and are often called + "Server Stubs" or in more generic form + "Mock Objects". + It is a great time saver to wrap and stub out every such resource. +

+

+ One often neglected factor is time. + For example, to test a session time-out coders will often + temporarily set the session time limit to a small value, say two seconds, + and then do a sleep(3) + and assert that the session is now invalid. + That adds three seconds to your test suite and is usually + a lot of extra code making your session classes that maleable. + Far simpler is to have a way to suddenly advance the clock. + To control time. +

+

+

A clock class

+ Again we will design our clock wrapper by writing tests. + Firstly we add a clock test case to our tests/all_tests.php + test suite... + + require_once('clock_test.php'); + + $test = &new TestSuite('All tests'); + $test->addTestCase(new TestOfLogging()); + $test->addTestCase(new TestOfClock()); + $test->run(new HtmlReporter()); +?> +]]> + Then we create the test case in the new file + tests/clock_test.php... +UnitTestCase('Clock class test'); + } + function testClockTellsTime() { + $clock = new Clock(); + $this->assertEqual($clock->now(), time(), 'Now is the right time'); + } + function testClockAdvance() { + } + } +?> +]]> + Our only test at the moment is that our new + Clock class acts + as a simple PHP time() + function substitute. + The other method is a place holder. + It's our TODO item if you like. + We haven't done a test for it yet because that + would spoil our rhythm. + We will write the time shift functionality once we are green. + At the moment we are obviously not green... +
+
+ Fatal error: Failed opening required '../classes/clock.php' (include_path='') in + /home/marcus/projects/lastcraft/tutorial_tests/tests/clock_test.php on line 2 +
+
+ We create a classes/clock.php file like so... + +]]> + This regains our flow ready for coding. +
+

All tests

+ Fail: Clock class test->testclocktellstime->[NULL: ] should be equal to [integer: 1050257362]
+
3/3 test cases complete. + 4 passes and 1 fails.
+
+ This is now easy to fix... + + return time(); + } +} +]]> + And now we are green... +
+

All tests

+
3/3 test cases complete. + 5 passes and 0 fails.
+
+ There is still a problem. + The clock could roll over during the assertion causing the + result to be out by one second. + The chances are small, but if there were a lot of timing tests + you would end up with a test suite that is erratic, severely + limiting its usefulness. + We will tackle this shortly and for now just jot it onto our + "to do" list. +

+

+ The advancement test looks like this... +UnitTestCase('Clock class test'); + } + function testClockTellsTime() { + $clock = new Clock(); + $this->assertEqual($clock->now(), time(), 'Now is the right time'); + } + function testClockAdvance() { + $clock = new Clock(); + $clock->advance(10); + $this->assertEqual($clock->now(), time() + 10, 'Advancement'); + } +} +]]> + The code to get to green is straight forward and just involves adding + a time offset. + + var $_offset; + + function Clock() { + $this->_offset = 0; + } + + function now() { + return time() + $this->_offset; + } + + function advance($offset) { + $this->_offset += $offset; + } +} +]]> +

+

+

Group test tidy up

+ Our all_tests.php file has some repetition we could + do without. + We have to manually add our test cases from each included + file. + It is possible to remove it, but use of the following requires care. + The TestSuite class has a + convenience method called addTestFile() + that takes a PHP file as a parameter. + This mechanism makes a note of all the classes, requires in the + file and then has a look at any newly created classes. + If they are descendents of TestCase + they are added as a new group test. +

+

+ Here is our refactored test suite using this method... + + require_once(SIMPLE_TEST . 'unit_tester.php'); + require_once(SIMPLE_TEST . 'reporter.php'); + + $test = &new TestSuite('All tests'); + $test->addTestFile('log_test.php'); + $test->addTestFile('clock_test.php'); + $test->run(new HtmlReporter()); +?> +]]> + The pitfalls of this are... +

    +
  1. + If the test file has already been included, + no new classes will be added to this group +
  2. +
  3. + If the test file has other classes that are + related to TestCase + then these will be added to the group test as well. +
  4. +
+ In our tests we have only test cases in the test files and + we removed their inclusion from the all_tests.php + script and so we are OK. + This is the usual situation. +

+

+ We should really fix the glitch with the possible + clock rollover so we'll + do this next. +

+
+ + Time is an often neglected variable in tests. + A clock class allows us to alter time. + Tidying the group test. + + + + The previous section is + grouping unit tests. + + + The next section is + subclassing test cases. + + + You will need + the SimpleTest unit tester + for the examples. + + + + + software development, + php programming, + programming php, + software development tools, + php tutorial, + free php scripts, + architecture, + php resources, + mock objects, + junit, + php testing, + unit test, + php testing + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/group_test_documentation.xml b/tests/simpletest/docs/source/en/group_test_documentation.xml new file mode 100644 index 00000000..797af17e --- /dev/null +++ b/tests/simpletest/docs/source/en/group_test_documentation.xml @@ -0,0 +1,330 @@ + + + SimpleTest for PHP test suites + +
+

+ To run test cases as part of a group, the test cases should really + be placed in files without the runner code... + +]]> + As many cases as needed can appear in a single file. + They should include any code they need, such as the library + being tested, but none of the simple test libraries. +

+

+ If you have extended any test cases, you can include them + as well. In PHP 4... + + class MyFileTestCase extends UnitTestCase { + ... + } + SimpleTest::ignore('MyFileTestCase'); + + class FileTester extends MyFileTestCase { ... } + + class SocketTester extends UnitTestCase { ... } +?> +]]> + The FileTester class does + not contain any actual tests, but is a base class for other + test cases. + For this reason we use the + SimpleTestOptions::ignore() directive + to tell the upcoming group test to ignore it. + This directive can appear anywhere in the file and works + when a whole file of test cases is loaded (see below). +

+

+ If you are using PHP 5, you do not need this special directive at all. + Simply mark any test cases that should not be run as abstract... +abstract class MyFileTestCase extends UnitTestCase { + ... +} + +class FileTester extends MyFileTestCase { ... } + +class SocketTester extends UnitTestCase { ... } +]]> +

+

+ We will call this sample file_test.php. + Next we create a group test file, called say my_group_test.php. + You will think of a better name I am sure. +

+

+ We will add the test file using a safe method... + + require_once('file_test.php'); + + $test = &new TestSuite('All file tests'); + $test->addTestCase(new FileTestCase()); + $test->run(new HtmlReporter()); +?> +]]> + This instantiates the test case before the test suite is + run. + This could get a little expensive with a large number of test + cases, and can be surprising behaviour. +

+

+ The main problem is that for every test case + that we add we will have + to require_once() the test code + file and manually instantiate each and every test case. +

+

+ We can save a lot of typing with... + + $test->addTestFile('file_test.php'); + $test->run(new HtmlReporter()); +?> +]]> + What happens here is that the TestSuite + class has done the require_once() + for us. + It then checks to see if any new test case classes + have been created by the new file and automatically adds + them to the group test. + Now all we have to do is add each new file. +

+

+ No only that, but you can guarantee that the constructor is run + just before the first test method and, in PHP 5, the destructor + is run just after the last test method. +

+

+ There are two things that could go wrong and which require care... +

    +
  1. + The file could already have been parsed by PHP, and so no + new classes will have been added. You should make + sure that the test cases are only included in this file + and no others. +
  2. +
  3. + New test case extension classes that get included will be + placed in the group test and run also. + You will need to add a SimpleTestOptions::ignore() + directive for these classes, or make sure that they are included + before the TestSuite::addTestFile() + line, or make sure that they are abstract classes. +
  4. +
+

+
+
+

+ The above method places all of the test cases into one large group. + For larger projects though this may not be flexible enough; you + may want to group the tests in all sorts of ways. +

+

+ To get a more flexible group test we can subclass + TestSuite and then instantiate it as needed... + + class FileTestSuite extends TestSuite { + function FileTestSuite() { + $this->TestSuite('All file tests'); + $this->addTestFile('file_test.php'); + } + } +?> +]]> + This effectively names the test in the constructor and then + adds our test cases and a single group below. + Of course we can add more than one group at this point. + We can now invoke the tests from a separate runner file... + + $test = &new FileTestSuite(); + $test->run(new HtmlReporter()); +?> +]]> + ...or we can group them into even larger group tests. + We can even mix groups and test cases freely as long as + we are careful about double includes... + + $test = &new BigTestSuite('Big group'); + $test->addTestFile('file_test_suite.php'); + $test->addTestFile('some_test_case.php'); + $test->run(new HtmlReporter()); +?> +]]> + In the event of a double include, ony the first instance + of the test case will be run. +

+

+ If we still wish to run the original group test, and we + don't want all of these little runner files, we can + put the test runner code around guard bars when we create + each group. +TestSuite('All file tests'); + $test->addTestFile('file_test.php'); + } + } + + if (! defined('RUNNER')) { + define('RUNNER', true); + $test = &new FileTestSuite(); + $test->run(new HtmlReporter()); + } +?> +]]> + This approach requires the guard to be set when including + the group test file, but this is still less hassle than + lots of separate runner files. + You include the same guard on the top level tests to make sure + that run() will run once only + from the top level script that has been invoked. + + define('RUNNER', true); + require_once('file_test_suite.php'); + + $test = &new BigTestSuite('Big group'); + $test->addTestCase(new FileTestSuite()); + $test->addTestCase(...); + $test->run(new HtmlReporter()); +?> +]]> + As with the normal test cases, a TestSuite can + be loaded with the TestSuite::addTestFile() method. + + $test->addTestFile('file_test_suite.php'); + $test->addTestFile(...); + $test->run(new HtmlReporter()); +?> +]]> +

+
+
+

+ If you already have unit tests for your code or are extending external + classes that have tests, it is unlikely that all of the test cases + are in SimpleTest format. + Fortunately it is possible to incorporate test cases from other + unit testers directly into SimpleTest group tests. +

+

+ Say we have the following + PhpUnit + test case in the file config_test.php... +class ConfigFileTest extends TestCase { + function ConfigFileTest() { + $this->TestCase('Config file test'); + } + + function testContents() { + $config = new ConfigFile('test.conf'); + $this->assertRegexp('/me/', $config->getValue('username')); + } +} +]]> + The group test can recognise this as long as we include + the appropriate adapter class before we add the test + file... + + require_once('simpletest/adapters/phpunit_test_case.php'); + + $test = &new TestSuite('All file tests'); + $test->addTestFile('config_test.php'); + $test->run(new HtmlReporter()); +?> +]]> + There are only two adapters, the other is for the + PEAR + 1.0 unit tester... + + require_once('simpletest/adapters/pear_test_case.php'); + + $test = &new TestSuite('All file tests'); + $test->addTestFile('some_pear_test_cases.php'); + $test->run(new HtmlReporter()); +?> +]]> + The PEAR test cases can be freely mixed with SimpleTest + ones even in the same test file, + but you cannot use SimpleTest assertions in the legacy + test case versions. + This is done as a check that you are not accidently making + your test cases completely dependent on SimpleTest. + You may want to do a PEAR release of your library for example, + which would mean shipping it with valid PEAR::PhpUnit test + cases. +

+
+
+ + + Different ways to group tests together. + + + Combining group tests into larger groups. + + + Integrating legacy test cases from other + types of PHPUnit. + + + + + SimpleTest project page on SourceForge. + + + SimpleTest download page on LastCraft. + + + + + php unit testing, test integration, documentation, marcus baker, simple test, + simpletest documentation, phpunit, pear + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/group_test_tutorial.xml b/tests/simpletest/docs/source/en/group_test_tutorial.xml new file mode 100644 index 00000000..e5399e4a --- /dev/null +++ b/tests/simpletest/docs/source/en/group_test_tutorial.xml @@ -0,0 +1,237 @@ + + + + PHP unit testing tutorial - Grouping together unit + tests and examples of writing test cases + + +

+ Next up we will fill in some blanks and create a test suite. +

+

+

Another test

+

+

+ Adding another test can be as simple as adding another method + to a test case... +UnitTestCase('Log class test'); + } + function testCreatingNewFile() { + @unlink('../temp/test.log'); + $log = new Log('../temp/test.log'); + $this->assertFalse(file_exists('../temp/test.log'), 'Created before message'); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('../temp/test.log'), 'File created'); + @unlink('../temp/test.log'); + } + function testAppendingToFile() { + @unlink('../temp/test.log'); + $log = new Log('../temp/test.log'); + $log->message('Test line 1'); + $messages = file('../temp/test.log'); + $this->assertWantedPattern('/Test line 1/', $messages[0]); + $log->message('Test line 2'); + $messages = file('../temp/test.log'); + $this->assertWantedPattern('/Test line 2/', $messages[1]); + @unlink('../temp/test.log'); + } +} +]]> + The assertWantedPattern() + test case method uses Perl style regular expressions for + matching. +

+

+ All we are doing in this new test method is writing a line to a file and + reading it back twice over. + We simply want to confirm that the logger appends the + text rather than writing over the old file. + A little pedantic, but hey, it's a tutorial! +

+

+ In fact this unit test actually passes straight away... +

+

Log class test

+
1/1 test cases complete. + 4 passes and 0 fails.
+
+ The trouble is there is already a lot of repetition here, + we have to delete the test file before and after every test. + With outrageous plagarism from JUnit, + SimpleTest has setUp() and + tearDown() methods + which are run before and after every test respectively. + File deletion is common to all the test methods so we + should move that operation there. +

+

+ Our tests are green so we can refactor... +UnitTestCase('Log class test'); + } + function setUp() { + @unlink('../temp/test.log'); + } + function tearDown() { + @unlink('../temp/test.log'); + } + function testCreatingNewFile() { + $log = new Log('../temp/test.log'); + $this->assertFalse(file_exists('../temp/test.log'), 'Created before message'); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('../temp/test.log'), 'File created'); + } + function testAppendingToFile() { + $log = new Log('../temp/test.log'); + $log->message('Test line 1'); + $messages = file('../temp/test.log'); + $this->assertWantedPattern('/Test line 1/', $messages[0]); + $log->message('Test line 2'); + $messages = file('../temp/test.log'); + $this->assertWantedPattern('/Test line 2/', $messages[1]); + } +} +]]> + The test stays green. + We can add non-test methods to the test case as long as the method + name does not start with the string "test". + Only the methods that start "test" are run. + This allows further optional refactoring... +UnitTestCase('Log class test'); + } + function setUp() { + @unlink('../temp/test.log'); + } + function tearDown() { + @unlink('../temp/test.log'); + } + function getFileLine($filename, $index) { + $messages = file($filename); + return $messages[$index]; + } + function testCreatingNewFile() { + $log = new Log('../temp/test.log'); + $this->assertFalse(file_exists('../temp/test.log'), 'Created before message'); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('../temp/test.log'), 'File created'); + } + function testAppendingToFile() { + $log = new Log('../temp/test.log'); + $log->message('Test line 1'); + $this->assertWantedPattern('/Test line 1/', $this->getFileLine('../temp/test.log', 0)); + $log->message('Test line 2'); + $this->assertWantedPattern('/Test line 2/', $this->getFileLine('../temp/test.log', 1)); + } +} +]]> + It is a matter of taste whether you prefer this version + to the previous one. There is a little more code, but + the logic of the test is clearer. +

+

+

A group test

+ A test case does not function alone for very long. + When coding for real we usually want to run as many tests as + quickly and as often as we can. + This means grouping them together into test suites that + could easily include every test in the application. +

+

+ Firstly we have to clean out the test running code from + our existing test case... + + require_once('../classes/log.php'); + + class TestOfLogging extends UnitTestCase { + ... + } +?> +]]> + We no longer need the SIMPLE_TEST + constant. + Next we create a group test called all_tests.php + in the tests folder... +addTestCase(new TestOfLogging()); + $test->run(new HtmlReporter()); +?> +]]> + We hardly notice the difference when things work... +

+

All tests

+
1/1 test cases complete. + 4 passes and 0 fails.
+
+ Group tests add to the test case count. + Adding new test cases is very straight forward. + Simply include the test cases file and add any contained test + cases individually. + You can also nest group tests within other group tests + (although you should avoid loops). +

+

+ In the next page + we will add these more quickly. +

+
+ + + Adding another test to the test case + and refactoring. + + + The crude way to group unit tests. + + + + + Next is controlling + how the class under test interacts with the rest + of the system. + + + Previous is the creation + of a first test. + + + You need SimpleTest to run these examples. + + + + + software development, + php programming, + programming in php, + test first, + software development tools, + php tutorial, + free php scripts, + architecture, + php resources, + mock objects, + junit, + php testing, + unit test, + phpunit, + PHP unit testing + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/improving_design_tutorial.xml b/tests/simpletest/docs/source/en/improving_design_tutorial.xml new file mode 100644 index 00000000..92c52269 --- /dev/null +++ b/tests/simpletest/docs/source/en/improving_design_tutorial.xml @@ -0,0 +1,197 @@ + + + + PHP unit testing tutorial - Top down design + test first with mock objects + + +

+

Mock now, code later

+

+

+ I lied. +

+

+ I haven't created a writer test at all, only the + FileWriter interface that I showed + earlier. + In fact I'll go one step further away from a finished article and assume + only an abstract writer in classes/writer.php... +Writer { + + function Writer() { + } + + function write($message) { + } + } +?> +]]> + The corresponding test changes are... + + Mock::generate('Writer'); + + class TestOfLogging extends UnitTestCase { + function TestOfLogging() { + $this->UnitTestCase('Log class test'); + } + function testWriting() { + $clock = &new MockClock($this); + $clock->setReturnValue('now', 'Timestamp'); + $writer = &new MockWriter($this); + $writer->expectOnce('write', array('[Timestamp] Test line')); + $log = &new Log($writer); + $log->message('Test line', &$clock); + $writer->tally(); + } + } +?> +]]> + In order to use the logging class we would need to code a file + writer or other sort of writer, but at the moment we are only + testing and so we do not yet need it. + So, in other words, using mocks we can defer the creation of + lower level objects until we feel like it. + Not only can we design top down, but we can test top down too. +

+

+

Approaching the bridge

+

+

+ Imagine for the moment that we had started the logging class + from another direction. + Pretend that we had coded just enough of the Log + to realise we needed a Writer somehow. + How would we have included it? +

+

+ Well, inheriting from the writer would not have allowed us to mock it + from the testing point of view. + From the design point of view we would have been restricted to + just one writer without multiple inheritence. +

+

+ Creating the writer internally, rather than passing it in the constructor, + by choosing a class name is possible, but we would have less control + of the mock object set up. + From the design point of view it would have been nearly impossible + to pass parameters to the writer in all the different formats ever needed. + You would have to have the writer restricted to say a hash or complicated + string describing the target details. + Needlessly complicated at best. +

+

+ Using a factory method to create the writer internally would be + possible, but would mean subclassing it for testing so that the factory + method could be replaced with one returning a mock. + More work from the test point of view, although still possible. + From the design point of view it would mean a new logger subclass + for every type of writer that we want to use. + This is called a parallel class hiearchy and obviously involves + duplication. + Yuk. +

+

+ At the other extreme, passing or creating the writer on every + message would have been repetitive and reduced the + Log class code to a single + method, a sure sign that the whole class has become redundant. +

+

+ This tension between ease of testing and avoiding repetition + has allowed us to find a flexible and clean design. + Remember our brief yearning for multiple inheritence? + We have replaced it with polymorphism (lots of writers) and separated the + logging hierachy from the writing hierarchy. + We connect the two through this simpler Log + by aggregation. + This trick is actually a design pattern called a "Bridge". +

+

+ So we have been pushed by test code (we haven't written much else yet) + into a design pattern. + Think about this for a second. + Tests improve code quality, certainly in my case, but this is + something far more profound and far more powerful. +

+

+ Testing has improved the design. +

+

+

Mock down design

+

+

+ Creating a mock object is as easy as creating the interface in text + form. + If you have UML or other tools that create these interfaces for you, + then you have an even more flexible route to quickly generate + test objects. + Even if you do not, you can switch from white board drawing, to + writing a test case, to writing a mock, to generating an interface + which takes us back to the whiteboard drawing again, fairly easily. + Like refactoring, design, code and test become unified. +

+

+ Because mock objects work top down they can be bought into the design + more quickly than normal refactoring, which requires at least + partially working code before it kicks in. + This means that the testing code interacts with the design faster + and this means that the design quality goes up sooner. +

+

+ A unit tester is a coding tool. + A unit tester with mock objects is a design tool. +

+
+ + + Mock now, code later. + + + We derive the bridge pattern. + + + Designing and testing hand in hand. + + + + + This tutorial follows Boundary classes. + + + You will need the SimpleTest testing framework + to try these examples. + + + For more mock object discussion see the + Extreme Tuesday Wiki + or the + C2 Wiki + + + + + software development, + php programming tutorial, + programming php test cases, + software development tools, + php tutorial, + free php code, + architecture, + php examples, + mock object examples, + junit style testing, + php testing frameworks, + unit test, + mock objects in PHP, + php testing + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/index.xml b/tests/simpletest/docs/source/en/index.xml new file mode 100644 index 00000000..2124d09d --- /dev/null +++ b/tests/simpletest/docs/source/en/index.xml @@ -0,0 +1,219 @@ + + + + The Last Craft? Web developer tutorials on PHP, Extreme programming + and Object Oriented development + + + +

+ This site focuses mostly on developing with lightweight web technologies such as + PHP, + especially when applied with agile methodologies such as + XP. + No guarantee of quality is given or even intended. + It is hoped only that what you find gives you ideas and enthusiasm + from a fellow computer programmer. +

+

+ I've been a little busy of late with children (two versions). + They take quite a chunk of your professional life and 100% of + what's left! + Hopefully the projects below should start to get back on track. +

+
+
+

+ My latest project is Cgreen. + It's a C unit tester. + There are a couple of C unit testing tools out there already of course. + What makes Cgreen different is that it is pure C99, includes + a tutorial right here and has facilities for creating mock functions. + Mock functions should lead to more decoupled C code if Mock objects are + anything to go by. + It's alpha status right now until I get feedback from other users. + So if you want to be influential, try it out right now. + The project has been mostly funded by Wordtracker, + for which I am very grateful. +

+

+ Along with Jon Ramsey, I am a founder of + PHP London, a PHP user + group not surprisingly based in London. + It's going well. + The networking meetings take place on the first Thursday of every month + at a pub. +

+

+ In addition the group organises other events that include the 2nd + London UK PHP Conference. + This is a one day event on Friday the 23rd of February 2007 and costs only + fifty quid. +

+

+ The SimpleTest PHP unit tester + is available for download from your nearest + SourceForge. + It is a PHP unit test and web test framework. + Users of JUnit will be + familiar with most of the interface. + The JWebUnit + style functionality is more complete now. + It has support for SSL, forms, frames, proxies and basic authentication. + The current CVS code should become the 1.0.1 release real soon now and + includes file upload and many small improvements. + The idea is that common but fiddly PHP tasks, such as logging into a site, + can be tested easily. +

+

+ My most neglected project right now is a requirents testing + and sign-off tool called + Arbiter. + It's actually best described in this + Sitepoint thread, + but basically think of it as a document driven FIT for small + web projects only. + The project is currently stalled due the birth of children and + writing projects. +

+

+ Also on the subject of open source, Wordtracker + have kindly agreed to publish some of their in house tools. + A Wordtracker spin off is fakeMail. + Testing applications that send e-mails can be a right royal pain because + of all of the infrastructure involved. + You will likely need an SMPT gateway that talks to a POP client that + you can read the queue from. + That's a lot of set up. + Fakemail acts as an SMTP gateway on any port + you define. + When you send it a mail it simply copies that mail to the local file + system in whatever directory you want. + You then just have to look at the local file. + It means that you must be able to configure your application to use + a port other than 25, but that's not usualy difficult. +

+
+
+

+ A craft is defined as... +

+ Art or skill; dexterity in particular manual employment; + hence, the occupation or employment itself; manual art; a + trade. +
+

+

+ If you lose a screw or clasp from a hand made jewellery box it is hopeless to + try to find a replacement. Nothing else is quite the same and the mechanism will + fail to work. It may even cause more damage when applied. You need to find the original maker + or someone of the same skill to make you another. + Sound like software? + Yet mechanical parts today are interchangeable. +

+

+ Writing software has resisted mass production. + As soon as a part of it becomes + routine it can be automated. + Once it is you don't need a programmer any more. + Routine programming jobs no longer exist. + All that is left is the unsolved problems that require + a higher level of skill in constructing their solutions. +

+

+ This dependency on the ability of the artisan, combined with nothing quite fitting + together properly, is what gives software the pre-industrial feel. +

+
+
+

+ The panel at the top is supposed to resemble a standard office index card. + The way it is marked out is called a + CRC card. + It stands for Classes, Responsibilities and + Collaborations and is the cheapest software development tool you + can find. + You really do buy a pack of cards. +

+

+ The role is written at the top and would often be just a class + name. + The left side is the object's responsibilities and on the + right collaborations (within the page I have treated these as + internal links and external links repectively). + A group of developers can point at, discuss and discard cards + in the heat of design session. + It makes it especially difficult for only one person to take charge + of a discussion in the way you can with a UML tool or notepad. + Try scribbling out five cards before someone gets a look in. +

+

+ Now nothing beats a whiteboard for collaboration, but if the level + of detail is getting too high and you want a temporary record, + give the CRC cards a try. +

+
+
+ + + Projects under development. + All free and open source software. + + + Why Last Craft? + Odd name isn't it? + + + Why this index card at the top? + + + + + SimpleTest is a PHP unit test framework. + + + My article on TDD + + + My article on the + Registry Pattern. + + + Site E-mail is + SpamCop + filtered which I cannot recommend enough. + + + + + software development, + computer programmer, + php programming, + programming php, + software development tools, + software development company, + php tutorial, + free php scripts, + bespoke software development uk, + corporate web development, + architecture, + php resources, + wordtracker, + xslt, + java, + bug tracker, + bug reporting, + unit test, + php testing, + test cases tutorial, + explain unit test case, + unit test example, + xml + + + A web site of software development tutorials and examples with an + emphasis on web programming, testing, agile methodology and PHP + development + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/intro.xml b/tests/simpletest/docs/source/en/intro.xml new file mode 100644 index 00000000..04a3dbad --- /dev/null +++ b/tests/simpletest/docs/source/en/intro.xml @@ -0,0 +1,54 @@ + + + + The Last Craft? Web developer tutorials on PHP, Extreme programming + and Object Oriented development + + +

+ The SimpleTest PHP unit tester is in + the 1.0.1 release cycle and is available for download from your nearest SourceForge. +

+

+ It is a PHP unit test, mock objects and web test framework. + Users of JUnit will be + familiar with most of the interface. + JWebUnit + style functionality is more complete now. + It has support for SSL, frames, proxies, basic authentication and the + standard HTML controls. + The idea is that common but fiddly PHP tasks, such as logging into a site, + can be tested easily. +

+

+ There is currently no support for JavaScript in the web tester. + For testing these elements we recommend + JSUnit + or + Selenium. +

+
+ + + software development, + computer programmer, + php programming, + programming php, + software development tools, + software development company, + php tutorial, + free php scripts, + bespoke software development uk, + corporate web development, + architecture, + php resources, + unit test, + php testing, + test cases tutorial, + explain unit test case, + unit test example, + xml + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/mock_objects_documentation.xml b/tests/simpletest/docs/source/en/mock_objects_documentation.xml new file mode 100644 index 00000000..63976878 --- /dev/null +++ b/tests/simpletest/docs/source/en/mock_objects_documentation.xml @@ -0,0 +1,698 @@ + + + SimpleTest for PHP mock objects documentation + +
+

+ Mock objects have two roles during a test case: actor and critic. +

+

+ The actor behaviour is to simulate objects that are difficult to + set up or time consuming to set up for a test. + The classic example is a database connection. + Setting up a test database at the start of each test would slow + testing to a crawl and would require the installation of the + database engine and test data on the test machine. + If we can simulate the connection and return data of our + choosing we not only win on the pragmatics of testing, but can + also feed our code spurious data to see how it responds. + We can simulate databases being down or other extremes + without having to create a broken database for real. + In other words, we get greater control of the test environment. +

+

+ If mock objects only behaved as actors they would simply be + known as server stubs. + 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 + return values on demand) they are also sensitive to the + messages sent to them (via expectations). + By setting expected parameters for a method call they act + as a guard that the calls upon them are made correctly. + If expectations are not met they save us the effort of + writing a failed test assertion by performing that duty on our + behalf. +

+

+ In the case of an imaginary database connection they can + test that the query, say SQL, was correctly formed by + the object that is using the connection. + Set them up with fairly tight expectations and you will + hardly need manual assertions at all. +

+
+
+

+ In the same way that we create server stubs, all we need is an + existing class, say a database connection that looks like this... +class DatabaseConnection { + function DatabaseConnection() { + } + + function query() { + } + + function selectQuery() { + } +} +]]> + The class does not need to have been implemented yet. + To create a mock version of the class we need to include the + mock object library and run the generator... +require_once('simpletest/unit_tester.php'); +require_once('simpletest/mock_objects.php'); +require_once('database_connection.php'); + +Mock::generate('DatabaseConnection'); +]]> + This generates a clone class called + MockDatabaseConnection. + We can now create instances of the new class within + our test case... + +class MyTestCase extends UnitTestCase { + + function testSomething() { + $connection = &new MockDatabaseConnection(); + } +} +]]> + Unlike the generated stubs the mock constructor needs a reference + to the test case so that it can dispatch passes and failures while + checking its expectations. + This means that mock objects can only be used within test cases. + Despite this their extra power means that stubs are hardly ever used + if mocks are available. +

+

+

Mocks as actors

+

+

+ The mock version of a class has all the methods of the original, + so that operations like + query()]]> are still + legal. + The return value will be null, + but we can change that with... +$connection->setReturnValue('query', 37) +]]> + Now every time we call + query()]]> we get + the result of 37. + We can set the return value to anything, say a hash of + imaginary database results or a list of persistent objects. + Parameters are irrelevant here, we always get the same + values back each time once they have been set up this way. + That may not sound like a convincing replica of a + database connection, but for the half a dozen lines of + a test method it is usually all you need. +

+

+ We can also add extra methods to the mock when generating it + and choose our own class name... +Mock::generate('DatabaseConnection', 'MyMockDatabaseConnection', array('setOptions')); +]]> + Here the mock will behave as if the setOptions() + existed in the original class. + This is handy if a class has used the PHP overload() + mechanism to add dynamic methods. + You can create a special mock to simulate this situation. +

+

+ 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... + + 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... + + $iterator = &new MockIterator(); + $iterator->setReturnValue('next', false); + $iterator->setReturnValueAt(0, 'next', 'First string'); + $iterator->setReturnValueAt(1, 'next', 'Second string'); + ... + } +} +]]> + When next() is called on the + mock iterator it will first return "First string", + on the second call "Second string" will be returned + and on any other call false will + be returned. + The sequenced return values take precedence over the constant + return value. + The constant one is a kind of default if you like. +

+

+ 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... + + This is a classic situation for using mock objects as + actual configuration will vary from machine to machine, + hardly helping the reliability of our tests if we use it + directly. + The problem though is that all the data comes through the + getValue() method and yet + we want different results for different keys. + Luckily the mocks have a filter system... +$config = &new MockConfiguration(); +$config->setReturnValue('getValue', 'primary', array('db_host')); +$config->setReturnValue('getValue', 'admin', array('db_user')); +$config->setReturnValue('getValue', 'secret', array('db_password')); +]]> + The extra parameter is a list of arguments to attempt + to match. + In this case we are trying to match only one argument which + is the look up key. + Now when the mock object has the + getValue() method invoked + like this... +getValue('db_user') +]]> + ...it will return "admin". + It finds this by attempting to match the calling arguments + to its list of returns one after another until + a complete match is found. +

+

+ You can set a default argument argument like so... + +$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. + The PHP4 copy semantics force us to use a different method + for this. + You might be simulating a container for example... + + In this case you can set a reference into the mock's + return list... + +$vector = &new MockVector(); +$vector->setReturnReference('get', $thing, array(12)); +]]> + With this arrangement you know that every time + 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->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... + + $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. +

+
+
+

+ Although the server stubs approach insulates your tests from + real world disruption, it is only half the benefit. + You can have the class under test receiving the required + messages, but is your new class sending correct ones? + Testing this can get messy without a mock objects library. +

+

+ By way of example, suppose we have a + SessionPool class that we + want to add logging to. + Rather than grow the original class into something more + complicated, we want to add this behaviour with a decorator (GOF). + The SessionPool code currently looks + like this... +class SessionPool { + function SessionPool() { + ... + } + + function &findSession($cookie) { + ... + } + ... +} + +class Session { + ... +} + + While our logging code looks like this... + +class Log { + function Log() { + ... + } + + function message() { + ... + } +} + +class LoggingSessionPool { + function LoggingSessionPool(&$session_pool, &$log) { + ... + } + + function &findSession(\$cookie) { + ... + } + ... +} +]]> + Out of all of this, the only class we want to test here + is the LoggingSessionPool. + In particular we would like to check that the + findSession() method is + called with the correct session ID in the cookie and that + it sent the message "Starting session $cookie" + to the logger. +

+

+ Despite the fact that we are testing only a few lines of + production code, here is what we would have to do in a + conventional test case: +

    +
  1. Create a log object.
  2. +
  3. Set a directory to place the log file.
  4. +
  5. Set the directory permissions so we can write the log.
  6. +
  7. Create a SessionPool object.
  8. +
  9. Hand start a session, which probably does lot's of things.
  10. +
  11. Invoke findSession().
  12. +
  13. Read the new Session ID (hope there is an accessor!).
  14. +
  15. Raise a test assertion to confirm that the ID matches the cookie.
  16. +
  17. Read the last line of the log file.
  18. +
  19. Pattern match out the extra logging timestamps, etc.
  20. +
  21. Assert that the session message is contained in the text.
  22. +
+ It is hardly surprising that developers hate writing tests + when they are this much drudgery. + To make things worse, every time the logging format changes or + the method of creating new sessions changes, we have to rewrite + parts of this test even though this test does not officially + test those parts of the system. + We are creating headaches for the writers of these other classes. +

+

+ Instead, here is the complete test method using mock object magic... + + $session = &new MockSession(); + $pool = &new MockSessionPool(); + $pool->setReturnReference('findSession', $session); + $pool->expectOnce('findSession', array('abc')); + + $log = &new MockLog(); + $log->expectOnce('message', array('Starting session abc')); + + $logging_pool = &new LoggingSessionPool($pool, $log); + $this->assertReference($logging_pool->findSession('abc'), $session); + } +} +]]> + We start by creating a dummy session. + We don't have to be too fussy about this as the check + for which session we want is done elsewhere. + We only need to check that it was the same one that came + from the session pool. +

+

+ findSession() is a factory + method the simulation of which is described above. + The point of departure comes with the first + expectOnce() call. + This line states that whenever + findSession() is invoked on the + mock, it will test the incoming arguments. + If it receives the single argument of a string "abc" + then a test pass is sent to the unit tester, otherwise a fail is + generated. + This was the part where we checked that the right session was asked for. + The argument list follows the same format as the one for setting + return values. + You can have wildcards and sequences and the order of + evaluation is the same. +

+

+ We use the same pattern to set up the mock logger. + We tell it that it should have + message() invoked + once only with the argument "Starting session abc". + By testing the calling arguments, rather than the logger output, + we insulate the test from any display changes in the logger. +

+

+ We start to run our tests when we create the new + LoggingSessionPool and feed + it our preset mock objects. + Everything is now under our control. +

+

+ This is still quite a bit of test code, but the code is very + strict. + If it still seems rather daunting there is a lot less of it + than if we tried this without mocks and this particular test, + interactions rather than output, is always more work to set + up. + More often you will be testing more complex situations without + needing this level or precision. + Also some of this can be refactored into a test case + setUp() method. +

+

+ Here is the full list of expectations you can set on a mock object + in SimpleTest... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExpectationNeeds tally()
expect($method, $args)No
expectAt($timing, $method, $args)No
expectCallCount($method, $count)Yes
expectMaximumCallCount($method, $count)No
expectMinimumCallCount($method, $count)Yes
expectNever($method)No
expectOnce($method, $args)Yes
expectAtLeastOnce($method, $args)Yes
+ Where the parameters are... +

+
$method
+
The method name, as a string, to apply the condition to.
+
$args
+
+ The arguments as a list. Wildcards can be included in the same + manner as for setReturn(). + This argument is optional for expectOnce() + and expectAtLeastOnce(). +
+
$timing
+
+ The only point in time to test the condition. + The first call starts at zero. +
+
$count
+
The number of calls expected.
+
+ The method expectMaximumCallCount() + is slightly different in that it will only ever generate a failure. + It is silent if the limit is never reached. +

+

+ Like the assertions within test cases, all of the expectations + can take a message override as an extra parameter. + Also the original failure message can be embedded in the output + as "%s". +

+
+
+

+ There are three approaches to creating mocks including the one + that SimpleTest employs. + Coding them by hand using a base class, generating them to + a file and dynamically generating them on the fly. +

+

+ Mock objects generated with SimpleTest + are dynamic. + They are created at run time in memory, using + eval(), rather than written + out to a file. + This makes the mocks easy to create, a one liner, + especially compared with hand + crafting them in a parallel class hierarchy. + The problem is that the behaviour is usually set up in the tests + themselves. + If the original objects change the mock versions + that the tests rely on can get out of sync. + This can happen with the parallel hierarchy approach as well, + but is far more quickly detected. +

+

+ The solution, of course, is to add some real integration + tests. + You don't need very many and the convenience gained + from the mocks more than outweighs the small amount of + extra testing. + You cannot trust code that was only tested with mocks. +

+

+ If you are still determined to build static libraries of mocks + because you want to simulate very specific behaviour, you can + achieve the same effect using the SimpleTest class generator. + In your library file, say mocks/connection.php for a + database connection, create a mock and inherit to override + special methods or add presets... + + Mock::generate('Connection', 'BasicMockConnection'); + class MockConnection extends BasicMockConnection { + function MockConnection() { + $this->BasicMockConnection(); + $this->setReturn('query', false); + } + } +?> +]]> + The generate call tells the class generator to create + a class called BasicMockConnection + rather than the usual MockConnection. + We then inherit from this to get our version of + MockConnection. + By intercepting in this way we can add behaviour, here setting + the default value of query() to be false. + By using the default name we make sure that the mock class + generator will not recreate a different one when invoked elsewhere in the + tests. + It never creates a class if it already exists. + As long as the above file is included first then all tests + that generated MockConnection should + now be using our one instead. + If we don't get the order right and the mock library + creates one first then the class creation will simply fail. +

+

+ Use this trick if you find you have a lot of common mock behaviour + or you are getting frequent integration problems at later + stages of testing. +

+
+
+ + + What are mock objects? + + + Creating mock objects. + + + Mocks as actors or stubs. + + + Mocks as critics with expectations. + + + Other approaches including mock libraries. + + + + + The original + Mock objects paper. + + + SimpleTest project page on SourceForge. + + + SimpleTest home page on LastCraft. + + + + + software development, + php programming, + programming php, + software development tools, + php tutorial, + free php scripts, + architecture, + php resources, + mock objects, + junit, + php testing, + unit test, + php testing, + jmock, + nmock + + +
diff --git a/tests/simpletest/docs/source/en/mock_objects_tutorial.xml b/tests/simpletest/docs/source/en/mock_objects_tutorial.xml new file mode 100644 index 00000000..7599aaec --- /dev/null +++ b/tests/simpletest/docs/source/en/mock_objects_tutorial.xml @@ -0,0 +1,361 @@ + + + PHP unit testing tutorial - Using mock objects in PHP + +

+

Refactoring the tests again

+

+

+ Before more functionality is added there is some refactoring + to do. + We are going to do some timing tests and so the + TimeTestCase class definitely needs + its own file. + Let's say tests/time_test_case.php... +UnitTestCase($test_name); + } + function assertSameTime($time1, $time2, $message = '') { + if (! $message) { + $message = "Time [$time1] should match time [$time2]"; + } + $this->assertTrue( + ($time1 == $time2) || ($time1 + 1 == $time2), + $message); + } + } +?> +]]> + We can then require() this file into + the all_tests.php script. +

+

+

Adding a timestamp to the Log

+

+

+ I don't know quite what the format of the log message should + be for the test, so to check for a timestamp we could do the + simplest possible thing, which is to look for a sequence of digits. + + require_once('../classes/clock.php'); + + class TestOfLogging extends TimeTestCase { + function TestOfLogging() { + $this->TimeTestCase('Log class test'); + } + function setUp() { + @unlink('../temp/test.log'); + } + function tearDown() { + @unlink('../temp/test.log'); + } + function getFileLine($filename, $index) { + $messages = file($filename); + return $messages[$index]; + } + function testCreatingNewFile() { + ... + } + function testAppendingToFile() { + ... + } + function testTimestamps() { + $log = new Log('../temp/test.log'); + $log->message('Test line'); + $this->assertTrue( + preg_match('/(\d+)/', $this->getFileLine('../temp/test.log', 0), $matches), + 'Found timestamp'); + $clock = new clock(); + $this->assertSameTime((integer)$matches[1], $clock->now(), 'Correct time'); + } + } +?> +]]> + The test case creates a new Log + object and writes a message. + We look for a digit sequence and then test it against the current + time using our Clock object. + Of course it doesn't work until we write the code. +

+

All tests

+ Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]
+ Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]
+ Pass: log_test.php->Log class test->testcreatingnewfile->Created before message
+ Pass: log_test.php->Log class test->testcreatingnewfile->File created
+ Fail: log_test.php->Log class test->testtimestamps->Found timestamp
+
+ Notice: Undefined offset: 1 in /home/marcus/projects/lastcraft/tutorial_tests/tests/log_test.php on line 44
+ Fail: log_test.php->Log class test->testtimestamps->Correct time
+ Pass: clock_test.php->Clock class test->testclockadvance->Advancement
+ Pass: clock_test.php->Clock class test->testclocktellstime->Now is the right time
+
3/3 test cases complete. + 6 passes and 2 fails.
+
+ The test suite is still showing the passes from our earlier + modification. +

+

+ We can get the tests to pass simply by adding a timestamp + when writing out to the file. + Yes, of course all of this is trivial and + I would not normally test this fanatically, but it is going + to illustrate a more general problem. + The log.php file becomes... + + require_once('../classes/clock.php'); + + class Log { + var $_file_path; + + function Log($file_path) { + $this->_file_path = $file_path; + } + + function message($message) { + $clock = new Clock(); + $file = fopen($this->_file_path, 'a'); + fwrite($file, "[" . $clock->now() . "] $message\n"); + fclose($file); + } + } +?> +]]> + The tests should now pass. +

+

+ Our new test is full of problems, though. + What if our time format changes to something else? + Things are going to be a lot more complicated to test if this + happens. + It also means that any changes to the clock class time + format will cause our logging tests to fail also. + This means that our log tests are tangled up with the clock tests + and extremely fragile. + It lacks cohesion, which is the same as saying it is not + tightly focused, testing facets of the clock as well as the log. + Our problems are caused in part because the clock output + is unpredictable when + all we really want to test is that the logging message + contains the output of + Clock::now(). + We don't + really care about the contents of that method call. +

+

+ Can we make that call predictable? + We could if we could get the log to use a dummy version + of the clock for the duration of the test. + The dummy clock class would have to behave the same way + as the Clock class + except for the fixed output from the + now() method. + Hey, that would even free us from using the + TimeTestCase class! +

+

+ We could write such a class pretty easily although it is + rather tedious work. + We just create another clock class with same interface + except that the now() method + returns a value that we can change with some other setter method. + That is quite a lot of work for a pretty minor test. +

+

+ Except that it is really no work at all. +

+

+

A mock clock

+

+

+ To reach instant testing clock nirvana we need + only three extra lines of code... + + This includes the mock generator code. + It is simplest to place this in the all_tests.php + script as it gets used rather a lot. + + This is the line that does the work. + The code generator scans the class for all of its + methods, creates code to generate an identically + interfaced class, but with the name "Mock" added, + and then eval()s the new code to + create the new class. + + This line can be added to any test method we are interested in. + It creates the dummy clock ready to receive our instructions. +

+

+ Our test case is on the first steps of a radical clean up... + + Mock::generate('Clock'); + + class TestOfLogging extends UnitTestCase { + function TestOfLogging() { + $this->UnitTestCase('Log class test'); + } + function setUp() { + @unlink('../temp/test.log'); + } + function tearDown() { + @unlink('../temp/test.log'); + } + function getFileLine($filename, $index) { + $messages = file($filename); + return $messages[$index]; + } + function testCreatingNewFile() { + ... + } + function testAppendingToFile() { + ... + } + function testTimestamps() { + $clock = &new MockClock($this); + $clock->setReturnValue('now', 'Timestamp'); + $log = new Log('../temp/test.log'); + $log->message('Test line', &$clock); + $this->assertWantedPattern( + '/Timestamp/', + $this->getFileLine('../temp/test.log', 0), + 'Found timestamp'); + } + } +?> +]]> + This test method creates a MockClock + object and then sets the return value of the + now() method to be the string + "Timestamp". + Every time we call $clock->now() + it will return this string. + This should be easy to spot. +

+

+ Next we create our log and send a message. + We pass into the message() + call the clock we would like to use. + This means that we will have to add an optional parameter to + the logging class to make testing possible... +_file_path = $file_path; + } + + function message($message, $clock = false) { + if (!is_object($clock)) { + $clock = new Clock(); + } + $file = fopen($this->_file_path, 'a'); + fwrite($file, "[" . $clock->now() . "] $message\n"); + fclose($file); + } +} +]]> + All of the tests now pass and they test only the logging code. + We can breathe easy again. +

+

+ Does that extra parameter in the Log + class bother you? + We have changed the interface just to facilitate testing after + all. + Are not interfaces the most important thing? + Have we sullied our class with test code? +

+

+ Possibly, but consider this. + Next chance you get, look at a circuit board, perhaps the motherboard + of the computer you are looking at right now. + On most boards you will find the odd empty hole, or solder + joint with nothing attached or perhaps a pin or socket + that has no obvious function. + Chances are that some of these are for expansion and + variations, but most of the remainder will be for testing. +

+

+ Think about that. + The factories making the boards many times over wasting material + on parts that do not add to the final function. + If hardware engineers can make this sacrifice of elegance I am + sure we can too. + Our sacrifice wastes no materials after all. +

+

+ Still bother you? + Actually it bothers me too, but not so much here. + The number one priority is code that works, not prizes + for minimalism. + If it really bothers you, then move the creation of the clock + into another protected factory method. + Then subclass the clock for testing and override the + factory method with one that returns the mock. + Your tests are clumsier, but your interface is intact. +

+

+ Again I leave the decision to you. +

+
+ + + Refactoring the tests so we can reuse + our new time test. + + Adding Log timestamps. + Mocking the clock to make the test cohesive. + + + + This follows the unit test tutorial. + + + Next is distilling boundary classes. + + + You will need the SimpleTest + tool to run the examples. + + + Mock objects papers. + + + + + software development, + php programming, + programming php, + software development tools, + php tutorial, + free php scripts, + architecture, + php resources, + mock objects, + junit, + php testing, + unit test, + php testing + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/overview.xml b/tests/simpletest/docs/source/en/overview.xml new file mode 100644 index 00000000..d5b69e48 --- /dev/null +++ b/tests/simpletest/docs/source/en/overview.xml @@ -0,0 +1,420 @@ + + + + Overview and feature list for the SimpleTest PHP unit tester and web tester + + +
+

+ The heart of SimpleTest is a testing framework built around + test case classes. + These are written as extensions of base test case classes, + each extended with methods that actually contain test code. + Top level test scripts then invoke the run() + methods on every one of these test cases in order. + Each test method is written to invoke various assertions that + the developer expects to be true such as + assertEqual(). + If the expectation is correct, then a successful result is dispatched to the + observing test reporter, but any failure triggers an alert + and a description of the mismatch. +

+

+ A test case looks like this... +MyTestCase extends UnitTestCase { + + function testLogWroteMessage() { + $log = &new Log('my.log'); + $log->message('Hello'); + $this->assertTrue(file_exists('my.log')); + } +} +?> +]]> +

+

+ These tools are designed for the developer. + Tests are written in the PHP language itself more or less + as the application itself is built. + The advantage of using PHP itself as the testing language is that + there are no new languages to learn, testing can start straight away, + and the developer can test any part of the code. + Basically, all parts that can be accessed by the application code can also be + accessed by the test code, if they are in the same programming language. +

+

+ The simplest type of test case is the + UnitTestCase. + This class of test case includes standard tests for equality, + references and pattern matching. + All these test the typical expectations of what you would + expect the result of a function or method to be. + This is by far the most common type of test in the daily + routine of development, making up about 95% of test cases. +

+

+ The top level task of a web application though is not to + produce correct output from its methods and objects, but + to generate web pages. + The WebTestCase class tests web + pages. + It simulates a web browser requesting a page, complete with + cookies, proxies, secure connections, authentication, forms, frames and most + navigation elements. + With this type of test case, the developer can assert that + information is present in the page and that forms and + sessions are handled correctly. +

+

+ A WebTestCase looks like this... +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->assertPattern('/Email me at/'); + } +} +?> +]]> +

+
+
+

+ The following is a very rough outline of past and future features + and their expected point of release. + I am afraid it is liable to change without warning as meeting the + milestones rather depends on time available. + Green stuff has been coded, but not necessarily released yet. + If you have a pressing need for a green but unreleased feature + then you should check-out the code from Sourceforge CVS directly. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureDescriptionRelease
Unit test caseCore test case class and assertions1.0
Html displaySimplest possible display1.0
Autoloading of test cases + Reading a file with test cases and loading them into a + group test automatically + 1.0
Mock objects + Objects capable of simulating other objects removing + test dependencies + 1.0
Web test caseAllows link following and title tag matching1.0
Partial mocks + Mocking parts of a class for testing less than a class + or for complex simulations + 1.0
Web cookie handlingCorrect handling of cookies when fetching pages1.0
Following redirectsPage fetching automatically follows 300 redirects1.0
Form parsingAbility to submit simple forms and read default form values1.0
Command line interfaceTest display without the need of a web browser1.0
Exposure of expectation classesCan create precise tests with mocks as well as test cases1.0
XML output and parsing + Allows multi host testing and the integration of acceptance + testing extensions + 1.0
Browser component + Exposure of lower level web browser interface for more + detailed test cases + 1.0
HTTP authentication + Fetching protected web pages with basic authentication + only + 1.0
SSL supportCan connect to https: pages1.0
Proxy supportCan connect via. common proxies1.0
Frames supportHandling of frames in web test cases1.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
Testing exceptionsSimilar to testing PHP errors1.0.1
HTML label supportCan access all controls using the visual label1.0.1
Code coverageReports using the bundled SpikeSource coverage tool1.0.1
Reporting machinery enhancementsImproved message passing for better cooperation with IDEs1.1
LocalisationMessages abstracted and code generated from XML1.1
IFrame supportReads IFrame content that can be refreshed1.1
Improved mock interfaceMore compact way of expressing mocks using fluent interfaces2.0
Assertion packsCan dynamically add assertions to test cases2.0
HTML table assertionsCan match table elements to numerical assertions2.0
XPath searching of HTML elementsMore flexible content matching2.0
Alternate HTML parsersCan detect compiled parsers for performance improvements2.0
Javascript suportUse of PECL module to add Javascript3.0
+ PHP5 migraton will start straight after the version 1.0.1 series, + whereupon only PHP 5.1+ will be supported. + SimpleTest is currently compatible with PHP 5, but will not + make use of all of the new features until version 2. +

+
+
+

+ Process is at least as important as tools. + The type of process that makes the heaviest use of a developer's + testing tool is of course + Extreme Programming. + This is one of the + Agile Methodologies + which combine various practices to "flatten the cost curve" of software development. + More extreme still is Test Driven Development, + where you very strictly adhere to the rule of no coding until you have a test. + If you're more of a planner, or believe that experience trumps evolution, + you may prefer the + RUP approach. + I haven't tried it, but even I can see that you will need test tools (see figure 9). +

+

+ Most unit testers clone JUnit to some degree, + as far as the interface at least. There is a wealth of information on the + JUnit site including the + FAQ + which contains plenty of general advice on testing. + Once you get bitten by the bug you will certainly appreciate the phrase + test infected + coined by Eric Gamma. + If you are still reviewing which unit tester to use the main choices + are PHPUnit + and Pear PHP::PHPUnit. + They currently lack a lot of features found in + SimpleTest, but the PEAR + version at least has been upgraded for PHP5 and is recommended if you are porting + existing JUnit test cases. +

+

+ There is currently a sad lack of material on mock objects, which is a shame + as unit testing without them is a lot more work. + The original mock objects paper + is very Java focused, but still worth a read. + As a new technology there are plenty of discussions and debate on how to use mocks, + often on Wikis such as + Extreme Tuesday + or www.mockobjects.com + or the original C2 Wiki. + Injecting mocks into a class is the main area of debate for which this + paper on IBM + makes a good starting point. +

+

+ There are plenty of web testing tools, but 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, + HTMLUnit + 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. +

+
+
+ + + Quick summary + of the SimpleTest tool for PHP. + + + List of features, + both current ones and those planned. + + + There are plenty of unit testing resources + on the web. + + + + + Documentation for SimpleTest. + + + How to write PHP test cases + is a fairly advanced tutorial. + + + SimpleTest API from phpdoc. + + + + + software development tools, + php programming, + programming php, + software development tools, + Tools for extreme programming, + free php scripts, + links of testing tools, + php testing resources, + mock objects, + junit, + jwebunit, + htmlunit, + itc, + php testing links, + unit test advice and documentation, + extreme programming in php + + + + + + Marcus Baker + + Primary Developer{@link mailto:marcus@lastcraft.com marcus@lastcraft.com} + + + + Harry Fuecks + + Packager{@link mailto:harryf@users.sourceforge.net harryf@users.sourceforge.net} + + + + Jason Sweat + + Documentation{@link mailto:jsweat_php@yahoo.com jsweat_php@yahoo.com} + + + + +
diff --git a/tests/simpletest/docs/source/en/partial_mocks_documentation.xml b/tests/simpletest/docs/source/en/partial_mocks_documentation.xml new file mode 100644 index 00000000..f28b6dcb --- /dev/null +++ b/tests/simpletest/docs/source/en/partial_mocks_documentation.xml @@ -0,0 +1,401 @@ + + + SimpleTest for PHP partial mocks documentation + + +

+ A partial mock is simply a pattern to alleviate a specific problem + in testing with mock objects, + that of getting mock objects into tight corners. + It's quite a limited tool and possibly not even a good idea. + It is included with SimpleTest because I have found it useful + on more than one occasion and has saved a lot of work at that point. +

+
+
+

+ When one object uses another it is very simple to just pass a mock + version in already set up with its expectations. + Things are rather tricker if one object creates another and the + creator is the one you want to test. + This means that the created object should be mocked, but we can + hardly tell our class under test to create a mock instead. + The tested class doesn't even know it is running inside a test + after all. +

+

+ For example, suppose we are building a telnet client and it + needs to create a network socket to pass its messages. + The connection method might look something like... +read( ... ); + ... + } + } +?> +]]> + We would really like to have a mock object version of the socket + here, what can we do? +

+

+ The first solution is to pass the socket in as a parameter, + forcing the creation up a level. + Having the client handle this is actually a very good approach + if you can manage it and should lead to factoring the creation from + the doing. + In fact, this is one way in which testing with mock objects actually + forces you to code more tightly focused solutions. + They improve your programming. +

+

+ Here this would be... +function &connect(&$socket, $username, $password) { + $socket->read( ... ); + ... + } + } +?> +]]> + This means that the test code is typical for a test involving + mock objects. + + $socket = &new MockSocket($this); + ... + $telnet = &new Telnet(); + $telnet->connect($socket, 'Me', 'Secret'); + ... + } +} +]]> + It is pretty obvious though that one level is all you can go. + You would hardly want your top level application creating + every low level file, socket and database connection ever + needed. + It wouldn't know the constructor parameters anyway. +

+

+ The next simplest compromise is to have the created object passed + in as an optional parameter... + + function &connect($ip, $port, $username, $password, $socket = false) { + if (!$socket) { + $socket = &new Socket($ip, $port); + } + $socket->read( ... ); + ... + return $socket; + } + } +?> +]]> + For a quick solution this is usually good enough. + The test now looks almost the same as if the parameter + was formally passed... + + $socket = &new MockSocket($this); + ... + $telnet = &new Telnet(); + $telnet->connect('127.0.0.1', 21, 'Me', 'Secret', &$socket); + ... + } +} +]]> + The problem with this approach is its untidiness. + There is test code in the main class and parameters passed + in the test case that are never used. + This is a quick and dirty approach, but nevertheless effective + in most situations. +

+

+ The next method is to pass in a factory object to do the creation... + + function Telnet(&$network) { + $this->_network = &$network; + } + ... + function &connect($ip, $port, $username, $password) { + $socket = &$this->_network->createSocket($ip, $port); + $socket->read( ... ); + ... + return $socket; + } + } +?> +]]> + This is probably the most highly factored answer as creation + is now moved into a small specialist class. + The networking factory can now be tested separately, but mocked + easily when we are testing the telnet class... + + $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'); + ... + } +} +]]> + The downside is that we are adding a lot more classes to the + library. + Also we are passing a lot of factories around which will + make the code a little less intuitive. + The most flexible solution, but the most complex. +

+

+ Is there a middle ground? +

+
+
+

+ There is a way we can circumvent the problem without creating + any new application classes, but it involves creating a subclass + when we do the actual testing. + Firstly we move the socket creation into its own method... + + $socket = &$this->_createSocket($ip, $port); + $socket->read( ... ); + ... + } + + function &_createSocket($ip, $port) { + return new Socket($ip, $port); + } + } +?> +]]> + This is the only change we make to the application code. +

+

+ For the test case we have to create a subclass so that + we can intercept the socket creation... +class TelnetTestVersion extends Telnet { + var $_mock; + + function TelnetTestVersion(&$mock) { + $this->_mock = &$mock; + $this->Telnet(); + } + + function &_createSocket() { + return $this->_mock; + } +} +]]> + Here I have passed the mock in the constructor, but a + setter would have done just as well. + Note that the mock was set into the object variable + before the constructor was chained. + This is necessary in case the constructor calls + connect(). + Otherwise it could get a null value from + _createSocket(). +

+

+ After the completion of all of this extra work the + actual test case is fairly easy. + We just test our new class instead... + + $socket = &new MockSocket($this); + ... + $telnet = &new TelnetTestVersion($socket); + $telnet->connect('127.0.0.1', 21, 'Me', 'Secret'); + ... + } +} +]]> + The new class is very simple of course. + It just sets up a return value, rather like a mock. + It would be nice if it also checked the incoming parameters + as well. + Just like a mock. + It seems we are likely to do this often, can + we automate the subclass creation? +

+
+
+

+ Of course the answer is "yes" or I would have stopped writing + this by now! + The previous test case was a lot of work, but we can + generate the subclass using a similar approach to the mock objects. +

+

+ Here is the partial mock version of the test... +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'); + ... + } +} +]]> + The partial mock is a subclass of the original with + selected methods "knocked out" with test + versions. + The generatePartial() call + takes three parameters: the class to be subclassed, + the new test class name and a list of methods to mock. +

+

+ Instantiating the resulting objects is slightly tricky. + The only constructor parameter of a partial mock is + the unit tester reference. + As with the normal mock objects this is needed for sending + test results in response to checked expectations. +

+

+ The original constructor is not run yet. + This is necessary in case the constructor is going to + make use of the as yet unset mocked methods. + We set any return values at this point and then run the + constructor with its normal parameters. + This three step construction of "new", followed + by setting up the methods, followed by running the constructor + proper is what distinguishes the partial mock code. +

+

+ Apart from construction, all of the mocked methods have + the same features as mock objects and all of the unmocked + methods behave as before. + We can set expectations very easily... +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(); + } +} +]]> +

+
+
+

+ The mocked out methods don't have to be factory methods, + they could be any sort of method. + In this way partial mocks allow us to take control of any part of + a class except the constructor. + We could even go as far as to mock every method + except one we actually want to test. +

+

+ This last situation is all rather hypothetical, as I haven't + tried it. + I am open to the possibility, but a little worried that + forcing object granularity may be better for the code quality. + I personally use partial mocks as a way of overriding creation + or for occasional testing of the TemplateMethod pattern. +

+

+ It's all going to come down to the coding standards of your + project to decide which mechanism you use. +

+
+
+ + + The mock injection problem. + + + Moving creation to a protected factory method. + + + Partial mocks generate subclasses. + + + Partial mocks test less than a class. + + + + + SimpleTest project page on SourceForge. + + + Full API for SimpleTest + from the PHPDoc. + + + The protected factory is described in + this paper from IBM. + This is the only formal comment I have seen on this problem. + + + + + php software development, + php test case development, + database programming php, + software development tools, + php advanced tutorial, + phpunit style scripts, + architecture, + php resources, + mock objects, + junit, + php test framework, + unit test, + php testing + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/reporter_documentation.xml b/tests/simpletest/docs/source/en/reporter_documentation.xml new file mode 100644 index 00000000..9bbe4317 --- /dev/null +++ b/tests/simpletest/docs/source/en/reporter_documentation.xml @@ -0,0 +1,470 @@ + + + SimpleTest for PHP test runner and display documentation + + +

+ SimpleTest pretty much follows the MVC pattern + (Model-View-Controller). + The reporter classes are the view and the model is your + test cases and their hiearchy. + The controller is mostly hidden from the user of + SimpleTest unless you want to change how the test cases + are actually run, in which case it is possible to + override the runner objects from within the test case. + As usual with MVC, the controller is mostly undefined + and there are other places to control the test run. +

+
+
+

+ The default test display is minimal in the extreme. + It reports success and failure with the conventional red and + green bars and shows a breadcrumb trail of test groups + for every failed assertion. + Here's a fail... +

+

File test

+ Fail: createnewfile->True assertion failed.
+
1/1 test cases complete. + 0 passes, 1 fails and 0 exceptions.
+
+ And here all tests passed... +
+

File test

+
1/1 test cases complete. + 1 passes, 0 fails and 0 exceptions.
+
+ The good news is that there are several points in the display + hiearchy for subclassing. +

+

+ For web page based displays there is the + HtmlReporter class with the following + signature... + + Here is what some of these methods mean. First the display methods + that you will probably want to override... +

    +
  • + HtmlReporter(string $encoding)
    + is the constructor. + Note that the unit test sets up the link to the display + rather than the other way around. + The display is a mostly passive receiver of test events. + This allows easy adaption of the display for other test + systems beside unit tests, such as monitoring servers. + The encoding is the character encoding you wish to + display the test output in. + In order to correctly render debug output when + using the web tester, this should match the encoding + of the site you are trying to test. + The available character set strings are described in + the PHP html_entities() + function. +
  • +
  • + void paintHeader(string $test_name)
    + is called once at the very start of the test when the first + start event arrives. + The first start event is usually delivered by the top level group + test and so this is where $test_name + comes from. + It paints the page titles, CSS, body tag, etc. + It returns nothing (void). +
  • +
  • + void paintFooter(string $test_name)
    + Called at the very end of the test to close any tags opened + by the page header. + By default it also displays the red/green bar and the final + count of results. + Actually the end of the test happens when a test end event + comes in with the same name as the one that started it all + at the same level. + The tests nest you see. + Closing the last test finishes the display. +
  • +
  • + void paintMethodStart(string $test_name)
    + is called at the start of each test method. + The name normally comes from method name. + The other test start events behave the same way except + that the group test one tells the reporter how large + it is in number of held test cases. + This is so that the reporter can display a progress bar + as the runner churns through the test cases. +
  • +
  • + void paintMethodEnd(string $test_name)
    + backs out of the test started with the same name. +
  • +
  • + void paintFail(string $message)
    + paints a failure. + By default it just displays the word fail, a breadcrumbs trail + showing the current test nesting and the message issued by + the assertion. +
  • +
  • + void paintPass(string $message)
    + by default does nothing. +
  • +
  • + string _getCss()
    + Returns the CSS styles as a string for the page header + method. + Additional styles have to be appended here if you are + not overriding the page header. + You will want to use this method in an overriden page header + if you want to include the original CSS. +
  • +
+ There are also some accessors to get information on the current + state of the test suite. + Use these to enrich the display... +
    +
  • + array getTestList()
    + is the first convenience method for subclasses. + Lists the current nesting of the tests as a list + of test names. + The first, most deeply nested test, is first in the + list and the current test method will be last. +
  • +
  • + integer getPassCount()
    + returns the number of passes chalked up so far. + Needed for the display at the end. +
  • +
  • + integer getFailCount()
    + is likewise the number of fails so far. +
  • +
  • + integer getExceptionCount()
    + is likewise the number of errors so far. +
  • +
  • + integer getTestCaseCount()
    + is the total number of test cases in the test run. + This includes the grouping tests themselves. +
  • +
  • + integer getTestCaseProgress()
    + is the number of test cases completed so far. +
  • +
+ One simple modification is to get the HtmlReporter to display + the passes as well as the failures and errors... +class ShowPasses extends HtmlReporter { + + function paintPass($message) { + parent::paintPass($message); + print "&Pass: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode("->", $breadcrumb); + print "->$message
\n"; + } + + function _getCss() { + return parent::_getCss() . ' .pass { color: green; }'; + } +} +]]>
+

+

+ One method that was glossed over was the makeDry() + method. + If you run this method, with no parameters, on the reporter + before the test suite is run no actual test methods + will be called. + You will still get the events of entering and leaving the + test methods and test cases, but no passes or failures etc, + because the test code will not actually be executed. +

+

+ The reason for this is to allow for more sophistcated + GUI displays that allow the selection of individual test + cases. + In order to build a list of possible tests they need a + report on the test structure for drawing, say a tree view + of the test suite. + With a reporter set to dry run that just sends drawing events + this is easily accomplished. +

+
+
+

+ Rather than simply modifying the existing display, you might want to + produce a whole new HTML look, or even generate text or XML. + Rather than override every method in + HtmlReporter we can take one + step up the class hiearchy to SimpleReporter + in the simple_test.php source file. +

+

+ A do nothing display, a blank canvas for your own creation, would + be... +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); + } +} +]]> + No output would come from this class until you add it. +

+
+
+

+ SimpleTest also ships with a minimal command line reporter. + The interface mimics JUnit to some extent, but paints the + failure messages as they arrive. + To use the command line reporter simply substitute it + for the HTML version... +addTestFile('tests/file_test.php'); + $test->run(new TextReporter()); +?> +]]> + Then invoke the test suite from the command line... +

+php file_test.php
+
+ You will need the command line version of PHP installed + of course. + A passing test suite looks like this... +
+File test
+OK
+Test cases run: 1/1, Failures: 0, Exceptions: 0
+
+ A failure triggers a display like this... +
+File test
+1) True assertion failed.
+	in createnewfile
+FAILURES!!!
+Test cases run: 1/1, Failures: 1, Exceptions: 0
+
+

+

+ One of the main reasons for using a command line driven + test suite is of using the tester as part of some automated + process. + To function properly in shell scripts the test script should + return a non-zero exit code on failure. + If a test suite fails the value false + is returned from the SimpleTest::run() + method. + We can use that result to exit the script with the desired return + code... +addTestFile('tests/file_test.php'); + exit ($test->run(new TextReporter()) ? 0 : 1); +?> +]]> + Of course we don't really want to create two test scripts, + a command line one and a web browser one, for each test suite. + The command line reporter includes a method to sniff out the + run time environment... +addTestFile('tests/file_test.php'); + if (TextReporter::inCli()) { + exit ($test->run(new TextReporter()) ? 0 : 1); + } + $test->run(new HtmlReporter()); +?> +]]> + This is the form used within SimpleTest itself. +

+
+
+

+ SimpleTest ships with an XmlReporter class + used for internal communication. + When run the output looks like... +


+
+  
+    Remote tests
+    
+      Visual test with 48 passes, 48 fails and 4 exceptions
+      
+        testofunittestcaseoutput
+        
+          testofresults
+          This assertion passed
+          This assertion failed
+        
+        
+          ...
+        
+      
+    
+  
+
+]]>
+ You can make use of this format with the parser + supplied as part of SimpleTest itself. + This is called SimpleTestXmlParser and + resides in xml.php within the SimpleTest package... +parse($test_output); +?> +]]> + The $test_output should be the XML format + from the XML reporter, and could come from say a command + line run of a test case. + The parser sends events to the reporter just like any + other test run. + There are some odd occasions where this is actually useful. +

+

+ A problem with large test suites is thet they can exhaust + the default 8Mb memory limit on a PHP process. + By having the test groups output in XML and run in + separate processes, the output can be reparsed to + aggregate the results into a much smaller footprint top level + test. +

+

+ Because the XML output can come from anywhere, this opens + up the possibility of aggregating test runs from remote + servers. + A test case already exists to do this within the SimpleTest + framework, but it is currently experimental... +require_once('../remote.php'); + require_once('../reporter.php'); + + $test_url = ...; + $dry_url = ...; + + $test = &new TestSuite('Remote tests'); + $test->addTestCase(new RemoteTestCase($test_url, $dry_url)); + $test->run(new HtmlReporter()); +?> +]]> + The RemoteTestCase takes the actual location + of the test runner, basically a web page in XML format. + It also takes the URL of a reporter set to do a dry run. + This is so that progress can be reported upward correctly. + The RemoteTestCase can be added to test suites + just like any other group test. +

+
+
+ + + Displaying results in HTML + + + Displaying and reporting results + in other formats + + + Using SimpleTest from the command line + + + Using Using XML for remote testing + + + + + SimpleTest project page on SourceForge. + + + SimpleTest download page on LastCraft. + + + The developer's API for SimpleTest + gives full detail on the classes and assertions available. + + + + + php unit testing, + documentation, + marcus baker, + simple test, + simpletest, + remote testing, + xml tests, + automated testing + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/simple_test.xml b/tests/simpletest/docs/source/en/simple_test.xml new file mode 100644 index 00000000..4a127c38 --- /dev/null +++ b/tests/simpletest/docs/source/en/simple_test.xml @@ -0,0 +1,466 @@ + + + + Download the Simple Test testing framework - + Unit tests and mock objects for PHP + + + + 1.0.1 release cycle started. + Features include include file upload, better PHP5 support for + mock objects, and HTML label support. + There is also a big clean up of method names and some internals + refactoring. + + +

+ The following assumes that you are familiar with the concept + of unit testing as well as the PHP web development language. + It is a guide for the impatient new user of + SimpleTest. + For fuller documentation, especially if you are new + to unit testing see the ongoing + documentation, and for + example test cases see the + unit testing tutorial. +

+
+
+

+ Amongst software testing tools, a unit tester is the one + closest to the developer. + In the context of agile development the test code sits right + next to the source code as both are written simultaneously. + In this context SimpleTest aims to be a complete PHP developer + test solution and is called "Simple" because it + should be easy to use and extend. + It wasn't a good choice of name really. + It includes all of the typical functions you would expect from + JUnit and the + PHPUnit + ports, but also adds + mock objects. + It has some JWebUnit + functionality as well. + This includes web page navigation, cookie testing and form submission. +

+

+ The quickest way to demonstrate is with an example. +

+

+ Let us suppose we are testing a simple file logging class called + Log in classes/log.php. + We start by creating a test script which we will call + tests/log_test.php and populate it as follows... + +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 + takes the file name to write to in the constructor and we have + a temporary folder in which to place this file... + + function testCreatingNewFile() { + @unlink('/temp/test.log'); + $log = new Log('/temp/test.log'); + $this->assertFalse(file_exists('/temp/test.log')); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('/temp/test.log')); + } +} +?> +]]> + When a test case runs it will search for any method that + starts with the string test + and execute that method. + We would normally have more than one test method of course. + Assertions within the test methods trigger messages to the + test framework which displays the result immediately. + This immediate response is important, not just in the event + of the code causing a crash, but also so that + print statements can display + their content right next to the test case concerned. +

+

+ To see these results we have to actually run the tests. + If this is the only test case we wish to run we can achieve + it with... +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()); +?> +]]> +

+

+ On failure the display looks like this... +

+

testoflogging

+ Fail: testcreatingnewfile->True assertion failed.
+
1/1 test cases complete. + 1 passes and 1 fails.
+
+ ...and if it passes like this... +
+

testoflogging

+
1/1 test cases complete. + 2 passes and 0 fails.
+
+ And if you get this... +
+ Fatal error: Failed opening required '../classes/log.php' (include_path='') in /home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php on line 7 +
+ it means you're missing the classes/Log.php file that could look like... +; +]]> +

+
+
+

+ It is unlikely in a real application that we will only ever run + one test case. + This means that we need a way of grouping cases into a test + script that can, if need be, run every test in the application. +

+

+ Our first step is to strip the includes and to undo our + previous hack... + +require_once('../classes/log.php'); + +class TestOfLogging extends UnitTestCase { + + function testCreatingNewFile() { + @unlink('/temp/test.log'); + $log = new Log('/temp/test.log'); + $this->assertFalse(file_exists('/temp/test.log')); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('/temp/test.log')); + } +} +?> +]]> + Next we create a new file called tests/all_tests.php + and insert the following code... +addTestFile('log_test.php'); +$test->run(new HtmlReporter()); +?> +]]> + The method TestSuite::addTestFile() + will include the test case file and read any new classes created + that are descended from SimpleTestCase, of which + UnitTestCase is one example. + Just the class names are stored for now, so that the test runner + can instantiate the class when it works its way + through your test suite. +

+

+ For this to work properly the test case file should not blindly include + any other test case extensions that do not actually run tests. + This could result in extra test cases being counted during the test + run. + Hardly a major problem, but to avoid this inconvenience simply add + a SimpleTestOptions::ignore() directive + somewhere in the test case file. + Also the test case file should not have been included + elsewhere or no cases will be added to this group test. + This would be a more serious error as if the test case classes are + already loaded by PHP the TestSuite::addTestFile() + method will not detect them. +

+

+ To display the results it is necessary only to invoke + tests/all_tests.php from the web server. +

+
+
+

+ Let's move further into the future. +

+

+ Assume that our logging class is tested and completed. + Assume also that we are testing another class that is + required to write log messages, say a + SessionPool. + We want to test a method that will probably end up looking + like this... + +class SessionPool { + ... + function logIn($username) { + ... + $this->_log->message("User $username logged in."); + ... + } + ... +} + +]]> + In the spirit of reuse we are using our + Log class. + A conventional test case might look like this... + +logIn('fred'); + $messages = file('/temp/test.log'); + $this->assertEqual($messages[0], "User fred logged in.\n"); + } +} +?> +]]> + This test case design is not all bad, but it could be improved. + We are spending time fiddling with log files which are + not part of our test. Worse, we have created close ties + with the Log class and + this test. + What if we don't use files any more, but use ths + syslog library instead? + Did you notice the extra carriage return in the message? + Was that added by the logger? + What if it also added a time stamp or other data? +

+

+ The only part that we really want to test is that a particular + message was sent to the logger. + We reduce coupling if we can pass in a fake logging class + that simply records the message calls for testing, but + takes no action. + It would have to look exactly like our original though. +

+

+ If the fake object doesn't write to a file then we save on deleting + the file before and after each test. We could save even more + test code if the fake object would kindly run the assertion for us. +

+

+ Too good to be true? + Luckily we can create such an object easily... + +Mock::generate('Log'); + +class TestOfSessionLogging extends UnitTestCase { + + function testLogInIsLogged() { + $log = &new MockLog(); + $log->expectOnce('message', array('User fred logged in.')); + $session_pool = &new SessionPool($log); + $session_pool->logIn('fred'); + } +} +?> +]]> + 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 + resulting pass or fail event to the test display. + 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 + selected according to the incoming arguments, sequences of + parameter expectations and limits on the number of times + a method is to be invoked. +

+

+ For this test to run the mock objects library must have been + included in the test suite, say in all_tests.php. +

+
+
+

+ One of the requirements of web sites is that they produce web + pages. + If you are building a project top-down and you want to fully + integrate testing along the way then you will want a way of + automatically navigating a site and examining output for + correctness. + This is the job of a web tester. +

+

+ The web testing in SimpleTest is fairly primitive, there is + no JavaScript for example. + To give an idea here is a trivial example where a home + page is fetched, from which we navigate to an "about" + page and then test some client determined content. + +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->click('About'); + } + + function testSearchEngineOptimisations() { + $this->assertTitle('A long title about us for search engines'); + $this->assertPattern('/a popular keyphrase/i'); + } +} +$test = &new TestOfAbout(); +$test->run(new HtmlReporter()); +?> +]]> + With this code as an acceptance test you can ensure that + the content always meets the specifications of both the + developers and the other project stakeholders. +

+

+ SourceForge.net Logo +

+
+
+ + + Using unit tester + with an example. + + + Grouping tests + for testing with one click. + + + Using mock objects + to ease testing and gain tighter control. + + + Testing web pages + at the browser level. + + + + + Download PHP Simple Test + from SourceForge. + + + The developer's API for SimpleTest + gives full detail on the classes and assertions available. + + + + + software development, + php programming, + programming php, + software development tools, + php tutorial, + free php scripts, + architecture, + php resources, + mock objects, + junit, + php testing, + php unit, + methodology, + test first, + sourceforge, + open source, + unit test, + web tester, + web testing, + html testing tools, + testing web pages, + php mock objects, + navigating websites automatically, + automated testing, + web scripting, + wget, + curl testing, + jmock for php, + jwebunit, + phpunit, + php unit testing, + php web testing, + jason sweat, + marcus baker, + topstyle plug in, + phpedit plug in + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/subclass_tutorial.xml b/tests/simpletest/docs/source/en/subclass_tutorial.xml new file mode 100644 index 00000000..990acf61 --- /dev/null +++ b/tests/simpletest/docs/source/en/subclass_tutorial.xml @@ -0,0 +1,256 @@ + + + PHP unit testing tutorial - Subclassing a test case + +

+

A timing insensitive assertion

+

+

+ We left our clock test with a hole. + If the PHP time() + function rolled over during this comparison... +assertEqual($clock->now(), time(), 'Now is the right time'); +} +]]> + ...our test would be out by one second and would cause + a false failure. + Erratic behaviour of our test suite is not what we want when + we could be running it a hundred times a day. +

+

+ We could rewrite the test as... + + $time1 = $clock->now(); + $time2 = time(); + $this->assertTrue($time1 == $time2) || ($time1 + 1 == $time2), 'Now is the right time'); +} +]]> + This is hardly a clear design though and we will have to repeat + this for every timing test that we do. + Repetition is public enemy number one and so we'll + use this as incentive to factor out the new test code. +UnitTestCase('Clock class test'); + } + function assertSameTime($time1, $time2, $message) { + $this->assertTrue( + ($time1 == $time2) || ($time1 + 1 == $time2), + $message); + } + function testClockTellsTime() { + $clock = new Clock(); + $this->assertSameTime($clock->now(), time(), 'Now is the right time'); + } + function testClockAdvance() { + $clock = new Clock(); + $clock->advance(10); + $this->assertSameTime($clock->now(), time() + 10, 'Advancement'); + } +} +]]> + Of course each time I make one of these changes I rerun the + tests to make sure we are still OK. + Refactor on green. + It's a lot safer. +

+

+

Reusing our assertion

+

+

+ It may be that we want more than one test case that is + timing sensitive. + Perhaps we are reading timestamps from database rows + or other places that could allow an extra second to + tick over. + For these new test classes to take advantage of our new assertion + we need to place it into a superclass. +

+

+ Here is the complete clock_test.php file after + promoting our assertSameTime() + method to its own superclass... + + class TimeTestCase extends UnitTestCase { + function TimeTestCase($test_name) { + $this->UnitTestCase($test_name); + } + function assertSameTime($time1, $time2, $message) { + $this->assertTrue( + ($time1 == $time2) || ($time1 + 1 == $time2), + $message); + } + } + + class TestOfClock extends TimeTestCase { + function TestOfClock() { + $this->TimeTestCase('Clock class test'); + } + function testClockTellsTime() { + $clock = new Clock(); + $this->assertSameTime($clock->now(), time(), 'Now is the right time'); + } + function testClockAdvance() { + $clock = new Clock(); + $clock->advance(10); + $this->assertSameTime($clock->now(), time() + 10, 'Advancement'); + } + } +?> +]]> + Now we get the benefit of our new assertion every + time we inherit from our own + TimeTestCase class + rather than the default + UnitTestCase. + This is very much how the JUnit tool was designed + to be used and SimpleTest is a port of that interface. + It is a testing framework from which your own test + system can be grown. +

+

+ If we run the tests now we get a slight niggle... +

+ Warning: Missing argument 1 for timetestcase() + in /home/marcus/projects/lastcraft/tutorial_tests/tests/clock_test.php on line 5
+

All tests

+
3/3 test cases complete. + 6 passes and 0 fails.
+
+ The reasons for this are quite tricky. +

+

+ Our subclass requires a constructor parameter that has + not been supplied and yet it appears that we did + supply it. + When we inherited our new class we passed it in our own + constructor. + It's right here... +TimeTestCase('Clock class test'); +} +]]> + In fact we are right, that is not the problem. +

+

+ Remember when we built our all_tests.php + group test by using the + addTestFile() method. + This method looks for test case classes, instantiates + them if they are new and then runs all of their tests. + What's happened is that it has found our + test case extension as well. + This is harmless as there are no test methods within it, + that is, method names that start with the string + "test". + No extra tests are run. +

+

+ The trouble is that it instantiates the class and does this without + the $test_name parameter + which is what causes our warning. + This parameter is not normally required of a test + case and not normally of its assertions either. + To make our extended test case match the + UnitTestCase interface + we must make these optional... +$test_name = false) { + $this->UnitTestCase($test_name); + } + function assertSameTime($time1, $time2, $message = false) { + if (! $message) { + $message = "Time [$time1] should match time [$time2]"; + } + $this->assertTrue( + ($time1 == $time2) || ($time1 + 1 == $time2), + $message); + } +} +]]> + Of course it should still bother you that this class is + instantiated by the test suite unnecessarily. + Here is a modification to prevent it running... +SimpleTestOptions::ignore('TimeTestCase'); +class TimeTestCase extends UnitTestCase { + function TimeTestCase($test_name = false) { + $this->UnitTestCase($test_name); + } + function assertSameTime($time1, $time2, $message = '') { + if (!$message) { + $message = "Time [$time1] should match time [$time2]"; + } + $this->assertTrue( + ($time1 == $time2) || ($time1 + 1 == $time2), + $message); + } +} +]]> + This just tells SimpleTest to always ignore this class when + building test suites. + It can be included anywhere in the test case file. +

+

+ Six passes looks good, but does not tell the casual + observer what has been tested. + For that you have to look at the code. + If that sounds like drudge to you and you would like this + information displayed before you then we should go on + to show the passes next. +

+
+ + + A timing insensitive assertion + that allows a one second gain. + + + Subclassing the test case + so as to reuse the test method. + + + + + The previous section was + controlling test variables. + + + The next tutorial section was + changing the test display. + + + You will need the + SimpleTest test tool to run the + sample code. + + + + + software development, + test case example, + programming php, + software development tools, + php tutorial, + creating subclass, + free php scripts, + architecture, + php resources, + junit, + phpunit style testing, + unit test, + php testing + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/support_website.xml b/tests/simpletest/docs/source/en/support_website.xml new file mode 100644 index 00000000..281f3e9d --- /dev/null +++ b/tests/simpletest/docs/source/en/support_website.xml @@ -0,0 +1,53 @@ + + + Support mailing list + +

+ The simpletest-support mailing-list is probably the most active area + around SimpleTest : help, advice, bugs and workarounds tend to happen most of the time. +

+

+ It's really easy to subscribe + and it's fully searchable too. +

+

+ At the last count, there were about 114 subscribers and 1908 message sent. + That's anything between 1 and 4 messages per day on average. +

+
+ + + Current release + + + Eclipse release + + + Packages + + + Source + + + Older stable releases + + + + + + + + + SimpleTest, + download, + source code, + stable release, + eclipse release, + eclipse plugin, + debian package, + drupal module, + pear channel, + pearified package + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/en/unit_test_documentation.xml b/tests/simpletest/docs/source/en/unit_test_documentation.xml new file mode 100644 index 00000000..662d9b58 --- /dev/null +++ b/tests/simpletest/docs/source/en/unit_test_documentation.xml @@ -0,0 +1,305 @@ + + + SimpleTest for PHP regression test documentation + +
+

+ The core system is a regression testing framework built around + test cases. + A sample test case looks like this... +class FileTestCase extends UnitTestCase { +} +]]> + Actual tests are added as methods in the test case whose names + by default start with the string "test" and + when the test case is invoked all such methods are run in + the order that PHP introspection finds them. + As many test methods can be added as needed. +

+

+ For example... +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'); + } +} +]]> + The constructor is optional and usually omitted. + Without a name, the class name is taken as the name of the test case. +

+

+ Our only test method at the moment is testCreation() + where we check that a file has been created by our + Writer object. + We could have put the unlink() + code into this method as well, but by placing it in + setUp() and + tearDown() we can use it with + other test methods that we add. +

+

+ The setUp() method is run + just before each and every test method. + tearDown() is run just after + each and every test method. +

+

+ You can place some test case set up into the constructor to + be run once for all the methods in the test case, but + you risk test inteference that way. + This way is slightly slower, but it is safer. + Note that if you come from a JUnit background this will not + be the behaviour you are used to. + JUnit surprisingly reinstantiates the test case for each test + method to prevent such interference. + SimpleTest requires the end user to use setUp(), but + supplies additional hooks for library writers. +

+

+ The means of reporting test results (see below) are by a + visiting display class + that is notified by various assert...() + methods. + Here is the full list for the UnitTestCase + class, the default for SimpleTest... + + + + + + + + + + + + + + + + + + + +
assertTrue($x)Fail if $x is false
assertFalse($x)Fail if $x is true
assertNull($x)Fail if $x is set
assertNotNull($x)Fail if $x not set
assertIsA($x, $t)Fail if $x is not the class or type $t
assertNotA($x, $t)Fail if $x is of the class or type $t
assertEqual($x, $y)Fail if $x == $y is false
assertNotEqual($x, $y)Fail if $x == $y is true
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
assertNotIdentical($x, $y)Fail if $x == $y is true and types match
assertReference($x, $y)Fail unless $x and $y are the same variable
assertClone($x, $y)Fail unless $x and $y are identical copies
assertPattern($p, $x)Fail unless the regex $p matches $x
assertNoPattern($p, $x)Fail if the regex $p matches $x
expectError($x)Swallows any upcoming matching error
assert($e)Fail on failed expectation object $e
+ All assertion methods can take an optional description as a + last parameter. + This is to label the displayed result with. + If omitted a default message is sent instead, which is usually + sufficient. + This default message can still be embedded in your own message + if you include "%s" within the string. + All the assertions return true on a pass or false on failure. +

+

+ Some examples... +$this->assertNull($variable, 'Should be cleared'); +]]> + ...will pass and normally show no message. + If you have + set up the tester to display passes + as well then the message will be displayed as is. +$this->assertIdentical(0, false, 'Zero is not false [%s]'); +]]> + This will fail as it performs a type + check, as well as a comparison, between the two values. + The "%s" part is replaced by the default + error message that would have been shown if we had not + supplied our own. +$this->assertReference($a, $b); +]]> + Will fail as the variable $a is a copy of $b. +$this->assertPattern('/hello/i', 'Hello world'); +]]> + This will pass as using a case insensitive match the string + hello is contained in Hello world. +$this->expectError(); +trigger_error('Catastrophe'); +]]> + Here the check catches the "Catastrophe" + message without checking the text and passes. + This removes the error from the queue. +$this->expectError('Catastrophe'); +trigger_error('Catastrophe'); +]]> + The next error check tests not only the existence of the error, + but also the text which, here matches so another pass. + If any unchecked errors are left at the end of a test method then + an exception will be reported in the test. +

+

+ Note that SimpleTest cannot catch compile time PHP errors. +

+

+ The test cases also have some convenience methods for debugging + code or extending the suite... + + + + + + + + +
setUp()Runs this before each test method
tearDown()Runs this after each test method
pass()Sends a test pass
fail()Sends a test failure
error()Sends an exception event
signal($type, $payload)Sends a user defined message to the test reporter
dump($var)Does a formatted print_r() for quick and dirty debugging
+

+
+
+

+ Of course additional test methods can be added to create + specific types of test case, so as to extend framework... + +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')); + } +} +]]> + Here the SimpleTest library is held in a folder called + simpletest that is local. + Substitute your own path for this. +

+

+ To prevent this test case being run accidently, it is + advisable to mark it as abstract. +

+

+ This new case can be now be inherited just like + a normal test case... +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'); + } +} +]]> +

+

+ If you want a test case that does not have all of the + UnitTestCase assertions, + only your own and a few basics, + you need to extend the SimpleTestCase + class instead. + It is found in simple_test.php rather than + unit_tester.php. + See later if you + want to incorporate other unit tester's + test cases in your test suites. +

+
+
+

+ You won't often run single test cases except when bashing + away at a module that is having difficulty, and you don't + want to upset the main test suite. + Here is the scaffolding needed to run a lone test case... + + 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()); +?> +]]> + This script will run as is, but of course will output zero passes + and zero failures until test methods are added. +

+
+
+ + + Unit test cases and basic assertions. + + + Extending test cases to + customise them for your own project. + + + Running a single case as + a single script. + + + + + SimpleTest project page on SourceForge. + + + SimpleTest download page on LastCraft. + + + Full API for SimpleTest + from the PHPDoc. + + + + + php unit testing, + test integration, + documentation, + marcus baker, + simple test, + simpletest documentation, + phpunit, + junit, + xunit, + agile web development, + eXtreme Programming, + Test Driven, + TDD + + +
diff --git a/tests/simpletest/docs/source/en/web_tester_documentation.xml b/tests/simpletest/docs/source/en/web_tester_documentation.xml new file mode 100644 index 00000000..d2da31ee --- /dev/null +++ b/tests/simpletest/docs/source/en/web_tester_documentation.xml @@ -0,0 +1,374 @@ + + + Simple Test for PHP web script testing documentation + +
+

+ Testing classes is all very well, but PHP is predominately + a language for creating functionality within web pages. + How do we test the front end presentation role of our PHP + applications? + Well the web pages are just text, so we should be able to + examine them just like any other test data. +

+

+ This leads to a tricky issue. + If we test at too low a level, testing for matching tags + in the page with pattern matching for example, our tests will + be brittle. + The slightest change in layout could break a large number of + tests. + If we test at too high a level, say using mock versions of a + template engine, then we lose the ability to automate some classes + of test. + For example, the interaction of forms and navigation will + have to be tested manually. + These types of test are extremely repetitive and error prone. +

+

+ SimpleTest includes a special form of test case for the testing + of web page actions. + The WebTestCase includes facilities + for navigation, content and cookie checks and form handling. + Usage of these test cases is similar to the + UnitTestCase... +class TestOfLastcraft extends WebTestCase { +} +]]> + Here we are about to test the + Last Craft site itself. + If this test case is in a file called lastcraft_test.php + then it can be loaded in a runner script just like unit tests... + + require_once('simpletest/web_tester.php'); + require_once('simpletest/reporter.php'); + + $test = &new TestSuite('Web site tests'); + $test->addTestFile('lastcraft_test.php'); + exit ($test->run(new TextReporter()) ? 0 : 1); +?> +]]> + I am using the text reporter here to more clearly + distinguish the web content from the test output. +

+

+ Nothing is being tested yet. + We can fetch the home page by using the + get() method... + + function testHomepage() { + $this->assertTrue($this->get('http://www.lastcraft.com/')); + } +} +]]> + The get() method will + return true only if page content was successfully + loaded. + It is a simple, but crude way to check that a web page + was actually delivered by the web server. + However that content may be a 404 response and yet + our get() method will still return true. +

+

+ Assuming that the web server for the Last Craft site is up + (sadly not always the case), we should see... +

+Web site tests
+OK
+Test cases run: 1/1, Failures: 0, Exceptions: 0
+
+ All we have really checked is that any kind of page was + returned. + We don't yet know if it was the right one. +

+
+
+

+ To confirm that the page we think we are on is actually the + page we are on, we need to verify the page content. + + $this->get('http://www.lastcraft.com/'); + $this->assertText('Why the last craft'); + } +} +]]> + The page from the last fetch is held in a buffer in + the test case, so there is no need to refer to it directly. + The pattern match is always made against the buffer. +

+

+ Here is the list of possible content assertions... + + + + + + + + + + + + + + + + + + + + + +
assertTitle($title)Pass if title is an exact match
assertText($text)Pass if matches visible and "alt" text
assertNoText($text)Pass if doesn't match visible and "alt" text
assertPattern($pattern)A Perl pattern match against the page content
assertNoPattern($pattern)A Perl pattern match to not find content
assertLink($label)Pass if a link with this text is present
assertNoLink($label)Pass if no link with this text is present
assertLinkById($id)Pass if a link with this id attribute is present
assertNoLinkById($id)Pass if no link with this id attribute is present
assertField($name, $value)Pass if an input tag with this name has this value
assertFieldById($id, $value)Pass if an input tag with this id has this value
assertResponse($codes)Pass if HTTP response matches this list
assertMime($types)Pass if MIME type is in this list
assertAuthentication($protocol)Pass if the current challenge is this protocol
assertNoAuthentication()Pass if there is no current challenge
assertRealm($name)Pass if the current challenge realm matches
assertHeader($header, $content)Pass if a header was fetched matching this value
assertNoHeader($header)Pass if a header was not fetched
assertCookie($name, $value)Pass if there is currently a matching cookie
assertNoCookie($name)Pass if there is currently no cookie of this name
+ As usual with the SimpleTest assertions, they all return + false on failure and true on pass. + They also allow an optional test message and you can embed + the original test message inside using "%s" inside + your custom message. +

+

+ So now we could instead test against the title tag with... +$this->assertTitle('The Last Craft? Web developer tutorials on PHP, Extreme programming and Object Oriented development'); +]]> + ...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... +$this->assertMime(array('text/plain', 'text/html')); +]]> + More interesting is checking the HTTP response code. + Like the MIME type, we can assert that the response code + is in a list of allowed values... +get('http://www.lastcraft.com/test/redirect.php'); + $this->assertResponse(200); + } +} +]]> + Here we are checking that the fetch is successful by + allowing only a 200 HTTP response. + This test will pass, but it is not actually correct to do so. + There is no page, instead the server issues a redirect. + The WebTestCase will + automatically follow up to three such redirects. + The tests are more robust this way and we are usually + interested in the interaction with the pages rather + than their delivery. + If the redirects are of interest then this ability must + be disabled... + + $this->setMaximumRedirects(0); + $this->get('http://www.lastcraft.com/test/redirect.php'); + $this->assertResponse(200); + } +} +]]> + The assertion now fails as expected... +

+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
+
+ We can modify the test to correctly assert redirects with... +setMaximumRedirects(0); + $this->get('http://www.lastcraft.com/test/redirect.php'); + $this->assertResponse(array(301, 302, 303, 307)); + } +} +]]> + This now passes. +

+
+
+

+ Users don't often navigate sites by typing in URLs, but by + clicking links and buttons. + Here we confirm that the contact details can be reached + from the home page... +get('http://www.lastcraft.com/'); + $this->clickLink('About'); + $this->assertTitle(new PatternExpectation('/About Last Craft/')); + } +} +]]> + The parameter is the text of the link. +

+

+ If the target is a button rather than an anchor tag, then + 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!'); +]]> +

+

+ The list of navigation methods is... + + + + + + + + + + + + + + + + + + + + + + + + + +
getUrl()The current location
get($url, $parameters)Send a GET request with these parameters
post($url, $parameters)Send a POST request with these parameters
head($url, $parameters)Send a HEAD request without replacing the page content
retry()Reload the last request
back()Like the browser back button
forward()Like the browser forward button
authenticate($name, $password)Retry after a challenge
restart()Restarts the browser as if a new session
getCookie($name)Gets the cookie value for the current context
ageCookies($interval)Ages current cookies prior to a restart
clearFrameFocus()Go back to treating all frames as one page
clickSubmit($label)Click the first button with this label
clickSubmitByName($name)Click the button with this name attribute
clickSubmitById($id)Click the button with this ID attribute
clickImage($label, $x, $y)Click an input tag of type image by title or alt text
clickImageByName($name, $x, $y)Click an input tag of type image by name
clickImageById($id, $x, $y)Click an input tag of type image by ID attribute
submitFormById($id)Submit a form without the submit value
clickLink($label, $index)Click an anchor by the visible label text
clickLinkById($id)Click an anchor by the ID attribute
getFrameFocus()The name of the currently selected frame
setFrameFocusByIndex($choice)Focus on a frame counting from 1
setFrameFocus($name)Focus on a frame by name
+

+

+ The parameters in the get(), post() or + head() methods are optional. + The HTTP HEAD fetch does not change the browser context, only loads + cookies. + This can be useful for when an image or stylesheet sets a cookie + for crafty robot blocking. +

+

+ The retry(), back() and + forward() commands work as they would on + your web browser. + They use the history to retry pages. + This can be handy for checking the effect of hitting the + back button on your forms. +

+

+ The frame methods need a little explanation. + By default a framed page is treated just like any other. + Content will be searced for throughout the entire frameset, + so clicking a link will work no matter which frame + the anchor tag is in. + You can override this behaviour by focusing on a single + frame. + If you do that, all searches and actions will apply to that + frame alone, such as authentication and retries. + If a link or button is not in a focused frame then it cannot + be clicked. +

+

+ Testing navigation on fixed pages only tells you when you + have broken an entire script. + For highly dynamic pages, such as for bulletin boards, this can + be crucial for verifying the correctness of the application. + For most applications though, the really tricky logic is usually in + the handling of forms and sessions. + Fortunately SimpleTest includes + tools for testing web forms + as well. +

+
+
+

+ Although SimpleTest does not have the goal of testing networking + problems, it does include some methods to modify and debug + the requests it makes. + Here is another method list... + + + + + + + + + + + +
getTransportError()The last socket error
showRequest()Dump the outgoing request
showHeaders()Dump the incoming headers
showSource()Dump the raw HTML page content
ignoreFrames()Do not load framesets
setCookie($name, $value)Set a cookie from now on
addHeader($header)Always add this header to the request
setMaximumRedirects($max)Stop after this many redirects
setConnectionTimeout($timeout)Kill the connection after this time between bytes
useProxy($proxy, $name, $password)Make requests via this proxy URL
+ These methods are principally for debugging. +

+
+
+ + + Successfully fetching a web page + + + Testing the page content + + + Navigating a web site + while testing + + + Raw request modifications and debugging methods + + + + + SimpleTest project page on SourceForge. + + + SimpleTest download page on LastCraft. + + + The developer's API for SimpleTest + gives full detail on the classes and assertions available. + + + + + software development, + php programming for clients, + customer focused php, + software development tools, + acceptance testing framework, + free php scripts, + architecture, + php resources, + HTMLUnit, + JWebUnit, + php testing, + unit test resource, + web testing + + +
diff --git a/tests/simpletest/docs/source/fr/authentication_documentation.xml b/tests/simpletest/docs/source/fr/authentication_documentation.xml new file mode 100644 index 00000000..99a74a5e --- /dev/null +++ b/tests/simpletest/docs/source/fr/authentication_documentation.xml @@ -0,0 +1,252 @@ + + + Documentation Simple Test : tester 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. +

+
+
+

+ 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... + + function test401Header() { + $this->get('http://www.lastcraft.com/protected/'); + $this->showHeaders(); + } +} +]]> + Ce qui nous permet de voir les entêtes reçues... +

+

File test

+
+
1/1 test cases complete. + 0 passes, 0 fails and 0 exceptions.
+
+ Sauf que nous voulons éviter l'inspection visuelle, on souhaite que SimpleTest puisse nous dire si oui ou non la page est protégée. Voici un test en profondeur sur nos entêtes... +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 : +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... +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. +

+
+
+

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


+    Username:
+    
+ Password: +
+ + +]]>
+ 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... +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é : +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... +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 ? +

+
+
+

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

+
+
+ + + Passer au travers d'une authentification HTTP basique + + + Tester l'authentification basée sur des cookies + + + Gérer les sessions du navigateur et les timeouts + + + + + La page du projet SimpleTest sur SourceForge. + + + La page de téléchargement de SimpleTest sur LastCraft. + + + L'API du développeur pour SimpleTest donne tous les détails sur les classes et les assertions disponibles. + + + + + développement logiciel, + programmation php, + php orienté client, + outils de développement logiciel, + tutorial php, + scripts php gratuits, + architecture, + ressources php, + objets fantaise, + php testing, + php unit, + méthodologie, + développement piloté par les tests, + outils tests html, + tester des web pages, + php objets fantaise, + naviguer automatiquement sur des sites web, + test automatisé, + scripting web, + HTMLUnit, + JWebUnit, + phpunit, + php unit testing, + php web testing, + test unitaire de système d'authentification, + authentification HTTP, + test de connexion, + test d'authentification, + test de sécurité + + +
+ diff --git a/tests/simpletest/docs/source/fr/books_website.xml b/tests/simpletest/docs/source/fr/books_website.xml new file mode 100644 index 00000000..4770ee15 --- /dev/null +++ b/tests/simpletest/docs/source/fr/books_website.xml @@ -0,0 +1,75 @@ + + + Livres avec / à propos / pas loin de SimpleTest + +
+

+ De temps en temsp, un livre est recommandé sur la mailing-list, + vous le trouverez ci-dessous avec les commentaires originaux ! +

+

+ Domain-Driven Design: Tackling Complexity in the Heart of Software +

+
+ Le Développement Piloté par les Tests est principalement intéressé par + les mécanismes pour coder, mais il dit que c'est fini quand il n'y plus + de duplication. Le Développement Piloté par la Conception (DDD) considère + que le code est constamment in churn, changeant de terminologie au + fur et à mesure que le domaine devient plus clair, et aussi nourrisant le domaine + avec des nouveaux termes quand le code évolue..
+
+ Et puis, c'est un super bouquin :) + [source] +
+
+
+

+ Deux contributeurs de Simpletest ont écrit des livres sur PHP. + Tous les deux ont de nombreux exemples avec le framework SimpleTest. +

+

+ PHP|Architect's Guide to PHP Design Patterns +
+ PHP|Architect's Guide to PHP Design Patterns
+ par Jason E. Sweat
+ (l'obtenir depuis : PHP|Architect | + Amazon ) +

+

+ The PHP Anthology: Object Oriented PHP Solutions +
+ The PHP Anthology: Object Oriented PHP Solutions
+ par Harry Fuecks
+ (l'obtenir depuis : SitePoint | + Amazon | + critique sur Slashdot ) +

+
+
+

+ Une manière d'aider l'équipe de contributeurs, c'est d'acheter des livres via + cete page avec Amazon (avec le mot-clé simpletest-21). + Nous adorons tous lire des trucs à la fois intéressants et stimulants. +

+
+
+ + + Latest recommandation + + + Books by contributors + + + Buying books + + + + + + + + + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/fr/boundary_classes_tutorial.xml b/tests/simpletest/docs/source/fr/boundary_classes_tutorial.xml new file mode 100644 index 00000000..b6917c80 --- /dev/null +++ b/tests/simpletest/docs/source/fr/boundary_classes_tutorial.xml @@ -0,0 +1,268 @@ + + + + Tutorial de tests unitaires PHP - Organiser les tests unitaires et les scénarios de test de classe frontière + + +

+ Vous pensez probablement que nous avons désormais épuisé les modifications sur la classe Log et qu'il n'y a plus rien à ajouter. Sauf que les choses ne sont jamais simples avec la Programmation Orienté Objet. Vous pensez comprendre un problème et un nouveau cas arrive : il défie votre point de vue et vous conduit vers une analyse encore plus profonde. Je pensais comprendre la classe de log et que seule la première page du tutorial l'utiliserait. Après ça, je serais passé à quelque chose de plus compliqué. Personne n'est plus surpris que moi de ne pas l'avoir bouclée. En fait je pense que je viens à peine de me rendre compte de ce qu'un loggueur fait. +

+

+

Variations sur un log

+

+

+ Supposons que nous ne voulons plus seulement enregistrer les logs vers un fichier. Nous pourrions vouloir les afficher à l'écran, les envoyer au daemon syslog d'Unix(tm) via un socket. Comment s'accommoder de tels changements ? +

+

+ Le plus simple est de créer des sous-classes de Log qui écrasent la méthode message() avec les nouvelles versions. Ce système fonctionne bien à court terme, sauf qu'il a quelque chose de subtilement mais foncièrement erroné. Supposons que nous créions ces sous-classes et que nous ayons des loggueurs écrivant vers un fichier, sur l'écran et via le réseau. Trois classes en tout : ça fonctionne. Maintenant supposons que nous voulons ajouter une nouvelle classe de log qui ajoute un filtrage par priorité des messages, ne laissant passer que les messages d'un certain type, le tout suivant un fichier de configuration. +

+

+ Nous sommes coincés. Si nous créons de nouvelles sous-classes, nous devons le faire pour l'ensemble des trois classes, ce qui nous donnerait six classes. L'envergure de la duplication est horrible. +

+

+ Alors, est-ce que vous êtes en train de souhaiter que PHP ait l'héritage multiple ? Effectivement, cela réduirait l'ampleur de la tâche à court terme, mais aussi compliquerait quelque chose qui devrait être une classe très simple. L'héritage multiple, même supporté, devrait être utilisé avec le plus grand soin car toutes sortes d'enchevêtrements peuvent en découler. En fait ce soudain besoin nous dit quelque chose d'autre - peut-être que notre erreur si situe au niveau de la conception. +

+

+ Qu'est-ce que doit faire un loggueur ? Est-ce qu'il envoie un message vers un fichier ? A l'écran ? Via le réseau ? Non. Il envoie un message, point final. La cible de ses messages peut être sélectionnée à l'initialisation du log, mais après ça pas touche : le loggueur doit pouvoir combiner et formater les éléments du message puisque tel est son véritable boulot. Présumer que la cible fut un nom de fichier était une belle paire d'oeillères. +

+

+

Abstraire un fichier vers un scripteur

+

+

+ La solution de cette mauvaise passe est un classique. Tout d'abord nous encapsulons la variation de la classe : cela ajoute un niveau d'indirection. Au lieu d'introduire le nom du fichier comme une chaîne, nous l'introduisons comme "cette chose vers laquelle on écrit" et que nous appelons un Writer. Retour aux tests... + + require_once('../classes/writer.php'); + Mock::generate('Clock'); + + class TestOfLogging extends UnitTestCase { + function TestOfLogging() { + $this->UnitTestCase('Log class test'); + } + function setUp() { + @unlink('../temp/test.log'); + } + function tearDown() { + @unlink('../temp/test.log'); + } + function getFileLine($filename, $index) { + $messages = file($filename); + return $messages[$index]; + } + function testCreatingNewFile() { + $log = new Log(new FileWriter('../temp/test.log')); + $this->assertFalse(file_exists('../temp/test.log'), 'Created before message'); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('../temp/test.log'), 'File created'); + } + function testAppendingToFile() { + $log = new Log(new FileWriter('../temp/test.log')); + $log->message('Test line 1'); + $this->assertWantedPattern( + '/Test line 1/', + $this->getFileLine('../temp/test.log', 0)); + $log->message('Test line 2'); + $this->assertWantedPattern( + '/Test line 2/', + $this->getFileLine('../temp/test.log', 1)); + } + function testTimestamps() { + $clock = &new MockClock($this); + $clock->setReturnValue('now', 'Timestamp'); + $log = new Log(new FileWriter('../temp/test.log')); + $log->message('Test line', &$clock); + $this->assertWantedPattern( + '/Timestamp/', + $this->getFileLine('../temp/test.log', 0), + 'Found timestamp'); + } + } +?> +]]> + Je vais parcourir ces tests pas à pas pour ne pas ajouter trop de confusion. J'ai remplacé les noms de fichier par une classe imaginaire FileWriter en provenance d'un fichier classes/writer.php. Par conséquent les tests devraient planter puisque nous n'avons pas encore écrit ce scripteur. Doit-on le faire maintenant ? +

+

+ Nous pourrions, mais ce n'est pas obligé. Par contre nous avons besoin de créer l'interface, ou alors il ne sera pas possible de la simuler. Au final classes/writer.php ressemble à... + +]]> + Nous avons aussi besoin de modifier la classe Log... + + require_once('../classes/writer.php'); + + class Log { + var $_writer; + + function Log(&$writer) { + $this->_writer = &$writer; + } + + function message($message, $clock = false) { + if (! is_object($clock)) { + $clock = new Clock(); + } + $this->_writer->write("[" . $clock->now() . "] $message"); + } + } +?> +]]> + Il n'y a pas grand chose qui n'ait pas changé y compris dans la plus petite de nos classes. Désormais les tests s'exécutent mais ne passent pas, à moins que nous ajoutions du code dans le scripteur. Alors que faisons nous ? +

+

+ Nous pourrions commencer par écrire des tests et développer la classe FileWriter parallèlement, mais lors de cette étape nos tests de Log continueraient d'échouer et de nous distraire. En fait nous n'en avons pas besoin. +

+

+ Une partie de notre objectif est de libérer la classe du loggueur de l'emprise du système de fichiers et il existe un moyen d'y arriver. Tout d'abord nous créons le fichier tests/writer_test.php de manière à avoir un endroit pour placer notre code test en provenance de log_test.php et que nous allons brasser. Sauf que je ne vais pas l'ajouter dans le fichier all_tests.php pour l'instant puisque qu'il s'agit de la partie de log que nous sommes en train d'aborder. +

+

+ Nous enlevons tous les test de log_test.php qui ne sont pas strictement en lien avec le journal et nous les gardons bien précieusement dans writer_test.php pour plus tard. Nous allons aussi simuler le scripteur pour qu'il n'écrive pas réellement dans un fichier... + + Mock::generate('FileWriter'); + + class TestOfLogging extends UnitTestCase { + function TestOfLogging() { + $this->UnitTestCase('Log class test'); + } + function testWriting() { + $clock = &new MockClock($this); + $clock->setReturnValue('now', 'Timestamp'); + $writer = &new MockFileWriter($this); + $writer->expectArguments('write', array('[Timestamp] Test line')); + $writer->expectCallCount('write', 1); + $log = &new Log($writer); + $log->message('Test line', &$clock); + $writer->tally(); + } + } +?> +]]> + Eh oui c'est tout : il s'agit bien de l'ensemble du scénario de test et c'est normal qu'il soit aussi court. Pas mal de choses se sont passées... +

    +
  1. + La nécessité de créer le fichier uniquement si nécessaire a été déplacée vers le FileWriter. +
  2. +
  3. + Étant donné que nous travaillons avec des objets fantaisie, aucun fichier n'a été créé et donc setUp() et tearDown() passent dans les tests du scripteur. +
  4. +
  5. + Désormais le test consiste simplement dans l'envoi d'un message type et du test de son format. +
  6. +
+ Attendez un instant, où sont les assertions ? +

+

+ Les objets fantaisie font beaucoup plus que se comporter comme des objets, ils exécutent aussi des test. L'appel expectArguments() dit à l'objet fantaisie d'attendre un seul paramètre de la chaîne "[Timestamp] Test" quand la méthode fantaise write() est appelée. Lorsque cette méthode est appelée les paramètres attendus sont comparés avec ceci et un succès ou un échec est renvoyé comme résultat au test unitaire. C'est pourquoi un nouvel objet fantaisie a une référence vers $this dans son constructeur, il a besoin de ce $this pour l'envoi de son propre résultat. +

+

+ L'autre attente, c'est que le write ne soit appelé qu'une seule et unique fois. Juste l'initialiser ne serait pas suffisant. L'objet fantaisie attendrait une éternité si la méthode n'était jamais appelée et par conséquent n'enverrait jamais le message d'erreur à la fin du test. Pour y faire face, l'appel tally() lui dit de vérifier le nombre d'appel à ce moment là. Nous pouvons voir tout ça en lançant les tests... +

+

All tests

+ Pass: log_test.php->Log class test->testwriting->Arguments for [write] were [String: [Timestamp] Test line]
+ Pass: log_test.php->Log class test->testwriting->Expected call count for [write] was [1], but got [1]
+ + Pass: clock_test.php->Clock class test->testclockadvance->Advancement
+ Pass: clock_test.php->Clock class test->testclocktellstime->Now is the right time
+
3/3 test cases complete. + 4 passes and 0 fails.
+
+

+

+ En fait nous pouvons encore raccourcir nos tests. L'attente de l'objet fantaisie expectOnce() peut combiner les deux attentes séparées. +setReturnValue('now', 'Timestamp'); + $writer = &new MockFileWriter($this); + $writer->expectOnce('write', array('[Timestamp] Test line')); + $log = &new Log($writer); + $log->message('Test line', &$clock); + $writer->tally(); +} +]]> + Cela peut être une abréviation utile. +

+

+

Classes frontières

+

+

+ Quelque chose de très agréable est arrivée au loggueur en plus de devenir purement et simplement plus court. +

+

+ Les seules choses dont il dépend sont maintenant des classes que nous avons écrites nous-même et qui dans les tests sont simulées : donc aucune dépendance hormis notre propre code PHP. Pas de fichier à écrire ni de déclenchement via une horloge à attendre. Cela veut dire que le scénario de test log_test.php va s'exécuter aussi vite que le processeur le permet. Par contraste les classes FileWriter et Clock sont très proches du système. Plus difficile à tester puisque de vraies données doivent être déplacées et validées avec soin, souvent par des astuces ad hoc. +

+

+ Notre dernière factorisation a beaucoup aidé. Les classes aux frontières de l'application et du système, celles qui sont difficiles à tester, sont désormais plus courtes étant donné que le code d'I/O a été éloigné encore plus de la logique applicative. Il existe des liens directs vers des opérations PHP : FileWriter::write() s'apparente à l'équivalent PHP fwrite() avec le fichier ouvert pour l'ajout et Clock::now() s'apparente lui aussi à un équivalent PHP time(). Primo le débogage devient plus simple. Secundo ces classes devraient bouger moins souvent. +

+

+ Si elles ne changent pas beaucoup alors il n'y a aucune raison pour continuer à en exécuter les tests. Cela veut dire que les tests pour les classes frontières peuvent être déplacées vers leur propre suite de tests, laissant les autres tourner à plein régime. En fait c'est comme ça que j'ai tendance à travailler et les scénarios de test de SimpleTest lui-même sont divisés de cette manière. +

+

+ Peut-être que ça ne vous paraît pas beaucoup avec un test unitaire et deux tests aux frontières, mais une application typique peut contenir vingt classes de frontière et deux cent classes d'application. Pour continuer leur exécution à toute vitesse, vous voudrez les tenir séparées. +

+

+ De plus, un bon développement passe par des décisions de tri entre les composants à utiliser. Peut-être, qui sait, tous ces simulacres pourront améliorer votre conception. +

+
+ + + + Variations sur un log + + + Abstraire un niveau supplémentaire via une classe fantaisie d'un scripteur + + + Séparer les tests des classes frontières pour un petit nettoyage + + + + + Ce tutorial suit l'introduction aux objets fantaisies. + + + Ensuite vient la conception pilotée par les tests. + + + Vous aurez besoin du framework de test SimpleTest pour essayer ces exemples. + + + + + développement logiciel, + programmation php, + outils de développement logiciel, + tutorial php, + scripts php gratuits, + organisation de tests unitaires, + conseil de test, + astuce de développement, + architecture logicielle pour des tests, + exemple de code php, + objets fantaisie, + port de junit, + exemples de scénarios de test, + test php, + outil de test unitaire, + suite de test php + + +
+ diff --git a/tests/simpletest/docs/source/fr/browser_documentation.xml b/tests/simpletest/docs/source/fr/browser_documentation.xml new file mode 100644 index 00000000..685ef74e --- /dev/null +++ b/tests/simpletest/docs/source/fr/browser_documentation.xml @@ -0,0 +1,199 @@ + + + Documentation SimpleTest : le composant de navigation web 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 framework SimpleTest lui-même. +

+
+
+

+ Vous pouvez utiliser le navigateur web dans des scripts PHP pour confirmer que des services marchent bien comme il faut ou pour extraire des informations à partir de ceux-ci de façon régulière. + Par exemple, voici un petit script pour extraire le nombre de bogues ouverts dans PHP 5 à partir du site web PHP... +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 formulaires 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 appelé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
+ Au jourd d'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 une unique et grande page. Le contenu de la page en cours sera une concaténation des toutes les fenêtres dans l'ordre spécifié par les balises "frameset". + + + + + + +
getFrames()Un déchargement de la structure de la fenêtre courante
getFrameFocus()L'index ou l'étiquette de la fenêtre en courante
setFrameFocusByIndex($choice)Sélectionne la fenêtre numérotée à partir de 1
setFrameFocus($name)Sélectionne une fenêtre par son étiquette
clearFrameFocus()Traite toutes les fenêtres comme une seule page
+ Lorsqu'on est focalisé sur une fenêtre unique, le contenu viendra de celle-ci uniquement. Cela comprend les liens à cliquer et les formulaires à transmettre. +

+
+
+

+ Toute cette masse de fonctionnalités est géniale lorsqu'on arrive à bien télécharger les pages, mais ce n'est pas toujours évident. Pour aider à découvrir les erreurs, le navigateur a aussi des méthodes pour aider au débogage. + + + + + + + + + + + + + +
setConnectionTimeout($timeout)Ferme la socket avec un délai trop long
getRequest()L'entête de la requête brute de la page ou de la fenêtre
getHeaders()L'entête de réponse de la page ou de la fenêtre
getTransportError()N'importe quel erreur au niveau de la socket dans le dernier téléchargement
getResponseCode()La réponse HTTP de la page ou de la fenêtre
getMimeType()Le type Mime de la page our de la fenêtre
getAuthentication()Le type d'authentification 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 redirections 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 individuelle ne se charge pas, il suffit de se diriger vers elle avec SimpleBrowser::setFrameFocus() : ensuite on utilisera SimpleBrowser::getRequest(), etc. pour voir ce qui se passe. +

+
+
+

+ Tout ce qui peut être fait dans WebTestCase peut maintenant être fait dans un UnitTestCase. Ce qui revient à dire que nous pouvons librement mélanger des tests sur des objets de domaine avec l'interface web... +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 à plusieurs couches de l'application, ça implique qu'il est plus que probable qu'il faudra le remanier lorsque le code changera. +

+

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

+
+
+ + + Utiliser le navigateur web dans des scripts + + + Déboguer les erreurs sur les pages + + + Tests complexes avec des navigateurs web multiples + + + + + La page du projet SimpleTest sur SourceForge. + + + La page de téléchargement de SimpleTest sur LastCraft. + + + L'API de développeur pour SimpleTest donne tous les détails sur les classes et les assertions disponibles. + + + + + développement logiciel, + programmation php pour des clients, + php centré autour du client, + outils de développement logiciel, + framework de test de recette, + scripts php gratuits, + test unitaire de systèmes d'authentification, + ressources php, + HTMLUnit, + JWebUnit, + test php, + ressource de test unitaire, + test web, + authentification HTTP, + tester la connection, + tester l'authentification, + tests de sécurité + + +
+ diff --git a/tests/simpletest/docs/source/fr/display_subclass_tutorial.xml b/tests/simpletest/docs/source/fr/display_subclass_tutorial.xml new file mode 100644 index 00000000..3ebbd206 --- /dev/null +++ b/tests/simpletest/docs/source/fr/display_subclass_tutorial.xml @@ -0,0 +1,214 @@ + + + Tutorial de test unitaire en PHP - Sous-classer l'affichage du test + +

+ Le composant affichage de SimpleTest est en fait la dernière partie à développer. Des morceaux de la section suivante changeront prochainement et -- avec optimisme -- des composants d'affichage plus sophistiqués seront écrits, mais pour l'instant si un affichage minime n'est pas suffisant, voici comment réaliser le votre. +

+

+

Je veux voir les succès !

+

+

+ Bon d'accord, voici comment. +

+

+ Nous devons créer une sous-classe de l'affichage utilisée, dans notre cas il s'agit de HtmlReporter. La classe HtmlReporter est situé dans le fichier simpletest/reporter.php : pour l'instant elle a l'interface suivante... + + Voici ce que les méthodes pertinentes veulent dire. Vous pouvez consulter la liste complète ici si cela vous intéresse. +

    +
  • + HtmlReporter()
    + est le constructeur. Notez qu'un test unitaire initie le lien vers l'affichage plutôt que l'inverse. L'affichage est un réceptacle passif des évènements de test. Cela permet une adaptation facile de l'affichage pour d'autres systèmes de test en dehors des tests unitaires comme la surveillance de serveurs par exemple. Autre avantage, un test unitaire peut écrire vers plus d'un affichage à la fois. +
  • +
  • + void paintFail(string $message)
    + peint un échec. Voir ci-dessous. +
  • +
  • + void paintPass(string \$message)
    + ne fait rien par défaut. C'est cette méthode que nous allons modifier. +
  • +
  • + string _getCss()
    + renvoie le style CSS - via une chaîne - pour la méthode d'entête de la page. Des styles complémentaires peuvent être ajoutés ici. +
  • +
  • + array getTestList()
    + est une méthode commode pour des sous-classes. Elle liste l'emboîtement courant des tests via une liste de noms de test. Le premier, le test emboîté le plus profondément, est le premier dans la liste et la méthode du test courant sera la dernière. +
  • +
+

+

+ Pour afficher les succès nous avons juste besoin que la méthode paintPass() se comporte comme paintFail(). Bien sûr nous n'allons pas modifier l'original. Nous allons juste créer une sous-classe. +

+

+

Une sous-classe d'affichage

+

+

+ Premièrement nous allons créer un fichier tests/show_passes.php dans notre projet de log et y placer cette classe vide... +HtmlReporter(); + } + } +?> +]]> + Une rapide mais attentive lecture du code de SimpleTest indique que l'implémentation de paintFail() ressemble à... +Fail: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode("->", $breadcrumb); + print "->$message
\n"; +} +]]>
+ Essentiellement elle s'enchaîne à la version du parent, que nous devons aussi réaliser pour garantir le ménage, et ensuite imprime une trace calculée à partir de la liste des tests courants. Par contre elle perd au passage le nom du test du premier niveau. Etant donné qu'il est identique pour chaque test, ce serait un peu trop d'informations. En la transposant dans notre nouvelle classe... +HtmlReporter(); + } + + function paintPass($message) { + parent::paintPass($message); + print "Pass: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode("->", $breadcrumb); + print "->$message
\n"; + }
+} +]]>
+ Pour l'instant tout roule. Maintenant pour utiliser notre nouvelle classe, nous allons modifier notre fichier tests/all_tests.php... + + require_once('show_passes.php'); + + $test = &new GroupTest('All tests'); + $test->addTestFile('log_test.php'); + $test->addTestFile('clock_test.php'); + $test->run(new ShowPasses()); +?> +]]> + Nous pouvons le lancer pour voir le résultat de notre bricolage... +

+

All tests

+ Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]
+ Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]
+ Pass: log_test.php->Log class test->testcreatingnewfile->Created before message
+ Pass: log_test.php->Log class test->testcreatingnewfile->File created
+ Pass: clock_test.php->Clock class test->testclockadvance->Advancement
+ Pass: clock_test.php->Clock class test->testclocktellstime->Now is the right time
+
3/3 test cases complete. + 6 passes and 0 fails.
+
+ Joli, mais pas encore digne d'une médaille d'or. Nous avons perdu un peu d'information au passage. L'affichage du span.pass n'est pas stylé en CSS, mais nous pouvons l'ajouter en modifiant une autre méthode... +HtmlReporter(); + } + + function paintPass($message) { + parent::paintPass($message); + print "Pass: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode("->", $breadcrumb); + print "->$message
\n"; + } + + function _getCss() { + return parent::_getCss() . ' .pass { color: green; }'; + } +} +]]>
+ Si vous ajoutez le code au fur et à mesure, vous verrez l'ajout du style dans le code source du résultat via le navigateur. A l'oeil, l'affichage devrait ressembler à... +
+

All tests

+ Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]
+ Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]
+ Pass: log_test.php->Log class test->testcreatingnewfile->Created before message
+ Pass: log_test.php->Log class test->testcreatingnewfile->File created
+ Pass: clock_test.php->Clock class test->testclockadvance->Advancement
+ Pass: clock_test.php->Clock class test->testclocktellstime->Now is the right time
+
3/3 test cases complete. + 6 passes and 0 fails.
+
+ Certains préfèrent voir les succès quand ils travaillent sur le code; le sentiment de travail achevé est sympathique après tout. Une fois que vous commencez à naviguer de haut en bas pour trouver les erreurs, assez vite vous en comprendrez le côté obscur. +

+

+ Essayez les deux méthodes pour déterminer votre préférence. Nous allons le laisser tel que pour l'étape qui approche : les objets fantaisie. Il s'agit du premier outil de test qui ajoute des tests additionnels : il sera utile de voir ce qui se passe dans les coulisses. +

+
+ + + Comment changer l'affichage pour afficher les passages avec succès. + + + Sous classer la classe HtmlReporter. + + + + + La section précédente : sous-classer les scénarios de test + + + Cette section est très spécifique à SimpleTest. Si vous utilisez un autre outil, n'hésitez pas à sauter pardessus. + + + + + développement logiciel piloté par les tests, + conseil pour programmer en php, + programmation php, + outils de développement logiciel, + tutorial php, + scripts php gratuits, + architecture, + exemple de scénario de test, + framework de tests unitaires, + ressources php, + exemple de code php, + junit, + phpunit, + simpletest, + test php, + outil de test unitaire, + suite de test php + + +
+ diff --git a/tests/simpletest/docs/source/fr/download_website.xml b/tests/simpletest/docs/source/fr/download_website.xml new file mode 100644 index 00000000..d7d255aa --- /dev/null +++ b/tests/simpletest/docs/source/fr/download_website.xml @@ -0,0 +1,100 @@ + + + Télécharger SimpleTest + +
+

+ La version courante est : + SimpleTest v1.0.1beta. +

+

+ Vous pouvez télécharger cette version depuis + SourceForget.net + et votre miroir le plus proche. Vous pouvez aussi jeter un oeil du côté + du changelog actuel. +

+

+ Au fait, ne soyez pas effrayé par le mot beta : + pas mal d'utilisateurs vont même jusqu'à utiliser la version CVS. +

+
+
+

+ Si Eclipse est votre IDE / éditeur de prédilection, vous aurez + peut-être envie d'utiliser le + plugin Eclipse. +

+

+ Pour utilser les procédures automatiques, l'URL est : +

http://simpletest.org/eclipse/
+

+
+
+

+ SimpleTest a été packagé par la communauté avec d'autres parfums encore. +

+ +

+ Attention : certains paquets ne sont pas toujours très à jour. +

+
+
+

+ Le code source est hébergé par SourceForge : vous pouvez l'étudier / le butiner + via le CVS repository. +

+
+
+ +
+
+ + + Version courante + + + Paquet Eclipse + + + Autres paquets + + + Source + + + Autres versions stables + + + + + + + + + SimpleTest, + download, + source code, + stable release, + eclipse release, + eclipse plugin, + debian package, + drupal module, + pear channel, + pearified package + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/fr/expectation_documentation.xml b/tests/simpletest/docs/source/fr/expectation_documentation.xml new file mode 100644 index 00000000..31190690 --- /dev/null +++ b/tests/simpletest/docs/source/fr/expectation_documentation.xml @@ -0,0 +1,213 @@ + + + Documentation SimpleTest : étendre le testeur unitaire avec des classes d'attentes supplémentaires + +
+

+ 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... + + $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... + + $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 qu'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. +

+
+
+

+ 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 ou celui d'un bouchon serveur. A chaque fois qu'une liste d'arguments est donnée, une liste d'objets d'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... + +$authorisation = new StubAuthorisation(); +$authorisation->setReturnValue( + 'isAllowed', + true, + array(new IsAExpectation('Session', 'Must be a session'))); +$authorisation->setReturnValue('isAllowed', false); +]]> + Le comportement par défaut du bouchon serveur est défini pour renvoyer false quand isAllowed est appelé. Lorsque nous appelons cette méthode avec un unique paramètre qui est un objet Session, il renverra true. Nous avons aussi ajouté un deuxième paramètre comme message. Il sera affiché dans le message d'erreur de l'objet fantaisie si l'attente est la cause de l'échec. +

+

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

+
+
+

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

+

+ Par exemple voici la création d'une classe pour tester la validité d'adresses IP. Pour fonctionner correctement avec les bouchons serveurs et les objets fantaisie, cette nouvelle classe d'attente devrait étendre SimpleExpectation... +class ValidIp extends SimpleExpectation { + + function test($ip) { + return (ip2long($ip) != -1); + } + + function testMessage($ip) { + return "Address [$ip] should be a valid IP address"; + } +} +]]> + Il n'y a véritablement que deux méthodes à mettre en place. La méthode test() devrait renvoyer un true si l'attente doit passer, et une erreur false dans le cas contraire. La méthode testMessage() ne devrait renvoyer que du texte utile à la compréhension du test en lui-même. +

+

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

+
+
+

+ Le framework 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... + + 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. +

+
+
+ + + Utiliser les attentes pour des tests plus précis avec des objets fantaisie + + + Changer le comportement d'un objet fantaisie avec des attentes + + + Créer des attentes + + + Par dessous SimpleTest utilise des classes d'attente + + + + + La page du projet SimpleTest sur SourceForge. + + + La page de téléchargement de SimpleTest sur LastCraft. + + + Les attentes imitent les contraintes dans JMock. + + + L'API complète pour SimpleTest réalisé avec PHPDoc. + + + + + objets fantaisie, + développement piloté par les tests, + héritage des attentes, + contraintes d'objet fantaisie, + test unitaire avancé en PHP, + test en premier, + architecture de framework de test + + +
+ diff --git a/tests/simpletest/docs/source/fr/first_test_tutorial.xml b/tests/simpletest/docs/source/fr/first_test_tutorial.xml new file mode 100644 index 00000000..9b90d4f6 --- /dev/null +++ b/tests/simpletest/docs/source/fr/first_test_tutorial.xml @@ -0,0 +1,285 @@ + + + Tutorial sur les tests unitaires en PHP - Créer un exemple de scénario de test en PHP + +

+ Si vous débutez avec les tests unitaires, il est recommandé d'essayer le code au fur et à mesure. Il n'y pas grand chose à taper et vous sentirez le rythme de la programmation pilotée par les tests. +

+

+ Pour exécuter les exemples tels quels, vous aurez besoin de créer un nouveau répertoire et d'y installer trois dossiers : classes, tests et temp. Dézippez le framework SimpleTest dans le dossier tests et assurez vous que votre serveur web puisse atteindre ces endroits. +

+

+

Un nouveau scénario de test

+

+

+ L'exemple dans l'introduction rapide comprenait les tests unitaires d'une simple classe de log. Dans ce tutorial à propos de Simple Test, je vais essayer de raconter toute l'histoire du développement de cette classe. Cette classe PHP est courte et simple : au cours de cette introduction, elle recevra beaucoup plus d'attention que dans le cadre d'un développement de production. Nous verrons que derrière son apparente simplicité se cachent des choix de conception étonnamment difficiles. +

+

+ Peut-être que ces choix sont trop difficiles ? Plutôt que d'essayer de penser à tout en amont, je vais commencer par poser une exigence : nous voulons écrire des messages dans un fichier. Ces messages doivent être ajoutés en fin de fichier s'il existe. Plus tard nous aurons besoin de priorités, de filtres et d'autres choses encore, mais nous plaçons l'écriture dans un fichier au coeur de nos préoccupations. Nous ne penserons à rien d'autres par peur de confusion. OK, commençons par écrire un test... +UnitTestCase(); + } + function testCreatingNewFile() { + } + } + + $test = &new TestOfLogging(); + $test->run(new HtmlReporter()); +?> +]]> + Pas à pas, voici ce qu'il veut dire. +

+

+ La constante SIMPLE_TEST contient le chemin vers les classes de Simple Test à partir de ce fichier. Les classes pourraient être placées dans le path du fichier php.ini mais si vous êtes sur un serveur mutualisé, vous n'y aurez probablement pas accès. Pour que tout le monde soit content, le chemin est déclaré explicitement dans le script de test. Plus tard nous verrons comment tout finira au même endroit. +

+

+ Demander la librairie unit_tester.php est assez évident mais qu'est-ce que ce fichier reporter.php ? Les librairies Simple Test sont une boîte à outils pour créer votre propre suite de tests standardisés. Elles peuvent être utilisées "telles quelles" sans problème, mais elles sont constituées de plusieurs éléments qui ont besoin d'être assemblés les uns aux autres. Le composant pour l'affichage est situé dans reporter.php. Probablement qu'un jour vous écrirez le vôtre : c'est pourquoi son inclusion est optionnelle. Simple Test contient une classe d'affichage, fonctionnelle mais basique : elle s'appelle HtmlReporter. Elle peut enregistrer des informations sur les tests : début, fin, erreur, réussite ou échec. Elle affiche cette information le plus rapidement possible au cas où le code de test planterait et masquerait le lieu de l'échec. +

+

+ Les tests eux-mêmes sont rassemblés dans une classe de scénario de test. Cette dernière est typiquement une extension de la classe UnitTestCase. Quand le test est exécuté, elle cherche les méthodes commençant par "test" et les lancent. Notre seule méthode de test pour l'instant est appellée testCreatingNewFile() mais elle est encore vide. +

+

+ Une méthode vide ne fait rien. Nous avons besoin d'y placer du code. La classe UnitTestCase génère des évènements de test à son exécution : ces évènements sont envoyés vers un observateur. La méthode UnitTestCase::run() lancent tous les tests de la classe. +

+

+ Et pour ajouter du code de test... + + require_once('../classes/log.php'); + + class TestOfLogging extends UnitTestCase { + function TestOfLogging() { + $this->UnitTestCase(); + } + function testCreatingNewFile() { + @unlink('../temp/test.log'); + $log = new Log('../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()); +?> +]]> +

+

+ Vous pensez probablement que ça représente beaucoup de code pour un unique test et je suis d'accord avec vous. Ne vous inquiétez pas. Il s'agit d'un coût fixe et à partir de maintenant nous pouvons ajouter des tests : une ligne ou presque à chaque fois. Parfois moins en utilisant des artefacts de test que nous découvrirons plus tard. +

+

+ Nous devons maintenant prendre nos premières décisions. Notre fichier de test s'appelle log_test.php (n'importe quel nom ferait l'affaire) : nous le plaçons dans un dossier appelé tests (partout ailleurs serait aussi bien). Notre fichier de code s'appelle log.php : c'est son contenu que nous allons tester. Je l'ai placé dans notre dossier classes : cela veut-il dire que nous construisons une classe ? +

+

+ Pour cet exemple, la réponse est oui, mais le testeur unitaire n'est pas restreint aux tests de classe. C'est juste que le code orienté objet est plus facile à dépecer et à remodeler. Ce n'est pas par hasard si la conduite de tests fins via les tests unitaires est apparue au sein de la communauté OO. +

+

+ Le test en lui-même est minimal. Tout d'abord il élimine tout autre fichier de test qui serait encore présent. Les décisions de conception arrivent ensuite en rafale. Notre classe s'appelle Log : elle passe le chemin du fichier au constructeur. Nous créons le log et nous lui envoyons aussitôt un message en utilisant la méthode message(). L'originalité dans le nommage n'est pas une caractéristique désirable chez un développeur informatique : c'est triste mais c'est comme ça. +

+

+ La plus petite unité d'un test mmm... heu... unitaire est l'assertion. Ici nous voulons nous assurer que le fichier log auquel nous venons d'envoyer un message a bel et bien été créé. UnitTestCase::assertTrue() enverra un évènement réussite si la condition évaluée est vraie ou un échec dans le cas contraire. Nous pouvons avoir un ensemble d'assertions différentes et encore plus si nous étendons nos scénarios de test classique. Voici la liste... + + + + + + + + + + + + + + + + +
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
+

+

+ Nous sommes désormais prêt à lancer notre script de test en le passant dans le navigateur. Qu'est-ce qui devrait arriver ? Il devrait planter... +

+ 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 +
+ La raison ? Nous n'avons pas encore créé log.php. +

+

+ Mais attendez une minute, c'est idiot ! Ne me dites pas qu'il faut créer un test sans écrire le code à tester auparavant... +

+

+

Développement piloté par les tests

+

+

+ Co-inventeur de l'Extreme Programming, Kent Beck a lancé un autre manifeste. Le livre est appelé Test Driven Development (Développement Piloté par les Tests) + ou TDD et élève les tests unitaires à une position élevée de la conception. En quelques mots, vous écrivez d'abord un petit test et seulement ensuite le code qui passe ce test. N'importe quel bout de code. Juste pour qu'il passe. +

+

+ Vous écrivez un autre test et puis de nouveau du code qui passe. Vous aurez alors un peu de duplication et généralement du code pas très propre. Vous remaniez (factorisez) ce code-là en vous assurant que les tests continuent à passer : vous ne pouvez rien casser. Une fois que le code est le plus propre possible vous êtes prêt à ajouter des nouvelles fonctionnalités. Il suffit juste de rajouter des nouveaux tests et de recommencer le cycle une nouvelle fois. + +

+

+ Il s'agit d'une approche assez radicale et j'ai parfois l'impression qu'elle est incomplète. Mais il s'agit d'un moyen efficace pour expliquer un testeur unitaire ! Il se trouve que nous avons un test qui échoue, pour ne pas dire qu'il plante : l'heure est venue d'écrire du code dans log.php... + +]]> + Il s'agit là du minimum que nous puissions faire pour éviter une erreur fatale de PHP. Et maintenant la réponse devient... +

+

testoflogging

+ Fail: testcreatingnewfile->True assertion failed.
+
1/1 test cases complete. + 0 passes and 1 fails.
+
+ "testoflogging" a échoué. Parmi les défauts de PHP on trouve cette fâcheuse tendance à transformer intérieurement les noms de classes et de méthodes en minuscules. SimpleTest utilise ces noms par défaut pour décrire les tests mais nous pouvons les remplacer par nos propres noms. + + $this->UnitTestCase('Log class test'); + } + function testCreatingNewFile() { + @unlink('../temp/test.log'); + $log = new Log('../temp/test.log'); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('../temp/test.log'), 'File created'); + } +} +]]> + Ce qui donne... +
+

Log class test

+ Fail: testcreatingnewfile->File created.
+
1/1 test cases complete. + 0 passes and 1 fails.
+
+ Par contre pour le nom des méthodes il n'y a rien à faire, désolé. +

+

+ Les messages d'un test comme ceux-ci ressemblent à bien des égards à des commentaires de code. Certains ne jurent que par eux, d'autres au contraire les bannissent purement et simplement en les considérant aussi encombrants qu'inutiles. Pour ma part, je me situe quelque part au milieu. +

+

+ Pour que le test passe, nous pourrions nous contenter de créer le fichier dans le constructeur de Log. Cette technique "en faisant semblant" est très utile pour vérifier que le test fonctionne pendant les passages difficiles. Elle le devient encore plus si vous sortez d'un passage avec des tests ayant échoués et que vous voulez juste vérifier de ne pas avoir oublié un truc bête. Nous n'allons pas aussi lentement donc... + + var $_file_path; + + function Log($file_path) { + $this->_file_path = $file_path; + } + + function message($message) { + $file = fopen($this->_file_path, 'a'); + fwrite($file, $message . "\n"); + fclose($file); + } + } +?> +]]> + Au total, pas moins de 4 échecs ont été nécessaire pour passer à l'étape suivante. Je n'avais pas créé le répertoire temporaire, je ne lui avais pas donné les droits d'écriture, j'avais une coquille et je n'avais pas non plus ajouté ce nouveau répertoire dans CVS. N'importe laquelle de ces erreurs aurait pu m'occuper pendant plusieurs heures si elle était apparue plus tard mais c'est bien pour ces cas là qu'on teste. Avec les corrections adéquates, ça donne... +

+

Log class test

+
1/1 test cases complete. + 1 passes and 0 fails.
+
+ Ça marche! +

+

+ Peut-être n'aimez-vous pas le style plutôt minimal de l'affichage. Les succès ne sont pas montrés par défaut puisque généralement vous n'avez pas besoin de plus d'information quand vous comprenez effectivement ce qui se passe. Dans le cas contraire, pensez à écrire d'autres tests. +

+

+ D'accord, c'est assez strict. Si vous voulez aussi voir les succès alors vous pouvez créer une sous-classe de HtmlReporter et l'utiliser pour les tests. Même moi j'aime bien ce confort parfois. +

+

+

Les tests comme documentation

+

+

+ Il y a une nuance ici. Nous ne voulons pas créer de fichier avant d'avoir effectivement envoyé de message. Plutôt que d'y réfléchir trop longtemps, nous allons juste ajouter un test pour ça. +UnitTestCase('Log class test'); + } + function testCreatingNewFile() { + @unlink('../temp/test.log'); + $log = new Log('../temp/test.log'); + $this->assertFalse(file_exists('../temp/test.log'), 'No file created before first message'); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('../temp/test.log'), 'File created'); + } +} +]]> + ...et découvrir que ça marche déjà... +

+

Log class test

+
1/1 test cases complete. + 2 passes and 0 fails.
+
+ En fait je savais que ça allait être le cas. J'ajoute ce test de confirmation tout d'abord pour garder l'esprit tranquille, mais aussi pour documenter ce comportement. Ce petit test supplémentaire dans son contexte en dit plus long qu'un scénario utilisateur d'une douzaine de lignes ou qu'un diagramme UML complet. Que la suite de tests devienne une source de documentation est un effet secondaire assez agréable. +

+

+ Devrions-nous supprimer le fichier temporaire à la fin du test ? Par habitude, je le fais une fois que j'en ai terminé avec la méthode de test et qu'elle marche. Je n'ai pas envie de valider du code qui laisse des restes de fichiers de test traîner après un test. Mais je ne le fais pas non plus pendant que j'écris le code. Peut-être devrais-je, mais parfois j'ai besoin de voir ce qui se passe : on retrouve cet aspect confort évoqué plus haut. +

+

+ Dans un véritable projet, nous avons habituellement plus qu'un unique scénario de test : c'est pourquoi nous allons regarder comment grouper des tests dans des suites de tests. +

+
+ + Créer un nouveau scénario de test. + Le Développement Piloté par les Tests en PHP. + Les tests comme documentation est un des nombreux effets secondaires. + + + + La FAQ de JUnit contient plein de conseils judicieux sur les tests. + + + Ensuite vient "comment grouper des scénarios de tests ensemble". + + + Vous aurez besoin du framework de test SimpleTest pour ces exemples. + + + + + développement logiciel, + programmation php, + outils de développement logiciel, + tutorial php, + scripts php gratuits, + architecture, + ressouces php, + objets fantaisie, + junit, + test php, + test unitaire, + test php automatisé, + tutorial de scénarios de test, + explication d'un scénario de test unitaire, + exemple de test unitaire + + +
+ diff --git a/tests/simpletest/docs/source/fr/form_testing_documentation.xml b/tests/simpletest/docs/source/fr/form_testing_documentation.xml new file mode 100644 index 00000000..508d078b --- /dev/null +++ b/tests/simpletest/docs/source/fr/form_testing_documentation.xml @@ -0,0 +1,207 @@ + + + Documentation SimpleTest : tester des formulaires HTML + +
+

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


+    
+    
+
+]]>
+ Il ressemble à... +

+

+

+ + +
+

+

+ Nous pouvons naviguer vers ce code, via le site LastCraft, avec le test suivant... + + 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 transmettrons... +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 quel 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... +

Select type of user to add:
+
+]]>
+ Qui ressemble à... +

+

+

+ Select type of user to add: + +
+

+

+ Le test suivant le confirmera... + + $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. +

+
+
+

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


+    Create privileges allowed:
+    
+ Retrieve privileges allowed: +
+ Update privileges allowed: +
+ Destroy privileges allowed: +
+ + +]]>
+ 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... + + 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'autres bouts de code de test pour confirmer cet effet, peut-être en nous connectant comme utilisateur et en essayant d'effectuer une mise à jour. +

+

+

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

+
+
+ + + Modifier les valeurs d'un formulaire et réussir à transmettre un simple formulaire + + + Gérer des objets à valeurs multiples en initialisant des listes. + + + Envoi brut quand il n'existe pas de bouton à cliquer. + + + + + La page du projet SimpleTest sur SourceForge. + + + La page de téléchargement de SimpleTest sur LastCraft. + + + L'API du développeur pour SimpleTest donne tous les détails sur les classes et les assertions disponibles. + + + + + développement logiciel, + programmation php pour des clients, + php centré sur le client, + outils de développement logiciel, + frameword de test de recette, + scripts php gratuits, + architecture, + ressources php, + HTMLUnit, + JWebUnit, + test php, + ressources de test unitaire, + test web + + +
+ diff --git a/tests/simpletest/docs/source/fr/gain_control_tutorial.xml b/tests/simpletest/docs/source/fr/gain_control_tutorial.xml new file mode 100644 index 00000000..c8c548f5 --- /dev/null +++ b/tests/simpletest/docs/source/fr/gain_control_tutorial.xml @@ -0,0 +1,215 @@ + + + Tutorial de test unitaire en PHP - Isoler les variables pendant le test + +

+ Pour tester un module de code vous avez besoin d'avoir un contrôle très précis sur son environnement. Si quelque chose change dans les coulisses, par exemple dans un fichier de configuration, alors les tests peuvent échouer de façon inattendue. Il ne s'agirait plus d'un test de code sans équivoque et pourrait vous faire perdre des heures précieuses à la recherche d'erreurs dans un code qui fonctionne. Alors qu'il s'agit d'un problème de configuration qui plante le test en question. Au mieux vos scénarios de test deviennent de plus en plus compliqués afin de prendre en compte toutes les variations possibles. +

+

+

Contrôler le temps

+

+

+ Il y a souvent beaucoup de variables évidentes qui peuvent affecter un scénario de test unitaire, d'autant plus dans un environnement de développement web dans lequel PHP a ses aises. Parmi celles-ci, on trouve les paramètres de connexion à la base de données et ceux de configuration, les droits de fichier et les ressources réseau, etc. L'échec ou la mauvaise installation de l'un ou l'autre de ces composants cassera la suite de test. Est-ce que nous devons ajouter des tests pour valider l'installation de ces composants ? C'est une bonne idée mais si vous les placez dans les tests du module de code vous aller commencer à encombrer votre code de test avec des détails hors de propos avec la tâche en cours. Ils doivent être placés dans leur propre groupe de tests. +

+

+ Par contre un autre problème reste : nos machines de développement doivent aussi avoir tous les composants système d'installés avant l'exécution de la suite de test. Et vos tests s'exécuteront plus lentement. +

+

+ Devant un tel dilemme, nous créerons souvent des versions enveloppantes des classes qui gèrent ces ressources. Les vilains détails de ces ressources sont ensuite codés une seule fois. J'aime bien appeler ces classes des "classes frontière" étant donné qu'elles existent en bordure de l'application, l'interface entre votre application et le reste du système. Ces classes frontière sont - dans le meilleur des cas - simulées pendant les tests par des versions de simulacre. Elles s'exécutent plus rapidement et sont souvent appelées "bouchon serveur [Ndt : Server Stubs]" ou dans leur forme plus générique "objet fantaisie [Ndt : Mock Objects]". Envelopper et bouchonner chacune de ces ressources permet d'économiser pas mal de temps. +

+

+ Un des facteurs souvent négligés reste le temps. Par exemple, pour tester l'expiration d'une session des codeurs vont souvent temporairement en caler la durée à une valeur très courte, disons 2 secondes, et ensuite effectuer un sleep(3) : ils estiment alors que la session a expirée. Sauf que cette opération ajoute 3 secondes à la suite de test : il s'agit souvent de beaucoup de code en plus pour rendre la classe de session aussi malléable. Plus simple serait d'avoir un moyen d'avancer l'horloge arbitrairement. De contrôler le temps. +

+

+

Une classe horloge

+ Une nouvelle fois, nous allons effectuer notre conception d'une enveloppe d'horloge via l'écriture de tests. Premièrement nous ajoutons un scénario de test d'horloge dans notre suite de test tests/all_tests.php... + + require_once('clock_test.php'); + + $test = &new GroupTest('All tests'); + $test->addTestCase(new TestOfLogging()); + $test->addTestCase(new TestOfClock()); + $test->run(new HtmlReporter()); +?> +]]> + Ensuite nous créons le scénario de test dans un nouveau fichier tests/clock_test.php... +UnitTestCase('Clock class test'); + } + function testClockTellsTime() { + $clock = new Clock(); + $this->assertEqual($clock->now(), time(), 'Now is the right time'); + } + function testClockAdvance() { + } + } +?> +]]> + Notre unique test pour le moment, c'est que notre nouvelle class Clock se comporte comme un simple substitut de la fonction time() en PHP. L'autre méthode tient lieu d'emploi. C'est notre chose à faire en quelque sorte. Nous ne lui avons pas donnée de test parce que ça casserait notre rythme. Nous écrirons cette fonctionnalité de décalage dans le temps une fois que nous serons au vert. Pour le moment nous ne sommes évidemment pas dans le vert... +
+
+ Fatal error: Failed opening required '../classes/clock.php' (include_path='') in + /home/marcus/projects/lastcraft/tutorial_tests/tests/clock_test.php on line 2 +
+
+ Nous créons un fichier classes/clock.php comme ceci... + +]]> + De la sorte nous reprenons le cours du code. +
+

All tests

+ Fail: Clock class test->testclocktellstime->[NULL: ] should be equal to [integer: 1050257362]
+
3/3 test cases complete. + 4 passes and 1 fails.
+
+ Facile à corriger... + + return time(); + } +} +]]> + Et nous revoici dans le vert... +
+

All tests

+
3/3 test cases complete. + 5 passes and 0 fails.
+
+ Il y a juste un petit problème. L'horloge pourrait basculer pendant l'assertion et créer un écart d'une seconde. Les probabilités sont assez faibles mais s'il devait y avoir beaucoup de tests de chronométrage nous finirions avec une suite de test qui serait erratique et forcément presque inutile. Nous nous y attaquerons bientôt et pour l'instant nous l'ajoutons dans la liste des "choses à faire". +

+

+ Le test d'avancement ressemble à... +UnitTestCase('Clock class test'); + } + function testClockTellsTime() { + $clock = new Clock(); + $this->assertEqual($clock->now(), time(), 'Now is the right time'); + } + function testClockAdvance() { + $clock = new Clock(); + $clock->advance(10); + $this->assertEqual($clock->now(), time() + 10, 'Advancement'); + } +} +]]> + Le code pour arriver au vert est direct : il suffit d'ajouter un décalage de temps. + + var $_offset; + + function Clock() { + $this->_offset = 0; + } + + function now() { + return time() + $this->_offset; + } + + function advance($offset) { + $this->_offset += $offset; + } +} +]]> +

+

+

Nettoyer le test de groupe

+ Notre fichier all_tests.php contient des répétitions dont nous pourrions nous débarrasser. Nous devons ajouter manuellement tous nos scénarios de test depuis chaque fichier inclus. C'est possible de les enlever mais avec les précautions suivantes. La classe GroupTest inclue une méthode bien pratique appelée addTestFile() qui prend un fichier PHP comme paramètre. Ce mécanisme prend note de toutes les classes : elle inclut le fichier et ensuite regarde toutes les classes nouvellement créées. S'il y a des filles de TestCase elles sont ajoutées au nouveau test de groupe. +

+

+ Voici notre suite de test remaniée en appliquant cette méthode... + + require_once(SIMPLE_TEST . 'unit_tester.php'); + require_once(SIMPLE_TEST . 'reporter.php'); + + $test = &new GroupTest('All tests'); + $test->addTestFile('log_test.php'); + $test->addTestFile('clock_test.php'); + $test->run(new HtmlReporter()); +?> +]]> + Les inconvéniants sont les suivants... +

    +
  1. + Si le fichier de test a déjà été inclus, aucune nouvelle classe ne sera ajoutée au groupe. +
  2. +
  3. + Si le fichier de test contient d'autres classes reliées à TestCase alors celles-ci aussi seront ajouté au test de groupe. +
  4. +
+ Dans nos test nous n'avons que des scénarios dans les fichiers de test et en plus nous avons supprimé leur inclusion du script all_tests.php : nous sommes donc en règle. C'est la situation la plus commune. +

+

+ Nous devrions corriger au plus vite le petit problème de décalage possible sur l'horloge : c'est ce que nous faisons ensuite. +

+
+ + Le temps est souvent une variable négligée dans les tests. + Une classe horloge nous permet de modifier le temps. + Nettoyer le test de groupe. + + + + La section précédente : grouper des tests unitaires. + + + La section suivante : sous classer les scénarios de test. + + + Vous aurez besoin du testeur unitaire SimpleTest pour les exemples. + + + + + développement logiciel, + programmation php, + outils de développement logiciel, + tutorial php, + scripts php gratuits, + organisation de tests unitaires, + conseil de test, + astuce de développement, + architecture logicielle pour des tests, + exemple de code php, + objets fantaisie, + junit, + test php, + outil de test unitaire, + suite de test php + + +
+ diff --git a/tests/simpletest/docs/source/fr/group_test_documentation.xml b/tests/simpletest/docs/source/fr/group_test_documentation.xml new file mode 100644 index 00000000..07d9505a --- /dev/null +++ b/tests/simpletest/docs/source/fr/group_test_documentation.xml @@ -0,0 +1,255 @@ + + + Documentation SimpleTest : 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... + +]]> + 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. + + 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 tests 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 tests, 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... + + 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... + + $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 à importer (via require_once()) le fichier de code de test et à instancier manuellement chaque scénario de test. Nous pouvons nous épargner beaucoup de dactylographie avec... + + $test->addTestFile('file_test.php'); + $test->run(new HtmlReporter()); +?> +]]> + 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 tests. 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 tests 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. +
+

+
+
+

+ 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 tests plus souple nous pouvons sous classer GroupTest et ensuite l'instancier au cas par cas... + + 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... + + $test = &new FileGroupTest(); + $test->run(new HtmlReporter()); +?> +]]> + ...ou alors nous pouvons les grouper dans un groupe de tests encore plus grand... + + $test = &new BigGroupTest('Big group'); + $test->addTestCase(new FileGroupTest()); + $test->addTestCase(...); + $test->run(new HtmlReporter()); +?> +]]> + Si nous souhaitons lancer le groupe de tests 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. +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 tests, 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é. +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(). + + $test->addTestFile('file_group_test.php'); + $test->addTestFile(...); + $test->run(new HtmlReporter()); +?> +]]> +

+
+
+

+ 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 PhpUnit dans 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 tests peut le reconnaître à partir du moment où nous mettons l'adaptateur approprié avant d'ajouter le fichier de test... + + 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... + + 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. +

+
+
+ + + Plusieurs approches pour grouper des tests ensemble. + + + Combiner des groupes des tests dans des groupes plus grands. + + + Intégrer des scénarios de test hérités d'un autre type de PHPUnit. + + + + + La page du projet SimpleTest sur SourceForge. + + + La page de téléchargement de SimpleTest sur LastCraft. + + + + + test unitaire en php, + intégration de test, + documentation, + marcus baker, + perrick penet, + test simple, + documentation simpletest, + phpunit, + pear + + +
+ diff --git a/tests/simpletest/docs/source/fr/group_test_tutorial.xml b/tests/simpletest/docs/source/fr/group_test_tutorial.xml new file mode 100644 index 00000000..748980be --- /dev/null +++ b/tests/simpletest/docs/source/fr/group_test_tutorial.xml @@ -0,0 +1,198 @@ + + + + Tutorial de test unitaire PHP - Grouper des tests unitaires et exemples d'écriture de scénarios de tests + + +

+ Pour enchaîner nous allons remplir des blancs et créer une suite de tests. +

+

+

Un autre test

+

+

+ Ajouter un autre test peut être aussi simple qu'ajouter une nouvelle méthode à un scénario de test... +UnitTestCase('Log class test'); + } + function testCreatingNewFile() { + @unlink('../temp/test.log'); + $log = new Log('../temp/test.log'); + $this->assertFalse(file_exists('../temp/test.log'), 'Created before message'); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('../temp/test.log'), 'File created'); + @unlink('../temp/test.log'); + } + function testAppendingToFile() { + @unlink('../temp/test.log'); + $log = new Log('../temp/test.log'); + $log->message('Test line 1'); + $messages = file('../temp/test.log'); + $this->assertWantedPattern('/Test line 1/', $messages[0]); + $log->message('Test line 2'); + $messages = file('../temp/test.log'); + $this->assertWantedPattern('/Test line 2/', $messages[1]); + @unlink('../temp/test.log'); + } +} +]]> + La méthode du scénario de test assertWantedPattern() utilise les expressions rationnelles Perl pour vérifier qu'une chaîne respecte un certain motif. +

+

+ Tout ce que nous faisons dans ce nouveau test, c'est écrire une ligne dans un fichier, puis la lire, le tout deux fois de suite. Nous souhaitons simplement vérifier que le loggueur ajoute le texte à la fin plutôt qu'écraser les données déjà existantes. Quelque peu pédant, mais après tout il s'agit d'un tutorial ! +

+

+ De toute façon ce test passe directement... +

+

Log class test

+
1/1 test cases complete. + 4 passes and 0 fails.
+
+ Notre code contient actuellement beaucoup de répétitions, nous devons effacer le fichier de test avant et après chaque test. De même que JUnit, SimpleTest utilise les méthodes setUp() et tearDown() qui sont exécutées respectivement avant et après chaque test. La suppression du fichier est commune à tous les tests : nous devrions donc y mettre cette opération. +

+

+ Nos tests sont verts donc nous pouvons faire un peu de remaniement... +UnitTestCase('Log class test'); + } + function setUp() { + @unlink('../temp/test.log'); + } + function tearDown() { + @unlink('../temp/test.log'); + } + function testCreatingNewFile() { + $log = new Log('../temp/test.log'); + $this->assertFalse(file_exists('../temp/test.log'), 'Created before message'); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('../temp/test.log'), 'File created'); + } + function testAppendingToFile() { + $log = new Log('../temp/test.log'); + $log->message('Test line 1'); + $messages = file('../temp/test.log'); + $this->assertWantedPattern('/Test line 1/', $messages[0]); + $log->message('Test line 2'); + $messages = file('../temp/test.log'); + $this->assertWantedPattern('/Test line 2/', $messages[1]); + } +} +]]> + Le test reste vert. Nous pouvons continuer à ajouter des méthodes sans test au scénario, il suffit que leur nom ne commence pas par la chaîne "test". Seules les méthodes commençant par "test" sont exécutées. Nous pouvons donc continuer le remaniement... +UnitTestCase('Log class test'); + } + function setUp() { + @unlink('../temp/test.log'); + } + function tearDown() { + @unlink('../temp/test.log'); + } + function getFileLine($filename, $index) { + $messages = file($filename); + return $messages[$index]; + } + function testCreatingNewFile() { + $log = new Log('../temp/test.log'); + $this->assertFalse(file_exists('../temp/test.log'), 'Created before message'); + $log->message('Should write this to a file'); + $this->assertTrue(file_exists('../temp/test.log'), 'File created'); + } + function testAppendingToFile() { + $log = new Log('../temp/test.log'); + $log->message('Test line 1'); + $this->assertWantedPattern('/Test line 1/', $this->getFileLine('../temp/test.log', 0)); + $log->message('Test line 2'); + $this->assertWantedPattern('/Test line 2/', $this->getFileLine('../temp/test.log', 1)); + } +} +]]> + Que vous préfériez cette version ou la précédente ne dépend que de votre goût personnel. Il y a un peu plus de code dans cette dernière mais la logique du test est plus claire. +

+

+

Un groupe de tests

+ Un scénario de test ne fonctionne pas tout seul pendant très longtemps. Quand on code pour de vrai nous souhaitons exécuter un maximum de tests aussi souvent et aussi rapidement que possible. Ça veut dire les grouper dans des suites de tests qui incluent l'ensemble des tests de l'application. +

+

+ Premièrement nous devons supprimer le code d'exécution des tests se trouvant dans notre scénario de test. + + require_once('../classes/log.php'); + + class TestOfLogging extends UnitTestCase { + ... + } +?> +]]> + Nous n'avons plus besoin de la constante SIMPLE_TEST. Ensuite nous créons un groupe de tests appelé all_tests.php dans le répertoire tests... +addTestCase(new TestOfLogging()); + $test->run(new HtmlReporter()); +?> +]]> + Il n'y a presque de pas de différence tant que les choses marchent... +

+

All tests

+
1/1 test cases complete. + 4 passes and 0 fails.
+
+ Les tests du groupe s'ajoutent au compteur des scénarios de test. Ajouter des nouveaux scénarios de test est très simple. Il suffit d'inclure le fichier d'un scénario et d'ajouter individuellement tous les scénarios autonomes. Vous pouvez aussi emboîter les groupes de test les uns dans les autres (tout en faisant bien attention d'éviter les boucles). +

+

+ Dans la page suivante nous les ajouterons encore plus rapidement. +

+
+ + + Ajouter un autres test au scénario existant et remanier. + + + La technique brute pour grouper des tests unitaires. + + + + + Ensuite vient le contrôle de comment la classe sous le test interagit avec le reste du système. + + + Avant il y a la création du premier test. + + + Vous aurez besoin de SimpleTest pour exécuter ces exemples. + + + + + développement logiciel, + programmation php, + outils de développement logiciel, + tutorial php, + scripts php gratuits, + pilotage par les tests, + architecture, + ressouces php, + objets fantaisie, + junit, + test php, + test unitaire, + phpunit, + test unitaire php + + +
+ diff --git a/tests/simpletest/docs/source/fr/improving_design_tutorial.xml b/tests/simpletest/docs/source/fr/improving_design_tutorial.xml new file mode 100644 index 00000000..f9944bd5 --- /dev/null +++ b/tests/simpletest/docs/source/fr/improving_design_tutorial.xml @@ -0,0 +1,137 @@ + + + + tutoriel de test unitaire en PHP - Conception du haut vers le bas, tester d'abord avec des objets fantaisie + + +

+

Commencer par la fantaisie, passer au code ensuite

+

+

+ J'ai menti. +

+

+ Je n'ai pas créé de test pour le scripteur, uniquement l'interface FileWriter que j'ai affiché plus tôt. En fait je vais encore m'éloigner d'un article fini et présumer l'existence un scripteur abstrait dans classes/writer.php... +Writer { + + function Writer() { + } + + function write($message) { + } + } +?> +]]> + Les changements correspondant au niveau du test sont... + + Mock::generate('Writer'); + + class TestOfLogging extends UnitTestCase { + function TestOfLogging() { + $this->UnitTestCase('Log class test'); + } + function testWriting() { + $clock = &new MockClock($this); + $clock->setReturnValue('now', 'Timestamp'); + $writer = &new MockWriter($this); + $writer->expectOnce('write', array('[Timestamp] Test line')); + $log = &new Log($writer); + $log->message('Test line', &$clock); + $writer->tally(); + } + } +?> +]]> + Afin d'utiliser la classe de log, nous aurions besoin de coder un scripteur de fichier - ou un autre type de scripteur - mais pour le moment nous ne faisons que des tests et nous n'en avons pas encore besoin. En d'autres termes, en utilisant des objets fantaisie nous pouvons décaler la création d'un objet de niveau plus bas jusqu'au moment opportun. Non seulement nous pouvons faire la conception du haut vers le bas, mais en plus nous pouvons aussi tester du haut vers le bas. +

+

+

S'approcher du bridge - pont

+

+

+ Imaginez pour un moment que nous ayons commencé la classe de log à partir d'une autre direction. Simulez avoir écrit juste assez du Log pour avoir réaliser le besoin d'un Writer. Comme l'aurions-nous inclus ? +

+

+ Bon, l'héritage du scripteur ne nous aurait pas permis de le simuler du point de vue des tests. De celui de la conception nous aurions été restreint à un unique scripteur sans héritage multiple. +

+

+ Créer un scripteur interne, plutôt qu'en le passant au constructeur, en choisissant un nom de classe, est possible, mais nous aurions moins de contrôle sur l'initialisation de l'objet fantaisie. Du point de vue de la conception il aurait été presque impossible de passer des paramètres au scripteur dans tous les formats possibles et envisageables. Vous auriez dû restreindre le scripteur à un hash ou à une chaîne compliquée décrivant tous les détails de la cible. Au mieux compliqué sans raison. +

+

+ Utiliser une méthode fabrique pour créer le scripteur intérieurement serait possible, mais ça voudrait dire le sous classer pour les tests de manière à remplacer la méthode fabrique par une autre méthode renvoyant un leurre. Plus de boulot du point de vue des tests, quoique toujours possible. Du point de vue de la conception, ça voudrait dire créer une nouvelle sous-classe de log pour chaque type de scripteur. Cela s'appelle une hiérarchie de classe parallèle et fait bien entendu à de la duplication. Beurk. +

+

+ A l'autre extrême, passer ou créer le scripteur à chaque message aurait été répétitif et aurait réduit le code de la classe Log à une unique méthode, un signe certain que toute la classe est devenue redondante. +

+

+ Cette tension entre la facilité du test et le refus de la répétition nous a permis de trouver une conception à la fois flexible et propre. Vous vous souvenez de notre bref envie de l'héritage multiple ? Nous l'avons remplacé par du polymorphisme (plein de scripteurs) et séparé la hiérarchie du journal de celle de l'écriture. Nous relions les deux par agrégation à travers le plus simple Log. Cette astuce est en fait un design pattern (modèle de conception) appelé "Pont" ou "Bridge". +

+

+ Donc nous avons été poussé par le code de test (nous n'avons presque rien écrit d'autre) vers un design pattern. Pensez-y une seconde. Les tests améliorent la qualité du code, à coup sûr dans mon cas, mais il y a quelque chose de bien plus profond et plus puissant. +

+

+ Les tests ont amélioré la conception. +

+

+

Simuler la conception

+

+

+ Créer un objet fantaisie est aussi simple que de créer l'interface à l'écrit. Si vous utilisez de l'UML ou d'autres outils pour générer ces interfaces alors vous avez un chemin encore plus flexible pour générer rapidement vos objets de test. Même sans, vous pouvez passer du dessin sur tableau blanc, à l'écriture de l'objet fantaisie, puis à la génération de l'interface qui nous renvoie de nouveau au tableau blanc, le tout très simplement. Comme le remaniement, la conception, le code et les tests s'unifient. +

+

+ Parce que les objets fantaisie travaillent du haut vers le bas, ils peuvent être amenés dans la conception plus rapidement qu'un remaniement classique qui demande quant à lui du code fonctionnel avant de pourvoir s'installer. Ça veut dire que le code de test interagit plus vite avec la conception : par conséquent la qualité de la conception augmente elle aussi plus vite. +

+

+ Un testeur unitaire est un outil de code. Un testeur unitaire avec objet fantaisie est un outil de conception. +

+
+ + + Simuler maintenant, coder plus tard. + + + Nous dérivons vers le design pattern bridge. + + + Conception et test main dans la main. + + + + + Ce tutorial suit les classes frontière. + + + Vous aurez besoin du framework de test SimpleTest pour essayer ces exemples. + + + Pour des discussions plus fournis sur les objets fantaisie, voyez le Wiki des Extreme Tuesday ou le Wiki C2 (en anglais tous les deux). + + + + + développement logiciel, + tutoriel de programmation php, + scénarios de test en php, + outils de développement logiciel, + tutorial php, + scripts php gratuits, + architecture, + exemple php, + exemple d'objet fantaisie, + test style junit, + architecture logicielle pour des tests, + framework de test en php, + test unitaire, + objet fantaisie en php + test php, + suite de test php + + +
+ diff --git a/tests/simpletest/docs/source/fr/index.xml b/tests/simpletest/docs/source/fr/index.xml new file mode 100644 index 00000000..ed4eb5fe --- /dev/null +++ b/tests/simpletest/docs/source/fr/index.xml @@ -0,0 +1,68 @@ + + + + Les articles de :: onpk :: sur php / simpletest : traductions en français des articles publiés sur Lastcraft.com + + + +

+ Cette section rassemble l'ensemble des articles et documentations pour SimpleTest traduits en français. +

+
+
+

+ J'ai commencé par découvrir l'Extreme Programming via le web. Ensuite j'ai gagné un livre en français sur XP. Et découvrant la confiance supplémentaire gagnée via les tests unitaires et de recette, je suis devenu "test-infected". +

+

+ Après avoir goûté aux joies de SimpleTest, j'ai contacté Marcus Baker -- responsable du projet -- pour lui proposer de traduire en français la page d'introduction, puis les tutoriaux et finalement toute la documentation. Un travail qui n'aurait pas été possible sans l'aide de quelques relecteurs bienveillants : Jérémie C., David B., Emmanuel G., Olivier L. et Cédric G. (dans le désordre). +

+

+ Si vous lisez attentivement ces quelques pages et que vous y trouvez encore des fautes d'orthographe, pensez à me les renvoyer : comme ça le prochain ne pourra pas se dire la même chose. +

+
+
+

+ J'ai un blog -- :: onpk ::, une entreprise -- No Parking dont le produit phare est openTIME. Dans la communauté je me ballade du côté de l'AFUP, des apéros PHP et des praticiens XP. +

+
+
+

+

+
+
+ + + Comment en arrive-t-on au développement piloté par les tests ? + + + Et en dehors des tests ? + + + Tous les articles + + + + + SimpleTest -- l'original en anglais. + + + + + développement logiciel, + programmation php, + outils de développement logiciel, + tutorial php, + scripts php gratuits, + conseil de test, + architecture logicielle pour des tests, + exemple de code php, + junit, + test php, + outil de test unitaire, + suite de test php + + + Des articles (documentations et tutoriels) pour découvrir le développement agile en PHP avec le framework de tests unitaires SimpleTest. + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/fr/intro.xml b/tests/simpletest/docs/source/fr/intro.xml new file mode 100644 index 00000000..7609c7fa --- /dev/null +++ b/tests/simpletest/docs/source/fr/intro.xml @@ -0,0 +1,36 @@ + + + + Les articles de :: onpk :: sur php / simpletest : traductions en français des articles publiés sur Lastcraft.com + + +

+ Le testeur unitaire SimpleTest PHP a enfin atteint la délicate version 1.0 : il est disponible au téléchargement chez votre SourceForge le plus proche. +

+

+ Il s'agit d'un testeur unitaire PHP et aussi d'un testeur web. Il est construit pour être extensible de plusieurs manières. Les utilisateurs de JUnit seront familiers avec la plupart des interfaces. L'affichage des tests est largement modifiable tout comme le scénario de test de base. Par ailleurs les objets fantaisie peuvent être utilisés avec d'autres testeurs unitaires. +

+

+ Les fonctionnalités à-la-JWebUnit sont plus complètes aussi. Il y a le support pour SSL, les fenêtres, les proxies, l'authentification simple et un large choix de contrôles HTML. L'idée est que les tâches fastidieuses en PHP, se connecter à un site par exemple, puissent être testées facilement. +

+
+ + + développement logiciel, + programmation php, + outils de développement logiciel, + tutorial php, + scripts php gratuits, + conseil de test, + architecture logicielle pour des tests, + exemple de code php, + junit, + test php, + outil de test unitaire, + suite de test php + + + Des articles (documentations et tutoriels) pour découvrir le développement agile en PHP avec le framework de tests unitaires SimpleTest. + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/fr/mock_objects_documentation.xml b/tests/simpletest/docs/source/fr/mock_objects_documentation.xml new file mode 100644 index 00000000..ebd461cf --- /dev/null +++ b/tests/simpletest/docs/source/fr/mock_objects_documentation.xml @@ -0,0 +1,458 @@ + + + Documentation SimpleTest : les objets fantaise + +
+

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

+

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

+

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

+

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

+
+
+

+ Comme pour la création des bouchons serveur, tout ce dont nous avons besoin c'est d'un classe existante. La fameuse connexion à une base de données qui ressemblerait à... +class DatabaseConnection { + function DatabaseConnection() { + } + + function query() { + } + + function selectQuery() { + } +} +]]> + Cette classe n'a pas encore besoin d'être implémentée. Pour en créer sa version fantaisie nous devons juste inclure la librairie d'objet fantaisie puis lancer le générateur... +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... + +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 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 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... + + 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... + + $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... + + 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... +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... + + Dans ce cas vous pouvez placer une référence dans la liste renvoyée par l'objet fantaisie... + +$vector = &new MockVector($this); +$vector->setReturnReference('get', $thing, array(12)); +]]> + Avec cet arrangement vous savez qu'à chaque appel de get(12)]]> le même $thing sera renvoyé. +

+
+
+

+ 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 session (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... + + $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 sortie 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 optionnel pour expectOnce() et expectAtLeastOnce(). +
+
$timing
+
+ Le seul point dans le temps pour tester la condition. Le premier appel commence à zéro. +
+
$count
+
Le nombre d'appels attendu.
+
+ La méthode expectMaximumCallCount() est légèrement différente dans le sens où elle ne pourra générer qu'un échec. Elle reste silencieuse si la limite n'est jamais atteinte. +

+

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

+
+
+

+ Il existe trois approches pour créer des objets fantaisie en comprenant celle utilisée 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'écrits 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 l'héritage pour hériter pour surcharger des méthodes spéciales ou ajouter des préréglages... + + 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. +

+
+
+

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

+

+ Non, pas du tout. + SimpleTest est une boîte à outils et parmi ceux-ci on trouve les objets fantaisie qui peuvent être utilisés indépendamment. Supposons que vous avez votre propre testeur unitaire favori et que tous vos tests actuels l'utilisent. Prétendez que vous avez appelé votre tester unitaire PHPUnit (c'est ce que tout le monde a fait) et que la classe principale de test ressemble à... + + La seule chose que la méthode assertion() réalise, c'est de préparer une sortie embellie alors le paramètre boolien de l'assertion sert à déterminer s'il s'agit d'une erreur ou d'un succès. Supposons qu'elle est utilisée de la manière suivante... +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... +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... +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. +

+
+
+ + + Que sont les objets fantaisie ? + + + Créer des objets fantaisie. + + + L'objet fantaisie - acteur ou bouchon. + + + L'objet fantaisie - critique avec des attentes. + + + D'autres approches y compris des librairies d'objets fantaisie. + + + Utiliser les objets fantaisie avec d'autres testeurs unitaires. + + + + + L'article originel sur les objets fantaisie. + + + La page du projet SimpleTest sur SourceForge. + + + La page d'accueil de SimpleTest sur LastCraft. + + + + + développement logiciel, + programmation en php, + outils de développement logiciel, + tutoriel php, + scripts php gratuits, + architecture, + ressources php, + mock objects, + objets fantaisie, + junit, + test php, + test unitaire, + tester en php + + +
+ diff --git a/tests/simpletest/docs/source/fr/mock_objects_tutorial.xml b/tests/simpletest/docs/source/fr/mock_objects_tutorial.xml new file mode 100644 index 00000000..21c59b5e --- /dev/null +++ b/tests/simpletest/docs/source/fr/mock_objects_tutorial.xml @@ -0,0 +1,269 @@ + + + tutorial sur les tests unitaires en PHP - Utiliser les objets fantaisie en PHP + +

+

Remanier les tests à nouveau

+

+

+ Avant d'ajouter de nouvelles fonctionnalités il y a du remaniement à faire. Nous allons effectuer des tests chronométrés et la classe TimeTestCase a définitivement besoin d'un fichier propre. Appelons le tests/time_test_case.php... +UnitTestCase($test_name); + } + function assertSameTime($time1, $time2, $message = '') { + if (! $message) { + $message = "Time [$time1] should match time [$time2]"; + } + $this->assertTrue( + ($time1 == $time2) || ($time1 + 1 == $time2), + $message); + } + } +?> +]]> + Nous pouvons lors utiliser require() pour incorporer ce fichier dans le script all_tests.php. +

+

+

Ajouter un timestamp au Log

+

+

+ Je ne sais pas trop quel devrait être le format du message de log pour le test alors pour vérifier le timestamp nous pourrions juste faire la plus simple des choses possibles, c'est à dire rechercher une suite de chiffres. + + require_once('../classes/clock.php'); + + class TestOfLogging extends TimeTestCase { + function TestOfLogging() { + $this->TimeTestCase('Log class test'); + } + function setUp() { + @unlink('../temp/test.log'); + } + function tearDown() { + @unlink('../temp/test.log'); + } + function getFileLine($filename, $index) { + $messages = file($filename); + return $messages[$index]; + } + function testCreatingNewFile() { + ... + } + function testAppendingToFile() { + ... + } + function testTimestamps() { + $log = new Log('../temp/test.log'); + $log->message('Test line'); + $this->assertTrue( + preg_match('/(\d+)/', $this->getFileLine('../temp/test.log', 0), $matches), + 'Found timestamp'); + $clock = new clock(); + $this->assertSameTime((integer)$matches[1], $clock->now(), 'Correct time'); + } + } +?> +]]> + Ce scénario de test crée un nouvel objet Log et écrit un message. Nous recherchons une suite de chiffres et nous la comparons à l'horloge présente en utilisant notre objet Clock. Bien sûr ça ne marche pas avant d'avoir écrit le code. +

+

All tests

+ Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]
+ Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]
+ Pass: log_test.php->Log class test->testcreatingnewfile->Created before message
+ Pass: log_test.php->Log class test->testcreatingnewfile->File created
+ Fail: log_test.php->Log class test->testtimestamps->Found timestamp
+
+ Notice: Undefined offset: 1 in /home/marcus/projects/lastcraft/tutorial_tests/tests/log_test.php on line 44
+ Fail: log_test.php->Log class test->testtimestamps->Correct time
+ Pass: clock_test.php->Clock class test->testclockadvance->Advancement
+ Pass: clock_test.php->Clock class test->testclocktellstime->Now is the right time
+
3/3 test cases complete. + 6 passes and 2 fails.
+
+ Cette suite de tests montre encore les succès de notre modification précédente. +

+

+ Nous pouvons faire passer les tests en ajoutant simplement un timestamp à l'écriture dans le fichier. Oui, bien sûr, tout ceci est assez trivial et d'habitude je ne le testerais pas aussi fanatiquement, mais ça va illustrer un problème plus général... Le fichier log.php devient... + + require_once('../classes/clock.php'); + + class Log { + var $_file_path; + + function Log($file_path) { + $this->_file_path = $file_path; + } + + function message($message) { + $clock = new Clock(); + $file = fopen($this->_file_path, 'a'); + fwrite($file, "[" . $clock->now() . "] $message\n"); + fclose($file); + } + } +?> +]]> + Les tests devraient passer. +

+

+ Par contre notre nouveau test est plein de problèmes. Qu'est-ce qui se passe si notre format de temps change ? Les choses vont devenir largement plus compliquées si ça venait à se produire. Cela veut aussi dire que n'importe quel changement du format de notre classe horloge causera aussi un échec dans les tests de log. Bilan : nos tests de log sont tout mélangés avec les test d'horloge et par la même très fragiles. Tester à la fois des facettes de l'horloge et d'autres du log manque de cohésion, ou de focalisation étanche si vous préférez. Nos problèmes sont causés en partie parce que le résultat de l'horloge est imprévisible alors que l'unique chose à tester est la présence du résultat de Clock::now(). Peu importe le contenu de l'appel de cette méthode. +

+

+ Pouvons-nous rendre cet appel prévisible ? Oui si nous pouvons forcer le loggueur à utiliser une version factice de l'horloge lors du test. Cette classe d'horloge factice devrait se comporter exactement comme la classe Clock à part une sortie fixée dans la méthode now(). Et au passage, ça nous affranchirait même de la classe TimeTestCase ! +

+

+ Nous pourrions écrire une telle classe assez facilement même s'il s'agit d'un boulot plutôt fastidieux. Nous devons juste créer une autre classe d'horloge avec la même interface sauf que la méthode now() retourne une valeur modifiable via une autre méthode d'initialisation. C'est plutôt pas mal de travail pour un test plutôt mineur. +

+

+ Sauf que ça se fait sans aucun effort. +

+

+

Une horloge fantaisie

+

+

+ Pour atteindre le nirvana de l'horloge instantané pour test nous n'avons besoin que de trois lignes de code supplémentaires... + + Cette instruction inclut le code de générateur d'objet fantaisie. Le plus simple reste de le mettre dans le script all_tests.php étant donné qu'il est utilisé assez fréquemment. + + C'est la ligne qui fait le travail. Le générateur de code scanne la classe, en extrait toutes ses méthodes, crée le code pour générer une classe avec une interface identique, mais en ajoutant le nom "Mock" et ensuite eval() le nouveau code pour créer la nouvelle classe. + + Cette ligne peut être ajoutée dans n'importe quelle méthode de test qui nous intéresserait. Elle crée l'horloge fantaisie prête à recevoir nos instructions. +

+

+ Notre scénario de test en est à ses premiers pas vers un nettoyage radical... + + Mock::generate('Clock'); + + class TestOfLogging extends UnitTestCase { + function TestOfLogging() { + $this->UnitTestCase('Log class test'); + } + function setUp() { + @unlink('../temp/test.log'); + } + function tearDown() { + @unlink('../temp/test.log'); + } + function getFileLine($filename, $index) { + $messages = file($filename); + return $messages[$index]; + } + function testCreatingNewFile() { + ... + } + function testAppendingToFile() { + ... + } + function testTimestamps() { + $clock = &new MockClock($this); + $clock->setReturnValue('now', 'Timestamp'); + $log = new Log('../temp/test.log'); + $log->message('Test line', &$clock); + $this->assertWantedPattern( + '/Timestamp/', + $this->getFileLine('../temp/test.log', 0), + 'Found timestamp'); + } + } +?> +]]> + Cette méthode de test crée un objet MockClock puis définit la valeur retourné par la méthode now() par la chaîne "Timestamp". A chaque fois que nous appelons $clock->now(), elle retournera cette même chaîne. Ça devrait être quelque chose de facilement repérable. +

+

+ Ensuite nous créons notre loggueur et envoyons un message. Nous incluons dans l'appel message() l'horloge que nous souhaitons utiliser. Ça veut dire que nous aurons à ajouter un paramètre optionnel à la classe de log pour rendre ce test possible... +_file_path = $file_path; + } + + function message($message, $clock = false) { + if (!is_object($clock)) { + $clock = new Clock(); + } + $file = fopen($this->_file_path, 'a'); + fwrite($file, "[" . $clock->now() . "] $message\n"); + fclose($file); + } +} +]]> + Maintenant tous les tests passent et ils ne testent que le code du loggueur. Nous pouvons à nouveau respirer. +

+

+ Est-ce que ce paramètre supplémentaire dans la classe Log vous gêne ? Nous n'avons changé l'interface que pour faciliter les tests après tout. Les interfaces ne sont-elles pas la chose la plus importante ? Avons nous souillé notre classe avec du code de test ? +

+

+ Peut-être, mais réfléchissez à ce qui suit. A la prochaine occasion, regardez une carte avec des circuits imprimés, peut-être la carte mère de l'ordinateur que vous regardez actuellement. Sur la plupart d'entre elles vous trouverez un trou bizarre et vide ou alors un point de soudure sans rien de fixé ou même une épingle ou une prise sans aucune fonction évidente. Peut-être certains sont là en prévision d'une expansion ou d'une variation future, mais la plupart n'y sont que pour les tests. +

+

+ Pensez-y. Les usines qui fabriquent ces cartes imprimées par centaine de milliers gaspillent des matières premières sur des pièces qui n'ajoutent rien à la fonction finale. Si les ingénieurs matériel peuvent faire quelques sacrifices à l'élégance, je suis sûr que nous pouvons aussi le faire. Notre sacrifice ne gaspille pas de matériel après tout. +

+

+ Ça vous gêne encore ? En fait moi aussi, mais pas tellement ici. La priorité numéro 1 reste du code qui marche, pas un prix pour minimalisme. Si ça vous gêne vraiment alors déplacez la création de l'horloge dans une autre méthode mère protégée. Ensuite sous classez l'horloge pour le test et écrasez la méthode mère avec une qui renvoie le leurre. Vos tests sont bancals mais votre interface est intacte. +

+

+ Une nouvelle fois je vous laisse la décision finale. +

+
+ + + Remanier les tests dans le but de réutiliser notre nouveau test de temps. + + Ajouter des timestamps de Log. + Créer une horloge fantaisie pour rendre les tests cohésifs. + + + + La section précédente : tutorial de test unitaire. + + + La section suivante : les frontières de l'application. + + + Vous aurez besoin du framework de test SimpleTest pour essayer ces exemples. + + + Documents sur les objets fantaisie. + + + + + développement logiciel, + programmation php, + outils de développement logiciel, + tutoriel php, + scripts php gratuits, + architecture, + ressources php, + objet fantaisie, + junit, + phpunit, + simpletest, + test php, + outil de test unitaire, + suite de test php + + +
+ diff --git a/tests/simpletest/docs/source/fr/overview.xml b/tests/simpletest/docs/source/fr/overview.xml new file mode 100644 index 00000000..ad1188a7 --- /dev/null +++ b/tests/simpletest/docs/source/fr/overview.xml @@ -0,0 +1,295 @@ + + + + Aperçu et liste des fonctionnalités des testeurs unitaires PHP et web de SimpleTest PHP + + +
+

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

+

+ Un scénario de test ressemble à... +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 à... +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/'); + } +} +]]> +

+
+
+

+ 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 tests 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
Test de l'upload de fichierPeut simuler la balise input de type file1.0.1
Amélioration sur la machinerie des rapportsRetouche sur la transmission des messages pour une meilleur coopération avec les IDEs1.1
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
+ La migration vers PHP5 commencera juste après la série des 1.0, à partir de là PHP4 ne sera plus supporté. SimpleTest est actuellement compatible avec PHP5 mais n'utilisera aucune des nouvelles fonctionnalités avant la version 2. +

+
+
+

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

+

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

+

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

+

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

+

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

+
+
+ + + Résumé rapide de l'outil SimpleTest pour PHP. + + + La liste des fonctionnalites, à la fois présentes et à venir. + + + Il y a beaucoup de ressources sur les tests unitaires sur le web. + + + + + Documentation pour SimpleTest. + + + Comment écrire des scénarios de test en PHP est un tutoriel plutôt avancé. + + + L'API de SimpleTest par phpdoc. + + + + + outils de développement logiciel, + programmation php, + outils pour l'extreme programming, + liens pour des outils de test, + ressources pour test en php, + objets fantaise, + junit, + jwebunit, + htmlunit, + itc, + liens pour tests en php, + conseil et documentation pour test unitaire, + extreme programming en php + + + + + + Marcus Baker + + Développeur principal{@link mailto:marcus@lastcraft.com marcus@lastcraft.com} + + + + Harry Fuecks + + Packageur{@link mailto:harryf@users.sourceforge.net harryf@users.sourceforge.net} + + + + Jason Sweat + + Documentation{@link mailto:jsweat_php@yahoo.com jsweat_php@yahoo.com} + + + + Perrick Penet + + Traduction{@link mailto:perrick@onpk.net perrick@onpk.net} + + + + +
+ diff --git a/tests/simpletest/docs/source/fr/partial_mocks_documentation.xml b/tests/simpletest/docs/source/fr/partial_mocks_documentation.xml new file mode 100644 index 00000000..9a523901 --- /dev/null +++ b/tests/simpletest/docs/source/fr/partial_mocks_documentation.xml @@ -0,0 +1,306 @@ + + + Documentation SimpleTest : 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à. +

+
+
+

+ 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... +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... +function &connect(&$socket, $username, $password) { + $socket->read( ... ); + ... + } + } +?> +]]> + Sous-entendu, votre code de test est typique d'un cas de test avec un objet fantaisie. + + $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... + + 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... + + $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... + + 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... + + $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 ? +

+
+
+

+ 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... + + $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... + + $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 ? +

+
+
+

+ 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... +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(); + } +} +]]> +

+
+
+

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

+

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

+
+
+ + + Le problème de l'injection d'un objet fantaisie. + + + Déplacer la création vers une méthode fabrique protégée. + + + L'objet fantaisie partiel génère une sous-classe. + + + Les objets fantaisie partiels testent moins qu'une classe. + + + + + La page du projet SimpleTest sur SourceForge. + + + L'API complète pour SimpleTest à partir de PHPDoc. + + + La méthode fabrique protégée est décrite dans cet article d'IBM. Il s'agit de l'unique papier formel que j'ai vu sur ce problème. + + + + + développement logiciel en php, + dévelopement d'un scénario de test en php, + programmation php avec base de données, + outils de développement logiciel, + tutoriel avancé en php, + scripts à la manière de phpunit, + architecture, + ressources php, + objets fantaisie, + junit, + framework de test en php, + test unitaire, + test en php + + +
+ diff --git a/tests/simpletest/docs/source/fr/reporter_documentation.xml b/tests/simpletest/docs/source/fr/reporter_documentation.xml new file mode 100644 index 00000000..e6d4d6b2 --- /dev/null +++ b/tests/simpletest/docs/source/fr/reporter_documentation.xml @@ -0,0 +1,341 @@ + + + Documentation SimpleTest : le rapporteur de test + + +

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

+
+
+

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

+

File test

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

File test

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

+

+ Pour l'affichage basé sur des pages web, il y a la classe HtmlReporter avec la signature suivante... + + 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 tests 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 tests indique au rapporteur le nombre de scénarios de test qu'il contient. De la sorte le rapporteur peut afficher une barre de progrès au fur et à mesure que l'exécuteur passe en revue les scénarios de test. +
  • +
  • + void paintMethodEnd(string $test_name)
    + clôt le test lancé avec le même nom. +
  • +
  • + void paintFail(string $message)
    + peint un échec. Par défaut il ne fait qu'afficher le mot "fail", une trace d'arborescence affichant la position du test en cours et le message transmis par l'assertion. +
  • +
  • + 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 "&Pass: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode("->", $breadcrumb); + print "->$message
\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 l'affichage, par exemple, d'une vue en arbre de la suite de test. Avec un rapporteur lancé sur une exécution sèche qui ne renverrait que les évènements d'affichage, cela devient facilement réalisable. +

+
+
+

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

+
+
+

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

+
+
+

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


+
+  
+    Remote tests
+    
+      Visual test with 48 passes, 48 fails and 4 exceptions
+      
+        testofunittestcaseoutput
+        
+          testofresults
+          This assertion passed
+          This assertion failed
+        
+        
+          ...
+        
+      
+    
+  
+
+]]>
+ 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... +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 très grandes suites de test , 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 parsé à nouveau pour agréger 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... +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 tests. +

+
+
+ + + Afficher les résultats en HTML + + + Afficher et rapporter les résultats dans d'autres formats + + + Utilisé SimpleTest depuis la ligne de commande + + + Utiliser XML pour des tests distants + + + + + La page du projet SimpleTest sur SourceForge. + + + La page de téléchargement de SimpleTest sur LastCraft. + + + L'API pour développeur de SimpleTest donne tous les détails sur les classes et les assertions disponibles. + + + + + test unitaire en php, + documentation, + marcus baker, + perrick penet + test simple, + simpletest, + test distant, + tests xml, + test automatisé + + +
+ diff --git a/tests/simpletest/docs/source/fr/server_stubs_documentation.xml b/tests/simpletest/docs/source/fr/server_stubs_documentation.xml new file mode 100644 index 00000000..25d59bc6 --- /dev/null +++ b/tests/simpletest/docs/source/fr/server_stubs_documentation.xml @@ -0,0 +1,251 @@ + + + Documentation SimpleTest : 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. +

+
+
+

+ 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... + +$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 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 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'une base de données imaginaire ou alors une liste d'objets persistants. Peu importe les paramètres, nous obtenons systématiquement les même valeurs chaque fois qu'ils ont été initialisés de la sorte : ça ne ressemble peut-être pas à une réponse convaincante venant d'une connexion vers une base de données. Mais pour la demi-douzaine de lignes d'une méthode de test c'est souvent largement suffisant. +

+
+
+

+ Sauf que les choses ne sont que rarement aussi simples. Parmi les problèmes les plus courants on trouve les itérateurs : le renvoi d'une valeur constante peut causer une boucle infini dans l'objet testé. Pour ceux-ci nous avons besoin de mettre sur pied une suite de valeurs. Prenons par exemple un itérateur simple qui ressemble à... + + 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... + + 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... +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... + + Dans ce cas vous pouvez mettre une référence dans la liste renvoyée par le bouchon... + +$vector = &new StubVector(); +$vector->setReturnReference('get', $thing, array(12)); +]]> + Avec ce petit arrangement vous vous assurez qu'à chaque fois que 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->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 une 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... + + $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. +

+
+
+

+ 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... +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 utilisé 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". +

+
+
+ + + Que sont les bouchons ? + + + Créer des bouchons serveur avec SimpleTest. + + + Modèles de simulation pour simuler des interactions d'objet plus complexes. + + + Options à la génération pour différents contextes. + + + + + La page du projet SimpleTest sur SourceForge. + + + La page de téléchargement de SimpleTest sur LastCraft. + + + L'API complète pour SimpleTest générée par PHPDoc. + + + + + développement logiciel, + programmation php, + outils de développement logiciel, + tutoriel php, + outil gratuit de test pour php, + architecture, + ressuorces php, + objets fantaisie, + prototypage avec langage de scripts, + bouchons serveur, + test unitaire, + prototypage en php, + méthodes de test, + méthodologie de test + + +
+ diff --git a/tests/simpletest/docs/source/fr/simple_test.xml b/tests/simpletest/docs/source/fr/simple_test.xml new file mode 100644 index 00000000..fb923bbe --- /dev/null +++ b/tests/simpletest/docs/source/fr/simple_test.xml @@ -0,0 +1,339 @@ + + + + Prise en main rapide de SimpleTest pour PHP - Tests unitaire et objets fantaisie pour PHP + + + +

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

+
+
+

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

+

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

+

+ Supposons que nous sommes en train de tester une simple classe de log dans un fichier : elle s'appelle Log dans classes/Log.php. Commençons par créer un script de test, appelé tests/log_test.php. Son contenu est le suivant... + +]]> + Ici le répertoire simpletest est soit dans le dossier courant, soit dans les dossiers pour fichiers inclus. Vous auriez à éditer ces arborescences suivant l'endroit où vous avez installé SimpleTest. Ensuite créons un scénario de test... + +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... + + 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... +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 à : +; +]]> +

+
+
+

+ 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... + +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 insère le code suivant... +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 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 toutes 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. +

+
+
+

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

+
+
+

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

+
+
+ + + Utiliser le testeur rapidement + avec un exemple. + + + Groupes de tests + pour tester en un seul clic. + + + Utiliser les objets fantaisie + pour faciliter les tests et gagner en contrôle. + + + Tester des pages web + au niveau de l'HTML. + + + + + Télécharger PHP Simple Test + depuis SourceForge. + + + L'API de SimpleTest pour développeur + donne tous les détails sur les classes et assertions existantes. + + + + + développement logiciel, + programmation php, + outils de développement logiciel, + tutorial php, + scripts php gratuits, + architecture, + ressources php, + objets fantaise, + junit, + php testing, + php unit, + méthodologie, + développement piloté par les tests, + sourceforge, + open source, + unit test, + web tester, + web testing, + outils tests html, + tester des web pages, + php objets fantaise, + naviguer automatiquement sur des sites web, + test automatisé, + scripting web, + wget, + test curl, + jmock pour php, + jwebunit, + phpunit, + php unit testing, + php web testing, + jason sweat, + marcus baker, + perrick penet, + topstyle plug in, + phpedit plug in + + +
diff --git a/tests/simpletest/docs/source/fr/subclass_tutorial.xml b/tests/simpletest/docs/source/fr/subclass_tutorial.xml new file mode 100644 index 00000000..fafce786 --- /dev/null +++ b/tests/simpletest/docs/source/fr/subclass_tutorial.xml @@ -0,0 +1,195 @@ + + + Tutorial de test unitaire en PHP - Sous classer un scénario de test + +

+

Une assertion insensible au chronomètre

+

+

+ Nous avions laissé notre test d'horloge avec un trou. Si la fonction time() de PHP avançait pendant cette comparaison... +assertEqual($clock->now(), time(), 'Now is the right time'); +} +]]> + ...notre test aurait un écart d'une seconde et entraînerait un faux échec. Un comportement erratique de notre suite de test n'est vraiment pas ce que nous souhaitons : nous pourrions la lancer une centaine de fois par jour. +

+

+ Nous pourrions ré-écrire notre test... + + $time1 = $clock->now(); + $time2 = time(); + $this->assertTrue(($time1 == $time2) || ($time1 + 1 == $time2), 'Now is the right time'); +} +]]> + Sauf que la conception n'est pas plus claire et que nous devrons le répéter pour chaque test de chronométrage. Les répétitions sont un ennemi public n°1 et donc un très bon stimulant pour le remaniement de notre code de test. +UnitTestCase('Clock class test'); + } + function assertSameTime($time1, $time2, $message) { + $this->assertTrue( + ($time1 == $time2) || ($time1 + 1 == $time2), + $message); + } + function testClockTellsTime() { + $clock = new Clock(); + $this->assertSameTime($clock->now(), time(), 'Now is the right time'); + } + function testClockAdvance() { + $clock = new Clock(); + $clock->advance(10); + $this->assertSameTime($clock->now(), time() + 10, 'Advancement'); + } +} +]]> + Bien entendu à chaque modification je relance les tests pour bien vérifier que nous sommes dans les clous. Remaniement au vert. C'est beaucoup plus sûr. +

+

+

Réutiliser notre assertion

+

+

+ Peut-être voulons nous ajouter d'autres tests sensibles au temps. Peut-être lisons nous des timestamps - en provenance d'une entrée dans une base de données ou d'ailleurs - qui tiendraient compte d'une simple seconde pour basculer. Pour que ces nouvelles classes de test profitent de notre nouvelle assertion nous avons besoin de la placer dans une "super classe". +

+

+ Voici notre fichier clock_test.php au complet après la promotion de notre méthode assertSameTime() dans sa propre "super classe"... + + class TimeTestCase extends UnitTestCase { + function TimeTestCase($test_name) { + $this->UnitTestCase($test_name); + } + function assertSameTime($time1, $time2, $message) { + $this->assertTrue( + ($time1 == $time2) || ($time1 + 1 == $time2), + $message); + } + } + + class TestOfClock extends TimeTestCase { + function TestOfClock() { + $this->TimeTestCase('Clock class test'); + } + function testClockTellsTime() { + $clock = new Clock(); + $this->assertSameTime($clock->now(), time(), 'Now is the right time'); + } + function testClockAdvance() { + $clock = new Clock(); + $clock->advance(10); + $this->assertSameTime($clock->now(), time() + 10, 'Advancement'); + } + } +?> +]]> + Désormais nous bénéficions de notre nouvelle assertion à chaque fois que nous héritons de notre propre classe TimeTestCase plutôt que de la classe par défaut UnitTestCase. Nous retrouvons la conception de l'outil JUnit et SimpleTest est un portage en PHP de cette interface. Il s'agit d'un framework de test à partir duquel votre propre système de test peut s'agrandir. +

+

+ Si nous lançons les tests maintenant une légère broutille survient... +

+ Warning: Missing argument 1 for timetestcase() + in /home/marcus/projects/lastcraft/tutorial_tests/tests/clock_test.php on line 5
+

All tests

+
3/3 test cases complete. + 6 passes and 0 fails.
+
+ La raison est assez délicate. +

+

+ Notre sous-classe exige un paramètre dans le constructeur qui n'a pas été fourni et pourtant il semblerait que nous l'ayons bel et bien fourni. Quand nous avons hérité de notre nouvelle casse nous lui avons passé notre propre constructeur. C'est juste là... +TimeTestCase('Clock class test'); +} +]]> + En fait nous avons raison, là n'est pas le problème. +

+

+ Vous vous souvenez de quand nous avons construit le test de groupe all_tests.php en utilisant la méthode addTestFile(). Cette méthode recherche les classes de scénario de test, les instancie si elles sont nouvelles puis exécute tous nos tests. Ce qui s'est passé ? Elle a aussi trouvé notre extension de scénario de test. C'est sans conséquence puisque qu'il n'y a pas de méthode de test à l'intérieur - comprendre pas de méthode commençant par "test". Aucun test supplémentaire n'est exécuté. +

+

+ Le problème vient du fait qu'il instancie la classe et le fait sans le paramètre $test_name qui déclenche l'avertissement. Ce paramètre n'est généralement nécessaire ni pour un scénario de test, ni pour son assertion. Pour que notre scénario de test étendu corresponde à l'interface de UnitTestCase, nous avons besoin de le rendre optionnel... +$test_name = false) { + $this->UnitTestCase($test_name); + } + function assertSameTime($time1, $time2, $message = false) { + if (! $message) { + $message = "Time [$time1] should match time [$time2]"; + } + $this->assertTrue( + ($time1 == $time2) || ($time1 + 1 == $time2), + $message); + } +} +]]> + Bien sûr, que cette classe soit instanciée sans raison par la suite de test devrait continuer à vous ennuyer. Voici une modification pour l'empêcher de s'exécuter... +SimpleTestOptions::ignore('TimeTestCase'); +class TimeTestCase extends UnitTestCase { + function TimeTestCase($test_name = false) { + $this->UnitTestCase($test_name); + } + function assertSameTime($time1, $time2, $message = '') { + if (!$message) { + $message = "Time [$time1] should match time [$time2]"; + } + $this->assertTrue( + ($time1 == $time2) || ($time1 + 1 == $time2), + $message); + } +} +]]> + Cette ligne ne fait que demander à SimpleTest d'ignorer cette classe lors de la construction des suites de test. Elle peut être ajoutée n'importe où dans le fichier de scénario de test. +

+

+ Les six succès ont l'air bien mais ne disent pas à un observateur peu attentif ce qui a été testé. Pour cela il faut regarder dans le code. Si cela vous paraît trop de boulot et que vous préfèreriez lire ces informations directement alors vous devriez aller lire comment afficher les succès. +

+
+ + + Une assertion insensible au chronomètre qui permet de gagner une seconde. + + + Sous classer un scénario de test afin de réutiliser la méthode de test. + + + + + Section précédente : contrôler les variables de test. + + + Section suivante : changer l'affichage des tests. + + + Vous aurez besoin du testeur unitaire SimpleTest pour les exemples. + + + + + développement logiciel, + programmation php, + outils de développement logiciel, + tutorial php, + scripts php gratuits, + organisation de tests unitaires, + création de sous-classe, + conseil de test, + astuce de développement, + exemple de code php, + objets fantaisie, + junit, + test php, + outil de test unitaire, + suite de test php + + +
+ diff --git a/tests/simpletest/docs/source/fr/support_website.xml b/tests/simpletest/docs/source/fr/support_website.xml new file mode 100644 index 00000000..f5768e3c --- /dev/null +++ b/tests/simpletest/docs/source/fr/support_website.xml @@ -0,0 +1,43 @@ + + + Mailing-list de support + +

+ La mailing-list simpletest-support est probablement l'endroit + le plus actif autour de SimpleTest : aide, conseil, bugs et détours, c'est là + que tout se passe la plupart du temps. Attention tout de même : les échanges + ont lieu en anglais. +

+

+ C'est vraiment + + simple de s'y abonner et en plus, on peut aussi + + l'utiliser pour ses recherches. +

+

+ Au dernier pointage, il y avait 114 abonnés et 1908 messages envoyés. + Cela fait de 1 à 4 messages par jour en moyenne. +

+
+ + + + + + + + + SimpleTest, + download, + source code, + stable release, + eclipse release, + eclipse plugin, + debian package, + drupal module, + pear channel, + pearified package + + +
\ No newline at end of file diff --git a/tests/simpletest/docs/source/fr/unit_test_documentation.xml b/tests/simpletest/docs/source/fr/unit_test_documentation.xml new file mode 100644 index 00000000..b3446859 --- /dev/null +++ b/tests/simpletest/docs/source/fr/unit_test_documentation.xml @@ -0,0 +1,225 @@ + + + Documentation SimpleTest pour les tests de régression en PHP + +
+

+ Le coeur du système est un framework de tests de régression construit autour des scénarios de test. Un exemple de scénario de test ressemble à... +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... +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
+

+
+
+

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

+
+
+

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

+
+
+ + + Scénarios de test unitaire et opérations basiques. + + + Étendre des scénarios de test pour les personnaliser à votre propre projet. + + + Lancer un scénario seul comme un script unique. + + + + + La page de SimpleTest sur SourceForge. + + + La page de téléchargement de SimpleTest sur LastCraft. + + + L'API complète de SimpleTest à partir de PHPDoc. + + + + + test unitaire php, + test d'intégration, + documentation, + marcus baker, + perrick penet + simple test, + documentation simpletest, + phpunit, + junit, + xunit + + +
+ diff --git a/tests/simpletest/docs/source/fr/web_tester_documentation.xml b/tests/simpletest/docs/source/fr/web_tester_documentation.xml new file mode 100644 index 00000000..2dfcfaae --- /dev/null +++ b/tests/simpletest/docs/source/fr/web_tester_documentation.xml @@ -0,0 +1,266 @@ + + + Documentation SimpleTest : tester des scripts web + +
+

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

+

+ 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... + + 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()... + + 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. +

+
+
+

+ Pour obtenir la confirmation que la page téléchargée est bien celle que nous attendions, nous devons vérifier son contenu. + + $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... +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... + + $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... +setMaximumRedirects(0); + $this->get('http://simpletest.sourceforge.net/'); + $this->assertResponse(array(301, 302, 303, 307)); + } +} +]]> + Maitenant ça passe. +

+
+
+

+ 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... +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 une ancre avec ce texte d'étiquette visible
clickLinkById($id)Clique sur une ancre avec cet attribut d'identification
+

+

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

+

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

+

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

+

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

+
+
+

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

+
+
+ + + Réussir à télécharger une page web + + + Tester le contenu de la page + + + Naviguer sur un site web pendant le test + + + Méthodes pour modifier une requête et pour déboguer + + + + + La page du projet SimpleTest sur SourceForge. + + + La page de téléchargement de SimpleTest sur LastCraft. + + + L'API du développeur pour SimpleTest donne tous les détails sur les classes et les assertions disponibles. + + + + + développement logiciel, + programmation php pour des clients, + php orienté client, + outils de développement logiciel, + framework de test de recette, + scripts php gratuits, + architecture, + ressources php, + HTMLUnit, + JWebUnit, + test php, + ressource de test unitaire, + test web + + +
+ diff --git a/tests/simpletest/dumper.php b/tests/simpletest/dumper.php new file mode 100644 index 00000000..7725f55a --- /dev/null +++ b/tests/simpletest/dumper.php @@ -0,0 +1,360 @@ +getType($value); + switch($type) { + case "Null": + return "NULL"; + case "Boolean": + return "Boolean: " . ($value ? "true" : "false"); + case "Array": + return "Array: " . count($value) . " items"; + case "Object": + return "Object: of " . get_class($value); + case "String": + return "String: " . $this->clipString($value, 200); + default: + return "$type: $value"; + } + return "Unknown"; + } + + /** + * Gets the string representation of a type. + * @param mixed $value Variable to check against. + * @return string Type. + * @access public + */ + function getType($value) { + if (! isset($value)) { + return "Null"; + } elseif (is_bool($value)) { + return "Boolean"; + } elseif (is_string($value)) { + return "String"; + } elseif (is_integer($value)) { + return "Integer"; + } elseif (is_float($value)) { + return "Float"; + } elseif (is_array($value)) { + return "Array"; + } elseif (is_resource($value)) { + return "Resource"; + } elseif (is_object($value)) { + return "Object"; + } + return "Unknown"; + } + + /** + * Creates a human readable description of the + * difference between two variables. Uses a + * dynamic call. + * @param mixed $first First variable. + * @param mixed $second Value to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Description of difference. + * @access public + */ + function describeDifference($first, $second, $identical = false) { + if ($identical) { + if (! $this->_isTypeMatch($first, $second)) { + return "with type mismatch as [" . $this->describeValue($first) . + "] does not match [" . $this->describeValue($second) . "]"; + } + } + $type = $this->getType($first); + if ($type == "Unknown") { + return "with unknown type"; + } + $method = '_describe' . $type . 'Difference'; + return $this->$method($first, $second, $identical); + } + + /** + * Tests to see if types match. + * @param mixed $first First variable. + * @param mixed $second Value to compare with. + * @return boolean True if matches. + * @access private + */ + function _isTypeMatch($first, $second) { + return ($this->getType($first) == $this->getType($second)); + } + + /** + * Clips a string to a maximum length. + * @param string $value String to truncate. + * @param integer $size Minimum string size to show. + * @param integer $position Centre of string section. + * @return string Shortened version. + * @access public + */ + function clipString($value, $size, $position = 0) { + $length = strlen($value); + if ($length <= $size) { + return $value; + } + $position = min($position, $length); + $start = ($size/2 > $position ? 0 : $position - $size/2); + if ($start + $size > $length) { + $start = $length - $size; + } + $value = substr($value, $start, $size); + return ($start > 0 ? "..." : "") . $value . ($start + $size < $length ? "..." : ""); + } + + /** + * Creates a human readable description of the + * difference between two variables. The minimal + * version. + * @param null $first First value. + * @param mixed $second Value to compare with. + * @return string Human readable description. + * @access private + */ + function _describeGenericDifference($first, $second) { + return "as [" . $this->describeValue($first) . + "] does not match [" . + $this->describeValue($second) . "]"; + } + + /** + * Creates a human readable description of the + * difference between a null and another variable. + * @param null $first First null. + * @param mixed $second Null to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeNullDifference($first, $second, $identical) { + return $this->_describeGenericDifference($first, $second); + } + + /** + * Creates a human readable description of the + * difference between a boolean and another variable. + * @param boolean $first First boolean. + * @param mixed $second Boolean to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeBooleanDifference($first, $second, $identical) { + return $this->_describeGenericDifference($first, $second); + } + + /** + * Creates a human readable description of the + * difference between a string and another variable. + * @param string $first First string. + * @param mixed $second String to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeStringDifference($first, $second, $identical) { + if (is_object($second) || is_array($second)) { + return $this->_describeGenericDifference($first, $second); + } + $position = $this->_stringDiffersAt($first, $second); + $message = "at character $position"; + $message .= " with [" . + $this->clipString($first, 200, $position) . "] and [" . + $this->clipString($second, 200, $position) . "]"; + return $message; + } + + /** + * Creates a human readable description of the + * difference between an integer and another variable. + * @param integer $first First number. + * @param mixed $second Number to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeIntegerDifference($first, $second, $identical) { + if (is_object($second) || is_array($second)) { + return $this->_describeGenericDifference($first, $second); + } + return "because [" . $this->describeValue($first) . + "] differs from [" . + $this->describeValue($second) . "] by " . + abs($first - $second); + } + + /** + * Creates a human readable description of the + * difference between two floating point numbers. + * @param float $first First float. + * @param mixed $second Float to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeFloatDifference($first, $second, $identical) { + if (is_object($second) || is_array($second)) { + return $this->_describeGenericDifference($first, $second); + } + return "because [" . $this->describeValue($first) . + "] differs from [" . + $this->describeValue($second) . "] by " . + abs($first - $second); + } + + /** + * Creates a human readable description of the + * difference between two arrays. + * @param array $first First array. + * @param mixed $second Array to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeArrayDifference($first, $second, $identical) { + if (! is_array($second)) { + return $this->_describeGenericDifference($first, $second); + } + if (! $this->_isMatchingKeys($first, $second, $identical)) { + return "as key list [" . + implode(", ", array_keys($first)) . "] does not match key list [" . + implode(", ", array_keys($second)) . "]"; + } + foreach (array_keys($first) as $key) { + if ($identical && ($first[$key] === $second[$key])) { + continue; + } + if (! $identical && ($first[$key] == $second[$key])) { + continue; + } + return "with member [$key] " . $this->describeDifference( + $first[$key], + $second[$key], + $identical); + } + return ""; + } + + /** + * Compares two arrays to see if their key lists match. + * For an identical match, the ordering and types of the keys + * is significant. + * @param array $first First array. + * @param array $second Array to compare with. + * @param boolean $identical If true then type anomolies count. + * @return boolean True if matching. + * @access private + */ + function _isMatchingKeys($first, $second, $identical) { + $first_keys = array_keys($first); + $second_keys = array_keys($second); + if ($identical) { + return ($first_keys === $second_keys); + } + sort($first_keys); + sort($second_keys); + return ($first_keys == $second_keys); + } + + /** + * Creates a human readable description of the + * difference between a resource and another variable. + * @param resource $first First resource. + * @param mixed $second Resource to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeResourceDifference($first, $second, $identical) { + return $this->_describeGenericDifference($first, $second); + } + + /** + * Creates a human readable description of the + * difference between two objects. + * @param object $first First object. + * @param mixed $second Object to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeObjectDifference($first, $second, $identical) { + if (! is_object($second)) { + return $this->_describeGenericDifference($first, $second); + } + return $this->_describeArrayDifference( + get_object_vars($first), + get_object_vars($second), + $identical); + } + + /** + * Find the first character position that differs + * in two strings by binary chop. + * @param string $first First string. + * @param string $second String to compare with. + * @return integer Position of first differing + * character. + * @access private + */ + function _stringDiffersAt($first, $second) { + if (! $first || ! $second) { + return 0; + } + if (strlen($first) < strlen($second)) { + list($first, $second) = array($second, $first); + } + $position = 0; + $step = strlen($first); + while ($step > 1) { + $step = (integer)(($step + 1) / 2); + if (strncmp($first, $second, $position + $step) == 0) { + $position += $step; + } + } + return $position; + } + + /** + * Sends a formatted dump of a variable to a string. + * @param mixed $variable Variable to display. + * @return string Output from print_r(). + * @access public + * @static + */ + function dump($variable) { + ob_start(); + print_r($variable); + $formatted = ob_get_contents(); + ob_end_clean(); + return $formatted; + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/eclipse.php b/tests/simpletest/eclipse.php new file mode 100644 index 00000000..e316cc53 --- /dev/null +++ b/tests/simpletest/eclipse.php @@ -0,0 +1,183 @@ +_listener = &$listener; + $this->SimpleScorer(); + $this->_case = ""; + $this->_group = ""; + $this->_method = ""; + $this->_cc = $cc; + $this->_error = false; + $this->_fail = false; + } + + function getDumper() { + return new SimpleDumper(); + } + + function &createListener($port,$host="127.0.0.1"){ + $tmplistener = & new SimpleSocket($host,$port,5); + return $tmplistener; + } + + function &createInvoker(&$invoker){ + $eclinvoker = & new EclipseInvoker( $invoker, $this->_listener); + return $eclinvoker; + } + + function escapeVal($val){ + $needle = array("\\","\"","/","\b","\f","\n","\r","\t"); + $replace = array('\\\\','\"','\/','\b','\f','\n','\r','\t'); + return str_replace($needle,$replace,$val); + } + + function paintPass($message){ + //get the first passing item -- so that clicking the test item goes to first pass + if (!$this->_pass){ + $this->_message = $this->escapeVal($message); + } + $this->_pass = true; + } + + function paintFail($message){ + //only get the first failure or error + if (!$this->_fail && !$this->_error){ + $this->_fail = true; + $this->_message = $this->escapeVal($message); + $this->_listener->write('{status:"fail",message:"'.$this->_message.'",group:"'.$this->_group.'",case:"'.$this->_case.'",method:"'.$this->_method.'"}'); + } + } + + function paintError($message){ + //only get the first failure or error + if (!$this->_fail && !$this->_error){ + $this->_error = true; + $this->_message = $this->escapeVal($message); + $this->_listener->write('{status:"error",message:"'.$this->_message.'",group:"'.$this->_group.'",case:"'.$this->_case.'",method:"'.$this->_method.'"}'); + } + } + + function paintHeader($method){ + } + + function paintFooter($method){ + } + + function paintMethodStart($method) { + $this->_pass = false; + $this->_fail = false; + $this->_error = false; + $this->_method = $this->escapeVal($method); + } + + function paintMethodEnd($method){ + if ($this->_fail || $this->_error || !$this->_pass){ + //do nothing + }else{ + //this ensures we only get one message per method that passes + $this->_listener->write('{status:"pass",message:"'.$this->_message.'",group:"'.$this->_group.'",case:"'.$this->_case.'",method:"'.$this->_method.'"}'); + } + } + + function paintCaseStart($case){ + $this->_case = $this->escapeVal($case); + } + + function paintCaseEnd($case){ + $this->_case = ""; + } + function paintGroupStart($group,$size){ + $this->_group = $this->escapeVal($group); + if ($this->_cc){ + if (extension_loaded('xdebug')){ + xdebug_start_code_coverage(XDEBUG_CC_UNUSED| XDEBUG_CC_DEAD_CODE); + } + } + } + function paintGroupEnd($group){ + $this->_group = ""; + $cc = ""; + if ($this->_cc){ + if (extension_loaded('xdebug')){ + $arrfiles = xdebug_get_code_coverage(); + xdebug_stop_code_coverage(); + $thisdir = dirname(__FILE__); + $thisdirlen = strlen($thisdir); + foreach ($arrfiles as $index=>$file){ + if (substr($index,0,$thisdirlen)===$thisdir){ + continue; + } + $lcnt = 0; + $ccnt = 0; + foreach ($file as $line){ + if ($line == -2){ + continue; + } + $lcnt++; + if ($line==1){ + $ccnt++; + } + } + if ($lcnt > 0){ + $cc.=round(($ccnt/$lcnt)*100,2).'%'; + }else{ + $cc.="0.00%"; + } + $cc.= "\t".$index."\n"; + } + } + } + $this->_listener->write('{status:"coverage",message:"'.EclipseReporter::escapeVal($cc).'"}'); + } +} + +/** + * base invoker class for eclipse plugin + * @package SimpleTest + * @subpackage Eclipse + */ +class EclipseInvoker extends SimpleInvokerDecorator{ + function EclipseInvoker(&$invoker,&$listener) { + $this->_listener = &$listener; + $this->SimpleInvokerDecorator($invoker); + } + + function before($method){ + ob_start(); + $this->_invoker->before($method); + } + + function after($method) { + $this->_invoker->after($method); + $output = ob_get_contents(); + ob_end_clean(); + if ($output!==""){ + $result = $this->_listener->write('{status:"info",message:"'.EclipseReporter::escapeVal($output).'"}'); + } + } + + +} + +?> \ No newline at end of file diff --git a/tests/simpletest/encoding.php b/tests/simpletest/encoding.php new file mode 100644 index 00000000..f509df27 --- /dev/null +++ b/tests/simpletest/encoding.php @@ -0,0 +1,521 @@ +_key = $key; + $this->_value = $value; + } + + /** + * The pair as a single string. + * @return string Encoded pair. + * @access public + */ + function asRequest() { + return urlencode($this->_key) . '=' . urlencode($this->_value); + } + + /** + * The MIME part as a string. + * @return string MIME part encoding. + * @access public + */ + function asMime() { + $part = 'Content-Disposition: form-data; '; + $part .= "name=\"" . $this->_key . "\"\r\n"; + $part .= "\r\n" . $this->_value; + return $part; + } + + /** + * Is this the value we are looking for? + * @param string $key Identifier. + * @return boolean True if matched. + * @access public + */ + function isKey($key) { + return $key == $this->_key; + } + + /** + * Is this the value we are looking for? + * @return string Identifier. + * @access public + */ + function getKey() { + return $this->_key; + } + + /** + * Is this the value we are looking for? + * @return string Content. + * @access public + */ + function getValue() { + return $this->_value; + } + } + + /** + * Single post parameter. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleAttachment { + var $_key; + var $_content; + var $_filename; + + /** + * Stashes the data for rendering later. + * @param string $key Key to add value to. + * @param string $content Raw data. + * @param hash $filename Original filename. + */ + function SimpleAttachment($key, $content, $filename) { + $this->_key = $key; + $this->_content = $content; + $this->_filename = $filename; + } + + /** + * The pair as a single string. + * @return string Encoded pair. + * @access public + */ + function asRequest() { + return ''; + } + + /** + * The MIME part as a string. + * @return string MIME part encoding. + * @access public + */ + function asMime() { + $part = 'Content-Disposition: form-data; '; + $part .= 'name="' . $this->_key . '"; '; + $part .= 'filename="' . $this->_filename . '"'; + $part .= "\r\nContent-Type: " . $this->_deduceMimeType(); + $part .= "\r\n\r\n" . $this->_content; + return $part; + } + + /** + * Attempts to figure out the MIME type from the + * file extension and the content. + * @return string MIME type. + * @access private + */ + function _deduceMimeType() { + if ($this->_isOnlyAscii($this->_content)) { + return 'text/plain'; + } + return 'application/octet-stream'; + } + + /** + * Tests each character is in the range 0-127. + * @param string $ascii String to test. + * @access private + */ + function _isOnlyAscii($ascii) { + for ($i = 0, $length = strlen($ascii); $i < $length; $i++) { + if (ord($ascii[$i]) > 127) { + return false; + } + } + return true; + } + + /** + * Is this the value we are looking for? + * @param string $key Identifier. + * @return boolean True if matched. + * @access public + */ + function isKey($key) { + return $key == $this->_key; + } + + /** + * Is this the value we are looking for? + * @return string Identifier. + * @access public + */ + function getKey() { + return $this->_key; + } + + /** + * Is this the value we are looking for? + * @return string Content. + * @access public + */ + function getValue() { + return $this->_filename; + } + } + + /** + * Bundle of GET/POST parameters. Can include + * repeated parameters. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleEncoding { + var $_request; + + /** + * Starts empty. + * @param array $query Hash of parameters. + * Multiple values are + * as lists on a single key. + * @access public + */ + function SimpleEncoding($query = false) { + if (! $query) { + $query = array(); + } + $this->clear(); + $this->merge($query); + } + + /** + * Empties the request of parameters. + * @access public + */ + function clear() { + $this->_request = array(); + } + + /** + * Adds a parameter to the query. + * @param string $key Key to add value to. + * @param string/array $value New data. + * @access public + */ + function add($key, $value) { + if ($value === false) { + return; + } + if (is_array($value)) { + foreach ($value as $item) { + $this->_addPair($key, $item); + } + } else { + $this->_addPair($key, $value); + } + } + + /** + * Adds a new value into the request. + * @param string $key Key to add value to. + * @param string/array $value New data. + * @access private + */ + function _addPair($key, $value) { + $this->_request[] = new SimpleEncodedPair($key, $value); + } + + /** + * Adds a MIME part to the query. Does nothing for a + * form encoded packet. + * @param string $key Key to add value to. + * @param string $content Raw data. + * @param hash $filename Original filename. + * @access public + */ + function attach($key, $content, $filename) { + $this->_request[] = new SimpleAttachment($key, $content, $filename); + } + + /** + * Adds a set of parameters to this query. + * @param array/SimpleQueryString $query Multiple values are + * as lists on a single key. + * @access public + */ + function merge($query) { + if (is_object($query)) { + $this->_request = array_merge($this->_request, $query->getAll()); + } elseif (is_array($query)) { + foreach ($query as $key => $value) { + $this->add($key, $value); + } + } + } + + /** + * Accessor for single value. + * @return string/array False if missing, string + * if present and array if + * multiple entries. + * @access public + */ + function getValue($key) { + $values = array(); + foreach ($this->_request as $pair) { + if ($pair->isKey($key)) { + $values[] = $pair->getValue(); + } + } + if (count($values) == 0) { + return false; + } elseif (count($values) == 1) { + return $values[0]; + } else { + return $values; + } + } + + /** + * Accessor for listing of pairs. + * @return array All pair objects. + * @access public + */ + function getAll() { + return $this->_request; + } + + /** + * Renders the query string as a URL encoded + * request part. + * @return string Part of URL. + * @access protected + */ + function _encode() { + $statements = array(); + foreach ($this->_request as $pair) { + if ($statement = $pair->asRequest()) { + $statements[] = $statement; + } + } + return implode('&', $statements); + } + } + + /** + * Bundle of GET parameters. Can include + * repeated parameters. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleGetEncoding extends SimpleEncoding { + + /** + * Starts empty. + * @param array $query Hash of parameters. + * Multiple values are + * as lists on a single key. + * @access public + */ + function SimpleGetEncoding($query = false) { + $this->SimpleEncoding($query); + } + + /** + * HTTP request method. + * @return string Always GET. + * @access public + */ + function getMethod() { + return 'GET'; + } + + /** + * Writes no extra headers. + * @param SimpleSocket $socket Socket to write to. + * @access public + */ + function writeHeadersTo(&$socket) { + } + + /** + * No data is sent to the socket as the data is encoded into + * the URL. + * @param SimpleSocket $socket Socket to write to. + * @access public + */ + function writeTo(&$socket) { + } + + /** + * Renders the query string as a URL encoded + * request part for attaching to a URL. + * @return string Part of URL. + * @access public + */ + function asUrlRequest() { + return $this->_encode(); + } + } + + /** + * Bundle of URL parameters for a HEAD request. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleHeadEncoding extends SimpleGetEncoding { + + /** + * Starts empty. + * @param array $query Hash of parameters. + * Multiple values are + * as lists on a single key. + * @access public + */ + function SimpleHeadEncoding($query = false) { + $this->SimpleGetEncoding($query); + } + + /** + * HTTP request method. + * @return string Always HEAD. + * @access public + */ + function getMethod() { + return 'HEAD'; + } + } + + /** + * Bundle of POST parameters. Can include + * repeated parameters. + * @package SimpleTest + * @subpackage WebTester + */ + class SimplePostEncoding extends SimpleEncoding { + + /** + * Starts empty. + * @param array $query Hash of parameters. + * Multiple values are + * as lists on a single key. + * @access public + */ + function SimplePostEncoding($query = false) { + $this->SimpleEncoding($query); + } + + /** + * HTTP request method. + * @return string Always POST. + * @access public + */ + function getMethod() { + return 'POST'; + } + + /** + * Dispatches the form headers down the socket. + * @param SimpleSocket $socket Socket to write to. + * @access public + */ + function writeHeadersTo(&$socket) { + $socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n"); + $socket->write("Content-Type: application/x-www-form-urlencoded\r\n"); + } + + /** + * Dispatches the form data down the socket. + * @param SimpleSocket $socket Socket to write to. + * @access public + */ + function writeTo(&$socket) { + $socket->write($this->_encode()); + } + + /** + * Renders the query string as a URL encoded + * request part for attaching to a URL. + * @return string Part of URL. + * @access public + */ + function asUrlRequest() { + return ''; + } + } + + /** + * Bundle of POST parameters in the multipart + * format. Can include file uploads. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleMultipartEncoding extends SimplePostEncoding { + var $_boundary; + + /** + * Starts empty. + * @param array $query Hash of parameters. + * Multiple values are + * as lists on a single key. + * @access public + */ + function SimpleMultipartEncoding($query = false, $boundary = false) { + $this->SimplePostEncoding($query); + $this->_boundary = ($boundary === false ? uniqid('st') : $boundary); + } + + /** + * Dispatches the form headers down the socket. + * @param SimpleSocket $socket Socket to write to. + * @access public + */ + function writeHeadersTo(&$socket) { + $socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n"); + $socket->write("Content-Type: multipart/form-data, boundary=" . $this->_boundary . "\r\n"); + } + + /** + * Dispatches the form data down the socket. + * @param SimpleSocket $socket Socket to write to. + * @access public + */ + function writeTo(&$socket) { + $socket->write($this->_encode()); + } + + /** + * Renders the query string as a URL encoded + * request part. + * @return string Part of URL. + * @access public + */ + function _encode() { + $stream = ''; + foreach ($this->_request as $pair) { + $stream .= "--" . $this->_boundary . "\r\n"; + $stream .= $pair->asMime() . "\r\n"; + } + $stream .= "--" . $this->_boundary . "--\r\n"; + return $stream; + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/errors.php b/tests/simpletest/errors.php new file mode 100644 index 00000000..ec219f54 --- /dev/null +++ b/tests/simpletest/errors.php @@ -0,0 +1,250 @@ +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) { + $context = &SimpleTest::getContext(); + $queue = &$context->get('SimpleErrorQueue'); + $queue->setTestCase($this->GetTestCase()); + set_error_handler('SimpleTestErrorHandler'); + parent::invoke($method); + while (list($severity, $message, $file, $line) = $queue->extract()) { + $severity = SimpleErrorQueue::getSeverityAsString($severity); + $test = &$this->getTestCase(); + $test->error($severity, $message, $file, $line); + } + restore_error_handler(); + } +} + +/** + * Singleton error queue used to record trapped + * errors. + * @package SimpleTest + * @subpackage UnitTester + */ +class SimpleErrorQueue { + var $_queue; + var $_expectation_queue; + var $_test; + + /** + * Starts with an empty queue. + */ + function SimpleErrorQueue() { + $this->clear(); + } + + /** + * Sets the currently running test case. + * @param SimpleTestCase $test Test case to send messages to. + * @access public + */ + function setTestCase(&$test) { + $this->_test = &$test; + } + + /** + * Adds an error to the front of the queue. + * @param integer $severity PHP error code. + * @param string $content Text of error. + * @param string $filename File error occoured in. + * @param integer $line Line number of error. + * @access public + */ + function add($severity, $content, $filename, $line) { + $content = str_replace('%', '%%', $content); + if (count($this->_expectation_queue)) { + $this->_testLatestError($severity, $content, $filename, $line); + } else { + array_push( + $this->_queue, + array($severity, $content, $filename, $line)); + } + } + + /** + * Tests the error against the most recent expected + * error. + * @param integer $severity PHP error code. + * @param string $content Text of error. + * @param string $filename File error occoured in. + * @param integer $line Line number of error. + * @access private + */ + function _testLatestError($severity, $content, $filename, $line) { + list($expected, $message) = array_shift($this->_expectation_queue); + $severity = $this->getSeverityAsString($severity); + $is_match = $this->_test->assert( + $expected, + $content, + sprintf($message, "%s -> PHP error [$content] severity [$severity] in [$filename] line [$line]")); + if (! $is_match) { + $this->_test->error($severity, $content, $filename, $line); + } + } + + /** + * Pulls the earliest error from the queue. + * @return False if none, or a list of error + * information. Elements are: severity + * as the PHP error code, the error message, + * the file with the error, the line number + * and a list of PHP super global arrays. + * @access public + */ + function extract() { + if (count($this->_queue)) { + return array_shift($this->_queue); + } + return false; + } + + /** + * Discards the contents of the error queue. + * @access public + */ + function clear() { + $this->_queue = array(); + $this->_expectation_queue = array(); + } + + /** + * @deprecated + */ + function assertNoErrors($message) { + return $this->_test->assert( + new TrueExpectation(), + count($this->_queue) == 0, + sprintf($message, 'Should be no errors')); + } + + /** + * @deprecated + */ + function assertError($expected, $message) { + if (count($this->_queue) == 0) { + $this->_test->fail(sprintf($message, 'Expected error not found')); + return false; + } + list($severity, $content, $file, $line) = $this->extract(); + $severity = $this->getSeverityAsString($severity); + return $this->_test->assert( + $expected, + $content, + sprintf($message, "Expected PHP error [$content] severity [$severity] in [$file] line [$line]")); + } + + /** + * Sets up an expectation of an error. If this is + * not fulfilled at the end of the test, a failure + * will occour. If the error does happen, then this + * will cancel it out and send a pass message. + * @param SimpleExpectation $expected Expected error match. + * @param string $message Message to display. + * @access public + */ + function expectError($expected, $message) { + array_push( + $this->_expectation_queue, + array($expected, $message)); + } + + /** + * Converts an error code into it's string + * representation. + * @param $severity PHP integer error code. + * @return String version of error code. + * @access public + * @static + */ + function getSeverityAsString($severity) { + static $map = array( + E_STRICT => 'E_STRICT', + E_ERROR => 'E_ERROR', + E_WARNING => 'E_WARNING', + E_PARSE => 'E_PARSE', + E_NOTICE => 'E_NOTICE', + E_CORE_ERROR => 'E_CORE_ERROR', + E_CORE_WARNING => 'E_CORE_WARNING', + E_COMPILE_ERROR => 'E_COMPILE_ERROR', + E_COMPILE_WARNING => 'E_COMPILE_WARNING', + E_USER_ERROR => 'E_USER_ERROR', + E_USER_WARNING => 'E_USER_WARNING', + E_USER_NOTICE => 'E_USER_NOTICE'); + return $map[$severity]; + } +} + +/** + * Error handler that simply stashes any errors into the global + * error queue. Simulates the existing behaviour with respect to + * logging errors, but this feature may be removed in future. + * @param $severity PHP error code. + * @param $message Text of error. + * @param $filename File error occoured in. + * @param $line Line number of error. + * @param $super_globals Hash of PHP super global arrays. + * @static + * @access public + */ +function SimpleTestErrorHandler($severity, $message, $filename, $line, $super_globals) { + $severity = $severity & error_reporting(); + if ($severity) { + restore_error_handler(); + if (ini_get('log_errors')) { + $label = SimpleErrorQueue::getSeverityAsString($severity); + error_log("$label: $message in $filename on line $line"); + } + $context = &SimpleTest::getContext(); + $queue = &$context->get('SimpleErrorQueue'); + $queue->add($severity, $message, $filename, $line); + set_error_handler('SimpleTestErrorHandler'); + } else { + if (version_compare(phpversion(), '5.2') >= 0) { + return false; + } + } +} +?> \ No newline at end of file diff --git a/tests/simpletest/exceptions.php b/tests/simpletest/exceptions.php new file mode 100644 index 00000000..2498a1f9 --- /dev/null +++ b/tests/simpletest/exceptions.php @@ -0,0 +1,192 @@ +SimpleInvokerDecorator($invoker); + } + + /** + * Invokes a test method whilst trapping expected + * exceptions. Any left over unthrown exceptions + * are then reported as failures. + * @param string $method Test method to call. + */ + function invoke($method) { + $trap = SimpleTest::getContext()->get('SimpleExceptionTrap'); + $trap->clear(); + try { + parent::invoke($method); + } catch (Exception $exception) { + if (! $trap->isExpected($this->getTestCase(), $exception)) { + $this->getTestCase()->exception($exception); + } + $trap->clear(); + $this->_invoker->getTestCase()->tearDown(); + } + if ($message = $trap->getOutstanding()) { + $this->getTestCase()->fail($message); + } + } +} + +/** + * Tests exceptions either by type or the exact + * exception. This could be improved to accept + * a pattern expectation to test the error + * message, but that will have to come later. + * @package SimpleTest + * @subpackage UnitTester + */ +class ExceptionExpectation extends SimpleExpectation { + private $expected; + + /** + * Sets up the conditions to test against. + * If the expected value is a string, then + * it will act as a test of the class name. + * An exception as the comparison will + * trigger an identical match. Writing this + * down now makes it look doubly dumb. I hope + * come up with a better scheme later. + * @param mixed $expected A class name or an actual + * exception to compare with. + * @param string $message Message to display. + */ + function __construct($expected, $message = '%s') { + $this->expected = $expected; + parent::__construct($message); + } + + /** + * Carry out the test. + * @param Exception $compare Value to check. + * @return boolean True if matched. + */ + function test($compare) { + if (is_string($this->expected)) { + return ($compare instanceof $this->expected); + } + if (get_class($compare) != get_class($this->expected)) { + return false; + } + return $compare->getMessage() == $this->expected->getMessage(); + } + + /** + * Create the message to display describing the test. + * @param Exception $compare Exception to match. + * @return string Final message. + */ + function testMessage($compare) { + if (is_string($this->expected)) { + return "Exception [" . $this->describeException($compare) . + "] should be type [" . $this->expected . "]"; + } + return "Exception [" . $this->describeException($compare) . + "] should match [" . + $this->describeException($this->expected) . "]"; + } + + /** + * Summary of an Exception object. + * @param Exception $compare Exception to describe. + * @return string Text description. + */ + protected function describeException($exception) { + return get_class($exception) . ": " . $exception->getMessage(); + } +} + +/** + * Stores expected exceptions for when they + * get thrown. Saves the irritating try...catch + * block. + * @package SimpleTest + * @subpackage UnitTester + */ +class SimpleExceptionTrap { + private $expected; + private $message; + + /** + * Clears down the queue ready for action. + */ + function __construct() { + $this->clear(); + } + + /** + * Sets up an expectation of an exception. + * This has the effect of intercepting an + * exception that matches. + * @param SimpleExpectation $expected Expected exception to match. + * @param string $message Message to display. + * @access public + */ + function expectException($expected = false, $message = '%s') { + if ($expected === false) { + $expected = new AnythingExpectation(); + } + if (! SimpleExpectation::isExpectation($expected)) { + $expected = new ExceptionExpectation($expected); + } + $this->expected = $expected; + $this->message = $message; + } + + /** + * Compares the expected exception with any + * in the queue. Issues a pass or fail and + * returns the state of the test. + * @param SimpleTestCase $test Test case to send messages to. + * @param Exception $exception Exception to compare. + * @return boolean False on no match. + */ + function isExpected($test, $exception) { + if ($this->expected) { + return $test->assert($this->expected, $exception, $this->message); + } + return false; + } + + /** + * Tests for any left over exception. + * @return string/false The failure message or false if none. + */ + function getOutstanding() { + return sprintf($this->message, 'Failed to trap exception'); + } + + /** + * Discards the contents of the error queue. + */ + function clear() { + $this->expected = false; + $this->message = false; + } +} +?> \ No newline at end of file diff --git a/tests/simpletest/expectation.php b/tests/simpletest/expectation.php new file mode 100644 index 00000000..443c6167 --- /dev/null +++ b/tests/simpletest/expectation.php @@ -0,0 +1,811 @@ +_message = $message; + } + + /** + * Tests the expectation. True if correct. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + * @abstract + */ + function test($compare) { + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + * @abstract + */ + function testMessage($compare) { + } + + /** + * Overlays the generated message onto the stored user + * message. An additional message can be interjected. + * @param mixed $compare Comparison value. + * @param SimpleDumper $dumper For formatting the results. + * @return string Description of success + * or failure. + * @access public + */ + function overlayMessage($compare, $dumper) { + $this->_dumper = $dumper; + return sprintf($this->_message, $this->testMessage($compare)); + } + + /** + * Accessor for the dumper. + * @return SimpleDumper Current value dumper. + * @access protected + */ + function &_getDumper() { + return $this->_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'); + } + } + + /** + * A wildcard expectation always matches. + * @package SimpleTest + * @subpackage MockObjects + */ + class AnythingExpectation extends SimpleExpectation { + + /** + * Tests the expectation. Always true. + * @param mixed $compare Ignored. + * @return boolean True. + * @access public + */ + function test($compare) { + return true; + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = &$this->_getDumper(); + return 'Anything always matches [' . $dumper->describeValue($compare) . ']'; + } + } + + /** + * An expectation that passes on boolean true. + * @package SimpleTest + * @subpackage MockObjects + */ + class TrueExpectation extends SimpleExpectation { + + /** + * Tests the expectation. + * @param mixed $compare Should be true. + * @return boolean True on match. + * @access public + */ + function test($compare) { + return (boolean)$compare; + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = &$this->_getDumper(); + return 'Expected true, got [' . $dumper->describeValue($compare) . ']'; + } + } + + /** + * An expectation that passes on boolean false. + * @package SimpleTest + * @subpackage MockObjects + */ + class FalseExpectation extends SimpleExpectation { + + /** + * Tests the expectation. + * @param mixed $compare Should be false. + * @return boolean True on match. + * @access public + */ + function test($compare) { + return ! (boolean)$compare; + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = &$this->_getDumper(); + return 'Expected false, got [' . $dumper->describeValue($compare) . ']'; + } + } + + /** + * Test for equality. + * @package SimpleTest + * @subpackage UnitTester + */ + class EqualExpectation extends SimpleExpectation { + var $_value; + + /** + * Sets the value to compare against. + * @param mixed $value Test value to match. + * @param string $message Customised message on failure. + * @access public + */ + function EqualExpectation($value, $message = '%s') { + $this->SimpleExpectation($message); + $this->_value = $value; + } + + /** + * Tests the expectation. True if it matches the + * held value. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return (($this->_value == $compare) && ($compare == $this->_value)); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if ($this->test($compare)) { + return "Equal expectation [" . $this->_dumper->describeValue($this->_value) . "]"; + } else { + return "Equal expectation fails " . + $this->_dumper->describeDifference($this->_value, $compare); + } + } + + /** + * Accessor for comparison value. + * @return mixed Held value to compare with. + * @access protected + */ + function _getValue() { + return $this->_value; + } + } + + /** + * Test for inequality. + * @package SimpleTest + * @subpackage UnitTester + */ + class NotEqualExpectation extends EqualExpectation { + + /** + * Sets the value to compare against. + * @param mixed $value Test value to match. + * @param string $message Customised message on failure. + * @access public + */ + function NotEqualExpectation($value, $message = '%s') { + $this->EqualExpectation($value, $message); + } + + /** + * Tests the expectation. True if it differs from the + * held value. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return ! parent::test($compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = &$this->_getDumper(); + if ($this->test($compare)) { + return "Not equal expectation passes " . + $dumper->describeDifference($this->_getValue(), $compare); + } else { + return "Not equal expectation fails [" . + $dumper->describeValue($this->_getValue()) . + "] matches"; + } + } + } + + /** + * Test for being within a range. + * @package SimpleTest + * @subpackage UnitTester + */ + class WithinMarginExpectation extends SimpleExpectation { + var $_upper; + var $_lower; + + /** + * Sets the value to compare against and the fuzziness of + * the match. Used for comparing floating point values. + * @param mixed $value Test value to match. + * @param mixed $margin Fuzziness of match. + * @param string $message Customised message on failure. + * @access public + */ + function WithinMarginExpectation($value, $margin, $message = '%s') { + $this->SimpleExpectation($message); + $this->_upper = $value + $margin; + $this->_lower = $value - $margin; + } + + /** + * Tests the expectation. True if it matches the + * held value. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return (($compare <= $this->_upper) && ($compare >= $this->_lower)); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if ($this->test($compare)) { + return $this->_withinMessage($compare); + } else { + return $this->_outsideMessage($compare); + } + } + + /** + * Creates a the message for being within the range. + * @param mixed $compare Value being tested. + * @access private + */ + function _withinMessage($compare) { + return "Within expectation [" . $this->_dumper->describeValue($this->_lower) . "] and [" . + $this->_dumper->describeValue($this->_upper) . "]"; + } + + /** + * Creates a the message for being within the range. + * @param mixed $compare Value being tested. + * @access private + */ + function _outsideMessage($compare) { + if ($compare > $this->_upper) { + return "Outside expectation " . + $this->_dumper->describeDifference($compare, $this->_upper); + } else { + return "Outside expectation " . + $this->_dumper->describeDifference($compare, $this->_lower); + } + } + } + + /** + * Test for being outside of a range. + * @package SimpleTest + * @subpackage UnitTester + */ + class OutsideMarginExpectation extends WithinMarginExpectation { + + /** + * Sets the value to compare against and the fuzziness of + * the match. Used for comparing floating point values. + * @param mixed $value Test value to not match. + * @param mixed $margin Fuzziness of match. + * @param string $message Customised message on failure. + * @access public + */ + function OutsideMarginExpectation($value, $margin, $message = '%s') { + $this->WithinMarginExpectation($value, $margin, $message); + } + + /** + * Tests the expectation. True if it matches the + * held value. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return ! parent::test($compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if (! $this->test($compare)) { + return $this->_withinMessage($compare); + } else { + return $this->_outsideMessage($compare); + } + } + } + + /** + * Test for identity. + * @package SimpleTest + * @subpackage UnitTester + */ + class IdenticalExpectation extends EqualExpectation { + + /** + * Sets the value to compare against. + * @param mixed $value Test value to match. + * @param string $message Customised message on failure. + * @access public + */ + function IdenticalExpectation($value, $message = '%s') { + $this->EqualExpectation($value, $message); + } + + /** + * Tests the expectation. True if it exactly + * matches the held value. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return SimpleTestCompatibility::isIdentical($this->_getValue(), $compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = &$this->_getDumper(); + if ($this->test($compare)) { + return "Identical expectation [" . $dumper->describeValue($this->_getValue()) . "]"; + } else { + return "Identical expectation [" . $dumper->describeValue($this->_getValue()) . + "] fails with [" . + $dumper->describeValue($compare) . "] " . + $dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS); + } + } + } + + /** + * Test for non-identity. + * @package SimpleTest + * @subpackage UnitTester + */ + class NotIdenticalExpectation extends IdenticalExpectation { + + /** + * Sets the value to compare against. + * @param mixed $value Test value to match. + * @param string $message Customised message on failure. + * @access public + */ + function NotIdenticalExpectation($value, $message = '%s') { + $this->IdenticalExpectation($value, $message); + } + + /** + * Tests the expectation. True if it differs from the + * held value. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return ! parent::test($compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = &$this->_getDumper(); + if ($this->test($compare)) { + return "Not identical expectation passes " . + $dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS); + } else { + return "Not identical expectation [" . $dumper->describeValue($this->_getValue()) . "] matches"; + } + } + } + + /** + * Test for a pattern using Perl regex rules. + * @package SimpleTest + * @subpackage UnitTester + */ + class PatternExpectation extends SimpleExpectation { + var $_pattern; + + /** + * Sets the value to compare against. + * @param string $pattern Pattern to search for. + * @param string $message Customised message on failure. + * @access public + */ + function PatternExpectation($pattern, $message = '%s') { + $this->SimpleExpectation($message); + $this->_pattern = $pattern; + } + + /** + * Accessor for the pattern. + * @return string Perl regex as string. + * @access protected + */ + function _getPattern() { + return $this->_pattern; + } + + /** + * Tests the expectation. True if the Perl regex + * matches the comparison value. + * @param string $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return (boolean)preg_match($this->_getPattern(), $compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if ($this->test($compare)) { + return $this->_describePatternMatch($this->_getPattern(), $compare); + } else { + $dumper = &$this->_getDumper(); + return "Pattern [" . $this->_getPattern() . + "] not detected in [" . + $dumper->describeValue($compare) . "]"; + } + } + + /** + * Describes a pattern match including the string + * found and it's position. + * @param string $pattern Regex to match against. + * @param string $subject Subject to search. + * @access protected + */ + function _describePatternMatch($pattern, $subject) { + preg_match($pattern, $subject, $matches); + $position = strpos($subject, $matches[0]); + $dumper = $this->_getDumper(); + return "Pattern [$pattern] detected at character [$position] in [" . + $dumper->describeValue($subject) . "] as [" . + $matches[0] . "] in region [" . + $dumper->clipString($subject, 100, $position) . "]"; + } + } + + /** + * @package SimpleTest + * @subpackage UnitTester + * @deprecated + */ + class WantedPatternExpectation extends PatternExpectation { + } + + /** + * Fail if a pattern is detected within the + * comparison. + * @package SimpleTest + * @subpackage UnitTester + */ + class NoPatternExpectation extends PatternExpectation { + + /** + * Sets the reject pattern + * @param string $pattern Pattern to search for. + * @param string $message Customised message on failure. + * @access public + */ + function NoPatternExpectation($pattern, $message = '%s') { + $this->PatternExpectation($pattern, $message); + } + + /** + * Tests the expectation. False if the Perl regex + * matches the comparison value. + * @param string $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return ! parent::test($compare); + } + + /** + * Returns a human readable test message. + * @param string $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if ($this->test($compare)) { + $dumper = &$this->_getDumper(); + return "Pattern [" . $this->_getPattern() . + "] not detected in [" . + $dumper->describeValue($compare) . "]"; + } else { + return $this->_describePatternMatch($this->_getPattern(), $compare); + } + } + } + + /** + * @package SimpleTest + * @subpackage UnitTester + * @deprecated + */ + class UnwantedPatternExpectation extends NoPatternExpectation { + } + + /** + * Tests either type or class name if it's an object. + * @package SimpleTest + * @subpackage UnitTester + */ + class IsAExpectation extends SimpleExpectation { + var $_type; + + /** + * Sets the type to compare with. + * @param string $type Type or class name. + * @param string $message Customised message on failure. + * @access public + */ + function IsAExpectation($type, $message = '%s') { + $this->SimpleExpectation($message); + $this->_type = $type; + } + + /** + * Accessor for type to check against. + * @return string Type or class name. + * @access protected + */ + function _getType() { + return $this->_type; + } + + /** + * Tests the expectation. True if the type or + * class matches the string value. + * @param string $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + if (is_object($compare)) { + return SimpleTestCompatibility::isA($compare, $this->_type); + } else { + return (strtolower(gettype($compare)) == $this->_canonicalType($this->_type)); + } + } + + /** + * Coerces type name into a gettype() match. + * @param string $type User type. + * @return string Simpler type. + * @access private + */ + function _canonicalType($type) { + $type = strtolower($type); + $map = array( + 'bool' => 'boolean', + 'float' => 'double', + 'real' => 'double', + 'int' => 'integer'); + if (isset($map[$type])) { + $type = $map[$type]; + } + return $type; + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = &$this->_getDumper(); + return "Value [" . $dumper->describeValue($compare) . + "] should be type [" . $this->_type . "]"; + } + } + + /** + * Tests either type or class name if it's an object. + * Will succeed if the type does not match. + * @package SimpleTest + * @subpackage UnitTester + */ + class NotAExpectation extends IsAExpectation { + var $_type; + + /** + * Sets the type to compare with. + * @param string $type Type or class name. + * @param string $message Customised message on failure. + * @access public + */ + function NotAExpectation($type, $message = '%s') { + $this->IsAExpectation($type, $message); + } + + /** + * Tests the expectation. False if the type or + * class matches the string value. + * @param string $compare Comparison value. + * @return boolean True if different. + * @access public + */ + function test($compare) { + return ! parent::test($compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = &$this->_getDumper(); + return "Value [" . $dumper->describeValue($compare) . + "] should not be type [" . $this->_getType() . "]"; + } + } + + /** + * Tests for existance of a method in an object + * @package SimpleTest + * @subpackage UnitTester + */ + class MethodExistsExpectation extends SimpleExpectation { + var $_method; + + /** + * Sets the value to compare against. + * @param string $method Method to check. + * @param string $message Customised message on failure. + * @access public + * @return void + */ + function MethodExistsExpectation($method, $message = '%s') { + $this->SimpleExpectation($message); + $this->_method = &$method; + } + + /** + * Tests the expectation. True if the method exists in the test object. + * @param string $compare Comparison method name. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return (boolean)(is_object($compare) && method_exists($compare, $this->_method)); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = &$this->_getDumper(); + if (! is_object($compare)) { + return 'No method on non-object [' . $dumper->describeValue($compare) . ']'; + } + $method = $this->_method; + return "Object [" . $dumper->describeValue($compare) . + "] should contain method [$method]"; + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/extensions/pear_test_case.php b/tests/simpletest/extensions/pear_test_case.php new file mode 100644 index 00000000..0a33526c --- /dev/null +++ b/tests/simpletest/extensions/pear_test_case.php @@ -0,0 +1,198 @@ +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->assert($expectation, $second, $message); + } + + /** + * Passes if the value tested is not null. + * @param $value Value to test against. + * @param $message Message to display. + * @public + */ + function assertNotNull($value, $message = "%s") { + parent::assert(new TrueExpectation(), isset($value), $message); + } + + /** + * Passes if the value tested is null. + * @param $value Value to test against. + * @param $message Message to display. + * @public + */ + function assertNull($value, $message = "%s") { + parent::assert(new TrueExpectation(), !isset($value), $message); + } + + /** + * 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->assert( + new TrueExpectation(), + 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->assert( + new falseExpectation(), + SimpleTestCompatibility::isReference($first, $second), + $message); + } + + /** + * Sends pass if the test condition resolves true, + * a fail otherwise. + * @param $condition Condition to test true. + * @param $message Message to display. + * @public + */ + function assertTrue($condition, $message = "%s") { + parent::assert(new TrueExpectation(), $condition, $message); + } + + /** + * Sends pass if the test condition resolves false, + * a fail otherwise. + * @param $condition Condition to test false. + * @param $message Message to display. + * @public + */ + function assertFalse($condition, $message = "%s") { + parent::assert(new FalseExpectation(), $condition, $message); + } + + /** + * Tests a regex match. Needs refactoring. + * @param $pattern Regex to match. + * @param $subject String to search in. + * @param $message Message to display. + * @public + */ + function assertRegExp($pattern, $subject, $message = "%s") { + $this->assert(new PatternExpectation($pattern), $subject, $message); + } + + /** + * Tests the type of a value. + * @param $value Value to take type of. + * @param $type Hoped for type. + * @param $message Message to display. + * @public + */ + function assertType($value, $type, $message = "%s") { + parent::assert(new TrueExpectation(), gettype($value) == strtolower($type), $message); + } + + /** + * Sets equality operation to act as a simple equal + * comparison only, allowing a broader range of + * matches. + * @param $loosely_typed True for broader comparison. + * @public + */ + function setLooselyTyped($loosely_typed) { + $this->_loosely_typed = $loosely_typed; + } + + /** + * For progress indication during + * a test amongst other things. + * @return Usually one. + * @public + */ + function countTestCases() { + return $this->getSize(); + } + + /** + * Accessor for name, normally just the class + * name. + * @public + */ + function getName() { + return $this->getLabel(); + } + + /** + * Does nothing. For compatibility only. + * @param $name Dummy + * @public + */ + function setName($name) { + } + } +?> diff --git a/tests/simpletest/extensions/phpunit_test_case.php b/tests/simpletest/extensions/phpunit_test_case.php new file mode 100644 index 00000000..234d5bac --- /dev/null +++ b/tests/simpletest/extensions/phpunit_test_case.php @@ -0,0 +1,96 @@ +SimpleTestCase($label); + } + + /** + * Sends pass if the test condition resolves true, + * a fail otherwise. + * @param $condition Condition to test true. + * @param $message Message to display. + * @public + */ + function assert($condition, $message = false) { + parent::assert(new TrueExpectation(), $condition, $message); + } + + /** + * Will test straight equality if set to loose + * typing, or identity if not. + * @param $first First value. + * @param $second Comparison value. + * @param $message Message to display. + * @public + */ + function assertEquals($first, $second, $message = false) { + parent::assert(new EqualExpectation($first), $second, $message); + } + + /** + * Simple string equality. + * @param $first First value. + * @param $second Comparison value. + * @param $message Message to display. + * @public + */ + function assertEqualsMultilineStrings($first, $second, $message = false) { + parent::assert(new EqualExpectation($first), $second, $message); + } + + /** + * Tests a regex match. + * @param $pattern Regex to match. + * @param $subject String to search in. + * @param $message Message to display. + * @public + */ + function assertRegexp($pattern, $subject, $message = false) { + parent::assert(new PatternExpectation($pattern), $subject, $message); + } + + /** + * Sends an error which we interpret as a fail + * with a different message for compatibility. + * @param $message Message to display. + * @public + */ + function error($message) { + parent::fail("Error triggered [$message]"); + } + + /** + * Accessor for name. + * @public + */ + function name() { + return $this->getLabel(); + } + } +?> diff --git a/tests/simpletest/form.php b/tests/simpletest/form.php new file mode 100644 index 00000000..208392d5 --- /dev/null +++ b/tests/simpletest/form.php @@ -0,0 +1,352 @@ +_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(); + $this->_images = array(); + $this->_widgets = array(); + $this->_radios = array(); + $this->_checkboxes = array(); + } + + /** + * Creates the request packet to be sent by the form. + * @param SimpleTag $tag Form tag to read. + * @return string Packet class. + * @access private + */ + function _setEncodingClass($tag) { + if (strtolower($tag->getAttribute('method')) == 'post') { + if (strtolower($tag->getAttribute('enctype')) == 'multipart/form-data') { + return 'SimpleMultipartEncoding'; + } + return 'SimplePostEncoding'; + } + return 'SimpleGetEncoding'; + } + + /** + * Sets the frame target within a frameset. + * @param string $frame Name of frame. + * @access public + */ + function setDefaultTarget($frame) { + $this->_default_target = $frame; + } + + /** + * Accessor for method of form submission. + * @return string Either get or post. + * @access public + */ + function getMethod() { + return ($this->_method ? strtolower($this->_method) : 'get'); + } + + /** + * Combined action attribute with current location + * to get an absolute form target. + * @param string $action Action attribute from form tag. + * @param SimpleUrl $base Page location. + * @return SimpleUrl Absolute form target. + */ + function _createAction($action, $base) { + if (($action === '') || ($action === false)) { + return $base; + } + $url = new SimpleUrl($action); + return $url->makeAbsolute($base); + } + + /** + * Absolute URL of the target. + * @return SimpleUrl URL target. + * @access public + */ + function getAction() { + $url = $this->_action; + if ($this->_default_target && ! $url->getTarget()) { + $url->setTarget($this->_default_target); + } + return $url; + } + + /** + * Creates the encoding for the current values in the + * form. + * @return SimpleFormEncoding Request to submit. + * @access private + */ + function _encode() { + $class = $this->_encoding; + $encoding = new $class(); + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + $this->_widgets[$i]->write($encoding); + } + return $encoding; + } + + /** + * ID field of form for unique identification. + * @return string Unique tag ID. + * @access public + */ + function getId() { + return $this->_id; + } + + /** + * Adds a tag contents to the form. + * @param SimpleWidget $tag Input tag to add. + * @access public + */ + function addWidget(&$tag) { + if (strtolower($tag->getAttribute('type')) == 'submit') { + $this->_buttons[] = &$tag; + } elseif (strtolower($tag->getAttribute('type')) == 'image') { + $this->_images[] = &$tag; + } elseif ($tag->getName()) { + $this->_setWidget($tag); + } + } + + /** + * Sets the widget into the form, grouping radio + * buttons if any. + * @param SimpleWidget $tag Incoming form control. + * @access private + */ + function _setWidget(&$tag) { + if (strtolower($tag->getAttribute('type')) == 'radio') { + $this->_addRadioButton($tag); + } elseif (strtolower($tag->getAttribute('type')) == 'checkbox') { + $this->_addCheckbox($tag); + } else { + $this->_widgets[] = &$tag; + } + } + + /** + * Adds a radio button, building a group if necessary. + * @param SimpleRadioButtonTag $tag Incoming form control. + * @access private + */ + function _addRadioButton(&$tag) { + if (! isset($this->_radios[$tag->getName()])) { + $this->_widgets[] = &new SimpleRadioGroup(); + $this->_radios[$tag->getName()] = count($this->_widgets) - 1; + } + $this->_widgets[$this->_radios[$tag->getName()]]->addWidget($tag); + } + + /** + * Adds a checkbox, making it a group on a repeated name. + * @param SimpleCheckboxTag $tag Incoming form control. + * @access private + */ + function _addCheckbox(&$tag) { + if (! isset($this->_checkboxes[$tag->getName()])) { + $this->_widgets[] = &$tag; + $this->_checkboxes[$tag->getName()] = count($this->_widgets) - 1; + } else { + $index = $this->_checkboxes[$tag->getName()]; + if (! SimpleTestCompatibility::isA($this->_widgets[$index], 'SimpleCheckboxGroup')) { + $previous = &$this->_widgets[$index]; + $this->_widgets[$index] = &new SimpleCheckboxGroup(); + $this->_widgets[$index]->addWidget($previous); + } + $this->_widgets[$index]->addWidget($tag); + } + } + + /** + * Extracts current value from form. + * @param SimpleSelector $selector Criteria to apply. + * @return string/array Value(s) as string or null + * if not set. + * @access public + */ + function getValue($selector) { + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($selector->isMatch($this->_widgets[$i])) { + return $this->_widgets[$i]->getValue(); + } + } + foreach ($this->_buttons as $button) { + if ($selector->isMatch($button)) { + return $button->getValue(); + } + } + return null; + } + + /** + * Sets a widget value within the form. + * @param SimpleSelector $selector Criteria to apply. + * @param string $value Value to input into the widget. + * @return boolean True if value is legal, false + * otherwise. If the field is not + * present, nothing will be set. + * @access public + */ + function setField($selector, $value) { + $success = false; + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($selector->isMatch($this->_widgets[$i])) { + if ($this->_widgets[$i]->setValue($value)) { + $success = true; + } + } + } + return $success; + } + + /** + * Used by the page object to set widgets labels to + * external label tags. + * @param SimpleSelector $selector Criteria to apply. + * @access public + */ + function attachLabelBySelector($selector, $label) { + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($selector->isMatch($this->_widgets[$i])) { + if (method_exists($this->_widgets[$i], 'setLabel')) { + $this->_widgets[$i]->setLabel($label); + return; + } + } + } + } + + /** + * Test to see if a form has a submit button. + * @param SimpleSelector $selector Criteria to apply. + * @return boolean True if present. + * @access public + */ + function hasSubmit($selector) { + foreach ($this->_buttons as $button) { + if ($selector->isMatch($button)) { + return true; + } + } + return false; + } + + /** + * Test to see if a form has an image control. + * @param SimpleSelector $selector Criteria to apply. + * @return boolean True if present. + * @access public + */ + function hasImage($selector) { + foreach ($this->_images as $image) { + if ($selector->isMatch($image)) { + return true; + } + } + return false; + } + + /** + * Gets the submit values for a selected button. + * @param SimpleSelector $selector Criteria to apply. + * @param hash $additional Additional data for the form. + * @return SimpleEncoding Submitted values or false + * if there is no such button + * in the form. + * @access public + */ + function submitButton($selector, $additional = false) { + $additional = $additional ? $additional : array(); + foreach ($this->_buttons as $button) { + if ($selector->isMatch($button)) { + $encoding = $this->_encode(); + $button->write($encoding); + if ($additional) { + $encoding->merge($additional); + } + return $encoding; + } + } + return false; + } + + /** + * Gets the submit values for an image. + * @param SimpleSelector $selector Criteria to apply. + * @param integer $x X-coordinate of click. + * @param integer $y Y-coordinate of click. + * @param hash $additional Additional data for the form. + * @return SimpleEncoding Submitted values or false + * if there is no such button in the + * form. + * @access public + */ + function submitImage($selector, $x, $y, $additional = false) { + $additional = $additional ? $additional : array(); + foreach ($this->_images as $image) { + if ($selector->isMatch($image)) { + $encoding = $this->_encode(); + $image->write($encoding, $x, $y); + if ($additional) { + $encoding->merge($additional); + } + return $encoding; + } + } + return false; + } + + /** + * Simply submits the form without the submit button + * value. Used when there is only one button or it + * is unimportant. + * @return hash Submitted values. + * @access public + */ + function submit() { + return $this->_encode(); + } + } +?> diff --git a/tests/simpletest/frames.php b/tests/simpletest/frames.php new file mode 100644 index 00000000..60f8f335 --- /dev/null +++ b/tests/simpletest/frames.php @@ -0,0 +1,588 @@ +_frameset = &$page; + $this->_frames = array(); + $this->_focus = false; + $this->_names = array(); + } + + /** + * Adds a parsed page to the frameset. + * @param SimplePage $page Frame page. + * @param string $name Name of frame in frameset. + * @access public + */ + function addFrame(&$page, $name = false) { + $this->_frames[] = &$page; + if ($name) { + $this->_names[$name] = count($this->_frames) - 1; + } + } + + /** + * Replaces existing frame with another. If the + * frame is nested, then the call is passed down + * one level. + * @param array $path Path of frame in frameset. + * @param SimplePage $page Frame source. + * @access public + */ + function setFrame($path, &$page) { + $name = array_shift($path); + if (isset($this->_names[$name])) { + $index = $this->_names[$name]; + } else { + $index = $name - 1; + } + if (count($path) == 0) { + $this->_frames[$index] = &$page; + return; + } + $this->_frames[$index]->setFrame($path, $page); + } + + /** + * Accessor for current frame focus. Will be + * false if no frame has focus. Will have the nested + * frame focus if any. + * @return array Labels or indexes of nested frames. + * @access public + */ + function getFrameFocus() { + if ($this->_focus === false) { + return array(); + } + return array_merge( + array($this->_getPublicNameFromIndex($this->_focus)), + $this->_frames[$this->_focus]->getFrameFocus()); + } + + /** + * Turns an internal array index into the frames list + * into a public name, or if none, then a one offset + * index. + * @param integer $subject Internal index. + * @return integer/string Public name. + * @access private + */ + function _getPublicNameFromIndex($subject) { + foreach ($this->_names as $name => $index) { + if ($subject == $index) { + return $name; + } + } + return $subject + 1; + } + + /** + * Sets the focus by index. The integer index starts from 1. + * If already focused and the target frame also has frames, + * then the nested frame will be focused. + * @param integer $choice Chosen frame. + * @return boolean True if frame exists. + * @access public + */ + function setFrameFocusByIndex($choice) { + if (is_integer($this->_focus)) { + if ($this->_frames[$this->_focus]->hasFrames()) { + return $this->_frames[$this->_focus]->setFrameFocusByIndex($choice); + } + } + if (($choice < 1) || ($choice > count($this->_frames))) { + return false; + } + $this->_focus = $choice - 1; + return true; + } + + /** + * Sets the focus by name. If already focused and the + * target frame also has frames, then the nested frame + * will be focused. + * @param string $name Chosen frame. + * @return boolean True if frame exists. + * @access public + */ + function setFrameFocus($name) { + if (is_integer($this->_focus)) { + if ($this->_frames[$this->_focus]->hasFrames()) { + return $this->_frames[$this->_focus]->setFrameFocus($name); + } + } + if (in_array($name, array_keys($this->_names))) { + $this->_focus = $this->_names[$name]; + return true; + } + return false; + } + + /** + * Clears the frame focus. + * @access public + */ + function clearFrameFocus() { + $this->_focus = false; + $this->_clearNestedFramesFocus(); + } + + /** + * Clears the frame focus for any nested frames. + * @access private + */ + function _clearNestedFramesFocus() { + for ($i = 0; $i < count($this->_frames); $i++) { + $this->_frames[$i]->clearFrameFocus(); + } + } + + /** + * Test for the presence of a frameset. + * @return boolean Always true. + * @access public + */ + function hasFrames() { + return true; + } + + /** + * Accessor for frames information. + * @return array/string Recursive hash of frame URL strings. + * The key is either a numerical + * index or the name attribute. + * @access public + */ + function getFrames() { + $report = array(); + for ($i = 0; $i < count($this->_frames); $i++) { + $report[$this->_getPublicNameFromIndex($i)] = + $this->_frames[$i]->getFrames(); + } + return $report; + } + + /** + * Accessor for raw text of either all the pages or + * the frame in focus. + * @return string Raw unparsed content. + * @access public + */ + function getRaw() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getRaw(); + } + $raw = ''; + for ($i = 0; $i < count($this->_frames); $i++) { + $raw .= $this->_frames[$i]->getRaw(); + } + return $raw; + } + + /** + * Accessor for plain text of either all the pages or + * the frame in focus. + * @return string Plain text content. + * @access public + */ + function getText() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getText(); + } + $raw = ''; + for ($i = 0; $i < count($this->_frames); $i++) { + $raw .= ' ' . $this->_frames[$i]->getText(); + } + return trim($raw); + } + + /** + * Accessor for last error. + * @return string Error from last response. + * @access public + */ + function getTransportError() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getTransportError(); + } + return $this->_frameset->getTransportError(); + } + + /** + * Request method used to fetch this frame. + * @return string GET, POST or HEAD. + * @access public + */ + function getMethod() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getMethod(); + } + return $this->_frameset->getMethod(); + } + + /** + * Original resource name. + * @return SimpleUrl Current url. + * @access public + */ + function getUrl() { + if (is_integer($this->_focus)) { + $url = $this->_frames[$this->_focus]->getUrl(); + $url->setTarget($this->_getPublicNameFromIndex($this->_focus)); + } else { + $url = $this->_frameset->getUrl(); + } + return $url; + } + + /** + * Original request data. + * @return mixed Sent content. + * @access public + */ + function getRequestData() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getRequestData(); + } + return $this->_frameset->getRequestData(); + } + + /** + * Accessor for current MIME type. + * @return string MIME type as string; e.g. 'text/html' + * @access public + */ + function getMimeType() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getMimeType(); + } + return $this->_frameset->getMimeType(); + } + + /** + * Accessor for last response code. + * @return integer Last HTTP response code received. + * @access public + */ + function getResponseCode() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getResponseCode(); + } + return $this->_frameset->getResponseCode(); + } + + /** + * Accessor for last Authentication type. Only valid + * straight after a challenge (401). + * @return string Description of challenge type. + * @access public + */ + function getAuthentication() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getAuthentication(); + } + return $this->_frameset->getAuthentication(); + } + + /** + * Accessor for last Authentication realm. Only valid + * straight after a challenge (401). + * @return string Name of security realm. + * @access public + */ + function getRealm() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getRealm(); + } + return $this->_frameset->getRealm(); + } + + /** + * Accessor for outgoing header information. + * @return string Header block. + * @access public + */ + function getRequest() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getRequest(); + } + return $this->_frameset->getRequest(); + } + + /** + * Accessor for raw header information. + * @return string Header block. + * @access public + */ + function getHeaders() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getHeaders(); + } + return $this->_frameset->getHeaders(); + } + + /** + * Accessor for parsed title. + * @return string Title or false if no title is present. + * @access public + */ + function getTitle() { + return $this->_frameset->getTitle(); + } + + /** + * Accessor for a list of all fixed links. + * @return array List of urls with scheme of + * http or https and hostname. + * @access public + */ + function getAbsoluteUrls() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getAbsoluteUrls(); + } + $urls = array(); + foreach ($this->_frames as $frame) { + $urls = array_merge($urls, $frame->getAbsoluteUrls()); + } + return array_values(array_unique($urls)); + } + + /** + * Accessor for a list of all relative links. + * @return array List of urls without hostname. + * @access public + */ + function getRelativeUrls() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getRelativeUrls(); + } + $urls = array(); + foreach ($this->_frames as $frame) { + $urls = array_merge($urls, $frame->getRelativeUrls()); + } + return array_values(array_unique($urls)); + } + + /** + * Accessor for URLs by the link label. Label will match + * regardess of whitespace issues and case. + * @param string $label Text of link. + * @return array List of links with that label. + * @access public + */ + function getUrlsByLabel($label) { + if (is_integer($this->_focus)) { + return $this->_tagUrlsWithFrame( + $this->_frames[$this->_focus]->getUrlsByLabel($label), + $this->_focus); + } + $urls = array(); + foreach ($this->_frames as $index => $frame) { + $urls = array_merge( + $urls, + $this->_tagUrlsWithFrame( + $frame->getUrlsByLabel($label), + $index)); + } + return $urls; + } + + /** + * Accessor for a URL by the id attribute. If in a frameset + * then the first link found with that ID attribute is + * returned only. Focus on a frame if you want one from + * a specific part of the frameset. + * @param string $id Id attribute of link. + * @return string URL with that id. + * @access public + */ + function getUrlById($id) { + foreach ($this->_frames as $index => $frame) { + if ($url = $frame->getUrlById($id)) { + if (! $url->gettarget()) { + $url->setTarget($this->_getPublicNameFromIndex($index)); + } + return $url; + } + } + return false; + } + + /** + * Attaches the intended frame index to a list of URLs. + * @param array $urls List of SimpleUrls. + * @param string $frame Name of frame or index. + * @return array List of tagged URLs. + * @access private + */ + function _tagUrlsWithFrame($urls, $frame) { + $tagged = array(); + foreach ($urls as $url) { + if (! $url->getTarget()) { + $url->setTarget($this->_getPublicNameFromIndex($frame)); + } + $tagged[] = $url; + } + return $tagged; + } + + /** + * Finds a held form by button label. Will only + * search correctly built forms. + * @param SimpleSelector $selector Button finder. + * @return SimpleForm Form object containing + * the button. + * @access public + */ + function &getFormBySubmit($selector) { + $form = &$this->_findForm('getFormBySubmit', $selector); + return $form; + } + + /** + * Finds a held form by image using a selector. + * Will only search correctly built forms. The first + * form found either within the focused frame, or + * across frames, will be the one returned. + * @param SimpleSelector $selector Image finder. + * @return SimpleForm Form object containing + * the image. + * @access public + */ + function &getFormByImage($selector) { + $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 + * of the HTML code. The first form found + * either within the focused frame, or across frames, + * will be the one returned. + * @param string $id Form label. + * @return SimpleForm Form object containing the matching ID. + * @access public + */ + function &getFormById($id) { + $form = &$this->_findForm('getFormById', $id); + return $form; + } + + /** + * General form finder. Will search all the frames or + * just the one in focus. + * @param string $method Method to use to find in a page. + * @param string $attribute Label, name or ID. + * @return SimpleForm Form object containing the matching ID. + * @access private + */ + function &_findForm($method, $attribute) { + if (is_integer($this->_focus)) { + $form = &$this->_findFormInFrame( + $this->_frames[$this->_focus], + $this->_focus, + $method, + $attribute); + return $form; + } + for ($i = 0; $i < count($this->_frames); $i++) { + $form = &$this->_findFormInFrame( + $this->_frames[$i], + $i, + $method, + $attribute); + if ($form) { + return $form; + } + } + $null = null; + return $null; + } + + /** + * Finds a form in a page using a form finding method. Will + * also tag the form with the frame name it belongs in. + * @param SimplePage $page Page content of frame. + * @param integer $index Internal frame representation. + * @param string $method Method to use to find in a page. + * @param string $attribute Label, name or ID. + * @return SimpleForm Form object containing the matching ID. + * @access private + */ + function &_findFormInFrame(&$page, $index, $method, $attribute) { + $form = &$this->_frames[$index]->$method($attribute); + if (isset($form)) { + $form->setDefaultTarget($this->_getPublicNameFromIndex($index)); + } + return $form; + } + + /** + * Sets a field on each form in which the field is + * available. + * @param SimpleSelector $selector Field finder. + * @param string $value Value to set field to. + * @return boolean True if value is valid. + * @access public + */ + function setField($selector, $value) { + if (is_integer($this->_focus)) { + $this->_frames[$this->_focus]->setField($selector, $value); + } else { + for ($i = 0; $i < count($this->_frames); $i++) { + $this->_frames[$i]->setField($selector, $value); + } + } + } + + /** + * Accessor for a form element value within a page. + * @param SimpleSelector $selector Field finder. + * @return string/boolean A string if the field is + * present, false if unchecked + * and null if missing. + * @access public + */ + function getField($selector) { + for ($i = 0; $i < count($this->_frames); $i++) { + $value = $this->_frames[$i]->getField($selector); + if (isset($value)) { + return $value; + } + } + return null; + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/http.php b/tests/simpletest/http.php new file mode 100644 index 00000000..6ec12cd6 --- /dev/null +++ b/tests/simpletest/http.php @@ -0,0 +1,624 @@ +_url = $url; + } + + /** + * Resource name. + * @return SimpleUrl Current url. + * @access protected + */ + function getUrl() { + return $this->_url; + } + + /** + * Creates the first line which is the actual request. + * @param string $method HTTP request method, usually GET. + * @return string Request line content. + * @access protected + */ + function _getRequestLine($method) { + return $method . ' ' . $this->_url->getPath() . + $this->_url->getEncodedRequest() . ' HTTP/1.0'; + } + + /** + * Creates the host part of the request. + * @return string Host line content. + * @access protected + */ + function _getHostLine() { + $line = 'Host: ' . $this->_url->getHost(); + if ($this->_url->getPort()) { + $line .= ':' . $this->_url->getPort(); + } + return $line; + } + + /** + * Opens a socket to the route. + * @param string $method HTTP request method, usually GET. + * @param integer $timeout Connection timeout. + * @return SimpleSocket New socket. + * @access public + */ + function &createConnection($method, $timeout) { + $default_port = ('https' == $this->_url->getScheme()) ? 443 : 80; + $socket = &$this->_createSocket( + $this->_url->getScheme() ? $this->_url->getScheme() : 'http', + $this->_url->getHost(), + $this->_url->getPort() ? $this->_url->getPort() : $default_port, + $timeout); + if (! $socket->isError()) { + $socket->write($this->_getRequestLine($method) . "\r\n"); + $socket->write($this->_getHostLine() . "\r\n"); + $socket->write("Connection: close\r\n"); + } + return $socket; + } + + /** + * Factory for socket. + * @param string $scheme Protocol to use. + * @param string $host Hostname to connect to. + * @param integer $port Remote port. + * @param integer $timeout Connection timeout. + * @return SimpleSocket/SimpleSecureSocket New socket. + * @access protected + */ + function &_createSocket($scheme, $host, $port, $timeout) { + if (in_array($scheme, array('https'))) { + $socket = &new SimpleSecureSocket($host, $port, $timeout); + } else { + $socket = &new SimpleSocket($host, $port, $timeout); + } + return $socket; + } + } + + /** + * Creates HTTP headers for the end point of + * a HTTP request via a proxy server. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleProxyRoute extends SimpleRoute { + var $_proxy; + var $_username; + var $_password; + + /** + * Stashes the proxy address. + * @param SimpleUrl $url URL as object. + * @param string $proxy Proxy URL. + * @param string $username Username for autentication. + * @param string $password Password for autentication. + * @access public + */ + function SimpleProxyRoute($url, $proxy, $username = false, $password = false) { + $this->SimpleRoute($url); + $this->_proxy = $proxy; + $this->_username = $username; + $this->_password = $password; + } + + /** + * Creates the first line which is the actual request. + * @param string $method HTTP request method, usually GET. + * @param SimpleUrl $url URL as object. + * @return string Request line content. + * @access protected + */ + function _getRequestLine($method) { + $url = $this->getUrl(); + $scheme = $url->getScheme() ? $url->getScheme() : 'http'; + $port = $url->getPort() ? ':' . $url->getPort() : ''; + return $method . ' ' . $scheme . '://' . $url->getHost() . $port . + $url->getPath() . $url->getEncodedRequest() . ' HTTP/1.0'; + } + + /** + * Creates the host part of the request. + * @param SimpleUrl $url URL as object. + * @return string Host line content. + * @access protected + */ + function _getHostLine() { + $host = 'Host: ' . $this->_proxy->getHost(); + $port = $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080; + return "$host:$port"; + } + + /** + * Opens a socket to the route. + * @param string $method HTTP request method, usually GET. + * @param integer $timeout Connection timeout. + * @return SimpleSocket New socket. + * @access public + */ + function &createConnection($method, $timeout) { + $socket = &$this->_createSocket( + $this->_proxy->getScheme() ? $this->_proxy->getScheme() : 'http', + $this->_proxy->getHost(), + $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080, + $timeout); + if ($socket->isError()) { + return $socket; + } + $socket->write($this->_getRequestLine($method) . "\r\n"); + $socket->write($this->_getHostLine() . "\r\n"); + if ($this->_username && $this->_password) { + $socket->write('Proxy-Authorization: Basic ' . + base64_encode($this->_username . ':' . $this->_password) . + "\r\n"); + } + $socket->write("Connection: close\r\n"); + return $socket; + } + } + + /** + * HTTP request for a web page. Factory for + * HttpResponse object. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleHttpRequest { + var $_route; + var $_encoding; + var $_headers; + var $_cookies; + + /** + * Builds the socket request from the different pieces. + * These include proxy information, URL, cookies, headers, + * request method and choice of encoding. + * @param SimpleRoute $route Request route. + * @param SimpleFormEncoding $encoding Content to send with + * request. + * @access public + */ + function SimpleHttpRequest(&$route, $encoding) { + $this->_route = &$route; + $this->_encoding = $encoding; + $this->_headers = array(); + $this->_cookies = array(); + } + + /** + * Dispatches the content to the route's socket. + * @param integer $timeout Connection timeout. + * @return SimpleHttpResponse A response which may only have + * an error, but hopefully has a + * complete web page. + * @access public + */ + function &fetch($timeout) { + $socket = &$this->_route->createConnection($this->_encoding->getMethod(), $timeout); + if (! $socket->isError()) { + $this->_dispatchRequest($socket, $this->_encoding); + } + $response = &$this->_createResponse($socket); + return $response; + } + + /** + * Sends the headers. + * @param SimpleSocket $socket Open socket. + * @param string $method HTTP request method, + * usually GET. + * @param SimpleFormEncoding $encoding Content to send with request. + * @access private + */ + function _dispatchRequest(&$socket, $encoding) { + foreach ($this->_headers as $header_line) { + $socket->write($header_line . "\r\n"); + } + if (count($this->_cookies) > 0) { + $socket->write("Cookie: " . implode(";", $this->_cookies) . "\r\n"); + } + $encoding->writeHeadersTo($socket); + $socket->write("\r\n"); + $encoding->writeTo($socket); + } + + /** + * Adds a header line to the request. + * @param string $header_line Text of full header line. + * @access public + */ + function addHeaderLine($header_line) { + $this->_headers[] = $header_line; + } + + /** + * Reads all the relevant cookies from the + * cookie jar. + * @param SimpleCookieJar $jar Jar to read + * @param SimpleUrl $url Url to use for scope. + * @access public + */ + function readCookiesFromJar($jar, $url) { + $this->_cookies = $jar->selectAsPairs($url); + } + + /** + * Wraps the socket in a response parser. + * @param SimpleSocket $socket Responding socket. + * @return SimpleHttpResponse Parsed response object. + * @access protected + */ + function &_createResponse(&$socket) { + $response = &new SimpleHttpResponse( + $socket, + $this->_route->getUrl(), + $this->_encoding); + return $response; + } + } + + /** + * Collection of header lines in the response. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleHttpHeaders { + var $_raw_headers; + var $_response_code; + var $_http_version; + var $_mime_type; + var $_location; + var $_cookies; + var $_authentication; + var $_realm; + + /** + * Parses the incoming header block. + * @param string $headers Header block. + * @access public + */ + function SimpleHttpHeaders($headers) { + $this->_raw_headers = $headers; + $this->_response_code = false; + $this->_http_version = false; + $this->_mime_type = ''; + $this->_location = false; + $this->_cookies = array(); + $this->_authentication = false; + $this->_realm = false; + foreach (split("\r\n", $headers) as $header_line) { + $this->_parseHeaderLine($header_line); + } + } + + /** + * Accessor for parsed HTTP protocol version. + * @return integer HTTP error code. + * @access public + */ + function getHttpVersion() { + return $this->_http_version; + } + + /** + * Accessor for raw header block. + * @return string All headers as raw string. + * @access public + */ + function getRaw() { + return $this->_raw_headers; + } + + /** + * Accessor for parsed HTTP error code. + * @return integer HTTP error code. + * @access public + */ + function getResponseCode() { + return (integer)$this->_response_code; + } + + /** + * Returns the redirected URL or false if + * no redirection. + * @return string URL or false for none. + * @access public + */ + function getLocation() { + return $this->_location; + } + + /** + * Test to see if the response is a valid redirect. + * @return boolean True if valid redirect. + * @access public + */ + function isRedirect() { + return in_array($this->_response_code, array(301, 302, 303, 307)) && + (boolean)$this->getLocation(); + } + + /** + * Test to see if the response is an authentication + * challenge. + * @return boolean True if challenge. + * @access public + */ + function isChallenge() { + return ($this->_response_code == 401) && + (boolean)$this->_authentication && + (boolean)$this->_realm; + } + + /** + * Accessor for MIME type header information. + * @return string MIME type. + * @access public + */ + function getMimeType() { + return $this->_mime_type; + } + + /** + * Accessor for authentication type. + * @return string Type. + * @access public + */ + function getAuthentication() { + return $this->_authentication; + } + + /** + * Accessor for security realm. + * @return string Realm. + * @access public + */ + function getRealm() { + return $this->_realm; + } + + /** + * Writes new cookies to the cookie jar. + * @param SimpleCookieJar $jar Jar to write to. + * @param SimpleUrl $url Host and path to write under. + * @access public + */ + function writeCookiesToJar(&$jar, $url) { + foreach ($this->_cookies as $cookie) { + $jar->setCookie( + $cookie->getName(), + $cookie->getValue(), + $url->getHost(), + $cookie->getPath(), + $cookie->getExpiry()); + } + } + + /** + * Called on each header line to accumulate the held + * data within the class. + * @param string $header_line One line of header. + * @access protected + */ + function _parseHeaderLine($header_line) { + if (preg_match('/HTTP\/(\d+\.\d+)\s+(\d+)/i', $header_line, $matches)) { + $this->_http_version = $matches[1]; + $this->_response_code = $matches[2]; + } + if (preg_match('/Content-type:\s*(.*)/i', $header_line, $matches)) { + $this->_mime_type = trim($matches[1]); + } + if (preg_match('/Location:\s*(.*)/i', $header_line, $matches)) { + $this->_location = trim($matches[1]); + } + if (preg_match('/Set-cookie:(.*)/i', $header_line, $matches)) { + $this->_cookies[] = $this->_parseCookie($matches[1]); + } + if (preg_match('/WWW-Authenticate:\s+(\S+)\s+realm=\"(.*?)\"/i', $header_line, $matches)) { + $this->_authentication = $matches[1]; + $this->_realm = trim($matches[2]); + } + } + + /** + * Parse the Set-cookie content. + * @param string $cookie_line Text after "Set-cookie:" + * @return SimpleCookie New cookie object. + * @access private + */ + function _parseCookie($cookie_line) { + $parts = split(";", $cookie_line); + $cookie = array(); + preg_match('/\s*(.*?)\s*=(.*)/', array_shift($parts), $cookie); + foreach ($parts as $part) { + if (preg_match('/\s*(.*?)\s*=(.*)/', $part, $matches)) { + $cookie[$matches[1]] = trim($matches[2]); + } + } + return new SimpleCookie( + $cookie[1], + trim($cookie[2]), + isset($cookie["path"]) ? $cookie["path"] : "", + isset($cookie["expires"]) ? $cookie["expires"] : false); + } + } + + /** + * Basic HTTP response. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleHttpResponse extends SimpleStickyError { + var $_url; + var $_encoding; + var $_sent; + var $_content; + var $_headers; + + /** + * Constructor. Reads and parses the incoming + * content and headers. + * @param SimpleSocket $socket Network connection to fetch + * response text from. + * @param SimpleUrl $url Resource name. + * @param mixed $encoding Record of content sent. + * @access public + */ + function SimpleHttpResponse(&$socket, $url, $encoding) { + $this->SimpleStickyError(); + $this->_url = $url; + $this->_encoding = $encoding; + $this->_sent = $socket->getSent(); + $this->_content = false; + $raw = $this->_readAll($socket); + if ($socket->isError()) { + $this->_setError('Error reading socket [' . $socket->getError() . ']'); + return; + } + $this->_parse($raw); + } + + /** + * Splits up the headers and the rest of the content. + * @param string $raw Content to parse. + * @access private + */ + function _parse($raw) { + if (! $raw) { + $this->_setError('Nothing fetched'); + $this->_headers = &new SimpleHttpHeaders(''); + } elseif (! strstr($raw, "\r\n\r\n")) { + $this->_setError('Could not split headers from content'); + $this->_headers = &new SimpleHttpHeaders($raw); + } else { + list($headers, $this->_content) = split("\r\n\r\n", $raw, 2); + $this->_headers = &new SimpleHttpHeaders($headers); + } + } + + /** + * Original request method. + * @return string GET, POST or HEAD. + * @access public + */ + function getMethod() { + return $this->_encoding->getMethod(); + } + + /** + * Resource name. + * @return SimpleUrl Current url. + * @access public + */ + function getUrl() { + return $this->_url; + } + + /** + * Original request data. + * @return mixed Sent content. + * @access public + */ + function getRequestData() { + return $this->_encoding; + } + + /** + * Raw request that was sent down the wire. + * @return string Bytes actually sent. + * @access public + */ + function getSent() { + return $this->_sent; + } + + /** + * Accessor for the content after the last + * header line. + * @return string All content. + * @access public + */ + function getContent() { + return $this->_content; + } + + /** + * Accessor for header block. The response is the + * combination of this and the content. + * @return SimpleHeaders Wrapped header block. + * @access public + */ + function getHeaders() { + return $this->_headers; + } + + /** + * Accessor for any new cookies. + * @return array List of new cookies. + * @access public + */ + function getNewCookies() { + return $this->_headers->getNewCookies(); + } + + /** + * Reads the whole of the socket output into a + * single string. + * @param SimpleSocket $socket Unread socket. + * @return string Raw output if successful + * else false. + * @access private + */ + function _readAll(&$socket) { + $all = ''; + while (! $this->_isLastPacket($next = $socket->read())) { + $all .= $next; + } + return $all; + } + + /** + * Test to see if the packet from the socket is the + * last one. + * @param string $packet Chunk to interpret. + * @return boolean True if empty or EOF. + * @access private + */ + function _isLastPacket($packet) { + if (is_string($packet)) { + return $packet === ''; + } + return ! $packet; + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/invoker.php b/tests/simpletest/invoker.php new file mode 100644 index 00000000..9c6ec46e --- /dev/null +++ b/tests/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 { + var $_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/simpletest/mock_objects.php b/tests/simpletest/mock_objects.php new file mode 100644 index 00000000..a9cb9815 --- /dev/null +++ b/tests/simpletest/mock_objects.php @@ -0,0 +1,1312 @@ += 0) { + require_once(dirname(__FILE__) . '/reflection_php5.php'); + } else { + require_once(dirname(__FILE__) . '/reflection_php4.php'); + } + /**#@-*/ + + /** + * Default character simpletest will substitute for any value + */ + if (! defined('MOCK_ANYTHING')) { + define('MOCK_ANYTHING', '*'); + } + + /** + * Parameter comparison assertion. + * @package SimpleTest + * @subpackage MockObjects + */ + class ParametersExpectation extends SimpleExpectation { + var $_expected; + + /** + * Sets the expected parameter list. + * @param array $parameters Array of parameters including + * those that are wildcarded. + * If the value is not an array + * then it is considered to match any. + * @param string $message Customised message on failure. + * @access public + */ + function ParametersExpectation($expected = false, $message = '%s') { + $this->SimpleExpectation($message); + $this->_expected = $expected; + } + + /** + * Tests the assertion. True if correct. + * @param array $parameters Comparison values. + * @return boolean True if correct. + * @access public + */ + function test($parameters) { + if (! is_array($this->_expected)) { + return true; + } + if (count($this->_expected) != count($parameters)) { + return false; + } + for ($i = 0; $i < count($this->_expected); $i++) { + if (! $this->_testParameter($parameters[$i], $this->_expected[$i])) { + return false; + } + } + return true; + } + + /** + * Tests an individual parameter. + * @param mixed $parameter Value to test. + * @param mixed $expected Comparison value. + * @return boolean True if expectation + * fulfilled. + * @access private + */ + function _testParameter($parameter, $expected) { + $comparison = $this->_coerceToExpectation($expected); + return $comparison->test($parameter); + } + + /** + * Returns a human readable test message. + * @param array $comparison Incoming parameter list. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($parameters) { + if ($this->test($parameters)) { + return "Expectation of " . count($this->_expected) . + " arguments of [" . $this->_renderArguments($this->_expected) . + "] is correct"; + } else { + return $this->_describeDifference($this->_expected, $parameters); + } + } + + /** + * Message to display if expectation differs from + * the parameters actually received. + * @param array $expected Expected parameters as list. + * @param array $parameters Actual parameters received. + * @return string Description of difference. + * @access private + */ + function _describeDifference($expected, $parameters) { + if (count($expected) != count($parameters)) { + return "Expected " . count($expected) . + " arguments of [" . $this->_renderArguments($expected) . + "] but got " . count($parameters) . + " arguments of [" . $this->_renderArguments($parameters) . "]"; + } + $messages = array(); + for ($i = 0; $i < count($expected); $i++) { + $comparison = $this->_coerceToExpectation($expected[$i]); + if (! $comparison->test($parameters[$i])) { + $messages[] = "parameter " . ($i + 1) . " with [" . + $comparison->overlayMessage($parameters[$i], $this->_getDumper()) . "]"; + } + } + return "Parameter expectation differs at " . implode(" and ", $messages); + } + + /** + * Creates an identical expectation if the + * object/value is not already some type + * of expectation. + * @param mixed $expected Expected value. + * @return SimpleExpectation Expectation object. + * @access private + */ + function _coerceToExpectation($expected) { + if (SimpleExpectation::isExpectation($expected)) { + return $expected; + } + return new IdenticalExpectation($expected); + } + + /** + * Renders the argument list as a string for + * messages. + * @param array $args Incoming arguments. + * @return string Simple description of type and value. + * @access private + */ + function _renderArguments($args) { + $descriptions = array(); + if (is_array($args)) { + foreach ($args as $arg) { + $dumper = &new SimpleDumper(); + $descriptions[] = $dumper->describeValue($arg); + } + } + return implode(', ', $descriptions); + } + } + + /** + * Confirms that the number of calls on a method is as expected. + * @package SimpleTest + * @subpackage MockObjects + */ + class CallCountExpectation extends SimpleExpectation { + var $_method; + var $_count; + + /** + * Stashes the method and expected count for later + * reporting. + * @param string $method Name of method to confirm against. + * @param integer $count Expected number of calls. + * @param string $message Custom error message. + */ + function CallCountExpectation($method, $count, $message = '%s') { + $this->_method = $method; + $this->_count = $count; + $this->SimpleExpectation($message); + } + + /** + * Tests the assertion. True if correct. + * @param integer $compare Measured call count. + * @return boolean True if expected. + * @access public + */ + function test($compare) { + return ($this->_count == $compare); + } + + /** + * Reports the comparison. + * @param integer $compare Measured call count. + * @return string Message to show. + * @access public + */ + function testMessage($compare) { + return 'Expected call count for [' . $this->_method . + '] was [' . $this->_count . + '] got [' . $compare . ']'; + } + } + + /** + * Confirms that the number of calls on a method is as expected. + * @package SimpleTest + * @subpackage MockObjects + */ + class MinimumCallCountExpectation extends SimpleExpectation { + var $_method; + var $_count; + + /** + * Stashes the method and expected count for later + * reporting. + * @param string $method Name of method to confirm against. + * @param integer $count Minimum number of calls. + * @param string $message Custom error message. + */ + function MinimumCallCountExpectation($method, $count, $message = '%s') { + $this->_method = $method; + $this->_count = $count; + $this->SimpleExpectation($message); + } + + /** + * Tests the assertion. True if correct. + * @param integer $compare Measured call count. + * @return boolean True if enough. + * @access public + */ + function test($compare) { + return ($this->_count <= $compare); + } + + /** + * Reports the comparison. + * @param integer $compare Measured call count. + * @return string Message to show. + * @access public + */ + function testMessage($compare) { + return 'Minimum call count for [' . $this->_method . + '] was [' . $this->_count . + '] got [' . $compare . ']'; + } + } + + /** + * Confirms that the number of calls on a method is as expected. + * @package SimpleTest + * @subpackage MockObjects + */ + class MaximumCallCountExpectation extends SimpleExpectation { + var $_method; + var $_count; + + /** + * Stashes the method and expected count for later + * reporting. + * @param string $method Name of method to confirm against. + * @param integer $count Minimum number of calls. + * @param string $message Custom error message. + */ + function MaximumCallCountExpectation($method, $count, $message = '%s') { + $this->_method = $method; + $this->_count = $count; + $this->SimpleExpectation($message); + } + + /** + * Tests the assertion. True if correct. + * @param integer $compare Measured call count. + * @return boolean True if not over. + * @access public + */ + function test($compare) { + return ($this->_count >= $compare); + } + + /** + * Reports the comparison. + * @param integer $compare Measured call count. + * @return string Message to show. + * @access public + */ + function testMessage($compare) { + return 'Maximum call count for [' . $this->_method . + '] was [' . $this->_count . + '] got [' . $compare . ']'; + } + } + + /** + * Retrieves values and references by searching the + * parameter lists until a match is found. + * @package SimpleTest + * @subpackage MockObjects + */ + class CallMap { + var $_map; + + /** + * Creates an empty call map. + * @access public + */ + function CallMap() { + $this->_map = array(); + } + + /** + * Stashes a value against a method call. + * @param array $parameters Arguments including wildcards. + * @param mixed $value Value copied into the map. + * @access public + */ + function addValue($parameters, $value) { + $this->addReference($parameters, $value); + } + + /** + * Stashes a reference against a method call. + * @param array $parameters Array of arguments (including wildcards). + * @param mixed $reference Array reference placed in the map. + * @access public + */ + function addReference($parameters, &$reference) { + $place = count($this->_map); + $this->_map[$place] = array(); + $this->_map[$place]["params"] = new ParametersExpectation($parameters); + $this->_map[$place]["content"] = &$reference; + } + + /** + * Searches the call list for a matching parameter + * set. Returned by reference. + * @param array $parameters Parameters to search by + * without wildcards. + * @return object Object held in the first matching + * slot, otherwise null. + * @access public + */ + function &findFirstMatch($parameters) { + $slot = $this->_findFirstSlot($parameters); + if (!isset($slot)) { + $null = null; + return $null; + } + return $slot["content"]; + } + + /** + * Searches the call list for a matching parameter + * set. True if successful. + * @param array $parameters Parameters to search by + * without wildcards. + * @return boolean True if a match is present. + * @access public + */ + function isMatch($parameters) { + return ($this->_findFirstSlot($parameters) != null); + } + + /** + * Searches the map for a matching item. + * @param array $parameters Parameters to search by + * without wildcards. + * @return array Reference to slot or null. + * @access private + */ + function &_findFirstSlot($parameters) { + $count = count($this->_map); + for ($i = 0; $i < $count; $i++) { + if ($this->_map[$i]["params"]->test($parameters)) { + return $this->_map[$i]; + } + } + $null = null; + 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 { + var $_wildcard = MOCK_ANYTHING; + var $_is_strict = true; + var $_returns; + var $_return_sequence; + var $_call_counts; + var $_expected_counts; + var $_max_counts; + var $_expected_args; + var $_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. + */ + 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(); + } + + /** + * Disables a name check when setting expectations. + * This hack is needed for the partial mocks. + * @access public + */ + function disableExpectationNameChecks() { + $this->_is_strict = false; + } + + /** + * Finds currently running test. + * @return SimpeTestCase Current test case. + * @access protected + */ + function &_getCurrentTestCase() { + $context = &SimpleTest::getContext(); + return $context->getTest(); + } + + /** + * Die if bad arguments array is passed + * @param mixed $args The arguments value to be checked. + * @param string $task Description of task attempt. + * @return boolean Valid arguments + * @access private + */ + function _checkArgumentsIsArray($args, $task) { + if (! is_array($args)) { + trigger_error( + "Cannot $task as \$args parameter is not an array", + E_USER_ERROR); + } + } + + /** + * Triggers a PHP error if the method is not part + * of this object. + * @param string $method Name of method. + * @param string $task Description of task attempt. + * @access protected + */ + function _dieOnNoMethod($method, $task) { + if ($this->_is_strict && ! method_exists($this, $method)) { + trigger_error( + "Cannot $task as no ${method}() in class " . get_class($this), + E_USER_ERROR); + } + } + + /** + * 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. + * @param array $args Arguments as an array. + * @access protected + */ + function _addCall($method, $args) { + if (!isset($this->_call_counts[$method])) { + $this->_call_counts[$method] = 0; + } + $this->_call_counts[$method]++; + } + + /** + * Fetches the call count of a method so far. + * @param string $method Method name called. + * @return Number of calls so far. + * @access public + */ + function getCallCount($method) { + $this->_dieOnNoMethod($method, "get call count"); + $method = strtolower($method); + if (! isset($this->_call_counts[$method])) { + return 0; + } + return $this->_call_counts[$method]; + } + + /** + * Sets a return for a parameter list that will + * be passed by value for all calls to this method. + * @param string $method Method name. + * @param mixed $value Result of call passed by value. + * @param array $args List of parameters to match + * including wildcards. + * @access public + */ + function setReturnValue($method, $value, $args = false) { + $this->_dieOnNoMethod($method, "set return value"); + $args = $this->_replaceWildcards($args); + $method = strtolower($method); + if (! isset($this->_returns[$method])) { + $this->_returns[$method] = new CallMap(); + } + $this->_returns[$method]->addValue($args, $value); + } + + /** + * Sets a return for a parameter list that will + * be passed by value only when the required call count + * is reached. + * @param integer $timing Number of calls in the future + * to which the result applies. If + * not set then all calls will return + * the value. + * @param string $method Method name. + * @param mixed $value Result of call passed by value. + * @param array $args List of parameters to match + * including wildcards. + * @access public + */ + function setReturnValueAt($timing, $method, $value, $args = false) { + $this->_dieOnNoMethod($method, "set return value sequence"); + $args = $this->_replaceWildcards($args); + $method = strtolower($method); + if (! isset($this->_return_sequence[$method])) { + $this->_return_sequence[$method] = array(); + } + if (! isset($this->_return_sequence[$method][$timing])) { + $this->_return_sequence[$method][$timing] = new CallMap(); + } + $this->_return_sequence[$method][$timing]->addValue($args, $value); + } + + /** + * Sets a return for a parameter list that will + * be passed by reference for all calls. + * @param string $method Method name. + * @param mixed $reference Result of the call will be this object. + * @param array $args List of parameters to match + * including wildcards. + * @access public + */ + function setReturnReference($method, &$reference, $args = false) { + $this->_dieOnNoMethod($method, "set return reference"); + $args = $this->_replaceWildcards($args); + $method = strtolower($method); + if (! isset($this->_returns[$method])) { + $this->_returns[$method] = new CallMap(); + } + $this->_returns[$method]->addReference($args, $reference); + } + + /** + * Sets a return for a parameter list that will + * be passed by value only when the required call count + * is reached. + * @param integer $timing Number of calls in the future + * to which the result applies. If + * not set then all calls will return + * the value. + * @param string $method Method name. + * @param mixed $reference Result of the call will be this object. + * @param array $args List of parameters to match + * including wildcards. + * @access public + */ + function setReturnReferenceAt($timing, $method, &$reference, $args = false) { + $this->_dieOnNoMethod($method, "set return reference sequence"); + $args = $this->_replaceWildcards($args); + $method = strtolower($method); + if (! isset($this->_return_sequence[$method])) { + $this->_return_sequence[$method] = array(); + } + if (! isset($this->_return_sequence[$method][$timing])) { + $this->_return_sequence[$method][$timing] = new CallMap(); + } + $this->_return_sequence[$method][$timing]->addReference($args, $reference); + } + + /** + * Sets up an expected call with a set of + * expected parameters in that call. All + * calls will be compared to these expectations + * regardless of when the call is made. + * @param string $method Method call to test. + * @param array $args Expected parameters for the call + * including wildcards. + * @param string $message Overridden message. + * @access public + */ + function expect($method, $args, $message = '%s') { + $this->_dieOnNoMethod($method, 'set expected arguments'); + $this->_checkArgumentsIsArray($args, 'set expected arguments'); + $args = $this->_replaceWildcards($args); + $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 + * expected call count will be adjusted if it + * is set too low to reach this call. + * @param integer $timing Number of calls in the future at + * which to test. Next call is 0. + * @param string $method Method call to test. + * @param array $args Expected parameters for the call + * including wildcards. + * @param string $message Overridden message. + * @access public + */ + function expectAt($timing, $method, $args, $message = '%s') { + $this->_dieOnNoMethod($method, 'set expected arguments at time'); + $this->_checkArgumentsIsArray($args, 'set expected arguments at time'); + $args = $this->_replaceWildcards($args); + if (! isset($this->_expected_args_at[$timing])) { + $this->_expected_args_at[$timing] = array(); + } + $method = strtolower($method); + $message .= Mock::getExpectationLine(); + $this->_expected_args_at[$timing][$method] = + new ParametersExpectation($args, $message); + } + + /** + * @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 + * is used to check this. + * @param string $method Method call to test. + * @param integer $count Number of times it should + * have been called at tally. + * @param string $message Overridden message. + * @access public + */ + function expectCallCount($method, $count, $message = '%s') { + $this->_dieOnNoMethod($method, 'set expected call count'); + $message .= Mock::getExpectationLine(); + $this->_expected_counts[strtolower($method)] = + new CallCountExpectation($method, $count, $message); + } + + /** + * Sets the number of times a method may be called + * before a test failure is triggered. + * @param string $method Method call to test. + * @param integer $count Most number of times it should + * have been called. + * @param string $message Overridden message. + * @access public + */ + function expectMaximumCallCount($method, $count, $message = '%s') { + $this->_dieOnNoMethod($method, 'set maximum call count'); + $message .= Mock::getExpectationLine(); + $this->_max_counts[strtolower($method)] = + new MaximumCallCountExpectation($method, $count, $message); + } + + /** + * Sets the number of times to call a method to prevent + * a failure on the tally. + * @param string $method Method call to test. + * @param integer $count Least number of times it should + * have been called. + * @param string $message Overridden message. + * @access public + */ + function expectMinimumCallCount($method, $count, $message = '%s') { + $this->_dieOnNoMethod($method, 'set minimum call count'); + $message .= Mock::getExpectationLine(); + $this->_expected_counts[strtolower($method)] = + new MinimumCallCountExpectation($method, $count, $message); + } + + /** + * Convenience method for barring a method + * call. + * @param string $method Method call to ban. + * @param string $message Overridden message. + * @access public + */ + function expectNever($method, $message = '%s') { + $this->expectMaximumCallCount($method, 0, $message); + } + + /** + * Convenience method for a single method + * call. + * @param string $method Method call to track. + * @param array $args Expected argument list or + * false for any arguments. + * @param string $message Overridden message. + * @access public + */ + function expectOnce($method, $args = false, $message = '%s') { + $this->expectCallCount($method, 1, $message); + if ($args !== false) { + $this->expectArguments($method, $args, $message); + } + } + + /** + * Convenience method for requiring a method + * call. + * @param string $method Method call to track. + * @param array $args Expected argument list or + * false for any arguments. + * @param string $message Overridden message. + * @access public + */ + function expectAtLeastOnce($method, $args = false, $message = '%s') { + $this->expectMinimumCallCount($method, 1, $message); + if ($args !== false) { + $this->expectArguments($method, $args, $message); + } + } + + /** + * @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 $test_method Current method name. + * @param SimpleTestCase $test Test to send message to. + * @access public + */ + function atTestEnd($test_method, &$test) { + foreach ($this->_expected_counts as $method => $expectation) { + $test->assert($expectation, $this->getCallCount($method)); + } + foreach ($this->_max_counts as $method => $expectation) { + if ($expectation->test($this->getCallCount($method))) { + $test->assert($expectation, $this->getCallCount($method)); + } + } + } + + /** + * Returns the expected value for the method name + * and checks expectations. Will generate any + * test assertions as a result of expectations + * if there is a test present. + * @param string $method Name of method to simulate. + * @param array $args Arguments as an array. + * @return mixed Stored return. + * @access private + */ + function &_invoke($method, $args) { + $method = strtolower($method); + $step = $this->getCallCount($method); + $this->_addCall($method, $args); + $this->_checkExpectations($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. + * @param array $args Argument list to match. + * @param integer $timing The position of this call + * in the call history. + * @access private + */ + function _checkExpectations($method, $args, $timing) { + $test = &$this->_getCurrentTestCase(); + if (isset($this->_max_counts[$method])) { + if (! $this->_max_counts[$method]->test($timing + 1)) { + $test->assert($this->_max_counts[$method], $timing + 1); + } + } + if (isset($this->_expected_args_at[$timing][$method])) { + $test->assert( + $this->_expected_args_at[$timing][$method], + $args, + "Mock method [$method] at [$timing] -> %s"); + } elseif (isset($this->_expected_args[$method])) { + $test->assert( + $this->_expected_args[$method], + $args, + "Mock method [$method] -> %s"); + } + } + } + + /** + * Static methods only service class for code generation of + * mock objects. + * @package SimpleTest + * @subpackage MockObjects + */ + class Mock { + + /** + * Factory for mock object classes. + * @access public + */ + function Mock() { + trigger_error('Mock factory methods are static.'); + } + + /** + * Clones a class' interface and creates a mock version + * that can have return values and expectations set. + * @param string $class Class to clone. + * @param string $mock_class New class name. Default is + * the old name with "Mock" + * prepended. + * @param array $methods Additional methods to add beyond + * those in the cloned class. Use this + * to emulate the dynamic addition of + * methods in the cloned class or when + * the class hasn't been written yet. + * @static + * @access public + */ + function generate($class, $mock_class = false, $methods = false) { + $generator = new MockGenerator($class, $mock_class); + return $generator->generate($methods); + } + + /** + * Temporary method while refactoring. + */ + function generateSubclass($class, $mock_class = false, $methods = array()) { + $generator = new MockGenerator($class, $mock_class); + return $generator->generateSubclass($methods); + } + + /** + * Generates a version of a class with selected + * methods mocked only. Inherits the old class + * and chains the mock methods of an aggregated + * mock object. + * @param string $class Class to clone. + * @param string $mock_class New class name. + * @param array $methods Methods to be overridden + * with mock versions. + * @static + * @access public + */ + function generatePartial($class, $mock_class, $methods) { + $generator = new MockGenerator($class, $mock_class); + return $generator->generatePartial($methods); + } + + /** + * Uses a stack trace to find the line of an assertion. + * @access public + * @static + */ + function getExpectationLine() { + $trace = new SimpleStackTrace(array('expect')); + return $trace->traceMethod(); + } + } + + /** + * @package SimpleTest + * @subpackage MockObjects + * @deprecated + */ + class Stub extends Mock { + } + + /** + * Service class for code generation of mock objects. + * @package SimpleTest + * @subpackage MockObjects + */ + class MockGenerator { + var $_class; + var $_mock_class; + var $_mock_base; + var $_reflection; + + function MockGenerator($class, $mock_class) { + $this->_class = $class; + $this->_mock_class = $mock_class; + if (! $this->_mock_class) { + $this->_mock_class = 'Mock' . $this->_class; + } + $this->_mock_base = SimpleTest::getMockBaseClass(); + $this->_reflection = new SimpleReflection($this->_class); + } + + /** + * Clones a class' interface and creates a mock version + * that can have return values and expectations set. + * @param array $methods Additional methods to add beyond + * those in th cloned class. Use this + * to emulate the dynamic addition of + * methods in the cloned class or when + * the class hasn't been written yet. + * @access public + */ + function generate($methods) { + if (! $this->_reflection->classOrInterfaceExists()) { + return false; + } + $mock_reflection = new SimpleReflection($this->_mock_class); + if ($mock_reflection->classExistsSansAutoload()) { + return false; + } + return eval( + $this->_createClassCode($methods ? $methods : array()) . + " return true;"); + } + + /** + * Subclasses a class and overrides every method with a mock one. + * that can have return values and expectations set. + * @param array $methods Additional methods to add beyond + * those in th cloned class. Use this + * to emulate the dynamic addition of + * methods in the cloned class or when + * the class hasn't been written yet. + * @access public + */ + function generateSubclass($methods) { + if (! $this->_reflection->classOrInterfaceExists()) { + return false; + } + $mock_reflection = new SimpleReflection($this->_mock_class); + if ($mock_reflection->classExistsSansAutoload()) { + return false; + } + if ($this->_reflection->isInterface()) { + return eval( + $this->_createClassCode($methods ? $methods : array()) . + " return true;"); + } else { + return eval( + $this->_createSubclassCode($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 array $methods Methods to be overridden + * with mock versions. + * @access public + */ + function generatePartial($methods) { + if (! $this->_reflection->classExists($this->_class)) { + return false; + } + $mock_reflection = new SimpleReflection($this->_mock_class); + if ($mock_reflection->classExistsSansAutoload()) { + trigger_error('Partial mock class [' . $this->_mock_class . '] already exists'); + return false; + } + return eval($this->_extendClassCode($methods)); + } + + /** + * The new mock class code as a string. + * @param array $methods Additional methods. + * @return string Code for new mock class. + * @access private + */ + function _createClassCode($methods) { + $implements = ''; + $interfaces = $this->_reflection->getInterfaces(); + if (function_exists('spl_classes')) { + $interfaces = array_diff($interfaces, array('Traversable')); + } + if (count($interfaces) > 0) { + $implements = 'implements ' . implode(', ', $interfaces); + } + $code = "class " . $this->_mock_class . " extends " . $this->_mock_base . " $implements {\n"; + $code .= " function " . $this->_mock_class . "() {\n"; + $code .= " \$this->" . $this->_mock_base . "();\n"; + $code .= " }\n"; + if (in_array('__construct', $this->_reflection->getMethods())) { + $code .= " " . $this->_reflection->getSignature('__construct') . " {\n"; + $code .= " \$this->" . $this->_mock_base . "();\n"; + $code .= " }\n"; + } + $code .= $this->_createHandlerCode($methods); + $code .= "}\n"; + return $code; + } + + /** + * The new mock class code as a string. The mock will + * be a subclass of the original mocked class. + * @param array $methods Additional methods. + * @return string Code for new mock class. + * @access private + */ + function _createSubclassCode($methods) { + $code = "class " . $this->_mock_class . " extends " . $this->_class . " {\n"; + $code .= " var \$_mock;\n"; + $code .= $this->_addMethodList(array_merge($methods, $this->_reflection->getMethods())); + $code .= "\n"; + $code .= " function " . $this->_mock_class . "() {\n"; + $code .= " \$this->_mock = &new " . $this->_mock_base . "();\n"; + $code .= " \$this->_mock->disableExpectationNameChecks();\n"; + $code .= " }\n"; + $code .= $this->_chainMockReturns(); + $code .= $this->_chainMockExpectations(); + $code .= $this->_overrideMethods($this->_reflection->getMethods()); + $code .= $this->_createNewMethodCode($methods); + $code .= "}\n"; + return $code; + } + + /** + * The extension class code as a string. The class + * composites a mock object and chains mocked methods + * to it. + * @param array $methods Mocked methods. + * @return string Code for a new class. + * @access private + */ + function _extendClassCode($methods) { + $code = "class " . $this->_mock_class . " extends " . $this->_class . " {\n"; + $code .= " var \$_mock;\n"; + $code .= $this->_addMethodList($methods); + $code .= "\n"; + $code .= " function " . $this->_mock_class . "() {\n"; + $code .= " \$this->_mock = &new " . $this->_mock_base . "();\n"; + $code .= " \$this->_mock->disableExpectationNameChecks();\n"; + $code .= " }\n"; + $code .= $this->_chainMockReturns(); + $code .= $this->_chainMockExpectations(); + $code .= $this->_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; + } + + /** + * Creates code within a class to generate a new + * methods. All methods call the _invoke() handler + * on the internal mock with the method name and + * the arguments in an array. + * @param array $methods Additional methods. + * @access private + */ + function _createNewMethodCode($methods) { + $code = ''; + foreach ($methods as $method) { + if ($this->_isConstructor($method)) { + continue; + } + $mock_reflection = new SimpleReflection($this->_mock_base); + if (in_array($method, $mock_reflection->getMethods())) { + continue; + } + $code .= " " . $this->_reflection->getSignature($method) . " {\n"; + $code .= " \$args = func_get_args();\n"; + $code .= " \$result = &\$this->_mock->_invoke(\"$method\", \$args);\n"; + $code .= " return \$result;\n"; + $code .= " }\n"; + } + return $code; + } + + /** + * Tests to see if a special PHP method is about to + * be stubbed by mistake. + * @param string $method Method name. + * @return boolean True if special. + * @access private + */ + function _isConstructor($method) { + return in_array( + strtolower($method), + array('__construct', '__destruct')); + } + + /** + * Creates a list of mocked methods for error checking. + * @param array $methods Mocked methods. + * @return string Code for a method list. + * @access private + */ + function _addMethodList($methods) { + return " var \$_mocked_methods = array('" . implode("', '", $methods) . "');\n"; + } + + /** + * Creates code to abandon the expectation if not mocked. + * @param string $alias Parameter name of method name. + * @return string Code for bail out. + * @access private + */ + function _bailOutIfNotMocked($alias) { + $code = " if (! in_array($alias, \$this->_mocked_methods)) {\n"; + $code .= " trigger_error(\"Method [$alias] is not mocked\");\n"; + $code .= " \$null = null;\n"; + $code .= " return \$null;\n"; + $code .= " }\n"; + return $code; + } + + /** + * Creates source code for chaining to the composited + * mock object. + * @return string Code for mock set up. + * @access private + */ + function _chainMockReturns() { + $code = " function setReturnValue(\$method, \$value, \$args = false) {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->setReturnValue(\$method, \$value, \$args);\n"; + $code .= " }\n"; + $code .= " function setReturnValueAt(\$timing, \$method, \$value, \$args = false) {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n"; + $code .= " }\n"; + $code .= " function setReturnReference(\$method, &\$ref, \$args = false) {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->setReturnReference(\$method, \$ref, \$args);\n"; + $code .= " }\n"; + $code .= " function setReturnReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->setReturnReferenceAt(\$timing, \$method, \$ref, \$args);\n"; + $code .= " }\n"; + return $code; + } + + /** + * Creates source code for chaining to an aggregated + * mock object. + * @return string Code for expectations. + * @access private + */ + function _chainMockExpectations() { + $code = " function expect(\$method, \$args = false, \$msg = '%s') {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expect(\$method, \$args, \$msg);\n"; + $code .= " }\n"; + $code .= " function expectArguments(\$method, \$args = false, \$msg = '%s') {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectArguments(\$method, \$args, \$msg);\n"; + $code .= " }\n"; + $code .= " function expectAt(\$timing, \$method, \$args = false, \$msg = '%s') {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args, \$msg);\n"; + $code .= " }\n"; + $code .= " function expectArgumentsAt(\$timing, \$method, \$args = false, \$msg = '%s') {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args, \$msg);\n"; + $code .= " }\n"; + $code .= " function expectCallCount(\$method, \$count) {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectCallCount(\$method, \$count, \$msg = '%s');\n"; + $code .= " }\n"; + $code .= " function expectMaximumCallCount(\$method, \$count, \$msg = '%s') {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectMaximumCallCount(\$method, \$count, \$msg = '%s');\n"; + $code .= " }\n"; + $code .= " function expectMinimumCallCount(\$method, \$count, \$msg = '%s') {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectMinimumCallCount(\$method, \$count, \$msg = '%s');\n"; + $code .= " }\n"; + $code .= " function expectNever(\$method) {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectNever(\$method);\n"; + $code .= " }\n"; + $code .= " function expectOnce(\$method, \$args = false, \$msg = '%s') {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectOnce(\$method, \$args, \$msg);\n"; + $code .= " }\n"; + $code .= " function expectAtLeastOnce(\$method, \$args = false, \$msg = '%s') {\n"; + $code .= $this->_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectAtLeastOnce(\$method, \$args, \$msg);\n"; + $code .= " }\n"; + $code .= " function tally() {\n"; + $code .= " \$this->_mock->tally();\n"; + $code .= " }\n"; + return $code; + } + + /** + * Creates source code to override a list of methods + * with mock versions. + * @param array $methods Methods to be overridden + * with mock versions. + * @return string Code for overridden chains. + * @access private + */ + function _overrideMethods($methods) { + $code = ""; + foreach ($methods as $method) { + if ($this->_isConstructor($method)) { + continue; + } + $code .= " " . $this->_reflection->getSignature($method) . " {\n"; + $code .= " \$args = func_get_args();\n"; + $code .= " \$result = &\$this->_mock->_invoke(\"$method\", \$args);\n"; + $code .= " return \$result;\n"; + $code .= " }\n"; + } + return $code; + } + } +?> diff --git a/tests/simpletest/packages/README b/tests/simpletest/packages/README new file mode 100644 index 00000000..3cf668ee --- /dev/null +++ b/tests/simpletest/packages/README @@ -0,0 +1,26 @@ +HOW TO MAKE A PACKAGE + +1. First make sure PEAR_PackageFileManager is installed; +(version 1.2.0 was used) + +$ pear install PEAR_PackageFileManager + +2. Edit the simpletest/packages/pear_package_create.php file (see comments for what +needs changing). + +3. Run the simpletest/packages/pear_package_create.php script, piping the output +to the file you want to create e.g.; + +$ ./pear_package_create.php > package.xml + +4. Copy the package.xml to the root of Simpletest. + +5. From the root of Simpletest type; + +$ pear package package.xml + +This creates the package zip + +6. Install with; + +$ pear install SimpleTest-x.x.x.tgz \ No newline at end of file diff --git a/tests/simpletest/packages/build_tarball.sh b/tests/simpletest/packages/build_tarball.sh new file mode 100755 index 00000000..513e4485 --- /dev/null +++ b/tests/simpletest/packages/build_tarball.sh @@ -0,0 +1,122 @@ +#!/bin/sh + +# Builds project release. +# +cd ../.. + +NAME=simpletest_`cat simpletest/VERSION`.tar.gz +FILES=(simpletest/compatibility.php \ + simpletest/collector.php \ + simpletest/dumper.php \ + simpletest/errors.php \ + simpletest/exceptions.php \ + simpletest/expectation.php \ + simpletest/socket.php \ + simpletest/encoding.php \ + simpletest/url.php \ + simpletest/cookies.php \ + simpletest/http.php \ + simpletest/authentication.php \ + simpletest/user_agent.php \ + simpletest/browser.php \ + simpletest/parser.php \ + simpletest/tag.php \ + simpletest/selector.php \ + simpletest/form.php \ + simpletest/frames.php \ + simpletest/page.php \ + simpletest/reflection_php4.php \ + simpletest/reflection_php5.php \ + simpletest/invoker.php \ + simpletest/scorer.php \ + simpletest/reporter.php \ + simpletest/mock_objects.php \ + simpletest/simpletest.php \ + simpletest/test_case.php \ + simpletest/unit_tester.php \ + simpletest/web_tester.php \ + simpletest/shell_tester.php \ + simpletest/xml.php \ + simpletest/detached.php \ + simpletest/remote.php \ + simpletest/extensions/pear_test_case.php \ + simpletest/extensions/phpunit_test_case.php \ + simpletest/README \ + simpletest/VERSION \ + simpletest/LICENSE \ + simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE \ + simpletest/test/all_tests.php \ + simpletest/test/unit_tests.php \ + simpletest/test/test_groups.php \ + simpletest/test/acceptance_test.php \ + simpletest/test/collector_test.php \ + simpletest/test/simpletest_test.php \ + simpletest/test/errors_test.php \ + simpletest/test/exceptions_test.php \ + simpletest/test/compatibility_test.php \ + simpletest/test/dumper_test.php \ + simpletest/test/expectation_test.php \ + simpletest/test/adapter_test.php \ + simpletest/test/socket_test.php \ + simpletest/test/url_test.php \ + simpletest/test/cookies_test.php \ + simpletest/test/encoding_test.php \ + simpletest/test/http_test.php \ + simpletest/test/authentication_test.php \ + simpletest/test/user_agent_test.php \ + simpletest/test/browser_test.php \ + simpletest/test/parser_test.php \ + simpletest/test/tag_test.php \ + simpletest/test/form_test.php \ + simpletest/test/frames_test.php \ + simpletest/test/page_test.php \ + simpletest/test/reflection_php4_test.php \ + simpletest/test/reflection_php5_test.php \ + simpletest/test/mock_objects_test.php \ + simpletest/test/interfaces_test.php \ + simpletest/test/visual_test.php \ + simpletest/test/shell_test.php \ + simpletest/test/web_tester_test.php \ + simpletest/test/unit_tester_test.php \ + simpletest/test/shell_tester_test.php \ + simpletest/test/xml_test.php \ + simpletest/test/live_test.php \ + simpletest/test/parse_error_test.php \ + simpletest/test/detached_test.php \ + simpletest/test/remote_test.php \ + simpletest/test/test_with_parse_error.php \ + simpletest/test/support/collector/collectable.1 \ + simpletest/test/support/collector/collectable.2 \ + simpletest/test/support/upload_sample.txt \ + simpletest/test/support/supplementary_upload_sample.txt \ + simpletest/test/support/latin1_sample \ + simpletest/test/support/spl_examples.php \ + simpletest/docs/en/docs.css \ + simpletest/docs/en/index.html \ + simpletest/docs/en/overview.html \ + simpletest/docs/en/unit_test_documentation.html \ + simpletest/docs/en/group_test_documentation.html \ + simpletest/docs/en/mock_objects_documentation.html \ + simpletest/docs/en/partial_mocks_documentation.html \ + simpletest/docs/en/reporter_documentation.html \ + simpletest/docs/en/expectation_documentation.html \ + simpletest/docs/en/web_tester_documentation.html \ + simpletest/docs/en/form_testing_documentation.html \ + simpletest/docs/en/authentication_documentation.html \ + simpletest/docs/en/browser_documentation.html \ + simpletest/docs/fr/docs.css \ + simpletest/docs/fr/index.html \ + simpletest/docs/fr/overview.html \ + simpletest/docs/fr/unit_test_documentation.html \ + simpletest/docs/fr/group_test_documentation.html \ + simpletest/docs/fr/server_stubs_documentation.html \ + simpletest/docs/fr/mock_objects_documentation.html \ + simpletest/docs/fr/partial_mocks_documentation.html \ + simpletest/docs/fr/reporter_documentation.html \ + simpletest/docs/fr/expectation_documentation.html \ + simpletest/docs/fr/web_tester_documentation.html \ + simpletest/docs/fr/form_testing_documentation.html \ + simpletest/docs/fr/authentication_documentation.html \ + simpletest/docs/fr/browser_documentation.html) + +tar -zcf $NAME ${FILES[*]} diff --git a/tests/simpletest/packages/bundled_docs.xslt b/tests/simpletest/packages/bundled_docs.xslt new file mode 100644 index 00000000..2a445497 --- /dev/null +++ b/tests/simpletest/packages/bundled_docs.xslt @@ -0,0 +1,246 @@ + + + + + + + + + + + + + + + + + <xsl:value-of select="//long_title"/> + + + + + + + + + +
+ +
+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + | + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
( pages) +
+
+
+ + +

+
+ + + This page... +
    + +
+
+ + + References and related information... +
    + +
+
+ + + + + + +
+            
+                
+            
+        
+
+ + + + + + + + +
+            
+                
+            
+        
+
+ + +
+            
+                
+            
+        
+
+ + +
+            
+        
+
+ + +

+ + +

+ +

+ +
+ + + + + + + + + + + + + + + + .html + + + + + + + + + + + + + + + + +
  • +
    + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/tests/simpletest/packages/bundled_map.xml b/tests/simpletest/packages/bundled_map.xml new file mode 100644 index 00000000..b5b950fa --- /dev/null +++ b/tests/simpletest/packages/bundled_map.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/tests/simpletest/packages/generate_package.php b/tests/simpletest/packages/generate_package.php new file mode 100644 index 00000000..2f339e1a --- /dev/null +++ b/tests/simpletest/packages/generate_package.php @@ -0,0 +1,136 @@ +setOptions(array( + 'baseinstalldir' => 'simpletest', + 'version' => '1.0.0', + 'license' => 'The Open Group Test Suite License', + 'packagedirectory' => '/var/www/html/tmp/simpletest', + 'state' => 'stable', + 'package' => 'simpletest', + 'simpleoutput' => true, + 'summary' => $shortDesc, + 'description' => $longDesc, + 'filelistgenerator' => 'file', // generate from cvs, use file for directory + 'notes' => 'See the CHANGELOG for full list of changes', + 'dir_roles' => array( + 'extensions' => 'php', + 'test' => 'test', + ), + 'ignore' => array( + 'packages/', + 'tutorials/', + 'ui/', + 'docs/', + '*CVS*', + 'TODO', + ), + 'roles' => array( + 'php' => 'php', + 'html' => 'php', + '*' => 'php', + ), + 'exceptions' => array( + 'VERSION' => 'doc', + 'HELP_MY_TESTS_DONT_WORK_ANYMORE' => 'doc', + 'LICENSE' => 'doc', + 'README' => 'doc', + ), + ) +); +if (is_a($e, 'PEAR_Error')) { + echo $e->getMessage(); + die(); +} + +$e = $packagexml->addMaintainer('lastcraft', 'lead', 'Marcus Baker', 'marcus@lastcraft.com'); +if (is_a($e, 'PEAR_Error')) { + echo $e->getMessage(); + exit; +} + +$e = $packagexml->addMaintainer('tswicegood', 'developer', 'Travis Swicegood', 'tswicegood@users.sourceforge.net'); +if (is_a($e, 'PEAR_Error')) { + echo $e->getMessage(); + exit; +} + +$e = $packagexml->addMaintainer('jsweat', 'helper', 'Jason Sweat', 'jsweat_php@yahoo.com'); +if (is_a($e, 'PEAR_Error')) { + echo $e->getMessage(); + exit; +} + +$e = $packagexml->addMaintainer('pp11', 'helper', 'Perrick Penet', 'perrick@noparking.net'); +if (is_a($e, 'PEAR_Error')) { + echo $e->getMessage(); + exit; +} + +$e = $packagexml->addMaintainer('shpikat', 'helper', 'Constantine Shpikat', 'shpikat@users.sourceforge.net'); +if (is_a($e, 'PEAR_Error')) { + echo $e->getMessage(); + exit; +} + +$e = $packagexml->addMaintainer('demianturner', 'helper', 'Demian Turner', 'demian@phpkitchen.com'); +if (is_a($e, 'PEAR_Error')) { + echo $e->getMessage(); + exit; +} + +// note use of {@link debugPackageFile()} - this is VERY important +if (isset($_GET['make']) || (isset($_SERVER['argv'][2]) && + $_SERVER['argv'][2] == 'make')) { + $e = $packagexml->writePackageFile(); +} else { + $e = $packagexml->debugPackageFile(); +} +if (is_a($e, 'PEAR_Error')) { + echo $e->getMessage(); + die(); +} +?> \ No newline at end of file diff --git a/tests/simpletest/packages/lastcraft.xslt b/tests/simpletest/packages/lastcraft.xslt new file mode 100644 index 00000000..d57d50af --- /dev/null +++ b/tests/simpletest/packages/lastcraft.xslt @@ -0,0 +1,302 @@ + + + + + + + + + + + + + + + + + <xsl:value-of select="//long_title"/> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + + +
    + + LastCraft Home Page + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + +
    • + + + + +
    • +
      +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    ( pages) +
    +
    +
    + + +
    +
    +

    +
    + +
    +
    + +
    +
    +
    +
    + + + This page... +
      + +
    +
    + + + Related... +
      + +
    +
    + + + + + + +
    +            
    +                
    +            
    +        
    +
    + + + + + + + + +
    +            
    +                
    +            
    +        
    +
    + + +
    +            
    +        
    +
    + + +

    + + +

    + +

    + +
    + + + + + + +

    + News: + +

    +
    + + + + + + + + + .php + + + + + + + + + + + + + + + + +
  • +
    + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/tests/simpletest/packages/make_bundled_docs.sh b/tests/simpletest/packages/make_bundled_docs.sh new file mode 100755 index 00000000..514c82dc --- /dev/null +++ b/tests/simpletest/packages/make_bundled_docs.sh @@ -0,0 +1,26 @@ +#!/bin/sh +xsltproc bundled_docs.xslt ../docs/source/en/simple_test.xml > ../docs/en/index.html +xsltproc bundled_docs.xslt ../docs/source/en/overview.xml > ../docs/en/overview.html +xsltproc bundled_docs.xslt ../docs/source/en/unit_test_documentation.xml > ../docs/en/unit_test_documentation.html +xsltproc bundled_docs.xslt ../docs/source/en/group_test_documentation.xml > ../docs/en/group_test_documentation.html +xsltproc bundled_docs.xslt ../docs/source/en/mock_objects_documentation.xml > ../docs/en/mock_objects_documentation.html +xsltproc bundled_docs.xslt ../docs/source/en/partial_mocks_documentation.xml > ../docs/en/partial_mocks_documentation.html +xsltproc bundled_docs.xslt ../docs/source/en/reporter_documentation.xml > ../docs/en/reporter_documentation.html +xsltproc bundled_docs.xslt ../docs/source/en/expectation_documentation.xml > ../docs/en/expectation_documentation.html +xsltproc bundled_docs.xslt ../docs/source/en/web_tester_documentation.xml > ../docs/en/web_tester_documentation.html +xsltproc bundled_docs.xslt ../docs/source/en/form_testing_documentation.xml > ../docs/en/form_testing_documentation.html +xsltproc bundled_docs.xslt ../docs/source/en/authentication_documentation.xml > ../docs/en/authentication_documentation.html +xsltproc bundled_docs.xslt ../docs/source/en/browser_documentation.xml > ../docs/en/browser_documentation.html +xsltproc bundled_docs.xslt ../docs/source/fr/simple_test.xml > ../docs/fr/index.html +xsltproc bundled_docs.xslt ../docs/source/fr/overview.xml > ../docs/fr/overview.html +xsltproc bundled_docs.xslt ../docs/source/fr/unit_test_documentation.xml > ../docs/fr/unit_test_documentation.html +xsltproc bundled_docs.xslt ../docs/source/fr/group_test_documentation.xml > ../docs/fr/group_test_documentation.html +xsltproc bundled_docs.xslt ../docs/source/fr/server_stubs_documentation.xml > ../docs/fr/server_stubs_documentation.html +xsltproc bundled_docs.xslt ../docs/source/fr/mock_objects_documentation.xml > ../docs/fr/mock_objects_documentation.html +xsltproc bundled_docs.xslt ../docs/source/fr/partial_mocks_documentation.xml > ../docs/fr/partial_mocks_documentation.html +xsltproc bundled_docs.xslt ../docs/source/fr/reporter_documentation.xml > ../docs/fr/reporter_documentation.html +xsltproc bundled_docs.xslt ../docs/source/fr/expectation_documentation.xml > ../docs/fr/expectation_documentation.html +xsltproc bundled_docs.xslt ../docs/source/fr/web_tester_documentation.xml > ../docs/fr/web_tester_documentation.html +xsltproc bundled_docs.xslt ../docs/source/fr/form_testing_documentation.xml > ../docs/fr/form_testing_documentation.html +xsltproc bundled_docs.xslt ../docs/source/fr/authentication_documentation.xml > ../docs/fr/authentication_documentation.html +xsltproc bundled_docs.xslt ../docs/source/fr/browser_documentation.xml > ../docs/fr/browser_documentation.html diff --git a/tests/simpletest/packages/make_bundled_docs_with_xalan.sh b/tests/simpletest/packages/make_bundled_docs_with_xalan.sh new file mode 100755 index 00000000..cfc6de35 --- /dev/null +++ b/tests/simpletest/packages/make_bundled_docs_with_xalan.sh @@ -0,0 +1,26 @@ +#!/bin/sh +Xalan -o ../docs/en/index.html ../docs/source/en/simple_test.xml bundled_docs.xslt +Xalan -o ../docs/en/overview.html ../docs/source/en/overview.xml bundled_docs.xslt +Xalan -o ../docs/en/unit_test_documentation.html ../docs/source/en/unit_test_documentation.xml bundled_docs.xslt +Xalan -o ../docs/en/group_test_documentation.html ../docs/source/en/group_test_documentation.xml bundled_docs.xslt +Xalan -o ../docs/en/mock_objects_documentation.html ../docs/source/en/mock_objects_documentation.xml bundled_docs.xslt +Xalan -o ../docs/en/partial_mocks_documentation.html ../docs/source/en/partial_mocks_documentation.xml bundled_docs.xslt +Xalan -o ../docs/en/reporter_documentation.html ../docs/source/en/reporter_documentation.xml bundled_docs.xslt +Xalan -o ../docs/en/expectation_documentation.html ../docs/source/en/expectation_documentation.xml bundled_docs.xslt +Xalan -o ../docs/en/web_tester_documentation.html ../docs/source/en/web_tester_documentation.xml bundled_docs.xslt +Xalan -o ../docs/en/form_testing_documentation.html ../docs/source/en/form_testing_documentation.xml bundled_docs.xslt +Xalan -o ../docs/en/authentication_documentation.html ../docs/source/en/authentication_documentation.xml bundled_docs.xslt +Xalan -o ../docs/en/browser_documentation.html ../docs/source/en/browser_documentation.xml bundled_docs.xslt +Xalan -o ../docs/fr/index.html ../docs/source/fr/simple_test.xml bundled_docs.xslt +Xalan -o ../docs/fr/overview.html ../docs/source/fr/overview.xml bundled_docs.xslt +Xalan -o ../docs/fr/unit_test_documentation.html ../docs/source/fr/unit_test_documentation.xml bundled_docs.xslt +Xalan -o ../docs/fr/group_test_documentation.html ../docs/source/fr/group_test_documentation.xml bundled_docs.xslt +Xalan -o ../docs/fr/server_stubs_documentation.html ../docs/source/fr/server_stubs_documentation.xml bundled_docs.xslt +Xalan -o ../docs/fr/mock_objects_documentation.html ../docs/source/fr/mock_objects_documentation.xml bundled_docs.xslt +Xalan -o ../docs/fr/partial_mocks_documentation.html ../docs/source/fr/partial_mocks_documentation.xml bundled_docs.xslt +Xalan -o ../docs/fr/reporter_documentation.html ../docs/source/fr/reporter_documentation.xml bundled_docs.xslt +Xalan -o ../docs/fr/expectation_documentation.html ../docs/source/fr/expectation_documentation.xml bundled_docs.xslt +Xalan -o ../docs/fr/web_tester_documentation.html ../docs/source/fr/web_tester_documentation.xml bundled_docs.xslt +Xalan -o ../docs/fr/form_testing_documentation.html ../docs/source/fr/form_testing_documentation.xml bundled_docs.xslt +Xalan -o ../docs/fr/authentication_documentation.html ../docs/source/fr/authentication_documentation.xml bundled_docs.xslt +Xalan -o ../docs/fr/browser_documentation.html ../docs/source/fr/browser_documentation.xml bundled_docs.xslt diff --git a/tests/simpletest/packages/make_lastcraft_docs.sh b/tests/simpletest/packages/make_lastcraft_docs.sh new file mode 100755 index 00000000..0eaf7421 --- /dev/null +++ b/tests/simpletest/packages/make_lastcraft_docs.sh @@ -0,0 +1,2 @@ +#!/bin/bash +php transform_all_lastcraft.php lastcraft.xslt ../docs/source/en/ ../docs/lastcraft/ diff --git a/tests/simpletest/packages/make_phpdoc_docs.sh b/tests/simpletest/packages/make_phpdoc_docs.sh new file mode 100755 index 00000000..fd56f334 --- /dev/null +++ b/tests/simpletest/packages/make_phpdoc_docs.sh @@ -0,0 +1,42 @@ +#!/bin/bash + +#DEST_DIR=../docs/pkg +if [ ! -d ../tutorials ] +then + mkdir ../tutorials +fi +if [ ! -d ../tutorials/SimpleTest ] +then + mkdir ../tutorials/SimpleTest +fi +DEST_DIR=../tutorials/SimpleTest + +rm ${DEST_DIR}/*.pkg +cp ../docs/pkg/SimpleTest.pkg.ini ${DEST_DIR} + +#Xalan -o ${DEST_DIR}/QuickStart.pkg ../docs/source/en/simple_test.xml phpdoc_docs.xslt +Xalan -o ${DEST_DIR}/SimpleTest.pkg ../docs/source/en/overview.xml phpdoc_docs.xslt +Xalan -o ${DEST_DIR}/UnitTestCase.pkg ../docs/source/en/unit_test_documentation.xml phpdoc_docs.xslt +Xalan -o ${DEST_DIR}/GroupTests.pkg ../docs/source/en/group_test_documentation.xml phpdoc_docs.xslt +Xalan -o ${DEST_DIR}/MockObjects.pkg ../docs/source/en/mock_objects_documentation.xml phpdoc_docs.xslt +Xalan -o ${DEST_DIR}/PartialMock.pkg ../docs/source/en/partial_mocks_documentation.xml phpdoc_docs.xslt +Xalan -o ${DEST_DIR}/Reporting.pkg ../docs/source/en/reporter_documentation.xml phpdoc_docs.xslt +Xalan -o ${DEST_DIR}/Expectations.pkg ../docs/source/en/expectation_documentation.xml phpdoc_docs.xslt +Xalan -o ${DEST_DIR}/WebTester.pkg ../docs/source/en/web_tester_documentation.xml phpdoc_docs.xslt +Xalan -o ${DEST_DIR}/FormTesting.pkg ../docs/source/en/form_testing_documentation.xml phpdoc_docs.xslt +Xalan -o ${DEST_DIR}/Authentication.pkg ../docs/source/en/authentication_documentation.xml phpdoc_docs.xslt +Xalan -o ${DEST_DIR}/Browser.pkg ../docs/source/en/browser_documentation.xml phpdoc_docs.xslt + +# some cleanup work +cd $DEST_DIR + +# remove XML declaration +for f in $(ls *.pkg --color=none) +do + grep -v -e '^ tmp.pkg + mv tmp.pkg $f +done + +# fix overview title +cat SimpleTest.pkg | sed -e 's/Overview/Simple Test PHP Unit Test Framework/g;s/<\([A-Za-z0-9]*\)\/>/<\1><\/\1>/g' > tmp.pkg +mv tmp.pkg SimpleTest.pkg diff --git a/tests/simpletest/packages/onpk/map_onpk.xml b/tests/simpletest/packages/onpk/map_onpk.xml new file mode 100644 index 00000000..b4f6b41c --- /dev/null +++ b/tests/simpletest/packages/onpk/map_onpk.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/simpletest/packages/onpk/onpk.xslt b/tests/simpletest/packages/onpk/onpk.xslt new file mode 100644 index 00000000..20530669 --- /dev/null +++ b/tests/simpletest/packages/onpk/onpk.xslt @@ -0,0 +1,227 @@ + + + + + + + + + + + + + + + + + + + <xsl:value-of select="//long_title"/> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + + + +
    + + + + + + + + + + + + + + + + + + + + + +
      + +
    • + + + +
    • +
      +
    +
    +
    + + + + + + + + + + + + +
    + +

    +
    + +
    +
    +
    + + + Cette page... +
      + +
    +
    + + + Pour aller plus loin... +
      + +
    +
    + + +
    + +
    +
    + + + + + + + + + + + + + + +
    +			
    +				
    +			
    +		
    +
    + + + + + + + + +

    + + +

    + +

    + +
    + + + + + + + + + + + + + .php + + + + + + + + + + + + + + + + +
  • +
    + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/tests/simpletest/packages/onpk/transform_all_onpk.php b/tests/simpletest/packages/onpk/transform_all_onpk.php new file mode 100644 index 00000000..c80350a6 --- /dev/null +++ b/tests/simpletest/packages/onpk/transform_all_onpk.php @@ -0,0 +1,32 @@ +"; + } else { + echo "erreur pour ".$destination." : ".xslt_error($xh)."
    "; + } + + xslt_free($xsltProcessor); +} +closedir($dir); +?> \ No newline at end of file diff --git a/tests/simpletest/packages/package.xml b/tests/simpletest/packages/package.xml new file mode 100644 index 00000000..470f0d44 --- /dev/null +++ b/tests/simpletest/packages/package.xml @@ -0,0 +1,710 @@ + + + + SimpleTest + Unit testing, mock objects and web testing framework for PHP. + The heart of SimpleTest is a testing framework built around test case classes. +These are written as extensions of base test case classes, each extended with +methods that actually contain test code. Top level test scripts then invoke +the run() methods on every one of these test cases in order. Each test +method is written to invoke various assertions that the developer expects to +be true such as assertEqual(). If the expectation is correct, then a +successful result is dispatched to the observing test reporter, but any +failure triggers an alert and a description of the mismatch. + +These tools are designed for the developer. Tests are written in the PHP +language itself more or less as the application itself is built. The advantage +of using PHP itself as the testing language is that there are no new languages +to learn, testing can start straight away, and the developer can test any part +of the code. Basically, all parts that can be accessed by the application code +can also be accessed by the test code if they are in the same language. + + + lastcraft + Marcus Baker + marcus@lastcraft.com + lead + + + jsweat + Jason Sweat + jsweat_php@yahoo.com + helper + + + hfuecks + Harry Fuecks + hfuecks@phppatterns.com + helper + + + + 0.9.4 + 2004-02-20 + The Open Group Test Suite License + beta + This is the final version of the PHP unit and web testing tool before the +stable release 1.0 version. It features many improvements to the HTML form +parsing and exposure of the underlying web browser. There are also numerous +minor improvements and bug fixes. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0.9.4 + 2004-02-20 + The Open Group Test Suite License + beta + This is the final version of the PHP unit and web testing tool before the +stable release 1.0 version. It features many improvements to the HTML form +parsing and exposure of the underlying web browser. There are also numerous +minor improvements and bug fixes. + + + diff --git a/tests/simpletest/packages/pear_package_create.php b/tests/simpletest/packages/pear_package_create.php new file mode 100755 index 00000000..f88787dd --- /dev/null +++ b/tests/simpletest/packages/pear_package_create.php @@ -0,0 +1,170 @@ +#!/usr/local/bin/php -q +'lastcraft','role'=>'lead','name'=>'Marcus Baker', 'email'=>'marcus@lastcraft.com'), + array ('handle'=>'jsweat','role'=>'helper','name'=>'Jason Sweat', 'email'=>'jsweat_php@yahoo.com'), + array ('handle'=>'hfuecks','role'=>'helper','name'=>'Harry Fuecks', 'email'=>'hfuecks@phppatterns.com'), +); +/*---------------------------------------------------------------------------*/ + +/** +* Code starts here +*/ +require_once('PEAR/PackageFileManager.php'); +$PPFM = new PEAR_PackageFileManager; + +if (version_compare(phpversion(), '4.3.0', '<') || + php_sapi_name() == 'cgi') { + define('STDOUT', fopen('php://stdout', 'w')); + define('STDERR', fopen('php://stderr', 'w')); + register_shutdown_function( + create_function('', 'fclose(STDOUT); fclose(STDERR); return true;')); +} + +/** +* A giant array to configure the PackageFileManager. For the "roles" see +* http://pear.php.net/manual/en/developers.packagedef.php +*/ +$options = array( + 'baseinstalldir' => 'simpletest', + 'version' => $version, + 'packagedirectory' => $packagedir, + 'outputdirectory' => $packagedir, + 'pathtopackagefile' => $packagedir, + 'state' => $state, + 'summary' => $shortDesc, + 'description' => $longDesc, + 'filelistgenerator' => 'file', + 'notes' => $releaseNotes, + 'package' => 'SimpleTest', + 'license' => 'The Open Group Test Suite License', + + 'dir_roles' => array( + 'docs' => 'doc', + 'test' => 'test', + 'extensions' => 'php', + //'tutorials' => 'doc', + //'tutorials/SimpleTest' => 'doc', + //'ui' => 'php', + //'ui/css' => 'data', + //'ui/img' => 'data', + //'ui/js' => 'data', + //'ui/js/tests' => 'test', + ), + 'exceptions' => + array( + 'HELP_MY_TESTS_DONT_WORK_ANYMORE' => 'doc', + 'LICENSE' => 'doc', + 'README' => 'doc', + 'TODO' => 'doc', + 'VERSION' => 'doc', + ), + 'ignore' => + array( + "$packagedir/packages", + "$packagedir/ui", + ), + ); + +$status = $PPFM->setOptions($options); + +if (PEAR::isError($status)) { + fwrite (STDERR,$status->getMessage()); + exit; +} + +foreach ( $maintainers as $maintainer ) { + $PPFM->addMaintainer( + $maintainer['handle'], + $maintainer['role'], + $maintainer['name'], + $maintainer['email'] ); +} + +// Adds a dependency of PHP 4.2.3+ +$status = $PPFM->addDependency('php', '4.2.3', 'ge', 'php'); +if (PEAR::isError($status)) { + fwrite (STDERR,$status->getMessage()); + exit; +} + +// hack (apparently) +$PPFM->addRole('tpl', 'php'); +$PPFM->addRole('png', 'php'); +$PPFM->addRole('gif', 'php'); +$PPFM->addRole('jpg', 'php'); +$PPFM->addRole('css', 'php'); +$PPFM->addRole('js', 'php'); +$PPFM->addRole('ini', 'php'); +$PPFM->addRole('inc', 'php'); +$PPFM->addRole('afm', 'php'); +$PPFM->addRole('pkg', 'doc'); +$PPFM->addRole('cls', 'doc'); +$PPFM->addRole('proc', 'doc'); +$PPFM->addRole('sh', 'script'); + +ob_start(); +$status = $PPFM->writePackageFile(false); +$output = ob_get_contents(); +ob_end_clean(); + +// Hacks to handle PPFM output +$start = strpos ($output,"getMessage()); +} +?> \ No newline at end of file diff --git a/tests/simpletest/packages/phpdoc_docs.xslt b/tests/simpletest/packages/phpdoc_docs.xslt new file mode 100644 index 00000000..c1975226 --- /dev/null +++ b/tests/simpletest/packages/phpdoc_docs.xslt @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + + + + <![CDATA[ + + + + ]]> + + + + + + + + + + + {@id } + <xsl:value-of select="@title"/> + + + + + + + + + + + + <xsl:value-of select="h2"/> + + + + + + + + + .html + + + + } + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/tests/simpletest/packages/simpletest.ini b/tests/simpletest/packages/simpletest.ini new file mode 100755 index 00000000..87676800 --- /dev/null +++ b/tests/simpletest/packages/simpletest.ini @@ -0,0 +1,92 @@ +;; phpDocumentor parse configuration file +;; +;; This file is designed to cut down on repetitive typing on the command-line or web interface +;; You can copy this file to create a number of configuration files that can be used with the +;; command-line switch -c, as in phpdoc -c default.ini or phpdoc -c myini.ini. The web +;; interface will automatically generate a list of .ini files that can be used. +;; +;; default.ini is used to generate the online manual at http://www.phpdoc.org/docs +;; +;; ALL .ini files must be in the user subdirectory of phpDocumentor with an extension of .ini +;; +;; Copyright 2002, Greg Beaver +;; +;; WARNING: do not change the name of any command-line parameters, phpDocumentor will ignore them + +[Parse Data] +;; title of all the documentation +;; legal values: any string +title = SimpleTest API Documentation + +;; parse files that start with a . like .bash_profile +;; legal values: true, false +hidden = false + +;; show elements marked @access private in documentation by setting this to on +;; legal values: on, off +parseprivate = off + +;; parse with javadoc-like description (first sentence is always the short description) +;; legal values: on, off +javadocdesc = off + +;; add any custom @tags separated by commas here +;; legal values: any legal tagname separated by commas. +;customtags = mytag1,mytag2 + +;; This is only used by the XML:DocBook/peardoc2 converter +defaultcategoryname = Documentation + +;; what is the main package? +;; legal values: alphanumeric string plus - and _ +defaultpackagename = SimpleTest + +;; output any parsing information? set to on for cron jobs +;; legal values: on +;quiet = on + +;; parse a PEAR-style repository. Do not turn this on if your project does +;; not have a parent directory named "pear" +;; legal values: on/off +;pear = on + +;; where should the documentation be written? +;; legal values: a legal path +target = /home/groups/s/si/simpletest/htdocs/api + +;; limit output to the specified packages, even if others are parsed +;; legal values: package names separated by commas +;packageoutput = package1,package2 + +;; comma-separated list of files to parse +;; legal values: paths separated by commas +;filename = /path/to/file1,/path/to/file2,fileincurrentdirectory + +;; comma-separated list of directories to parse +;; legal values: directory paths separated by commas +;directory = /path1,/path2,.,..,subdirectory +;directory = /home/jeichorn/cvs/pear +directory = /home/groups/s/si/simpletest/simpletest_doc_target + +;; template base directory (the equivalent directory of /phpDocumentor) +;templatebase = /path/to/my/templates + +;; comma-separated list of files, directories or wildcards ? and * (any wildcard) to ignore +;; legal values: any wildcard strings separated by commas +;ignore = /path/to/ignore*,*list.php,myfile.php,subdirectory/ +;ignore = templates_c/,*HTML/default/*,spec/ +ignore = docs/,packages/,test/ + +;; comma-separated list of Converters to use in outputformat:Convertername:templatedirectory format +;; legal values: HTML:frames:default,HTML:frames:l0l33t,HTML:frames:phpdoc.de,HTML:frames:phphtmllib, +;; HTML:frames:earthli, +;; HTML:frames:DOM/default,HTML:frames:DOM/l0l33t,HTML:frames:DOM/phpdoc.de, +;; HTML:frames:DOM/phphtmllib,HTML:frames:DOM/earthli +;; HTML:Smarty:default,HTML:Smarty:PHP,HTML:Smarty:HandS +;; PDF:default:default,CHM:default:default,XML:DocBook/peardoc2:default +;output=HTML:frames:earthli,HTML:frames:default,HTML:frames:l0l33t,HTML:frames:phpdoc.de,HTML:frames:phphtmllib,HTML:frames:DOM/default,HTML:frames:DOM/l0l33t,HTML:frames:DOM/phpdoc.de,HTML:frames:DOM/earthli,HTML:frames:DOM/phphtmllib,HTML:frames:phpedit,HTML:Smarty:default,HTML:Smarty:PHP,HTML:Smarty:HandS,CHM:default:default,PDF:default:default +output=HTML:frames:DOM/earthlisf + +;; turn this option on if you want highlighted source code for every file +;; legal values: on/off +sourcecode = off diff --git a/tests/simpletest/packages/simpletest.org/index.php b/tests/simpletest/packages/simpletest.org/index.php new file mode 100644 index 00000000..84bd497c --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/index.php @@ -0,0 +1,46 @@ +destination("map.xml"); + + if (!empty($destination)) { + $page = file_get_contents('template.html'); + + $page = str_replace('TITLE', $source->title(), $page); + $page = str_replace('CONTENT', $source->content(), $page); + $links = $source->links("map.xml"); + foreach ($links as $category => $link) { + $page = str_replace("LINKS_".strtoupper($category), $link, $page); + } + + $destination_dir = dirname($destination_path.$destination); + if (!is_dir($destination_dir)) { + mkdir($destination_dir); + } + + $ok = file_put_contents($destination_path.$destination, $page); + if ($ok) { + $result = "OK"; + } else { + $result = "KO"; + } + echo $destination_path.$destination." : ".$result."
    "; + } + } + } + closedir($dir); +} +?> \ No newline at end of file diff --git a/tests/simpletest/packages/simpletest.org/map.xml b/tests/simpletest/packages/simpletest.org/map.xml new file mode 100644 index 00000000..8b0d5aa8 --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/map.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/simpletest/packages/simpletest.org/package.php b/tests/simpletest/packages/simpletest.org/package.php new file mode 100644 index 00000000..dc0745fc --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/package.php @@ -0,0 +1,259 @@ +xpath('//page'); + return $titles[0]->attributes()->title; + } + + function transform_code($code) { + $code = str_replace('', '', $code); + $code = str_replace('<', '<', $code); + $code = str_replace('>', '>', $code); + $code = str_replace('<strong>', '', $code); + $code = str_replace('</strong>', '', $code); + + return $code; + } + + function content() { + $content = ""; + $sections = $this->xpath('//section'); + if (count($sections) > 0) { + $content = $this->content_with_sections(); + } else { + $content = $this->content_without_sections(); + } + + return $content; + } + + function content_without_sections() { + $content_without_sections = ""; + $contents = $this->xpath('//content'); + foreach ($contents as $content) { + $content_element = $content->asXML(); + $elements_divided = preg_split('/|<\/php>/', $content_element); + + if (count($elements_divided) > 1) { + $content_element = ''; + foreach ($elements_divided as $element_divided) { + if (strpos($element_divided, ''.$this->transform_code($element_divided).''; + } + $content_element .= $element_divided; + } + } + $content_without_sections .= $content_element; + } + + return $content_without_sections; + } + + function content_with_sections() { + $content = ""; + $sections = $this->xpath('//section'); + foreach ($sections as $section) { + $content .= "

    ".(string)$section->attributes()->title."

    "; + foreach ($section as $element) { + $content_element = $element->asXML(); + $elements_divided = preg_split('/|<\/php>/', $content_element); + + if (count($elements_divided) > 1) { + $content_element = ''; + foreach ($elements_divided as $element_divided) { + if (strpos($element_divided, ''.$this->transform_code($element_divided).''; + } + $content_element .= $element_divided; + } + } + $content .= $content_element; + } + } + + return $content; + } + + function here() { + $pages = $this->xpath('//page'); + return $pages[0]->attributes()->here; + } + + function parent($map) { + $here = $this->here(); + $pages = $map->xpath('//page[normalize-space(@here)="'.$here.'"]/parent::*'); + return $pages[0]->attributes()->here; + } + + function destination($path_to_map) { + $destination = ''; + $here = $this->here(); + + $map = simplexml_load_file($path_to_map); + $pages = $map->xpath('//page'); + $i = 0; + foreach ($pages as $page) { + $i++; + if ((string)$page->attributes()->here == $here) { + $destination = (string)$page->attributes()->file; + break; + } + } + + return $destination; + } + + function url($file) { + $segments = explode("/", $file); + + return array_pop($segments); + } + + function links_from_xpath($xpath, $map) { + $link = ""; + + $here = $this->here(); + $pages = $map->xpath($xpath); + foreach ($pages as $page) { + $link .= '
  • '; + $link .= $page->attributes()->title.'
  • '; + } + + return $link; + } + + function links_parent_siblings_after($map) { + $here = $this->parent($map); + $query = '//page[normalize-space(@here)="'.$here.'"]/following-sibling::*'; + + return $this->links_from_xpath($query, $map); + } + + function links_parent($map) { + $here = $this->parent($map); + $query = '//page[normalize-space(@here)="'.$here.'"]'; + + return $this->links_from_xpath($query, $map); + } + + function links_parent_siblings_before($map) { + $here = $this->parent($map); + $query = '//page[normalize-space(@here)="'.$here.'"]/preceding-sibling::*'; + + return $this->links_from_xpath($query, $map); + } + + function links_parent_ancestors($map) { + $here = $this->parent($map); + return $this->links_ancestors_from($here, $map); + } + + function links_self_ancestors($map) { + $here = $this->here(); + return $this->links_ancestors_from($here, $map); + } + + function links_ancestors_from($here, $map) { + $link = ""; + + $pages = $map->xpath('//page[normalize-space(@here)="'.$here.'"]/ancestor::*'); + foreach ($pages as $page) { + $here = (string)$page->attributes()->here; + if ($this->level_from_root($here, $map) >= 2) { + $link .= '
  • '; + $link .= $page->attributes()->title.'
  • '; + } + } + + return $link; + } + function links_siblings_before($map) { + $here = $this->here(); + $query = '//page[normalize-space(@here)="'.$here.'"]/preceding-sibling::*'; + + return $this->links_from_xpath($query, $map); + } + + function links_self($map) { + $here = $this->here(); + $query = '//page[normalize-space(@here)="'.$here.'"]'; + + return $this->links_from_xpath($query, $map); + } + + function links_siblings_after($map) { + $here = $this->here(); + $query = '//page[normalize-space(@here)="'.$here.'"]/following-sibling::*'; + + return $this->links_from_xpath($query, $map); + } + + function links_children($map) { + $here = $this->here(); + $query = '//page[normalize-space(@here)="'.$here.'"]/child::*'; + + return $this->links_from_xpath($query, $map); + } + + function links($path_to_map) { + $links['download'] = ""; + $links['start_testing'] = ""; + $links['support'] = ""; + + $map = simplexml_load_file($path_to_map); + + $link = '
      '; + $here = $this->here(); + $level = $this->level_from_root($here, $map); + if ($level == 2) { + $link .= $this->links_self($map); + $link .= $this->links_children($map); + } + if ($level == 3) { + $link .= $this->links_self_ancestors($map); + $link .= $this->links_siblings_before($map); + $link .= $this->links_self($map); + $chilren = $this->links_children($map); + if ($chilren) { + $link = preg_replace('/(<\/li>)$/', '', $link).'
        '.$chilren.'
      '; + } + $link .= $this->links_siblings_after($map); + } + if ($level == 4) { + $link .= $this->links_parent_ancestors($map); + $link .= $this->links_parent_siblings_before($map); + $link .= $this->links_parent($map); + $link = preg_replace('/(<\/li>)$/', '', $link).'
        '; + $link .= $this->links_siblings_before($map); + $link .= $this->links_self($map); + $chilren = $this->links_children($map); + if ($chilren) { + $link = preg_replace('/(<\/li>)$/', '', $link).'
          '.$chilren.'
        '; + } + $link .= $this->links_siblings_after($map); + $link .= '
      '; + $link .= $this->links_parent_siblings_after($map); + } + $link .= '
    '; + + if (strpos($link, 'download.html') !== false) { + $links['download'] = $link; + } elseif (strpos($link, 'start-testing.html') !== false) { + $links['start_testing'] = $link; + } elseif (strpos($link, 'support.html') !== false) { + $links['support'] = $link; + } + + return $links; + } + + function level_from_root($here, $map) { + $ancestors = $map->xpath('//page[normalize-space(@here)="'.$here.'"]/ancestor::*'); + + return count($ancestors); + } +} + +?> \ No newline at end of file diff --git a/tests/simpletest/packages/simpletest.org/template.html b/tests/simpletest/packages/simpletest.org/template.html new file mode 100644 index 00000000..dee4674a --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/template.html @@ -0,0 +1,42 @@ + + + + +TITLE + + + +
    +
    + +
    +
    + + LINKS_DOWNLOAD +
    +
    + + LINKS_START_TESTING +
    +
    + + LINKS_SUPPORT +
    +
    + + SourceForge.net Logo + +
    +
    +
    +
    +

    TITLE

    + + CONTENT +
    +
    + + + diff --git a/tests/simpletest/packages/simpletest.org/test/package/content_without_section.xml b/tests/simpletest/packages/simpletest.org/test/package/content_without_section.xml new file mode 100644 index 00000000..47be74df --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/test/package/content_without_section.xml @@ -0,0 +1,91 @@ + + + + Overview and feature list for the SimpleTest PHP unit tester and web tester + + +

    + A test case looks like this... +MyTestCase extends UnitTestCase { + + function testLogWroteMessage() { + $log = &new Log('my.log'); + $log->message('Hello'); + $this->assertTrue(file_exists('my.log')); + } +} +?> +]]> +

    +
    + + + Quick summary + of the SimpleTest tool for PHP. + + + List of features, + both current ones and those planned. + + + There are plenty of unit testing resources + on the web. + + + + + Documentation for SimpleTest. + + + How to write PHP test cases + is a fairly advanced tutorial. + + + SimpleTest API from phpdoc. + + + + + software development tools, + php programming, + programming php, + software development tools, + Tools for extreme programming, + free php scripts, + links of testing tools, + php testing resources, + mock objects, + junit, + jwebunit, + htmlunit, + itc, + php testing links, + unit test advice and documentation, + extreme programming in php + + + + + + Marcus Baker + + Primary Developer{@link mailto:marcus@lastcraft.com marcus@lastcraft.com} + + + + Harry Fuecks + + Packager{@link mailto:harryf@users.sourceforge.net harryf@users.sourceforge.net} + + + + Jason Sweat + + Documentation{@link mailto:jsweat_php@yahoo.com jsweat_php@yahoo.com} + + + + +
    diff --git a/tests/simpletest/packages/simpletest.org/test/package/here_download.xml b/tests/simpletest/packages/simpletest.org/test/package/here_download.xml new file mode 100644 index 00000000..cdc3df33 --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/test/package/here_download.xml @@ -0,0 +1,91 @@ + + + + Overview and feature list for the SimpleTest PHP unit tester and web tester + + +

    + A test case looks like this... +MyTestCase extends UnitTestCase { + + function testLogWroteMessage() { + $log = &new Log('my.log'); + $log->message('Hello'); + $this->assertTrue(file_exists('my.log')); + } +} +?> +]]> +

    +
    + + + Quick summary + of the SimpleTest tool for PHP. + + + List of features, + both current ones and those planned. + + + There are plenty of unit testing resources + on the web. + + + + + Documentation for SimpleTest. + + + How to write PHP test cases + is a fairly advanced tutorial. + + + SimpleTest API from phpdoc. + + + + + software development tools, + php programming, + programming php, + software development tools, + Tools for extreme programming, + free php scripts, + links of testing tools, + php testing resources, + mock objects, + junit, + jwebunit, + htmlunit, + itc, + php testing links, + unit test advice and documentation, + extreme programming in php + + + + + + Marcus Baker + + Primary Developer{@link mailto:marcus@lastcraft.com marcus@lastcraft.com} + + + + Harry Fuecks + + Packager{@link mailto:harryf@users.sourceforge.net harryf@users.sourceforge.net} + + + + Jason Sweat + + Documentation{@link mailto:jsweat_php@yahoo.com jsweat_php@yahoo.com} + + + + +
    diff --git a/tests/simpletest/packages/simpletest.org/test/package/here_overview.xml b/tests/simpletest/packages/simpletest.org/test/package/here_overview.xml new file mode 100644 index 00000000..47be74df --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/test/package/here_overview.xml @@ -0,0 +1,91 @@ + + + + Overview and feature list for the SimpleTest PHP unit tester and web tester + + +

    + A test case looks like this... +MyTestCase extends UnitTestCase { + + function testLogWroteMessage() { + $log = &new Log('my.log'); + $log->message('Hello'); + $this->assertTrue(file_exists('my.log')); + } +} +?> +]]> +

    +
    + + + Quick summary + of the SimpleTest tool for PHP. + + + List of features, + both current ones and those planned. + + + There are plenty of unit testing resources + on the web. + + + + + Documentation for SimpleTest. + + + How to write PHP test cases + is a fairly advanced tutorial. + + + SimpleTest API from phpdoc. + + + + + software development tools, + php programming, + programming php, + software development tools, + Tools for extreme programming, + free php scripts, + links of testing tools, + php testing resources, + mock objects, + junit, + jwebunit, + htmlunit, + itc, + php testing links, + unit test advice and documentation, + extreme programming in php + + + + + + Marcus Baker + + Primary Developer{@link mailto:marcus@lastcraft.com marcus@lastcraft.com} + + + + Harry Fuecks + + Packager{@link mailto:harryf@users.sourceforge.net harryf@users.sourceforge.net} + + + + Jason Sweat + + Documentation{@link mailto:jsweat_php@yahoo.com jsweat_php@yahoo.com} + + + + +
    diff --git a/tests/simpletest/packages/simpletest.org/test/package/here_simpletest.xml b/tests/simpletest/packages/simpletest.org/test/package/here_simpletest.xml new file mode 100644 index 00000000..c9a83dc3 --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/test/package/here_simpletest.xml @@ -0,0 +1,91 @@ + + + + Overview and feature list for the SimpleTest PHP unit tester and web tester + + +

    + A test case looks like this... +MyTestCase extends UnitTestCase { + + function testLogWroteMessage() { + $log = &new Log('my.log'); + $log->message('Hello'); + $this->assertTrue(file_exists('my.log')); + } +} +?> +]]> +

    +
    + + + Quick summary + of the SimpleTest tool for PHP. + + + List of features, + both current ones and those planned. + + + There are plenty of unit testing resources + on the web. + + + + + Documentation for SimpleTest. + + + How to write PHP test cases + is a fairly advanced tutorial. + + + SimpleTest API from phpdoc. + + + + + software development tools, + php programming, + programming php, + software development tools, + Tools for extreme programming, + free php scripts, + links of testing tools, + php testing resources, + mock objects, + junit, + jwebunit, + htmlunit, + itc, + php testing links, + unit test advice and documentation, + extreme programming in php + + + + + + Marcus Baker + + Primary Developer{@link mailto:marcus@lastcraft.com marcus@lastcraft.com} + + + + Harry Fuecks + + Packager{@link mailto:harryf@users.sourceforge.net harryf@users.sourceforge.net} + + + + Jason Sweat + + Documentation{@link mailto:jsweat_php@yahoo.com jsweat_php@yahoo.com} + + + + +
    diff --git a/tests/simpletest/packages/simpletest.org/test/package/here_start_testing.xml b/tests/simpletest/packages/simpletest.org/test/package/here_start_testing.xml new file mode 100644 index 00000000..47be74df --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/test/package/here_start_testing.xml @@ -0,0 +1,91 @@ + + + + Overview and feature list for the SimpleTest PHP unit tester and web tester + + +

    + A test case looks like this... +MyTestCase extends UnitTestCase { + + function testLogWroteMessage() { + $log = &new Log('my.log'); + $log->message('Hello'); + $this->assertTrue(file_exists('my.log')); + } +} +?> +]]> +

    +
    + + + Quick summary + of the SimpleTest tool for PHP. + + + List of features, + both current ones and those planned. + + + There are plenty of unit testing resources + on the web. + + + + + Documentation for SimpleTest. + + + How to write PHP test cases + is a fairly advanced tutorial. + + + SimpleTest API from phpdoc. + + + + + software development tools, + php programming, + programming php, + software development tools, + Tools for extreme programming, + free php scripts, + links of testing tools, + php testing resources, + mock objects, + junit, + jwebunit, + htmlunit, + itc, + php testing links, + unit test advice and documentation, + extreme programming in php + + + + + + Marcus Baker + + Primary Developer{@link mailto:marcus@lastcraft.com marcus@lastcraft.com} + + + + Harry Fuecks + + Packager{@link mailto:harryf@users.sourceforge.net harryf@users.sourceforge.net} + + + + Jason Sweat + + Documentation{@link mailto:jsweat_php@yahoo.com jsweat_php@yahoo.com} + + + + +
    diff --git a/tests/simpletest/packages/simpletest.org/test/package/here_support.xml b/tests/simpletest/packages/simpletest.org/test/package/here_support.xml new file mode 100644 index 00000000..867325a7 --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/test/package/here_support.xml @@ -0,0 +1,91 @@ + + + + Overview and feature list for the SimpleTest PHP unit tester and web tester + + +

    + A test case looks like this... +MyTestCase extends UnitTestCase { + + function testLogWroteMessage() { + $log = &new Log('my.log'); + $log->message('Hello'); + $this->assertTrue(file_exists('my.log')); + } +} +?> +]]> +

    +
    + + + Quick summary + of the SimpleTest tool for PHP. + + + List of features, + both current ones and those planned. + + + There are plenty of unit testing resources + on the web. + + + + + Documentation for SimpleTest. + + + How to write PHP test cases + is a fairly advanced tutorial. + + + SimpleTest API from phpdoc. + + + + + software development tools, + php programming, + programming php, + software development tools, + Tools for extreme programming, + free php scripts, + links of testing tools, + php testing resources, + mock objects, + junit, + jwebunit, + htmlunit, + itc, + php testing links, + unit test advice and documentation, + extreme programming in php + + + + + + Marcus Baker + + Primary Developer{@link mailto:marcus@lastcraft.com marcus@lastcraft.com} + + + + Harry Fuecks + + Packager{@link mailto:harryf@users.sourceforge.net harryf@users.sourceforge.net} + + + + Jason Sweat + + Documentation{@link mailto:jsweat_php@yahoo.com jsweat_php@yahoo.com} + + + + +
    diff --git a/tests/simpletest/packages/simpletest.org/test/package/here_unit-tester.xml b/tests/simpletest/packages/simpletest.org/test/package/here_unit-tester.xml new file mode 100644 index 00000000..a3740945 --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/test/package/here_unit-tester.xml @@ -0,0 +1,91 @@ + + + + Overview and feature list for the SimpleTest PHP unit tester and web tester + + +

    + A test case looks like this... +MyTestCase extends UnitTestCase { + + function testLogWroteMessage() { + $log = &new Log('my.log'); + $log->message('Hello'); + $this->assertTrue(file_exists('my.log')); + } +} +?> +]]> +

    +
    + + + Quick summary + of the SimpleTest tool for PHP. + + + List of features, + both current ones and those planned. + + + There are plenty of unit testing resources + on the web. + + + + + Documentation for SimpleTest. + + + How to write PHP test cases + is a fairly advanced tutorial. + + + SimpleTest API from phpdoc. + + + + + software development tools, + php programming, + programming php, + software development tools, + Tools for extreme programming, + free php scripts, + links of testing tools, + php testing resources, + mock objects, + junit, + jwebunit, + htmlunit, + itc, + php testing links, + unit test advice and documentation, + extreme programming in php + + + + + + Marcus Baker + + Primary Developer{@link mailto:marcus@lastcraft.com marcus@lastcraft.com} + + + + Harry Fuecks + + Packager{@link mailto:harryf@users.sourceforge.net harryf@users.sourceforge.net} + + + + Jason Sweat + + Documentation{@link mailto:jsweat_php@yahoo.com jsweat_php@yahoo.com} + + + + +
    diff --git a/tests/simpletest/packages/simpletest.org/test/package/map.xml b/tests/simpletest/packages/simpletest.org/test/package/map.xml new file mode 100644 index 00000000..ec25596c --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/test/package/map.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/simpletest/packages/simpletest.org/test/package/one_section_with_php_code.xml b/tests/simpletest/packages/simpletest.org/test/package/one_section_with_php_code.xml new file mode 100644 index 00000000..b09eaea5 --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/test/package/one_section_with_php_code.xml @@ -0,0 +1,93 @@ + + + + Overview and feature list for the SimpleTest PHP unit tester and web tester + + +
    +

    + A test case looks like this... +MyTestCase extends UnitTestCase { + + function testLogWroteMessage() { + $log = &new Log('my.log'); + $log->message('Hello'); + $this->assertTrue(file_exists('my.log')); + } +} +?> +]]> +

    +
    +
    + + + Quick summary + of the SimpleTest tool for PHP. + + + List of features, + both current ones and those planned. + + + There are plenty of unit testing resources + on the web. + + + + + Documentation for SimpleTest. + + + How to write PHP test cases + is a fairly advanced tutorial. + + + SimpleTest API from phpdoc. + + + + + software development tools, + php programming, + programming php, + software development tools, + Tools for extreme programming, + free php scripts, + links of testing tools, + php testing resources, + mock objects, + junit, + jwebunit, + htmlunit, + itc, + php testing links, + unit test advice and documentation, + extreme programming in php + + + + + + Marcus Baker + + Primary Developer{@link mailto:marcus@lastcraft.com marcus@lastcraft.com} + + + + Harry Fuecks + + Packager{@link mailto:harryf@users.sourceforge.net harryf@users.sourceforge.net} + + + + Jason Sweat + + Documentation{@link mailto:jsweat_php@yahoo.com jsweat_php@yahoo.com} + + + + +
    diff --git a/tests/simpletest/packages/simpletest.org/test/package_test.php b/tests/simpletest/packages/simpletest.org/test/package_test.php new file mode 100644 index 00000000..78008ce1 --- /dev/null +++ b/tests/simpletest/packages/simpletest.org/test/package_test.php @@ -0,0 +1,89 @@ +content(); + $this->assertPattern('/
    /', $content);
    +		$this->assertNoPattern('/<\!\[CDATA\[/', $content);
    +		$this->assertPattern('/

    /', $content); + } + + function testOfContentWithoutSections() { + $file = dirname(__FILE__).'/package/content_without_section.xml'; + $source = simplexml_load_file($file, "SimpleTestXMLElement"); + $content = $source->content(); + $this->assertPattern('/

    /', $content); + } + + function testOfSingleLink() { + $file = dirname(__FILE__).'/package/here_download.xml'; + $source = simplexml_load_file($file, "SimpleTestXMLElement"); + $map = dirname(__FILE__).'/package/map.xml'; + $links = $source->links($map); + $this->assertEqual(count($links), 3); + $links_download = '

    '; + $this->assertEqual($links['download'], $links_download); + } + + function testOfMultipleLinks() { + $file = dirname(__FILE__).'/package/here_support.xml'; + $source = simplexml_load_file($file, "SimpleTestXMLElement"); + $map = dirname(__FILE__).'/package/map.xml'; + $links = $source->links($map); + $this->assertEqual(count($links), 3); + $links_support = ''; + $this->assertEqual($links['support'], $links_support); + } + + function testOfHierarchicalLinks() { + $file = dirname(__FILE__).'/package/here_overview.xml'; + $source = simplexml_load_file($file, "SimpleTestXMLElement"); + $map = dirname(__FILE__).'/package/map.xml'; + $links = $source->links($map); + $this->assertEqual(count($links), 3); + $links_start_testing = ''; + $this->assertEqual($links['start_testing'], $links_start_testing); + } + + function testOfRootLinksWithHierarchy() { + $file = dirname(__FILE__).'/package/here_simpletest.xml'; + $source = simplexml_load_file($file, "SimpleTestXMLElement"); + $map = dirname(__FILE__).'/package/map.xml'; + $links = $source->links($map); + $this->assertEqual(count($links), 3); + $links_start_testing = ''; + $this->assertEqual($links['start_testing'], $links_start_testing); + } + + function testOfLinksWithNonRootParent() { + $file = dirname(__FILE__).'/package/here_unit-tester.xml'; + $source = simplexml_load_file($file, "SimpleTestXMLElement"); + $map = dirname(__FILE__).'/package/map.xml'; + $links = $source->links($map); + $this->assertEqual(count($links), 3); + $links_start_testing = ''; + $this->assertEqual($links['start_testing'], $links_start_testing); + } +} + +$test = &new TestOfContentTransformationFromXMLToHTML(); +$test->run(new HtmlReporter()); + +?> \ No newline at end of file diff --git a/tests/simpletest/packages/site_map.xml b/tests/simpletest/packages/site_map.xml new file mode 100644 index 00000000..10e56637 --- /dev/null +++ b/tests/simpletest/packages/site_map.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/simpletest/packages/transform_all_lastcraft.php b/tests/simpletest/packages/transform_all_lastcraft.php new file mode 100644 index 00000000..866202c3 --- /dev/null +++ b/tests/simpletest/packages/transform_all_lastcraft.php @@ -0,0 +1,17 @@ + \ No newline at end of file diff --git a/tests/simpletest/page.php b/tests/simpletest/page.php new file mode 100644 index 00000000..47883b0d --- /dev/null +++ b/tests/simpletest/page.php @@ -0,0 +1,975 @@ + '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. + * @package SimpleTest + * @subpackage WebTester + */ + class SimplePageBuilder extends SimpleSaxListener { + var $_tags; + var $_page; + var $_private_content_tag; + + /** + * Sets the builder up empty. + * @access public + */ + function SimplePageBuilder() { + $this->SimpleSaxListener(); + } + + /** + * Frees up any references so as to allow the PHP garbage + * collection from unset() to work. + * @access public + */ + function free() { + unset($this->_tags); + unset($this->_page); + unset($this->_private_content_tags); + } + + /** + * Reads the raw content and send events + * into the page to be built. + * @param $response SimpleHttpResponse Fetched response. + * @return SimplePage Newly parsed page. + * @access public + */ + function &parse($response) { + $this->_tags = array(); + $this->_page = &$this->_createPage($response); + $parser = &$this->_createParser($this); + $parser->parse($response->getContent()); + $this->_page->acceptPageEnd(); + return $this->_page; + } + + /** + * Creates an empty page. + * @return SimplePage New unparsed page. + * @access protected + */ + function &_createPage($response) { + $page = &new SimplePage($response); + return $page; + } + + /** + * Creates the parser used with the builder. + * @param $listener SimpleSaxListener Target of parser. + * @return SimpleSaxParser Parser to generate + * events for the builder. + * @access protected + */ + function &_createParser(&$listener) { + $parser = &new SimpleHtmlSaxParser($listener); + return $parser; + } + + /** + * Start of element event. Opens a new tag. + * @param string $name Element name. + * @param hash $attributes Attributes without content + * are marked as true. + * @return boolean False on parse error. + * @access public + */ + function startElement($name, $attributes) { + $factory = &new SimpleTagBuilder(); + $tag = $factory->createTag($name, $attributes); + if (! $tag) { + return true; + } + if ($tag->getTagName() == 'label') { + $this->_page->acceptLabelStart($tag); + $this->_openTag($tag); + return true; + } + if ($tag->getTagName() == 'form') { + $this->_page->acceptFormStart($tag); + return true; + } + if ($tag->getTagName() == 'frameset') { + $this->_page->acceptFramesetStart($tag); + return true; + } + if ($tag->getTagName() == 'frame') { + $this->_page->acceptFrame($tag); + return true; + } + if ($tag->isPrivateContent() && ! isset($this->_private_content_tag)) { + $this->_private_content_tag = &$tag; + } + if ($tag->expectEndTag()) { + $this->_openTag($tag); + return true; + } + $this->_page->acceptTag($tag); + return true; + } + + /** + * End of element event. + * @param string $name Element name. + * @return boolean False on parse error. + * @access public + */ + function endElement($name) { + if ($name == 'label') { + $this->_page->acceptLabelEnd(); + return true; + } + if ($name == 'form') { + $this->_page->acceptFormEnd(); + return true; + } + if ($name == 'frameset') { + $this->_page->acceptFramesetEnd(); + return true; + } + if ($this->_hasNamedTagOnOpenTagStack($name)) { + $tag = array_pop($this->_tags[$name]); + if ($tag->isPrivateContent() && $this->_private_content_tag->getTagName() == $name) { + unset($this->_private_content_tag); + } + $this->_addContentTagToOpenTags($tag); + $this->_page->acceptTag($tag); + return true; + } + return true; + } + + /** + * Test to see if there are any open tags awaiting + * closure that match the tag name. + * @param string $name Element name. + * @return boolean True if any are still open. + * @access private + */ + function _hasNamedTagOnOpenTagStack($name) { + return isset($this->_tags[$name]) && (count($this->_tags[$name]) > 0); + } + + /** + * Unparsed, but relevant data. The data is added + * to every open tag. + * @param string $text May include unparsed tags. + * @return boolean False on parse error. + * @access public + */ + function addContent($text) { + if (isset($this->_private_content_tag)) { + $this->_private_content_tag->addContent($text); + } else { + $this->_addContentToAllOpenTags($text); + } + return true; + } + + /** + * Any content fills all currently open tags unless it + * is part of an option tag. + * @param string $text May include unparsed tags. + * @access private + */ + function _addContentToAllOpenTags($text) { + foreach (array_keys($this->_tags) as $name) { + for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) { + $this->_tags[$name][$i]->addContent($text); + } + } + } + + /** + * Parsed data in tag form. The parsed tag is added + * to every open tag. Used for adding options to select + * fields only. + * @param SimpleTag $tag Option tags only. + * @access private + */ + function _addContentTagToOpenTags(&$tag) { + if ($tag->getTagName() != 'option') { + return; + } + foreach (array_keys($this->_tags) as $name) { + for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) { + $this->_tags[$name][$i]->addTag($tag); + } + } + } + + /** + * Opens a tag for receiving content. Multiple tags + * will be receiving input at the same time. + * @param SimpleTag $tag New content tag. + * @access private + */ + function _openTag(&$tag) { + $name = $tag->getTagName(); + if (! in_array($name, array_keys($this->_tags))) { + $this->_tags[$name] = array(); + } + $this->_tags[$name][] = &$tag; + } + } + + /** + * A wrapper for a web page. + * @package SimpleTest + * @subpackage WebTester + */ + class SimplePage { + var $_links; + var $_title; + var $_last_widget; + var $_label; + var $_left_over_labels; + var $_open_forms; + var $_complete_forms; + var $_frameset; + var $_frames; + var $_frameset_nesting_level; + var $_transport_error; + var $_raw; + var $_text; + var $_sent; + var $_headers; + var $_method; + var $_url; + var $_request_data; + + /** + * Parses a page ready to access it's contents. + * @param SimpleHttpResponse $response Result of HTTP fetch. + * @access public + */ + function SimplePage($response = false) { + $this->_links = array(); + $this->_title = false; + $this->_left_over_labels = array(); + $this->_open_forms = array(); + $this->_complete_forms = array(); + $this->_frameset = false; + $this->_frames = array(); + $this->_frameset_nesting_level = 0; + $this->_text = false; + if ($response) { + $this->_extractResponse($response); + } else { + $this->_noResponse(); + } + } + + /** + * Extracts all of the response information. + * @param SimpleHttpResponse $response Response being parsed. + * @access private + */ + function _extractResponse($response) { + $this->_transport_error = $response->getError(); + $this->_raw = $response->getContent(); + $this->_sent = $response->getSent(); + $this->_headers = $response->getHeaders(); + $this->_method = $response->getMethod(); + $this->_url = $response->getUrl(); + $this->_request_data = $response->getRequestData(); + } + + /** + * Sets up a missing response. + * @access private + */ + function _noResponse() { + $this->_transport_error = 'No page fetched yet'; + $this->_raw = false; + $this->_sent = false; + $this->_headers = false; + $this->_method = 'GET'; + $this->_url = false; + $this->_request_data = false; + } + + /** + * Original request as bytes sent down the wire. + * @return mixed Sent content. + * @access public + */ + function getRequest() { + return $this->_sent; + } + + /** + * Accessor for raw text of page. + * @return string Raw unparsed content. + * @access public + */ + function getRaw() { + return $this->_raw; + } + + /** + * Accessor for plain text of page as a text browser + * would see it. + * @return string Plain text of page. + * @access public + */ + function getText() { + if (! $this->_text) { + $this->_text = SimpleHtmlSaxParser::normalise($this->_raw); + } + return $this->_text; + } + + /** + * Accessor for raw headers of page. + * @return string Header block as text. + * @access public + */ + function getHeaders() { + if ($this->_headers) { + return $this->_headers->getRaw(); + } + return false; + } + + /** + * Original request method. + * @return string GET, POST or HEAD. + * @access public + */ + function getMethod() { + return $this->_method; + } + + /** + * Original resource name. + * @return SimpleUrl Current url. + * @access public + */ + function getUrl() { + return $this->_url; + } + + /** + * Original request data. + * @return mixed Sent content. + * @access public + */ + function getRequestData() { + return $this->_request_data; + } + + /** + * Accessor for last error. + * @return string Error from last response. + * @access public + */ + function getTransportError() { + return $this->_transport_error; + } + + /** + * Accessor for current MIME type. + * @return string MIME type as string; e.g. 'text/html' + * @access public + */ + function getMimeType() { + if ($this->_headers) { + return $this->_headers->getMimeType(); + } + return false; + } + + /** + * Accessor for HTTP response code. + * @return integer HTTP response code received. + * @access public + */ + function getResponseCode() { + if ($this->_headers) { + return $this->_headers->getResponseCode(); + } + return false; + } + + /** + * Accessor for last Authentication type. Only valid + * straight after a challenge (401). + * @return string Description of challenge type. + * @access public + */ + function getAuthentication() { + if ($this->_headers) { + return $this->_headers->getAuthentication(); + } + return false; + } + + /** + * Accessor for last Authentication realm. Only valid + * straight after a challenge (401). + * @return string Name of security realm. + * @access public + */ + function getRealm() { + if ($this->_headers) { + return $this->_headers->getRealm(); + } + return false; + } + + /** + * Accessor for current frame focus. Will be + * false as no frames. + * @return array Always empty. + * @access public + */ + function getFrameFocus() { + return array(); + } + + /** + * Sets the focus by index. The integer index starts from 1. + * @param integer $choice Chosen frame. + * @return boolean Always false. + * @access public + */ + function setFrameFocusByIndex($choice) { + return false; + } + + /** + * Sets the focus by name. Always fails for a leaf page. + * @param string $name Chosen frame. + * @return boolean False as no frames. + * @access public + */ + function setFrameFocus($name) { + return false; + } + + /** + * Clears the frame focus. Does nothing for a leaf page. + * @access public + */ + function clearFrameFocus() { + } + + /** + * Adds a tag to the page. + * @param SimpleTag $tag Tag to accept. + * @access public + */ + function acceptTag(&$tag) { + if ($tag->getTagName() == "a") { + $this->_addLink($tag); + } elseif ($tag->getTagName() == "title") { + $this->_setTitle($tag); + } elseif ($this->_isFormElement($tag->getTagName())) { + for ($i = 0; $i < count($this->_open_forms); $i++) { + $this->_open_forms[$i]->addWidget($tag); + } + $this->_last_widget = &$tag; + } + } + + /** + * Opens a label for a described widget. + * @param SimpleFormTag $tag Tag to accept. + * @access public + */ + function acceptLabelStart(&$tag) { + $this->_label = &$tag; + unset($this->_last_widget); + } + + /** + * Closes the most recently opened label. + * @access public + */ + function acceptLabelEnd() { + if (isset($this->_label)) { + if (isset($this->_last_widget)) { + $this->_last_widget->setLabel($this->_label->getText()); + unset($this->_last_widget); + } else { + $this->_left_over_labels[] = SimpleTestCompatibility::copy($this->_label); + } + unset($this->_label); + } + } + + /** + * Tests to see if a tag is a possible form + * element. + * @param string $name HTML element name. + * @return boolean True if form element. + * @access private + */ + function _isFormElement($name) { + return in_array($name, array('input', 'button', 'textarea', 'select')); + } + + /** + * Opens a form. New widgets go here. + * @param SimpleFormTag $tag Tag to accept. + * @access public + */ + function acceptFormStart(&$tag) { + $this->_open_forms[] = &new SimpleForm($tag, $this->getUrl()); + } + + /** + * Closes the most recently opened form. + * @access public + */ + function acceptFormEnd() { + if (count($this->_open_forms)) { + $this->_complete_forms[] = array_pop($this->_open_forms); + } + } + + /** + * Opens a frameset. A frameset may contain nested + * frameset tags. + * @param SimpleFramesetTag $tag Tag to accept. + * @access public + */ + function acceptFramesetStart(&$tag) { + if (! $this->_isLoadingFrames()) { + $this->_frameset = &$tag; + } + $this->_frameset_nesting_level++; + } + + /** + * Closes the most recently opened frameset. + * @access public + */ + function acceptFramesetEnd() { + if ($this->_isLoadingFrames()) { + $this->_frameset_nesting_level--; + } + } + + /** + * Takes a single frame tag and stashes it in + * the current frame set. + * @param SimpleFrameTag $tag Tag to accept. + * @access public + */ + function acceptFrame(&$tag) { + if ($this->_isLoadingFrames()) { + if ($tag->getAttribute('src')) { + $this->_frames[] = &$tag; + } + } + } + + /** + * Test to see if in the middle of reading + * a frameset. + * @return boolean True if inframeset. + * @access private + */ + function _isLoadingFrames() { + if (! $this->_frameset) { + return false; + } + return ($this->_frameset_nesting_level > 0); + } + + /** + * Test to see if link is an absolute one. + * @param string $url Url to test. + * @return boolean True if absolute. + * @access protected + */ + function _linkIsAbsolute($url) { + $parsed = new SimpleUrl($url); + return (boolean)($parsed->getScheme() && $parsed->getHost()); + } + + /** + * Adds a link to the page. + * @param SimpleAnchorTag $tag Link to accept. + * @access protected + */ + function _addLink($tag) { + $this->_links[] = $tag; + } + + /** + * Marker for end of complete page. Any work in + * progress can now be closed. + * @access public + */ + function acceptPageEnd() { + while (count($this->_open_forms)) { + $this->_complete_forms[] = array_pop($this->_open_forms); + } + 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. + * @access public + */ + function hasFrames() { + return (boolean)$this->_frameset; + } + + /** + * Accessor for frame name and source URL for every frame that + * will need to be loaded. Immediate children only. + * @return boolean/array False if no frameset or + * otherwise a hash of frame URLs. + * The key is either a numerical + * base one index or the name attribute. + * @access public + */ + function getFrameset() { + if (! $this->_frameset) { + return false; + } + $urls = array(); + for ($i = 0; $i < count($this->_frames); $i++) { + $name = $this->_frames[$i]->getAttribute('name'); + $url = new SimpleUrl($this->_frames[$i]->getAttribute('src')); + $urls[$name ? $name : $i + 1] = $url->makeAbsolute($this->getUrl()); + } + return $urls; + } + + /** + * Fetches a list of loaded frames. + * @return array/string Just the URL for a single page. + * @access public + */ + function getFrames() { + $url = $this->getUrl(); + return $url->asString(); + } + + /** + * Accessor for a list of all fixed links. + * @return array List of urls with scheme of + * http or https and hostname. + * @access public + */ + function getAbsoluteUrls() { + $all = array(); + foreach ($this->_links as $link) { + if ($this->_linkIsAbsolute($link->getHref())) { + $all[] = $link->getHref(); + } + } + return $all; + } + + /** + * Accessor for a list of all relative links. + * @return array List of urls without hostname. + * @access public + */ + function getRelativeUrls() { + $all = array(); + foreach ($this->_links as $link) { + if (! $this->_linkIsAbsolute($link->getHref())) { + $all[] = $link->getHref(); + } + } + return $all; + } + + /** + * Accessor for URLs by the link label. Label will match + * regardess of whitespace issues and case. + * @param string $label Text of link. + * @return array List of links with that label. + * @access public + */ + function getUrlsByLabel($label) { + $matches = array(); + foreach ($this->_links as $link) { + if ($link->getText() == $label) { + $matches[] = $this->_getUrlFromLink($link); + } + } + return $matches; + } + + /** + * Accessor for a URL by the id attribute. + * @param string $id Id attribute of link. + * @return SimpleUrl URL with that id of false if none. + * @access public + */ + function getUrlById($id) { + foreach ($this->_links as $link) { + if ($link->getAttribute('id') === (string)$id) { + return $this->_getUrlFromLink($link); + } + } + return false; + } + + /** + * Converts a link into a target URL. + * @param SimpleAnchor $link Parsed link. + * @return SimpleUrl URL with frame target if any. + * @access private + */ + function _getUrlFromLink($link) { + $url = $this->_makeAbsolute($link->getHref()); + if ($link->getAttribute('target')) { + $url->setTarget($link->getAttribute('target')); + } + return $url; + } + + /** + * Expands expandomatic URLs into fully qualified + * URLs. + * @param SimpleUrl $url Relative URL. + * @return SimpleUrl Absolute URL. + * @access protected + */ + function _makeAbsolute($url) { + if (! is_object($url)) { + $url = new SimpleUrl($url); + } + return $url->makeAbsolute($this->getUrl()); + } + + /** + * Sets the title tag contents. + * @param SimpleTitleTag $tag Title of page. + * @access protected + */ + function _setTitle(&$tag) { + $this->_title = &$tag; + } + + /** + * Accessor for parsed title. + * @return string Title or false if no title is present. + * @access public + */ + function getTitle() { + if ($this->_title) { + return $this->_title->getText(); + } + return false; + } + + /** + * Finds a held form by button label. Will only + * search correctly built forms. + * @param SimpleSelector $selector Button finder. + * @return SimpleForm Form object containing + * the button. + * @access public + */ + function &getFormBySubmit($selector) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->hasSubmit($selector)) { + return $this->_complete_forms[$i]; + } + } + $null = null; + return $null; + } + + /** + * Finds a held form by image using a selector. + * Will only search correctly built forms. + * @param SimpleSelector $selector Image finder. + * @return SimpleForm Form object containing + * the image. + * @access public + */ + function &getFormByImage($selector) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->hasImage($selector)) { + return $this->_complete_forms[$i]; + } + } + $null = null; + return $null; + } + + /** + * Finds a held form by the form ID. A way of + * identifying a specific form when we have control + * of the HTML code. + * @param string $id Form label. + * @return SimpleForm Form object containing the matching ID. + * @access public + */ + function &getFormById($id) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->getId() == $id) { + return $this->_complete_forms[$i]; + } + } + $null = null; + return $null; + } + + /** + * Sets a field on each form in which the field is + * available. + * @param SimpleSelector $selector Field finder. + * @param string $value Value to set field to. + * @return boolean True if value is valid. + * @access public + */ + function setField($selector, $value) { + $is_set = false; + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->setField($selector, $value)) { + $is_set = true; + } + } + return $is_set; + } + + /** + * Accessor for a form element value within a page. + * @param SimpleSelector $selector Field finder. + * @return string/boolean A string if the field is + * present, false if unchecked + * and null if missing. + * @access public + */ + function getField($selector) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + $value = $this->_complete_forms[$i]->getValue($selector); + if (isset($value)) { + return $value; + } + } + return null; + } + } +?> diff --git a/tests/simpletest/parser.php b/tests/simpletest/parser.php new file mode 100644 index 00000000..9a4f6949 --- /dev/null +++ b/tests/simpletest/parser.php @@ -0,0 +1,775 @@ +_case = $case; + $this->_patterns = array(); + $this->_labels = array(); + $this->_regex = null; + } + + /** + * Adds a pattern with an optional label. + * @param string $pattern Perl style regex, but ( and ) + * lose the usual meaning. + * @param string $label Label of regex to be returned + * on a match. + * @access public + */ + function addPattern($pattern, $label = true) { + $count = count($this->_patterns); + $this->_patterns[$count] = $pattern; + $this->_labels[$count] = $label; + $this->_regex = null; + } + + /** + * Attempts to match all patterns at once against + * a string. + * @param string $subject String to match against. + * @param string $match First matched portion of + * subject. + * @return boolean True on success. + * @access public + */ + function match($subject, &$match) { + if (count($this->_patterns) == 0) { + return false; + } + if (! preg_match($this->_getCompoundedRegex(), $subject, $matches)) { + $match = ''; + return false; + } + $match = $matches[0]; + for ($i = 1; $i < count($matches); $i++) { + if ($matches[$i]) { + return $this->_labels[$i - 1]; + } + } + return true; + } + + /** + * Compounds the patterns into a single + * regular expression separated with the + * "or" operator. Caches the regex. + * Will automatically escape (, ) and / tokens. + * @param array $patterns List of patterns in order. + * @access private + */ + function _getCompoundedRegex() { + if ($this->_regex == null) { + for ($i = 0, $count = count($this->_patterns); $i < $count; $i++) { + $this->_patterns[$i] = '(' . str_replace( + array('/', '(', ')'), + array('\/', '\(', '\)'), + $this->_patterns[$i]) . ')'; + } + $this->_regex = "/" . implode("|", $this->_patterns) . "/" . $this->_getPerlMatchingFlags(); + } + return $this->_regex; + } + + /** + * Accessor for perl regex mode flags to use. + * @return string Perl regex flags. + * @access private + */ + function _getPerlMatchingFlags() { + return ($this->_case ? "msS" : "msSi"); + } + } + + /** + * States for a stack machine. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleStateStack { + var $_stack; + + /** + * Constructor. Starts in named state. + * @param string $start Starting state name. + * @access public + */ + function SimpleStateStack($start) { + $this->_stack = array($start); + } + + /** + * Accessor for current state. + * @return string State. + * @access public + */ + function getCurrent() { + return $this->_stack[count($this->_stack) - 1]; + } + + /** + * Adds a state to the stack and sets it + * to be the current state. + * @param string $state New state. + * @access public + */ + function enter($state) { + array_push($this->_stack, $state); + } + + /** + * Leaves the current state and reverts + * to the previous one. + * @return boolean False if we drop off + * the bottom of the list. + * @access public + */ + function leave() { + if (count($this->_stack) == 1) { + return false; + } + array_pop($this->_stack); + return true; + } + } + + /** + * Accepts text and breaks it into tokens. + * Some optimisation to make the sure the + * content is only scanned by the PHP regex + * parser once. Lexer modes must not start + * with leading underscores. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleLexer { + var $_regexes; + var $_parser; + var $_mode; + var $_mode_handlers; + var $_case; + + /** + * Sets up the lexer in case insensitive matching + * by default. + * @param SimpleSaxParser $parser Handling strategy by + * reference. + * @param string $start Starting handler. + * @param boolean $case True for case sensitive. + * @access public + */ + function SimpleLexer(&$parser, $start = "accept", $case = false) { + $this->_case = $case; + $this->_regexes = array(); + $this->_parser = &$parser; + $this->_mode = &new SimpleStateStack($start); + $this->_mode_handlers = array($start => $start); + } + + /** + * Adds a token search pattern for a particular + * parsing mode. The pattern does not change the + * current mode. + * @param string $pattern Perl style regex, but ( and ) + * lose the usual meaning. + * @param string $mode Should only apply this + * pattern when dealing with + * this type of input. + * @access public + */ + function addPattern($pattern, $mode = "accept") { + if (! isset($this->_regexes[$mode])) { + $this->_regexes[$mode] = new ParallelRegex($this->_case); + } + $this->_regexes[$mode]->addPattern($pattern); + if (! isset($this->_mode_handlers[$mode])) { + $this->_mode_handlers[$mode] = $mode; + } + } + + /** + * Adds a pattern that will enter a new parsing + * mode. Useful for entering parenthesis, strings, + * tags, etc. + * @param string $pattern Perl style regex, but ( and ) + * lose the usual meaning. + * @param string $mode Should only apply this + * pattern when dealing with + * this type of input. + * @param string $new_mode Change parsing to this new + * nested mode. + * @access public + */ + function addEntryPattern($pattern, $mode, $new_mode) { + if (! isset($this->_regexes[$mode])) { + $this->_regexes[$mode] = new ParallelRegex($this->_case); + } + $this->_regexes[$mode]->addPattern($pattern, $new_mode); + if (! isset($this->_mode_handlers[$new_mode])) { + $this->_mode_handlers[$new_mode] = $new_mode; + } + } + + /** + * Adds a pattern that will exit the current mode + * and re-enter the previous one. + * @param string $pattern Perl style regex, but ( and ) + * lose the usual meaning. + * @param string $mode Mode to leave. + * @access public + */ + function addExitPattern($pattern, $mode) { + if (! isset($this->_regexes[$mode])) { + $this->_regexes[$mode] = new ParallelRegex($this->_case); + } + $this->_regexes[$mode]->addPattern($pattern, "__exit"); + if (! isset($this->_mode_handlers[$mode])) { + $this->_mode_handlers[$mode] = $mode; + } + } + + /** + * Adds a pattern that has a special mode. Acts as an entry + * and exit pattern in one go, effectively calling a special + * parser handler for this token only. + * @param string $pattern Perl style regex, but ( and ) + * lose the usual meaning. + * @param string $mode Should only apply this + * pattern when dealing with + * this type of input. + * @param string $special Use this mode for this one token. + * @access public + */ + function addSpecialPattern($pattern, $mode, $special) { + if (! isset($this->_regexes[$mode])) { + $this->_regexes[$mode] = new ParallelRegex($this->_case); + } + $this->_regexes[$mode]->addPattern($pattern, "_$special"); + if (! isset($this->_mode_handlers[$special])) { + $this->_mode_handlers[$special] = $special; + } + } + + /** + * Adds a mapping from a mode to another handler. + * @param string $mode Mode to be remapped. + * @param string $handler New target handler. + * @access public + */ + function mapHandler($mode, $handler) { + $this->_mode_handlers[$mode] = $handler; + } + + /** + * Splits the page text into tokens. Will fail + * if the handlers report an error or if no + * content is consumed. If successful then each + * unparsed and parsed token invokes a call to the + * held listener. + * @param string $raw Raw HTML text. + * @return boolean True on success, else false. + * @access public + */ + function parse($raw) { + if (! isset($this->_parser)) { + return false; + } + $length = strlen($raw); + while (is_array($parsed = $this->_reduce($raw))) { + list($raw, $unmatched, $matched, $mode) = $parsed; + if (! $this->_dispatchTokens($unmatched, $matched, $mode)) { + return false; + } + if ($raw === '') { + return true; + } + if (strlen($raw) == $length) { + return false; + } + $length = strlen($raw); + } + if (! $parsed) { + return false; + } + return $this->_invokeParser($raw, LEXER_UNMATCHED); + } + + /** + * Sends the matched token and any leading unmatched + * text to the parser changing the lexer to a new + * mode if one is listed. + * @param string $unmatched Unmatched leading portion. + * @param string $matched Actual token match. + * @param string $mode Mode after match. A boolean + * false mode causes no change. + * @return boolean False if there was any error + * from the parser. + * @access private + */ + function _dispatchTokens($unmatched, $matched, $mode = false) { + if (! $this->_invokeParser($unmatched, LEXER_UNMATCHED)) { + return false; + } + if (is_bool($mode)) { + return $this->_invokeParser($matched, LEXER_MATCHED); + } + if ($this->_isModeEnd($mode)) { + if (! $this->_invokeParser($matched, LEXER_EXIT)) { + return false; + } + return $this->_mode->leave(); + } + if ($this->_isSpecialMode($mode)) { + $this->_mode->enter($this->_decodeSpecial($mode)); + if (! $this->_invokeParser($matched, LEXER_SPECIAL)) { + return false; + } + return $this->_mode->leave(); + } + $this->_mode->enter($mode); + return $this->_invokeParser($matched, LEXER_ENTER); + } + + /** + * Tests to see if the new mode is actually to leave + * the current mode and pop an item from the matching + * mode stack. + * @param string $mode Mode to test. + * @return boolean True if this is the exit mode. + * @access private + */ + function _isModeEnd($mode) { + return ($mode === "__exit"); + } + + /** + * Test to see if the mode is one where this mode + * is entered for this token only and automatically + * leaves immediately afterwoods. + * @param string $mode Mode to test. + * @return boolean True if this is the exit mode. + * @access private + */ + function _isSpecialMode($mode) { + return (strncmp($mode, "_", 1) == 0); + } + + /** + * Strips the magic underscore marking single token + * modes. + * @param string $mode Mode to decode. + * @return string Underlying mode name. + * @access private + */ + function _decodeSpecial($mode) { + return substr($mode, 1); + } + + /** + * Calls the parser method named after the current + * mode. Empty content will be ignored. The lexer + * has a parser handler for each mode in the lexer. + * @param string $content Text parsed. + * @param boolean $is_match Token is recognised rather + * than unparsed data. + * @access private + */ + function _invokeParser($content, $is_match) { + if (($content === '') || ($content === false)) { + return true; + } + $handler = $this->_mode_handlers[$this->_mode->getCurrent()]; + return $this->_parser->$handler($content, $is_match); + } + + /** + * Tries to match a chunk of text and if successful + * removes the recognised chunk and any leading + * unparsed data. Empty strings will not be matched. + * @param string $raw The subject to parse. This is the + * content that will be eaten. + * @return array/boolean Three item list of unparsed + * content followed by the + * recognised token and finally the + * action the parser is to take. + * True if no match, false if there + * is a parsing error. + * @access private + */ + function _reduce($raw) { + if ($action = $this->_regexes[$this->_mode->getCurrent()]->match($raw, $match)) { + $unparsed_character_count = strpos($raw, $match); + $unparsed = substr($raw, 0, $unparsed_character_count); + $raw = substr($raw, $unparsed_character_count + strlen($match)); + return array($raw, $unparsed, $match, $action); + } + return true; + } + } + + /** + * Breas HTML into SAX events. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleHtmlLexer extends SimpleLexer { + + /** + * Sets up the lexer with case insensitive matching + * and adds the HTML handlers. + * @param SimpleSaxParser $parser Handling strategy by + * reference. + * @access public + */ + function SimpleHtmlLexer(&$parser) { + $this->SimpleLexer($parser, 'text'); + $this->mapHandler('text', 'acceptTextToken'); + $this->_addSkipping(); + foreach ($this->_getParsedTags() as $tag) { + $this->_addTag($tag); + } + $this->_addInTagTokens(); + } + + /** + * List of parsed tags. Others are ignored. + * @return array List of searched for tags. + * @access private + */ + function _getParsedTags() { + return array('a', 'title', 'form', 'input', 'button', 'textarea', 'select', + 'option', 'frameset', 'frame', 'label'); + } + + /** + * The lexer has to skip certain sections such + * as server code, client code and styles. + * @access private + */ + 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 string $tag Name of tag to scan for. + * @access private + */ + 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. + * @access private + */ + function _addInTagTokens() { + $this->mapHandler('tag', 'acceptStartToken'); + $this->addSpecialPattern('\s+', 'tag', 'ignore'); + $this->_addAttributeTokens(); + $this->addExitPattern('/>', 'tag'); + $this->addExitPattern('>', 'tag'); + } + + /** + * Matches attributes that are either single quoted, + * double quoted or unquoted. + * @access private + */ + 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 { + var $_lexer; + var $_listener; + var $_tag; + var $_attributes; + var $_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 &createLexer(&$parser) { + $lexer = &new SimpleHtmlLexer($parser); + return $lexer; + } + + /** + * Accepts a token from the tag mode. If the + * starting element completes then the element + * is dispatched and the current attributes + * set back to empty. The element or attribute + * name is converted to lower case. + * @param string $token Incoming characters. + * @param integer $event Lexer event type. + * @return boolean False if parse error. + * @access public + */ + function acceptStartToken($token, $event) { + if ($event == LEXER_ENTER) { + $this->_tag = strtolower(substr($token, 1)); + return true; + } + if ($event == LEXER_EXIT) { + $success = $this->_listener->startElement( + $this->_tag, + $this->_attributes); + $this->_tag = ''; + $this->_attributes = array(); + return $success; + } + if ($token != '=') { + $this->_current_attribute = strtolower(SimpleHtmlSaxParser::decodeHtml($token)); + $this->_attributes[$this->_current_attribute] = ''; + } + return true; + } + + /** + * Accepts a token from the end tag mode. + * The element name is converted to lower case. + * @param string $token Incoming characters. + * @param integer $event Lexer event type. + * @return boolean False if parse error. + * @access public + */ + function acceptEndToken($token, $event) { + if (! preg_match('/<\/(.*)>/', $token, $matches)) { + return false; + } + return $this->_listener->endElement(strtolower($matches[1])); + } + + /** + * Part of the tag data. + * @param string $token Incoming characters. + * @param integer $event Lexer event type. + * @return boolean False if parse error. + * @access public + */ + function acceptAttributeToken($token, $event) { + if ($this->_current_attribute) { + if ($event == LEXER_UNMATCHED) { + $this->_attributes[$this->_current_attribute] .= + SimpleHtmlSaxParser::decodeHtml($token); + } + if ($event == LEXER_SPECIAL) { + $this->_attributes[$this->_current_attribute] .= + preg_replace('/^=\s*/' , '', SimpleHtmlSaxParser::decodeHtml($token)); + } + } + return true; + } + + /** + * A character entity. + * @param string $token Incoming characters. + * @param integer $event Lexer event type. + * @return boolean False if parse error. + * @access public + */ + function acceptEntityToken($token, $event) { + } + + /** + * Character data between tags regarded as + * important. + * @param string $token Incoming characters. + * @param integer $event Lexer event type. + * @return boolean False if parse error. + * @access public + */ + function acceptTextToken($token, $event) { + return $this->_listener->addContent($token); + } + + /** + * Incoming data to be ignored. + * @param string $token Incoming characters. + * @param integer $event Lexer event type. + * @return boolean False if parse error. + * @access public + */ + function ignore($token, $event) { + return true; + } + + /** + * Decodes any HTML entities. + * @param string $html Incoming HTML. + * @return string Outgoing plain text. + * @access public + * @static + */ + function decodeHtml($html) { + static $translations; + if (! isset($translations)) { + $translations = array_flip(get_html_translation_table(HTML_ENTITIES)); + } + return strtr($html, $translations); + } + + /** + * Turns HTML into text browser visible text. Images + * are converted to their alt text and tags are supressed. + * Entities are converted to their visible representation. + * @param string $html HTML to convert. + * @return string Plain text. + * @access public + * @static + */ + function normalise($html) { + $text = preg_replace('||', '', $html); + $text = preg_replace('||', ' \1 ', $text); + $text = preg_replace('||', ' \1 ', $text); + $text = preg_replace('||', ' \1 ', $text); + $text = preg_replace('|<.*?>|', '', $text); + $text = SimpleHtmlSaxParser::decodeHtml($text); + $text = preg_replace('|\s+|', ' ', $text); + return trim($text); + } + } + + /** + * SAX event handler. + * @package SimpleTest + * @subpackage WebTester + * @abstract + */ + class SimpleSaxListener { + + /** + * Sets the document to write to. + * @access public + */ + function SimpleSaxListener() { + } + + /** + * Start of element event. + * @param string $name Element name. + * @param hash $attributes Name value pairs. + * Attributes without content + * are marked as true. + * @return boolean False on parse error. + * @access public + */ + function startElement($name, $attributes) { + } + + /** + * End of element event. + * @param string $name Element name. + * @return boolean False on parse error. + * @access public + */ + function endElement($name) { + } + + /** + * Unparsed, but relevant data. + * @param string $text May include unparsed tags. + * @return boolean False on parse error. + * @access public + */ + function addContent($text) { + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/reflection_php4.php b/tests/simpletest/reflection_php4.php new file mode 100644 index 00000000..92936972 --- /dev/null +++ b/tests/simpletest/reflection_php4.php @@ -0,0 +1,126 @@ +_interface = $interface; + } + + /** + * Checks that a class has been declared. + * @return boolean True if defined. + * @access public + */ + function classExists() { + return class_exists($this->_interface); + } + + /** + * Needed to kill the autoload feature in PHP5 + * for classes created dynamically. + * @return boolean True if defined. + * @access public + */ + function classExistsSansAutoload() { + return class_exists($this->_interface); + } + + /** + * Checks that a class or interface has been + * declared. + * @return boolean True if defined. + * @access public + */ + function classOrInterfaceExists() { + return class_exists($this->_interface); + } + + /** + * Needed to kill the autoload feature in PHP5 + * for classes created dynamically. + * @return boolean True if defined. + * @access public + */ + function classOrInterfaceExistsSansAutoload() { + return class_exists($this->_interface); + } + + /** + * Gets the list of methods on a class or + * interface. + * @returns array List of method names. + * @access public + */ + function getMethods() { + return get_class_methods($this->_interface); + } + + /** + * Gets the list of interfaces from a class. If the + * class name is actually an interface then just that + * interface is returned. + * @returns array List of interfaces. + * @access public + */ + function getInterfaces() { + return array(); + } + + /** + * Finds the parent class name. + * @returns string Parent class name. + * @access public + */ + function getParent() { + return strtolower(get_parent_class($this->_interface)); + } + + /** + * Determines if the class is abstract, which for PHP 4 + * will never be the case. + * @returns boolean True if abstract. + * @access public + */ + function isAbstract() { + return false; + } + + /** + * Determines if the the entity is an interface, which for PHP 4 + * will never be the case. + * @returns boolean True if interface. + * @access public + */ + function isInterface() { + return false; + } + + /** + * 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/simpletest/reflection_php5.php b/tests/simpletest/reflection_php5.php new file mode 100644 index 00000000..3a8cf597 --- /dev/null +++ b/tests/simpletest/reflection_php5.php @@ -0,0 +1,293 @@ +_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(); + } + + /** + * Determines if the class is an interface. + * @returns boolean True if interface. + * @access public + */ + function isInterface() { + $reflection = new ReflectionClass($this->_interface); + return $reflection->isInterface(); + } + + /** + * Whittles 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(); + $blacklist = array(); + foreach ($interfaces as $interface) { + foreach($interfaces as $possible_parent) { + if ($interface->getName() == $possible_parent->getName()) { + continue; + } + if ($interface->isSubClassOf($possible_parent)) { + $blacklist[$possible_parent->getName()] = true; + } + } + if (!isset($blacklist[$interface->getName()])) { + $parents[] = $interface->getName(); + } + } + return $parents; + } + + /** + * 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 == '__set') { + return 'function __set($key, $value)'; + } + if ($name == '__call') { + return 'function __call($method, $arguments)'; + } + if (version_compare(phpversion(), '5.1.0', '>=')) { + if (in_array($name, array('__get', '__isset', $name == '__unset'))) { + return "function {$name}(\$key)"; + } + } + if (! 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; + } + } +?> diff --git a/tests/simpletest/remote.php b/tests/simpletest/remote.php new file mode 100644 index 00000000..45da7987 --- /dev/null +++ b/tests/simpletest/remote.php @@ -0,0 +1,117 @@ +_url = $url; + $this->_dry_url = $dry_url ? $dry_url : $url; + $this->_size = false; + } + + /** + * Accessor for the test name for subclasses. + * @return string Name of the test. + * @access public + */ + function getLabel() { + return $this->_url; + } + + /** + * Runs the top level test for this class. Currently + * reads the data as a single chunk. I'll fix this + * once I have added iteration to the browser. + * @param SimpleReporter $reporter Target of test results. + * @returns boolean True if no failures. + * @access public + */ + function run(&$reporter) { + $browser = &$this->_createBrowser(); + $xml = $browser->get($this->_url); + if (! $xml) { + trigger_error('Cannot read remote test URL [' . $this->_url . ']'); + return false; + } + $parser = &$this->_createParser($reporter); + if (! $parser->parse($xml)) { + trigger_error('Cannot parse incoming XML from [' . $this->_url . ']'); + return false; + } + return true; + } + + /** + * Creates a new web browser object for fetching + * the XML report. + * @return SimpleBrowser New browser. + * @access protected + */ + function &_createBrowser() { + $browser = &new SimpleBrowser(); + return $browser; + } + + /** + * Creates the XML parser. + * @param SimpleReporter $reporter Target of test results. + * @return SimpleTestXmlListener XML reader. + * @access protected + */ + function &_createParser(&$reporter) { + $parser = &new SimpleTestXmlParser($reporter); + return $parser; + } + + /** + * Accessor for the number of subtests. + * @return integer Number of test cases. + * @access public + */ + function getSize() { + if ($this->_size === false) { + $browser = &$this->_createBrowser(); + $xml = $browser->get($this->_dry_url); + if (! $xml) { + trigger_error('Cannot read remote test URL [' . $this->_dry_url . ']'); + return false; + } + $reporter = &new SimpleReporter(); + $parser = &$this->_createParser($reporter); + if (! $parser->parse($xml)) { + trigger_error('Cannot parse incoming XML from [' . $this->_dry_url . ']'); + return false; + } + $this->_size = $reporter->getTestCaseCount(); + } + return $this->_size; + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/reporter.php b/tests/simpletest/reporter.php new file mode 100644 index 00000000..8fe177cb --- /dev/null +++ b/tests/simpletest/reporter.php @@ -0,0 +1,426 @@ +SimpleReporter(); + $this->_character_set = $character_set; + } + + /** + * Paints the top of the web page setting the + * title to the name of the starting test. + * @param string $test_name Name class of test. + * @access public + */ + function paintHeader($test_name) { + $this->sendNoCacheHeaders(); + print ""; + print "\n\n$test_name\n"; + print "\n"; + print "\n"; + print "\n\n"; + print "

    $test_name

    \n"; + flush(); + } + + /** + * Send the headers necessary to ensure the page is + * reloaded on every request. Otherwise you could be + * scratching your head over out of date test data. + * @access public + * @static + */ + function sendNoCacheHeaders() { + if (! headers_sent()) { + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); + header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); + header("Cache-Control: no-store, no-cache, must-revalidate"); + header("Cache-Control: post-check=0, pre-check=0", false); + header("Pragma: no-cache"); + } + } + + /** + * Paints the CSS. Add additional styles here. + * @return string CSS code as text. + * @access protected + */ + function _getCss() { + return ".fail { background-color: inherit; color: red; }" . + ".pass { background-color: inherit; color: green; }" . + " pre { background-color: lightgray; color: inherit; }"; + } + + /** + * Paints the end of the test with a summary of + * the passes and failures. + * @param string $test_name Name class of test. + * @access public + */ + function paintFooter($test_name) { + $colour = ($this->getFailCount() + $this->getExceptionCount() > 0 ? "red" : "green"); + print "
    "; + print $this->getTestCaseProgress() . "/" . $this->getTestCaseCount(); + print " test cases complete:\n"; + print "" . $this->getPassCount() . " passes, "; + print "" . $this->getFailCount() . " fails and "; + print "" . $this->getExceptionCount() . " exceptions."; + print "
    \n"; + print "\n\n"; + } + + /** + * Paints the test failure with a breadcrumbs + * trail of the nesting test suites below the + * top level test. + * @param string $message Failure message displayed in + * the context of the other tests. + * @access public + */ + function paintFail($message) { + parent::paintFail($message); + print "Fail: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode(" -> ", $breadcrumb); + print " -> " . $this->_htmlEntities($message) . "
    \n"; + } + + /** + * Paints a PHP error. + * @param string $message Message is ignored. + * @access public + */ + function paintError($message) { + parent::paintError($message); + print "Exception: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode(" -> ", $breadcrumb); + print " -> " . $this->_htmlEntities($message) . "
    \n"; + } + + /** + * Paints a PHP exception. + * @param Exception $exception Exception to display. + * @access public + */ + function paintException($exception) { + parent::paintException($exception); + print "Exception: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode(" -> ", $breadcrumb); + $message = 'Unexpected exception of type [' . get_class($exception) . + '] with message ['. $exception->getMessage() . + '] in ['. $exception->getFile() . + ' line ' . $exception->getLine() . ']'; + print " -> " . $this->_htmlEntities($message) . "
    \n"; + } + + /** + * Prints the message for skipping tests. + * @param string $message Text of skip condition. + * @access public + */ + function paintSkip($message) { + parent::paintSkip($message); + print "Skipped: "; + $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. + * @access public + */ + function paintFormattedMessage($message) { + print '
    ' . $this->_htmlEntities($message) . '
    '; + } + + /** + * Character set adjusted entity conversion. + * @param string $message Plain text or Unicode message. + * @return string Browser readable message. + * @access protected + */ + function _htmlEntities($message) { + return htmlentities($message, ENT_COMPAT, $this->_character_set); + } + } + + /** + * Sample minimal test displayer. Generates only + * failure messages and a pass count. For command + * line use. I've tried to make it look like JUnit, + * but I wanted to output the errors as they arrived + * which meant dropping the dots. + * @package SimpleTest + * @subpackage UnitTester + */ + class TextReporter extends SimpleReporter { + + /** + * Does nothing yet. The first output will + * be sent on the first test start. + * @access public + */ + function TextReporter() { + $this->SimpleReporter(); + } + + /** + * Paints the title only. + * @param string $test_name Name class of test. + * @access public + */ + function paintHeader($test_name) { + if (! SimpleReporter::inCli()) { + header('Content-type: text/plain'); + } + print "$test_name\n"; + flush(); + } + + /** + * Paints the end of the test with a summary of + * the passes and failures. + * @param string $test_name Name class of test. + * @access public + */ + function paintFooter($test_name) { + if ($this->getFailCount() + $this->getExceptionCount() == 0) { + print "OK\n"; + } else { + print "FAILURES!!!\n"; + } + print "Test cases run: " . $this->getTestCaseProgress() . + "/" . $this->getTestCaseCount() . + ", Passes: " . $this->getPassCount() . + ", Failures: " . $this->getFailCount() . + ", Exceptions: " . $this->getExceptionCount() . "\n"; + } + + /** + * Paints the test failure as a stack trace. + * @param string $message Failure message displayed in + * the context of the other tests. + * @access public + */ + function paintFail($message) { + parent::paintFail($message); + print $this->getFailCount() . ") $message\n"; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); + print "\n"; + } + + /** + * Paints a PHP error or exception. + * @param string $message Message to be shown. + * @access public + * @abstract + */ + function paintError($message) { + parent::paintError($message); + print "Exception " . $this->getExceptionCount() . "!\n$message\n"; + } + + /** + * Paints a PHP error or exception. + * @param Exception $exception Exception to describe. + * @access public + * @abstract + */ + function paintException($exception) { + parent::paintException($exception); + $message = 'Unexpected exception of type [' . get_class($exception) . + '] with message ['. $exception->getMessage() . + '] in ['. $exception->getFile() . + ' line ' . $exception->getLine() . ']'; + print "Exception " . $this->getExceptionCount() . "!\n$message\n"; + } + + /** + * Prints the message for skipping tests. + * @param string $message Text of skip condition. + * @access public + */ + function paintSkip($message) { + parent::paintSkip($message); + print "Skip: $message\n"; + } + + /** + * Paints formatted text such as dumped variables. + * @param string $message Text to show. + * @access public + */ + function paintFormattedMessage($message) { + print "$message\n"; + flush(); + } + } + + /** + * Runs just a single test group, a single case or + * even a single test within that case. + * @package SimpleTest + * @subpackage UnitTester + */ + class SelectiveReporter extends SimpleReporterDecorator { + var $_just_this_case =false; + var $_just_this_test = false; + var $_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/simpletest/scorer.php b/tests/simpletest/scorer.php new file mode 100644 index 00000000..de6e4899 --- /dev/null +++ b/tests/simpletest/scorer.php @@ -0,0 +1,863 @@ +_passes = 0; + $this->_fails = 0; + $this->_exceptions = 0; + $this->_is_dry_run = false; + } + + /** + * Signals that the next evaluation will be a dry + * run. That is, the structure events will be + * recorded, but no tests will be run. + * @param boolean $is_dry Dry run if true. + * @access public + */ + function makeDry($is_dry = true) { + $this->_is_dry_run = $is_dry; + } + + /** + * The reporter has a veto on what should be run. + * @param string $test_case_name name of test case. + * @param string $method Name of test method. + * @access public + */ + function shouldInvoke($test_case_name, $method) { + return ! $this->_is_dry_run; + } + + /** + * Can wrap the invoker in preperation for running + * a test. + * @param SimpleInvoker $invoker Individual test runner. + * @return SimpleInvoker Wrapped test runner. + * @access public + */ + function &createInvoker(&$invoker) { + return $invoker; + } + + /** + * Accessor for current status. Will be false + * if there have been any failures or exceptions. + * Used for command line tools. + * @return boolean True if no failures. + * @access public + */ + function getStatus() { + if ($this->_exceptions + $this->_fails > 0) { + return false; + } + return true; + } + + /** + * Paints the start of a group test. + * @param string $test_name Name of test or other label. + * @param integer $size Number of test cases starting. + * @access public + */ + function paintGroupStart($test_name, $size) { + } + + /** + * Paints the end of a group test. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintGroupEnd($test_name) { + } + + /** + * Paints the start of a test case. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintCaseStart($test_name) { + } + + /** + * Paints the end of a test case. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintCaseEnd($test_name) { + } + + /** + * Paints the start of a test method. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintMethodStart($test_name) { + } + + /** + * Paints the end of a test method. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintMethodEnd($test_name) { + } + + /** + * Increments the pass count. + * @param string $message Message is ignored. + * @access public + */ + function paintPass($message) { + $this->_passes++; + } + + /** + * Increments the fail count. + * @param string $message Message is ignored. + * @access public + */ + function paintFail($message) { + $this->_fails++; + } + + /** + * Deals with PHP 4 throwing an error. + * @param string $message Text of error formatted by + * the test case. + * @access public + */ + function paintError($message) { + $this->_exceptions++; + } + + /** + * Deals with PHP 5 throwing an exception. + * @param Exception $exception The actual exception thrown. + * @access public + */ + function paintException($exception) { + $this->_exceptions++; + } + + /** + * Prints the message for skipping tests. + * @param string $message Text of skip condition. + * @access public + */ + function paintSkip($message) { + } + + /** + * Accessor for the number of passes so far. + * @return integer Number of passes. + * @access public + */ + function getPassCount() { + return $this->_passes; + } + + /** + * Accessor for the number of fails so far. + * @return integer Number of fails. + * @access public + */ + function getFailCount() { + return $this->_fails; + } + + /** + * Accessor for the number of untrapped errors + * so far. + * @return integer Number of exceptions. + * @access public + */ + function getExceptionCount() { + return $this->_exceptions; + } + + /** + * Paints a simple supplementary message. + * @param string $message Text to display. + * @access public + */ + function paintMessage($message) { + } + + /** + * Paints a formatted ASCII message such as a + * variable dump. + * @param string $message Text to display. + * @access public + */ + function paintFormattedMessage($message) { + } + + /** + * By default just ignores user generated events. + * @param string $type Event type as text. + * @param mixed $payload Message or object. + * @access public + */ + function paintSignal($type, $payload) { + } + } + + /** + * Recipient of generated test messages that can display + * page footers and headers. Also keeps track of the + * test nesting. This is the main base class on which + * to build the finished test (page based) displays. + * @package SimpleTest + * @subpackage UnitTester + */ + class SimpleReporter extends SimpleScorer { + var $_test_stack; + var $_size; + var $_progress; + + /** + * Starts the display with no results in. + * @access public + */ + function SimpleReporter() { + $this->SimpleScorer(); + $this->_test_stack = array(); + $this->_size = null; + $this->_progress = 0; + } + + /** + * Gets the formatter for variables and other small + * generic data items. + * @return SimpleDumper Formatter. + * @access public + */ + function getDumper() { + return new SimpleDumper(); + } + + /** + * Paints the start of a group test. Will also paint + * the page header and footer if this is the + * first test. Will stash the size if the first + * start. + * @param string $test_name Name of test that is starting. + * @param integer $size Number of test cases starting. + * @access public + */ + function paintGroupStart($test_name, $size) { + if (! isset($this->_size)) { + $this->_size = $size; + } + if (count($this->_test_stack) == 0) { + $this->paintHeader($test_name); + } + $this->_test_stack[] = $test_name; + } + + /** + * Paints the end of a group test. Will paint the page + * footer if the stack of tests has unwound. + * @param string $test_name Name of test that is ending. + * @param integer $progress Number of test cases ending. + * @access public + */ + function paintGroupEnd($test_name) { + array_pop($this->_test_stack); + if (count($this->_test_stack) == 0) { + $this->paintFooter($test_name); + } + } + + /** + * Paints the start of a test case. Will also paint + * the page header and footer if this is the + * first test. Will stash the size if the first + * start. + * @param string $test_name Name of test that is starting. + * @access public + */ + function paintCaseStart($test_name) { + if (! isset($this->_size)) { + $this->_size = 1; + } + if (count($this->_test_stack) == 0) { + $this->paintHeader($test_name); + } + $this->_test_stack[] = $test_name; + } + + /** + * Paints the end of a test case. Will paint the page + * footer if the stack of tests has unwound. + * @param string $test_name Name of test that is ending. + * @access public + */ + function paintCaseEnd($test_name) { + $this->_progress++; + array_pop($this->_test_stack); + if (count($this->_test_stack) == 0) { + $this->paintFooter($test_name); + } + } + + /** + * Paints the start of a test method. + * @param string $test_name Name of test that is starting. + * @access public + */ + function paintMethodStart($test_name) { + $this->_test_stack[] = $test_name; + } + + /** + * Paints the end of a test method. Will paint the page + * footer if the stack of tests has unwound. + * @param string $test_name Name of test that is ending. + * @access public + */ + function paintMethodEnd($test_name) { + array_pop($this->_test_stack); + } + + /** + * Paints the test document header. + * @param string $test_name First test top level + * to start. + * @access public + * @abstract + */ + function paintHeader($test_name) { + } + + /** + * Paints the test document footer. + * @param string $test_name The top level test. + * @access public + * @abstract + */ + function paintFooter($test_name) { + } + + /** + * Accessor for internal test stack. For + * subclasses that need to see the whole test + * history for display purposes. + * @return array List of methods in nesting order. + * @access public + */ + function getTestList() { + return $this->_test_stack; + } + + /** + * Accessor for total test size in number + * of test cases. Null until the first + * test is started. + * @return integer Total number of cases at start. + * @access public + */ + function getTestCaseCount() { + return $this->_size; + } + + /** + * Accessor for the number of test cases + * completed so far. + * @return integer Number of ended cases. + * @access public + */ + function getTestCaseProgress() { + return $this->_progress; + } + + /** + * Static check for running in the comand line. + * @return boolean True if CLI. + * @access public + * @static + */ + function inCli() { + return php_sapi_name() == 'cli'; + } + } + + /** + * For modifying the behaviour of the visual reporters. + * @package SimpleTest + * @subpackage UnitTester + */ + class SimpleReporterDecorator { + var $_reporter; + + /** + * Mediates between the 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); + } + + /** + * Gets the formatter for variables and other small + * generic data items. + * @return SimpleDumper Formatter. + * @access public + */ + function getDumper() { + return $this->_reporter->getDumper(); + } + + /** + * Paints the start of a group test. + * @param string $test_name Name of test or other label. + * @param integer $size Number of test cases starting. + * @access public + */ + function paintGroupStart($test_name, $size) { + $this->_reporter->paintGroupStart($test_name, $size); + } + + /** + * Paints the end of a group test. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintGroupEnd($test_name) { + $this->_reporter->paintGroupEnd($test_name); + } + + /** + * Paints the start of a test case. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintCaseStart($test_name) { + $this->_reporter->paintCaseStart($test_name); + } + + /** + * Paints the end of a test case. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintCaseEnd($test_name) { + $this->_reporter->paintCaseEnd($test_name); + } + + /** + * Paints the start of a test method. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintMethodStart($test_name) { + $this->_reporter->paintMethodStart($test_name); + } + + /** + * Paints the end of a test method. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintMethodEnd($test_name) { + $this->_reporter->paintMethodEnd($test_name); + } + + /** + * Chains to the wrapped reporter. + * @param string $message Message is ignored. + * @access public + */ + function paintPass($message) { + $this->_reporter->paintPass($message); + } + + /** + * Chains to the wrapped reporter. + * @param string $message Message is ignored. + * @access public + */ + function paintFail($message) { + $this->_reporter->paintFail($message); + } + + /** + * Chains to the wrapped reporter. + * @param string $message Text of error formatted by + * the test case. + * @access public + */ + function paintError($message) { + $this->_reporter->paintError($message); + } + + /** + * Chains to the wrapped reporter. + * @param Exception $exception Exception to show. + * @access public + */ + function paintException($exception) { + $this->_reporter->paintException($exception); + } + + /** + * Prints the message for skipping tests. + * @param string $message Text of skip condition. + * @access public + */ + function paintSkip($message) { + $this->_reporter->paintSkip($message); + } + + /** + * Chains to the wrapped reporter. + * @param string $message Text to display. + * @access public + */ + function paintMessage($message) { + $this->_reporter->paintMessage($message); + } + + /** + * Chains to the wrapped reporter. + * @param string $message Text to display. + * @access public + */ + function paintFormattedMessage($message) { + $this->_reporter->paintFormattedMessage($message); + } + + /** + * Chains to the wrapped reporter. + * @param string $type Event type as text. + * @param mixed $payload Message or object. + * @return boolean Should return false if this + * type of signal should fail the + * test suite. + * @access public + */ + function paintSignal($type, &$payload) { + $this->_reporter->paintSignal($type, $payload); + } + } + + /** + * For sending messages to multiple reporters at + * the same time. + * @package SimpleTest + * @subpackage UnitTester + */ + class MultipleReporter { + var $_reporters = array(); + + /** + * Adds a reporter to the subscriber list. + * @param SimpleScorer $reporter Reporter to receive events. + * @access public + */ + function attachReporter(&$reporter) { + $this->_reporters[] = &$reporter; + } + + /** + * Signals that the next evaluation will be a dry + * run. That is, the structure events will be + * recorded, but no tests will be run. + * @param boolean $is_dry Dry run if true. + * @access public + */ + function makeDry($is_dry = true) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->makeDry($is_dry); + } + } + + /** + * Accessor for current status. Will be false + * if there have been any failures or exceptions. + * If any reporter reports a failure, the whole + * suite fails. + * @return boolean True if no failures. + * @access public + */ + function getStatus() { + for ($i = 0; $i < count($this->_reporters); $i++) { + if (! $this->_reporters[$i]->getStatus()) { + return false; + } + } + return true; + } + + /** + * The reporter has a veto on what should be run. + * It requires all reporters to want to run the method. + * @param string $test_case_name name of test case. + * @param string $method Name of test method. + * @access public + */ + function shouldInvoke($test_case_name, $method) { + for ($i = 0; $i < count($this->_reporters); $i++) { + if (! $this->_reporters[$i]->shouldInvoke($test_case_name, $method)) { + return false; + } + } + return true; + } + + /** + * Every reporter gets a chance to wrap the invoker. + * @param SimpleInvoker $invoker Individual test runner. + * @return SimpleInvoker Wrapped test runner. + * @access public + */ + function &createInvoker(&$invoker) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $invoker = &$this->_reporters[$i]->createInvoker($invoker); + } + return $invoker; + } + + /** + * Gets the formatter for variables and other small + * generic data items. + * @return SimpleDumper Formatter. + * @access public + */ + function getDumper() { + return new SimpleDumper(); + } + + /** + * Paints the start of a group test. + * @param string $test_name Name of test or other label. + * @param integer $size Number of test cases starting. + * @access public + */ + function paintGroupStart($test_name, $size) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintGroupStart($test_name, $size); + } + } + + /** + * Paints the end of a group test. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintGroupEnd($test_name) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintGroupEnd($test_name); + } + } + + /** + * Paints the start of a test case. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintCaseStart($test_name) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintCaseStart($test_name); + } + } + + /** + * Paints the end of a test case. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintCaseEnd($test_name) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintCaseEnd($test_name); + } + } + + /** + * Paints the start of a test method. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintMethodStart($test_name) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintMethodStart($test_name); + } + } + + /** + * Paints the end of a test method. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintMethodEnd($test_name) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintMethodEnd($test_name); + } + } + + /** + * Chains to the wrapped reporter. + * @param string $message Message is ignored. + * @access public + */ + function paintPass($message) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintPass($message); + } + } + + /** + * Chains to the wrapped reporter. + * @param string $message Message is ignored. + * @access public + */ + function paintFail($message) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintFail($message); + } + } + + /** + * Chains to the wrapped reporter. + * @param string $message Text of error formatted by + * the test case. + * @access public + */ + function paintError($message) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintError($message); + } + } + + /** + * Chains to the wrapped reporter. + * @param Exception $exception Exception to display. + * @access public + */ + function paintException($exception) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintException($exception); + } + } + + /** + * Prints the message for skipping tests. + * @param string $message Text of skip condition. + * @access public + */ + function paintSkip($message) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintSkip($message); + } + } + + /** + * Chains to the wrapped reporter. + * @param string $message Text to display. + * @access public + */ + function paintMessage($message) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintMessage($message); + } + } + + /** + * Chains to the wrapped reporter. + * @param string $message Text to display. + * @access public + */ + function paintFormattedMessage($message) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintFormattedMessage($message); + } + } + + /** + * Chains to the wrapped reporter. + * @param string $type Event type as text. + * @param mixed $payload Message or object. + * @return boolean Should return false if this + * type of signal should fail the + * test suite. + * @access public + */ + function paintSignal($type, &$payload) { + for ($i = 0; $i < count($this->_reporters); $i++) { + $this->_reporters[$i]->paintSignal($type, $payload); + } + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/selector.php b/tests/simpletest/selector.php new file mode 100644 index 00000000..72800090 --- /dev/null +++ b/tests/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 { + var $_label; + + /** + * Stashes the name for later comparison. + * @param string $label Visible text to match. + */ + function SimpleByLabel($label) { + $this->_label = $label; + } + + /** + * Comparison. Compares visible text of widget or + * related label. + * @param SimpleWidget $widget Control to compare. + * @access public + */ + function isMatch($widget) { + if (! method_exists($widget, 'isLabel')) { + return false; + } + return $widget->isLabel($this->_label); + } + } + + /** + * Used to extract form elements for testing against. + * Searches dy id attribute. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleById { + var $_id; + + /** + * Stashes the name for later comparison. + * @param string $id ID atribute to match. + */ + function SimpleById($id) { + $this->_id = $id; + } + + /** + * Comparison. Compares id attribute of widget. + * @param SimpleWidget $widget Control to compare. + * @access public + */ + function isMatch($widget) { + return $widget->isId($this->_id); + } + } + + /** + * Used to extract form elements for testing against. + * Searches by visible label, name or alt text. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleByLabelOrName { + var $_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/simpletest/shell_tester.php b/tests/simpletest/shell_tester.php new file mode 100644 index 00000000..e245eda7 --- /dev/null +++ b/tests/simpletest/shell_tester.php @@ -0,0 +1,333 @@ +_output = false; + } + + /** + * Actually runs the command. Does not trap the + * error stream output as this need PHP 4.3+. + * @param string $command The actual command line + * to run. + * @return integer Exit code. + * @access public + */ + function execute($command) { + $this->_output = false; + exec($command, $this->_output, $ret); + return $ret; + } + + /** + * Accessor for the last output. + * @return string Output as text. + * @access public + */ + function getOutput() { + return implode("\n", $this->_output); + } + + /** + * Accessor for the last output. + * @return array Output as array of lines. + * @access public + */ + function getOutputAsList() { + return $this->_output; + } + } + + /** + * Test case for testing of command line scripts and + * utilities. Usually scripts that are external to the + * PHP code, but support it in some way. + * @package SimpleTest + * @subpackage UnitTester + */ + class ShellTestCase extends SimpleTestCase { + var $_current_shell; + var $_last_status; + var $_last_command; + + /** + * Creates an empty test case. Should be subclassed + * with test methods for a functional test case. + * @param string $label Name of test case. Will use + * the class name if none specified. + * @access public + */ + function ShellTestCase($label = false) { + $this->SimpleTestCase($label); + $this->_current_shell = &$this->_createShell(); + $this->_last_status = false; + $this->_last_command = ''; + } + + /** + * Executes a command and buffers the results. + * @param string $command Command to run. + * @return boolean True if zero exit code. + * @access public + */ + function execute($command) { + $shell = &$this->_getShell(); + $this->_last_status = $shell->execute($command); + $this->_last_command = $command; + return ($this->_last_status === 0); + } + + /** + * Dumps the output of the last command. + * @access public + */ + function dumpOutput() { + $this->dump($this->getOutput()); + } + + /** + * Accessor for the last output. + * @return string Output as text. + * @access public + */ + function getOutput() { + $shell = &$this->_getShell(); + return $shell->getOutput(); + } + + /** + * Accessor for the last output. + * @return array Output as array of lines. + * @access public + */ + function getOutputAsList() { + $shell = &$this->_getShell(); + return $shell->getOutputAsList(); + } + + /** + * Called from within the test methods to register + * passes and failures. + * @param boolean $result Pass on true. + * @param string $message Message to display describing + * the test state. + * @return boolean True on pass + * @access public + */ + function assertTrue($result, $message = false) { + return $this->assert(new TrueExpectation(), $result, $message); + } + + /** + * Will be true on false and vice versa. False + * is the PHP definition of false, so that null, + * empty strings, zero and an empty array all count + * as false. + * @param boolean $result Pass on false. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertFalse($result, $message = '%s') { + return $this->assert(new FalseExpectation(), $result, $message); + } + + /** + * Will trigger a pass if the two parameters have + * the same value only. Otherwise a fail. This + * is for testing hand extracted text, etc. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertEqual($first, $second, $message = "%s") { + return $this->assert( + new EqualExpectation($first), + $second, + $message); + } + + /** + * Will trigger a pass if the two parameters have + * a different value. Otherwise a fail. This + * is for testing hand extracted text, etc. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertNotEqual($first, $second, $message = "%s") { + return $this->assert( + new NotEqualExpectation($first), + $second, + $message); + } + + /** + * Tests the last status code from the shell. + * @param integer $status Expected status of last + * command. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertExitCode($status, $message = "%s") { + $message = sprintf($message, "Expected status code of [$status] from [" . + $this->_last_command . "], but got [" . + $this->_last_status . "]"); + return $this->assertTrue($status === $this->_last_status, $message); + } + + /** + * Attempt to exactly match the combined STDERR and + * STDOUT output. + * @param string $expected Expected output. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertOutput($expected, $message = "%s") { + $shell = &$this->_getShell(); + return $this->assert( + new EqualExpectation($expected), + $shell->getOutput(), + $message); + } + + /** + * Scans the output for a Perl regex. If found + * anywhere it passes, else it fails. + * @param string $pattern Regex to search for. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertOutputPattern($pattern, $message = "%s") { + $shell = &$this->_getShell(); + return $this->assert( + new PatternExpectation($pattern), + $shell->getOutput(), + $message); + } + + /** + * If a Perl regex is found anywhere in the current + * output then a failure is generated, else a pass. + * @param string $pattern Regex to search for. + * @param $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertNoOutputPattern($pattern, $message = "%s") { + $shell = &$this->_getShell(); + return $this->assert( + new NoPatternExpectation($pattern), + $shell->getOutput(), + $message); + } + + /** + * File existence check. + * @param string $path Full filename and path. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertFileExists($path, $message = "%s") { + $message = sprintf($message, "File [$path] should exist"); + return $this->assertTrue(file_exists($path), $message); + } + + /** + * File non-existence check. + * @param string $path Full filename and path. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertFileNotExists($path, $message = "%s") { + $message = sprintf($message, "File [$path] should not exist"); + return $this->assertFalse(file_exists($path), $message); + } + + /** + * Scans a file for a Perl regex. If found + * anywhere it passes, else it fails. + * @param string $pattern Regex to search for. + * @param string $path Full filename and path. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertFilePattern($pattern, $path, $message = "%s") { + $shell = &$this->_getShell(); + return $this->assert( + new PatternExpectation($pattern), + implode('', file($path)), + $message); + } + + /** + * If a Perl regex is found anywhere in the named + * file then a failure is generated, else a pass. + * @param string $pattern Regex to search for. + * @param string $path Full filename and path. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertNoFilePattern($pattern, $path, $message = "%s") { + $shell = &$this->_getShell(); + return $this->assert( + new NoPatternExpectation($pattern), + implode('', file($path)), + $message); + } + + /** + * Accessor for current shell. Used for testing the + * the tester itself. + * @return Shell Current shell. + * @access protected + */ + function &_getShell() { + return $this->_current_shell; + } + + /** + * Factory for the shell to run the command on. + * @return Shell New shell object. + * @access protected + */ + function &_createShell() { + $shell = &new SimpleShell(); + return $shell; + } + } +?> diff --git a/tests/simpletest/simpletest.php b/tests/simpletest/simpletest.php new file mode 100644 index 00000000..8e2760e0 --- /dev/null +++ b/tests/simpletest/simpletest.php @@ -0,0 +1,436 @@ += 0) { + require_once(dirname(__FILE__) . '/reflection_php5.php'); + } else { + require_once(dirname(__FILE__) . '/reflection_php4.php'); + } + /**#@-*/ + + /** + * Registry and test context. Includes a few + * global options that I'm slowly getting rid of. + * @package SimpleTest + * @subpackage UnitTester + */ + class SimpleTest { + + /** + * Reads the SimpleTest version from the release file. + * @return string Version string. + * @static + * @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 just nice to have the ignore() + * calls at the top of the file before the actual declarations. + * @param array $classes Class names of interest. + * @static + * @access public + */ + function ignoreParentsIfIgnored($classes) { + $registry = &SimpleTest::_getRegistry(); + 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']; + } + + /** + * 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; + } + + /** + * Accessor for the context of the current + * test run. + * @return SimpleTestContext Current test run. + * @access public + * @static + */ + function &getContext() { + static $context = false; + if (! $context) { + $context = new SimpleTestContext(); + } + return $context; + } + + /** + * 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); + } + } + + /** + * Container for all components for a specific + * test run. Makes things like error queues + * available to PHP event handlers, and also + * gets around some nasty reference issues in + * the mocks. + * @package SimpleTest + */ + class SimpleTestContext { + var $_test; + var $_reporter; + var $_resources; + + /** + * Clears down the current context. + * @access public + */ + function clear() { + $this->_resources = array(); + } + + /** + * Sets the current test case instance. This + * global instance can be used by the mock objects + * to send message to the test cases. + * @param SimpleTestCase $test Test case to register. + * @access public + */ + function setTest(&$test) { + $this->clear(); + $this->_test = &$test; + } + + /** + * Accessor for currently running test case. + * @return SimpleTestCase Current test. + * @access public + */ + function &getTest() { + return $this->_test; + } + + /** + * Sets the current reporter. This + * global instance can be used by the mock objects + * to send messages. + * @param SimpleReporter $reporter Reporter to register. + * @access public + */ + function setReporter(&$reporter) { + $this->clear(); + $this->_reporter = &$reporter; + } + + /** + * Accessor for current reporter. + * @return SimpleReporter Current reporter. + * @access public + */ + function &getReporter() { + return $this->_reporter; + } + + /** + * Accessor for the Singleton resource. + * @return object Global resource. + * @access public + * @static + */ + function &get($resource) { + if (! isset($this->_resources[$resource])) { + $this->_resources[$resource] = &new $resource(); + } + return $this->_resources[$resource]; + } + } + + /** + * Interrogates the stack trace to recover the + * failure point. + * @package SimpleTest + * @subpackage UnitTester + */ + class SimpleStackTrace { + var $_prefixes; + + /** + * Stashes the list of target prefixes. + * @param array $prefixes List of method prefixes + * to search for. + */ + function SimpleStackTrace($prefixes) { + $this->_prefixes = $prefixes; + } + + /** + * Extracts the last method name that was not within + * Simpletest itself. Captures a stack trace if none given. + * @param array $stack List of stack frames. + * @return string Snippet of test report with line + * number and file. + * @access public + */ + function traceMethod($stack = false) { + $stack = $stack ? $stack : $this->_captureTrace(); + foreach ($stack as $frame) { + if ($this->_frameLiesWithinSimpleTestFolder($frame)) { + continue; + } + if ($this->_frameMatchesPrefix($frame)) { + return ' at [' . $frame['file'] . ' line ' . $frame['line'] . ']'; + } + } + return ''; + } + + /** + * Test to see if error is generated by SimpleTest itself. + * @param array $frame PHP stack frame. + * @return boolean True if a SimpleTest file. + * @access private + */ + function _frameLiesWithinSimpleTestFolder($frame) { + if (isset($frame['file'])) { + $path = substr(SIMPLE_TEST, 0, -1); + if (strpos($frame['file'], $path) === 0) { + if (dirname($frame['file']) == $path) { + return true; + } + } + } + return false; + } + + /** + * Tries to determine if the method call is an assert, etc. + * @param array $frame PHP stack frame. + * @return boolean True if matches a target. + * @access private + */ + function _frameMatchesPrefix($frame) { + foreach ($this->_prefixes as $prefix) { + if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) { + return true; + } + } + return false; + } + + /** + * Grabs a current stack trace. + * @return array Fulle trace. + * @access private + */ + function _captureTrace() { + if (function_exists('debug_backtrace')) { + return array_reverse(debug_backtrace()); + } + return array(); + } + } + + /** + * @package SimpleTest + * @subpackage UnitTester + * @deprecated + */ + class SimpleTestOptions extends SimpleTest { + + /** + * @deprecated + */ + function getVersion() { + return Simpletest::getVersion(); + } + + /** + * @deprecated + */ + function ignore($class) { + return Simpletest::ignore($class); + } + + /** + * @deprecated + */ + function isIgnored($class) { + return Simpletest::isIgnored($class); + } + + /** + * @deprecated + */ + function setMockBaseClass($mock_base) { + return Simpletest::setMockBaseClass($mock_base); + } + + /** + * @deprecated + */ + function getMockBaseClass() { + return Simpletest::getMockBaseClass(); + } + + /** + * @deprecated + */ + function useProxy($proxy, $username = false, $password = false) { + return Simpletest::useProxy($proxy, $username, $password); + } + + /** + * @deprecated + */ + function getDefaultProxy() { + return Simpletest::getDefaultProxy(); + } + + /** + * @deprecated + */ + function getDefaultProxyUsername() { + return Simpletest::getDefaultProxyUsername(); + } + + /** + * @deprecated + */ + function getDefaultProxyPassword() { + return Simpletest::getDefaultProxyPassword(); + } + } +?> diff --git a/tests/simpletest/socket.php b/tests/simpletest/socket.php new file mode 100644 index 00000000..23de6305 --- /dev/null +++ b/tests/simpletest/socket.php @@ -0,0 +1,216 @@ +_clearError(); + } + + /** + * Test for an outstanding error. + * @return boolean True if there is an error. + * @access public + */ + function isError() { + return ($this->_error != ''); + } + + /** + * Accessor for an outstanding error. + * @return string Empty string if no error otherwise + * the error message. + * @access public + */ + function getError() { + return $this->_error; + } + + /** + * Sets the internal error. + * @param string Error message to stash. + * @access protected + */ + function _setError($error) { + $this->_error = $error; + } + + /** + * Resets the error state to no error. + * @access protected + */ + function _clearError() { + $this->_setError(''); + } + } + + /** + * Wrapper for TCP/IP socket. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleSocket extends SimpleStickyError { + var $_handle; + var $_is_open = false; + var $_sent = ''; + var $lock_size; + + /** + * Opens a socket for reading and writing. + * @param string $host Hostname to send request to. + * @param integer $port Port on remote machine to open. + * @param integer $timeout Connection timeout in seconds. + * @param integer $block_size Size of chunk to read. + * @access public + */ + function SimpleSocket($host, $port, $timeout, $block_size = 255) { + $this->SimpleStickyError(); + if (! ($this->_handle = $this->_openSocket($host, $port, $error_number, $error, $timeout))) { + $this->_setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds"); + return; + } + $this->_is_open = true; + $this->_block_size = $block_size; + SimpleTestCompatibility::setTimeout($this->_handle, $timeout); + } + + /** + * Writes some data to the socket and saves alocal copy. + * @param string $message String to send to socket. + * @return boolean True if successful. + * @access public + */ + function write($message) { + if ($this->isError() || ! $this->isOpen()) { + return false; + } + $count = fwrite($this->_handle, $message); + if (! $count) { + if ($count === false) { + $this->_setError('Cannot write to socket'); + $this->close(); + } + return false; + } + fflush($this->_handle); + $this->_sent .= $message; + return true; + } + + /** + * Reads data from the socket. The error suppresion + * is a workaround for PHP4 always throwing a warning + * with a secure socket. + * @return integer/boolean Incoming bytes. False + * on error. + * @access public + */ + function read() { + if ($this->isError() || ! $this->isOpen()) { + return false; + } + $raw = @fread($this->_handle, $this->_block_size); + if ($raw === false) { + $this->_setError('Cannot read from socket'); + $this->close(); + } + return $raw; + } + + /** + * Accessor for socket open state. + * @return boolean True if open. + * @access public + */ + function isOpen() { + return $this->_is_open; + } + + /** + * Closes the socket preventing further reads. + * Cannot be reopened once closed. + * @return boolean True if successful. + * @access public + */ + function close() { + $this->_is_open = false; + return fclose($this->_handle); + } + + /** + * Accessor for content so far. + * @return string Bytes sent only. + * @access public + */ + function getSent() { + return $this->_sent; + } + + /** + * Actually opens the low level socket. + * @param string $host Host to connect to. + * @param integer $port Port on host. + * @param integer $error_number Recipient of error code. + * @param string $error Recipoent of error message. + * @param integer $timeout Maximum time to wait for connection. + * @access protected + */ + function _openSocket($host, $port, &$error_number, &$error, $timeout) { + return @fsockopen($host, $port, $error_number, $error, $timeout); + } + } + + /** + * Wrapper for TCP/IP socket over TLS. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleSecureSocket extends SimpleSocket { + + /** + * Opens a secure socket for reading and writing. + * @param string $host Hostname to send request to. + * @param integer $port Port on remote machine to open. + * @param integer $timeout Connection timeout in seconds. + * @access public + */ + function SimpleSecureSocket($host, $port, $timeout) { + $this->SimpleSocket($host, $port, $timeout); + } + + /** + * Actually opens the low level socket. + * @param string $host Host to connect to. + * @param integer $port Port on host. + * @param integer $error_number Recipient of error code. + * @param string $error Recipient of error message. + * @param integer $timeout Maximum time to wait for connection. + * @access protected + */ + function _openSocket($host, $port, &$error_number, &$error, $timeout) { + return parent::_openSocket("tls://$host", $port, $error_number, $error, $timeout); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/tag.php b/tests/simpletest/tag.php new file mode 100644 index 00000000..9439441d --- /dev/null +++ b/tests/simpletest/tag.php @@ -0,0 +1,1392 @@ +_name = strtolower(trim($name)); + $this->_attributes = $attributes; + $this->_content = ''; + } + + /** + * Check to see if the tag can have both start and + * end tags with content in between. + * @return boolean True if content allowed. + * @access public + */ + function expectEndTag() { + return true; + } + + /** + * The current tag should not swallow all content for + * itself as it's searchable page content. Private + * content tags are usually widgets that contain default + * values. + * @return boolean False as content is available + * to other tags by default. + * @access public + */ + function isPrivateContent() { + return false; + } + + /** + * Appends string content to the current content. + * @param string $content Additional text. + * @access public + */ + function addContent($content) { + $this->_content .= (string)$content; + } + + /** + * Adds an enclosed tag to the content. + * @param SimpleTag $tag New tag. + * @access public + */ + function addTag(&$tag) { + } + + /** + * Accessor for tag name. + * @return string Name of tag. + * @access public + */ + function getTagName() { + return $this->_name; + } + + /** + * List of legal child elements. + * @return array List of element names. + * @access public + */ + function getChildElements() { + return array(); + } + + /** + * Accessor for an attribute. + * @param string $label Attribute name. + * @return string Attribute value. + * @access public + */ + function getAttribute($label) { + $label = strtolower($label); + if (! isset($this->_attributes[$label])) { + return false; + } + return (string)$this->_attributes[$label]; + } + + /** + * Sets an attribute. + * @param string $label Attribute name. + * @return string $value New attribute value. + * @access protected + */ + function _setAttribute($label, $value) { + $this->_attributes[strtolower($label)] = $value; + } + + /** + * Accessor for the whole content so far. + * @return string Content as big raw string. + * @access public + */ + function getContent() { + return $this->_content; + } + + /** + * Accessor for content reduced to visible text. Acts + * like a text mode browser, normalising space and + * reducing images to their alt text. + * @return string Content as plain text. + * @access public + */ + function getText() { + return SimpleHtmlSaxParser::normalise($this->_content); + } + + /** + * Test to see if id attribute matches. + * @param string $id ID to test against. + * @return boolean True on match. + * @access public + */ + function isId($id) { + return ($this->getAttribute('id') == $id); + } + } + + /** + * Page title. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleTitleTag extends SimpleTag { + + /** + * Starts with a named tag with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleTitleTag($attributes) { + $this->SimpleTag('title', $attributes); + } + } + + /** + * Link. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleAnchorTag extends SimpleTag { + + /** + * Starts with a named tag with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleAnchorTag($attributes) { + $this->SimpleTag('a', $attributes); + } + + /** + * Accessor for URL as string. + * @return string Coerced as string. + * @access public + */ + function getHref() { + $url = $this->getAttribute('href'); + if (is_bool($url)) { + $url = ''; + } + return $url; + } + } + + /** + * Form element. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleWidget extends SimpleTag { + var $_value; + var $_label; + var $_is_set; + + /** + * Starts with a named tag with attributes only. + * @param string $name Tag name. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleWidget($name, $attributes) { + $this->SimpleTag($name, $attributes); + $this->_value = false; + $this->_label = false; + $this->_is_set = false; + } + + /** + * Accessor for name submitted as the key in + * GET/POST variables hash. + * @return string Parsed value. + * @access public + */ + function getName() { + return $this->getAttribute('name'); + } + + /** + * Accessor for default value parsed with the tag. + * @return string Parsed value. + * @access public + */ + function getDefault() { + return $this->getAttribute('value'); + } + + /** + * Accessor for currently set value or default if + * none. + * @return string Value set by form or default + * if none. + * @access public + */ + function getValue() { + if (! $this->_is_set) { + return $this->getDefault(); + } + return $this->_value; + } + + /** + * Sets the current form element value. + * @param string $value New value. + * @return boolean True if allowed. + * @access public + */ + function setValue($value) { + $this->_value = $value; + $this->_is_set = true; + return true; + } + + /** + * Resets the form element value back to the + * default. + * @access public + */ + function resetValue() { + $this->_is_set = false; + } + + /** + * Allows setting of a label externally, say by a + * label tag. + * @param string $label Label to attach. + * @access public + */ + function setLabel($label) { + $this->_label = trim($label); + } + + /** + * Reads external or internal label. + * @param string $label Label to test. + * @return boolean True is match. + * @access public + */ + function isLabel($label) { + return $this->_label == trim($label); + } + + /** + * Dispatches the value into the form encoded packet. + * @param SimpleEncoding $encoding Form packet. + * @access public + */ + function write(&$encoding) { + if ($this->getName()) { + $encoding->add($this->getName(), $this->getValue()); + } + } + } + + /** + * Text, password and hidden field. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleTextTag extends SimpleWidget { + + /** + * Starts with a named tag with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleTextTag($attributes) { + $this->SimpleWidget('input', $attributes); + if ($this->getAttribute('value') === false) { + $this->_setAttribute('value', ''); + } + } + + /** + * Tag contains no content. + * @return boolean False. + * @access public + */ + function expectEndTag() { + return false; + } + + /** + * Sets the current form element value. Cannot + * change the value of a hidden field. + * @param string $value New value. + * @return boolean True if allowed. + * @access public + */ + function setValue($value) { + if ($this->getAttribute('type') == 'hidden') { + return false; + } + return parent::setValue($value); + } + } + + /** + * Submit button as input tag. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleSubmitTag extends SimpleWidget { + + /** + * Starts with a named tag with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleSubmitTag($attributes) { + $this->SimpleWidget('input', $attributes); + if ($this->getAttribute('value') === false) { + $this->_setAttribute('value', 'Submit'); + } + } + + /** + * Tag contains no end element. + * @return boolean False. + * @access public + */ + function expectEndTag() { + return false; + } + + /** + * Disables the setting of the button value. + * @param string $value Ignored. + * @return boolean True if allowed. + * @access public + */ + function setValue($value) { + return false; + } + + /** + * Value of browser visible text. + * @return string Visible label. + * @access public + */ + function getLabel() { + return $this->getValue(); + } + + /** + * Test for a label match when searching. + * @param string $label Label to test. + * @return boolean True on match. + * @access public + */ + function isLabel($label) { + return trim($label) == trim($this->getLabel()); + } + } + + /** + * Image button as input tag. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleImageSubmitTag extends SimpleWidget { + + /** + * Starts with a named tag with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleImageSubmitTag($attributes) { + $this->SimpleWidget('input', $attributes); + } + + /** + * Tag contains no end element. + * @return boolean False. + * @access public + */ + function expectEndTag() { + return false; + } + + /** + * Disables the setting of the button value. + * @param string $value Ignored. + * @return boolean True if allowed. + * @access public + */ + function setValue($value) { + return false; + } + + /** + * Value of browser visible text. + * @return string Visible label. + * @access public + */ + function getLabel() { + if ($this->getAttribute('title')) { + return $this->getAttribute('title'); + } + return $this->getAttribute('alt'); + } + + /** + * Test for a label match when searching. + * @param string $label Label to test. + * @return boolean True on match. + * @access public + */ + function isLabel($label) { + return trim($label) == trim($this->getLabel()); + } + + /** + * Dispatches the value into the form encoded packet. + * @param SimpleEncoding $encoding Form packet. + * @param integer $x X coordinate of click. + * @param integer $y Y coordinate of click. + * @access public + */ + function write(&$encoding, $x, $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); + } + } + } + + /** + * Submit button as button tag. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleButtonTag extends SimpleWidget { + + /** + * Starts with a named tag with attributes only. + * Defaults are very browser dependent. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleButtonTag($attributes) { + $this->SimpleWidget('button', $attributes); + } + + /** + * Check to see if the tag can have both start and + * end tags with content in between. + * @return boolean True if content allowed. + * @access public + */ + function expectEndTag() { + return true; + } + + /** + * Disables the setting of the button value. + * @param string $value Ignored. + * @return boolean True if allowed. + * @access public + */ + function setValue($value) { + return false; + } + + /** + * Value of browser visible text. + * @return string Visible label. + * @access public + */ + function getLabel() { + return $this->getContent(); + } + + /** + * Test for a label match when searching. + * @param string $label Label to test. + * @return boolean True on match. + * @access public + */ + function isLabel($label) { + return trim($label) == trim($this->getLabel()); + } + } + + /** + * Content tag for text area. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleTextAreaTag extends SimpleWidget { + + /** + * Starts with a named tag with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleTextAreaTag($attributes) { + $this->SimpleWidget('textarea', $attributes); + } + + /** + * Accessor for starting value. + * @return string Parsed value. + * @access public + */ + function getDefault() { + return $this->_wrap(SimpleHtmlSaxParser::decodeHtml($this->getContent())); + } + + /** + * Applies word wrapping if needed. + * @param string $value New value. + * @return boolean True if allowed. + * @access public + */ + function setValue($value) { + return parent::setValue($this->_wrap($value)); + } + + /** + * Test to see if text should be wrapped. + * @return boolean True if wrapping on. + * @access private + */ + function _wrapIsEnabled() { + if ($this->getAttribute('cols')) { + $wrap = $this->getAttribute('wrap'); + if (($wrap == 'physical') || ($wrap == 'hard')) { + return true; + } + } + return false; + } + + /** + * Performs the formatting that is peculiar to + * this tag. There is strange behaviour in this + * one, including stripping a leading new line. + * Go figure. I am using Firefox as a guide. + * @param string $text Text to wrap. + * @return string Text wrapped with carriage + * returns and line feeds + * @access private + */ + function _wrap($text) { + $text = str_replace("\r\r\n", "\r\n", str_replace("\n", "\r\n", $text)); + $text = str_replace("\r\n\n", "\r\n", str_replace("\r", "\r\n", $text)); + if (strncmp($text, "\r\n", strlen("\r\n")) == 0) { + $text = substr($text, strlen("\r\n")); + } + if ($this->_wrapIsEnabled()) { + return wordwrap( + $text, + (integer)$this->getAttribute('cols'), + "\r\n"); + } + return $text; + } + + /** + * The content of textarea is not part of the page. + * @return boolean True. + * @access public + */ + function isPrivateContent() { + return true; + } + } + + /** + * File upload widget. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleUploadTag extends SimpleWidget { + + /** + * Starts with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleUploadTag($attributes) { + $this->SimpleWidget('input', $attributes); + } + + /** + * Tag contains no content. + * @return boolean False. + * @access public + */ + function expectEndTag() { + return false; + } + + /** + * Dispatches the value into the form encoded packet. + * @param SimpleEncoding $encoding Form packet. + * @access public + */ + function write(&$encoding) { + if (! file_exists($this->getValue())) { + return; + } + $encoding->attach( + $this->getName(), + implode('', file($this->getValue())), + basename($this->getValue())); + } + } + + /** + * Drop down widget. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleSelectionTag extends SimpleWidget { + var $_options; + var $_choice; + + /** + * Starts with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleSelectionTag($attributes) { + $this->SimpleWidget('select', $attributes); + $this->_options = array(); + $this->_choice = false; + } + + /** + * Adds an option tag to a selection field. + * @param SimpleOptionTag $tag New option. + * @access public + */ + function addTag(&$tag) { + if ($tag->getTagName() == 'option') { + $this->_options[] = &$tag; + } + } + + /** + * Text within the selection element is ignored. + * @param string $content Ignored. + * @access public + */ + function addContent($content) { + } + + /** + * Scans options for defaults. If none, then + * the first option is selected. + * @return string Selected field. + * @access public + */ + function getDefault() { + for ($i = 0, $count = count($this->_options); $i < $count; $i++) { + if ($this->_options[$i]->getAttribute('selected') !== false) { + return $this->_options[$i]->getDefault(); + } + } + if ($count > 0) { + return $this->_options[0]->getDefault(); + } + return ''; + } + + /** + * Can only set allowed values. + * @param string $value New choice. + * @return boolean True if allowed. + * @access public + */ + function setValue($value) { + for ($i = 0, $count = count($this->_options); $i < $count; $i++) { + if ($this->_options[$i]->isValue($value)) { + $this->_choice = $i; + return true; + } + } + return false; + } + + /** + * Accessor for current selection value. + * @return string Value attribute or + * content of opton. + * @access public + */ + function getValue() { + if ($this->_choice === false) { + return $this->getDefault(); + } + return $this->_options[$this->_choice]->getValue(); + } + } + + /** + * Drop down widget. + * @package SimpleTest + * @subpackage WebTester + */ + class MultipleSelectionTag extends SimpleWidget { + var $_options; + var $_values; + + /** + * Starts with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function MultipleSelectionTag($attributes) { + $this->SimpleWidget('select', $attributes); + $this->_options = array(); + $this->_values = false; + } + + /** + * Adds an option tag to a selection field. + * @param SimpleOptionTag $tag New option. + * @access public + */ + function addTag(&$tag) { + if ($tag->getTagName() == 'option') { + $this->_options[] = &$tag; + } + } + + /** + * Text within the selection element is ignored. + * @param string $content Ignored. + * @access public + */ + function addContent($content) { + } + + /** + * Scans options for defaults to populate the + * value array(). + * @return array Selected fields. + * @access public + */ + function getDefault() { + $default = array(); + for ($i = 0, $count = count($this->_options); $i < $count; $i++) { + if ($this->_options[$i]->getAttribute('selected') !== false) { + $default[] = $this->_options[$i]->getDefault(); + } + } + return $default; + } + + /** + * Can only set allowed values. Any illegal value + * will result in a failure, but all correct values + * will be set. + * @param array $desired New choices. + * @return boolean True if all allowed. + * @access public + */ + function setValue($desired) { + $achieved = array(); + foreach ($desired as $value) { + $success = false; + for ($i = 0, $count = count($this->_options); $i < $count; $i++) { + if ($this->_options[$i]->isValue($value)) { + $achieved[] = $this->_options[$i]->getValue(); + $success = true; + break; + } + } + if (! $success) { + return false; + } + } + $this->_values = $achieved; + return true; + } + + /** + * Accessor for current selection value. + * @return array List of currently set options. + * @access public + */ + function getValue() { + if ($this->_values === false) { + return $this->getDefault(); + } + return $this->_values; + } + } + + /** + * Option for selection field. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleOptionTag extends SimpleWidget { + + /** + * Stashes the attributes. + */ + function SimpleOptionTag($attributes) { + $this->SimpleWidget('option', $attributes); + } + + /** + * Does nothing. + * @param string $value Ignored. + * @return boolean Not allowed. + * @access public + */ + function setValue($value) { + return false; + } + + /** + * Test to see if a value matches the option. + * @param string $compare Value to compare with. + * @return boolean True if possible match. + * @access public + */ + function isValue($compare) { + $compare = trim($compare); + if (trim($this->getValue()) == $compare) { + return true; + } + return trim($this->getContent()) == $compare; + } + + /** + * Accessor for starting value. Will be set to + * the option label if no value exists. + * @return string Parsed value. + * @access public + */ + function getDefault() { + if ($this->getAttribute('value') === false) { + return $this->getContent(); + } + return $this->getAttribute('value'); + } + + /** + * The content of options is not part of the page. + * @return boolean True. + * @access public + */ + function isPrivateContent() { + return true; + } + } + + /** + * Radio button. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleRadioButtonTag extends SimpleWidget { + + /** + * Stashes the attributes. + * @param array $attributes Hash of attributes. + */ + function SimpleRadioButtonTag($attributes) { + $this->SimpleWidget('input', $attributes); + if ($this->getAttribute('value') === false) { + $this->_setAttribute('value', 'on'); + } + } + + /** + * Tag contains no content. + * @return boolean False. + * @access public + */ + function expectEndTag() { + return false; + } + + /** + * The only allowed value sn the one in the + * "value" attribute. + * @param string $value New value. + * @return boolean True if allowed. + * @access public + */ + function setValue($value) { + if ($value === false) { + return parent::setValue($value); + } + if ($value !== $this->getAttribute('value')) { + return false; + } + return parent::setValue($value); + } + + /** + * Accessor for starting value. + * @return string Parsed value. + * @access public + */ + function getDefault() { + if ($this->getAttribute('checked') !== false) { + return $this->getAttribute('value'); + } + return false; + } + } + + /** + * Checkbox widget. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleCheckboxTag extends SimpleWidget { + + /** + * Starts with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function 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 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 { + var $_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; + } + + /** + * Accessor for an attribute. + * @param string $label Attribute name. + * @return boolean Always false. + * @access public + */ + function getAttribute($label) { + return false; + } + + /** + * Fetches the name for the widget from the first + * member. + * @return string Name of widget. + * @access public + */ + function getName() { + if (count($this->_widgets) > 0) { + return $this->_widgets[0]->getName(); + } + } + + /** + * Scans the widgets for one with the appropriate + * ID field. + * @param string $id ID value to try. + * @return boolean True if matched. + * @access public + */ + function isId($id) { + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($this->_widgets[$i]->isId($id)) { + return true; + } + } + return false; + } + + /** + * Scans the widgets for one with the appropriate + * attached label. + * @param string $label Attached label to try. + * @return boolean True if matched. + * @access public + */ + function isLabel($label) { + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($this->_widgets[$i]->isLabel($label)) { + return true; + } + } + return false; + } + + /** + * Dispatches the value into the form encoded packet. + * @param SimpleEncoding $encoding Form packet. + * @access public + */ + function write(&$encoding) { + $encoding->add($this->getName(), $this->getValue()); + } + } + + /** + * A group of tags with the same name within a form. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleCheckboxGroup extends SimpleTagGroup { + + /** + * Accessor for current selected widget or false + * if none. + * @return string/array Widget values or false if none. + * @access public + */ + function getValue() { + $values = array(); + $widgets = &$this->_getWidgets(); + for ($i = 0, $count = count($widgets); $i < $count; $i++) { + if ($widgets[$i]->getValue() !== false) { + $values[] = $widgets[$i]->getValue(); + } + } + return $this->_coerceValues($values); + } + + /** + * Accessor for starting value that is active. + * @return string/array Widget values or false if none. + * @access public + */ + function getDefault() { + $values = array(); + $widgets = &$this->_getWidgets(); + for ($i = 0, $count = count($widgets); $i < $count; $i++) { + if ($widgets[$i]->getDefault() !== false) { + $values[] = $widgets[$i]->getDefault(); + } + } + return $this->_coerceValues($values); + } + + /** + * Accessor for current set values. + * @param string/array/boolean $values Either a single string, a + * hash or false for nothing set. + * @return boolean True if all values can be set. + * @access public + */ + function setValue($values) { + $values = $this->_makeArray($values); + if (! $this->_valuesArePossible($values)) { + return false; + } + $widgets = &$this->_getWidgets(); + for ($i = 0, $count = count($widgets); $i < $count; $i++) { + $possible = $widgets[$i]->getAttribute('value'); + if (in_array($widgets[$i]->getAttribute('value'), $values)) { + $widgets[$i]->setValue($possible); + } else { + $widgets[$i]->setValue(false); + } + } + return true; + } + + /** + * Tests to see if a possible value set is legal. + * @param string/array/boolean $values Either a single string, a + * hash or false for nothing set. + * @return boolean False if trying to set a + * missing value. + * @access private + */ + function _valuesArePossible($values) { + $matches = array(); + $widgets = &$this->_getWidgets(); + for ($i = 0, $count = count($widgets); $i < $count; $i++) { + $possible = $widgets[$i]->getAttribute('value'); + if (in_array($possible, $values)) { + $matches[] = $possible; + } + } + return ($values == $matches); + } + + /** + * Converts the output to an appropriate format. This means + * that no values is false, a single value is just that + * value and only two or more are contained in an array. + * @param array $values List of values of widgets. + * @return string/array/boolean Expected format for a tag. + * @access private + */ + function _coerceValues($values) { + if (count($values) == 0) { + return false; + } elseif (count($values) == 1) { + return $values[0]; + } else { + return $values; + } + } + + /** + * Converts false or string into array. The opposite of + * the coercian method. + * @param string/array/boolean $value A single item is converted + * to a one item list. False + * gives an empty list. + * @return array List of values, possibly empty. + * @access private + */ + function _makeArray($value) { + if ($value === false) { + return array(); + } + if (is_string($value)) { + return array($value); + } + return $value; + } + } + + /** + * A group of tags with the same name within a form. + * Used for radio buttons. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleRadioGroup extends SimpleTagGroup { + + /** + * Each tag is tried in turn until one is + * successfully set. The others will be + * unchecked if successful. + * @param string $value New value. + * @return boolean True if any allowed. + * @access public + */ + function setValue($value) { + if (! $this->_valueIsPossible($value)) { + return false; + } + $index = false; + $widgets = &$this->_getWidgets(); + for ($i = 0, $count = count($widgets); $i < $count; $i++) { + if (! $widgets[$i]->setValue($value)) { + $widgets[$i]->setValue(false); + } + } + return true; + } + + /** + * Tests to see if a value is allowed. + * @param string Attempted value. + * @return boolean True if a valid value. + * @access private + */ + function _valueIsPossible($value) { + $widgets = &$this->_getWidgets(); + for ($i = 0, $count = count($widgets); $i < $count; $i++) { + if ($widgets[$i]->getAttribute('value') == $value) { + return true; + } + } + return false; + } + + /** + * Accessor for current selected widget or false + * if none. + * @return string/boolean Value attribute or + * content of opton. + * @access public + */ + function getValue() { + $widgets = &$this->_getWidgets(); + for ($i = 0, $count = count($widgets); $i < $count; $i++) { + if ($widgets[$i]->getValue() !== false) { + return $widgets[$i]->getValue(); + } + } + return false; + } + + /** + * Accessor for starting value that is active. + * @return string/boolean Value of first checked + * widget or false if none. + * @access public + */ + function getDefault() { + $widgets = &$this->_getWidgets(); + for ($i = 0, $count = count($widgets); $i < $count; $i++) { + if ($widgets[$i]->getDefault() !== false) { + return $widgets[$i]->getDefault(); + } + } + return false; + } + } + + /** + * Tag to keep track of labels. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleLabelTag extends SimpleTag { + + /** + * Starts with a named tag with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function 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 + * @subpackage WebTester + */ + class SimpleFormTag extends SimpleTag { + + /** + * Starts with a named tag with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleFormTag($attributes) { + $this->SimpleTag('form', $attributes); + } + } + + /** + * Tag to aid parsing the frames in a page. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleFrameTag extends SimpleTag { + + /** + * Starts with a named tag with attributes only. + * @param hash $attributes Attribute names and + * string values. + */ + function SimpleFrameTag($attributes) { + $this->SimpleTag('frame', $attributes); + } + + /** + * Tag contains no content. + * @return boolean False. + * @access public + */ + function expectEndTag() { + return false; + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/acceptance_test.php b/tests/simpletest/test/acceptance_test.php new file mode 100644 index 00000000..2f56211e --- /dev/null +++ b/tests/simpletest/test/acceptance_test.php @@ -0,0 +1,1511 @@ +addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + $this->assertTrue($browser->get('http://www.lastcraft.com/test/network_confirm.php')); + $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); + $this->assertPattern('/Request method.*?
    GET<\/dd>/', $browser->getContent()); + $this->assertEqual($browser->getTitle(), 'Simple test target file'); + $this->assertEqual($browser->getResponseCode(), 200); + $this->assertEqual($browser->getMimeType(), 'text/html'); + } + + function testPost() { + $browser = &new SimpleBrowser(); + $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + $this->assertTrue($browser->post('http://www.lastcraft.com/test/network_confirm.php')); + $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); + $this->assertPattern('/Request method.*?
    POST<\/dd>/', $browser->getContent()); + } + + function testAbsoluteLinkFollowing() { + $browser = &new SimpleBrowser(); + $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + $browser->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($browser->clickLink('Absolute')); + $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); + } + + function testRelativeLinkFollowing() { + $browser = &new SimpleBrowser(); + $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + $browser->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($browser->clickLink('Relative')); + $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); + } + + function testUnifiedClickLinkClicking() { + $browser = &new SimpleBrowser(); + $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + $browser->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($browser->click('Relative')); + $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); + } + + function testIdLinkFollowing() { + $browser = &new SimpleBrowser(); + $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + $browser->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($browser->clickLinkById(1)); + $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); + } + + function testCookieReading() { + $browser = &new SimpleBrowser(); + $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + $browser->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->assertEqual($browser->getCurrentCookieValue('session_cookie'), 'A'); + $this->assertEqual($browser->getCurrentCookieValue('short_cookie'), 'B'); + $this->assertEqual($browser->getCurrentCookieValue('day_cookie'), 'C'); + } + + function testSimpleSubmit() { + $browser = &new SimpleBrowser(); + $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + $browser->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($browser->clickSubmit('Go!')); + $this->assertPattern('/Request method.*?
    POST<\/dd>/', $browser->getContent()); + $this->assertPattern('/go=\[Go!\]/', $browser->getContent()); + } + + function testUnifiedClickCanSubmit() { + $browser = &new SimpleBrowser(); + $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + $browser->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($browser->click('Go!')); + $this->assertPattern('/go=\[Go!\]/', $browser->getContent()); + } + } + + class TestOfLiveFetching extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testGet() { + $this->assertTrue($this->get('http://www.lastcraft.com/test/network_confirm.php')); + $this->assertEqual($this->getUrl(), 'http://www.lastcraft.com/test/network_confirm.php'); + $this->assertText('target for the SimpleTest'); + $this->assertPattern('/Request method.*?
    GET<\/dd>/'); + $this->assertTitle('Simple test target file'); + $this->assertTitle(new PatternExpectation('/target file/')); + $this->assertResponse(200); + $this->assertMime('text/html'); + $this->assertHeader('connection', 'close'); + $this->assertHeader('connection', new PatternExpectation('/los/')); + } + + function testSlowGet() { + $this->assertTrue($this->get('http://www.lastcraft.com/test/slow_page.php')); + } + + function testTimedOutGet() { + $this->setConnectionTimeout(1); + $this->ignoreErrors(); + $this->assertFalse($this->get('http://www.lastcraft.com/test/slow_page.php')); + } + + function testPost() { + $this->assertTrue($this->post('http://www.lastcraft.com/test/network_confirm.php')); + $this->assertText('target for the SimpleTest'); + $this->assertPattern('/Request method.*?
    POST<\/dd>/'); + } + + function testGetWithData() { + $this->get('http://www.lastcraft.com/test/network_confirm.php', array("a" => "aaa")); + $this->assertPattern('/Request method.*?
    GET<\/dd>/'); + $this->assertText('a=[aaa]'); + } + + function testPostWithData() { + $this->post('http://www.lastcraft.com/test/network_confirm.php', array("a" => "aaa")); + $this->assertPattern('/Request method.*?
    POST<\/dd>/'); + $this->assertText('a=[aaa]'); + } + + function testRelativeGet() { + $this->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($this->get('network_confirm.php')); + $this->assertText('target for the SimpleTest'); + } + + function testRelativePost() { + $this->post('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($this->post('network_confirm.php')); + $this->assertText('target for the SimpleTest'); + } + + function testLinkAssertions() { + $this->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertLink('Absolute', 'http://www.lastcraft.com/test/network_confirm.php'); + $this->assertLink('Absolute', new PatternExpectation('/confirm/')); + $this->assertClickable('Absolute'); + } + + function testAbsoluteLinkFollowing() { + $this->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($this->clickLink('Absolute')); + $this->assertText('target for the SimpleTest'); + } + + function testRelativeLinkFollowing() { + $this->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($this->clickLink('Relative')); + $this->assertText('target for the SimpleTest'); + } + + function testLinkIdFollowing() { + $this->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertLinkById(1); + $this->assertTrue($this->clickLinkById(1)); + $this->assertText('target for the SimpleTest'); + } + + function testAbsoluteUrlBehavesAbsolutely() { + $this->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->get('http://www.lastcraft.com'); + $this->assertText('No guarantee of quality is given or even intended'); + } + } + + class TestOfLivePageLinkingWithMinimalLinks extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testClickToExplicitelyNamedSelfReturns() { + $this->get('http://www.lastcraft.com/test/front_controller_style/a_page.php'); + $this->assertEqual($this->getUrl(), 'http://www.lastcraft.com/test/front_controller_style/a_page.php'); + $this->assertTitle('Simple test page with links'); + $this->assertLink('Self'); + $this->clickLink('Self'); + $this->assertTitle('Simple test page with links'); + } + + function testClickToMissingPageReturnsToSamePage() { + $this->get('http://www.lastcraft.com/test/front_controller_style/a_page.php'); + $this->clickLink('No page'); + $this->assertTitle('Simple test page with links'); + $this->assertText('[action=no_page]'); + } + + function testClickToBareActionReturnsToSamePage() { + $this->get('http://www.lastcraft.com/test/front_controller_style/a_page.php'); + $this->clickLink('Bare action'); + $this->assertTitle('Simple test page with links'); + $this->assertText('[action=]'); + } + + function testClickToSingleQuestionMarkReturnsToSamePage() { + $this->get('http://www.lastcraft.com/test/front_controller_style/a_page.php'); + $this->clickLink('Empty query'); + $this->assertTitle('Simple test page with links'); + } + + function testClickToEmptyStringReturnsToSamePage() { + $this->get('http://www.lastcraft.com/test/front_controller_style/a_page.php'); + $this->clickLink('Empty link'); + $this->assertTitle('Simple test page with links'); + } + + function testClickToSingleDotGoesToCurrentDirectory() { + $this->get('http://www.lastcraft.com/test/front_controller_style/a_page.php'); + $this->clickLink('Current directory'); + $this->assertTitle('Simple test front controller'); + } + + function testClickBackADirectoryLevel() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickLink('Down one'); + $this->assertText('Index of /test'); + } + } + + class TestOfLiveFrontControllerEmulation extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testJumpToNamedPage() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->assertText('Simple test front controller'); + $this->clickLink('Index'); + $this->assertResponse(200); + $this->assertText('[action=index]'); + } + + function testJumpToUnnamedPage() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickLink('No page'); + $this->assertResponse(200); + $this->assertText('Simple test front controller'); + $this->assertText('[action=no_page]'); + } + + function testJumpToUnnamedPageWithBareParameter() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickLink('Bare action'); + $this->assertResponse(200); + $this->assertText('Simple test front controller'); + $this->assertText('[action=]'); + } + + function testJumpToUnnamedPageWithEmptyQuery() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickLink('Empty query'); + $this->assertResponse(200); + $this->assertPattern('/Simple test front controller/'); + $this->assertPattern('/raw get data.*?\[\].*?get data/si'); + } + + function testJumpToUnnamedPageWithEmptyLink() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickLink('Empty link'); + $this->assertResponse(200); + $this->assertPattern('/Simple test front controller/'); + $this->assertPattern('/raw get data.*?\[\].*?get data/si'); + } + + function testJumpBackADirectoryLevel() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickLink('Down one'); + $this->assertText('Index of /test'); + } + + function testSubmitToNamedPage() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->assertText('Simple test front controller'); + $this->clickSubmit('Index'); + $this->assertResponse(200); + $this->assertText('[action=Index]'); + } + + function testSubmitToSameDirectory() { + $this->get('http://www.lastcraft.com/test/front_controller_style/index.php'); + $this->clickSubmit('Same directory'); + $this->assertResponse(200); + $this->assertText('[action=Same+directory]'); + } + + function testSubmitToEmptyAction() { + $this->get('http://www.lastcraft.com/test/front_controller_style/index.php'); + $this->clickSubmit('Empty action'); + $this->assertResponse(200); + $this->assertText('[action=Empty+action]'); + } + + function testSubmitToNoAction() { + $this->get('http://www.lastcraft.com/test/front_controller_style/index.php'); + $this->clickSubmit('No action'); + $this->assertResponse(200); + $this->assertText('[action=No+action]'); + } + + function testSubmitBackADirectoryLevel() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickSubmit('Down one'); + $this->assertText('Index of /test'); + } + + function testSubmitToNamedPageWithMixedPostAndGet() { + $this->get('http://www.lastcraft.com/test/front_controller_style/?a=A'); + $this->assertText('Simple test front controller'); + $this->clickSubmit('Index post'); + $this->assertText('action=[Index post]'); + $this->assertNoText('[a=A]'); + } + + function testSubmitToSameDirectoryMixedPostAndGet() { + $this->get('http://www.lastcraft.com/test/front_controller_style/index.php?a=A'); + $this->clickSubmit('Same directory post'); + $this->assertText('action=[Same directory post]'); + $this->assertNoText('[a=A]'); + } + + function testSubmitToEmptyActionMixedPostAndGet() { + $this->get('http://www.lastcraft.com/test/front_controller_style/index.php?a=A'); + $this->clickSubmit('Empty action post'); + $this->assertText('action=[Empty action post]'); + $this->assertText('[a=A]'); + } + + function testSubmitToNoActionMixedPostAndGet() { + $this->get('http://www.lastcraft.com/test/front_controller_style/index.php?a=A'); + $this->clickSubmit('No action post'); + $this->assertText('action=[No action post]'); + $this->assertText('[a=A]'); + } + } + + class TestOfLiveHeaders extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testConfirmingHeaderExistence() { + $this->get('http://www.lastcraft.com/'); + $this->assertHeader('content-type'); + $this->assertHeader('content-type', 'text/html'); + $this->assertHeaderPattern('content-type', '/HTML/i'); + $this->assertNoHeader('WWW-Authenticate'); + } + } + + class TestOfLiveRedirects extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testNoRedirects() { + $this->setMaximumRedirects(0); + $this->get('http://www.lastcraft.com/test/redirect.php'); + $this->assertTitle('Redirection test'); + } + + function testRedirects() { + $this->setMaximumRedirects(1); + $this->get('http://www.lastcraft.com/test/redirect.php'); + $this->assertTitle('Simple test target file'); + } + + function testRedirectLosesGetData() { + $this->get('http://www.lastcraft.com/test/redirect.php', array('a' => 'aaa')); + $this->assertNoText('a=[aaa]'); + } + + function testRedirectKeepsExtraRequestDataOfItsOwn() { + $this->get('http://www.lastcraft.com/test/redirect.php'); + $this->assertText('r=[rrr]'); + } + + function testRedirectLosesPostData() { + $this->post('http://www.lastcraft.com/test/redirect.php', array('a' => 'aaa')); + $this->assertTitle('Simple test target file'); + $this->assertNoText('a=[aaa]'); + } + + function testRedirectWithBaseUrlChange() { + $this->get('http://www.lastcraft.com/test/base_change_redirect.php'); + $this->assertTitle('Simple test target file in folder'); + $this->get('http://www.lastcraft.com/test/path/base_change_redirect.php'); + $this->assertTitle('Simple test target file'); + } + + function testRedirectWithDoubleBaseUrlChange() { + $this->get('http://www.lastcraft.com/test/double_base_change_redirect.php'); + $this->assertTitle('Simple test target file'); + } + } + + class TestOfLiveCookies extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testCookieSettingAndAssertions() { + $this->setCookie('a', 'Test cookie a'); + $this->setCookie('b', 'Test cookie b', 'www.lastcraft.com'); + $this->setCookie('c', 'Test cookie c', 'www.lastcraft.com', 'test'); + $this->get('http://www.lastcraft.com/test/network_confirm.php'); + $this->assertText('Test cookie a'); + $this->assertText('Test cookie b'); + $this->assertText('Test cookie c'); + $this->assertCookie('a'); + $this->assertCookie('b', 'Test cookie b'); + $this->assertTrue($this->getCookie('c') == 'Test cookie c'); + } + + function testNoCookieSetWhenCookiesDisabled() { + $this->setCookie('a', 'Test cookie a'); + $this->ignoreCookies(); + $this->get('http://www.lastcraft.com/test/network_confirm.php'); + $this->assertNoText('Test cookie a'); + } + + function testCookieReading() { + $this->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->assertCookie('session_cookie', 'A'); + $this->assertCookie('short_cookie', 'B'); + $this->assertCookie('day_cookie', 'C'); + } + + function testNoCookieReadingWhenCookiesDisabled() { + $this->ignoreCookies(); + $this->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->assertNoCookie('session_cookie'); + $this->assertNoCookie('short_cookie'); + $this->assertNoCookie('day_cookie'); + } + + function testCookiePatternAssertions() { + $this->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->assertCookie('session_cookie', new PatternExpectation('/a/i')); + } + + function testTemporaryCookieExpiry() { + $this->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->restart(); + $this->assertNoCookie('session_cookie'); + $this->assertCookie('day_cookie', 'C'); + } + + function testTimedCookieExpiryWith100SecondMargin() { + $this->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->ageCookies(3600); + $this->restart(time() + 100); + $this->assertNoCookie('session_cookie'); + $this->assertNoCookie('hour_cookie'); + $this->assertCookie('day_cookie', 'C'); + } + + function testNoClockOverDriftBy100Seconds() { + $this->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->restart(time() + 200); + $this->assertNoCookie( + 'short_cookie', + '%s -> Please check your computer clock setting if you are not using NTP'); + } + + function testNoClockUnderDriftBy100Seconds() { + $this->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->restart(time() + 0); + $this->assertCookie( + 'short_cookie', + 'B', + '%s -> Please check your computer clock setting if you are not using NTP'); + } + + function testCookiePath() { + $this->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->assertNoCookie('path_cookie', 'D'); + $this->get('./path/show_cookies.php'); + $this->assertPattern('/path_cookie/'); + $this->assertCookie('path_cookie', 'D'); + } + } + + class TestOfLiveForms extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testSimpleSubmit() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertPattern('/Request method.*?
    POST<\/dd>/'); + $this->assertText('go=[Go!]'); + } + + function testDefaultFormValues() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertFieldByName('a', ''); + $this->assertFieldByName('b', 'Default text'); + $this->assertFieldByName('c', ''); + $this->assertFieldByName('d', 'd1'); + $this->assertFieldByName('e', false); + $this->assertFieldByName('f', 'on'); + $this->assertFieldByName('g', 'g3'); + $this->assertFieldByName('h', 2); + $this->assertFieldByName('go', 'Go!'); + $this->assertClickable('Go!'); + $this->assertSubmit('Go!'); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertText('go=[Go!]'); + $this->assertText('a=[]'); + $this->assertText('b=[Default text]'); + $this->assertText('c=[]'); + $this->assertText('d=[d1]'); + $this->assertNoText('e=['); + $this->assertText('f=[on]'); + $this->assertText('g=[g3]'); + } + + function testFormSubmissionByButtonLabel() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->setFieldByName('a', 'aaa'); + $this->setFieldByName('b', 'bbb'); + $this->setFieldByName('c', 'ccc'); + $this->setFieldByName('d', 'D2'); + $this->setFieldByName('e', 'on'); + $this->setFieldByName('f', false); + $this->setFieldByName('g', 'g2'); + $this->setFieldByName('h', 1); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertText('a=[aaa]'); + $this->assertText('b=[bbb]'); + $this->assertText('c=[ccc]'); + $this->assertText('d=[d2]'); + $this->assertText('e=[on]'); + $this->assertNoText('f=['); + $this->assertText('g=[g2]'); + } + + function testAdditionalFormValues() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickSubmit('Go!', array('add' => 'A'))); + $this->assertText('go=[Go!]'); + $this->assertText('add=[A]'); + } + + function testFormSubmissionByName() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->setFieldByName('a', 'A'); + $this->assertTrue($this->clickSubmitByName('go')); + $this->assertText('a=[A]'); + } + + function testFormSubmissionByNameAndAdditionalParameters() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickSubmitByName('go', array('add' => 'A'))); + $this->assertText('go=[Go!]'); + $this->assertText('add=[A]'); + } + + function testFormSubmissionBySubmitButtonLabeledSubmit() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickSubmitByName('test')); + $this->assertText('test=[Submit]'); + } + + function testFormSubmissionWithIds() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertFieldById(1, ''); + $this->assertFieldById(2, 'Default text'); + $this->assertFieldById(3, ''); + $this->assertFieldById(4, 'd1'); + $this->assertFieldById(5, false); + $this->assertFieldById(6, 'on'); + $this->assertFieldById(8, 'g3'); + $this->assertFieldById(11, 2); + $this->setFieldById(1, 'aaa'); + $this->setFieldById(2, 'bbb'); + $this->setFieldById(3, 'ccc'); + $this->setFieldById(4, 'D2'); + $this->setFieldById(5, 'on'); + $this->setFieldById(6, false); + $this->setFieldById(8, 'g2'); + $this->setFieldById(11, 'H1'); + $this->assertTrue($this->clickSubmitById(99)); + $this->assertText('a=[aaa]'); + $this->assertText('b=[bbb]'); + $this->assertText('c=[ccc]'); + $this->assertText('d=[d2]'); + $this->assertText('e=[on]'); + $this->assertNoText('f=['); + $this->assertText('g=[g2]'); + $this->assertText('h=[1]'); + $this->assertText('go=[Go!]'); + } + + function testFormSubmissionWithLabels() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertField('Text A', ''); + $this->assertField('Text B', 'Default text'); + $this->assertField('Text area C', ''); + $this->assertField('Selection D', 'd1'); + $this->assertField('Checkbox E', false); + $this->assertField('Checkbox F', 'on'); + $this->assertField('3', 'g3'); + $this->assertField('Selection H', 2); + $this->setField('Text A', 'aaa'); + $this->setField('Text B', 'bbb'); + $this->setField('Text area C', 'ccc'); + $this->setField('Selection D', 'D2'); + $this->setField('Checkbox E', 'on'); + $this->setField('Checkbox F', false); + $this->setField('2', 'g2'); + $this->setField('Selection H', 'H1'); + $this->clickSubmit('Go!'); + $this->assertText('a=[aaa]'); + $this->assertText('b=[bbb]'); + $this->assertText('c=[ccc]'); + $this->assertText('d=[d2]'); + $this->assertText('e=[on]'); + $this->assertNoText('f=['); + $this->assertText('g=[g2]'); + $this->assertText('h=[1]'); + $this->assertText('go=[Go!]'); + } + + function testSettingCheckboxWithBooleanTrueSetsUnderlyingValue() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->setField('Checkbox E', true); + $this->assertField('Checkbox E', 'on'); + $this->clickSubmit('Go!'); + $this->assertText('e=[on]'); + } + + function testFormSubmissionWithMixedPostAndGet() { + $this->get('http://www.lastcraft.com/test/form_with_mixed_post_and_get.html'); + $this->setField('Text A', 'Hello'); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertText('a=[Hello]'); + $this->assertText('x=[X]'); + $this->assertText('y=[Y]'); + } + + function testFormSubmissionWithMixedPostAndEncodedGet() { + $this->get('http://www.lastcraft.com/test/form_with_mixed_post_and_get.html'); + $this->setField('Text B', 'Hello'); + $this->assertTrue($this->clickSubmit('Go encoded!')); + $this->assertText('b=[Hello]'); + $this->assertText('x=[X]'); + $this->assertText('y=[Y]'); + } + + function testFormSubmissionWithoutAction() { + $this->get('http://www.lastcraft.com/test/form_without_action.php?test=test'); + $this->assertText('_GET : [test]'); + $this->assertTrue($this->clickSubmit('Submit Post With Empty Action')); + $this->assertText('_GET : [test]'); + $this->assertText('_POST : [test]'); + } + + function testImageSubmissionByLabel() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertImage('Image go!'); + $this->assertTrue($this->clickImage('Image go!', 10, 12)); + $this->assertText('go_x=[10]'); + $this->assertText('go_y=[12]'); + } + + function testImageSubmissionByLabelWithAdditionalParameters() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickImage('Image go!', 10, 12, array('add' => 'A'))); + $this->assertText('add=[A]'); + } + + function testImageSubmissionByName() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickImageByName('go', 10, 12)); + $this->assertText('go_x=[10]'); + $this->assertText('go_y=[12]'); + } + + function testImageSubmissionById() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickImageById(97, 10, 12)); + $this->assertText('go_x=[10]'); + $this->assertText('go_y=[12]'); + } + + function testButtonSubmissionByLabel() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickSubmit('Button go!', 10, 12)); + $this->assertPattern('/go=\[ButtonGo\]/s'); + } + + function testNamelessSubmitSendsNoValue() { + $this->get('http://www.lastcraft.com/test/form_with_unnamed_submit.html'); + $this->click('Go!'); + $this->assertNoText('Go!'); + $this->assertNoText('submit'); + } + + function testNamelessImageSendsXAndYValues() { + $this->get('http://www.lastcraft.com/test/form_with_unnamed_submit.html'); + $this->clickImage('Image go!', 4, 5); + $this->assertNoText('ImageGo'); + $this->assertText('x=[4]'); + $this->assertText('y=[5]'); + } + + function testNamelessButtonSendsNoValue() { + $this->get('http://www.lastcraft.com/test/form_with_unnamed_submit.html'); + $this->click('Button Go!'); + $this->assertNoText('ButtonGo'); + } + + function testSelfSubmit() { + $this->get('http://www.lastcraft.com/test/self_form.php'); + $this->assertNoText('[Submitted]'); + $this->assertNoText('[Wrong form]'); + $this->assertTrue($this->clickSubmit()); + $this->assertText('[Submitted]'); + $this->assertNoText('[Wrong form]'); + $this->assertTitle('Test of form self submission'); + } + + function testSelfSubmitWithParameters() { + $this->get('http://www.lastcraft.com/test/self_form.php'); + $this->setFieldByName('visible', 'Resent'); + $this->assertTrue($this->clickSubmit()); + $this->assertText('[Resent]'); + } + + function testSettingOfBlankOption() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->setFieldByName('d', '')); + $this->clickSubmit('Go!'); + $this->assertText('d=[]'); + } + + function testAssertingFieldValueWithPattern() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->setField('c', 'A very long string'); + $this->assertField('c', new PatternExpectation('/very long/')); + } + + function testSendingMultipartFormDataEncodedForm() { + $this->get('http://www.lastcraft.com/test/form_data_encoded_form.html'); + $this->assertField('Text A', ''); + $this->assertField('Text B', 'Default text'); + $this->assertField('Text area C', ''); + $this->assertField('Selection D', 'd1'); + $this->assertField('Checkbox E', false); + $this->assertField('Checkbox F', 'on'); + $this->assertField('3', 'g3'); + $this->assertField('Selection H', 2); + $this->setField('Text A', 'aaa'); + $this->setField('Text B', 'bbb'); + $this->setField('Text area C', 'ccc'); + $this->setField('Selection D', 'D2'); + $this->setField('Checkbox E', 'on'); + $this->setField('Checkbox F', false); + $this->setField('2', 'g2'); + $this->setField('Selection H', 'H1'); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertText('a=[aaa]'); + $this->assertText('b=[bbb]'); + $this->assertText('c=[ccc]'); + $this->assertText('d=[d2]'); + $this->assertText('e=[on]'); + $this->assertNoText('f=['); + $this->assertText('g=[g2]'); + $this->assertText('h=[1]'); + $this->assertText('go=[Go!]'); + } + + function testSettingVariousBlanksInFields() { + $this->get('http://www.lastcraft.com/test/form_with_false_defaults.html'); + $this->assertField('Text A', ''); + $this->setField('Text A', '0'); + $this->assertField('Text A', '0'); + $this->assertField('Text area B', ''); + $this->setField('Text area B', '0'); + $this->assertField('Text area B', '0'); + $this->assertField('Text area C', " "); + $this->assertField('Selection D', ''); + $this->setField('Selection D', 'D2'); + $this->assertField('Selection D', 'D2'); + $this->setField('Selection D', 'D3'); + $this->assertField('Selection D', '0'); + $this->setField('Selection D', 'D4'); + $this->assertField('Selection D', '?'); + $this->assertField('Checkbox E', ''); + $this->assertField('Checkbox F', 'on'); + $this->assertField('Checkbox G', '0'); + $this->assertField('Checkbox H', '?'); + $this->assertFieldByName('i', 'on'); + $this->setFieldByName('i', ''); + $this->assertFieldByName('i', ''); + $this->setFieldByName('i', '0'); + $this->assertFieldByName('i', '0'); + $this->setFieldByName('i', '?'); + $this->assertFieldByName('i', '?'); + } + + function testSubmissionOfBlankFields() { + $this->get('http://www.lastcraft.com/test/form_with_false_defaults.html'); + $this->setField('Text A', ''); + $this->setField('Text area B', ''); + $this->setFieldByName('i', ''); + $this->click('Go!'); + $this->assertText('a=[]'); + $this->assertText('b=[]'); + $this->assertPattern('/c=\[ \]/'); + $this->assertText('d=[]'); + $this->assertText('e=[]'); + $this->assertText('i=[]'); + } + + function testSubmissionOfEmptyValues() { + $this->get('http://www.lastcraft.com/test/form_with_false_defaults.html'); + $this->setField('Selection D', 'D2'); + $this->click('Go!'); + $this->assertText('a=[]'); + $this->assertText('b=[]'); + $this->assertText('d=[D2]'); + $this->assertText('f=[on]'); + $this->assertText('i=[on]'); + } + + function testSubmissionOfZeroes() { + $this->get('http://www.lastcraft.com/test/form_with_false_defaults.html'); + $this->setField('Text A', '0'); + $this->setField('Text area B', '0'); + $this->setField('Selection D', 'D3'); + $this->setFieldByName('i', '0'); + $this->click('Go!'); + $this->assertText('a=[0]'); + $this->assertText('b=[0]'); + $this->assertText('d=[0]'); + $this->assertText('g=[0]'); + $this->assertText('i=[0]'); + } + + function testSubmissionOfQuestionMarks() { + $this->get('http://www.lastcraft.com/test/form_with_false_defaults.html'); + $this->setField('Text A', '?'); + $this->setField('Text area B', '?'); + $this->setField('Selection D', 'D4'); + $this->setFieldByName('i', '?'); + $this->click('Go!'); + $this->assertText('a=[?]'); + $this->assertText('b=[?]'); + $this->assertText('d=[?]'); + $this->assertText('h=[?]'); + $this->assertText('i=[?]'); + } + + function testSubmissionOfHtmlEncodedValues() { + $this->get('http://www.lastcraft.com/test/form_with_tricky_defaults.html'); + $this->assertField('Text A', '&\'"<>'); + $this->assertField('Text B', '"'); + $this->assertField('Text area C', '&\'"<>'); + $this->assertField('Selection D', "'"); + $this->assertField('Checkbox E', '&\'"<>'); + $this->assertField('Checkbox F', false); + $this->assertFieldByname('i', "'"); + $this->click('Go!'); + $this->assertText('a=[&\'"<>, "]'); + $this->assertText('c=[&\'"<>]'); + $this->assertText("d=[']"); + $this->assertText('e=[&\'"<>]'); + $this->assertText("i=[']"); + } + } + + class TestOfLiveMultiValueWidgets extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testDefaultFormValueSubmission() { + $this->get('http://www.lastcraft.com/test/multiple_widget_form.html'); + $this->assertFieldByName('a', array('a2', 'a3')); + $this->assertFieldByName('b', array('b2', 'b3')); + $this->assertFieldByName('c[]', array('c2', 'c3')); + $this->assertFieldByName('d', array('2', '3')); + $this->assertFieldByName('e', array('2', '3')); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertText('a=[a2, a3]'); + $this->assertText('b=[b2, b3]'); + $this->assertText('c=[c2, c3]'); + $this->assertText('d=[2, 3]'); + $this->assertText('e=[2, 3]'); + } + + function testSubmittingMultipleValues() { + $this->get('http://www.lastcraft.com/test/multiple_widget_form.html'); + $this->setFieldByName('a', array('a1', 'a4')); + $this->assertFieldByName('a', array('a1', 'a4')); + $this->assertFieldByName('a', array('a4', 'a1')); + $this->setFieldByName('b', array('b1', 'b4')); + $this->assertFieldByName('b', array('b1', 'b4')); + $this->setFieldByName('c[]', array('c1', 'c4')); + $this->assertField('c[]', array('c1', 'c4')); + $this->setFieldByName('d', array('1', '4')); + $this->assertField('d', array('1', '4')); + $this->setFieldByName('e', array('e1', 'e4')); + $this->assertField('e', array('1', '4')); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertText('a=[a1, a4]'); + $this->assertText('b=[b1, b4]'); + $this->assertText('c=[c1, c4]'); + $this->assertText('d=[1, 4]'); + $this->assertText('e=[1, 4]'); + } + + function testSettingByOptionValue() { + $this->get('http://www.lastcraft.com/test/multiple_widget_form.html'); + $this->setFieldByName('d', array('1', '4')); + $this->assertField('d', array('1', '4')); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertText('d=[1, 4]'); + } + + function testSubmittingMultipleValuesByLabel() { + $this->get('http://www.lastcraft.com/test/multiple_widget_form.html'); + $this->setField('Multiple selection A', array('a1', 'a4')); + $this->assertField('Multiple selection A', array('a1', 'a4')); + $this->assertField('Multiple selection A', array('a4', 'a1')); + $this->setField('multiple selection C', array('c1', 'c4')); + $this->assertField('multiple selection C', array('c1', 'c4')); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertText('a=[a1, a4]'); + $this->assertText('c=[c1, c4]'); + } + + function testSavantStyleHiddenFieldDefaults() { + $this->get('http://www.lastcraft.com/test/savant_style_form.html'); + $this->assertFieldByName('a', array('a0')); + $this->assertFieldByName('b', array('b0')); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertText('a=[a0]'); + $this->assertText('b=[b0]'); + } + + function testSavantStyleHiddenDefaultsAreOverridden() { + $this->get('http://www.lastcraft.com/test/savant_style_form.html'); + $this->assertTrue($this->setFieldByName('a', array('a1'))); + $this->assertTrue($this->setFieldByName('b', 'b1')); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertText('a=[a1]'); + $this->assertText('b=[b1]'); + } + + function testSavantStyleFormSettingById() { + $this->get('http://www.lastcraft.com/test/savant_style_form.html'); + $this->assertFieldById(1, array('a0')); + $this->assertFieldById(4, array('b0')); + $this->assertTrue($this->setFieldById(2, 'a1')); + $this->assertTrue($this->setFieldById(5, 'b1')); + $this->assertTrue($this->clickSubmitById(99)); + $this->assertText('a=[a1]'); + $this->assertText('b=[b1]'); + } + } + + class TestOfFileUploads extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testSingleFileUpload() { + $this->get('http://www.lastcraft.com/test/upload_form.html'); + $this->assertTrue($this->setField('Content:', + dirname(__FILE__) . '/support/upload_sample.txt')); + $this->assertField('Content:', dirname(__FILE__) . '/support/upload_sample.txt'); + $this->click('Go!'); + $this->assertText('Sample for testing file upload'); + } + + function testMultipleFileUpload() { + $this->get('http://www.lastcraft.com/test/upload_form.html'); + $this->assertTrue($this->setField('Content:', + dirname(__FILE__) . '/support/upload_sample.txt')); + $this->assertTrue($this->setField('Supplemental:', + dirname(__FILE__) . '/support/supplementary_upload_sample.txt')); + $this->assertField('Supplemental:', + dirname(__FILE__) . '/support/supplementary_upload_sample.txt'); + $this->click('Go!'); + $this->assertText('Sample for testing file upload'); + $this->assertText('Some more text content'); + } + + function testBinaryFileUpload() { + $this->get('http://www.lastcraft.com/test/upload_form.html'); + $this->assertTrue($this->setField('Content:', + dirname(__FILE__) . '/support/latin1_sample')); + $this->click('Go!'); + $this->assertText( + implode('', file(dirname(__FILE__) . '/support/latin1_sample'))); + } + } + + class TestOfLiveHistoryNavigation extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testRetry() { + $this->get('http://www.lastcraft.com/test/cookie_based_counter.php'); + $this->assertPattern('/count: 1/i'); + $this->retry(); + $this->assertPattern('/count: 2/i'); + $this->retry(); + $this->assertPattern('/count: 3/i'); + } + + function testOfBackButton() { + $this->get('http://www.lastcraft.com/test/1.html'); + $this->clickLink('2'); + $this->assertTitle('2'); + $this->assertTrue($this->back()); + $this->assertTitle('1'); + $this->assertTrue($this->forward()); + $this->assertTitle('2'); + $this->assertFalse($this->forward()); + } + + function testGetRetryResubmitsData() { + $this->assertTrue($this->get( + 'http://www.lastcraft.com/test/network_confirm.php?a=aaa')); + $this->assertPattern('/Request method.*?
    GET<\/dd>/'); + $this->assertText('a=[aaa]'); + $this->retry(); + $this->assertPattern('/Request method.*?
    GET<\/dd>/'); + $this->assertText('a=[aaa]'); + } + + function testGetRetryResubmitsExtraData() { + $this->assertTrue($this->get( + 'http://www.lastcraft.com/test/network_confirm.php', + array('a' => 'aaa'))); + $this->assertPattern('/Request method.*?
    GET<\/dd>/'); + $this->assertText('a=[aaa]'); + $this->retry(); + $this->assertPattern('/Request method.*?
    GET<\/dd>/'); + $this->assertText('a=[aaa]'); + } + + function testPostRetryResubmitsData() { + $this->assertTrue($this->post( + 'http://www.lastcraft.com/test/network_confirm.php', + array('a' => 'aaa'))); + $this->assertPattern('/Request method.*?
    POST<\/dd>/'); + $this->assertText('a=[aaa]'); + $this->retry(); + $this->assertPattern('/Request method.*?
    POST<\/dd>/'); + $this->assertText('a=[aaa]'); + } + + function testGetRetryResubmitsRepeatedData() { + $this->assertTrue($this->get( + 'http://www.lastcraft.com/test/network_confirm.php?a=1&a=2')); + $this->assertPattern('/Request method.*?
    GET<\/dd>/'); + $this->assertText('a=[1, 2]'); + $this->retry(); + $this->assertPattern('/Request method.*?
    GET<\/dd>/'); + $this->assertText('a=[1, 2]'); + } + } + + class TestOfLiveAuthentication extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testChallengeFromProtectedPage() { + $this->get('http://www.lastcraft.com/test/protected/'); + $this->assertResponse(401); + $this->assertAuthentication('Basic'); + $this->assertRealm('SimpleTest basic authentication'); + $this->assertRealm(new PatternExpectation('/simpletest/i')); + $this->authenticate('test', 'secret'); + $this->assertResponse(200); + $this->retry(); + $this->assertResponse(200); + } + + function testTrailingSlashImpliedWithinRealm() { + $this->get('http://www.lastcraft.com/test/protected/'); + $this->authenticate('test', 'secret'); + $this->assertResponse(200); + $this->get('http://www.lastcraft.com/test/protected'); + $this->assertResponse(200); + } + + function testTrailingSlashImpliedSettingRealm() { + $this->get('http://www.lastcraft.com/test/protected'); + $this->authenticate('test', 'secret'); + $this->assertResponse(200); + $this->get('http://www.lastcraft.com/test/protected/'); + $this->assertResponse(200); + } + + function testEncodedAuthenticationFetchesPage() { + $this->get('http://test:secret@www.lastcraft.com/test/protected/'); + $this->assertResponse(200); + } + + function testEncodedAuthenticationFetchesPageAfterTrailingSlashRedirect() { + $this->get('http://test:secret@www.lastcraft.com/test/protected'); + $this->assertResponse(200); + } + + function testRealmExtendsToWholeDirectory() { + $this->get('http://www.lastcraft.com/test/protected/1.html'); + $this->authenticate('test', 'secret'); + $this->clickLink('2'); + $this->assertResponse(200); + $this->clickLink('3'); + $this->assertResponse(200); + } + + function testRedirectKeepsAuthentication() { + $this->get('http://www.lastcraft.com/test/protected/local_redirect.php'); + $this->authenticate('test', 'secret'); + $this->assertTitle('Simple test target file'); + } + + function testRedirectKeepsEncodedAuthentication() { + $this->get('http://test:secret@www.lastcraft.com/test/protected/local_redirect.php'); + $this->assertResponse(200); + $this->assertTitle('Simple test target file'); + } + + function testSessionRestartLosesAuthentication() { + $this->get('http://www.lastcraft.com/test/protected/'); + $this->authenticate('test', 'secret'); + $this->assertResponse(200); + $this->restart(); + $this->get('http://www.lastcraft.com/test/protected/'); + $this->assertResponse(401); + } + } + + class TestOfLoadingFrames extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testNoFramesContentWhenFramesDisabled() { + $this->ignoreFrames(); + $this->get('http://www.lastcraft.com/test/one_page_frameset.html'); + $this->assertTitle('Frameset for testing of SimpleTest'); + $this->assertText('This content is for no frames only'); + } + + function testPatternMatchCanReadTheOnlyFrame() { + $this->get('http://www.lastcraft.com/test/one_page_frameset.html'); + $this->assertText('A target for the SimpleTest test suite'); + $this->assertNoText('This content is for no frames only'); + } + + function testMessyFramesetResponsesByName() { + $this->assertTrue($this->get( + 'http://www.lastcraft.com/test/messy_frameset.html')); + $this->assertTitle('Frameset for testing of SimpleTest'); + + $this->assertTrue($this->setFrameFocus('Front controller')); + $this->assertResponse(200); + $this->assertText('Simple test front controller'); + + $this->assertTrue($this->setFrameFocus('One')); + $this->assertResponse(200); + $this->assertLink('2'); + + $this->assertTrue($this->setFrameFocus('Frame links')); + $this->assertResponse(200); + $this->assertLink('Set one to 2'); + + $this->assertTrue($this->setFrameFocus('Counter')); + $this->assertResponse(200); + $this->assertText('Count: 1'); + + $this->assertTrue($this->setFrameFocus('Redirected')); + $this->assertResponse(200); + $this->assertText('r=rrr'); + + $this->assertTrue($this->setFrameFocus('Protected')); + $this->assertResponse(401); + + $this->assertTrue($this->setFrameFocus('Protected redirect')); + $this->assertResponse(401); + + $this->assertTrue($this->setFrameFocusByIndex(1)); + $this->assertResponse(200); + $this->assertText('Simple test front controller'); + + $this->assertTrue($this->setFrameFocusByIndex(2)); + $this->assertResponse(200); + $this->assertLink('2'); + + $this->assertTrue($this->setFrameFocusByIndex(3)); + $this->assertResponse(200); + $this->assertLink('Set one to 2'); + + $this->assertTrue($this->setFrameFocusByIndex(4)); + $this->assertResponse(200); + $this->assertText('Count: 1'); + + $this->assertTrue($this->setFrameFocusByIndex(5)); + $this->assertResponse(200); + $this->assertText('r=rrr'); + + $this->assertTrue($this->setFrameFocusByIndex(6)); + $this->assertResponse(401); + + $this->assertTrue($this->setFrameFocusByIndex(7)); + } + + function testReloadingFramesetPage() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->assertText('Count: 1'); + $this->retry(); + $this->assertText('Count: 2'); + $this->retry(); + $this->assertText('Count: 3'); + } + + function testReloadingSingleFrameWithCookieCounter() { + $this->get('http://www.lastcraft.com/test/counting_frameset.html'); + $this->setFrameFocus('a'); + $this->assertText('Count: 1'); + $this->setFrameFocus('b'); + $this->assertText('Count: 2'); + + $this->setFrameFocus('a'); + $this->retry(); + $this->assertText('Count: 3'); + $this->retry(); + $this->assertText('Count: 4'); + $this->setFrameFocus('b'); + $this->assertText('Count: 2'); + } + + function testReloadingFrameWhenUnfocusedReloadsWholeFrameset() { + $this->get('http://www.lastcraft.com/test/counting_frameset.html'); + $this->setFrameFocus('a'); + $this->assertText('Count: 1'); + $this->setFrameFocus('b'); + $this->assertText('Count: 2'); + + $this->clearFrameFocus('a'); + $this->retry(); + + $this->assertTitle('Frameset for testing of SimpleTest'); + $this->setFrameFocus('a'); + $this->assertText('Count: 3'); + $this->setFrameFocus('b'); + $this->assertText('Count: 4'); + } + + function testClickingNormalLinkReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('2'); + $this->assertLink('3'); + $this->assertText('Simple test front controller'); + } + + function testJumpToNamedPageReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->assertPattern('/Simple test front controller/'); + $this->clickLink('Index'); + $this->assertResponse(200); + $this->assertText('[action=index]'); + $this->assertText('Count: 1'); + } + + function testJumpToUnnamedPageReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('No page'); + $this->assertResponse(200); + $this->assertText('Simple test front controller'); + $this->assertText('[action=no_page]'); + $this->assertText('Count: 1'); + } + + function testJumpToUnnamedPageWithBareParameterReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('Bare action'); + $this->assertResponse(200); + $this->assertText('Simple test front controller'); + $this->assertText('[action=]'); + $this->assertText('Count: 1'); + } + + function testJumpToUnnamedPageWithEmptyQueryReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('Empty query'); + $this->assertResponse(200); + $this->assertPattern('/Simple test front controller/'); + $this->assertPattern('/raw get data.*?\[\].*?get data/si'); + $this->assertPattern('/Count: 1/'); + } + + function testJumpToUnnamedPageWithEmptyLinkReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('Empty link'); + $this->assertResponse(200); + $this->assertPattern('/Simple test front controller/'); + $this->assertPattern('/raw get data.*?\[\].*?get data/si'); + $this->assertPattern('/Count: 1/'); + } + + function testJumpBackADirectoryLevelReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('Down one'); + $this->assertPattern('/index of \/test/i'); + $this->assertPattern('/Count: 1/'); + } + + function testSubmitToNamedPageReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->assertPattern('/Simple test front controller/'); + $this->clickSubmit('Index'); + $this->assertResponse(200); + $this->assertText('[action=Index]'); + $this->assertText('Count: 1'); + } + + function testSubmitToSameDirectoryReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickSubmit('Same directory'); + $this->assertResponse(200); + $this->assertText('[action=Same+directory]'); + $this->assertText('Count: 1'); + } + + function testSubmitToEmptyActionReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickSubmit('Empty action'); + $this->assertResponse(200); + $this->assertText('[action=Empty+action]'); + $this->assertText('Count: 1'); + } + + function testSubmitToNoActionReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickSubmit('No action'); + $this->assertResponse(200); + $this->assertText('[action=No+action]'); + $this->assertText('Count: 1'); + } + + function testSubmitBackADirectoryLevelReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickSubmit('Down one'); + $this->assertPattern('/index of \/test/i'); + $this->assertPattern('/Count: 1/'); + } + + function testTopLinkExitsFrameset() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('Exit the frameset'); + $this->assertTitle('Simple test target file'); + } + + function testLinkInOnePageCanLoadAnother() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->assertNoLink('3'); + $this->clickLink('Set one to 2'); + $this->assertLink('3'); + $this->assertNoLink('2'); + $this->assertTitle('Frameset for testing of SimpleTest'); + } + } + + class TestOfFrameAuthentication extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testUnauthenticatedFrameSendsChallenge() { + $this->get('http://www.lastcraft.com/test/protected/'); + $this->setFrameFocus('Protected'); + $this->assertAuthentication('Basic'); + $this->assertRealm('SimpleTest basic authentication'); + $this->assertResponse(401); + } + + function testCanReadFrameFromAlreadyAuthenticatedRealm() { + $this->get('http://www.lastcraft.com/test/protected/'); + $this->authenticate('test', 'secret'); + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->setFrameFocus('Protected'); + $this->assertResponse(200); + $this->assertText('A target for the SimpleTest test suite'); + } + + function testCanAuthenticateFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->setFrameFocus('Protected'); + $this->authenticate('test', 'secret'); + $this->assertResponse(200); + $this->assertText('A target for the SimpleTest test suite'); + $this->clearFrameFocus(); + $this->assertText('Count: 1'); + } + + function testCanAuthenticateRedirectedFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->setFrameFocus('Protected redirect'); + $this->assertResponse(401); + $this->authenticate('test', 'secret'); + $this->assertResponse(200); + $this->assertText('A target for the SimpleTest test suite'); + $this->clearFrameFocus(); + $this->assertText('Count: 1'); + } + } + + class TestOfNestedFrames extends WebTestCase { + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); + } + + function testCanNavigateToSpecificContent() { + $this->get('http://www.lastcraft.com/test/nested_frameset.html'); + $this->assertTitle('Nested frameset for testing of SimpleTest'); + + $this->assertPattern('/This is frame A/'); + $this->assertPattern('/This is frame B/'); + $this->assertPattern('/Simple test front controller/'); + $this->assertLink('2'); + $this->assertLink('Set one to 2'); + $this->assertPattern('/Count: 1/'); + $this->assertPattern('/r=rrr/'); + + $this->setFrameFocus('pair'); + $this->assertPattern('/This is frame A/'); + $this->assertPattern('/This is frame B/'); + $this->assertNoPattern('/Simple test front controller/'); + $this->assertNoLink('2'); + + $this->setFrameFocus('aaa'); + $this->assertPattern('/This is frame A/'); + $this->assertNoPattern('/This is frame B/'); + + $this->clearFrameFocus(); + $this->assertResponse(200); + $this->setFrameFocus('messy'); + $this->assertResponse(200); + $this->setFrameFocus('Front controller'); + $this->assertResponse(200); + $this->assertPattern('/Simple test front controller/'); + $this->assertNoLink('2'); + } + + function testReloadingFramesetPage() { + $this->get('http://www.lastcraft.com/test/nested_frameset.html'); + $this->assertPattern('/Count: 1/'); + $this->retry(); + $this->assertPattern('/Count: 2/'); + $this->retry(); + $this->assertPattern('/Count: 3/'); + } + + function testRetryingNestedPageOnlyRetriesThatSet() { + $this->get('http://www.lastcraft.com/test/nested_frameset.html'); + $this->assertPattern('/Count: 1/'); + $this->setFrameFocus('messy'); + $this->retry(); + $this->assertPattern('/Count: 2/'); + $this->setFrameFocus('Counter'); + $this->retry(); + $this->assertPattern('/Count: 3/'); + + $this->clearFrameFocus(); + $this->setFrameFocus('messy'); + $this->setFrameFocus('Front controller'); + $this->retry(); + + $this->clearFrameFocus(); + $this->assertPattern('/Count: 3/'); + } + + function testAuthenticatingNestedPage() { + $this->get('http://www.lastcraft.com/test/nested_frameset.html'); + $this->setFrameFocus('messy'); + $this->setFrameFocus('Protected'); + $this->assertAuthentication('Basic'); + $this->assertRealm('SimpleTest basic authentication'); + $this->assertResponse(401); + + $this->authenticate('test', 'secret'); + $this->assertResponse(200); + $this->assertPattern('/A target for the SimpleTest test suite/'); + } + } +?> diff --git a/tests/simpletest/test/adapter_test.php b/tests/simpletest/test/adapter_test.php new file mode 100644 index 00000000..78445501 --- /dev/null +++ b/tests/simpletest/test/adapter_test.php @@ -0,0 +1,74 @@ +assertTrue(true, "PEAR true"); + $this->assertFalse(false, "PEAR false"); + } + + function testName() { + $this->assertTrue($this->getName() == get_class($this)); + } + + function testPass() { + $this->pass("PEAR pass"); + } + + function testNulls() { + $value = null; + $this->assertNull($value, "PEAR null"); + $value = 0; + $this->assertNotNull($value, "PEAR not null"); + } + + function testType() { + $this->assertType("Hello", "string", "PEAR type"); + } + + function testEquals() { + $this->assertEquals(12, 12, "PEAR identity"); + $this->setLooselyTyped(true); + $this->assertEquals("12", 12, "PEAR equality"); + } + + function testSame() { + $same = &new SameTestClass(); + $this->assertSame($same, $same, "PEAR same"); + } + + function testRegExp() { + $this->assertRegExp('/hello/', "A big hello from me", "PEAR regex"); + } + } + + class TestOfPhpUnitAdapter extends TestCase { + function TestOfPhpUnitAdapter() { + $this->TestCase('TestOfPhpUnitAdapter'); + } + + function testBoolean() { + $this->assert(true, 'PHP Unit true'); + } + + function testName() { + $this->assert($this->name() == 'TestOfPhpUnitAdapter'); + } + + function testEquals() { + $this->assertEquals(12, 12, 'PHP Unit equality'); + } + + function testMultilineEquals() { + $this->assertEquals("a\nb\n", "a\nb\n", 'PHP Unit equality'); + } + + function testRegExp() { + $this->assertRegexp('/hello/', 'A big hello from me', 'PHPUnit regex'); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/all_tests.php b/tests/simpletest/test/all_tests.php new file mode 100644 index 00000000..c96a18bb --- /dev/null +++ b/tests/simpletest/test/all_tests.php @@ -0,0 +1,15 @@ +run(new SelectiveReporter(new TextReporter(), @$argv[1], @$argv[2])); + return ($result ? 0 : 1); + } + $test->run(new SelectiveReporter(new HtmlReporter(), @$_GET['c'], @$_GET['t'])); +?> diff --git a/tests/simpletest/test/authentication_test.php b/tests/simpletest/test/authentication_test.php new file mode 100644 index 00000000..92733281 --- /dev/null +++ b/tests/simpletest/test/authentication_test.php @@ -0,0 +1,144 @@ +assertTrue($realm->isWithin( + new SimpleUrl('http://www.here.com/path/hello.html'))); + } + + function testInsideWithLongerUrl() { + $realm = &new SimpleRealm( + 'Basic', + new SimpleUrl('http://www.here.com/path/')); + $this->assertTrue($realm->isWithin( + new SimpleUrl('http://www.here.com/path/hello.html'))); + } + + function testBelowRootIsOutside() { + $realm = &new SimpleRealm( + 'Basic', + new SimpleUrl('http://www.here.com/path/')); + $this->assertTrue($realm->isWithin( + new SimpleUrl('http://www.here.com/path/more/hello.html'))); + } + + function testOldNetscapeDefinitionIsOutside() { + $realm = &new SimpleRealm( + 'Basic', + new SimpleUrl('http://www.here.com/path/')); + $this->assertFalse($realm->isWithin( + new SimpleUrl('http://www.here.com/pathmore/hello.html'))); + } + + function testInsideWithMissingTrailingSlash() { + $realm = &new SimpleRealm( + 'Basic', + new SimpleUrl('http://www.here.com/path/')); + $this->assertTrue($realm->isWithin( + new SimpleUrl('http://www.here.com/path'))); + } + + function testDifferentPageNameStillInside() { + $realm = &new SimpleRealm( + 'Basic', + new SimpleUrl('http://www.here.com/path/hello.html')); + $this->assertTrue($realm->isWithin( + new SimpleUrl('http://www.here.com/path/goodbye.html'))); + } + + function testNewUrlInSameDirectoryDoesNotChangeRealm() { + $realm = &new SimpleRealm( + 'Basic', + new SimpleUrl('http://www.here.com/path/hello.html')); + $realm->stretch(new SimpleUrl('http://www.here.com/path/goodbye.html')); + $this->assertTrue($realm->isWithin( + new SimpleUrl('http://www.here.com/path/index.html'))); + $this->assertFalse($realm->isWithin( + new SimpleUrl('http://www.here.com/index.html'))); + } + + function testNewUrlMakesRealmTheCommonPath() { + $realm = &new SimpleRealm( + 'Basic', + new SimpleUrl('http://www.here.com/path/here/hello.html')); + $realm->stretch(new SimpleUrl('http://www.here.com/path/there/goodbye.html')); + $this->assertTrue($realm->isWithin( + new SimpleUrl('http://www.here.com/path/here/index.html'))); + $this->assertTrue($realm->isWithin( + new SimpleUrl('http://www.here.com/path/there/index.html'))); + $this->assertTrue($realm->isWithin( + new SimpleUrl('http://www.here.com/path/index.html'))); + $this->assertFalse($realm->isWithin( + new SimpleUrl('http://www.here.com/index.html'))); + $this->assertFalse($realm->isWithin( + new SimpleUrl('http://www.here.com/paths/index.html'))); + $this->assertFalse($realm->isWithin( + new SimpleUrl('http://www.here.com/pathindex.html'))); + } + } + + class TestOfAuthenticator extends UnitTestCase { + + function testNoRealms() { + $request = &new MockSimpleHttpRequest(); + $request->expectNever('addHeaderLine'); + $authenticator = &new SimpleAuthenticator(); + $authenticator->addHeaders($request, new SimpleUrl('http://here.com/')); + } + + function &createSingleRealm() { + $authenticator = &new SimpleAuthenticator(); + $authenticator->addRealm( + new SimpleUrl('http://www.here.com/path/hello.html'), + 'Basic', + 'Sanctuary'); + $authenticator->setIdentityForRealm('www.here.com', 'Sanctuary', 'test', 'secret'); + return $authenticator; + } + + function testOutsideRealm() { + $request = &new MockSimpleHttpRequest(); + $request->expectNever('addHeaderLine'); + $authenticator = &$this->createSingleRealm(); + $authenticator->addHeaders( + $request, + new SimpleUrl('http://www.here.com/hello.html')); + } + + function testWithinRealm() { + $request = &new MockSimpleHttpRequest(); + $request->expectOnce('addHeaderLine'); + $authenticator = &$this->createSingleRealm(); + $authenticator->addHeaders( + $request, + new SimpleUrl('http://www.here.com/path/more/hello.html')); + } + + function testRestartingClearsRealm() { + $request = &new MockSimpleHttpRequest(); + $request->expectNever('addHeaderLine'); + $authenticator = &$this->createSingleRealm(); + $authenticator->restartSession(); + $authenticator->addHeaders( + $request, + new SimpleUrl('http://www.here.com/hello.html')); + } + + function testDifferentHostIsOutsideRealm() { + $request = &new MockSimpleHttpRequest(); + $request->expectNever('addHeaderLine'); + $authenticator = &$this->createSingleRealm(); + $authenticator->addHeaders( + $request, + new SimpleUrl('http://here.com/path/hello.html')); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/browser_test.php b/tests/simpletest/test/browser_test.php new file mode 100644 index 00000000..83e67b44 --- /dev/null +++ b/tests/simpletest/test/browser_test.php @@ -0,0 +1,791 @@ +assertIdentical($history->getUrl(), false); + $this->assertIdentical($history->getParameters(), false); + } + + function testCannotMoveInEmptyHistory() { + $history = &new SimpleBrowserHistory(); + $this->assertFalse($history->back()); + $this->assertFalse($history->forward()); + } + + function testCurrentTargetAccessors() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + new SimpleUrl('http://www.here.com/'), + new SimpleGetEncoding()); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.here.com/')); + $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); + } + + function testSecondEntryAccessors() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + new SimpleUrl('http://www.first.com/'), + new SimpleGetEncoding()); + $history->recordEntry( + new SimpleUrl('http://www.second.com/'), + new SimplePostEncoding(array('a' => 1))); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); + $this->assertIdentical( + $history->getParameters(), + new SimplePostEncoding(array('a' => 1))); + } + + function testGoingBackwards() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + new SimpleUrl('http://www.first.com/'), + new SimpleGetEncoding()); + $history->recordEntry( + new SimpleUrl('http://www.second.com/'), + new SimplePostEncoding(array('a' => 1))); + $this->assertTrue($history->back()); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); + $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); + } + + function testGoingBackwardsOffBeginning() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + new SimpleUrl('http://www.first.com/'), + new SimpleGetEncoding()); + $this->assertFalse($history->back()); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); + $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); + } + + function testGoingForwardsOffEnd() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + new SimpleUrl('http://www.first.com/'), + new SimpleGetEncoding()); + $this->assertFalse($history->forward()); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); + $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); + } + + function testGoingBackwardsAndForwards() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + new SimpleUrl('http://www.first.com/'), + new SimpleGetEncoding()); + $history->recordEntry( + new SimpleUrl('http://www.second.com/'), + new SimplePostEncoding(array('a' => 1))); + $this->assertTrue($history->back()); + $this->assertTrue($history->forward()); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); + $this->assertIdentical( + $history->getParameters(), + new SimplePostEncoding(array('a' => 1))); + } + + function testNewEntryReplacesNextOne() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + new SimpleUrl('http://www.first.com/'), + new SimpleGetEncoding()); + $history->recordEntry( + new SimpleUrl('http://www.second.com/'), + new SimplePostEncoding(array('a' => 1))); + $history->back(); + $history->recordEntry( + new SimpleUrl('http://www.third.com/'), + new SimpleGetEncoding()); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.third.com/')); + $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); + } + + function testNewEntryDropsFutureEntries() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + new SimpleUrl('http://www.first.com/'), + new SimpleGetEncoding()); + $history->recordEntry( + new SimpleUrl('http://www.second.com/'), + new SimpleGetEncoding()); + $history->recordEntry( + new SimpleUrl('http://www.third.com/'), + new SimpleGetEncoding()); + $history->back(); + $history->back(); + $history->recordEntry( + new SimpleUrl('http://www.fourth.com/'), + new SimpleGetEncoding()); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.fourth.com/')); + $this->assertFalse($history->forward()); + $history->back(); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); + $this->assertFalse($history->back()); + } + } + + class TestOfParsedPageAccess extends UnitTestCase { + + function &loadPage(&$page) { + $response = &new MockSimpleHttpResponse($this); + + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', $response); + + $browser = &new MockParseSimpleBrowser($this); + $browser->setReturnReference('_createUserAgent', $agent); + $browser->setReturnReference('_parse', $page); + $browser->SimpleBrowser(); + + $browser->get('http://this.com/page.html'); + return $browser; + } + + function testAccessorsWhenNoPage() { + $agent = &new MockSimpleUserAgent($this); + + $browser = &new MockParseSimpleBrowser($this); + $browser->setReturnReference('_createUserAgent', $agent); + $browser->SimpleBrowser(); + + $this->assertEqual($browser->getContent(), ''); + } + + function testParse() { + $page = &new MockSimplePage(); + $page->setReturnValue('getRequest', "GET here.html\r\n\r\n"); + $page->setReturnValue('getRaw', 'Raw HTML'); + $page->setReturnValue('getTitle', 'Here'); + $page->setReturnValue('getFrameFocus', 'Frame'); + $page->setReturnValue('getMimeType', 'text/html'); + $page->setReturnValue('getResponseCode', 200); + $page->setReturnValue('getAuthentication', 'Basic'); + $page->setReturnValue('getRealm', 'Somewhere'); + $page->setReturnValue('getTransportError', 'Ouch!'); + + $browser = &$this->loadPage($page); + + $this->assertEqual($browser->getRequest(), "GET here.html\r\n\r\n"); + $this->assertEqual($browser->getContent(), 'Raw HTML'); + $this->assertEqual($browser->getTitle(), 'Here'); + $this->assertEqual($browser->getFrameFocus(), 'Frame'); + $this->assertIdentical($browser->getResponseCode(), 200); + $this->assertEqual($browser->getMimeType(), 'text/html'); + $this->assertEqual($browser->getAuthentication(), 'Basic'); + $this->assertEqual($browser->getRealm(), 'Somewhere'); + $this->assertEqual($browser->getTransportError(), 'Ouch!'); + } + + function testLinkAffirmationWhenPresent() { + $page = &new MockSimplePage(); + $page->setReturnValue('getUrlsByLabel', array('http://www.nowhere.com')); + $page->expectOnce('getUrlsByLabel', array('a link label')); + $browser = &$this->loadPage($page); + $this->assertIdentical($browser->getLink('a link label'), 'http://www.nowhere.com'); + } + + function testLinkAffirmationByIdWhenPresent() { + $page = &new MockSimplePage(); + $page->setReturnValue('getUrlById', 'a_page.com', array(99)); + $page->setReturnValue('getUrlById', false, array('*')); + $browser = &$this->loadPage($page); + $this->assertIdentical($browser->getLinkById(99), 'a_page.com'); + $this->assertFalse($browser->getLinkById(98)); + } + + function testSettingFieldIsPassedToPage() { + $page = &new MockSimplePage(); + $page->expectOnce('setField', array(new SimpleByLabelOrName('key'), 'Value')); + $page->setReturnValue('getField', 'Value'); + $browser = &$this->loadPage($page); + $this->assertEqual($browser->getField('key'), 'Value'); + $browser->setField('key', 'Value'); + } + } + + class TestOfBrowserNavigation extends UnitTestCase { + + function &createBrowser(&$agent, &$page) { + $browser = &new MockParseSimpleBrowser(); + $browser->setReturnReference('_createUserAgent', $agent); + $browser->setReturnReference('_parse', $page); + $browser->SimpleBrowser(); + return $browser; + } + + function testClickLinkRequestsPage() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + $agent->expectArgumentsAt( + 0, + 'fetchResponse', + array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding())); + $agent->expectArgumentsAt( + 1, + 'fetchResponse', + array(new SimpleUrl('http://this.com/new.html'), new SimpleGetEncoding())); + $agent->expectCallCount('fetchResponse', 2); + + $page = &new MockSimplePage(); + $page->setReturnValue('getUrlsByLabel', array(new SimpleUrl('http://this.com/new.html'))); + $page->expectOnce('getUrlsByLabel', array('New')); + $page->setReturnValue('getRaw', 'A page'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickLink('New')); + } + + function testClickLinkWithUnknownFrameStillRequestsWholePage() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + $agent->expectArgumentsAt( + 0, + 'fetchResponse', + array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding())); + $target = new SimpleUrl('http://this.com/new.html'); + $target->setTarget('missing'); + $agent->expectArgumentsAt( + 1, + 'fetchResponse', + array($target, new SimpleGetEncoding())); + $agent->expectCallCount('fetchResponse', 2); + + $parsed_url = new SimpleUrl('http://this.com/new.html'); + $parsed_url->setTarget('missing'); + + $page = &new MockSimplePage(); + $page->setReturnValue('getUrlsByLabel', array($parsed_url)); + $page->setReturnValue('hasFrames', false); + $page->expectOnce('getUrlsByLabel', array('New')); + $page->setReturnValue('getRaw', 'A page'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickLink('New')); + } + + function testClickingMissingLinkFails() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + + $page = &new MockSimplePage(); + $page->setReturnValue('getUrlsByLabel', array()); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $this->assertTrue($browser->get('http://this.com/page.html')); + $this->assertFalse($browser->clickLink('New')); + } + + function testClickIndexedLink() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + $agent->expectArgumentsAt( + 1, + 'fetchResponse', + array(new SimpleUrl('1.html'), new SimpleGetEncoding())); + $agent->expectCallCount('fetchResponse', 2); + + $page = &new MockSimplePage(); + $page->setReturnValue( + 'getUrlsByLabel', + array(new SimpleUrl('0.html'), new SimpleUrl('1.html'))); + $page->setReturnValue('getRaw', 'A page'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickLink('New', 1)); + } + + function testClinkLinkById() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + $agent->expectArgumentsAt(1, 'fetchResponse', array( + new SimpleUrl('http://this.com/link.html'), + new SimpleGetEncoding())); + $agent->expectCallCount('fetchResponse', 2); + + $page = &new MockSimplePage(); + $page->setReturnValue('getUrlById', new SimpleUrl('http://this.com/link.html')); + $page->expectOnce('getUrlById', array(2)); + $page->setReturnValue('getRaw', 'A page'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickLinkById(2)); + } + + function testClickingMissingLinkIdFails() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + + $page = &new MockSimplePage(); + $page->setReturnValue('getUrlById', false); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertFalse($browser->clickLink(0)); + } + + function testSubmitFormByLabel() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + $agent->expectArgumentsAt(1, 'fetchResponse', array( + new SimpleUrl('http://this.com/handler.html'), + new SimplePostEncoding(array('a' => 'A')))); + $agent->expectCallCount('fetchResponse', 2); + + $form = &new MockSimpleForm(); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); + $form->expectOnce('submitButton', array(new SimpleByLabel('Go'), false)); + + $page = &new MockSimplePage(); + $page->setReturnReference('getFormBySubmit', $form); + $page->expectOnce('getFormBySubmit', array(new SimpleByLabel('Go'))); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickSubmit('Go')); + } + + function testDefaultSubmitFormByLabel() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + $agent->expectArgumentsAt(1, 'fetchResponse', array( + new SimpleUrl('http://this.com/page.html'), + new SimpleGetEncoding(array('a' => 'A')))); + $agent->expectCallCount('fetchResponse', 2); + + $form = &new MockSimpleForm(); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/page.html')); + $form->setReturnValue('getMethod', 'get'); + $form->setReturnValue('submitButton', new SimpleGetEncoding(array('a' => 'A'))); + + $page = &new MockSimplePage(); + $page->setReturnReference('getFormBySubmit', $form); + $page->expectOnce('getFormBySubmit', array(new SimpleByLabel('Submit'))); + $page->setReturnValue('getRaw', 'stuff'); + $page->setReturnValue('getUrl', new SimpleUrl('http://this.com/page.html')); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickSubmit()); + } + + function testSubmitFormByName() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + + $form = &new MockSimpleForm(); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); + + $page = &new MockSimplePage(); + $page->setReturnReference('getFormBySubmit', $form); + $page->expectOnce('getFormBySubmit', array(new SimpleByName('me'))); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickSubmitByName('me')); + } + + function testSubmitFormById() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + + $form = &new MockSimpleForm(); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); + $form->expectOnce('submitButton', array(new SimpleById(99), false)); + + $page = &new MockSimplePage(); + $page->setReturnReference('getFormBySubmit', $form); + $page->expectOnce('getFormBySubmit', array(new SimpleById(99))); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickSubmitById(99)); + } + + function testSubmitFormByImageLabel() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + + $form = &new MockSimpleForm(); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); + $form->expectOnce('submitImage', array(new SimpleByLabel('Go!'), 10, 11, false)); + + $page = &new MockSimplePage(); + $page->setReturnReference('getFormByImage', $form); + $page->expectOnce('getFormByImage', array(new SimpleByLabel('Go!'))); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickImage('Go!', 10, 11)); + } + + function testSubmitFormByImageName() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + + $form = &new MockSimpleForm(); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); + $form->expectOnce('submitImage', array(new SimpleByName('a'), 10, 11, false)); + + $page = &new MockSimplePage(); + $page->setReturnReference('getFormByImage', $form); + $page->expectOnce('getFormByImage', array(new SimpleByName('a'))); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickImageByName('a', 10, 11)); + } + + function testSubmitFormByImageId() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + + $form = &new MockSimpleForm(); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); + $form->expectOnce('submitImage', array(new SimpleById(99), 10, 11, false)); + + $page = &new MockSimplePage(); + $page->setReturnReference('getFormByImage', $form); + $page->expectOnce('getFormByImage', array(new SimpleById(99))); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickImageById(99, 10, 11)); + } + + function testSubmitFormByFormId() { + $agent = &new MockSimpleUserAgent(); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse()); + $agent->expectArgumentsAt(1, 'fetchResponse', array( + new SimpleUrl('http://this.com/handler.html'), + new SimplePostEncoding(array('a' => 'A')))); + $agent->expectCallCount('fetchResponse', 2); + + $form = &new MockSimpleForm(); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submit', new SimplePostEncoding(array('a' => 'A'))); + + $page = &new MockSimplePage(); + $page->setReturnReference('getFormById', $form); + $page->expectOnce('getFormById', array(33)); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->submitFormById(33)); + } + } + + class TestOfBrowserFrames extends UnitTestCase { + + function &createBrowser(&$agent) { + $browser = &new MockUserAgentSimpleBrowser(); + $browser->setReturnReference('_createUserAgent', $agent); + $browser->SimpleBrowser(); + return $browser; + } + + function &createUserAgent($pages) { + $agent = &new MockSimpleUserAgent(); + foreach ($pages as $url => $raw) { + $url = new SimpleUrl($url); + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getUrl', $url); + $response->setReturnValue('getContent', $raw); + $agent->setReturnReference('fetchResponse', $response, array($url, '*')); + } + return $agent; + } + + function testSimplePageHasNoFrames() { + $browser = &$this->createBrowser($this->createUserAgent( + array('http://site.with.no.frames/' => 'A non-framed page'))); + $this->assertEqual( + $browser->get('http://site.with.no.frames/'), + 'A non-framed page'); + $this->assertIdentical($browser->getFrames(), 'http://site.with.no.frames/'); + } + + function testFramesetWithNoFrames() { + $browser = &$this->createBrowser($this->createUserAgent( + array('http://site.with.no.frames/' => ''))); + $this->assertEqual( + $browser->get('http://site.with.no.frames/'), + ''); + $this->assertIdentical($browser->getFrames(), array()); + } + + function testFramesetWithSingleFrame() { + $frameset = ''; + $browser = &$this->createBrowser($this->createUserAgent(array( + 'http://site.with.one.frame/' => $frameset, + 'http://site.with.one.frame/frame.html' => 'A frame'))); + + $this->assertEqual( + $browser->get('http://site.with.one.frame/'), + 'A frame'); + $this->assertIdentical( + $browser->getFrames(), + array('a' => 'http://site.with.one.frame/frame.html')); + } + + function testTitleTakenFromFramesetPage() { + $frameset = 'Frameset title' . + ''; + $browser = &$this->createBrowser($this->createUserAgent(array( + 'http://site.with.one.frame/' => $frameset, + 'http://site.with.one.frame/frame.html' => 'Page title'))); + + $browser->get('http://site.with.one.frame/'); + $this->assertEqual($browser->getTitle(), 'Frameset title'); + } + + function testFramesetWithSingleUnnamedFrame() { + $frameset = ''; + $browser = &$this->createBrowser($this->createUserAgent(array( + 'http://site.with.one.frame/' => $frameset, + 'http://site.with.one.frame/frame.html' => 'One frame'))); + + $this->assertEqual( + $browser->get('http://site.with.one.frame/'), + 'One frame'); + $this->assertIdentical( + $browser->getFrames(), + array(1 => 'http://site.with.one.frame/frame.html')); + } + + function testFramesetWithMultipleFrames() { + $frameset = '' . + '' . + '' . + '' . + ''; + $browser = &$this->createBrowser($this->createUserAgent(array( + 'http://site.with.frames/' => $frameset, + 'http://site.with.frames/frame_a.html' => 'A frame', + 'http://site.with.frames/frame_b.html' => 'B frame', + 'http://site.with.frames/frame_c.html' => 'C frame'))); + + $this->assertEqual( + $browser->get('http://site.with.frames/'), + 'A frameB frameC frame'); + $this->assertIdentical($browser->getFrames(), array( + 'a' => 'http://site.with.frames/frame_a.html', + 'b' => 'http://site.with.frames/frame_b.html', + 'c' => 'http://site.with.frames/frame_c.html')); + } + + function testFrameFocusByName() { + $frameset = '' . + '' . + '' . + '' . + ''; + $browser = &$this->createBrowser($this->createUserAgent(array( + 'http://site.with.frames/' => $frameset, + 'http://site.with.frames/frame_a.html' => 'A frame', + 'http://site.with.frames/frame_b.html' => 'B frame', + 'http://site.with.frames/frame_c.html' => 'C frame'))); + + $browser->get('http://site.with.frames/'); + $browser->setFrameFocus('a'); + $this->assertEqual($browser->getContent(), 'A frame'); + $browser->setFrameFocus('b'); + $this->assertEqual($browser->getContent(), 'B frame'); + $browser->setFrameFocus('c'); + $this->assertEqual($browser->getContent(), 'C frame'); + } + + function testFramesetWithSomeNamedFrames() { + $frameset = '' . + '' . + '' . + '' . + '' . + ''; + $browser = &$this->createBrowser($this->createUserAgent(array( + 'http://site.with.frames/' => $frameset, + 'http://site.with.frames/frame_a.html' => 'A frame', + 'http://site.with.frames/frame_b.html' => 'B frame', + 'http://site.with.frames/frame_c.html' => 'C frame', + 'http://site.with.frames/frame_d.html' => 'D frame'))); + + $this->assertEqual( + $browser->get('http://site.with.frames/'), + 'A frameB frameC frameD frame'); + $this->assertIdentical($browser->getFrames(), array( + 'a' => 'http://site.with.frames/frame_a.html', + 2 => 'http://site.with.frames/frame_b.html', + 'c' => 'http://site.with.frames/frame_c.html', + 4 => 'http://site.with.frames/frame_d.html')); + } + + function testFrameFocusWithMixedNamesAndIndexes() { + $frameset = '' . + '' . + '' . + '' . + '' . + ''; + $browser = &$this->createBrowser($this->createUserAgent(array( + 'http://site.with.frames/' => $frameset, + 'http://site.with.frames/frame_a.html' => 'A frame', + 'http://site.with.frames/frame_b.html' => 'B frame', + 'http://site.with.frames/frame_c.html' => 'C frame', + 'http://site.with.frames/frame_d.html' => 'D frame'))); + + $browser->get('http://site.with.frames/'); + $browser->setFrameFocus('a'); + $this->assertEqual($browser->getContent(), 'A frame'); + $browser->setFrameFocus(2); + $this->assertEqual($browser->getContent(), 'B frame'); + $browser->setFrameFocus('c'); + $this->assertEqual($browser->getContent(), 'C frame'); + $browser->setFrameFocus(4); + $this->assertEqual($browser->getContent(), 'D frame'); + $browser->clearFrameFocus(); + $this->assertEqual($browser->getContent(), 'A frameB frameC frameD frame'); + } + + function testNestedFrameset() { + $inner = '' . + '' . + ''; + $outer = '' . + '' . + ''; + $browser = &$this->createBrowser($this->createUserAgent(array( + 'http://site.with.nested.frame/' => $outer, + 'http://site.with.nested.frame/inner.html' => $inner, + 'http://site.with.nested.frame/page.html' => 'The page'))); + + $this->assertEqual( + $browser->get('http://site.with.nested.frame/'), + 'The page'); + $this->assertIdentical($browser->getFrames(), array( + 'inner' => array( + 'page' => 'http://site.with.nested.frame/page.html'))); + } + + function testCanNavigateToNestedFrame() { + $inner = '' . + '' . + '' . + ''; + $outer = '' . + '' . + '' . + ''; + $browser = &$this->createBrowser($this->createUserAgent(array( + 'http://site.with.nested.frames/' => $outer, + 'http://site.with.nested.frames/inner.html' => $inner, + 'http://site.with.nested.frames/one.html' => 'Page one', + 'http://site.with.nested.frames/two.html' => 'Page two', + 'http://site.with.nested.frames/three.html' => 'Page three'))); + + $browser->get('http://site.with.nested.frames/'); + $this->assertEqual($browser->getContent(), 'Page onePage twoPage three'); + + $this->assertTrue($browser->setFrameFocus('inner')); + $this->assertEqual($browser->getFrameFocus(), array('inner')); + $this->assertTrue($browser->setFrameFocus('one')); + $this->assertEqual($browser->getFrameFocus(), array('inner', 'one')); + $this->assertEqual($browser->getContent(), 'Page one'); + + $this->assertTrue($browser->setFrameFocus('two')); + $this->assertEqual($browser->getFrameFocus(), array('inner', 'two')); + $this->assertEqual($browser->getContent(), 'Page two'); + + $browser->clearFrameFocus(); + $this->assertTrue($browser->setFrameFocus('three')); + $this->assertEqual($browser->getFrameFocus(), array('three')); + $this->assertEqual($browser->getContent(), 'Page three'); + + $this->assertTrue($browser->setFrameFocus('inner')); + $this->assertEqual($browser->getContent(), 'Page onePage two'); + } + + function testCanNavigateToNestedFrameByIndex() { + $inner = '' . + '' . + '' . + ''; + $outer = '' . + '' . + '' . + ''; + $browser = &$this->createBrowser($this->createUserAgent(array( + 'http://site.with.nested.frames/' => $outer, + 'http://site.with.nested.frames/inner.html' => $inner, + 'http://site.with.nested.frames/one.html' => 'Page one', + 'http://site.with.nested.frames/two.html' => 'Page two', + 'http://site.with.nested.frames/three.html' => 'Page three'))); + + $browser->get('http://site.with.nested.frames/'); + $this->assertEqual($browser->getContent(), 'Page onePage twoPage three'); + + $this->assertTrue($browser->setFrameFocusByIndex(1)); + $this->assertEqual($browser->getFrameFocus(), array(1)); + $this->assertTrue($browser->setFrameFocusByIndex(1)); + $this->assertEqual($browser->getFrameFocus(), array(1, 1)); + $this->assertEqual($browser->getContent(), 'Page one'); + + $this->assertTrue($browser->setFrameFocusByIndex(2)); + $this->assertEqual($browser->getFrameFocus(), array(1, 2)); + $this->assertEqual($browser->getContent(), 'Page two'); + + $browser->clearFrameFocus(); + $this->assertTrue($browser->setFrameFocusByIndex(2)); + $this->assertEqual($browser->getFrameFocus(), array(2)); + $this->assertEqual($browser->getContent(), 'Page three'); + + $this->assertTrue($browser->setFrameFocusByIndex(1)); + $this->assertEqual($browser->getContent(), 'Page onePage two'); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/collector_test.php b/tests/simpletest/test/collector_test.php new file mode 100644 index 00000000..992bbd96 --- /dev/null +++ b/tests/simpletest/test/collector_test.php @@ -0,0 +1,50 @@ +EqualExpectation($v = str_replace("\\", '/', $value), $message); + } + + function test($compare) { + return parent::test(str_replace("\\", '/', $compare)); + } +} + +class TestOfCollector extends UnitTestCase { + + function testCollectionIsAddedToGroup() { + $suite = &new MockTestSuite(); + $suite->expectMinimumCallCount('addTestFile', 2); + $suite->expectArguments( + 'addTestFile', + array(new PatternExpectation('/collectable\\.(1|2)$/'))); + $collector = &new SimpleCollector(); + $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); + } +} + +class TestOfPatternCollector extends UnitTestCase { + + function testAddingEverythingToGroup() { + $suite = &new MockTestSuite(); + $suite->expectCallCount('addTestFile', 2); + $suite->expectArguments( + 'addTestFile', + array(new PatternExpectation('/collectable\\.(1|2)$/'))); + $collector = &new SimplePatternCollector('/.*/'); + $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); + } + + function testOnlyMatchedFilesAreAddedToGroup() { + $suite = &new MockTestSuite(); + $suite->expectOnce('addTestFile', array(new PathEqualExpectation( + dirname(__FILE__) . '/support/collector/collectable.1'))); + $collector = &new SimplePatternCollector('/1$/'); + $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); + } +} +?> \ No newline at end of file diff --git a/tests/simpletest/test/compatibility_test.php b/tests/simpletest/test/compatibility_test.php new file mode 100644 index 00000000..80593813 --- /dev/null +++ b/tests/simpletest/test/compatibility_test.php @@ -0,0 +1,96 @@ += 0) { + eval('interface ComparisonInterface { }'); + eval('class ComparisonClassWithInterface implements ComparisonInterface { }'); + } + + class TestOfCompatibility extends UnitTestCase { + + function testIsA() { + $this->assertTrue(SimpleTestCompatibility::isA( + new ComparisonClass(), + 'ComparisonClass')); + $this->assertFalse(SimpleTestCompatibility::isA( + new ComparisonClass(), + 'ComparisonSubclass')); + $this->assertTrue(SimpleTestCompatibility::isA( + new ComparisonSubclass(), + 'ComparisonClass')); + } + + function testIdentityOfNumericStrings() { + $numericString1 = "123"; + $numericString2 = "00123"; + $this->assertNotIdentical($numericString1, $numericString2); + } + + function testIdentityOfObjects() { + $object1 = new ComparisonClass(); + $object2 = new ComparisonClass(); + $this->assertIdentical($object1, $object2); + } + + function testReferences () { + $thing = "Hello"; + $thing_reference = &$thing; + $thing_copy = $thing; + $this->assertTrue(SimpleTestCompatibility::isReference( + $thing, + $thing)); + $this->assertTrue(SimpleTestCompatibility::isReference( + $thing, + $thing_reference)); + $this->assertFalse(SimpleTestCompatibility::isReference( + $thing, + $thing_copy)); + } + + function testObjectReferences () { + $object = &new ComparisonClass(); + $object_reference = &$object; + $object_copy = new ComparisonClass(); + $object_assignment = $object; + $this->assertTrue(SimpleTestCompatibility::isReference( + $object, + $object)); + $this->assertTrue(SimpleTestCompatibility::isReference( + $object, + $object_reference)); + $this->assertFalse(SimpleTestCompatibility::isReference( + $object, + $object_copy)); + if (version_compare(phpversion(), '5', '>=')) { + $this->assertTrue(SimpleTestCompatibility::isReference( + $object, + $object_assignment)); + } else { + $this->assertFalse(SimpleTestCompatibility::isReference( + $object, + $object_assignment)); + } + } + + function testInteraceComparison() { + if (version_compare(phpversion(), '5', '<')) { + return; + } + + $object = new ComparisonClassWithInterface(); + $this->assertFalse(SimpleTestCompatibility::isA( + new ComparisonClass(), + 'ComparisonInterface')); + $this->assertTrue(SimpleTestCompatibility::isA( + new ComparisonClassWithInterface(), + 'ComparisonInterface')); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/cookies_test.php b/tests/simpletest/test/cookies_test.php new file mode 100644 index 00000000..f3a3860d --- /dev/null +++ b/tests/simpletest/test/cookies_test.php @@ -0,0 +1,225 @@ +assertFalse($cookie->getValue()); + $this->assertEqual($cookie->getPath(), "/"); + $this->assertIdentical($cookie->getHost(), false); + $this->assertFalse($cookie->getExpiry()); + $this->assertFalse($cookie->isSecure()); + } + + function testCookieAccessors() { + $cookie = new SimpleCookie( + "name", + "value", + "/path", + "Mon, 18 Nov 2002 15:50:29 GMT", + true); + $this->assertEqual($cookie->getName(), "name"); + $this->assertEqual($cookie->getValue(), "value"); + $this->assertEqual($cookie->getPath(), "/path/"); + $this->assertEqual($cookie->getExpiry(), "Mon, 18 Nov 2002 15:50:29 GMT"); + $this->assertTrue($cookie->isSecure()); + } + + function testFullHostname() { + $cookie = new SimpleCookie("name"); + $this->assertTrue($cookie->setHost("host.name.here")); + $this->assertEqual($cookie->getHost(), "host.name.here"); + $this->assertTrue($cookie->setHost("host.com")); + $this->assertEqual($cookie->getHost(), "host.com"); + } + + function testHostTruncation() { + $cookie = new SimpleCookie("name"); + $cookie->setHost("this.host.name.here"); + $this->assertEqual($cookie->getHost(), "host.name.here"); + $cookie->setHost("this.host.com"); + $this->assertEqual($cookie->getHost(), "host.com"); + $this->assertTrue($cookie->setHost("dashes.in-host.com")); + $this->assertEqual($cookie->getHost(), "in-host.com"); + } + + function testBadHosts() { + $cookie = new SimpleCookie("name"); + $this->assertFalse($cookie->setHost("gibberish")); + $this->assertFalse($cookie->setHost("host.here")); + $this->assertFalse($cookie->setHost("host..com")); + $this->assertFalse($cookie->setHost("...")); + $this->assertFalse($cookie->setHost("host.com.")); + } + + function testHostValidity() { + $cookie = new SimpleCookie("name"); + $cookie->setHost("this.host.name.here"); + $this->assertTrue($cookie->isValidHost("host.name.here")); + $this->assertTrue($cookie->isValidHost("that.host.name.here")); + $this->assertFalse($cookie->isValidHost("bad.host")); + $this->assertFalse($cookie->isValidHost("nearly.name.here")); + } + + function testPathValidity() { + $cookie = new SimpleCookie("name", "value", "/path"); + $this->assertFalse($cookie->isValidPath("/")); + $this->assertTrue($cookie->isValidPath("/path/")); + $this->assertTrue($cookie->isValidPath("/path/more")); + } + + function testSessionExpiring() { + $cookie = new SimpleCookie("name", "value", "/path"); + $this->assertTrue($cookie->isExpired(0)); + } + + function testTimestampExpiry() { + $cookie = new SimpleCookie("name", "value", "/path", 456); + $this->assertFalse($cookie->isExpired(0)); + $this->assertTrue($cookie->isExpired(457)); + $this->assertFalse($cookie->isExpired(455)); + } + + function testDateExpiry() { + $cookie = new SimpleCookie( + "name", + "value", + "/path", + "Mon, 18 Nov 2002 15:50:29 GMT"); + $this->assertTrue($cookie->isExpired("Mon, 18 Nov 2002 15:50:30 GMT")); + $this->assertFalse($cookie->isExpired("Mon, 18 Nov 2002 15:50:28 GMT")); + } + + function testAging() { + $cookie = new SimpleCookie("name", "value", "/path", 200); + $cookie->agePrematurely(199); + $this->assertFalse($cookie->isExpired(0)); + $cookie->agePrematurely(2); + $this->assertTrue($cookie->isExpired(0)); + } + } + + class TestOfCookieJar extends UnitTestCase { + + function testAddCookie() { + $jar = new SimpleCookieJar(); + $jar->setCookie("a", "A"); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); + } + + function testHostFilter() { + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'A', 'my-host.com'); + $jar->setCookie('b', 'B', 'another-host.com'); + $jar->setCookie('c', 'C'); + $this->assertEqual( + $jar->selectAsPairs(new SimpleUrl('my-host.com')), + array('a=A', 'c=C')); + $this->assertEqual( + $jar->selectAsPairs(new SimpleUrl('another-host.com')), + array('b=B', 'c=C')); + $this->assertEqual( + $jar->selectAsPairs(new SimpleUrl('www.another-host.com')), + array('b=B', 'c=C')); + $this->assertEqual( + $jar->selectAsPairs(new SimpleUrl('new-host.org')), + array('c=C')); + $this->assertEqual( + $jar->selectAsPairs(new SimpleUrl('/')), + array('a=A', 'b=B', 'c=C')); + } + + function testPathFilter() { + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'A', false, '/path/'); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/elsewhere')), array()); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/')), array('a=A')); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path')), array('a=A')); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/pa')), array()); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/here')), array('a=A')); + } + + function testPathFilterDeeply() { + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'A', false, '/path/more_path/'); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/')), array()); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path')), array()); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/pa')), array()); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/more_path/')), array('a=A')); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/more_path/and_more')), array('a=A')); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/not_here/')), array()); + } + + function testMultipleCookieWithDifferentPathsButSameName() { + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'abc', false, '/'); + $jar->setCookie('a', '123', false, '/path/here/'); + $this->assertEqual( + $jar->selectAsPairs(new SimpleUrl('/')), + array('a=abc')); + $this->assertEqual( + $jar->selectAsPairs(new SimpleUrl('my-host.com/')), + array('a=abc')); + $this->assertEqual( + $jar->selectAsPairs(new SimpleUrl('my-host.com/path/')), + array('a=abc')); + $this->assertEqual( + $jar->selectAsPairs(new SimpleUrl('my-host.com/path/here')), + array('a=abc', 'a=123')); + $this->assertEqual( + $jar->selectAsPairs(new SimpleUrl('my-host.com/path/here/there')), + array('a=abc', 'a=123')); + } + + function testOverwrite() { + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'abc', false, '/'); + $jar->setCookie('a', 'cde', false, '/'); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=cde')); + } + + function testClearSessionCookies() { + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'A', false, '/'); + $jar->restartSession(); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); + } + + function testExpiryFilterByDate() { + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'A', false, '/', 'Wed, 25-Dec-02 04:24:20 GMT'); + $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); + $jar->restartSession("Wed, 25-Dec-02 04:24:21 GMT"); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); + } + + function testExpiryFilterByAgeing() { + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'A', false, '/', 'Wed, 25-Dec-02 04:24:20 GMT'); + $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); + $jar->agePrematurely(2); + $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); + } + + function testCookieClearing() { + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'abc', false, '/'); + $jar->setCookie('a', '', false, '/'); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=')); + } + + function testCookieClearByLoweringDate() { + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'abc', false, '/', 'Wed, 25-Dec-02 04:24:21 GMT'); + $jar->setCookie('a', 'def', false, '/', 'Wed, 25-Dec-02 04:24:19 GMT'); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=def')); + $jar->restartSession('Wed, 25-Dec-02 04:24:20 GMT'); + $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/detached_test.php b/tests/simpletest/test/detached_test.php new file mode 100644 index 00000000..1b9337e8 --- /dev/null +++ b/tests/simpletest/test/detached_test.php @@ -0,0 +1,15 @@ +addTestCase(new DetachedTestCase($command)); + if (SimpleReporter::inCli()) { + exit ($test->run(new TextReporter()) ? 0 : 1); + } + $test->run(new HtmlReporter()); +?> \ No newline at end of file diff --git a/tests/simpletest/test/dumper_test.php b/tests/simpletest/test/dumper_test.php new file mode 100644 index 00000000..c911d3b0 --- /dev/null +++ b/tests/simpletest/test/dumper_test.php @@ -0,0 +1,87 @@ +assertEqual( + $dumper->clipString("Hello", 6), + "Hello", + "Hello, 6->%s"); + $this->assertEqual( + $dumper->clipString("Hello", 5), + "Hello", + "Hello, 5->%s"); + $this->assertEqual( + $dumper->clipString("Hello world", 3), + "Hel...", + "Hello world, 3->%s"); + $this->assertEqual( + $dumper->clipString("Hello world", 6, 3), + "Hello ...", + "Hello world, 6, 3->%s"); + $this->assertEqual( + $dumper->clipString("Hello world", 3, 6), + "...o w...", + "Hello world, 3, 6->%s"); + $this->assertEqual( + $dumper->clipString("Hello world", 4, 11), + "...orld", + "Hello world, 4, 11->%s"); + $this->assertEqual( + $dumper->clipString("Hello world", 4, 12), + "...orld", + "Hello world, 4, 12->%s"); + } + + function testDescribeNull() { + $dumper = new SimpleDumper(); + $this->assertPattern('/null/i', $dumper->describeValue(null)); + } + + function testDescribeBoolean() { + $dumper = new SimpleDumper(); + $this->assertPattern('/boolean/i', $dumper->describeValue(true)); + $this->assertPattern('/true/i', $dumper->describeValue(true)); + $this->assertPattern('/false/i', $dumper->describeValue(false)); + } + + function testDescribeString() { + $dumper = new SimpleDumper(); + $this->assertPattern('/string/i', $dumper->describeValue('Hello')); + $this->assertPattern('/Hello/', $dumper->describeValue('Hello')); + } + + function testDescribeInteger() { + $dumper = new SimpleDumper(); + $this->assertPattern('/integer/i', $dumper->describeValue(35)); + $this->assertPattern('/35/', $dumper->describeValue(35)); + } + + function testDescribeFloat() { + $dumper = new SimpleDumper(); + $this->assertPattern('/float/i', $dumper->describeValue(0.99)); + $this->assertPattern('/0\.99/', $dumper->describeValue(0.99)); + } + + function testDescribeArray() { + $dumper = new SimpleDumper(); + $this->assertPattern('/array/i', $dumper->describeValue(array(1, 4))); + $this->assertPattern('/2/i', $dumper->describeValue(array(1, 4))); + } + + function testDescribeObject() { + $dumper = new SimpleDumper(); + $this->assertPattern( + '/object/i', + $dumper->describeValue(new DumperDummy())); + $this->assertPattern( + '/DumperDummy/i', + $dumper->describeValue(new DumperDummy())); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/eclipse_test.php b/tests/simpletest/test/eclipse_test.php new file mode 100644 index 00000000..00832c63 --- /dev/null +++ b/tests/simpletest/test/eclipse_test.php @@ -0,0 +1,32 @@ +expectOnce('write',array($expected)); + $listener->setReturnValue('write',-1); + + $pathparts = pathinfo($fullpath); + $filename = $pathparts['basename']; + $test= &new TestSuite($filename); + $test->addTestFile($fullpath); + $test->run(new EclipseReporter(&$listener)); + $this->assertEqual($expected,$listener->output); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/encoding_test.php b/tests/simpletest/test/encoding_test.php new file mode 100644 index 00000000..1ef66642 --- /dev/null +++ b/tests/simpletest/test/encoding_test.php @@ -0,0 +1,191 @@ +assertEqual($pair->asRequest(), 'a=A'); + } + + function testMimeEncodedAsHeadersAndContent() { + $pair = new SimpleEncodedPair('a', 'A'); + $this->assertEqual( + $pair->asMime(), + "Content-Disposition: form-data; name=\"a\"\r\n\r\nA"); + } + + function testAttachmentEncodedAsHeadersWithDispositionAndContent() { + $part = new SimpleAttachment('a', 'A', 'aaa.txt'); + $this->assertEqual( + $part->asMime(), + "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" . + "Content-Type: text/plain\r\n\r\nA"); + } + } + + class TestOfEncoding extends UnitTestCase { + var $_content_so_far; + + function write($content) { + $this->_content_so_far .= $content; + } + + function clear() { + $this->_content_so_far = ''; + } + + function assertWritten($encoding, $content, $message = '%s') { + $this->clear(); + $encoding->writeTo($this); + $this->assertIdentical($this->_content_so_far, $content, $message); + } + + function testGetEmpty() { + $encoding = &new SimpleGetEncoding(); + $this->assertIdentical($encoding->getValue('a'), false); + $this->assertIdentical($encoding->asUrlRequest(), ''); + } + + function testPostEmpty() { + $encoding = &new SimplePostEncoding(); + $this->assertIdentical($encoding->getValue('a'), false); + $this->assertWritten($encoding, ''); + } + + function testPrefilled() { + $encoding = &new SimplePostEncoding(array('a' => 'aaa')); + $this->assertIdentical($encoding->getValue('a'), 'aaa'); + $this->assertWritten($encoding, 'a=aaa'); + } + + function testPrefilledWithObject() { + $encoding = &new SimplePostEncoding(new SimpleEncoding(array('a' => 'aaa'))); + $this->assertIdentical($encoding->getValue('a'), 'aaa'); + $this->assertWritten($encoding, 'a=aaa'); + } + + function testMultiplePrefilled() { + $encoding = &new SimplePostEncoding(array('a' => array('a1', 'a2'))); + $this->assertIdentical($encoding->getValue('a'), array('a1', 'a2')); + $this->assertWritten($encoding, 'a=a1&a=a2'); + } + + function testSingleParameter() { + $encoding = &new SimplePostEncoding(); + $encoding->add('a', 'Hello'); + $this->assertEqual($encoding->getValue('a'), 'Hello'); + $this->assertWritten($encoding, 'a=Hello'); + } + + function testFalseParameter() { + $encoding = &new SimplePostEncoding(); + $encoding->add('a', false); + $this->assertEqual($encoding->getValue('a'), false); + $this->assertWritten($encoding, ''); + } + + function testUrlEncoding() { + $encoding = &new SimplePostEncoding(); + $encoding->add('a', 'Hello there!'); + $this->assertWritten($encoding, 'a=Hello+there%21'); + } + + function testUrlEncodingOfKey() { + $encoding = &new SimplePostEncoding(); + $encoding->add('a!', 'Hello'); + $this->assertWritten($encoding, 'a%21=Hello'); + } + + function testMultipleParameter() { + $encoding = &new SimplePostEncoding(); + $encoding->add('a', 'Hello'); + $encoding->add('b', 'Goodbye'); + $this->assertWritten($encoding, 'a=Hello&b=Goodbye'); + } + + function testEmptyParameters() { + $encoding = &new SimplePostEncoding(); + $encoding->add('a', ''); + $encoding->add('b', ''); + $this->assertWritten($encoding, 'a=&b='); + } + + function testRepeatedParameter() { + $encoding = &new SimplePostEncoding(); + $encoding->add('a', 'Hello'); + $encoding->add('a', 'Goodbye'); + $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); + $this->assertWritten($encoding, 'a=Hello&a=Goodbye'); + } + + function testAddingLists() { + $encoding = &new SimplePostEncoding(); + $encoding->add('a', array('Hello', 'Goodbye')); + $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); + $this->assertWritten($encoding, 'a=Hello&a=Goodbye'); + } + + function testMergeInHash() { + $encoding = &new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B')); + $encoding->merge(array('a' => 'A2')); + $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); + $this->assertIdentical($encoding->getValue('b'), 'B'); + } + + function testMergeInObject() { + $encoding = &new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B')); + $encoding->merge(new SimpleEncoding(array('a' => 'A2'))); + $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); + $this->assertIdentical($encoding->getValue('b'), 'B'); + } + + function testPrefilledMultipart() { + $encoding = &new SimpleMultipartEncoding(array('a' => 'aaa'), 'boundary'); + $this->assertIdentical($encoding->getValue('a'), 'aaa'); + $this->assertwritten($encoding, + "--boundary\r\n" . + "Content-Disposition: form-data; name=\"a\"\r\n" . + "\r\n" . + "aaa\r\n" . + "--boundary--\r\n"); + } + + function testAttachment() { + $encoding = &new SimpleMultipartEncoding(array(), 'boundary'); + $encoding->attach('a', 'aaa', 'aaa.txt'); + $this->assertIdentical($encoding->getValue('a'), 'aaa.txt'); + $this->assertwritten($encoding, + "--boundary\r\n" . + "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" . + "Content-Type: text/plain\r\n" . + "\r\n" . + "aaa\r\n" . + "--boundary--\r\n"); + } + } + + class TestOfFormHeaders extends UnitTestCase { + + function testEmptyEncodingWritesZeroContentLength() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("Content-Length: 0\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); + $encoding = &new SimplePostEncoding(); + $encoding->writeHeadersTo($socket); + } + + function testEmptyMultipartEncodingWritesEndBoundaryContentLength() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("Content-Length: 14\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Content-Type: multipart/form-data, boundary=boundary\r\n")); + $encoding = &new SimpleMultipartEncoding(array(), 'boundary'); + $encoding->writeHeadersTo($socket); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/errors_test.php b/tests/simpletest/test/errors_test.php new file mode 100644 index 00000000..f43a7a15 --- /dev/null +++ b/tests/simpletest/test/errors_test.php @@ -0,0 +1,235 @@ +get('SimpleErrorQueue'); + $queue->clear(); + } + + function tearDown() { + $context = &SimpleTest::getContext(); + $queue = &$context->get('SimpleErrorQueue'); + $queue->clear(); + } + + function testOrder() { + $context = &SimpleTest::getContext(); + $queue = &$context->get('SimpleErrorQueue'); + $queue->add(1024, 'Ouch', 'here.php', 100); + $queue->add(512, 'Yuk', 'there.php', 101); + $this->assertEqual( + $queue->extract(), + array(1024, 'Ouch', 'here.php', 100)); + $this->assertEqual( + $queue->extract(), + array(512, 'Yuk', 'there.php', 101)); + $this->assertFalse($queue->extract()); + } + + function testAssertNoErrorsGivesTrueWhenNoErrors() { + $test = &new MockSimpleTestCase(); + $test->expectOnce('assert', array(new TrueExpectation(), true, 'Should be no errors')); + $test->setReturnValue('assert', true); + $queue = &new SimpleErrorQueue(); + $queue->setTestCase($test); + $this->assertTrue($queue->assertNoErrors('%s')); + } + + function testAssertNoErrorsIssuesFailWhenErrors() { + $test = &new MockSimpleTestCase(); + $test->expectOnce('assert', array(new TrueExpectation(), false, 'Should be no errors')); + $test->setReturnValue('assert', false); + $queue = &new SimpleErrorQueue(); + $queue->setTestCase($test); + $queue->add(1024, 'Ouch', 'here.php', 100); + $this->assertFalse($queue->assertNoErrors('%s')); + } + + function testAssertErrorFailsWhenNoError() { + $test = &new MockSimpleTestCase(); + $test->expectOnce('fail', array('Expected error not found')); + $test->setReturnValue('assert', false); + $queue = &new SimpleErrorQueue(); + $queue->setTestCase($test); + $this->assertFalse($queue->assertError(false, '%s')); + } + + function testAssertErrorFailsWhenErrorDoesntMatch() { + $test = &new MockSimpleTestCase(); + $test->expectOnce('assert', array( + new MockSimpleExpectation(), + 'B', + 'Expected PHP error [B] severity [E_USER_NOTICE] in [b.php] line [100]')); + $test->setReturnValue('assert', false); + $queue = &new SimpleErrorQueue(); + $queue->setTestCase($test); + $queue->add(1024, 'B', 'b.php', 100); + $this->assertFalse($queue->assertError(new MockSimpleExpectation(), '%s')); + } + + function testExpectationMatchCancelsIncomingError() { + $test = &new MockSimpleTestCase(); + $test->expectOnce('assert', array(new MockSimpleExpectation(), 'B', 'a message')); + $test->setReturnValue('assert', true); + $test->expectNever('error'); + $queue = &new SimpleErrorQueue(); + $queue->setTestCase($test); + $queue->expectError(new MockSimpleExpectation(), 'a message'); + $queue->add(1024, 'B', 'b.php', 100); + } + + function testExpectationMissTriggersError() { + $test = &new MockSimpleTestCase(); + $test->expectOnce('assert', array(new MockSimpleExpectation(), 'B', 'a message')); + $test->setReturnValue('assert', false); + $test->expectOnce('error'); + $queue = &new SimpleErrorQueue(); + $queue->setTestCase($test); + $queue->expectError(new MockSimpleExpectation(), 'a message'); + $queue->add(1024, 'B', 'b.php', 100); + } + } + + class TestOfErrorTrap extends UnitTestCase { + var $_old; + + function setUp() { + $this->_old = error_reporting(E_ALL); + set_error_handler('SimpleTestErrorHandler'); + } + + function tearDown() { + restore_error_handler(); + error_reporting($this->_old); + } + + function testQueueStartsEmpty() { + $context = &SimpleTest::getContext(); + $queue = &$context->get('SimpleErrorQueue'); + $this->assertFalse($queue->extract()); + } + + function testTrappedErrorPlacedInQueue() { + trigger_error('Ouch!'); + $context = &SimpleTest::getContext(); + $queue = &$context->get('SimpleErrorQueue'); + list($severity, $message, $file, $line) = $queue->extract(); + $this->assertEqual($message, 'Ouch!'); + $this->assertEqual($file, __FILE__); + $this->assertFalse($queue->extract()); + } + + function testErrorsAreSwallowedByMatchingExpectation() { + $this->expectError('Ouch!'); + trigger_error('Ouch!'); + } + + function testErrorsAreSwallowedInOrder() { + $this->expectError('a'); + $this->expectError('b'); + trigger_error('a'); + trigger_error('b'); + } + + function testAnyErrorCanBeSwallowed() { + $this->expectError(); + trigger_error('Ouch!'); + } + + function testErrorCanBeSwallowedByPatternMatching() { + $this->expectError(new PatternExpectation('/ouch/i')); + trigger_error('Ouch!'); + } + + function testErrorWithPercentsPassesWithNoSprintfError() { + $this->expectError("%"); + trigger_error('%'); + } + } + + class TestOfErrors extends UnitTestCase { + var $_old; + + function setUp() { + $this->_old = error_reporting(E_ALL); + } + + function tearDown() { + error_reporting($this->_old); + } + + function testDefaultWhenAllReported() { + error_reporting(E_ALL); + trigger_error('Ouch!'); + $this->assertError('Ouch!'); + } + + function testNoticeWhenReported() { + error_reporting(E_ALL); + trigger_error('Ouch!', E_USER_NOTICE); + $this->assertError('Ouch!'); + } + + function testWarningWhenReported() { + error_reporting(E_ALL); + trigger_error('Ouch!', E_USER_WARNING); + $this->assertError('Ouch!'); + } + + function testErrorWhenReported() { + error_reporting(E_ALL); + trigger_error('Ouch!', E_USER_ERROR); + $this->assertError('Ouch!'); + } + + function testNoNoticeWhenNotReported() { + error_reporting(0); + trigger_error('Ouch!', E_USER_NOTICE); + } + + function testNoWarningWhenNotReported() { + error_reporting(0); + trigger_error('Ouch!', E_USER_WARNING); + } + + function testNoticeSuppressedWhenReported() { + error_reporting(E_ALL); + @trigger_error('Ouch!', E_USER_NOTICE); + } + + function testWarningSuppressedWhenReported() { + error_reporting(E_ALL); + @trigger_error('Ouch!', E_USER_WARNING); + } + + function testErrorWithPercentsReportedWithNoSprintfError() { + trigger_error('%'); + $this->assertError('%'); + } + } + + class TestOfErrorsExcludingPHP52AndAbove extends UnitTestCase { + function skip() { + $this->skipIf(version_compare(phpversion(), '5.2', '>='), 'E_USER_ERROR not tested for PHP 5.2 and above'); + } + + function testNoErrorWhenNotReported() { + error_reporting(0); + trigger_error('Ouch!', E_USER_ERROR); + } + + function testErrorSuppressedWhenReported() { + error_reporting(E_ALL); + @trigger_error('Ouch!', E_USER_ERROR); + } + } + +// TODO: Add stacked error handler test +?> \ No newline at end of file diff --git a/tests/simpletest/test/exceptions_test.php b/tests/simpletest/test/exceptions_test.php new file mode 100644 index 00000000..af194ac4 --- /dev/null +++ b/tests/simpletest/test/exceptions_test.php @@ -0,0 +1,118 @@ +assertTrue($expectation->test(new MyTestException())); + $this->assertTrue($expectation->test(new HigherTestException())); + $this->assertFalse($expectation->test(new OtherTestException())); + } + + function testMatchesClassAndMessageWhenExceptionExpected() { + $expectation = new ExceptionExpectation(new MyTestException('Hello')); + $this->assertTrue($expectation->test(new MyTestException('Hello'))); + $this->assertFalse($expectation->test(new HigherTestException('Hello'))); + $this->assertFalse($expectation->test(new OtherTestException('Hello'))); + $this->assertFalse($expectation->test(new MyTestException('Goodbye'))); + $this->assertFalse($expectation->test(new MyTestException())); + } + + function testMessagelessExceptionMatchesOnlyOnClass() { + $expectation = new ExceptionExpectation(new MyTestException()); + $this->assertTrue($expectation->test(new MyTestException())); + $this->assertFalse($expectation->test(new HigherTestException())); + } +} + +class TestOfExceptionTrap extends UnitTestCase { + + function testNoExceptionsInQueueMeansNoTestMessages() { + $test = new MockSimpleTestCase(); + $test->expectNever('assert'); + $queue = new SimpleExceptionTrap(); + $this->assertFalse($queue->isExpected($test, new Exception())); + } + + function testMatchingExceptionGivesTrue() { + $expectation = new MockSimpleExpectation(); + $expectation->setReturnValue('test', true); + $test = new MockSimpleTestCase(); + $test->setReturnValue('assert', true); + $queue = new SimpleExceptionTrap(); + $queue->expectException($expectation, 'message'); + $this->assertTrue($queue->isExpected($test, new Exception())); + } + + function testMatchingExceptionTriggersAssertion() { + $test = new MockSimpleTestCase(); + $test->expectOnce('assert', array( + '*', + new ExceptionExpectation(new Exception()), + 'message')); + $queue = new SimpleExceptionTrap(); + $queue->expectException(new ExceptionExpectation(new Exception()), 'message'); + $queue->isExpected($test, new Exception()); + } +} + +class TestOfCatchingExceptions extends UnitTestCase { + + function testCanCatchAnyExpectedException() { + $this->expectException(); + throw new Exception(); + } + + function testCanMatchExceptionByClass() { + $this->expectException('MyTestException'); + throw new HigherTestException(); + } + + function testCanMatchExceptionExactly() { + $this->expectException(new Exception('Ouch')); + throw new Exception('Ouch'); + } + + function testLastListedExceptionIsTheOneThatCounts() { + $this->expectException('OtherTestException'); + $this->expectException('MyTestException'); + throw new HigherTestException(); + } +} + +class Test1Exception extends Exception {} +class Test2Exception extends Exception {} + +class TestOfCallingTearDownWithExceptions extends UnitTestCase { + public function setUp() { + $GLOBALS['setUp'] = true; + } + + public function tearDown() { + $GLOBALS['tearDown'] = true; + } + + public function test1() { + $this->assertTrue($GLOBALS['setUp']); + $this->assertNull($GLOBALS['tearDown']); + $this->expectException('Test1Exception'); + throw new Test1Exception(__FUNCTION__); + } + + public function test2() { + $this->assertTrue($GLOBALS['setUp']); + $this->assertTrue($GLOBALS['tearDown']); + $this->expectException('Test2Exception'); + throw new Test2Exception(__FUNCTION__); + } +} +?> \ No newline at end of file diff --git a/tests/simpletest/test/expectation_test.php b/tests/simpletest/test/expectation_test.php new file mode 100644 index 00000000..6bd68d08 --- /dev/null +++ b/tests/simpletest/test/expectation_test.php @@ -0,0 +1,205 @@ +assertTrue($is_true->test(true)); + $this->assertFalse($is_true->test(false)); + } + + function testStringMatch() { + $hello = &new EqualExpectation("Hello"); + $this->assertTrue($hello->test("Hello")); + $this->assertFalse($hello->test("Goodbye")); + } + + function testInteger() { + $fifteen = &new EqualExpectation(15); + $this->assertTrue($fifteen->test(15)); + $this->assertFalse($fifteen->test(14)); + } + + function testFloat() { + $pi = &new EqualExpectation(3.14); + $this->assertTrue($pi->test(3.14)); + $this->assertFalse($pi->test(3.15)); + } + + function testArray() { + $colours = &new EqualExpectation(array("r", "g", "b")); + $this->assertTrue($colours->test(array("r", "g", "b"))); + $this->assertFalse($colours->test(array("g", "b", "r"))); + } + + function testHash() { + $is_blue = &new EqualExpectation(array("r" => 0, "g" => 0, "b" => 255)); + $this->assertTrue($is_blue->test(array("r" => 0, "g" => 0, "b" => 255))); + $this->assertFalse($is_blue->test(array("r" => 0, "g" => 255, "b" => 0))); + } + + function testHashWithOutOfOrderKeysShouldStillMatch() { + $any_order = &new EqualExpectation(array('a' => 1, 'b' => 2)); + $this->assertTrue($any_order->test(array('b' => 2, 'a' => 1))); + } + } + + class TestOfWithin extends UnitTestCase { + + function testWithinFloatingPointMargin() { + $within = new WithinMarginExpectation(1.0, 0.2); + $this->assertFalse($within->test(0.7)); + $this->assertTrue($within->test(0.8)); + $this->assertTrue($within->test(0.9)); + $this->assertTrue($within->test(1.1)); + $this->assertTrue($within->test(1.2)); + $this->assertFalse($within->test(1.3)); + } + + function testOutsideFloatingPointMargin() { + $within = new OutsideMarginExpectation(1.0, 0.2); + $this->assertTrue($within->test(0.7)); + $this->assertFalse($within->test(0.8)); + $this->assertFalse($within->test(1.2)); + $this->assertTrue($within->test(1.3)); + } + } + + class TestOfInequality extends UnitTestCase { + + function testStringMismatch() { + $not_hello = &new NotEqualExpectation("Hello"); + $this->assertTrue($not_hello->test("Goodbye")); + $this->assertFalse($not_hello->test("Hello")); + } + } + + class RecursiveNasty { + var $_me; + + function RecursiveNasty() { + $this->_me = $this; + } + } + + class TestOfIdentity extends UnitTestCase { + + function testType() { + $string = &new IdenticalExpectation("37"); + $this->assertTrue($string->test("37")); + $this->assertFalse($string->test(37)); + $this->assertFalse($string->test("38")); + } + + function _testNastyPhp5Bug() { + $this->assertFalse(new RecursiveNasty() != new RecursiveNasty()); + } + + function _testReallyHorribleRecursiveStructure() { + $hopeful = &new IdenticalExpectation(new RecursiveNasty()); + $this->assertTrue($hopeful->test(new RecursiveNasty())); + } + } + + class TestOfNonIdentity extends UnitTestCase { + + function testType() { + $string = &new NotIdenticalExpectation("37"); + $this->assertTrue($string->test("38")); + $this->assertTrue($string->test(37)); + $this->assertFalse($string->test("37")); + } + } + + class TestOfPatterns extends UnitTestCase { + + function testWanted() { + $pattern = &new PatternExpectation('/hello/i'); + $this->assertTrue($pattern->test("Hello world")); + $this->assertFalse($pattern->test("Goodbye world")); + } + + function testUnwanted() { + $pattern = &new NoPatternExpectation('/hello/i'); + $this->assertFalse($pattern->test("Hello world")); + $this->assertTrue($pattern->test("Goodbye world")); + } + } + + class ExpectedMethodTarget { + function hasThisMethod() {} + } + + class TestOfMethodExistence extends UnitTestCase { + + function testHasMethod() { + $instance = &new ExpectedMethodTarget(); + $expectation = &new MethodExistsExpectation('hasThisMethod'); + $this->assertTrue($expectation->test($instance)); + $expectation = &new MethodExistsExpectation('doesNotHaveThisMethod'); + $this->assertFalse($expectation->test($instance)); + } + } + + class TestOfIsA extends UnitTestCase { + + function testString() { + $expectation = &new IsAExpectation('string'); + $this->assertTrue($expectation->test('Hello')); + $this->assertFalse($expectation->test(5)); + } + + function testBoolean() { + $expectation = &new IsAExpectation('boolean'); + $this->assertTrue($expectation->test(true)); + $this->assertFalse($expectation->test(1)); + } + + function testBool() { + $expectation = &new IsAExpectation('bool'); + $this->assertTrue($expectation->test(true)); + $this->assertFalse($expectation->test(1)); + } + + function testDouble() { + $expectation = &new IsAExpectation('double'); + $this->assertTrue($expectation->test(5.0)); + $this->assertFalse($expectation->test(5)); + } + + function testFloat() { + $expectation = &new IsAExpectation('float'); + $this->assertTrue($expectation->test(5.0)); + $this->assertFalse($expectation->test(5)); + } + + function testReal() { + $expectation = &new IsAExpectation('real'); + $this->assertTrue($expectation->test(5.0)); + $this->assertFalse($expectation->test(5)); + } + + function testInteger() { + $expectation = &new IsAExpectation('integer'); + $this->assertTrue($expectation->test(5)); + $this->assertFalse($expectation->test(5.0)); + } + + function testInt() { + $expectation = &new IsAExpectation('int'); + $this->assertTrue($expectation->test(5)); + $this->assertFalse($expectation->test(5.0)); + } + } + + class TestOfNotA extends UnitTestCase { + + function testString() { + $expectation = &new NotAExpectation('string'); + $this->assertFalse($expectation->test('Hello')); + $this->assertTrue($expectation->test(5)); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/form_test.php b/tests/simpletest/test/form_test.php new file mode 100644 index 00000000..1d33a01a --- /dev/null +++ b/tests/simpletest/test/form_test.php @@ -0,0 +1,328 @@ + 'GET', 'action' => 'here.php', 'id' => '33')); + $form = &new SimpleForm($tag, new SimpleUrl('http://host/a/index.html')); + $this->assertEqual($form->getMethod(), 'get'); + $this->assertEqual( + $form->getAction(), + new SimpleUrl('http://host/a/here.php')); + $this->assertIdentical($form->getId(), '33'); + $this->assertNull($form->getValue(new SimpleByName('a'))); + } + + function testEmptyAction() { + $tag = &new SimpleFormTag(array('method' => 'GET', 'action' => '', 'id' => '33')); + $form = &new SimpleForm($tag, new SimpleUrl('http://host/a/index.html')); + $this->assertEqual( + $form->getAction(), + new SimpleUrl('http://host/a/index.html')); + } + + function testMissingAction() { + $tag = &new SimpleFormTag(array('method' => 'GET', 'id' => '33')); + $form = &new SimpleForm($tag, new SimpleUrl('http://host/a/index.html')); + $this->assertEqual( + $form->getAction(), + new SimpleUrl('http://host/a/index.html')); + } + + function testRootAction() { + $tag = &new SimpleFormTag(array('method' => 'GET', 'action' => '/', 'id' => '33')); + $form = &new SimpleForm($tag, new SimpleUrl('http://host/a/index.html')); + $this->assertEqual( + $form->getAction(), + new SimpleUrl('http://host/')); + } + + function testDefaultFrameTargetOnForm() { + $tag = &new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php', 'id' => '33')); + $form = &new SimpleForm($tag, new SimpleUrl('http://host/a/index.html')); + $form->setDefaultTarget('frame'); + + $expected = new SimpleUrl('http://host/a/here.php'); + $expected->setTarget('frame'); + $this->assertEqual($form->getAction(), $expected); + } + + function testTextWidget() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $form->addWidget(new SimpleTextTag( + array('name' => 'me', 'type' => 'text', 'value' => 'Myself'))); + $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Myself'); + $this->assertTrue($form->setField(new SimpleByName('me'), 'Not me')); + $this->assertFalse($form->setField(new SimpleByName('not_present'), 'Not me')); + $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Not me'); + $this->assertNull($form->getValue(new SimpleByName('not_present'))); + } + + function testTextWidgetById() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $form->addWidget(new SimpleTextTag( + array('name' => 'me', 'type' => 'text', 'value' => 'Myself', 'id' => 50))); + $this->assertIdentical($form->getValue(new SimpleById(50)), 'Myself'); + $this->assertTrue($form->setField(new SimpleById(50), 'Not me')); + $this->assertIdentical($form->getValue(new SimpleById(50)), 'Not me'); + } + + function testTextWidgetByLabel() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $widget = &new SimpleTextTag(array('name' => 'me', 'type' => 'text', 'value' => 'a')); + $form->addWidget($widget); + $widget->setLabel('thing'); + $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'a'); + $this->assertTrue($form->setField(new SimpleByLabel('thing'), 'b')); + $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'b'); + } + + function testSubmitEmpty() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $this->assertIdentical($form->submit(), new SimpleGetEncoding()); + } + + function testSubmitButton() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('http://host')); + $form->addWidget(new SimpleSubmitTag( + array('type' => 'submit', 'name' => 'go', 'value' => 'Go!', 'id' => '9'))); + $this->assertTrue($form->hasSubmit(new SimpleByName('go'))); + $this->assertEqual($form->getValue(new SimpleByName('go')), 'Go!'); + $this->assertEqual($form->getValue(new SimpleById(9)), 'Go!'); + $this->assertEqual( + $form->submitButton(new SimpleByName('go')), + new SimpleGetEncoding(array('go' => 'Go!'))); + $this->assertEqual( + $form->submitButton(new SimpleByLabel('Go!')), + new SimpleGetEncoding(array('go' => 'Go!'))); + $this->assertEqual( + $form->submitButton(new SimpleById(9)), + new SimpleGetEncoding(array('go' => 'Go!'))); + } + + function testSubmitWithAdditionalParameters() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('http://host')); + $form->addWidget(new SimpleSubmitTag( + array('type' => 'submit', 'name' => 'go', 'value' => 'Go!'))); + $this->assertEqual( + $form->submitButton(new SimpleByLabel('Go!'), array('a' => 'A')), + new SimpleGetEncoding(array('go' => 'Go!', 'a' => 'A'))); + } + + function testSubmitButtonWithLabelOfSubmit() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('http://host')); + $form->addWidget(new SimpleSubmitTag( + array('type' => 'submit', 'name' => 'test', 'value' => 'Submit'))); + $this->assertEqual( + $form->submitButton(new SimpleByName('test')), + new SimpleGetEncoding(array('test' => 'Submit'))); + $this->assertEqual( + $form->submitButton(new SimpleByLabel('Submit')), + new SimpleGetEncoding(array('test' => 'Submit'))); + } + + function testSubmitButtonWithWhitespacePaddedLabelOfSubmit() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('http://host')); + $form->addWidget(new SimpleSubmitTag( + array('type' => 'submit', 'name' => 'test', 'value' => ' Submit '))); + $this->assertEqual( + $form->submitButton(new SimpleByLabel('Submit')), + new SimpleGetEncoding(array('test' => ' Submit '))); + } + + function testImageSubmitButton() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $form->addWidget(new SimpleImageSubmitTag(array( + 'type' => 'image', + 'src' => 'source.jpg', + 'name' => 'go', + 'alt' => 'Go!', + 'id' => '9'))); + $this->assertTrue($form->hasImage(new SimpleByLabel('Go!'))); + $this->assertEqual( + $form->submitImage(new SimpleByLabel('Go!'), 100, 101), + new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); + $this->assertTrue($form->hasImage(new SimpleByName('go'))); + $this->assertEqual( + $form->submitImage(new SimpleByName('go'), 100, 101), + new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); + $this->assertTrue($form->hasImage(new SimpleById(9))); + $this->assertEqual( + $form->submitImage(new SimpleById(9), 100, 101), + new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); + } + + function testImageSubmitButtonWithAdditionalData() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $form->addWidget(new SimpleImageSubmitTag(array( + 'type' => 'image', + 'src' => 'source.jpg', + 'name' => 'go', + 'alt' => 'Go!'))); + $this->assertEqual( + $form->submitImage(new SimpleByLabel('Go!'), 100, 101, array('a' => 'A')), + new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A'))); + } + + function testButtonTag() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('http://host')); + $widget = &new SimpleButtonTag( + array('type' => 'submit', 'name' => 'go', 'value' => 'Go', 'id' => '9')); + $widget->addContent('Go!'); + $form->addWidget($widget); + $this->assertTrue($form->hasSubmit(new SimpleByName('go'))); + $this->assertTrue($form->hasSubmit(new SimpleByLabel('Go!'))); + $this->assertEqual( + $form->submitButton(new SimpleByName('go')), + new SimpleGetEncoding(array('go' => 'Go'))); + $this->assertEqual( + $form->submitButton(new SimpleByLabel('Go!')), + new SimpleGetEncoding(array('go' => 'Go'))); + $this->assertEqual( + $form->submitButton(new SimpleById(9)), + new SimpleGetEncoding(array('go' => 'Go'))); + } + + function testSingleSelectFieldSubmitted() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $select = &new SimpleSelectionTag(array('name' => 'a')); + $select->addTag(new SimpleOptionTag( + array('value' => 'aaa', 'selected' => ''))); + $form->addWidget($select); + $this->assertIdentical( + $form->submit(), + new SimpleGetEncoding(array('a' => 'aaa'))); + } + + function testSingleSelectFieldSubmittedWithPost() { + $form = &new SimpleForm( + new SimpleFormTag(array('method' => 'post')), + new SimpleUrl('htp://host')); + $select = &new SimpleSelectionTag(array('name' => 'a')); + $select->addTag(new SimpleOptionTag( + array('value' => 'aaa', 'selected' => ''))); + $form->addWidget($select); + $this->assertIdentical( + $form->submit(), + new SimplePostEncoding(array('a' => 'aaa'))); + } + + function testUnchecked() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $form->addWidget(new SimpleCheckboxTag( + array('name' => 'me', 'type' => 'checkbox'))); + $this->assertIdentical($form->getValue(new SimpleByName('me')), false); + $this->assertTrue($form->setField(new SimpleByName('me'), 'on')); + $this->assertEqual($form->getValue(new SimpleByName('me')), 'on'); + $this->assertFalse($form->setField(new SimpleByName('me'), 'other')); + $this->assertEqual($form->getValue(new SimpleByName('me')), 'on'); + } + + function testChecked() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $form->addWidget(new SimpleCheckboxTag( + array('name' => 'me', 'value' => 'a', 'type' => 'checkbox', 'checked' => ''))); + $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); + $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); + $this->assertEqual($form->getValue(new SimpleByName('me')), 'a'); + $this->assertTrue($form->setField(new SimpleByName('me'), false)); + $this->assertEqual($form->getValue(new SimpleByName('me')), false); + } + + function testSingleUncheckedRadioButton() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $form->addWidget(new SimpleRadioButtonTag( + array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); + $this->assertIdentical($form->getValue(new SimpleByName('me')), false); + $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); + $this->assertEqual($form->getValue(new SimpleByName('me')), 'a'); + } + + function testSingleCheckedRadioButton() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $form->addWidget(new SimpleRadioButtonTag( + array('name' => 'me', 'value' => 'a', 'type' => 'radio', 'checked' => ''))); + $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); + $this->assertFalse($form->setField(new SimpleByName('me'), 'other')); + } + + function testUncheckedRadioButtons() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $form->addWidget(new SimpleRadioButtonTag( + array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); + $form->addWidget(new SimpleRadioButtonTag( + array('name' => 'me', 'value' => 'b', 'type' => 'radio'))); + $this->assertIdentical($form->getValue(new SimpleByName('me')), false); + $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); + $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); + $this->assertTrue($form->setField(new SimpleByName('me'), 'b')); + $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); + $this->assertFalse($form->setField(new SimpleByName('me'), 'c')); + $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); + } + + function testCheckedRadioButtons() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $form->addWidget(new SimpleRadioButtonTag( + array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); + $form->addWidget(new SimpleRadioButtonTag( + array('name' => 'me', 'value' => 'b', 'type' => 'radio', 'checked' => ''))); + $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); + $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); + $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); + } + + function testMultipleFieldsWithSameKey() { + $form = &new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $form->addWidget(new SimpleCheckboxTag( + array('name' => 'a', 'type' => 'checkbox', 'value' => 'me'))); + $form->addWidget(new SimpleCheckboxTag( + array('name' => 'a', 'type' => 'checkbox', 'value' => 'you'))); + $this->assertIdentical($form->getValue(new SimpleByName('a')), false); + $this->assertTrue($form->setField(new SimpleByName('a'), 'me')); + $this->assertIdentical($form->getValue(new SimpleByName('a')), 'me'); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/frames_test.php b/tests/simpletest/test/frames_test.php new file mode 100644 index 00000000..00e95012 --- /dev/null +++ b/tests/simpletest/test/frames_test.php @@ -0,0 +1,575 @@ +setReturnValue('getTitle', 'This page'); + $frameset = &new SimpleFrameset($page); + $this->assertEqual($frameset->getTitle(), 'This page'); + } + + function TestHeadersReadFromFramesetByDefault() { + $page = &new MockSimplePage(); + $page->setReturnValue('getHeaders', 'Header: content'); + $page->setReturnValue('getMimeType', 'text/xml'); + $page->setReturnValue('getResponseCode', 401); + $page->setReturnValue('getTransportError', 'Could not parse headers'); + $page->setReturnValue('getAuthentication', 'Basic'); + $page->setReturnValue('getRealm', 'Safe place'); + + $frameset = &new SimpleFrameset($page); + + $this->assertIdentical($frameset->getHeaders(), 'Header: content'); + $this->assertIdentical($frameset->getMimeType(), 'text/xml'); + $this->assertIdentical($frameset->getResponseCode(), 401); + $this->assertIdentical($frameset->getTransportError(), 'Could not parse headers'); + $this->assertIdentical($frameset->getAuthentication(), 'Basic'); + $this->assertIdentical($frameset->getRealm(), 'Safe place'); + } + + function testEmptyFramesetHasNoContent() { + $page = &new MockSimplePage(); + $page->setReturnValue('getRaw', 'This content'); + $frameset = &new SimpleFrameset($page); + $this->assertEqual($frameset->getRaw(), ''); + } + + function testRawContentIsFromOnlyFrame() { + $page = &new MockSimplePage(); + $page->expectNever('getRaw'); + + $frame = &new MockSimplePage(); + $frame->setReturnValue('getRaw', 'Stuff'); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame); + $this->assertEqual($frameset->getRaw(), 'Stuff'); + } + + function testRawContentIsFromAllFrames() { + $page = &new MockSimplePage(); + $page->expectNever('getRaw'); + + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue('getRaw', 'Stuff1'); + + $frame2 = &new MockSimplePage(); + $frame2->setReturnValue('getRaw', 'Stuff2'); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame1); + $frameset->addFrame($frame2); + $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); + } + + function testTextContentIsFromOnlyFrame() { + $page = &new MockSimplePage(); + $page->expectNever('getText'); + + $frame = &new MockSimplePage(); + $frame->setReturnValue('getText', 'Stuff'); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame); + $this->assertEqual($frameset->getText(), 'Stuff'); + } + + function testTextContentIsFromAllFrames() { + $page = &new MockSimplePage(); + $page->expectNever('getText'); + + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue('getText', 'Stuff1'); + + $frame2 = &new MockSimplePage(); + $frame2->setReturnValue('getText', 'Stuff2'); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame1); + $frameset->addFrame($frame2); + $this->assertEqual($frameset->getText(), 'Stuff1 Stuff2'); + } + + function testFieldFoundIsFirstInFramelist() { + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue('getField', null); + $frame1->expectOnce('getField', array(new SimpleByName('a'))); + + $frame2 = &new MockSimplePage(); + $frame2->setReturnValue('getField', 'A'); + $frame2->expectOnce('getField', array(new SimpleByName('a'))); + + $frame3 = &new MockSimplePage(); + $frame3->expectNever('getField'); + + $page = &new MockSimplePage(); + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame1); + $frameset->addFrame($frame2); + $frameset->addFrame($frame3); + $this->assertIdentical($frameset->getField(new SimpleByName('a')), 'A'); + } + + function testFrameReplacementByIndex() { + $page = &new MockSimplePage(); + $page->expectNever('getRaw'); + + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue('getRaw', 'Stuff1'); + + $frame2 = &new MockSimplePage(); + $frame2->setReturnValue('getRaw', 'Stuff2'); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame1); + $frameset->setFrame(array(1), $frame2); + $this->assertEqual($frameset->getRaw(), 'Stuff2'); + } + + function testFrameReplacementByName() { + $page = &new MockSimplePage(); + $page->expectNever('getRaw'); + + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue('getRaw', 'Stuff1'); + + $frame2 = &new MockSimplePage(); + $frame2->setReturnValue('getRaw', 'Stuff2'); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame1, 'a'); + $frameset->setFrame(array('a'), $frame2); + $this->assertEqual($frameset->getRaw(), 'Stuff2'); + } + } + + class TestOfFrameNavigation extends UnitTestCase { + + function testStartsWithoutFrameFocus() { + $page = &new MockSimplePage(); + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame); + $this->assertFalse($frameset->getFrameFocus()); + } + + function testCanFocusOnSingleFrame() { + $page = &new MockSimplePage(); + $page->expectNever('getRaw'); + + $frame = &new MockSimplePage(); + $frame->setReturnValue('getFrameFocus', array()); + $frame->setReturnValue('getRaw', 'Stuff'); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame); + + $this->assertFalse($frameset->setFrameFocusByIndex(0)); + $this->assertTrue($frameset->setFrameFocusByIndex(1)); + $this->assertEqual($frameset->getRaw(), 'Stuff'); + $this->assertFalse($frameset->setFrameFocusByIndex(2)); + $this->assertIdentical($frameset->getFrameFocus(), array(1)); + } + + function testContentComesFromFrameInFocus() { + $page = &new MockSimplePage(); + + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue('getRaw', 'Stuff1'); + $frame1->setReturnValue('getFrameFocus', array()); + + $frame2 = &new MockSimplePage(); + $frame2->setReturnValue('getRaw', 'Stuff2'); + $frame2->setReturnValue('getFrameFocus', array()); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame1); + $frameset->addFrame($frame2); + + $this->assertTrue($frameset->setFrameFocusByIndex(1)); + $this->assertEqual($frameset->getFrameFocus(), array(1)); + $this->assertEqual($frameset->getRaw(), 'Stuff1'); + + $this->assertTrue($frameset->setFrameFocusByIndex(2)); + $this->assertEqual($frameset->getFrameFocus(), array(2)); + $this->assertEqual($frameset->getRaw(), 'Stuff2'); + + $this->assertFalse($frameset->setFrameFocusByIndex(3)); + $this->assertEqual($frameset->getFrameFocus(), array(2)); + + $frameset->clearFrameFocus(); + $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); + } + + function testCanFocusByName() { + $page = &new MockSimplePage(); + + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue('getRaw', 'Stuff1'); + $frame1->setReturnValue('getFrameFocus', array()); + + $frame2 = &new MockSimplePage(); + $frame2->setReturnValue('getRaw', 'Stuff2'); + $frame2->setReturnValue('getFrameFocus', array()); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame1, 'A'); + $frameset->addFrame($frame2, 'B'); + + $this->assertTrue($frameset->setFrameFocus('A')); + $this->assertEqual($frameset->getFrameFocus(), array('A')); + $this->assertEqual($frameset->getRaw(), 'Stuff1'); + + $this->assertTrue($frameset->setFrameFocusByIndex(2)); + $this->assertEqual($frameset->getFrameFocus(), array('B')); + $this->assertEqual($frameset->getRaw(), 'Stuff2'); + + $this->assertFalse($frameset->setFrameFocus('z')); + + $frameset->clearFrameFocus(); + $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); + } + } + + class TestOfFramesetPageInterface extends UnitTestCase { + var $_page_interface; + var $_frameset_interface; + + function TestOfFramesetPageInterface() { + $this->UnitTestCase(); + $this->_page_interface = $this->_getPageMethods(); + $this->_frameset_interface = $this->_getFramesetMethods(); + } + + function assertListInAnyOrder($list, $expected) { + sort($list); + sort($expected); + $this->assertEqual($list, $expected); + } + + function _getPageMethods() { + $methods = array(); + foreach (get_class_methods('SimplePage') as $method) { + if (strtolower($method) == strtolower('SimplePage')) { + continue; + } + if (strtolower($method) == strtolower('getFrameset')) { + continue; + } + if (strncmp($method, '_', 1) == 0) { + continue; + } + if (strncmp($method, 'accept', 6) == 0) { + continue; + } + $methods[] = $method; + } + return $methods; + } + + function _getFramesetMethods() { + $methods = array(); + foreach (get_class_methods('SimpleFrameset') as $method) { + if (strtolower($method) == strtolower('SimpleFrameset')) { + continue; + } + if (strncmp($method, '_', 1) == 0) { + continue; + } + if (strncmp($method, 'add', 3) == 0) { + continue; + } + $methods[] = $method; + } + return $methods; + } + + function testFramsetHasPageInterface() { + $difference = array(); + foreach ($this->_page_interface as $method) { + if (! in_array($method, $this->_frameset_interface)) { + $this->fail("No [$method] in Frameset class"); + return; + } + } + $this->pass('Frameset covers Page interface'); + } + + function testHeadersReadFromFrameIfInFocus() { + $frame = &new MockSimplePage(); + $frame->setReturnValue('getUrl', new SimpleUrl('http://localhost/stuff')); + + $frame->setReturnValue('getRequest', 'POST stuff'); + $frame->setReturnValue('getMethod', 'POST'); + $frame->setReturnValue('getRequestData', array('a' => 'A')); + $frame->setReturnValue('getHeaders', 'Header: content'); + $frame->setReturnValue('getMimeType', 'text/xml'); + $frame->setReturnValue('getResponseCode', 401); + $frame->setReturnValue('getTransportError', 'Could not parse headers'); + $frame->setReturnValue('getAuthentication', 'Basic'); + $frame->setReturnValue('getRealm', 'Safe place'); + + $frameset = &new SimpleFrameset(new MockSimplePage()); + $frameset->addFrame($frame); + $frameset->setFrameFocusByIndex(1); + + $url = new SimpleUrl('http://localhost/stuff'); + $url->setTarget(1); + $this->assertIdentical($frameset->getUrl(), $url); + + $this->assertIdentical($frameset->getRequest(), 'POST stuff'); + $this->assertIdentical($frameset->getMethod(), 'POST'); + $this->assertIdentical($frameset->getRequestData(), array('a' => 'A')); + $this->assertIdentical($frameset->getHeaders(), 'Header: content'); + $this->assertIdentical($frameset->getMimeType(), 'text/xml'); + $this->assertIdentical($frameset->getResponseCode(), 401); + $this->assertIdentical($frameset->getTransportError(), 'Could not parse headers'); + $this->assertIdentical($frameset->getAuthentication(), 'Basic'); + $this->assertIdentical($frameset->getRealm(), 'Safe place'); + } + + function testAbsoluteUrlsComeFromBothFrames() { + $page = &new MockSimplePage(); + $page->expectNever('getAbsoluteUrls'); + + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue( + 'getAbsoluteUrls', + array('http://www.lastcraft.com/', 'http://myserver/')); + + $frame2 = &new MockSimplePage(); + $frame2->setReturnValue( + 'getAbsoluteUrls', + array('http://www.lastcraft.com/', 'http://test/')); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame1); + $frameset->addFrame($frame2); + $this->assertListInAnyOrder( + $frameset->getAbsoluteUrls(), + array('http://www.lastcraft.com/', 'http://myserver/', 'http://test/')); + } + + function testRelativeUrlsComeFromBothFrames() { + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue( + 'getRelativeUrls', + array('/', '.', '/test/', 'goodbye.php')); + + $frame2 = &new MockSimplePage(); + $frame2->setReturnValue( + 'getRelativeUrls', + array('/', '..', '/test/', 'hello.php')); + + $page = &new MockSimplePage(); + $page->expectNever('getRelativeUrls'); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame1); + $frameset->addFrame($frame2); + $this->assertListInAnyOrder( + $frameset->getRelativeUrls(), + array('/', '.', '/test/', 'goodbye.php', '..', 'hello.php')); + } + + function testLabelledUrlsComeFromBothFrames() { + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue( + 'getUrlsByLabel', + array(new SimpleUrl('goodbye.php')), + array('a')); + + $frame2 = &new MockSimplePage(); + $frame2->setReturnValue( + 'getUrlsByLabel', + array(new SimpleUrl('hello.php')), + array('a')); + + $frameset = &new SimpleFrameset(new MockSimplePage()); + $frameset->addFrame($frame1); + $frameset->addFrame($frame2, 'Two'); + + $expected1 = new SimpleUrl('goodbye.php'); + $expected1->setTarget(1); + $expected2 = new SimpleUrl('hello.php'); + $expected2->setTarget('Two'); + $this->assertEqual( + $frameset->getUrlsByLabel('a'), + array($expected1, $expected2)); + } + + function testUrlByIdComesFromFirstFrameToRespond() { + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue('getUrlById', new SimpleUrl('four.php'), array(4)); + $frame1->setReturnValue('getUrlById', false, array(5)); + + $frame2 = &new MockSimplePage(); + $frame2->setReturnValue('getUrlById', false, array(4)); + $frame2->setReturnValue('getUrlById', new SimpleUrl('five.php'), array(5)); + + $frameset = &new SimpleFrameset(new MockSimplePage()); + $frameset->addFrame($frame1); + $frameset->addFrame($frame2); + + $four = new SimpleUrl('four.php'); + $four->setTarget(1); + $this->assertEqual($frameset->getUrlById(4), $four); + $five = new SimpleUrl('five.php'); + $five->setTarget(2); + $this->assertEqual($frameset->getUrlById(5), $five); + } + + function testReadUrlsFromFrameInFocus() { + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue('getAbsoluteUrls', array('a')); + $frame1->setReturnValue('getRelativeUrls', array('r')); + $frame1->setReturnValue('getUrlsByLabel', array(new SimpleUrl('l'))); + $frame1->setReturnValue('getUrlById', new SimpleUrl('i')); + + $frame2 = &new MockSimplePage(); + $frame2->expectNever('getAbsoluteUrls'); + $frame2->expectNever('getRelativeUrls'); + $frame2->expectNever('getUrlsByLabel'); + $frame2->expectNever('getUrlById'); + + $frameset = &new SimpleFrameset(new MockSimplePage()); + $frameset->addFrame($frame1, 'A'); + $frameset->addFrame($frame2, 'B'); + $frameset->setFrameFocus('A'); + + $this->assertIdentical($frameset->getAbsoluteUrls(), array('a')); + $this->assertIdentical($frameset->getRelativeUrls(), array('r')); + $expected = new SimpleUrl('l'); + $expected->setTarget('A'); + $this->assertIdentical($frameset->getUrlsByLabel('label'), array($expected)); + $expected = new SimpleUrl('i'); + $expected->setTarget('A'); + $this->assertIdentical($frameset->getUrlById(99), $expected); + } + + function testReadFrameTaggedUrlsFromFrameInFocus() { + $frame = &new MockSimplePage(); + + $by_label = new SimpleUrl('l'); + $by_label->setTarget('L'); + $frame->setReturnValue('getUrlsByLabel', array($by_label)); + + $by_id = new SimpleUrl('i'); + $by_id->setTarget('I'); + $frame->setReturnValue('getUrlById', $by_id); + + $frameset = &new SimpleFrameset(new MockSimplePage()); + $frameset->addFrame($frame, 'A'); + $frameset->setFrameFocus('A'); + + $this->assertIdentical($frameset->getUrlsByLabel('label'), array($by_label)); + $this->assertIdentical($frameset->getUrlById(99), $by_id); + } + + function testFindingFormsById() { + $frame = &new MockSimplePage(); + $form = &new MockSimpleForm(); + $frame->setReturnReference('getFormById', $form, array('a')); + + $frameset = &new SimpleFrameset(new MockSimplePage()); + $frameset->addFrame(new MockSimplePage(), 'A'); + $frameset->addFrame($frame, 'B'); + $this->assertReference($frameset->getFormById('a'), $form); + + $frameset->setFrameFocus('A'); + $this->assertNull($frameset->getFormById('a')); + + $frameset->setFrameFocus('B'); + $this->assertReference($frameset->getFormById('a'), $form); + } + + function testFindingFormsBySubmit() { + $frame = &new MockSimplePage(); + $form = &new MockSimpleForm(); + $frame->setReturnReference( + 'getFormBySubmit', + $form, + array(new SimpleByLabel('a'))); + + $frameset = &new SimpleFrameset(new MockSimplePage()); + $frameset->addFrame(new MockSimplePage(), 'A'); + $frameset->addFrame($frame, 'B'); + $this->assertReference($frameset->getFormBySubmit(new SimpleByLabel('a')), $form); + + $frameset->setFrameFocus('A'); + $this->assertNull($frameset->getFormBySubmit(new SimpleByLabel('a'))); + + $frameset->setFrameFocus('B'); + $this->assertReference($frameset->getFormBySubmit(new SimpleByLabel('a')), $form); + } + + function testFindingFormsByImage() { + $frame = &new MockSimplePage(); + $form = &new MockSimpleForm(); + $frame->setReturnReference( + 'getFormByImage', + $form, + array(new SimpleByLabel('a'))); + + $frameset = &new SimpleFrameset(new MockSimplePage()); + $frameset->addFrame(new MockSimplePage(), 'A'); + $frameset->addFrame($frame, 'B'); + $this->assertReference($frameset->getFormByImage(new SimpleByLabel('a')), $form); + + $frameset->setFrameFocus('A'); + $this->assertNull($frameset->getFormByImage(new SimpleByLabel('a'))); + + $frameset->setFrameFocus('B'); + $this->assertReference($frameset->getFormByImage(new SimpleByLabel('a')), $form); + } + + function testSettingAllFrameFieldsWhenNoFrameFocus() { + $frame1 = &new MockSimplePage(); + $frame1->expectOnce('setField', array(new SimpleById(22), 'A')); + + $frame2 = &new MockSimplePage(); + $frame2->expectOnce('setField', array(new SimpleById(22), 'A')); + + $frameset = &new SimpleFrameset(new MockSimplePage()); + $frameset->addFrame($frame1, 'A'); + $frameset->addFrame($frame2, 'B'); + $frameset->setField(new SimpleById(22), 'A'); + } + + function testOnlySettingFieldFromFocusedFrame() { + $frame1 = &new MockSimplePage(); + $frame1->expectOnce('setField', array(new SimpleByLabelOrName('a'), 'A')); + + $frame2 = &new MockSimplePage(); + $frame2->expectNever('setField'); + + $frameset = &new SimpleFrameset(new MockSimplePage()); + $frameset->addFrame($frame1, 'A'); + $frameset->addFrame($frame2, 'B'); + $frameset->setFrameFocus('A'); + $frameset->setField(new SimpleByLabelOrName('a'), 'A'); + } + + function testOnlyGettingFieldFromFocusedFrame() { + $frame1 = &new MockSimplePage(); + $frame1->setReturnValue('getField', 'f', array(new SimpleByName('a'))); + + $frame2 = &new MockSimplePage(); + $frame2->expectNever('getField'); + + $frameset = &new SimpleFrameset(new MockSimplePage()); + $frameset->addFrame($frame1, 'A'); + $frameset->addFrame($frame2, 'B'); + $frameset->setFrameFocus('A'); + $this->assertIdentical($frameset->getField(new SimpleByName('a')), 'f'); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/http_test.php b/tests/simpletest/test/http_test.php new file mode 100644 index 00000000..40f0f572 --- /dev/null +++ b/tests/simpletest/test/http_test.php @@ -0,0 +1,427 @@ +expectArgumentsAt(0, 'write', array("GET /here.html HTTP/1.0\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Host: a.valid.host\r\n")); + $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); + $socket->expectCallCount('write', 3); + + $route = &new PartialSimpleRoute(); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleRoute(new SimpleUrl('http://a.valid.host/here.html')); + + $this->assertReference($route->createConnection('GET', 15), $socket); + } + + function testDefaultPostRequest() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("POST /here.html HTTP/1.0\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Host: a.valid.host\r\n")); + $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); + $socket->expectCallCount('write', 3); + + $route = &new PartialSimpleRoute(); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleRoute(new SimpleUrl('http://a.valid.host/here.html')); + + $route->createConnection('POST', 15); + } + + function testGetWithPort() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("GET /here.html HTTP/1.0\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Host: a.valid.host:81\r\n")); + $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); + $socket->expectCallCount('write', 3); + + $route = &new PartialSimpleRoute(); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleRoute(new SimpleUrl('http://a.valid.host:81/here.html')); + + $route->createConnection('GET', 15); + } + + function testGetWithParameters() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("GET /here.html?a=1&b=2 HTTP/1.0\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Host: a.valid.host\r\n")); + $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); + $socket->expectCallCount('write', 3); + + $route = &new PartialSimpleRoute(); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleRoute(new SimpleUrl('http://a.valid.host/here.html?a=1&b=2')); + + $route->createConnection('GET', 15); + } + } + + class TestOfProxyRoute extends UnitTestCase { + + function testDefaultGet() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("GET http://a.valid.host/here.html HTTP/1.0\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Host: my-proxy:8080\r\n")); + $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); + $socket->expectCallCount('write', 3); + + $route = &new PartialSimpleProxyRoute(); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleProxyRoute( + new SimpleUrl('http://a.valid.host/here.html'), + new SimpleUrl('http://my-proxy')); + $route->createConnection('GET', 15); + } + + function testDefaultPost() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("POST http://a.valid.host/here.html HTTP/1.0\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Host: my-proxy:8080\r\n")); + $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); + $socket->expectCallCount('write', 3); + + $route = &new PartialSimpleProxyRoute(); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleProxyRoute( + new SimpleUrl('http://a.valid.host/here.html'), + new SimpleUrl('http://my-proxy')); + $route->createConnection('POST', 15); + } + + function testGetWithPort() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("GET http://a.valid.host:81/here.html HTTP/1.0\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Host: my-proxy:8081\r\n")); + $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); + $socket->expectCallCount('write', 3); + + $route = &new PartialSimpleProxyRoute(); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleProxyRoute( + new SimpleUrl('http://a.valid.host:81/here.html'), + new SimpleUrl('http://my-proxy:8081')); + $route->createConnection('GET', 15); + } + + function testGetWithParameters() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("GET http://a.valid.host/here.html?a=1&b=2 HTTP/1.0\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Host: my-proxy:8080\r\n")); + $socket->expectArgumentsAt(2, 'write', array("Connection: close\r\n")); + $socket->expectCallCount('write', 3); + + $route = &new PartialSimpleProxyRoute(); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleProxyRoute( + new SimpleUrl('http://a.valid.host/here.html?a=1&b=2'), + new SimpleUrl('http://my-proxy')); + $route->createConnection('GET', 15); + } + + function testGetWithAuthentication() { + $encoded = base64_encode('Me:Secret'); + + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("GET http://a.valid.host/here.html HTTP/1.0\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Host: my-proxy:8080\r\n")); + $socket->expectArgumentsAt(2, 'write', array("Proxy-Authorization: Basic $encoded\r\n")); + $socket->expectArgumentsAt(3, 'write', array("Connection: close\r\n")); + $socket->expectCallCount('write', 4); + + $route = &new PartialSimpleProxyRoute(); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleProxyRoute( + new SimpleUrl('http://a.valid.host/here.html'), + new SimpleUrl('http://my-proxy'), + 'Me', + 'Secret'); + $route->createConnection('GET', 15); + } + } + + class TestOfHttpRequest extends UnitTestCase { + + function testReadingBadConnection() { + $socket = &new MockSimpleSocket(); + + $route = &new MockSimpleRoute(); + $route->setReturnReference('createConnection', $socket); + + $request = &new SimpleHttpRequest($route, new SimpleGetEncoding()); + $reponse = &$request->fetch(15); + $this->assertTrue($reponse->isError()); + } + + function testReadingGoodConnection() { + $socket = &new MockSimpleSocket(); + $socket->expectOnce('write', array("\r\n")); + + $route = &new MockSimpleRoute(); + $route->setReturnReference('createConnection', $socket); + $route->expectArguments('createConnection', array('GET', 15)); + + $request = &new SimpleHttpRequest($route, new SimpleGetEncoding()); + $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); + } + + function testWritingAdditionalHeaders() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("My: stuff\r\n")); + $socket->expectArgumentsAt(1, 'write', array("\r\n")); + $socket->expectCallCount('write', 2); + + $route = &new MockSimpleRoute(); + $route->setReturnReference('createConnection', $socket); + + $request = &new SimpleHttpRequest($route, new SimpleGetEncoding()); + $request->addHeaderLine('My: stuff'); + $request->fetch(15); + } + + function testCookieWriting() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("Cookie: a=A\r\n")); + $socket->expectArgumentsAt(1, 'write', array("\r\n")); + $socket->expectCallCount('write', 2); + + $route = &new MockSimpleRoute(); + $route->setReturnReference('createConnection', $socket); + + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'A'); + + $request = &new SimpleHttpRequest($route, new SimpleGetEncoding()); + $request->readCookiesFromJar($jar, new SimpleUrl('/')); + $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); + } + + function testMultipleCookieWriting() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("Cookie: a=A;b=B\r\n")); + + $route = &new MockSimpleRoute(); + $route->setReturnReference('createConnection', $socket); + + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'A'); + $jar->setCookie('b', 'B'); + + $request = &new SimpleHttpRequest($route, new SimpleGetEncoding()); + $request->readCookiesFromJar($jar, new SimpleUrl('/')); + $request->fetch(15); + } + } + + class TestOfHttpPostRequest extends UnitTestCase { + + function testReadingBadConnectionCausesErrorBecauseOfDeadSocket() { + $socket = &new MockSimpleSocket(); + + $route = &new MockSimpleRoute(); + $route->setReturnReference('createConnection', $socket); + + $request = &new SimpleHttpRequest($route, new SimplePostEncoding()); + $reponse = &$request->fetch(15); + $this->assertTrue($reponse->isError()); + } + + function testReadingGoodConnection() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("Content-Length: 0\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); + $socket->expectArgumentsAt(2, 'write', array("\r\n")); + $socket->expectArgumentsAt(3, 'write', array("")); + + $route = &new MockSimpleRoute(); + $route->setReturnReference('createConnection', $socket); + $route->expectArguments('createConnection', array('POST', 15)); + + $request = &new SimpleHttpRequest($route, new SimplePostEncoding()); + $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); + } + + function testContentHeadersCalculated() { + $socket = &new MockSimpleSocket(); + $socket->expectArgumentsAt(0, 'write', array("Content-Length: 3\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); + $socket->expectArgumentsAt(2, 'write', array("\r\n")); + $socket->expectArgumentsAt(3, 'write', array("a=A")); + + $route = &new MockSimpleRoute(); + $route->setReturnReference('createConnection', $socket); + $route->expectArguments('createConnection', array('POST', 15)); + + $request = &new SimpleHttpRequest( + $route, + new SimplePostEncoding(array('a' => 'A'))); + $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); + } + } + + class TestOfHttpHeaders extends UnitTestCase { + + function testParseBasicHeaders() { + $headers = new SimpleHttpHeaders( + "HTTP/1.1 200 OK\r\n" . + "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n" . + "Content-Type: text/plain\r\n" . + "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n" . + "Connection: close"); + $this->assertIdentical($headers->getHttpVersion(), "1.1"); + $this->assertIdentical($headers->getResponseCode(), 200); + $this->assertEqual($headers->getMimeType(), "text/plain"); + } + + function testNonStandardResponseHeader() { + $headers = new SimpleHttpHeaders( + "HTTP/1.1 302 (HTTP-Version SP Status-Code CRLF)\r\n" . + "Connection: close"); + $this->assertIdentical($headers->getResponseCode(), 302); + } + + function testCanParseMultipleCookies() { + $jar = &new MockSimpleCookieJar(); + $jar->expectAt(0, 'setCookie', array('a', 'aaa', 'host', '/here/', 'Wed, 25 Dec 2002 04:24:20 GMT')); + $jar->expectAt(1, 'setCookie', array('b', 'bbb', 'host', '/', false)); + + $headers = new SimpleHttpHeaders( + "HTTP/1.1 200 OK\r\n" . + "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n" . + "Content-Type: text/plain\r\n" . + "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n" . + "Set-Cookie: a=aaa; expires=Wed, 25-Dec-02 04:24:20 GMT; path=/here/\r\n" . + "Set-Cookie: b=bbb\r\n" . + "Connection: close"); + $headers->writeCookiesToJar($jar, new SimpleUrl('http://host')); + } + + function testCanRecogniseRedirect() { + $headers = new SimpleHttpHeaders("HTTP/1.1 301 OK\r\n" . + "Content-Type: text/plain\r\n" . + "Content-Length: 0\r\n" . + "Location: http://www.somewhere-else.com/\r\n" . + "Connection: close"); + $this->assertIdentical($headers->getResponseCode(), 301); + $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/"); + $this->assertTrue($headers->isRedirect()); + } + + function testCanParseChallenge() { + $headers = new SimpleHttpHeaders("HTTP/1.1 401 Authorization required\r\n" . + "Content-Type: text/plain\r\n" . + "Connection: close\r\n" . + "WWW-Authenticate: Basic realm=\"Somewhere\""); + $this->assertEqual($headers->getAuthentication(), 'Basic'); + $this->assertEqual($headers->getRealm(), 'Somewhere'); + $this->assertTrue($headers->isChallenge()); + } + } + + class TestOfHttpResponse extends UnitTestCase { + + function testBadRequest() { + $socket = &new MockSimpleSocket(); + $socket->setReturnValue('getSent', ''); + + $response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); + $this->assertTrue($response->isError()); + $this->assertPattern('/Nothing fetched/', $response->getError()); + $this->assertIdentical($response->getContent(), false); + $this->assertIdentical($response->getSent(), ''); + } + + function testBadSocketDuringResponse() { + $socket = &new MockSimpleSocket(); + $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\n"); + $socket->setReturnValueAt(1, "read", "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); + $socket->setReturnValue("read", ""); + $socket->setReturnValue('getSent', 'HTTP/1.1 ...'); + + $response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); + $this->assertTrue($response->isError()); + $this->assertEqual($response->getContent(), ''); + $this->assertEqual($response->getSent(), 'HTTP/1.1 ...'); + } + + function testIncompleteHeader() { + $socket = &new MockSimpleSocket(); + $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\n"); + $socket->setReturnValueAt(1, "read", "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); + $socket->setReturnValueAt(2, "read", "Content-Type: text/plain\r\n"); + $socket->setReturnValue("read", ""); + + $response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); + $this->assertTrue($response->isError()); + $this->assertEqual($response->getContent(), ""); + } + + function testParseOfResponseHeadersWhenChunked() { + $socket = &new MockSimpleSocket(); + $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\nDate: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); + $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); + $socket->setReturnValueAt(2, "read", "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\nConne"); + $socket->setReturnValueAt(3, "read", "ction: close\r\n\r\nthis is a test file\n"); + $socket->setReturnValueAt(4, "read", "with two lines in it\n"); + $socket->setReturnValue("read", ""); + + $response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); + $this->assertFalse($response->isError()); + $this->assertEqual( + $response->getContent(), + "this is a test file\nwith two lines in it\n"); + $headers = $response->getHeaders(); + $this->assertIdentical($headers->getHttpVersion(), "1.1"); + $this->assertIdentical($headers->getResponseCode(), 200); + $this->assertEqual($headers->getMimeType(), "text/plain"); + $this->assertFalse($headers->isRedirect()); + $this->assertFalse($headers->getLocation()); + } + + function testRedirect() { + $socket = &new MockSimpleSocket(); + $socket->setReturnValueAt(0, "read", "HTTP/1.1 301 OK\r\n"); + $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); + $socket->setReturnValueAt(2, "read", "Location: http://www.somewhere-else.com/\r\n"); + $socket->setReturnValueAt(3, "read", "Connection: close\r\n"); + $socket->setReturnValueAt(4, "read", "\r\n"); + $socket->setReturnValue("read", ""); + + $response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); + $headers = $response->getHeaders(); + $this->assertTrue($headers->isRedirect()); + $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/"); + } + + function testRedirectWithPort() { + $socket = &new MockSimpleSocket(); + $socket->setReturnValueAt(0, "read", "HTTP/1.1 301 OK\r\n"); + $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); + $socket->setReturnValueAt(2, "read", "Location: http://www.somewhere-else.com:80/\r\n"); + $socket->setReturnValueAt(3, "read", "Connection: close\r\n"); + $socket->setReturnValueAt(4, "read", "\r\n"); + $socket->setReturnValue("read", ""); + + $response = &new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); + $headers = $response->getHeaders(); + $this->assertTrue($headers->isRedirect()); + $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com:80/"); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/interfaces_test.php b/tests/simpletest/test/interfaces_test.php new file mode 100644 index 00000000..62677694 --- /dev/null +++ b/tests/simpletest/test/interfaces_test.php @@ -0,0 +1,119 @@ +assertIsA($mock, 'SimpleMock'); + $this->assertIsA($mock, 'MockDummyInterface'); + $this->assertTrue(method_exists($mock, 'aMethod')); + $this->assertTrue(method_exists($mock, 'anotherMethod')); + $this->assertNull($mock->aMethod()); + } + + function testMockedInterfaceExpectsParameters() { + $mock = new MockDummyInterface(); + $mock->anotherMethod(); + $this->assertError(); + } + + function testCannotPartiallyMockAnInterface() { + $this->assertFalse(class_exists('PartialDummyInterface')); + } + } + + class TestOfSpl extends UnitTestCase { + + function testCanMockAllSplClasses() { + if (! function_exists('spl_classes')) { + return; + } + foreach(spl_classes() as $class) { + $mock_class = "Mock$class"; + Mock::generate($class); + $this->assertIsA(new $mock_class(), $mock_class); + } + } + + function testExtensionOfCommonSplClasses() { + if (! function_exists('spl_classes')) { + return; + } + Mock::generate('IteratorImplementation'); + $this->assertIsA( + new IteratorImplementation(), + 'IteratorImplementation'); + Mock::generate('IteratorAggregateImplementation'); + $this->assertIsA( + new IteratorAggregateImplementation(), + 'IteratorAggregateImplementation'); + } + } + + class WithHint { + function hinted(DummyInterface $object) { } + } + + class ImplementsDummy implements DummyInterface { + function aMethod() { } + function anotherMethod($a) { } + function &referenceMethod(&$a) { } + function extraMethod($a = false) { } + } + Mock::generate('ImplementsDummy'); + + class TestOfImplementations extends UnitTestCase { + + function testMockedInterfaceCanPassThroughTypeHint() { + $mock = new MockDummyInterface(); + $hinter = new WithHint(); + $hinter->hinted($mock); + } + + function testImplementedInterfacesAreCarried() { + $mock = new MockImplementsDummy(); + $hinter = new WithHint(); + $hinter->hinted($mock); + } + + function testNoSpuriousWarningsWhenSkippingDefaultedParameter() { + $mock = new MockImplementsDummy(); + $mock->extraMethod(); + } + } + + interface SampleClassWithConstruct { + function __construct($something); + } + + class TestOfInterfaceMocksWithConstruct extends UnitTestCase { + function testBasicConstructOfAnInterface() { + Mock::generate('SampleClassWithConstruct'); + $this->assertNoErrors(); + } + } + + interface SampleInterfaceWithClone { + function __clone(); + } + + class TestOfSampleInterfaceWithClone extends UnitTestCase { + function testCanMockWithoutErrors() { + Mock::generate('SampleInterfaceWithClone'); + $this->assertNoErrors(); + } + } +?> diff --git a/tests/simpletest/test/live_test.php b/tests/simpletest/test/live_test.php new file mode 100644 index 00000000..be9dedb7 --- /dev/null +++ b/tests/simpletest/test/live_test.php @@ -0,0 +1,47 @@ +assertTrue($socket->isError()); + $this->assertPattern( + '/Cannot open \\[bad_url:111\\] with \\[/', + $socket->getError()); + $this->assertFalse($socket->isOpen()); + $this->assertFalse($socket->write('A message')); + } + + function testSocketClosure() { + $socket = &new SimpleSocket('www.lastcraft.com', 80, 15, 8); + $this->assertTrue($socket->isOpen()); + $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n")); + $socket->write("Host: www.lastcraft.com\r\n"); + $socket->write("Connection: close\r\n\r\n"); + $this->assertEqual($socket->read(), "HTTP/1.1"); + $socket->close(); + $this->assertIdentical($socket->read(), false); + } + + function testRecordOfSentCharacters() { + $socket = &new SimpleSocket('www.lastcraft.com', 80, 15); + $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n")); + $socket->write("Host: www.lastcraft.com\r\n"); + $socket->write("Connection: close\r\n\r\n"); + $socket->close(); + $this->assertEqual($socket->getSent(), + "GET /test/network_confirm.php HTTP/1.0\r\n" . + "Host: www.lastcraft.com\r\n" . + "Connection: close\r\n\r\n"); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/mock_objects_test.php b/tests/simpletest/test/mock_objects_test.php new file mode 100644 index 00000000..6dded0ec --- /dev/null +++ b/tests/simpletest/test/mock_objects_test.php @@ -0,0 +1,666 @@ +assertTrue($expectation->test(33)); + $this->assertTrue($expectation->test(false)); + $this->assertTrue($expectation->test(null)); + } + } + + class TestOfParametersExpectation extends UnitTestCase { + + function testEmptyMatch() { + $expectation = new ParametersExpectation(array()); + $this->assertTrue($expectation->test(array())); + $this->assertFalse($expectation->test(array(33))); + } + + function testSingleMatch() { + $expectation = new ParametersExpectation(array(0)); + $this->assertFalse($expectation->test(array(1))); + $this->assertTrue($expectation->test(array(0))); + } + + function testAnyMatch() { + $expectation = new ParametersExpectation(false); + $this->assertTrue($expectation->test(array())); + $this->assertTrue($expectation->test(array(1, 2))); + } + + function testMissingParameter() { + $expectation = new ParametersExpectation(array(0)); + $this->assertFalse($expectation->test(array())); + } + + function testNullParameter() { + $expectation = new ParametersExpectation(array(null)); + $this->assertTrue($expectation->test(array(null))); + $this->assertFalse($expectation->test(array())); + } + + function testAnythingExpectations() { + $expectation = new ParametersExpectation(array(new AnythingExpectation())); + $this->assertFalse($expectation->test(array())); + $this->assertIdentical($expectation->test(array(null)), true); + $this->assertIdentical($expectation->test(array(13)), true); + } + + function testOtherExpectations() { + $expectation = new ParametersExpectation( + array(new PatternExpectation('/hello/i'))); + $this->assertFalse($expectation->test(array('Goodbye'))); + $this->assertTrue($expectation->test(array('hello'))); + $this->assertTrue($expectation->test(array('Hello'))); + } + + function testIdentityOnly() { + $expectation = new ParametersExpectation(array("0")); + $this->assertFalse($expectation->test(array(0))); + $this->assertTrue($expectation->test(array("0"))); + } + + function testLongList() { + $expectation = new ParametersExpectation( + array("0", 0, new AnythingExpectation(), false)); + $this->assertTrue($expectation->test(array("0", 0, 37, false))); + $this->assertFalse($expectation->test(array("0", 0, 37, true))); + $this->assertFalse($expectation->test(array("0", 0, 37))); + } + } + + class TestOfCallMap extends UnitTestCase { + + function testEmpty() { + $map = new CallMap(); + $this->assertFalse($map->isMatch("any", array())); + $this->assertNull($map->findFirstMatch("any", array())); + } + + function testExactValue() { + $map = new CallMap(); + $map->addValue(array(0), "Fred"); + $map->addValue(array(1), "Jim"); + $map->addValue(array("1"), "Tom"); + $this->assertTrue($map->isMatch(array(0))); + $this->assertEqual($map->findFirstMatch(array(0)), "Fred"); + $this->assertTrue($map->isMatch(array(1))); + $this->assertEqual($map->findFirstMatch(array(1)), "Jim"); + $this->assertEqual($map->findFirstMatch(array("1")), "Tom"); + } + + function testExactReference() { + $map = new CallMap(); + $ref = "Fred"; + $map->addReference(array(0), $ref); + $this->assertEqual($map->findFirstMatch(array(0)), "Fred"); + $ref2 = &$map->findFirstMatch(array(0)); + $this->assertReference($ref2, $ref); + } + + function testWildcard() { + $map = new CallMap(); + $map->addValue(array(new AnythingExpectation(), 1, 3), "Fred"); + $this->assertTrue($map->isMatch(array(2, 1, 3))); + $this->assertEqual($map->findFirstMatch(array(2, 1, 3)), "Fred"); + } + + function testAllWildcard() { + $map = new CallMap(); + $this->assertFalse($map->isMatch(array(2, 1, 3))); + $map->addValue("", "Fred"); + $this->assertTrue($map->isMatch(array(2, 1, 3))); + $this->assertEqual($map->findFirstMatch(array(2, 1, 3)), "Fred"); + } + + function testOrdering() { + $map = new CallMap(); + $map->addValue(array(1, 2), "1, 2"); + $map->addValue(array(1, 3), "1, 3"); + $map->addValue(array(1), "1"); + $map->addValue(array(1, 4), "1, 4"); + $map->addValue(array(new AnythingExpectation()), "Any"); + $map->addValue(array(2), "2"); + $map->addValue("", "Default"); + $map->addValue(array(), "None"); + $this->assertEqual($map->findFirstMatch(array(1, 2)), "1, 2"); + $this->assertEqual($map->findFirstMatch(array(1, 3)), "1, 3"); + $this->assertEqual($map->findFirstMatch(array(1, 4)), "1, 4"); + $this->assertEqual($map->findFirstMatch(array(1)), "1"); + $this->assertEqual($map->findFirstMatch(array(2)), "Any"); + $this->assertEqual($map->findFirstMatch(array(3)), "Any"); + $this->assertEqual($map->findFirstMatch(array()), "Default"); + } + } + + class Dummy { + function Dummy() { + } + + function aMethod() { + return true; + } + + function anotherMethod() { + return true; + } + } + + Stub::generateSubclass('Dummy', 'StubDummy'); + Stub::generateSubclass('Dummy', 'AnotherStubDummy'); + Stub::generateSubclass('Dummy', 'StubDummyWithExtraMethods', array('extraMethod')); + + class SpecialSimpleStub extends SimpleMock { + function SpecialSimpleStub() { + $this->SimpleMock(); + } + } + SimpleTest::setMockBaseClass('SpecialSimpleStub'); + Stub::generateSubclass('Dummy', 'SpecialStubDummy'); + SimpleTest::setMockBaseClass('SimpleMock'); + + class TestOfStubGeneration extends UnitTestCase { + + function testCloning() { + $stub = &new StubDummy(); + $this->assertTrue(method_exists($stub, "aMethod")); + $this->assertNull($stub->aMethod(null)); + } + + function testCloningWithExtraMethod() { + $stub = &new StubDummyWithExtraMethods(); + $this->assertTrue(method_exists($stub, "extraMethod")); + } + + function testCloningWithChosenClassName() { + $stub = &new AnotherStubDummy(); + $this->assertTrue(method_exists($stub, "aMethod")); + } + + function testCloningWithDifferentBaseClass() { + $stub = &new SpecialStubDummy(); + $this->assertTrue(method_exists($stub, "aMethod")); + } + } + + class TestOfServerStubReturns extends UnitTestCase { + + function testDefaultReturn() { + $stub = &new StubDummy(); + $stub->setReturnValue("aMethod", "aaa"); + $this->assertIdentical($stub->aMethod(), "aaa"); + $this->assertIdentical($stub->aMethod(), "aaa"); + } + + function testParameteredReturn() { + $stub = &new StubDummy(); + $stub->setReturnValue("aMethod", "aaa", array(1, 2, 3)); + $this->assertNull($stub->aMethod()); + $this->assertIdentical($stub->aMethod(1, 2, 3), "aaa"); + } + + function testReferenceReturned() { + $stub = &new StubDummy(); + $object = new Dummy(); + $stub->setReturnReference("aMethod", $object, array(1, 2, 3)); + $this->assertReference($zref =& $stub->aMethod(1, 2, 3), $object); + } + + function testMultipleMethods() { + $stub = &new StubDummy(); + $stub->setReturnValue("aMethod", 100, array(1)); + $stub->setReturnValue("aMethod", 200, array(2)); + $stub->setReturnValue("anotherMethod", 10, array(1)); + $stub->setReturnValue("anotherMethod", 20, array(2)); + $this->assertIdentical($stub->aMethod(1), 100); + $this->assertIdentical($stub->anotherMethod(1), 10); + $this->assertIdentical($stub->aMethod(2), 200); + $this->assertIdentical($stub->anotherMethod(2), 20); + } + + function testReturnSequence() { + $stub = &new StubDummy(); + $stub->setReturnValueAt(0, "aMethod", "aaa"); + $stub->setReturnValueAt(1, "aMethod", "bbb"); + $stub->setReturnValueAt(3, "aMethod", "ddd"); + $this->assertIdentical($stub->aMethod(), "aaa"); + $this->assertIdentical($stub->aMethod(), "bbb"); + $this->assertNull($stub->aMethod()); + $this->assertIdentical($stub->aMethod(), "ddd"); + } + + function testReturnReferenceSequence() { + $stub = &new StubDummy(); + $object = new Dummy(); + $stub->setReturnReferenceAt(1, "aMethod", $object); + $this->assertNull($stub->aMethod()); + $this->assertReference($zref =& $stub->aMethod(), $object); + $this->assertNull($stub->aMethod()); + } + + function testComplicatedReturnSequence() { + $stub = &new StubDummy(); + $object = new Dummy(); + $stub->setReturnValueAt(1, "aMethod", "aaa", array("a")); + $stub->setReturnValueAt(1, "aMethod", "bbb"); + $stub->setReturnReferenceAt(2, "aMethod", $object, array('*', 2)); + $stub->setReturnValueAt(2, "aMethod", "value", array('*', 3)); + $stub->setReturnValue("aMethod", 3, array(3)); + $this->assertNull($stub->aMethod()); + $this->assertEqual($stub->aMethod("a"), "aaa"); + $this->assertReference($zref =& $stub->aMethod(1, 2), $object); + $this->assertEqual($stub->aMethod(3), 3); + $this->assertNull($stub->aMethod()); + } + + function testMultipleMethodSequences() { + $stub = &new StubDummy(); + $stub->setReturnValueAt(0, "aMethod", "aaa"); + $stub->setReturnValueAt(1, "aMethod", "bbb"); + $stub->setReturnValueAt(0, "anotherMethod", "ccc"); + $stub->setReturnValueAt(1, "anotherMethod", "ddd"); + $this->assertIdentical($stub->aMethod(), "aaa"); + $this->assertIdentical($stub->anotherMethod(), "ccc"); + $this->assertIdentical($stub->aMethod(), "bbb"); + $this->assertIdentical($stub->anotherMethod(), "ddd"); + } + + function testSequenceFallback() { + $stub = &new StubDummy(); + $stub->setReturnValueAt(0, "aMethod", "aaa", array('a')); + $stub->setReturnValueAt(1, "aMethod", "bbb", array('a')); + $stub->setReturnValue("aMethod", "AAA"); + $this->assertIdentical($stub->aMethod('a'), "aaa"); + $this->assertIdentical($stub->aMethod('b'), "AAA"); + } + + function testMethodInterference() { + $stub = &new StubDummy(); + $stub->setReturnValueAt(0, "anotherMethod", "aaa"); + $stub->setReturnValue("aMethod", "AAA"); + $this->assertIdentical($stub->aMethod(), "AAA"); + $this->assertIdentical($stub->anotherMethod(), "aaa"); + } + } + + Mock::generateSubclass('Dummy'); + Mock::generateSubclass('Dummy', 'AnotherMockDummy'); + Mock::generateSubclass('Dummy', 'MockDummyWithExtraMethods', array('extraMethod')); + + class SpecialSimpleMock extends SimpleMock { } + + SimpleTest::setMockBaseClass("SpecialSimpleMock"); + Mock::generateSubclass("Dummy", "SpecialMockDummy"); + SimpleTest::setMockBaseClass("SimpleMock"); + + class TestOfMockGeneration extends UnitTestCase { + + function testCloning() { + $mock = &new MockDummy(); + $this->assertTrue(method_exists($mock, "aMethod")); + $this->assertNull($mock->aMethod()); + } + + function testCloningWithExtraMethod() { + $mock = &new MockDummyWithExtraMethods(); + $this->assertTrue(method_exists($mock, "extraMethod")); + } + + function testCloningWithChosenClassName() { + $mock = &new AnotherMockDummy(); + $this->assertTrue(method_exists($mock, "aMethod")); + } + + function testCloningWithDifferentBaseClass() { + $mock = &new SpecialMockDummy(); + $this->assertTrue(method_exists($mock, "aMethod")); + } + } + + class TestOfMockReturns extends UnitTestCase { + + function testParameteredReturn() { + $mock = &new MockDummy(); + $mock->setReturnValue('aMethod', 'aaa', array(1, 2, 3)); + $this->assertNull($mock->aMethod()); + $this->assertIdentical($mock->aMethod(1, 2, 3), 'aaa'); + } + + function testReferenceReturned() { + $mock = &new MockDummy(); + $object = new Dummy(); + $mock->setReturnReference("aMethod", $object, array(1, 2, 3)); + $this->assertReference($zref =& $mock->aMethod(1, 2, 3), $object); + } + + function testPatternMatchReturn() { + $mock = &new MockDummy(); + $mock->setReturnValue( + "aMethod", + "aaa", + array(new PatternExpectation('/hello/i'))); + $this->assertIdentical($mock->aMethod('Hello'), "aaa"); + $this->assertNull($mock->aMethod('Goodbye')); + } + + function testReturnReferenceSequence() { + $mock = &new MockDummy(); + $object = new Dummy(); + $mock->setReturnReferenceAt(1, 'aMethod', $object); + $this->assertNull($mock->aMethod()); + $this->assertReference($zref =& $mock->aMethod(), $object); + $this->assertNull($mock->aMethod()); + $this->swallowErrors(); + } + } + + class ClassWithSpecialMethods { + function __get($name) { } + function __set($name, $value) { } + function __isset($name) { } + function __unset($name) { } + function __call($method, $arguments) { } + function __toString() { } + } + Mock::generateSubclass('ClassWithSpecialMethods'); + + class TestOfSpecialMethods extends UnitTestCase { + function skip() { + $this->skipIf(version_compare(phpversion(), '5', '<='), 'Overloading not tested for PHP 4'); + } + + function testCanMockTheThingAtAll() { + $mock = new MockClassWithSpecialMethods(); + } + + function testReturnFromSpecialAccessor() { + $mock = &new MockClassWithSpecialMethods(); + $mock->setReturnValue('__get', '1st Return', array('first')); + $mock->setReturnValue('__get', '2nd Return', array('second')); + $this->assertEqual($mock->first, '1st Return'); + $this->assertEqual($mock->second, '2nd Return'); + } + + function testcanExpectTheSettingOfValue() { + $mock = &new MockClassWithSpecialMethods(); + $mock->expectOnce('__set', array('a', 'A')); + $mock->a = 'A'; + } + + function testCanSimulateAnOverloadmethod() { + $mock = &new MockClassWithSpecialMethods(); + $mock->expectOnce('__call', array('amOverloaded', array('A'))); + $mock->setReturnValue('__call', 'aaa'); + $this->assertIdentical($mock->amOverloaded('A'), 'aaa'); + } + + function testCanEmulateIsset() { + $mock = &new MockClassWithSpecialMethods(); + $mock->setReturnValue('__isset', true); + $this->assertIdentical(isset($mock->a), true); + } + + function testCanExpectUnset() { + $mock = &new MockClassWithSpecialMethods(); + $mock->expectOnce('__unset', array('a')); + unset($mock->a); + } + + function testToStringMagic() { + $mock = &new MockClassWithSpecialMethods(); + $mock->expectOnce('__toString'); + $mock->setReturnValue('__toString', 'AAA'); + ob_start(); + print $mock; + $output = ob_get_contents(); + ob_end_clean(); + $this->assertEqual($output, 'AAA'); + } + } + + class TestOfMockTally extends UnitTestCase { + + function testZeroCallCount() { + $mock = &new MockDummy(); + $mock->expectCallCount('aMethod', 0); + } + + function testExpectedCallCount() { + $mock = &new MockDummy(); + $mock->expectCallCount('aMethod', 2); + $mock->aMethod(); + $mock->aMethod(); + } + } + + class MockWithInjectedTestCase extends SimpleMock { + function &_getCurrentTestCase() { + $context = &SimpleTest::getContext(); + $test = &$context->getTest(); + return $test->test; + } + } + + SimpleTest::setMockBaseClass('MockWithInjectedTestCase'); + Mock::generateSubclass('Dummy', 'MockDummyWithInjectedTestCase'); + SimpleTest::setMockBaseClass('SimpleMock'); + Mock::generateSubclass('SimpleTestCase'); + + class TestOfMockExpectations extends UnitTestCase { + var $test; + + function setUp() { + $this->test = &new MockSimpleTestCase(); + } + + function testSettingExpectationOnNonMethodThrowsError() { + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectMaximumCallCount('aMissingMethod', 2); + $this->assertError(); + } + + function testMaxCallsDetectsOverrun() { + $this->test->expectOnce('assert', array(new IsAExpectation('MaximumCallCountExpectation'), 3)); + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectMaximumCallCount('aMethod', 2); + $mock->aMethod(); + $mock->aMethod(); + $mock->aMethod(); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testTallyOnMaxCallsSendsPassOnUnderrun() { + $this->test->expectOnce('assert', array(new IsAExpectation('MaximumCallCountExpectation'), 2)); + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectMaximumCallCount("aMethod", 2); + $mock->aMethod(); + $mock->aMethod(); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testExpectNeverDetectsOverrun() { + $this->test->expectOnce('assert', array(new IsAExpectation('MaximumCallCountExpectation'), 1)); + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectNever('aMethod'); + $mock->aMethod(); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testTallyOnExpectNeverSendsPassOnUnderrun() { + $this->test->expectOnce('assert', array(new IsAExpectation('MaximumCallCountExpectation'), 0)); + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectNever('aMethod'); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testMinCalls() { + $this->test->expectOnce('assert', array(new IsAExpectation('MinimumCallCountExpectation'), 2)); + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectMinimumCallCount('aMethod', 2); + $mock->aMethod(); + $mock->aMethod(); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testFailedNever() { + $this->test->expectOnce('assert', array(new IsAExpectation('MaximumCallCountExpectation'), 1)); + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectNever('aMethod'); + $mock->aMethod(); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testUnderOnce() { + $this->test->expectOnce('assert', array(new IsAExpectation('CallCountExpectation'), 0)); + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectOnce('aMethod'); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testOverOnce() { + $this->test->expectOnce('assert', array(new IsAExpectation('CallCountExpectation'), 2)); + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectOnce('aMethod'); + $mock->aMethod(); + $mock->aMethod(); + $mock->_mock->atTestEnd('testSomething', $this->test); + $this->swallowErrors(); + } + + function testUnderAtLeastOnce() { + $this->test->expectOnce('assert', array(new IsAExpectation('MinimumCallCountExpectation'), 0)); + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectAtLeastOnce("aMethod"); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testZeroArguments() { + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectArguments("aMethod", array()); + $mock->aMethod(); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testExpectedArguments() { + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectArguments('aMethod', array(1, 2, 3)); + $mock->aMethod(1, 2, 3); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testFailedArguments() { + $this->test->expectOnce('assert', array(new IsAExpectation('ParametersExpectation'), array('that'), '*')); + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectArguments('aMethod', array('this')); + $mock->aMethod('that'); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testWildcardArguments() { + $mock = &new MockDummyWithInjectedTestCase($this, "wild"); + $mock->expectArguments("aMethod", array("wild", 123, "wild")); + $mock->aMethod(100, 123, 101); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testSpecificSequence() { + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectArgumentsAt(1, "aMethod", array(1, 2, 3)); + $mock->expectArgumentsAt(2, "aMethod", array("Hello")); + $mock->aMethod(); + $mock->aMethod(1, 2, 3); + $mock->aMethod("Hello"); + $mock->aMethod(); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + + function testBadArgParameter() { + $mock = &new MockDummyWithInjectedTestCase(); + $mock->expectArguments("aMethod", "foo"); + $this->assertErrorPattern('/\$args.*not an array/i'); + $mock->aMethod(); + $mock->tally(); + $mock->_mock->atTestEnd('testSomething', $this->test); + } + } + + class TestOfMockComparisons extends UnitTestCase { + + function testEqualComparisonOfMocksDoesNotCrash() { + $expectation = &new EqualExpectation(new MockDummy()); + $this->assertTrue($expectation->test(new MockDummy(), true)); + } + + function testIdenticalComparisonOfMocksDoesNotCrash() { + $expectation = &new IdenticalExpectation(new MockDummy()); + $this->assertTrue($expectation->test(new MockDummy())); + } + } + + Mock::generatePartial('Dummy', 'TestDummy', array('anotherMethod')); + + class TestOfPartialMocks extends UnitTestCase { + + function testMethodReplacement() { + $mock = &new TestDummy(); + $this->assertEqual($mock->aMethod(99), 99); + $this->assertNull($mock->anotherMethod()); + } + + function testSettingReturns() { + $mock = &new TestDummy(); + $mock->setReturnValue('anotherMethod', 33, array(3)); + $mock->setReturnValue('anotherMethod', 22); + $mock->setReturnValueAt(2, 'anotherMethod', 44, array(3)); + $this->assertEqual($mock->anotherMethod(), 22); + $this->assertEqual($mock->anotherMethod(3), 33); + $this->assertEqual($mock->anotherMethod(3), 44); + } + + function testReferences() { + $mock = &new TestDummy(); + $object = new Dummy(); + $mock->setReturnReferenceAt(0, 'anotherMethod', $object, array(3)); + $this->assertReference($zref =& $mock->anotherMethod(3), $object); + } + + function testExpectations() { + $mock = &new TestDummy(); + $mock->expectCallCount('anotherMethod', 2); + $mock->expectArguments('anotherMethod', array(77)); + $mock->expectArgumentsAt(1, 'anotherMethod', array(66)); + $mock->anotherMethod(77); + $mock->anotherMethod(66); + } + + function testSettingExpectationOnMissingMethodThrowsError() { + $mock = &new TestDummy(); + $mock->expectCallCount('aMissingMethod', 2); + $this->assertError(); + } + } + + class ConstructorSuperClass { + function ConstructorSuperClass() { } + } + + class ConstructorSubClass extends ConstructorSuperClass { + } + + class TestOfPHP4StyleSuperClassConstruct extends UnitTestCase { + /* + * This addresses issue #1231401. Without the fix in place, this will + * generate a fatal PHP error. + */ + function testBasicConstruct() { + Mock::generateSubclass('ConstructorSubClass'); + $mock = &new MockConstructorSubClass(); + $this->assertIsA($mock, 'ConstructorSubClass'); + $this->assertTrue(method_exists($mock, 'ConstructorSuperClass')); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/page_test.php b/tests/simpletest/test/page_test.php new file mode 100644 index 00000000..e55cfc6b --- /dev/null +++ b/tests/simpletest/test/page_test.php @@ -0,0 +1,885 @@ + 'http://somewhere')); + $tag->addContent('Label'); + + $page = &new MockSimplePage(); + $page->expectArguments('acceptTag', array($tag)); + $page->expectCallCount('acceptTag', 1); + + $builder = &new PartialSimplePageBuilder(); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', new MockSimpleHtmlSaxParser()); + $builder->SimplePageBuilder(); + + $builder->parse(new MockSimpleHttpResponse()); + $this->assertTrue($builder->startElement( + 'a', + array('href' => 'http://somewhere'))); + $this->assertTrue($builder->addContent('Label')); + $this->assertTrue($builder->endElement('a')); + } + + function testLinkWithId() { + $tag = &new SimpleAnchorTag(array("href" => "http://somewhere", "id" => "44")); + $tag->addContent("Label"); + + $page = &new MockSimplePage(); + $page->expectArguments("acceptTag", array($tag)); + $page->expectCallCount("acceptTag", 1); + + $builder = &new PartialSimplePageBuilder(); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', new MockSimpleHtmlSaxParser()); + $builder->SimplePageBuilder(); + + $builder->parse(new MockSimpleHttpResponse()); + $this->assertTrue($builder->startElement( + "a", + array("href" => "http://somewhere", "id" => "44"))); + $this->assertTrue($builder->addContent("Label")); + $this->assertTrue($builder->endElement("a")); + } + + function testLinkExtraction() { + $tag = &new SimpleAnchorTag(array("href" => "http://somewhere")); + $tag->addContent("Label"); + + $page = &new MockSimplePage(); + $page->expectArguments("acceptTag", array($tag)); + $page->expectCallCount("acceptTag", 1); + + $builder = &new PartialSimplePageBuilder(); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', new MockSimpleHtmlSaxParser()); + $builder->SimplePageBuilder(); + + $builder->parse(new MockSimpleHttpResponse()); + $this->assertTrue($builder->addContent("Starting stuff")); + $this->assertTrue($builder->startElement( + "a", + array("href" => "http://somewhere"))); + $this->assertTrue($builder->addContent("Label")); + $this->assertTrue($builder->endElement("a")); + $this->assertTrue($builder->addContent("Trailing stuff")); + } + + function testMultipleLinks() { + $a1 = new SimpleAnchorTag(array("href" => "http://somewhere")); + $a1->addContent("1"); + + $a2 = new SimpleAnchorTag(array("href" => "http://elsewhere")); + $a2->addContent("2"); + + $page = &new MockSimplePage(); + $page->expectArgumentsAt(0, "acceptTag", array($a1)); + $page->expectArgumentsAt(1, "acceptTag", array($a2)); + $page->expectCallCount("acceptTag", 2); + + $builder = &new PartialSimplePageBuilder(); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', new MockSimpleHtmlSaxParser()); + $builder->SimplePageBuilder(); + + $builder->parse(new MockSimpleHttpResponse()); + $builder->startElement("a", array("href" => "http://somewhere")); + $builder->addContent("1"); + $builder->endElement("a"); + $builder->addContent("Padding"); + $builder->startElement("a", array("href" => "http://elsewhere")); + $builder->addContent("2"); + $builder->endElement("a"); + } + + function testTitle() { + $tag = &new SimpleTitleTag(array()); + $tag->addContent("HereThere"); + + $page = &new MockSimplePage(); + $page->expectArguments("acceptTag", array($tag)); + $page->expectCallCount("acceptTag", 1); + + $builder = &new PartialSimplePageBuilder(); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', new MockSimpleHtmlSaxParser()); + $builder->SimplePageBuilder(); + + $builder->parse(new MockSimpleHttpResponse()); + $builder->startElement("title", array()); + $builder->addContent("Here"); + $builder->addContent("There"); + $builder->endElement("title"); + } + + function testForm() { + $page = &new MockSimplePage(); + $page->expectOnce("acceptFormStart", array(new SimpleFormTag(array()))); + $page->expectOnce("acceptFormEnd", array()); + + $builder = &new PartialSimplePageBuilder(); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', new MockSimpleHtmlSaxParser()); + $builder->SimplePageBuilder(); + + $builder->parse(new MockSimpleHttpResponse()); + $builder->startElement("form", array()); + $builder->addContent("Stuff"); + $builder->endElement("form"); + } + } + + class TestOfPageParsing extends UnitTestCase { + + function testParseMechanics() { + $parser = &new MockSimpleHtmlSaxParser(); + $parser->expectOnce('parse', array('stuff')); + + $page = &new MockSimplePage(); + $page->expectOnce('acceptPageEnd'); + + $builder = &new PartialSimplePageBuilder(); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', $parser); + $builder->SimplePageBuilder(); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', 'stuff'); + $builder->parse($response); + } + } + + class TestOfErrorPage extends UnitTestCase { + + function testInterface() { + $page = &new SimplePage(); + $this->assertEqual($page->getTransportError(), 'No page fetched yet'); + $this->assertIdentical($page->getRaw(), false); + $this->assertIdentical($page->getHeaders(), false); + $this->assertIdentical($page->getMimeType(), false); + $this->assertIdentical($page->getResponseCode(), false); + $this->assertIdentical($page->getAuthentication(), false); + $this->assertIdentical($page->getRealm(), false); + $this->assertFalse($page->hasFrames()); + $this->assertIdentical($page->getAbsoluteUrls(), array()); + $this->assertIdentical($page->getRelativeUrls(), array()); + $this->assertIdentical($page->getTitle(), false); + } + } + + class TestOfPageHeaders extends UnitTestCase { + + function testUrlAccessor() { + $headers = &new MockSimpleHttpHeaders(); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getHeaders', $headers); + $response->setReturnValue('getMethod', 'POST'); + $response->setReturnValue('getUrl', new SimpleUrl('here')); + $response->setReturnValue('getRequestData', array('a' => 'A')); + + $page = &new SimplePage($response); + $this->assertEqual($page->getMethod(), 'POST'); + $this->assertEqual($page->getUrl(), new SimpleUrl('here')); + $this->assertEqual($page->getRequestData(), array('a' => 'A')); + } + + function testTransportError() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getError', 'Ouch'); + + $page = &new SimplePage($response); + $this->assertEqual($page->getTransportError(), 'Ouch'); + } + + function testHeadersAccessor() { + $headers = &new MockSimpleHttpHeaders(); + $headers->setReturnValue('getRaw', 'My: Headers'); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getHeaders', $headers); + + $page = &new SimplePage($response); + $this->assertEqual($page->getHeaders(), 'My: Headers'); + } + + function testMimeAccessor() { + $headers = &new MockSimpleHttpHeaders(); + $headers->setReturnValue('getMimeType', 'text/html'); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getHeaders', $headers); + + $page = &new SimplePage($response); + $this->assertEqual($page->getMimeType(), 'text/html'); + } + + function testResponseAccessor() { + $headers = &new MockSimpleHttpHeaders(); + $headers->setReturnValue('getResponseCode', 301); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getHeaders', $headers); + + $page = &new SimplePage($response); + $this->assertIdentical($page->getResponseCode(), 301); + } + + function testAuthenticationAccessors() { + $headers = &new MockSimpleHttpHeaders(); + $headers->setReturnValue('getAuthentication', 'Basic'); + $headers->setReturnValue('getRealm', 'Secret stuff'); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getHeaders', $headers); + + $page = &new SimplePage($response); + $this->assertEqual($page->getAuthentication(), 'Basic'); + $this->assertEqual($page->getRealm(), 'Secret stuff'); + } + } + + class TestOfHtmlPage extends UnitTestCase { + + function testRawAccessor() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', 'Raw HTML'); + + $page = &new SimplePage($response); + $this->assertEqual($page->getRaw(), 'Raw HTML'); + } + + function testTextAccessor() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', 'Some "messy" HTML'); + + $page = &new SimplePage($response); + $this->assertEqual($page->getText(), 'Some "messy" HTML'); + } + + function testNoLinks() { + $page = &new SimplePage(new MockSimpleHttpResponse()); + $this->assertIdentical($page->getAbsoluteUrls(), array(), 'abs->%s'); + $this->assertIdentical($page->getRelativeUrls(), array(), 'rel->%s'); + $this->assertIdentical($page->getUrlsByLabel('Label'), array()); + } + + function testAddAbsoluteLink() { + $link = &new SimpleAnchorTag(array('href' => 'http://somewhere.com')); + $link->addContent('Label'); + + $page = &new SimplePage(new MockSimpleHttpResponse()); + $page->AcceptTag($link); + + $this->assertEqual($page->getAbsoluteUrls(), array('http://somewhere.com'), 'abs->%s'); + $this->assertIdentical($page->getRelativeUrls(), array(), 'rel->%s'); + $this->assertEqual( + $page->getUrlsByLabel('Label'), + array(new SimpleUrl('http://somewhere.com'))); + } + + function testAddStrictRelativeLink() { + $link = &new SimpleAnchorTag(array('href' => './somewhere.php')); + $link->addContent('Label'); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); + + $page = &new SimplePage($response); + $page->AcceptTag($link); + + $this->assertEqual($page->getAbsoluteUrls(), array(), 'abs->%s'); + $this->assertIdentical($page->getRelativeUrls(), array('./somewhere.php'), 'rel->%s'); + $this->assertEqual( + $page->getUrlsByLabel('Label'), + array(new SimpleUrl('http://host/somewhere.php'))); + } + + function testAddRelativeLink() { + $link = &new SimpleAnchorTag(array('href' => 'somewhere.php')); + $link->addContent('Label'); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); + + $page = &new SimplePage($response); + $page->AcceptTag($link); + + $this->assertEqual($page->getAbsoluteUrls(), array(), 'abs->%s'); + $this->assertIdentical($page->getRelativeUrls(), array('somewhere.php'), 'rel->%s'); + $this->assertEqual( + $page->getUrlsByLabel('Label'), + array(new SimpleUrl('http://host/somewhere.php'))); + } + + function testLinkIds() { + $link = &new SimpleAnchorTag(array('href' => './somewhere.php', 'id' => 33)); + $link->addContent('Label'); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); + + $page = &new SimplePage($response); + $page->AcceptTag($link); + + $this->assertEqual( + $page->getUrlsByLabel('Label'), + array(new SimpleUrl('http://host/somewhere.php'))); + $this->assertFalse($page->getUrlById(0)); + $this->assertEqual( + $page->getUrlById(33), + new SimpleUrl('http://host/somewhere.php')); + } + + function testFindLinkWithNormalisation() { + $link = &new SimpleAnchorTag(array('href' => './somewhere.php', 'id' => 33)); + $link->addContent(' Long & thin '); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); + + $page = &new SimplePage($response); + $page->AcceptTag($link); + + $this->assertEqual( + $page->getUrlsByLabel('Long & thin'), + array(new SimpleUrl('http://host/somewhere.php'))); + } + + function testFindLinkWithImage() { + $link = &new SimpleAnchorTag(array('href' => './somewhere.php', 'id' => 33)); + $link->addContent('<A picture>'); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); + + $page = &new SimplePage($response); + $page->AcceptTag($link); + + $this->assertEqual( + $page->getUrlsByLabel(''), + array(new SimpleUrl('http://host/somewhere.php'))); + } + + function testTitleSetting() { + $title = &new SimpleTitleTag(array()); + $title->addContent('Title'); + $page = &new SimplePage(new MockSimpleHttpResponse()); + $page->AcceptTag($title); + $this->assertEqual($page->getTitle(), 'Title'); + } + + function testFramesetAbsence() { + $url = new SimpleUrl('here'); + $response = new MockSimpleHttpResponse(); + $response->setReturnValue('getUrl', $url); + $page = &new SimplePage($response); + $this->assertFalse($page->hasFrames()); + $this->assertIdentical($page->getFrameset(), false); + } + + function testHasEmptyFrameset() { + $page = &new SimplePage(new MockSimpleHttpResponse()); + $page->acceptFramesetStart(new SimpleTag('frameset', array())); + $page->acceptFramesetEnd(); + $this->assertTrue($page->hasFrames()); + $this->assertIdentical($page->getFrameset(), array()); + } + + function testFramesInPage() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getUrl', new SimpleUrl('http://here')); + + $page = &new SimplePage($response); + $page->acceptFrame(new SimpleFrameTag(array('src' => '1.html'))); + $page->acceptFramesetStart(new SimpleTag('frameset', array())); + $page->acceptFrame(new SimpleFrameTag(array('src' => '2.html'))); + $page->acceptFrame(new SimpleFrameTag(array('src' => '3.html'))); + $page->acceptFramesetEnd(); + $page->acceptFrame(new SimpleFrameTag(array('src' => '4.html'))); + + $this->assertTrue($page->hasFrames()); + $this->assertIdentical($page->getFrameset(), array( + 1 => new SimpleUrl('http://here/2.html'), + 2 => new SimpleUrl('http://here/3.html'))); + } + + function testNamedFramesInPage() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getUrl', new SimpleUrl('http://here')); + + $page = &new SimplePage($response); + $page->acceptFramesetStart(new SimpleTag('frameset', array())); + $page->acceptFrame(new SimpleFrameTag(array('src' => '1.html'))); + $page->acceptFrame(new SimpleFrameTag(array('src' => '2.html', 'name' => 'A'))); + $page->acceptFrame(new SimpleFrameTag(array('src' => '3.html', 'name' => 'B'))); + $page->acceptFrame(new SimpleFrameTag(array('src' => '4.html'))); + $page->acceptFramesetEnd(); + + $this->assertTrue($page->hasFrames()); + $this->assertIdentical($page->getFrameset(), array( + 1 => new SimpleUrl('http://here/1.html'), + 'A' => new SimpleUrl('http://here/2.html'), + 'B' => new SimpleUrl('http://here/3.html'), + 4 => new SimpleUrl('http://here/4.html'))); + } + } + + class TestOfFormsCreatedFromEventStream extends UnitTestCase { + + function testFormCanBeSubmitted() { + $page = &new SimplePage(new MockSimpleHttpResponse()); + $page->acceptFormStart( + new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php'))); + $page->AcceptTag( + new SimpleSubmitTag(array('type' => 'submit', 'name' => 's'))); + $page->acceptFormEnd(); + $form = &$page->getFormBySubmit(new SimpleByLabel('Submit')); + $this->assertEqual( + $form->submitButton(new SimpleByLabel('Submit')), + new SimpleGetEncoding(array('s' => 'Submit'))); + } + + function testInputFieldCanBeReadBack() { + $page = &new SimplePage(new MockSimpleHttpResponse()); + $page->acceptFormStart( + new SimpleFormTag(array("method" => "GET", "action" => "here.php"))); + $page->AcceptTag( + new SimpleTextTag(array("type" => "text", "name" => "a", "value" => "A"))); + $page->AcceptTag( + new SimpleSubmitTag(array("type" => "submit", "name" => "s"))); + $page->acceptFormEnd(); + $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); + } + + function testInputFieldCanBeReadBackByLabel() { + $label = &new SimpleLabelTag(array()); + $page = &new SimplePage(new MockSimpleHttpResponse()); + $page->acceptFormStart( + new SimpleFormTag(array("method" => "GET", "action" => "here.php"))); + $page->acceptLabelStart($label); + $label->addContent('l'); + $page->AcceptTag( + new SimpleTextTag(array("type" => "text", "name" => "a", "value" => "A"))); + $page->acceptLabelEnd(); + $page->AcceptTag( + new SimpleSubmitTag(array("type" => "submit", "name" => "s"))); + $page->acceptFormEnd(); + $this->assertEqual($page->getField(new SimpleByLabel('l')), 'A'); + } + } + + class TestOfPageScraping extends UnitTestCase { + + function &parse($response) { + $builder = &new SimplePageBuilder(); + $page = &$builder->parse($response); + return $page; + } + + function testEmptyPage() { + $page = &new SimplePage(new MockSimpleHttpResponse()); + $this->assertIdentical($page->getAbsoluteUrls(), array()); + $this->assertIdentical($page->getRelativeUrls(), array()); + $this->assertIdentical($page->getTitle(), false); + } + + function testUninterestingPage() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', '

    Stuff

    '); + + $page = &$this->parse($response); + $this->assertIdentical($page->getAbsoluteUrls(), array()); + $this->assertIdentical($page->getRelativeUrls(), array()); + } + + function testLinksPage() { + $raw = ''; + $raw .= '
    There'; + $raw .= 'That page'; + $raw .= ''; + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', $raw); + $response->setReturnValue('getUrl', new SimpleUrl('http://www.here.com/a/index.html')); + + $page = &$this->parse($response); + $this->assertIdentical( + $page->getAbsoluteUrls(), + array('http://there.com/that.html')); + $this->assertIdentical( + $page->getRelativeUrls(), + array('there.html')); + $this->assertIdentical( + $page->getUrlsByLabel('There'), + array(new SimpleUrl('http://www.here.com/a/there.html'))); + $this->assertEqual( + $page->getUrlById('0'), + new SimpleUrl('http://there.com/that.html')); + } + + function testTitle() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', 'Me'); + $page = &$this->parse($response); + $this->assertEqual($page->getTitle(), 'Me'); + } + + function testNastyTitle() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue( + 'getContent', + ' <b>Me&Me '); + $page = &$this->parse($response); + $this->assertEqual($page->getTitle(), "Me&Me"); + } + + function testCompleteForm() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertEqual($page->getField(new SimpleByName('here')), "Hello"); + } + + function testUnclosedForm() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + ''); + $page = &$this->parse($response); + $this->assertEqual($page->getField(new SimpleByName('here')), "Hello"); + } + + function testEmptyFrameset() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue( + 'getContent', + ''); + $page = &$this->parse($response); + $this->assertTrue($page->hasFrames()); + $this->assertIdentical($page->getFrameset(), array()); + } + + function testSingleFrame() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue( + 'getContent', + ''); + $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); + + $page = &$this->parse($response); + $this->assertTrue($page->hasFrames()); + $this->assertIdentical( + $page->getFrameset(), + array(1 => new SimpleUrl('http://host/a.html'))); + } + + function testSingleFrameInNestedFrameset() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '' . + '' . + ''); + $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); + + $page = &$this->parse($response); + $this->assertTrue($page->hasFrames()); + $this->assertIdentical( + $page->getFrameset(), + array(1 => new SimpleUrl('http://host/a.html'))); + } + + function testFrameWithNoSource() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue( + 'getContent', + ''); + $page = &$this->parse($response); + $this->assertTrue($page->hasFrames()); + $this->assertIdentical($page->getFrameset(), array()); + } + + function testFramesCollectedWithNestedFramesetTags() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '' . + '' . + '' . + '' . + ''); + $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); + + $page = &$this->parse($response); + $this->assertTrue($page->hasFrames()); + $this->assertIdentical($page->getFrameset(), array( + 1 => new SimpleUrl('http://host/a.html'), + 2 => new SimpleUrl('http://host/b.html'), + 3 => new SimpleUrl('http://host/c.html'))); + } + + function testNamedFrames() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '' . + '' . + '' . + '' . + '' . + ''); + $response->setReturnValue('getUrl', new SimpleUrl('http://host/')); + + $page = &$this->parse($response); + $this->assertTrue($page->hasFrames()); + $this->assertIdentical($page->getFrameset(), array( + 1 => new SimpleUrl('http://host/a.html'), + '_one' => new SimpleUrl('http://host/b.html'), + 3 => new SimpleUrl('http://host/c.html'), + '_two' => new SimpleUrl('http://host/d.html'))); + } + + function testFindFormByLabel() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue( + 'getContent', + '
    '); + $page = &$this->parse($response); + $this->assertNull($page->getFormBySubmit(new SimpleByLabel('submit'))); + $this->assertNull($page->getFormBySubmit(new SimpleByName('submit'))); + $this->assertIsA( + $page->getFormBySubmit(new SimpleByLabel('Submit')), + 'SimpleForm'); + } + + function testConfirmSubmitAttributesAreCaseSensitive() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue( + 'getContent', + '
    '); + $page = &$this->parse($response); + $this->assertIsA( + $page->getFormBySubmit(new SimpleByName('S')), + 'SimpleForm'); + $this->assertIsA( + $page->getFormBySubmit(new SimpleByLabel('S')), + 'SimpleForm'); + } + + function testFindFormByImage() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertIsA( + $page->getFormByImage(new SimpleByLabel('Label')), + 'SimpleForm'); + $this->assertIsA( + $page->getFormByImage(new SimpleByName('me')), + 'SimpleForm'); + $this->assertIsA( + $page->getFormByImage(new SimpleById(100)), + 'SimpleForm'); + } + + function testFindFormByButtonTag() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertNull($page->getFormBySubmit(new SimpleByLabel('b'))); + $this->assertNull($page->getFormBySubmit(new SimpleByLabel('B'))); + $this->assertIsA( + $page->getFormBySubmit(new SimpleByName('b')), + 'SimpleForm'); + $this->assertIsA( + $page->getFormBySubmit(new SimpleByLabel('BBB')), + 'SimpleForm'); + } + + function testFindFormById() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue( + 'getContent', + '
    '); + $page = &$this->parse($response); + $this->assertNull($page->getFormById(54)); + $this->assertIsA($page->getFormById(55), 'SimpleForm'); + } + + function testReadingTextField() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertNull($page->getField(new SimpleByName('missing'))); + $this->assertIdentical($page->getField(new SimpleByName('a')), ''); + $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb'); + } + + function testReadingTextFieldIsCaseInsensitive() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertNull($page->getField(new SimpleByName('missing'))); + $this->assertIdentical($page->getField(new SimpleByName('a')), ''); + $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb'); + } + + function testSettingTextField() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa')); + $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); + $this->assertTrue($page->setField(new SimpleById(3), 'bbb')); + $this->assertEqual($page->getField(new SimpleBYId(3)), 'bbb'); + $this->assertFalse($page->setField(new SimpleByName('z'), 'zzz')); + $this->assertNull($page->getField(new SimpleByName('z'))); + } + + function testSettingTextFieldByEnclosingLabel() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); + $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); + $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa')); + $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa'); + } + + function testGettingTextFieldByEnclosingLabelWithConflictingOtherFields() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); + $this->assertEqual($page->getField(new SimpleByName('b')), 'B'); + $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); + } + + function testSettingTextFieldByExternalLabel() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); + $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa')); + $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa'); + } + + function testReadingTextArea() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); + } + + function testSettingTextArea() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertTrue($page->setField(new SimpleByName('a'), 'AAA')); + $this->assertEqual($page->getField(new SimpleByName('a')), 'AAA'); + } + + function testSettingSelectionField() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertEqual($page->getField(new SimpleByName('a')), 'bbb'); + $this->assertFalse($page->setField(new SimpleByName('a'), 'ccc')); + $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa')); + $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); + } + + function testSettingSelectionFieldByEnclosingLabel() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); + $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'B')); + $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'B'); + } + + function testSettingRadioButtonByEnclosingLabel() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', + '
    ' . + '' . + '' . + '
    '); + $page = &$this->parse($response); + $this->assertEqual($page->getField(new SimpleByLabel('A')), 'a'); + $this->assertTrue($page->setField(new SimpleBylabel('B'), 'b')); + $this->assertEqual($page->getField(new SimpleByLabel('B')), 'b'); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/parse_error_test.php b/tests/simpletest/test/parse_error_test.php new file mode 100644 index 00000000..c8f41907 --- /dev/null +++ b/tests/simpletest/test/parse_error_test.php @@ -0,0 +1,10 @@ +addTestFile('test_with_parse_error.php'); + $test->run(new HtmlReporter()); +?> \ No newline at end of file diff --git a/tests/simpletest/test/parser_test.php b/tests/simpletest/test/parser_test.php new file mode 100644 index 00000000..691c9d34 --- /dev/null +++ b/tests/simpletest/test/parser_test.php @@ -0,0 +1,520 @@ +assertFalse($regex->match("Hello", $match)); + $this->assertEqual($match, ""); + } + + function testNoSubject() { + $regex = &new ParallelRegex(false); + $regex->addPattern(".*"); + $this->assertTrue($regex->match("", $match)); + $this->assertEqual($match, ""); + } + + function testMatchAll() { + $regex = &new ParallelRegex(false); + $regex->addPattern(".*"); + $this->assertTrue($regex->match("Hello", $match)); + $this->assertEqual($match, "Hello"); + } + + function testCaseSensitive() { + $regex = &new ParallelRegex(true); + $regex->addPattern("abc"); + $this->assertTrue($regex->match("abcdef", $match)); + $this->assertEqual($match, "abc"); + $this->assertTrue($regex->match("AAABCabcdef", $match)); + $this->assertEqual($match, "abc"); + } + + function testCaseInsensitive() { + $regex = &new ParallelRegex(false); + $regex->addPattern("abc"); + $this->assertTrue($regex->match("abcdef", $match)); + $this->assertEqual($match, "abc"); + $this->assertTrue($regex->match("AAABCabcdef", $match)); + $this->assertEqual($match, "ABC"); + } + + function testMatchMultiple() { + $regex = &new ParallelRegex(true); + $regex->addPattern("abc"); + $regex->addPattern("ABC"); + $this->assertTrue($regex->match("abcdef", $match)); + $this->assertEqual($match, "abc"); + $this->assertTrue($regex->match("AAABCabcdef", $match)); + $this->assertEqual($match, "ABC"); + $this->assertFalse($regex->match("Hello", $match)); + } + + function testPatternLabels() { + $regex = &new ParallelRegex(false); + $regex->addPattern("abc", "letter"); + $regex->addPattern("123", "number"); + $this->assertIdentical($regex->match("abcdef", $match), "letter"); + $this->assertEqual($match, "abc"); + $this->assertIdentical($regex->match("0123456789", $match), "number"); + $this->assertEqual($match, "123"); + } + } + + class TestOfStateStack extends UnitTestCase { + + function testStartState() { + $stack = &new SimpleStateStack("one"); + $this->assertEqual($stack->getCurrent(), "one"); + } + + function testExhaustion() { + $stack = &new SimpleStateStack("one"); + $this->assertFalse($stack->leave()); + } + + function testStateMoves() { + $stack = &new SimpleStateStack("one"); + $stack->enter("two"); + $this->assertEqual($stack->getCurrent(), "two"); + $stack->enter("three"); + $this->assertEqual($stack->getCurrent(), "three"); + $this->assertTrue($stack->leave()); + $this->assertEqual($stack->getCurrent(), "two"); + $stack->enter("third"); + $this->assertEqual($stack->getCurrent(), "third"); + $this->assertTrue($stack->leave()); + $this->assertTrue($stack->leave()); + $this->assertEqual($stack->getCurrent(), "one"); + } + } + + class TestParser { + + function accept() { + } + + function a() { + } + + function b() { + } + } + Mock::generate('TestParser'); + + class TestOfLexer extends UnitTestCase { + + function testEmptyPage() { + $handler = &new MockTestParser(); + $handler->expectNever("accept"); + $handler->setReturnValue("accept", true); + $handler->expectNever("accept"); + $handler->setReturnValue("accept", true); + $lexer = &new SimpleLexer($handler); + $lexer->addPattern("a+"); + $this->assertTrue($lexer->parse("")); + } + + function testSinglePattern() { + $handler = &new MockTestParser(); + $handler->expectArgumentsAt(0, "accept", array("aaa", LEXER_MATCHED)); + $handler->expectArgumentsAt(1, "accept", array("x", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(2, "accept", array("a", LEXER_MATCHED)); + $handler->expectArgumentsAt(3, "accept", array("yyy", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(4, "accept", array("a", LEXER_MATCHED)); + $handler->expectArgumentsAt(5, "accept", array("x", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(6, "accept", array("aaa", LEXER_MATCHED)); + $handler->expectArgumentsAt(7, "accept", array("z", LEXER_UNMATCHED)); + $handler->expectCallCount("accept", 8); + $handler->setReturnValue("accept", true); + $lexer = &new SimpleLexer($handler); + $lexer->addPattern("a+"); + $this->assertTrue($lexer->parse("aaaxayyyaxaaaz")); + } + + function testMultiplePattern() { + $handler = &new MockTestParser(); + $target = array("a", "b", "a", "bb", "x", "b", "a", "xxxxxx", "a", "x"); + for ($i = 0; $i < count($target); $i++) { + $handler->expectArgumentsAt($i, "accept", array($target[$i], '*')); + } + $handler->expectCallCount("accept", count($target)); + $handler->setReturnValue("accept", true); + $lexer = &new SimpleLexer($handler); + $lexer->addPattern("a+"); + $lexer->addPattern("b+"); + $this->assertTrue($lexer->parse("ababbxbaxxxxxxax")); + } + } + + class TestOfLexerModes extends UnitTestCase { + + function testIsolatedPattern() { + $handler = &new MockTestParser(); + $handler->expectArgumentsAt(0, "a", array("a", LEXER_MATCHED)); + $handler->expectArgumentsAt(1, "a", array("b", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(2, "a", array("aa", LEXER_MATCHED)); + $handler->expectArgumentsAt(3, "a", array("bxb", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(4, "a", array("aaa", LEXER_MATCHED)); + $handler->expectArgumentsAt(5, "a", array("x", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(6, "a", array("aaaa", LEXER_MATCHED)); + $handler->expectArgumentsAt(7, "a", array("x", LEXER_UNMATCHED)); + $handler->expectCallCount("a", 8); + $handler->setReturnValue("a", true); + $lexer = &new SimpleLexer($handler, "a"); + $lexer->addPattern("a+", "a"); + $lexer->addPattern("b+", "b"); + $this->assertTrue($lexer->parse("abaabxbaaaxaaaax")); + } + + function testModeChange() { + $handler = &new MockTestParser(); + $handler->expectArgumentsAt(0, "a", array("a", LEXER_MATCHED)); + $handler->expectArgumentsAt(1, "a", array("b", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(2, "a", array("aa", LEXER_MATCHED)); + $handler->expectArgumentsAt(3, "a", array("b", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(4, "a", array("aaa", LEXER_MATCHED)); + $handler->expectArgumentsAt(0, "b", array(":", LEXER_ENTER)); + $handler->expectArgumentsAt(1, "b", array("a", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(2, "b", array("b", LEXER_MATCHED)); + $handler->expectArgumentsAt(3, "b", array("a", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(4, "b", array("bb", LEXER_MATCHED)); + $handler->expectArgumentsAt(5, "b", array("a", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(6, "b", array("bbb", LEXER_MATCHED)); + $handler->expectArgumentsAt(7, "b", array("a", LEXER_UNMATCHED)); + $handler->expectCallCount("a", 5); + $handler->expectCallCount("b", 8); + $handler->setReturnValue("a", true); + $handler->setReturnValue("b", true); + $lexer = &new SimpleLexer($handler, "a"); + $lexer->addPattern("a+", "a"); + $lexer->addEntryPattern(":", "a", "b"); + $lexer->addPattern("b+", "b"); + $this->assertTrue($lexer->parse("abaabaaa:ababbabbba")); + } + + function testNesting() { + $handler = &new MockTestParser(); + $handler->setReturnValue("a", true); + $handler->setReturnValue("b", true); + $handler->expectArgumentsAt(0, "a", array("aa", LEXER_MATCHED)); + $handler->expectArgumentsAt(1, "a", array("b", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(2, "a", array("aa", LEXER_MATCHED)); + $handler->expectArgumentsAt(3, "a", array("b", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(0, "b", array("(", LEXER_ENTER)); + $handler->expectArgumentsAt(1, "b", array("bb", LEXER_MATCHED)); + $handler->expectArgumentsAt(2, "b", array("a", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(3, "b", array("bb", LEXER_MATCHED)); + $handler->expectArgumentsAt(4, "b", array(")", LEXER_EXIT)); + $handler->expectArgumentsAt(4, "a", array("aa", LEXER_MATCHED)); + $handler->expectArgumentsAt(5, "a", array("b", LEXER_UNMATCHED)); + $handler->expectCallCount("a", 6); + $handler->expectCallCount("b", 5); + $lexer = &new SimpleLexer($handler, "a"); + $lexer->addPattern("a+", "a"); + $lexer->addEntryPattern("(", "a", "b"); + $lexer->addPattern("b+", "b"); + $lexer->addExitPattern(")", "b"); + $this->assertTrue($lexer->parse("aabaab(bbabb)aab")); + } + + function testSingular() { + $handler = &new MockTestParser(); + $handler->setReturnValue("a", true); + $handler->setReturnValue("b", true); + $handler->expectArgumentsAt(0, "a", array("aa", LEXER_MATCHED)); + $handler->expectArgumentsAt(1, "a", array("aa", LEXER_MATCHED)); + $handler->expectArgumentsAt(2, "a", array("xx", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(3, "a", array("xx", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(0, "b", array("b", LEXER_SPECIAL)); + $handler->expectArgumentsAt(1, "b", array("bbb", LEXER_SPECIAL)); + $handler->expectCallCount("a", 4); + $handler->expectCallCount("b", 2); + $lexer = &new SimpleLexer($handler, "a"); + $lexer->addPattern("a+", "a"); + $lexer->addSpecialPattern("b+", "a", "b"); + $this->assertTrue($lexer->parse("aabaaxxbbbxx")); + } + + function testUnwindTooFar() { + $handler = &new MockTestParser(); + $handler->setReturnValue("a", true); + $handler->expectArgumentsAt(0, "a", array("aa", LEXER_MATCHED)); + $handler->expectArgumentsAt(1, "a", array(")", LEXER_EXIT)); + $handler->expectCallCount("a", 2); + $lexer = &new SimpleLexer($handler, "a"); + $lexer->addPattern("a+", "a"); + $lexer->addExitPattern(")", "a"); + $this->assertFalse($lexer->parse("aa)aa")); + } + } + + class TestOfLexerHandlers extends UnitTestCase { + + function testModeMapping() { + $handler = &new MockTestParser(); + $handler->setReturnValue("a", true); + $handler->expectArgumentsAt(0, "a", array("aa", LEXER_MATCHED)); + $handler->expectArgumentsAt(1, "a", array("(", LEXER_ENTER)); + $handler->expectArgumentsAt(2, "a", array("bb", LEXER_MATCHED)); + $handler->expectArgumentsAt(3, "a", array("a", LEXER_UNMATCHED)); + $handler->expectArgumentsAt(4, "a", array("bb", LEXER_MATCHED)); + $handler->expectArgumentsAt(5, "a", array(")", LEXER_EXIT)); + $handler->expectArgumentsAt(6, "a", array("b", LEXER_UNMATCHED)); + $handler->expectCallCount("a", 7); + $lexer = &new SimpleLexer($handler, "mode_a"); + $lexer->addPattern("a+", "mode_a"); + $lexer->addEntryPattern("(", "mode_a", "mode_b"); + $lexer->addPattern("b+", "mode_b"); + $lexer->addExitPattern(")", "mode_b"); + $lexer->mapHandler("mode_a", "a"); + $lexer->mapHandler("mode_b", "a"); + $this->assertTrue($lexer->parse("aa(bbabb)b")); + } + } + + class TestOfSimpleHtmlLexer extends UnitTestCase { + + function &createParser() { + $parser = &new MockSimpleHtmlSaxParser(); + $parser->setReturnValue('acceptStartToken', true); + $parser->setReturnValue('acceptEndToken', true); + $parser->setReturnValue('acceptAttributeToken', true); + $parser->setReturnValue('acceptEntityToken', true); + $parser->setReturnValue('acceptTextToken', true); + $parser->setReturnValue('ignore', true); + return $parser; + } + + function testNoContent() { + $parser = &$this->createParser(); + $parser->expectNever('acceptStartToken'); + $parser->expectNever('acceptEndToken'); + $parser->expectNever('acceptAttributeToken'); + $parser->expectNever('acceptEntityToken'); + $parser->expectNever('acceptTextToken'); + $lexer = &new SimpleHtmlLexer($parser); + $this->assertTrue($lexer->parse('')); + } + + function testUninteresting() { + $parser = &$this->createParser(); + $parser->expectOnce('acceptTextToken', array('', '*')); + $lexer = &new SimpleHtmlLexer($parser); + $this->assertTrue($lexer->parse('')); + } + + function testSkipCss() { + $parser = &$this->createParser(); + $parser->expectNever('acceptTextToken'); + $parser->expectAtLeastOnce('ignore'); + $lexer = &new SimpleHtmlLexer($parser); + $this->assertTrue($lexer->parse("")); + } + + function testSkipJavaScript() { + $parser = &$this->createParser(); + $parser->expectNever('acceptTextToken'); + $parser->expectAtLeastOnce('ignore'); + $lexer = &new SimpleHtmlLexer($parser); + $this->assertTrue($lexer->parse("")); + } + + function testSkipHtmlComments() { + $parser = &$this->createParser(); + $parser->expectNever('acceptTextToken'); + $parser->expectAtLeastOnce('ignore'); + $lexer = &new SimpleHtmlLexer($parser); + $this->assertTrue($lexer->parse("")); + } + + function testTagWithNoAttributes() { + $parser = &$this->createParser(); + $parser->expectAt(0, 'acceptStartToken', array('expectAt(1, 'acceptStartToken', array('>', '*')); + $parser->expectCallCount('acceptStartToken', 2); + $parser->expectOnce('acceptTextToken', array('Hello', '*')); + $parser->expectOnce('acceptEndToken', array('', '*')); + $lexer = &new SimpleHtmlLexer($parser); + $this->assertTrue($lexer->parse('Hello')); + } + + function testTagWithAttributes() { + $parser = &$this->createParser(); + $parser->expectOnce('acceptTextToken', array('label', '*')); + $parser->expectAt(0, 'acceptStartToken', array('expectAt(1, 'acceptStartToken', array('href', '*')); + $parser->expectAt(2, 'acceptStartToken', array('>', '*')); + $parser->expectCallCount('acceptStartToken', 3); + $parser->expectAt(0, 'acceptAttributeToken', array('= "', '*')); + $parser->expectAt(1, 'acceptAttributeToken', array('here.html', '*')); + $parser->expectAt(2, 'acceptAttributeToken', array('"', '*')); + $parser->expectCallCount('acceptAttributeToken', 3); + $parser->expectOnce('acceptEndToken', array('', '*')); + $lexer = &new SimpleHtmlLexer($parser); + $this->assertTrue($lexer->parse('label')); + } + } + + class TestOfHtmlSaxParser extends UnitTestCase { + + function &createListener() { + $listener = &new MockSimpleSaxListener(); + $listener->setReturnValue('startElement', true); + $listener->setReturnValue('addContent', true); + $listener->setReturnValue('endElement', true); + return $listener; + } + + function testFramesetTag() { + $listener = &$this->createListener(); + $listener->expectOnce('startElement', array('frameset', array())); + $listener->expectOnce('addContent', array('Frames')); + $listener->expectOnce('endElement', array('frameset')); + $parser = &new SimpleHtmlSaxParser($listener); + $this->assertTrue($parser->parse('Frames')); + } + + function testTagWithUnquotedAttributes() { + $listener = &$this->createListener(); + $listener->expectOnce( + 'startElement', + array('input', array('name' => 'a.b.c', 'value' => 'd'))); + $parser = &new SimpleHtmlSaxParser($listener); + $this->assertTrue($parser->parse('')); + } + + function testTagInsideContent() { + $listener = &$this->createListener(); + $listener->expectOnce('startElement', array('a', array())); + $listener->expectAt(0, 'addContent', array('')); + $listener->expectAt(1, 'addContent', array('')); + $parser = &new SimpleHtmlSaxParser($listener); + $this->assertTrue($parser->parse('')); + } + + function testTagWithInternalContent() { + $listener = &$this->createListener(); + $listener->expectOnce('startElement', array('a', array())); + $listener->expectOnce('addContent', array('label')); + $listener->expectOnce('endElement', array('a')); + $parser = &new SimpleHtmlSaxParser($listener); + $this->assertTrue($parser->parse('label')); + } + + function testLinkAddress() { + $listener = &$this->createListener(); + $listener->expectOnce('startElement', array('a', array('href' => 'here.html'))); + $listener->expectOnce('addContent', array('label')); + $listener->expectOnce('endElement', array('a')); + $parser = &new SimpleHtmlSaxParser($listener); + $this->assertTrue($parser->parse("label")); + } + + function testEncodedAttribute() { + $listener = &$this->createListener(); + $listener->expectOnce('startElement', array('a', array('href' => 'here&there.html'))); + $listener->expectOnce('addContent', array('label')); + $listener->expectOnce('endElement', array('a')); + $parser = &new SimpleHtmlSaxParser($listener); + $this->assertTrue($parser->parse("label")); + } + + function testTagWithId() { + $listener = &$this->createListener(); + $listener->expectOnce('startElement', array('a', array('id' => '0'))); + $listener->expectOnce('addContent', array('label')); + $listener->expectOnce('endElement', array('a')); + $parser = &new SimpleHtmlSaxParser($listener); + $this->assertTrue($parser->parse('label')); + } + + function testTagWithEmptyAttributes() { + $listener = &$this->createListener(); + $listener->expectOnce( + 'startElement', + array('option', array('value' => '', 'selected' => ''))); + $listener->expectOnce('addContent', array('label')); + $listener->expectOnce('endElement', array('option')); + $parser = &new SimpleHtmlSaxParser($listener); + $this->assertTrue($parser->parse('')); + } + + function testComplexTagWithLotsOfCaseVariations() { + $listener = &$this->createListener(); + $listener->expectOnce( + 'startElement', + array('a', array('href' => 'here.html', 'style' => "'cool'"))); + $listener->expectOnce('addContent', array('label')); + $listener->expectOnce('endElement', array('a')); + $parser = &new SimpleHtmlSaxParser($listener); + $this->assertTrue($parser->parse('label')); + } + + function testXhtmlSelfClosingTag() { + $listener = &$this->createListener(); + $listener->expectOnce( + 'startElement', + array('input', array('type' => 'submit', 'name' => 'N', 'value' => 'V'))); + $parser = &new SimpleHtmlSaxParser($listener); + $this->assertTrue($parser->parse('')); + } + + function testNestedFrameInFrameset() { + $listener = &$this->createListener(); + $listener->expectAt(0, 'startElement', array('frameset', array())); + $listener->expectAt(1, 'startElement', array('frame', array('src' => 'frame.html'))); + $listener->expectCallCount('startElement', 2); + $listener->expectOnce('addContent', array('Hello')); + $listener->expectOnce('endElement', array('frameset')); + $parser = &new SimpleHtmlSaxParser($listener); + $this->assertTrue($parser->parse( + 'Hello')); + } + } + + class TestOfTextExtraction extends UnitTestCase { + + function testSpaceNormalisation() { + $this->assertEqual( + SimpleHtmlSaxParser::normalise("\nOne\tTwo \nThree\t"), + 'One Two Three'); + } + + function testTagSuppression() { + $this->assertEqual( + SimpleHtmlSaxParser::normalise('Hello'), + 'Hello'); + } + + function testAdjoiningTagSuppression() { + $this->assertEqual( + SimpleHtmlSaxParser::normalise('HelloGoodbye'), + 'HelloGoodbye'); + } + + function testExtractImageAltTextWithDifferentQuotes() { + $this->assertEqual( + SimpleHtmlSaxParser::normalise('One\'Two\'Three'), + 'One Two Three'); + } + + function testExtractImageAltTextMultipleTimes() { + $this->assertEqual( + SimpleHtmlSaxParser::normalise('OneTwoThree'), + 'One Two Three'); + } + + function testHtmlEntityTranslation() { + $this->assertEqual( + SimpleHtmlSaxParser::normalise('<>"&'), + '<>"&'); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/reflection_php4_test.php b/tests/simpletest/test/reflection_php4_test.php new file mode 100644 index 00000000..03e8b31b --- /dev/null +++ b/tests/simpletest/test/reflection_php4_test.php @@ -0,0 +1,60 @@ +assertTrue($reflection->classOrInterfaceExists()); + $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); + } + + function testClassNonExistence() { + $reflection = new SimpleReflection('UnknownThing'); + $this->assertFalse($reflection->classOrInterfaceExists()); + $this->assertFalse($reflection->classOrInterfaceExistsSansAutoload()); + } + + function testDetectionOfInterfacesAlwaysFalse() { + $reflection = new SimpleReflection('AnyOldThing'); + $this->assertFalse($reflection->isAbstract()); + $this->assertFalse($reflection->isInterface()); + } + + function testFindingParentClass() { + $reflection = new SimpleReflection('AnyOldChildThing'); + $this->assertEqual(strtolower($reflection->getParent()), 'anyoldthing'); + } + + function testMethodsListFromClass() { + $reflection = new SimpleReflection('AnyOldThing'); + $methods = $reflection->getMethods(); + $this->assertEqualIgnoringCase($methods[0], 'aMethod'); + } + + function testNoInterfacesForPHP4() { + $reflection = new SimpleReflection('AnyOldThing'); + $this->assertEqual( + $reflection->getInterfaces(), + array()); + } + + function testMostGeneralPossibleSignature() { + $reflection = new SimpleReflection('AnyOldThing'); + $this->assertEqualIgnoringCase( + $reflection->getSignature('aMethod'), + 'function &aMethod()'); + } + + function assertEqualIgnoringCase($a, $b) { + return $this->assertEqual(strtolower($a), strtolower($b)); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/reflection_php5_test.php b/tests/simpletest/test/reflection_php5_test.php new file mode 100644 index 00000000..0cb2ff2c --- /dev/null +++ b/tests/simpletest/test/reflection_php5_test.php @@ -0,0 +1,194 @@ +assertTrue($reflection->classOrInterfaceExists()); + $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); + $this->assertFalse($reflection->isAbstract()); + $this->assertFalse($reflection->isInterface()); + } + + function testClassNonExistence() { + $reflection = new SimpleReflection('UnknownThing'); + $this->assertFalse($reflection->classOrInterfaceExists()); + $this->assertFalse($reflection->classOrInterfaceExistsSansAutoload()); + } + + function testDetectionOfAbstractClass() { + $reflection = new SimpleReflection('AnyOldClass'); + $this->assertTrue($reflection->isAbstract()); + } + + function testFindingParentClass() { + $reflection = new SimpleReflection('AnyOldSubclass'); + $this->assertEqual($reflection->getParent(), 'AnyOldImplementation'); + } + + function testInterfaceExistence() { + $reflection = new SimpleReflection('AnyOldInterface'); + $this->assertTrue( + $reflection->classOrInterfaceExists()); + $this->assertTrue( + $reflection->classOrInterfaceExistsSansAutoload()); + $this->assertTrue($reflection->isInterface()); + } + + function testMethodsListFromClass() { + $reflection = new SimpleReflection('AnyOldClass'); + $this->assertIdentical($reflection->getMethods(), array('aMethod')); + } + + function testMethodsListFromInterface() { + $reflection = new SimpleReflection('AnyOldInterface'); + $this->assertIdentical($reflection->getMethods(), array('aMethod')); + $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); + } + + function testMethodsComeFromDescendentInterfacesASWell() { + $reflection = new SimpleReflection('AnyDescendentInterface'); + $this->assertIdentical($reflection->getMethods(), array('aMethod')); + } + + function testCanSeparateInterfaceMethodsFromOthers() { + $reflection = new SimpleReflection('AnyOldImplementation'); + $this->assertIdentical($reflection->getMethods(), array('aMethod', 'extraMethod')); + $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); + } + + function testMethodsComeFromDescendentInterfacesInAbstractClass() { + $reflection = new SimpleReflection('AnyAbstractImplementation'); + $this->assertIdentical($reflection->getMethods(), array('aMethod')); + } + + function testInterfaceHasOnlyItselfToImplement() { + $reflection = new SimpleReflection('AnyOldInterface'); + $this->assertEqual( + $reflection->getInterfaces(), + array('AnyOldInterface')); + } + + function testInterfacesListedForClass() { + $reflection = new SimpleReflection('AnyOldImplementation'); + $this->assertEqual( + $reflection->getInterfaces(), + array('AnyOldInterface')); + } + + function testInterfacesListedForSubclass() { + $reflection = new SimpleReflection('AnyOldSubclass'); + $this->assertEqual( + $reflection->getInterfaces(), + array('AnyOldInterface')); + } + + function testNoParameterCreationWhenNoInterface() { + $reflection = new SimpleReflection('AnyOldArgumentClass'); + $function = $reflection->getSignature('aMethod'); + if (version_compare(phpversion(), '5.0.2', '<=')) { + $this->assertEqual('function amethod()', strtolower($function)); + } else { + $this->assertEqual('function aMethod()', $function); + } + } + + function testParameterCreationWithoutTypeHinting() { + $reflection = new SimpleReflection('AnyOldArgumentImplementation'); + $function = $reflection->getSignature('aMethod'); + if (version_compare(phpversion(), '5.0.2', '<=')) { + $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); + } else { + $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); + } + } + + function testParameterCreationForTypeHinting() { + $reflection = new SimpleReflection('AnyOldTypeHintedClass'); + $function = $reflection->getSignature('aMethod'); + if (version_compare(phpversion(), '5.0.2', '<=')) { + $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); + } else { + $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); + } + } + + function testIssetFunctionSignature() { + $reflection = new SimpleReflection('AnyOldOverloadedClass'); + $function = $reflection->getSignature('__isset'); + if (version_compare(phpversion(), '5.1.0', '>=')) { + $this->assertEqual('function __isset($key)', $function); + } else { + $this->assertEqual('function __isset()', $function); + } + } + + function testUnsetFunctionSignature() { + $reflection = new SimpleReflection('AnyOldOverloadedClass'); + $function = $reflection->getSignature('__unset'); + if (version_compare(phpversion(), '5.1.0', '>=')) { + $this->assertEqual('function __unset($key)', $function); + } else { + $this->assertEqual('function __unset()', $function); + } + } + + function testProperlyReflectsTheFinalInterfaceWhenObjectImplementsAnExtendedInterface() { + $reflection = new SimpleReflection('AnyDescendentImplementation'); + $interfaces = $reflection->getInterfaces(); + $this->assertEqual(1, count($interfaces)); + $this->assertEqual('AnyDescendentInterface', array_shift($interfaces)); + } + } +?> diff --git a/tests/simpletest/test/remote_test.php b/tests/simpletest/test/remote_test.php new file mode 100644 index 00000000..d3088573 --- /dev/null +++ b/tests/simpletest/test/remote_test.php @@ -0,0 +1,20 @@ +addTestCase(new RemoteTestCase($test_url . '?xml=yes', $test_url . '?xml=yes&dry=yes')); + if (SimpleReporter::inCli()) { + exit ($test->run(new TextReporter()) ? 0 : 1); + } + $test->run(new HtmlReporter()); +?> \ No newline at end of file diff --git a/tests/simpletest/test/shell_test.php b/tests/simpletest/test/shell_test.php new file mode 100644 index 00000000..b2232572 --- /dev/null +++ b/tests/simpletest/test/shell_test.php @@ -0,0 +1,38 @@ +assertIdentical($shell->execute('echo Hello'), 0); + $this->assertPattern('/Hello/', $shell->getOutput()); + } + + function testBadCommand() { + $shell = &new SimpleShell(); + $this->assertNotEqual($ret = $shell->execute('blurgh! 2>&1'), 0); + } + } + + class TestOfShellTesterAndShell extends ShellTestCase { + + function testEcho() { + $this->assertTrue($this->execute('echo Hello')); + $this->assertExitCode(0); + $this->assertoutput('Hello'); + } + + function testFileExistence() { + $this->assertFileExists(dirname(__FILE__) . '/all_tests.php'); + $this->assertFileNotExists('wibble'); + } + + function testFilePatterns() { + $this->assertFilePattern('/all_tests/i', dirname(__FILE__) . '/all_tests.php'); + $this->assertNoFilePattern('/sputnik/i', dirname(__FILE__) . '/all_tests.php'); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/shell_tester_test.php b/tests/simpletest/test/shell_tester_test.php new file mode 100644 index 00000000..bad4f7da --- /dev/null +++ b/tests/simpletest/test/shell_tester_test.php @@ -0,0 +1,41 @@ +_mock_shell; + } + + function testGenericEquality() { + $this->assertEqual('a', 'a'); + $this->assertNotEqual('a', 'A'); + } + + function testExitCode() { + $this->_mock_shell = &new MockSimpleShell(); + $this->_mock_shell->setReturnValue('execute', 0); + $this->_mock_shell->expectOnce('execute', array('ls')); + $this->assertTrue($this->execute('ls')); + $this->assertExitCode(0); + } + + function testOutput() { + $this->_mock_shell = &new MockSimpleShell(); + $this->_mock_shell->setReturnValue('execute', 0); + $this->_mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); + $this->assertOutput("Line 1\nLine 2\n"); + } + + function testOutputPatterns() { + $this->_mock_shell = &new MockSimpleShell(); + $this->_mock_shell->setReturnValue('execute', 0); + $this->_mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); + $this->assertOutputPattern('/line/i'); + $this->assertNoOutputPattern('/line 2/'); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/simpletest_test.php b/tests/simpletest/test/simpletest_test.php new file mode 100644 index 00000000..9c9c897c --- /dev/null +++ b/tests/simpletest/test/simpletest_test.php @@ -0,0 +1,57 @@ +fail('Should be ignored'); + } + } + + class ShouldNeverBeRunEither extends ShouldNeverBeRun { } + + class TestOfStackTrace extends UnitTestCase { + + function testCanFindAssertInTrace() { + $trace = new SimpleStackTrace(array('assert')); + $this->assertEqual( + $trace->traceMethod(array(array( + 'file' => '/my_test.php', + 'line' => 24, + 'function' => 'assertSomething'))), + ' at [/my_test.php line 24]'); + } + } + + class DummyResource { } + + class TestOfContext extends UnitTestCase { + + function testCurrentContextIsUnique() { + $this->assertReference( + SimpleTest::getContext(), + SimpleTest::getContext()); + } + + function testContextHoldsCurrentTestCase() { + $context = &SimpleTest::getContext(); + $this->assertReference($this, $context->getTest()); + } + + function testResourceIsSingleInstanceWithContext() { + $context = &new SimpleTestContext(); + $this->assertReference( + $context->get('DummyResource'), + $context->get('DummyResource')); + } + + function testClearingContextResetsResources() { + $context = &new SimpleTestContext(); + $resource = &$context->get('DummyResource'); + $context->clear(); + $this->assertClone($resource, $context->get('DummyResource')); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/site/1.html b/tests/simpletest/test/site/1.html new file mode 100644 index 00000000..cdc3e0b7 --- /dev/null +++ b/tests/simpletest/test/site/1.html @@ -0,0 +1,6 @@ + + 1 + + 2 + + \ No newline at end of file diff --git a/tests/simpletest/test/site/2.html b/tests/simpletest/test/site/2.html new file mode 100644 index 00000000..fea1449e --- /dev/null +++ b/tests/simpletest/test/site/2.html @@ -0,0 +1,6 @@ + + 2 + + 3 + + \ No newline at end of file diff --git a/tests/simpletest/test/site/3.html b/tests/simpletest/test/site/3.html new file mode 100644 index 00000000..fdd13802 --- /dev/null +++ b/tests/simpletest/test/site/3.html @@ -0,0 +1,6 @@ + + 3 + + 1 + + \ No newline at end of file diff --git a/tests/simpletest/test/site/base_change_redirect.php b/tests/simpletest/test/site/base_change_redirect.php new file mode 100644 index 00000000..096c45db --- /dev/null +++ b/tests/simpletest/test/site/base_change_redirect.php @@ -0,0 +1,6 @@ + + Redirection test + This is a test page for the SimpleTest PHP unit tester + \ No newline at end of file diff --git a/tests/simpletest/test/site/cookie_based_counter.php b/tests/simpletest/test/site/cookie_based_counter.php new file mode 100644 index 00000000..239b9c86 --- /dev/null +++ b/tests/simpletest/test/site/cookie_based_counter.php @@ -0,0 +1,10 @@ + + Cookie Counter + + \ No newline at end of file diff --git a/tests/simpletest/test/site/counting_frameset.html b/tests/simpletest/test/site/counting_frameset.html new file mode 100644 index 00000000..0fc8ac0c --- /dev/null +++ b/tests/simpletest/test/site/counting_frameset.html @@ -0,0 +1,10 @@ + + Frameset for testing of SimpleTest + + + + + This content is for no frames only. + + + \ No newline at end of file diff --git a/tests/simpletest/test/site/double_base_change_redirect.php b/tests/simpletest/test/site/double_base_change_redirect.php new file mode 100644 index 00000000..a76172f6 --- /dev/null +++ b/tests/simpletest/test/site/double_base_change_redirect.php @@ -0,0 +1,6 @@ + + Redirection test + This is a test page for the SimpleTest PHP unit tester + \ No newline at end of file diff --git a/tests/simpletest/test/site/form.html b/tests/simpletest/test/site/form.html new file mode 100644 index 00000000..cc1138e4 --- /dev/null +++ b/tests/simpletest/test/site/form.html @@ -0,0 +1,47 @@ + + Test of form submission + +
    + +
    + +
    + +
    + +
    + +
    + +
    + Radio G + + + + +
    + +
    + +
    + +
    + +
    + +
    + +
    + + \ No newline at end of file diff --git a/tests/simpletest/test/site/form_data_encoded_form.html b/tests/simpletest/test/site/form_data_encoded_form.html new file mode 100644 index 00000000..a0f6b011 --- /dev/null +++ b/tests/simpletest/test/site/form_data_encoded_form.html @@ -0,0 +1,47 @@ + + Test of form submission + +
    + +
    + +
    + +
    + +
    + +
    + +
    + Radio G + + + + +
    + +
    + +
    + +
    + +
    + +
    + +
    + + \ No newline at end of file diff --git a/tests/simpletest/test/site/form_with_false_defaults.html b/tests/simpletest/test/site/form_with_false_defaults.html new file mode 100644 index 00000000..9f3fb381 --- /dev/null +++ b/tests/simpletest/test/site/form_with_false_defaults.html @@ -0,0 +1,40 @@ + + Test of form submission + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + Radio I + + + + +
    + +
    + + \ No newline at end of file diff --git a/tests/simpletest/test/site/form_with_mixed_post_and_get.html b/tests/simpletest/test/site/form_with_mixed_post_and_get.html new file mode 100644 index 00000000..cf8e551d --- /dev/null +++ b/tests/simpletest/test/site/form_with_mixed_post_and_get.html @@ -0,0 +1,15 @@ + + Test of form submission + +
    + +
    + +
    +
    + +
    + +
    + + \ No newline at end of file diff --git a/tests/simpletest/test/site/form_with_tricky_defaults.html b/tests/simpletest/test/site/form_with_tricky_defaults.html new file mode 100644 index 00000000..e028ceb6 --- /dev/null +++ b/tests/simpletest/test/site/form_with_tricky_defaults.html @@ -0,0 +1,35 @@ + + Test of form submission + +
    + +
    + +
    + +
    + +
    + +
    + +
    + Radio I + + + + + +
    + +
    + + \ No newline at end of file diff --git a/tests/simpletest/test/site/form_with_unnamed_submit.html b/tests/simpletest/test/site/form_with_unnamed_submit.html new file mode 100644 index 00000000..08801f1a --- /dev/null +++ b/tests/simpletest/test/site/form_with_unnamed_submit.html @@ -0,0 +1,12 @@ + + Test of form submission + +
    + +
    + + + +
    + + \ No newline at end of file diff --git a/tests/simpletest/test/site/form_without_action.php b/tests/simpletest/test/site/form_without_action.php new file mode 100644 index 00000000..e17bcf56 --- /dev/null +++ b/tests/simpletest/test/site/form_without_action.php @@ -0,0 +1,11 @@ + + Test of form submission + +

    _GET : []

    +

    _POST : []

    +
    + + +
    + + \ No newline at end of file diff --git a/tests/simpletest/test/site/frame_a.html b/tests/simpletest/test/site/frame_a.html new file mode 100644 index 00000000..6eeb8022 --- /dev/null +++ b/tests/simpletest/test/site/frame_a.html @@ -0,0 +1,6 @@ + + A + + This is frame A
    + + \ No newline at end of file diff --git a/tests/simpletest/test/site/frame_b.html b/tests/simpletest/test/site/frame_b.html new file mode 100644 index 00000000..19576142 --- /dev/null +++ b/tests/simpletest/test/site/frame_b.html @@ -0,0 +1,6 @@ + + B + + This is frame B
    + + \ No newline at end of file diff --git a/tests/simpletest/test/site/frame_links.html b/tests/simpletest/test/site/frame_links.html new file mode 100644 index 00000000..864960ac --- /dev/null +++ b/tests/simpletest/test/site/frame_links.html @@ -0,0 +1,7 @@ + + 1 + + Set one to 2 + Exit the frameset + + \ No newline at end of file diff --git a/tests/simpletest/test/site/frameset.html b/tests/simpletest/test/site/frameset.html new file mode 100644 index 00000000..331a0b11 --- /dev/null +++ b/tests/simpletest/test/site/frameset.html @@ -0,0 +1,10 @@ + + Frameset for testing of SimpleTest + + + + + This content is for no frames only. + + + \ No newline at end of file diff --git a/tests/simpletest/test/site/front_controller_style/a_page.php b/tests/simpletest/test/site/front_controller_style/a_page.php new file mode 100644 index 00000000..5f28c24a --- /dev/null +++ b/tests/simpletest/test/site/front_controller_style/a_page.php @@ -0,0 +1,37 @@ + 0) { + $_COOKIE = $HTTP_COOKIE_VARS; + } + if (count($HTTP_GET_VARS) > 0) { + $_GET = $HTTP_GET_VARS; + } + if (count($HTTP_POST_VARS) > 0) { + $_POST = $HTTP_POST_VARS; + } + if (! isset($_SERVER)) { + $_SERVER = $HTTP_SERVER_VARS; + } + global $HTTP_RAW_POST_DATA; + + require_once('../page_request.php'); +?> + Simple test page with links + + Simple test page with links +

    Links

    + Self + No page + Bare action + Empty query + Empty link + Current directory + Down one +

    Forms

    +
    +
    +
    +
    +
    + + + \ No newline at end of file diff --git a/tests/simpletest/test/site/front_controller_style/index.php b/tests/simpletest/test/site/front_controller_style/index.php new file mode 100644 index 00000000..3f2dd082 --- /dev/null +++ b/tests/simpletest/test/site/front_controller_style/index.php @@ -0,0 +1,44 @@ + 0) { + $_COOKIE = $HTTP_COOKIE_VARS; + } + if (count($HTTP_GET_VARS) > 0) { + $_GET = $HTTP_GET_VARS; + } + if (count($HTTP_POST_VARS) > 0) { + $_POST = $HTTP_POST_VARS; + } + if (! isset($_SERVER)) { + $_SERVER = $HTTP_SERVER_VARS; + } + global $HTTP_RAW_POST_DATA; + + require_once('../page_request.php'); +?> + Simple test front controller + + Simple test front controller +

    Links

    + Index + No page + Bare action + Empty query + Empty link + Down one + +

    Forms

    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + + + \ No newline at end of file diff --git a/tests/simpletest/test/site/front_controller_style/show_request.php b/tests/simpletest/test/site/front_controller_style/show_request.php new file mode 100644 index 00000000..f38473ae --- /dev/null +++ b/tests/simpletest/test/site/front_controller_style/show_request.php @@ -0,0 +1,49 @@ +

    Request

    +
    +
    Protocol version
    +
    Request method
    +
    Accept header
    +
    +

    Cookies

    + 0) { + foreach ($_COOKIE as $key => $value) { + print "$key=[$value]
    \n"; + } + } + ?> +

    Raw GET data

    + +

    GET data

    + 0) { + foreach ($get as $key => $value) { + if (is_array($value)) { + $value = implode(', ', $value); + } + print "$key=[$value]
    \n"; + } + } + ?> +

    Raw POST data

    + +
    +

    POST data

    + 0) { + foreach ($_POST as $key => $value) { + print $key . "=["; + if (is_array($value)) { + print implode(', ', $value); + } else { + print $value; + } + print "]
    \n"; + } + } + ?> diff --git a/tests/simpletest/test/site/link_confirm.php b/tests/simpletest/test/site/link_confirm.php new file mode 100644 index 00000000..a9654b34 --- /dev/null +++ b/tests/simpletest/test/site/link_confirm.php @@ -0,0 +1,17 @@ + + SimpleTest testing links + +

    + A target for the + SimpleTest + test suite. +

    +

    +

    +

    + + diff --git a/tests/simpletest/test/site/local_redirect.php b/tests/simpletest/test/site/local_redirect.php new file mode 100644 index 00000000..85357111 --- /dev/null +++ b/tests/simpletest/test/site/local_redirect.php @@ -0,0 +1,6 @@ + + Redirection test + This is a test page for the SimpleTest PHP unit tester + \ No newline at end of file diff --git a/tests/simpletest/test/site/messy_frameset.html b/tests/simpletest/test/site/messy_frameset.html new file mode 100644 index 00000000..83649777 --- /dev/null +++ b/tests/simpletest/test/site/messy_frameset.html @@ -0,0 +1,16 @@ + + Frameset for testing of SimpleTest + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/simpletest/test/site/multiple_widget_form.html b/tests/simpletest/test/site/multiple_widget_form.html new file mode 100644 index 00000000..ec26b11d --- /dev/null +++ b/tests/simpletest/test/site/multiple_widget_form.html @@ -0,0 +1,59 @@ + + Test of form submission + +
    + + +
    + Multiple checkboxes B + + + + +
    + PHP compatible + +
    + + +
    + + +
    + +
    + + +
    + + \ No newline at end of file diff --git a/tests/simpletest/test/site/nested_frameset.html b/tests/simpletest/test/site/nested_frameset.html new file mode 100644 index 00000000..9e2e2983 --- /dev/null +++ b/tests/simpletest/test/site/nested_frameset.html @@ -0,0 +1,10 @@ + + Nested frameset for testing of SimpleTest + + + + + This content is for no frames only. + + + \ No newline at end of file diff --git a/tests/simpletest/test/site/network_confirm.php b/tests/simpletest/test/site/network_confirm.php new file mode 100644 index 00000000..868f6bed --- /dev/null +++ b/tests/simpletest/test/site/network_confirm.php @@ -0,0 +1,77 @@ + 0) { + $_COOKIE = $HTTP_COOKIE_VARS; + } + if (count($HTTP_GET_VARS) > 0) { + $_GET = $HTTP_GET_VARS; + } + if (count($HTTP_POST_VARS) > 0) { + $_POST = $HTTP_POST_VARS; + } + if (! isset($_SERVER)) { + $_SERVER = $HTTP_SERVER_VARS; + } + global $HTTP_RAW_POST_DATA; + + require_once('page_request.php'); +?> + Simple test target file + + A target for the SimpleTest test suite. +

    Request

    +
    +
    Protocol version
    +
    Request method
    +
    Accept header
    +
    +

    Cookies

    + 0) { + foreach ($_COOKIE as $key => $value) { + print htmlentities($key) . "=[" . htmlentities($value) . "]
    \n"; + } + } + ?> +

    Raw GET data

    + +

    GET data

    + 0) { + foreach ($get as $key => $value) { + if (is_array($value)) { + $value = implode(', ', $value); + } + print htmlentities($key) . "=[" . htmlentities($value) . "]
    \n"; + } + } + ?> +

    Dump of $_GET data

    + '; + print_r($_GET); + print '
    '; + ?> +

    Raw POST data

    + +
    +

    POST data

    + 0) { + foreach ($_POST as $key => $value) { + print htmlentities($key) . "=["; + if (is_array($value)) { + print implode(', ', htmlentities($value)); + } else { + print htmlentities($value); + } + print "]
    \n"; + } + } + ?> + + diff --git a/tests/simpletest/test/site/one_page_frameset.html b/tests/simpletest/test/site/one_page_frameset.html new file mode 100644 index 00000000..d961313e --- /dev/null +++ b/tests/simpletest/test/site/one_page_frameset.html @@ -0,0 +1,9 @@ + + Frameset for testing of SimpleTest + + + + This content is for no frames only. + + + \ No newline at end of file diff --git a/tests/simpletest/test/site/page_request.php b/tests/simpletest/test/site/page_request.php new file mode 100644 index 00000000..bb17525e --- /dev/null +++ b/tests/simpletest/test/site/page_request.php @@ -0,0 +1,63 @@ +_parsed = array(); + foreach ($statements as $statement) { + if (strpos($statement, '=') === false) { + continue; + } + $this->_parseStatement($statement); + } + } + + /** @access private */ + function _parseStatement($statement) { + list($key, $value) = explode('=', $statement); + $key = urldecode($key); + if (preg_match('/(.*)\[\]$/', $key, $matches)) { + $key = $matches[1]; + if (! isset($this->_parsed[$key])) { + $this->_parsed[$key] = array(); + } + $this->_addValue($key, $value); + } elseif (isset($this->_parsed[$key])) { + $this->_addValue($key, $value); + } else { + $this->_setValue($key, $value); + } + } + + /** @access private */ + function _addValue($key, $value) { + if (! is_array($this->_parsed[$key])) { + $this->_parsed[$key] = array($this->_parsed[$key]); + } + $this->_parsed[$key][] = urldecode($value); + } + + /** @access private */ + function _setValue($key, $value) { + $this->_parsed[$key] = urldecode($value); + } + + function getAll() { + return $this->_parsed; + } + + function get() { + $request = &new PageRequest($_SERVER['QUERY_STRING']); + return $request->getAll(); + } + + function post() { + global $HTTP_RAW_POST_DATA; + $request = &new PageRequest($HTTP_RAW_POST_DATA); + return $request->getAll(); + } +} +?> \ No newline at end of file diff --git a/tests/simpletest/test/site/path/base_change_redirect.php b/tests/simpletest/test/site/path/base_change_redirect.php new file mode 100644 index 00000000..08636a9c --- /dev/null +++ b/tests/simpletest/test/site/path/base_change_redirect.php @@ -0,0 +1,6 @@ + + Redirection test + This is a test page for the SimpleTest PHP unit tester + \ No newline at end of file diff --git a/tests/simpletest/test/site/path/network_confirm.php b/tests/simpletest/test/site/path/network_confirm.php new file mode 100644 index 00000000..a9fb3182 --- /dev/null +++ b/tests/simpletest/test/site/path/network_confirm.php @@ -0,0 +1,71 @@ + 0) { + $_COOKIE = $HTTP_COOKIE_VARS; + } + if (count($HTTP_GET_VARS) > 0) { + $_GET = $HTTP_GET_VARS; + } + if (count($HTTP_POST_VARS) > 0) { + $_POST = $HTTP_POST_VARS; + } + if (!isset($_SERVER)) { + $_SERVER = $HTTP_SERVER_VARS; + } + global $HTTP_RAW_POST_DATA; + + require_once('../page_request.php'); +?> + Simple test target file in folder + + A target for the SimpleTest test suite. +

    Request

    +
    +
    Protocol version
    +
    Request method
    +
    Accept header
    +
    +

    Cookies

    + 0) { + foreach ($_COOKIE as $key => $value) { + print $key . "=[" . $value . "]
    \n"; + } + } + ?> +

    Raw GET data

    + +

    GET data

    + 0) { + foreach ($get as $key => $value) { + if (is_array($value)) { + $value = implode(', ', $value); + } + print $key . "=[" . $value . "]
    \n"; + } + } + ?> +

    Raw POST data

    + +
    +

    POST data

    + 0) { + foreach ($_POST as $key => $value) { + print $key . "=["; + if (is_array($value)) { + print implode(', ', $value); + } else { + print $value; + } + print "]
    \n"; + } + } + ?> + + diff --git a/tests/simpletest/test/site/path/show_cookies.php b/tests/simpletest/test/site/path/show_cookies.php new file mode 100644 index 00000000..1135b048 --- /dev/null +++ b/tests/simpletest/test/site/path/show_cookies.php @@ -0,0 +1,18 @@ + 0) { + $_COOKIE = $HTTP_COOKIE_VARS; + } +?> + Simple test target file + + A target for the SimpleTest test suite that displays cookies. +

    Cookies

    + 0) { + foreach ($_COOKIE as $key => $value) { + print $key . "=" . $value . ";"; + } + } + ?> + + \ No newline at end of file diff --git a/tests/simpletest/test/site/protected/.htaccess b/tests/simpletest/test/site/protected/.htaccess new file mode 100644 index 00000000..7e89c370 --- /dev/null +++ b/tests/simpletest/test/site/protected/.htaccess @@ -0,0 +1,5 @@ +AuthName "Test of basic authentication" +AuthType Basic +AuthUserFile /home/marcus/projects/lastcraft/www/test/protected/.htpasswd +require valid-user + diff --git a/tests/simpletest/test/site/protected/.htpasswd b/tests/simpletest/test/site/protected/.htpasswd new file mode 100644 index 00000000..f40e1f23 --- /dev/null +++ b/tests/simpletest/test/site/protected/.htpasswd @@ -0,0 +1 @@ +test:wOGY3sAo.zsek diff --git a/tests/simpletest/test/site/protected/1.html b/tests/simpletest/test/site/protected/1.html new file mode 100644 index 00000000..cdc3e0b7 --- /dev/null +++ b/tests/simpletest/test/site/protected/1.html @@ -0,0 +1,6 @@ + + 1 + + 2 + + \ No newline at end of file diff --git a/tests/simpletest/test/site/protected/2.html b/tests/simpletest/test/site/protected/2.html new file mode 100644 index 00000000..fea1449e --- /dev/null +++ b/tests/simpletest/test/site/protected/2.html @@ -0,0 +1,6 @@ + + 2 + + 3 + + \ No newline at end of file diff --git a/tests/simpletest/test/site/protected/3.html b/tests/simpletest/test/site/protected/3.html new file mode 100644 index 00000000..fdd13802 --- /dev/null +++ b/tests/simpletest/test/site/protected/3.html @@ -0,0 +1,6 @@ + + 3 + + 1 + + \ No newline at end of file diff --git a/tests/simpletest/test/site/protected/htaccess b/tests/simpletest/test/site/protected/htaccess new file mode 100644 index 00000000..866def10 --- /dev/null +++ b/tests/simpletest/test/site/protected/htaccess @@ -0,0 +1,4 @@ +AuthName "SimpleTest basic authentication" +AuthType Basic +AuthUserFile /web/guide/lastcraft/public_html/test/protected/.htpasswd +require valid-user diff --git a/tests/simpletest/test/site/protected/local_redirect.php b/tests/simpletest/test/site/protected/local_redirect.php new file mode 100644 index 00000000..85357111 --- /dev/null +++ b/tests/simpletest/test/site/protected/local_redirect.php @@ -0,0 +1,6 @@ + + Redirection test + This is a test page for the SimpleTest PHP unit tester + \ No newline at end of file diff --git a/tests/simpletest/test/site/protected/network_confirm.php b/tests/simpletest/test/site/protected/network_confirm.php new file mode 100644 index 00000000..e0f8a6e4 --- /dev/null +++ b/tests/simpletest/test/site/protected/network_confirm.php @@ -0,0 +1,71 @@ + 0) { + $_COOKIE = $HTTP_COOKIE_VARS; + } + if (count($HTTP_GET_VARS) > 0) { + $_GET = $HTTP_GET_VARS; + } + if (count($HTTP_POST_VARS) > 0) { + $_POST = $HTTP_POST_VARS; + } + if (!isset($_SERVER)) { + $_SERVER = $HTTP_SERVER_VARS; + } + global $HTTP_RAW_POST_DATA; + + require_once('../page_request.php'); +?> + Simple test target file + + A target for the SimpleTest test suite. +

    Request

    +
    +
    Protocol version
    +
    Request method
    +
    Accept header
    +
    +

    Cookies

    + 0) { + foreach ($_COOKIE as $key => $value) { + print $key . "=[" . $value . "]
    \n"; + } + } + ?> +

    Raw GET data

    + +

    GET data

    + 0) { + foreach ($get as $key => $value) { + if (is_array($value)) { + $value = implode(', ', $value); + } + print $key . "=[" . $value . "]
    \n"; + } + } + ?> +

    Raw POST data

    + +
    +

    POST data

    + 0) { + foreach ($_POST as $key => $value) { + print $key . "=["; + if (is_array($value)) { + print implode(', ', $value); + } else { + print $value; + } + print "]
    \n"; + } + } + ?> + + diff --git a/tests/simpletest/test/site/redirect.php b/tests/simpletest/test/site/redirect.php new file mode 100644 index 00000000..14c23fa8 --- /dev/null +++ b/tests/simpletest/test/site/redirect.php @@ -0,0 +1,6 @@ + + Redirection test + This is a test page for the SimpleTest PHP unit tester + \ No newline at end of file diff --git a/tests/simpletest/test/site/savant_style_form.html b/tests/simpletest/test/site/savant_style_form.html new file mode 100644 index 00000000..f510555c --- /dev/null +++ b/tests/simpletest/test/site/savant_style_form.html @@ -0,0 +1,20 @@ + + Test of form submission with Savant style controls + +
    + Checkbox A + + + +
    + Radio B + + + + + +
    + +
    + + \ No newline at end of file diff --git a/tests/simpletest/test/site/search.png b/tests/simpletest/test/site/search.png new file mode 100644 index 0000000000000000000000000000000000000000..3cccbd5a4d636428d78a01ccc5b103237dd9013d GIT binary patch literal 1260 zcmVM!OPAnE85e=b1?++uiiAn;$%qyzl$o_kHhu z|A`i1MdV2u6e=l{Xd(h?>oCwntc8%)zA00Xmx5ac)x#Q{MO zkmq?Mg!t%&_PdTxPALe2sAEJl&`yQRaU5#3T2GEymKDp$IVT~+C*iaZf;i{zM;Ri<-?Q5fLS-)hgN{rNqX@25Pk$3WWj| z7Z))oD3wZ>pPxr6l|sUG-B_kVp@4F^jB>f$MdO^qFbwtk@bD1fIi0jhrGoSGa{vHi z3=0bjXfzs%r(Uls9i6hpVlkpuN*Sv&M7>_e_4PGUsT6>Y=af)b?&+}9=hZnKCyQ>ZljSXp`fkFrhf`A;y ziCmhLl6>E%$+H8UdHzJHUMC6Zx5DbfiVWd zFpx+j;5ZHp!-#~&+}s=hpjhF`r^y4pzAt*`2IV!S1y-T z2m`>y#f6e7l}Z4BY&P3zzT!!AQQi`Z#Uc(55AmaUfLAZqu)e+?;aOQ(QQs?-3Tm|) z0Kl>=7>0q{+gmt}({*;o1P1`furvTf9O)O~s21y32-kJ-%g;aI)yp-t7X$&0j*hw# z8+c4^!!U4gaDdItO#t1FXqwg~cjI~pf&iTJ_jWGsf1hDbJ`>_yy{es7uh&)2s#Gety1G(*EH31F=@mjmWH{%@X0xbP ztC1pPnkMGv<{n?Vy$22Q5<-w^nyQcKv$HeU+1cs3y+H!!9ILCVNV5!Hy!af+WD3$E+p#`XGE`o4b#rCFx0^TTOnVqyZLqoWua z8bTuRG;b)!fXC+P`#$dP@A2l%-+d_rfQN^FK8XMM^Hg7YhKEP+>{$ZIWGdnm0Q?II WL8H`*Xe6Nk0000 0) { + $_GET = $HTTP_GET_VARS; + } +?> + Test of form self submission + +
    + +
    +

    []

    +

    []

    +

    []

    +
    + + + +
    + + + \ No newline at end of file diff --git a/tests/simpletest/test/site/set_cookies.php b/tests/simpletest/test/site/set_cookies.php new file mode 100644 index 00000000..6b448f12 --- /dev/null +++ b/tests/simpletest/test/site/set_cookies.php @@ -0,0 +1,18 @@ + + SimpleTest testing links + +

    + A target for the + SimpleTest + test suite. + All it does is set some cookies which you can see + here. +

    + + diff --git a/tests/simpletest/test/site/slow_page.php b/tests/simpletest/test/site/slow_page.php new file mode 100644 index 00000000..c1aef316 --- /dev/null +++ b/tests/simpletest/test/site/slow_page.php @@ -0,0 +1,6 @@ + + Slow page + This page takes at least two seconds + \ No newline at end of file diff --git a/tests/simpletest/test/site/timestamp.php b/tests/simpletest/test/site/timestamp.php new file mode 100644 index 00000000..3117c486 --- /dev/null +++ b/tests/simpletest/test/site/timestamp.php @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/tests/simpletest/test/site/upload_form.html b/tests/simpletest/test/site/upload_form.html new file mode 100644 index 00000000..806f6799 --- /dev/null +++ b/tests/simpletest/test/site/upload_form.html @@ -0,0 +1,11 @@ + + Test of file upload + +
    + +
    +
    + +
    + + \ No newline at end of file diff --git a/tests/simpletest/test/site/upload_handler.php b/tests/simpletest/test/site/upload_handler.php new file mode 100644 index 00000000..7680b88b --- /dev/null +++ b/tests/simpletest/test/site/upload_handler.php @@ -0,0 +1,18 @@ + + Test of file upload + +

    +

    + + \ No newline at end of file diff --git a/tests/simpletest/test/socket_test.php b/tests/simpletest/test/socket_test.php new file mode 100644 index 00000000..dc0f4f34 --- /dev/null +++ b/tests/simpletest/test/socket_test.php @@ -0,0 +1,26 @@ +assertFalse($error->isError()); + $error->_setError('Ouch'); + $this->assertTrue($error->isError()); + $this->assertEqual($error->getError(), 'Ouch'); + } + + function testClearingError() { + $error = new SimpleStickyError(); + $error->_setError('Ouch'); + $this->assertTrue($error->isError()); + $error->_clearError(); + $this->assertFalse($error->isError()); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/support/collector/collectable.1 b/tests/simpletest/test/support/collector/collectable.1 new file mode 100644 index 00000000..e69de29b diff --git a/tests/simpletest/test/support/collector/collectable.2 b/tests/simpletest/test/support/collector/collectable.2 new file mode 100644 index 00000000..e69de29b diff --git a/tests/simpletest/test/support/latin1_sample b/tests/simpletest/test/support/latin1_sample new file mode 100644 index 00000000..19035257 --- /dev/null +++ b/tests/simpletest/test/support/latin1_sample @@ -0,0 +1 @@ +£¹²³¼½¾@¶øþðßæ«»¢µ \ No newline at end of file diff --git a/tests/simpletest/test/support/spl_examples.php b/tests/simpletest/test/support/spl_examples.php new file mode 100644 index 00000000..091892c2 --- /dev/null +++ b/tests/simpletest/test/support/spl_examples.php @@ -0,0 +1,15 @@ + \ No newline at end of file diff --git a/tests/simpletest/test/support/supplementary_upload_sample.txt b/tests/simpletest/test/support/supplementary_upload_sample.txt new file mode 100644 index 00000000..d8aa9e81 --- /dev/null +++ b/tests/simpletest/test/support/supplementary_upload_sample.txt @@ -0,0 +1 @@ +Some more text content \ No newline at end of file diff --git a/tests/simpletest/test/support/test1.php b/tests/simpletest/test/support/test1.php new file mode 100644 index 00000000..b414586d --- /dev/null +++ b/tests/simpletest/test/support/test1.php @@ -0,0 +1,7 @@ +assertEqual(3,1+2, "pass1"); + } +} +?> diff --git a/tests/simpletest/test/support/upload_sample.txt b/tests/simpletest/test/support/upload_sample.txt new file mode 100644 index 00000000..ec98d7c5 --- /dev/null +++ b/tests/simpletest/test/support/upload_sample.txt @@ -0,0 +1 @@ +Sample for testing file upload \ No newline at end of file diff --git a/tests/simpletest/test/tag_test.php b/tests/simpletest/test/tag_test.php new file mode 100644 index 00000000..c2472c04 --- /dev/null +++ b/tests/simpletest/test/tag_test.php @@ -0,0 +1,555 @@ + '1', 'b' => '')); + $this->assertEqual($tag->getTagName(), 'title'); + $this->assertIdentical($tag->getAttribute('a'), '1'); + $this->assertIdentical($tag->getAttribute('b'), ''); + $this->assertIdentical($tag->getAttribute('c'), false); + $this->assertIdentical($tag->getContent(), ''); + } + + function testTitleContent() { + $tag = &new SimpleTitleTag(array()); + $this->assertTrue($tag->expectEndTag()); + $tag->addContent('Hello'); + $tag->addContent('World'); + $this->assertEqual($tag->getText(), 'HelloWorld'); + } + + function testMessyTitleContent() { + $tag = &new SimpleTitleTag(array()); + $this->assertTrue($tag->expectEndTag()); + $tag->addContent('Hello'); + $tag->addContent('World'); + $this->assertEqual($tag->getText(), 'HelloWorld'); + } + + function testTagWithNoEnd() { + $tag = &new SimpleTextTag(array()); + $this->assertFalse($tag->expectEndTag()); + } + + function testAnchorHref() { + $tag = &new SimpleAnchorTag(array('href' => 'http://here/')); + $this->assertEqual($tag->getHref(), 'http://here/'); + + $tag = &new SimpleAnchorTag(array('href' => '')); + $this->assertIdentical($tag->getAttribute('href'), ''); + $this->assertIdentical($tag->getHref(), ''); + + $tag = &new SimpleAnchorTag(array()); + $this->assertIdentical($tag->getAttribute('href'), false); + $this->assertIdentical($tag->getHref(), ''); + } + + function testIsIdMatchesIdAttribute() { + $tag = &new SimpleAnchorTag(array('href' => 'http://here/', 'id' => 7)); + $this->assertIdentical($tag->getAttribute('id'), '7'); + $this->assertTrue($tag->isId(7)); + } + } + + class TestOfWidget extends UnitTestCase { + + function testTextEmptyDefault() { + $tag = &new SimpleTextTag(array('type' => 'text')); + $this->assertIdentical($tag->getDefault(), ''); + $this->assertIdentical($tag->getValue(), ''); + } + + function testSettingOfExternalLabel() { + $tag = &new SimpleTextTag(array('type' => 'text')); + $tag->setLabel('it'); + $this->assertTrue($tag->isLabel('it')); + } + + function testTextDefault() { + $tag = &new SimpleTextTag(array('value' => 'aaa')); + $this->assertEqual($tag->getDefault(), 'aaa'); + $this->assertEqual($tag->getValue(), 'aaa'); + } + + function testSettingTextValue() { + $tag = &new SimpleTextTag(array('value' => 'aaa')); + $tag->setValue('bbb'); + $this->assertEqual($tag->getValue(), 'bbb'); + $tag->resetValue(); + $this->assertEqual($tag->getValue(), 'aaa'); + } + + function testFailToSetHiddenValue() { + $tag = &new SimpleTextTag(array('value' => 'aaa', 'type' => 'hidden')); + $this->assertFalse($tag->setValue('bbb')); + $this->assertEqual($tag->getValue(), 'aaa'); + } + + function testSubmitDefaults() { + $tag = &new SimpleSubmitTag(array('type' => 'submit')); + $this->assertIdentical($tag->getName(), false); + $this->assertEqual($tag->getValue(), 'Submit'); + $this->assertFalse($tag->setValue('Cannot set this')); + $this->assertEqual($tag->getValue(), 'Submit'); + $this->assertEqual($tag->getLabel(), 'Submit'); + + $encoding = &new MockSimpleMultipartEncoding(); + $encoding->expectNever('add'); + $tag->write($encoding); + } + + function testPopulatedSubmit() { + $tag = &new SimpleSubmitTag( + array('type' => 'submit', 'name' => 's', 'value' => 'Ok!')); + $this->assertEqual($tag->getName(), 's'); + $this->assertEqual($tag->getValue(), 'Ok!'); + $this->assertEqual($tag->getLabel(), 'Ok!'); + + $encoding = &new MockSimpleMultipartEncoding(); + $encoding->expectOnce('add', array('s', 'Ok!')); + $tag->write($encoding); + } + + function testImageSubmit() { + $tag = &new SimpleImageSubmitTag( + array('type' => 'image', 'name' => 's', 'alt' => 'Label')); + $this->assertEqual($tag->getName(), 's'); + $this->assertEqual($tag->getLabel(), 'Label'); + + $encoding = &new MockSimpleMultipartEncoding(); + $encoding->expectAt(0, 'add', array('s.x', 20)); + $encoding->expectAt(1, 'add', array('s.y', 30)); + $tag->write($encoding, 20, 30); + } + + function testImageSubmitTitlePreferredOverAltForLabel() { + $tag = &new SimpleImageSubmitTag( + array('type' => 'image', 'name' => 's', 'alt' => 'Label', 'title' => 'Title')); + $this->assertEqual($tag->getLabel(), 'Title'); + } + + function testButton() { + $tag = &new SimpleButtonTag( + array('type' => 'submit', 'name' => 's', 'value' => 'do')); + $tag->addContent('I am a button'); + $this->assertEqual($tag->getName(), 's'); + $this->assertEqual($tag->getValue(), 'do'); + $this->assertEqual($tag->getLabel(), 'I am a button'); + + $encoding = &new MockSimpleMultipartEncoding(); + $encoding->expectOnce('add', array('s', 'do')); + $tag->write($encoding); + } + } + + class TestOfTextArea extends UnitTestCase { + + function testDefault() { + $tag = &new SimpleTextAreaTag(array('name' => 'a')); + $tag->addContent('Some text'); + $this->assertEqual($tag->getName(), 'a'); + $this->assertEqual($tag->getDefault(), 'Some text'); + } + + function testWrapping() { + $tag = &new SimpleTextAreaTag(array('cols' => '10', 'wrap' => 'physical')); + $tag->addContent("Lot's of text that should be wrapped"); + $this->assertEqual( + $tag->getDefault(), + "Lot's of\r\ntext that\r\nshould be\r\nwrapped"); + $tag->setValue("New long text\r\nwith two lines"); + $this->assertEqual( + $tag->getValue(), + "New long\r\ntext\r\nwith two\r\nlines"); + } + + function testWrappingRemovesLeadingcariageReturn() { + $tag = &new SimpleTextAreaTag(array('cols' => '20', 'wrap' => 'physical')); + $tag->addContent("\rStuff"); + $this->assertEqual($tag->getDefault(), 'Stuff'); + $tag->setValue("\nNew stuff\n"); + $this->assertEqual($tag->getValue(), "New stuff\r\n"); + } + + function testBreaksAreNewlineAndCarriageReturn() { + $tag = &new SimpleTextAreaTag(array('cols' => '10')); + $tag->addContent("Some\nText\rwith\r\nbreaks"); + $this->assertEqual($tag->getValue(), "Some\r\nText\r\nwith\r\nbreaks"); + } + } + + class TestOfCheckbox extends UnitTestCase { + + function testCanSetCheckboxToNamedValueWithBooleanTrue() { + $tag = &new SimpleCheckboxTag(array('name' => 'a', 'value' => 'A')); + $this->assertEqual($tag->getValue(), false); + $tag->setValue(true); + $this->assertIdentical($tag->getValue(), 'A'); + } + } + + class TestOfSelection extends UnitTestCase { + + function testEmpty() { + $tag = &new SimpleSelectionTag(array('name' => 'a')); + $this->assertIdentical($tag->getValue(), ''); + } + + function testSingle() { + $tag = &new SimpleSelectionTag(array('name' => 'a')); + $option = &new SimpleOptionTag(array()); + $option->addContent('AAA'); + $tag->addTag($option); + $this->assertEqual($tag->getValue(), 'AAA'); + } + + function testSingleDefault() { + $tag = &new SimpleSelectionTag(array('name' => 'a')); + $option = &new SimpleOptionTag(array('selected' => '')); + $option->addContent('AAA'); + $tag->addTag($option); + $this->assertEqual($tag->getValue(), 'AAA'); + } + + function testSingleMappedDefault() { + $tag = &new SimpleSelectionTag(array('name' => 'a')); + $option = &new SimpleOptionTag(array('selected' => '', 'value' => 'aaa')); + $option->addContent('AAA'); + $tag->addTag($option); + $this->assertEqual($tag->getValue(), 'aaa'); + } + + function testStartsWithDefault() { + $tag = &new SimpleSelectionTag(array('name' => 'a')); + $a = &new SimpleOptionTag(array()); + $a->addContent('AAA'); + $tag->addTag($a); + $b = &new SimpleOptionTag(array('selected' => '')); + $b->addContent('BBB'); + $tag->addTag($b); + $c = &new SimpleOptionTag(array()); + $c->addContent('CCC'); + $tag->addTag($c); + $this->assertEqual($tag->getValue(), 'BBB'); + } + + function testSettingOption() { + $tag = &new SimpleSelectionTag(array('name' => 'a')); + $a = &new SimpleOptionTag(array()); + $a->addContent('AAA'); + $tag->addTag($a); + $b = &new SimpleOptionTag(array('selected' => '')); + $b->addContent('BBB'); + $tag->addTag($b); + $c = &new SimpleOptionTag(array()); + $c->addContent('CCC'); + $tag->setValue('AAA'); + $this->assertEqual($tag->getValue(), 'AAA'); + } + + function testSettingMappedOption() { + $tag = &new SimpleSelectionTag(array('name' => 'a')); + $a = &new SimpleOptionTag(array('value' => 'aaa')); + $a->addContent('AAA'); + $tag->addTag($a); + $b = &new SimpleOptionTag(array('value' => 'bbb', 'selected' => '')); + $b->addContent('BBB'); + $tag->addTag($b); + $c = &new SimpleOptionTag(array('value' => 'ccc')); + $c->addContent('CCC'); + $tag->addTag($c); + $tag->setValue('AAA'); + $this->assertEqual($tag->getValue(), 'aaa'); + $tag->setValue('ccc'); + $this->assertEqual($tag->getValue(), 'ccc'); + } + + function testSelectionDespiteSpuriousWhitespace() { + $tag = &new SimpleSelectionTag(array('name' => 'a')); + $a = &new SimpleOptionTag(array()); + $a->addContent(' AAA '); + $tag->addTag($a); + $b = &new SimpleOptionTag(array('selected' => '')); + $b->addContent(' BBB '); + $tag->addTag($b); + $c = &new SimpleOptionTag(array()); + $c->addContent(' CCC '); + $tag->addTag($c); + $this->assertEqual($tag->getValue(), ' BBB '); + $tag->setValue('AAA'); + $this->assertEqual($tag->getValue(), ' AAA '); + } + + function testFailToSetIllegalOption() { + $tag = &new SimpleSelectionTag(array('name' => 'a')); + $a = &new SimpleOptionTag(array()); + $a->addContent('AAA'); + $tag->addTag($a); + $b = &new SimpleOptionTag(array('selected' => '')); + $b->addContent('BBB'); + $tag->addTag($b); + $c = &new SimpleOptionTag(array()); + $c->addContent('CCC'); + $tag->addTag($c); + $this->assertFalse($tag->setValue('Not present')); + $this->assertEqual($tag->getValue(), 'BBB'); + } + + function testNastyOptionValuesThatLookLikeFalse() { + $tag = &new SimpleSelectionTag(array('name' => 'a')); + $a = &new SimpleOptionTag(array('value' => '1')); + $a->addContent('One'); + $tag->addTag($a); + $b = &new SimpleOptionTag(array('value' => '0')); + $b->addContent('Zero'); + $tag->addTag($b); + $this->assertIdentical($tag->getValue(), '1'); + $tag->setValue('Zero'); + $this->assertIdentical($tag->getValue(), '0'); + } + + function testBlankOption() { + $tag = &new SimpleSelectionTag(array('name' => 'A')); + $a = &new SimpleOptionTag(array()); + $tag->addTag($a); + $b = &new SimpleOptionTag(array()); + $b->addContent('b'); + $tag->addTag($b); + $this->assertIdentical($tag->getValue(), ''); + $tag->setValue('b'); + $this->assertIdentical($tag->getValue(), 'b'); + $tag->setValue(''); + $this->assertIdentical($tag->getValue(), ''); + } + + function testMultipleDefaultWithNoSelections() { + $tag = &new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); + $a = &new SimpleOptionTag(array()); + $a->addContent('AAA'); + $tag->addTag($a); + $b = &new SimpleOptionTag(array()); + $b->addContent('BBB'); + $tag->addTag($b); + $this->assertIdentical($tag->getDefault(), array()); + $this->assertIdentical($tag->getValue(), array()); + } + + function testMultipleDefaultWithSelections() { + $tag = &new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); + $a = &new SimpleOptionTag(array('selected' => '')); + $a->addContent('AAA'); + $tag->addTag($a); + $b = &new SimpleOptionTag(array('selected' => '')); + $b->addContent('BBB'); + $tag->addTag($b); + $this->assertIdentical($tag->getDefault(), array('AAA', 'BBB')); + $this->assertIdentical($tag->getValue(), array('AAA', 'BBB')); + } + + function testSettingMultiple() { + $tag = &new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); + $a = &new SimpleOptionTag(array('selected' => '')); + $a->addContent('AAA'); + $tag->addTag($a); + $b = &new SimpleOptionTag(array()); + $b->addContent('BBB'); + $tag->addTag($b); + $c = &new SimpleOptionTag(array('selected' => '', 'value' => 'ccc')); + $c->addContent('CCC'); + $tag->addTag($c); + $this->assertIdentical($tag->getDefault(), array('AAA', 'ccc')); + $this->assertTrue($tag->setValue(array('BBB', 'ccc'))); + $this->assertIdentical($tag->getValue(), array('BBB', 'ccc')); + $this->assertTrue($tag->setValue(array())); + $this->assertIdentical($tag->getValue(), array()); + } + + function testFailToSetIllegalOptionsInMultiple() { + $tag = &new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); + $a = &new SimpleOptionTag(array('selected' => '')); + $a->addContent('AAA'); + $tag->addTag($a); + $b = &new SimpleOptionTag(array()); + $b->addContent('BBB'); + $tag->addTag($b); + $this->assertFalse($tag->setValue(array('CCC'))); + $this->assertTrue($tag->setValue(array('AAA', 'BBB'))); + $this->assertFalse($tag->setValue(array('AAA', 'CCC'))); + } + } + + class TestOfRadioGroup extends UnitTestCase { + + function testEmptyGroup() { + $group = &new SimpleRadioGroup(); + $this->assertIdentical($group->getDefault(), false); + $this->assertIdentical($group->getValue(), false); + $this->assertFalse($group->setValue('a')); + } + + function testReadingSingleButtonGroup() { + $group = &new SimpleRadioGroup(); + $group->addWidget(new SimpleRadioButtonTag( + array('value' => 'A', 'checked' => ''))); + $this->assertIdentical($group->getDefault(), 'A'); + $this->assertIdentical($group->getValue(), 'A'); + } + + function testReadingMultipleButtonGroup() { + $group = &new SimpleRadioGroup(); + $group->addWidget(new SimpleRadioButtonTag( + array('value' => 'A'))); + $group->addWidget(new SimpleRadioButtonTag( + array('value' => 'B', 'checked' => ''))); + $this->assertIdentical($group->getDefault(), 'B'); + $this->assertIdentical($group->getValue(), 'B'); + } + + function testFailToSetUnlistedValue() { + $group = &new SimpleRadioGroup(); + $group->addWidget(new SimpleRadioButtonTag(array('value' => 'z'))); + $this->assertFalse($group->setValue('a')); + $this->assertIdentical($group->getValue(), false); + } + + function testSettingNewValueClearsTheOldOne() { + $group = &new SimpleRadioGroup(); + $group->addWidget(new SimpleRadioButtonTag( + array('value' => 'A'))); + $group->addWidget(new SimpleRadioButtonTag( + array('value' => 'B', 'checked' => ''))); + $this->assertTrue($group->setValue('A')); + $this->assertIdentical($group->getValue(), 'A'); + } + + function testIsIdMatchesAnyWidgetInSet() { + $group = &new SimpleRadioGroup(); + $group->addWidget(new SimpleRadioButtonTag( + array('value' => 'A', 'id' => 'i1'))); + $group->addWidget(new SimpleRadioButtonTag( + array('value' => 'B', 'id' => 'i2'))); + $this->assertFalse($group->isId('i0')); + $this->assertTrue($group->isId('i1')); + $this->assertTrue($group->isId('i2')); + } + + function testIsLabelMatchesAnyWidgetInSet() { + $group = &new SimpleRadioGroup(); + $button1 = &new SimpleRadioButtonTag(array('value' => 'A')); + $button1->setLabel('one'); + $group->addWidget($button1); + $button2 = &new SimpleRadioButtonTag(array('value' => 'B')); + $button2->setLabel('two'); + $group->addWidget($button2); + $this->assertFalse($group->isLabel('three')); + $this->assertTrue($group->isLabel('one')); + $this->assertTrue($group->isLabel('two')); + } + } + + class TestOfTagGroup extends UnitTestCase { + + function testReadingMultipleCheckboxGroup() { + $group = &new SimpleCheckboxGroup(); + $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); + $group->addWidget(new SimpleCheckboxTag( + array('value' => 'B', 'checked' => ''))); + $this->assertIdentical($group->getDefault(), 'B'); + $this->assertIdentical($group->getValue(), 'B'); + } + + function testReadingMultipleUncheckedItems() { + $group = &new SimpleCheckboxGroup(); + $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); + $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); + $this->assertIdentical($group->getDefault(), false); + $this->assertIdentical($group->getValue(), false); + } + + function testReadingMultipleCheckedItems() { + $group = &new SimpleCheckboxGroup(); + $group->addWidget(new SimpleCheckboxTag( + array('value' => 'A', 'checked' => ''))); + $group->addWidget(new SimpleCheckboxTag( + array('value' => 'B', 'checked' => ''))); + $this->assertIdentical($group->getDefault(), array('A', 'B')); + $this->assertIdentical($group->getValue(), array('A', 'B')); + } + + function testSettingSingleValue() { + $group = &new SimpleCheckboxGroup(); + $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); + $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); + $this->assertTrue($group->setValue('A')); + $this->assertIdentical($group->getValue(), 'A'); + $this->assertTrue($group->setValue('B')); + $this->assertIdentical($group->getValue(), 'B'); + } + + function testSettingMultipleValues() { + $group = &new SimpleCheckboxGroup(); + $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); + $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); + $this->assertTrue($group->setValue(array('A', 'B'))); + $this->assertIdentical($group->getValue(), array('A', 'B')); + } + + function testSettingNoValue() { + $group = &new SimpleCheckboxGroup(); + $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); + $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); + $this->assertTrue($group->setValue(false)); + $this->assertIdentical($group->getValue(), false); + } + + function testIsIdMatchesAnyIdInSet() { + $group = &new SimpleCheckboxGroup(); + $group->addWidget(new SimpleCheckboxTag(array('id' => 1, 'value' => 'A'))); + $group->addWidget(new SimpleCheckboxTag(array('id' => 2, 'value' => 'B'))); + $this->assertFalse($group->isId(0)); + $this->assertTrue($group->isId(1)); + $this->assertTrue($group->isId(2)); + } + } + + class TestOfUploadWidget extends UnitTestCase { + + function testValueIsFilePath() { + $upload = &new SimpleUploadTag(array('name' => 'a')); + $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt'); + $this->assertEqual($upload->getValue(), dirname(__FILE__) . '/support/upload_sample.txt'); + } + + function testSubmitsFileContents() { + $encoding = &new MockSimpleMultipartEncoding(); + $encoding->expectOnce('attach', array( + 'a', + 'Sample for testing file upload', + 'upload_sample.txt')); + $upload = &new SimpleUploadTag(array('name' => 'a')); + $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt'); + $upload->write($encoding); + } + } + + class TestOfLabelTag extends UnitTestCase { + + function testLabelShouldHaveAnEndTag() { + $label = &new SimpleLabelTag(array()); + $this->assertTrue($label->expectEndTag()); + } + + function testContentIsTextOnly() { + $label = &new SimpleLabelTag(array()); + $label->addContent('Here are words'); + $this->assertEqual($label->getText(), 'Here are words'); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/test_groups.php b/tests/simpletest/test/test_groups.php new file mode 100644 index 00000000..91b8c967 --- /dev/null +++ b/tests/simpletest/test/test_groups.php @@ -0,0 +1,67 @@ +TestSuite('Unit tests'); + $path = dirname(__FILE__); + $this->addTestFile($path . '/errors_test.php'); + if (version_compare(phpversion(), '5') >= 0) { + $this->addTestFile($path . '/exceptions_test.php'); + } + $this->addTestFile($path . '/compatibility_test.php'); + $this->addTestFile($path . '/simpletest_test.php'); + $this->addTestFile($path . '/dumper_test.php'); + $this->addTestFile($path . '/expectation_test.php'); + $this->addTestFile($path . '/unit_tester_test.php'); + if (version_compare(phpversion(), '5', '>=')) { + $this->addTestFile($path . '/reflection_php5_test.php'); + } else { + $this->addTestFile($path . '/reflection_php4_test.php'); + } + $this->addTestFile($path . '/mock_objects_test.php'); + if (version_compare(phpversion(), '5', '>=')) { + $this->addTestFile($path . '/interfaces_test.php'); + } + $this->addTestFile($path . '/collector_test.php'); + $this->addTestFile($path . '/adapter_test.php'); + $this->addTestFile($path . '/socket_test.php'); + $this->addTestFile($path . '/encoding_test.php'); + $this->addTestFile($path . '/url_test.php'); + $this->addTestFile($path . '/cookies_test.php'); + $this->addTestFile($path . '/http_test.php'); + $this->addTestFile($path . '/authentication_test.php'); + $this->addTestFile($path . '/user_agent_test.php'); + $this->addTestFile($path . '/parser_test.php'); + $this->addTestFile($path . '/tag_test.php'); + $this->addTestFile($path . '/form_test.php'); + $this->addTestFile($path . '/page_test.php'); + $this->addTestFile($path . '/frames_test.php'); + $this->addTestFile($path . '/browser_test.php'); + $this->addTestFile($path . '/web_tester_test.php'); + $this->addTestFile($path . '/shell_tester_test.php'); + $this->addTestFile($path . '/xml_test.php'); + } + } + + // Uncomment and modify the following line if you are accessing + // the net via a proxy server. + // + // SimpleTest::useProxy('http://my-proxy', 'optional username', 'optional password'); + + class AllTests extends TestSuite { + function AllTests() { + $this->TestSuite('All tests for SimpleTest ' . SimpleTest::getVersion()); + $this->addTestCase(new UnitTests()); + $this->addTestFile(dirname(__FILE__) . '/shell_test.php'); + $this->addTestFile(dirname(__FILE__) . '/live_test.php'); + $this->addTestFile(dirname(__FILE__) . '/acceptance_test.php'); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/test_with_parse_error.php b/tests/simpletest/test/test_with_parse_error.php new file mode 100644 index 00000000..be748e41 --- /dev/null +++ b/tests/simpletest/test/test_with_parse_error.php @@ -0,0 +1,8 @@ + \ No newline at end of file diff --git a/tests/simpletest/test/unit_tester_test.php b/tests/simpletest/test/unit_tester_test.php new file mode 100644 index 00000000..bed5ae07 --- /dev/null +++ b/tests/simpletest/test/unit_tester_test.php @@ -0,0 +1,54 @@ +assertTrue($this->assertTrue(true)); + } + + function testAssertFalseReturnsAssertionAsBoolean() { + $this->assertTrue($this->assertFalse(false)); + } + + function testAssertEqualReturnsAssertionAsBoolean() { + $this->assertTrue($this->assertEqual(5, 5)); + } + + function testAssertIdenticalReturnsAssertionAsBoolean() { + $this->assertTrue($this->assertIdentical(5, 5)); + } + + function testCoreAssertionsDoNotThrowErrors() { + $this->assertIsA($this, 'UnitTestCase'); + $this->assertNotA($this, 'WebTestCase'); + } + + function testReferenceAssertionOnObjects() { + $a = &new ReferenceForTesting(); + $b = &$a; + $this->assertReference($a, $b); + } + + function testReferenceAssertionOnScalars() { + $a = 25; + $b = &$a; + $this->assertReference($a, $b); + } + + function testCloneOnObjects() { + $a = &new ReferenceForTesting(); + $b = &new ReferenceForTesting(); + $this->assertClone($a, $b); + } + + function testCloneOnScalars() { + $a = 25; + $b = 25; + $this->assertClone($a, $b); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/unit_tests.php b/tests/simpletest/test/unit_tests.php new file mode 100644 index 00000000..d72df16d --- /dev/null +++ b/tests/simpletest/test/unit_tests.php @@ -0,0 +1,17 @@ +run(new SelectiveReporter(new TextReporter(), @$argv[1], @$argv[2])); + return ($result ? 0 : 1); + } + $test->run(new SelectiveReporter(new HtmlReporter(), @$_GET['c'], @$_GET['t'])); +} +?> \ No newline at end of file diff --git a/tests/simpletest/test/url_test.php b/tests/simpletest/test/url_test.php new file mode 100644 index 00000000..9429832e --- /dev/null +++ b/tests/simpletest/test/url_test.php @@ -0,0 +1,407 @@ +assertEqual($url->getScheme(), ''); + $this->assertEqual($url->getHost(), ''); + $this->assertEqual($url->getScheme('http'), 'http'); + $this->assertEqual($url->getHost('localhost'), 'localhost'); + $this->assertEqual($url->getPath(), ''); + } + + function testBasicParsing() { + $url = new SimpleUrl('https://www.lastcraft.com/test/'); + $this->assertEqual($url->getScheme(), 'https'); + $this->assertEqual($url->getHost(), 'www.lastcraft.com'); + $this->assertEqual($url->getPath(), '/test/'); + } + + function testRelativeUrls() { + $url = new SimpleUrl('../somewhere.php'); + $this->assertEqual($url->getScheme(), false); + $this->assertEqual($url->getHost(), false); + $this->assertEqual($url->getPath(), '../somewhere.php'); + } + + function testParseBareParameter() { + $url = new SimpleUrl('?a'); + $this->assertEqual($url->getPath(), ''); + $this->assertEqual($url->getEncodedRequest(), '?a'); + $url->addRequestParameter('x', 'X'); + $this->assertEqual($url->getEncodedRequest(), '?a=&x=X'); + } + + function testParseEmptyParameter() { + $url = new SimpleUrl('?a='); + $this->assertEqual($url->getPath(), ''); + $this->assertEqual($url->getEncodedRequest(), '?a='); + $url->addRequestParameter('x', 'X'); + $this->assertEqual($url->getEncodedRequest(), '?a=&x=X'); + } + + function testParseParameterPair() { + $url = new SimpleUrl('?a=A'); + $this->assertEqual($url->getPath(), ''); + $this->assertEqual($url->getEncodedRequest(), '?a=A'); + $url->addRequestParameter('x', 'X'); + $this->assertEqual($url->getEncodedRequest(), '?a=A&x=X'); + } + + function testParseMultipleParameters() { + $url = new SimpleUrl('?a=A&b=B'); + $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); + $url->addRequestParameter('x', 'X'); + $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&x=X'); + } + + function testParsingParameterMixture() { + $url = new SimpleUrl('?a=A&b=&c'); + $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c'); + $url->addRequestParameter('x', 'X'); + $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c=&x=X'); + } + + function testAddParametersFromScratch() { + $url = new SimpleUrl(''); + $url->addRequestParameter('a', 'A'); + $this->assertEqual($url->getEncodedRequest(), '?a=A'); + $url->addRequestParameter('b', 'B'); + $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); + $url->addRequestParameter('a', 'aaa'); + $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&a=aaa'); + } + + function testClearingParameters() { + $url = new SimpleUrl(''); + $url->addRequestParameter('a', 'A'); + $url->clearRequest(); + $this->assertIdentical($url->getEncodedRequest(), ''); + } + + function testEncodingParameters() { + $url = new SimpleUrl(''); + $url->addRequestParameter('a', '?!"\'#~@[]{}:;<>,./|£$%^&*()_+-='); + $this->assertIdentical( + $request = $url->getEncodedRequest(), + '?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%A3%24%25%5E%26%2A%28%29_%2B-%3D'); + } + + function testDecodingParameters() { + $url = new SimpleUrl('?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%A3%24%25%5E%26%2A%28%29_%2B-%3D'); + $this->assertEqual( + $url->getEncodedRequest(), + '?a=' . urlencode('?!"\'#~@[]{}:;<>,./|£$%^&*()_+-=')); + } + + function testSettingCordinates() { + $url = new SimpleUrl(''); + $url->setCoordinates('32', '45'); + $this->assertIdentical($url->getX(), 32); + $this->assertIdentical($url->getY(), 45); + $this->assertEqual($url->getEncodedRequest(), ''); + } + + function testParseCordinates() { + $url = new SimpleUrl('?32,45'); + $this->assertIdentical($url->getX(), 32); + $this->assertIdentical($url->getY(), 45); + } + + function testClearingCordinates() { + $url = new SimpleUrl('?32,45'); + $url->setCoordinates(); + $this->assertIdentical($url->getX(), false); + $this->assertIdentical($url->getY(), false); + } + + function testParsingParameterCordinateMixture() { + $url = new SimpleUrl('?a=A&b=&c?32,45'); + $this->assertIdentical($url->getX(), 32); + $this->assertIdentical($url->getY(), 45); + $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c'); + } + + function testParsingParameterWithBadCordinates() { + $url = new SimpleUrl('?a=A&b=&c?32'); + $this->assertIdentical($url->getX(), false); + $this->assertIdentical($url->getY(), false); + $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c?32'); + } + + function testPageSplitting() { + $url = new SimpleUrl('./here/../there/somewhere.php'); + $this->assertEqual($url->getPath(), './here/../there/somewhere.php'); + $this->assertEqual($url->getPage(), 'somewhere.php'); + $this->assertEqual($url->getBasePath(), './here/../there/'); + } + + function testAbsolutePathPageSplitting() { + $url = new SimpleUrl("http://host.com/here/there/somewhere.php"); + $this->assertEqual($url->getPath(), "/here/there/somewhere.php"); + $this->assertEqual($url->getPage(), "somewhere.php"); + $this->assertEqual($url->getBasePath(), "/here/there/"); + } + + function testSplittingUrlWithNoPageGivesEmptyPage() { + $url = new SimpleUrl('/here/there/'); + $this->assertEqual($url->getPath(), '/here/there/'); + $this->assertEqual($url->getPage(), ''); + $this->assertEqual($url->getBasePath(), '/here/there/'); + } + + function testPathNormalisation() { + $this->assertEqual( + SimpleUrl::normalisePath('https://host.com/I/am/here/../there/somewhere.php'), + 'https://host.com/I/am/there/somewhere.php'); + } + + // regression test for #1535407 + function testPathNormalisationWithSinglePeriod() { + $this->assertEqual( + SimpleUrl::normalisePath('https://host.com/I/am/here/./../there/somewhere.php'), + 'https://host.com/I/am/there/somewhere.php'); + } + + function testUsernameAndPasswordAreUrlDecoded() { + $url = new SimpleUrl('http://' . urlencode('test@test') . + ':' . urlencode('$!£@*&%') . '@www.lastcraft.com'); + $this->assertEqual($url->getUsername(), 'test@test'); + $this->assertEqual($url->getPassword(), '$!£@*&%'); + } + + function testBlitz() { + $this->assertUrl( + "https://username:password@www.somewhere.com:243/this/that/here.php?a=1&b=2#anchor", + array("https", "username", "password", "www.somewhere.com", 243, "/this/that/here.php", "com", "?a=1&b=2", "anchor"), + array("a" => "1", "b" => "2")); + $this->assertUrl( + "username:password@www.somewhere.com/this/that/here.php?a=1", + array(false, "username", "password", "www.somewhere.com", false, "/this/that/here.php", "com", "?a=1", false), + array("a" => "1")); + $this->assertUrl( + "username:password@somewhere.com:243?1,2", + array(false, "username", "password", "somewhere.com", 243, "/", "com", "", false), + array(), + array(1, 2)); + $this->assertUrl( + "https://www.somewhere.com", + array("https", false, false, "www.somewhere.com", false, "/", "com", "", false)); + $this->assertUrl( + "username@www.somewhere.com:243#anchor", + array(false, "username", false, "www.somewhere.com", 243, "/", "com", "", "anchor")); + $this->assertUrl( + "/this/that/here.php?a=1&b=2?3,4", + array(false, false, false, false, false, "/this/that/here.php", false, "?a=1&b=2", false), + array("a" => "1", "b" => "2"), + array(3, 4)); + $this->assertUrl( + "username@/here.php?a=1&b=2", + array(false, "username", false, false, false, "/here.php", false, "?a=1&b=2", false), + array("a" => "1", "b" => "2")); + } + + function testAmbiguousHosts() { + $this->assertUrl( + "tigger", + array(false, false, false, false, false, "tigger", false, "", false)); + $this->assertUrl( + "/tigger", + array(false, false, false, false, false, "/tigger", false, "", false)); + $this->assertUrl( + "//tigger", + array(false, false, false, "tigger", false, "/", false, "", false)); + $this->assertUrl( + "//tigger/", + array(false, false, false, "tigger", false, "/", false, "", false)); + $this->assertUrl( + "tigger.com", + array(false, false, false, "tigger.com", false, "/", "com", "", false)); + $this->assertUrl( + "me.net/tigger", + array(false, false, false, "me.net", false, "/tigger", "net", "", false)); + } + + function testAsString() { + $this->assertPreserved('https://www.here.com'); + $this->assertPreserved('http://me:secret@www.here.com'); + $this->assertPreserved('http://here/there'); + $this->assertPreserved('http://here/there?a=A&b=B'); + $this->assertPreserved('http://here/there?a=1&a=2'); + $this->assertPreserved('http://here/there?a=1&a=2?9,8'); + $this->assertPreserved('http://host?a=1&a=2'); + $this->assertPreserved('http://host#stuff'); + $this->assertPreserved('http://me:secret@www.here.com/a/b/c/here.html?a=A?7,6'); + $this->assertPreserved('http://www.here.com/?a=A__b=B'); + } + + function assertUrl($raw, $parts, $params = false, $coords = false) { + if (! is_array($params)) { + $params = array(); + } + $url = new SimpleUrl($raw); + $this->assertIdentical($url->getScheme(), $parts[0], "[$raw] scheme -> %s"); + $this->assertIdentical($url->getUsername(), $parts[1], "[$raw] username -> %s"); + $this->assertIdentical($url->getPassword(), $parts[2], "[$raw] password -> %s"); + $this->assertIdentical($url->getHost(), $parts[3], "[$raw] host -> %s"); + $this->assertIdentical($url->getPort(), $parts[4], "[$raw] port -> %s"); + $this->assertIdentical($url->getPath(), $parts[5], "[$raw] path -> %s"); + $this->assertIdentical($url->getTld(), $parts[6], "[$raw] tld -> %s"); + $this->assertIdentical($url->getEncodedRequest(), $parts[7], "[$raw] encoded -> %s"); + $this->assertIdentical($url->getFragment(), $parts[8], "[$raw] fragment -> %s"); + if ($coords) { + $this->assertIdentical($url->getX(), $coords[0], "[$raw] x -> %s"); + $this->assertIdentical($url->getY(), $coords[1], "[$raw] y -> %s"); + } + } + + function testUrlWithTwoSlashesInPath() { + $url = new SimpleUrl('/article/categoryedit/insert//'); + $this->assertEqual($url->getPath(), '/article/categoryedit/insert//'); + } + + function assertPreserved($string) { + $url = new SimpleUrl($string); + $this->assertEqual($url->asString(), $string); + } + } + + class TestOfAbsoluteUrls extends UnitTestCase { + + function testMakingAbsolute() { + $url = new SimpleUrl('../there/somewhere.php'); + $this->assertEqual($url->getPath(), '../there/somewhere.php'); + $absolute = $url->makeAbsolute('https://host.com:1234/I/am/here/'); + $this->assertEqual($absolute->getScheme(), 'https'); + $this->assertEqual($absolute->getHost(), 'host.com'); + $this->assertEqual($absolute->getPort(), 1234); + $this->assertEqual($absolute->getPath(), '/I/am/there/somewhere.php'); + } + + function testMakingAnEmptyUrlAbsolute() { + $url = new SimpleUrl(''); + $this->assertEqual($url->getPath(), ''); + $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); + $this->assertEqual($absolute->getScheme(), 'http'); + $this->assertEqual($absolute->getHost(), 'host.com'); + $this->assertEqual($absolute->getPath(), '/I/am/here/page.html'); + } + + function testMakingAnEmptyUrlAbsoluteWithMissingPageName() { + $url = new SimpleUrl(''); + $this->assertEqual($url->getPath(), ''); + $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); + $this->assertEqual($absolute->getScheme(), 'http'); + $this->assertEqual($absolute->getHost(), 'host.com'); + $this->assertEqual($absolute->getPath(), '/I/am/here/'); + } + + function testMakingAShortQueryUrlAbsolute() { + $url = new SimpleUrl('?a#b'); + $this->assertEqual($url->getPath(), ''); + $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); + $this->assertEqual($absolute->getScheme(), 'http'); + $this->assertEqual($absolute->getHost(), 'host.com'); + $this->assertEqual($absolute->getPath(), '/I/am/here/'); + $this->assertEqual($absolute->getEncodedRequest(), '?a'); + $this->assertEqual($absolute->getFragment(), 'b'); + } + + function testMakingADirectoryUrlAbsolute() { + $url = new SimpleUrl('hello/'); + $this->assertEqual($url->getPath(), 'hello/'); + $this->assertEqual($url->getBasePath(), 'hello/'); + $this->assertEqual($url->getPage(), ''); + $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); + $this->assertEqual($absolute->getPath(), '/I/am/here/hello/'); + } + + function testMakingARootUrlAbsolute() { + $url = new SimpleUrl('/'); + $this->assertEqual($url->getPath(), '/'); + $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); + $this->assertEqual($absolute->getPath(), '/'); + } + + function testMakingARootPageUrlAbsolute() { + $url = new SimpleUrl('/here.html'); + $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); + $this->assertEqual($absolute->getPath(), '/here.html'); + } + + function testCarryAuthenticationFromRootPage() { + $url = new SimpleUrl('here.html'); + $absolute = $url->makeAbsolute('http://test:secret@host.com/'); + $this->assertEqual($absolute->getPath(), '/here.html'); + $this->assertEqual($absolute->getUsername(), 'test'); + $this->assertEqual($absolute->getPassword(), 'secret'); + } + + function testMakingCoordinateUrlAbsolute() { + $url = new SimpleUrl('?1,2'); + $this->assertEqual($url->getPath(), ''); + $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); + $this->assertEqual($absolute->getScheme(), 'http'); + $this->assertEqual($absolute->getHost(), 'host.com'); + $this->assertEqual($absolute->getPath(), '/I/am/here/'); + $this->assertEqual($absolute->getX(), 1); + $this->assertEqual($absolute->getY(), 2); + } + + function testMakingAbsoluteAppendedPath() { + $url = new SimpleUrl('./there/somewhere.php'); + $absolute = $url->makeAbsolute('https://host.com/here/'); + $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php'); + } + + function testMakingAbsoluteBadlyFormedAppendedPath() { + $url = new SimpleUrl('there/somewhere.php'); + $absolute = $url->makeAbsolute('https://host.com/here/'); + $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php'); + } + + function testMakingAbsoluteHasNoEffectWhenAlreadyAbsolute() { + $url = new SimpleUrl('https://test:secret@www.lastcraft.com:321/stuff/?a=1#f'); + $absolute = $url->makeAbsolute('http://host.com/here/'); + $this->assertEqual($absolute->getScheme(), 'https'); + $this->assertEqual($absolute->getUsername(), 'test'); + $this->assertEqual($absolute->getPassword(), 'secret'); + $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); + $this->assertEqual($absolute->getPort(), 321); + $this->assertEqual($absolute->getPath(), '/stuff/'); + $this->assertEqual($absolute->getEncodedRequest(), '?a=1'); + $this->assertEqual($absolute->getFragment(), 'f'); + } + + function testMakingAbsoluteCarriesAuthenticationWhenAlreadyAbsolute() { + $url = new SimpleUrl('https://www.lastcraft.com'); + $absolute = $url->makeAbsolute('http://test:secret@host.com/here/'); + $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); + $this->assertEqual($absolute->getUsername(), 'test'); + $this->assertEqual($absolute->getPassword(), 'secret'); + } + + function testMakingHostOnlyAbsoluteDoesNotCarryAnyOtherInformation() { + $url = new SimpleUrl('http://www.lastcraft.com'); + $absolute = $url->makeAbsolute('https://host.com:81/here/'); + $this->assertEqual($absolute->getScheme(), 'http'); + $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); + $this->assertIdentical($absolute->getPort(), false); + $this->assertEqual($absolute->getPath(), '/'); + } + } + + class TestOfFrameUrl extends UnitTestCase { + + function testTargetAttachment() { + $url = new SimpleUrl('http://www.site.com/home.html'); + $this->assertIdentical($url->getTarget(), false); + $url->setTarget('A frame'); + $this->assertIdentical($url->getTarget(), 'A frame'); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/user_agent_test.php b/tests/simpletest/test/user_agent_test.php new file mode 100644 index 00000000..86fb85c1 --- /dev/null +++ b/tests/simpletest/test/user_agent_test.php @@ -0,0 +1,358 @@ +_headers = &new MockSimpleHttpHeaders(); + + $this->_response = &new MockSimpleHttpResponse(); + $this->_response->setReturnValue('isError', false); + $this->_response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); + + $this->_request = &new MockSimpleHttpRequest(); + $this->_request->setReturnReference('fetch', $this->_response); + } + + function testGetRequestWithoutIncidentGivesNoErrors() { + $url = new SimpleUrl('http://test:secret@this.com/page.html'); + $url->addRequestParameters(array('a' => 'A', 'b' => 'B')); + + $agent = &new MockRequestUserAgent(); + $agent->setReturnReference('_createHttpRequest', $this->_request); + $agent->SimpleUserAgent(); + + $response = &$agent->fetchResponse( + new SimpleUrl('http://test:secret@this.com/page.html'), + new SimpleGetEncoding(array('a' => 'A', 'b' => 'B'))); + $this->assertFalse($response->isError()); + } + } + + class TestOfAdditionalHeaders extends UnitTestCase { + + function testAdditionalHeaderAddedToRequest() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); + + $request = &new MockSimpleHttpRequest(); + $request->setReturnReference('fetch', $response); + $request->expectOnce( + 'addHeaderLine', + array('User-Agent: SimpleTest')); + + $agent = &new MockRequestUserAgent(); + $agent->setReturnReference('_createHttpRequest', $request); + $agent->SimpleUserAgent(); + $agent->addHeader('User-Agent: SimpleTest'); + $response = &$agent->fetchResponse(new SimpleUrl('http://this.host/'), new SimpleGetEncoding()); + } + } + + class TestOfBrowserCookies extends UnitTestCase { + + function &_createStandardResponse() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue("isError", false); + $response->setReturnValue("getContent", "stuff"); + $response->setReturnReference("getHeaders", new MockSimpleHttpHeaders()); + return $response; + } + + function &_createCookieSite($header_lines) { + $headers = &new SimpleHttpHeaders($header_lines); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue("isError", false); + $response->setReturnReference("getHeaders", $headers); + $response->setReturnValue("getContent", "stuff"); + + $request = &new MockSimpleHttpRequest(); + $request->setReturnReference("fetch", $response); + return $request; + } + + function &_createMockedRequestUserAgent(&$request) { + $agent = &new MockRequestUserAgent(); + $agent->setReturnReference('_createHttpRequest', $request); + $agent->SimpleUserAgent(); + return $agent; + } + + function testCookieJarIsSentToRequest() { + $jar = new SimpleCookieJar(); + $jar->setCookie('a', 'A'); + + $request = &new MockSimpleHttpRequest(); + $request->setReturnReference('fetch', $this->_createStandardResponse()); + $request->expectOnce('readCookiesFromJar', array($jar, '*')); + + $agent = &$this->_createMockedRequestUserAgent($request); + $agent->setCookie('a', 'A'); + $agent->fetchResponse( + new SimpleUrl('http://this.com/this/path/page.html'), + new SimpleGetEncoding()); + } + + function testNoCookieJarIsSentToRequestWhenCookiesAreDisabled() { + $request = &new MockSimpleHttpRequest(); + $request->setReturnReference('fetch', $this->_createStandardResponse()); + $request->expectNever('readCookiesFromJar'); + + $agent = &$this->_createMockedRequestUserAgent($request); + $agent->setCookie('a', 'A'); + $agent->ignoreCookies(); + $agent->fetchResponse( + new SimpleUrl('http://this.com/this/path/page.html'), + new SimpleGetEncoding()); + } + + function testReadingNewCookie() { + $request = &$this->_createCookieSite('Set-cookie: a=AAAA'); + $agent = &$this->_createMockedRequestUserAgent($request); + $agent->fetchResponse( + new SimpleUrl('http://this.com/this/path/page.html'), + new SimpleGetEncoding()); + $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); + } + + function testIgnoringNewCookieWhenCookiesDisabled() { + $request = &$this->_createCookieSite('Set-cookie: a=AAAA'); + $agent = &$this->_createMockedRequestUserAgent($request); + $agent->ignoreCookies(); + $agent->fetchResponse( + new SimpleUrl('http://this.com/this/path/page.html'), + new SimpleGetEncoding()); + $this->assertIdentical($agent->getCookieValue("this.com", "this/path/", "a"), false); + } + + function testOverwriteCookieThatAlreadyExists() { + $request = &$this->_createCookieSite('Set-cookie: a=AAAA'); + $agent = &$this->_createMockedRequestUserAgent($request); + $agent->setCookie('a', 'A'); + $agent->fetchResponse( + new SimpleUrl('http://this.com/this/path/page.html'), + new SimpleGetEncoding()); + $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); + } + + function testClearCookieBySettingExpiry() { + $request = &$this->_createCookieSite('Set-cookie: a=b'); + $agent = &$this->_createMockedRequestUserAgent($request); + + $agent->setCookie("a", "A", "this/path/", "Wed, 25-Dec-02 04:24:21 GMT"); + $agent->fetchResponse( + new SimpleUrl('http://this.com/this/path/page.html'), + new SimpleGetEncoding()); + $this->assertIdentical( + $agent->getCookieValue("this.com", "this/path/", "a"), + "b"); + $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); + $this->assertIdentical( + $agent->getCookieValue("this.com", "this/path/", "a"), + false); + } + + function testAgeingAndClearing() { + $request = &$this->_createCookieSite('Set-cookie: a=A; expires=Wed, 25-Dec-02 04:24:21 GMT; path=/this/path'); + $agent = &$this->_createMockedRequestUserAgent($request); + + $agent->fetchResponse( + new SimpleUrl('http://this.com/this/path/page.html'), + new SimpleGetEncoding()); + $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); + $this->assertIdentical( + $agent->getCookieValue("this.com", "this/path/", "a"), + "A"); + $agent->ageCookies(2); + $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); + $this->assertIdentical( + $agent->getCookieValue("this.com", "this/path/", "a"), + false); + } + + function testReadingIncomingAndSettingNewCookies() { + $request = &$this->_createCookieSite('Set-cookie: a=AAA'); + $agent = &$this->_createMockedRequestUserAgent($request); + + $this->assertNull($agent->getBaseCookieValue("a", false)); + $agent->fetchResponse( + new SimpleUrl('http://this.com/this/path/page.html'), + new SimpleGetEncoding()); + $agent->setCookie("b", "BBB", "this.com", "this/path/"); + $this->assertEqual( + $agent->getBaseCookieValue("a", new SimpleUrl('http://this.com/this/path/page.html')), + "AAA"); + $this->assertEqual( + $agent->getBaseCookieValue("b", new SimpleUrl('http://this.com/this/path/page.html')), + "BBB"); + } + } + + class TestOfHttpRedirects extends UnitTestCase { + + function &createRedirect($content, $redirect) { + $headers = &new MockSimpleHttpHeaders(); + $headers->setReturnValue('isRedirect', (boolean)$redirect); + $headers->setReturnValue('getLocation', $redirect); + + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('getContent', $content); + $response->setReturnReference('getHeaders', $headers); + + $request = &new MockSimpleHttpRequest(); + $request->setReturnReference('fetch', $response); + return $request; + } + + function testDisabledRedirects() { + $agent = &new MockRequestUserAgent(); + $agent->setReturnReference( + '_createHttpRequest', + $this->createRedirect('stuff', 'there.html')); + $agent->expectOnce('_createHttpRequest'); + $agent->SimpleUserAgent(); + + $agent->setMaximumRedirects(0); + $response = &$agent->fetchResponse(new SimpleUrl('here.html'), new SimpleGetEncoding()); + $this->assertEqual($response->getContent(), 'stuff'); + } + + function testSingleRedirect() { + $agent = &new MockRequestUserAgent(); + $agent->setReturnReferenceAt( + 0, + '_createHttpRequest', + $this->createRedirect('first', 'two.html')); + $agent->setReturnReferenceAt( + 1, + '_createHttpRequest', + $this->createRedirect('second', 'three.html')); + $agent->expectCallCount('_createHttpRequest', 2); + $agent->SimpleUserAgent(); + + $agent->setMaximumRedirects(1); + $response = &$agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); + $this->assertEqual($response->getContent(), 'second'); + } + + function testDoubleRedirect() { + $agent = &new MockRequestUserAgent(); + $agent->setReturnReferenceAt( + 0, + '_createHttpRequest', + $this->createRedirect('first', 'two.html')); + $agent->setReturnReferenceAt( + 1, + '_createHttpRequest', + $this->createRedirect('second', 'three.html')); + $agent->setReturnReferenceAt( + 2, + '_createHttpRequest', + $this->createRedirect('third', 'four.html')); + $agent->expectCallCount('_createHttpRequest', 3); + $agent->SimpleUserAgent(); + + $agent->setMaximumRedirects(2); + $response = &$agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); + $this->assertEqual($response->getContent(), 'third'); + } + + function testSuccessAfterRedirect() { + $agent = &new MockRequestUserAgent(); + $agent->setReturnReferenceAt( + 0, + '_createHttpRequest', + $this->createRedirect('first', 'two.html')); + $agent->setReturnReferenceAt( + 1, + '_createHttpRequest', + $this->createRedirect('second', false)); + $agent->setReturnReferenceAt( + 2, + '_createHttpRequest', + $this->createRedirect('third', 'four.html')); + $agent->expectCallCount('_createHttpRequest', 2); + $agent->SimpleUserAgent(); + + $agent->setMaximumRedirects(2); + $response = &$agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); + $this->assertEqual($response->getContent(), 'second'); + } + + function testRedirectChangesPostToGet() { + $agent = &new MockRequestUserAgent(); + $agent->setReturnReferenceAt( + 0, + '_createHttpRequest', + $this->createRedirect('first', 'two.html')); + $agent->expectArgumentsAt(0, '_createHttpRequest', array('*', new IsAExpectation('SimplePostEncoding'))); + $agent->setReturnReferenceAt( + 1, + '_createHttpRequest', + $this->createRedirect('second', 'three.html')); + $agent->expectArgumentsAt(1, '_createHttpRequest', array('*', new IsAExpectation('SimpleGetEncoding'))); + $agent->expectCallCount('_createHttpRequest', 2); + $agent->SimpleUserAgent(); + $agent->setMaximumRedirects(1); + $response = &$agent->fetchResponse(new SimpleUrl('one.html'), new SimplePostEncoding()); + } + } + + class TestOfBadHosts extends UnitTestCase { + + function &_createSimulatedBadHost() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnValue('isError', true); + $response->setReturnValue('getError', 'Bad socket'); + $response->setReturnValue('getContent', false); + + $request = &new MockSimpleHttpRequest(); + $request->setReturnReference('fetch', $response); + return $request; + } + + function testUntestedHost() { + $request = &$this->_createSimulatedBadHost(); + + $agent = &new MockRequestUserAgent(); + $agent->setReturnReference('_createHttpRequest', $request); + $agent->SimpleUserAgent(); + + $response = &$agent->fetchResponse( + new SimpleUrl('http://this.host/this/path/page.html'), + new SimpleGetEncoding()); + $this->assertTrue($response->isError()); + } + } + + class TestOfAuthorisation extends UnitTestCase { + + function testAuthenticateHeaderAdded() { + $response = &new MockSimpleHttpResponse(); + $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); + + $request = &new MockSimpleHttpRequest(); + $request->setReturnReference('fetch', $response); + $request->expectOnce( + 'addHeaderLine', + array('Authorization: Basic ' . base64_encode('test:secret'))); + + $agent = &new MockRequestUserAgent(); + $agent->setReturnReference('_createHttpRequest', $request); + $agent->SimpleUserAgent(); + $response = &$agent->fetchResponse( + new SimpleUrl('http://test:secret@this.host'), + new SimpleGetEncoding()); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/visual_test.php b/tests/simpletest/test/visual_test.php new file mode 100644 index 00000000..5bad166e --- /dev/null +++ b/tests/simpletest/test/visual_test.php @@ -0,0 +1,566 @@ +_a = $a; + } + } + + class PassingUnitTestCaseOutput extends UnitTestCase { + + function testOfResults() { + $this->pass('Pass'); + } + + function testTrue() { + $this->assertTrue(true); + } + + function testFalse() { + $this->assertFalse(false); + } + + function testExpectation() { + $expectation = &new EqualExpectation(25, 'My expectation message: %s'); + $this->assert($expectation, 25, 'My assert message : %s'); + } + + function testNull() { + $this->assertNull(null, "%s -> Pass"); + $this->assertNotNull(false, "%s -> Pass"); + } + + function testType() { + $this->assertIsA("hello", "string", "%s -> Pass"); + $this->assertIsA($this, "PassingUnitTestCaseOutput", "%s -> Pass"); + $this->assertIsA($this, "UnitTestCase", "%s -> Pass"); + } + + function testTypeEquality() { + $this->assertEqual("0", 0, "%s -> Pass"); + } + + function testNullEquality() { + $this->assertNotEqual(null, 1, "%s -> Pass"); + $this->assertNotEqual(1, null, "%s -> Pass"); + } + + function testIntegerEquality() { + $this->assertNotEqual(1, 2, "%s -> Pass"); + } + + function testStringEquality() { + $this->assertEqual("a", "a", "%s -> Pass"); + $this->assertNotEqual("aa", "ab", "%s -> Pass"); + } + + function testHashEquality() { + $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> Pass"); + } + + function testWithin() { + $this->assertWithinMargin(5, 5.4, 0.5, "%s -> Pass"); + } + + function testOutside() { + $this->assertOutsideMargin(5, 5.6, 0.5, "%s -> Pass"); + } + + function testStringIdentity() { + $a = "fred"; + $b = $a; + $this->assertIdentical($a, $b, "%s -> Pass"); + } + + function testTypeIdentity() { + $a = "0"; + $b = 0; + $this->assertNotIdentical($a, $b, "%s -> Pass"); + } + + function testNullIdentity() { + $this->assertNotIdentical(null, 1, "%s -> Pass"); + $this->assertNotIdentical(1, null, "%s -> Pass"); + } + + function testHashIdentity() { + } + + function testObjectEquality() { + $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Pass"); + $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Pass"); + } + + function testObjectIndentity() { + $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Pass"); + $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Pass"); + } + + function testReference() { + $a = "fred"; + $b = &$a; + $this->assertReference($a, $b, "%s -> Pass"); + } + + function testCloneOnDifferentObjects() { + $a = "fred"; + $b = $a; + $c = "Hello"; + $this->assertClone($a, $b, "%s -> Pass"); + } + + function testPatterns() { + $this->assertPattern('/hello/i', "Hello there", "%s -> Pass"); + $this->assertNoPattern('/hello/', "Hello there", "%s -> Pass"); + } + + function testLongStrings() { + $text = ""; + for ($i = 0; $i < 10; $i++) { + $text .= "0123456789"; + } + $this->assertEqual($text, $text); + } + } + + class FailingUnitTestCaseOutput extends UnitTestCase { + + function testOfResults() { + $this->fail('Fail'); // Fail. + } + + function testTrue() { + $this->assertTrue(false); // Fail. + } + + function testFalse() { + $this->assertFalse(true); // Fail. + } + + function testExpectation() { + $expectation = &new EqualExpectation(25, 'My expectation message: %s'); + $this->assert($expectation, 24, 'My assert message : %s'); // Fail. + } + + function testNull() { + $this->assertNull(false, "%s -> Fail"); // Fail. + $this->assertNotNull(null, "%s -> Fail"); // Fail. + } + + function testType() { + $this->assertIsA(14, "string", "%s -> Fail"); // Fail. + $this->assertIsA(14, "TestOfUnitTestCaseOutput", "%s -> Fail"); // Fail. + $this->assertIsA($this, "TestReporter", "%s -> Fail"); // Fail. + } + + function testTypeEquality() { + $this->assertNotEqual("0", 0, "%s -> Fail"); // Fail. + } + + function testNullEquality() { + $this->assertEqual(null, 1, "%s -> Fail"); // Fail. + $this->assertEqual(1, null, "%s -> Fail"); // Fail. + } + + function testIntegerEquality() { + $this->assertEqual(1, 2, "%s -> Fail"); // Fail. + } + + function testStringEquality() { + $this->assertNotEqual("a", "a", "%s -> Fail"); // Fail. + $this->assertEqual("aa", "ab", "%s -> Fail"); // Fail. + } + + function testHashEquality() { + $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "Z"), "%s -> Fail"); + } + + function testWithin() { + $this->assertWithinMargin(5, 5.6, 0.5, "%s -> Fail"); // Fail. + } + + function testOutside() { + $this->assertOutsideMargin(5, 5.4, 0.5, "%s -> Fail"); // Fail. + } + + function testStringIdentity() { + $a = "fred"; + $b = $a; + $this->assertNotIdentical($a, $b, "%s -> Fail"); // Fail. + } + + function testTypeIdentity() { + $a = "0"; + $b = 0; + $this->assertIdentical($a, $b, "%s -> Fail"); // Fail. + } + + function testNullIdentity() { + $this->assertIdentical(null, 1, "%s -> Fail"); // Fail. + $this->assertIdentical(1, null, "%s -> Fail"); // Fail. + } + + function testHashIdentity() { + $this->assertIdentical(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> fail"); // Fail. + } + + function testObjectEquality() { + $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Fail"); // Fail. + $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Fail"); // Fail. + } + + function testObjectIndentity() { + $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Fail"); // Fail. + $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Fail"); // Fail. + } + + function testReference() { + $a = "fred"; + $b = &$a; + $this->assertClone($a, $b, "%s -> Fail"); // Fail. + } + + function testCloneOnDifferentObjects() { + $a = "fred"; + $b = $a; + $c = "Hello"; + $this->assertClone($a, $c, "%s -> Fail"); // Fail. + } + + function testPatterns() { + $this->assertPattern('/hello/', "Hello there", "%s -> Fail"); // Fail. + $this->assertNoPattern('/hello/i', "Hello there", "%s -> Fail"); // Fail. + } + + function testLongStrings() { + $text = ""; + for ($i = 0; $i < 10; $i++) { + $text .= "0123456789"; + } + $this->assertEqual($text . $text, $text . "a" . $text); // Fail. + } + } + + class VisualTestOfErrors extends UnitTestCase { + + function testDumping() { + $this->dump(array('Hello'), 'Displaying a variable'); + } + + function testErrorDisplay() { + trigger_error('Default'); // Exception. + trigger_error('Error', E_USER_ERROR); // Exception. + trigger_error('Warning', E_USER_WARNING); // Exception. + trigger_error('Notice', E_USER_NOTICE); // Exception. + } + + function testErrorTrap() { + $this->expectError(); // Pass. + trigger_error('Error 1'); + } + + function testErrorText() { + $this->expectError('Error 2', "%s -> Pass"); + $this->expectError('Error 2b', "%s -> Fail"); // Fail. + trigger_error('Error 2'); + $this->dump('This should lie between the two errors'); + trigger_error('Error 3'); + } + + function testErrorPatterns() { + $this->expectError(new PatternExpectation('/Error 2/'), "%s -> Pass"); + $this->expectError(new PatternExpectation('/Error 2/'), "%s -> Fail"); // Fail. + trigger_error('Error 2'); + $this->dump('This should lie between the two errors'); + trigger_error('Error 3'); + } + + function testExceptionTrap() { + if (version_compare(phpversion(), '5') >= 0) { + eval('throw new Exception("Ouch!");'); + $this->message('Should not be here'); + } else { + trigger_error('No exceptions in PHP4'); + } + } + + function testExceptionExpectationShowsErrorWhenNoException() { + if (version_compare(phpversion(), '5') >= 0) { + $this->expectException(); + } else { + trigger_error('No exceptions in PHP4'); + } + } + + function testExceptionExpectationShowsPassWhenException() { + if (version_compare(phpversion(), '5') >= 0) { + $this->expectException(); + eval('throw new Exception("Ouch!");'); + } else { + trigger_error('No exceptions in PHP4'); + } + } + + function testSignal() { + $fred = "signal as a string"; + $this->signal("Signal", $fred); // Signal. + } + } + + class Dummy { + function Dummy() { + } + + function a() { + } + } + Mock::generate('Dummy'); + + class TestOfMockObjectsOutput extends UnitTestCase { + + function testCallCounts() { + $dummy = &new MockDummy(); + $dummy->expectCallCount('a', 1, 'My message: %s'); + $dummy->a(); + $dummy->a(); + } + + function testMinimumCallCounts() { + $dummy = &new MockDummy(); + $dummy->expectMinimumCallCount('a', 2, 'My message: %s'); + $dummy->a(); + $dummy->a(); + } + + function testEmptyMatching() { + $dummy = &new MockDummy(); + $dummy->expectArguments('a', array()); + $dummy->a(); + $dummy->a(null); // Fail. + } + + function testEmptyMatchingWithCustomMessage() { + $dummy = &new MockDummy(); + $dummy->expectArguments('a', array(), 'My expectation message: %s'); + $dummy->a(); + $dummy->a(null); // Fail. + } + + function testNullMatching() { + $dummy = &new MockDummy(); + $dummy->expectArguments('a', array(null)); + $dummy->a(null); + $dummy->a(); // Fail. + } + + function testBooleanMatching() { + $dummy = &new MockDummy(); + $dummy->expectArguments('a', array(true, false)); + $dummy->a(true, false); + $dummy->a(true, true); // Fail. + } + + function testIntegerMatching() { + $dummy = &new MockDummy(); + $dummy->expectArguments('a', array(32, 33)); + $dummy->a(32, 33); + $dummy->a(32, 34); // Fail. + } + + function testFloatMatching() { + $dummy = &new MockDummy(); + $dummy->expectArguments('a', array(3.2, 3.3)); + $dummy->a(3.2, 3.3); + $dummy->a(3.2, 3.4); // Fail. + } + + function testStringMatching() { + $dummy = &new MockDummy(); + $dummy->expectArguments('a', array('32', '33')); + $dummy->a('32', '33'); + $dummy->a('32', '34'); // Fail. + } + + function testEmptyMatchingWithCustomExpectationMessage() { + $dummy = &new MockDummy(); + $dummy->expectArguments( + 'a', + array(new EqualExpectation('A', 'My part expectation message: %s')), + 'My expectation message: %s'); + $dummy->a('A'); + $dummy->a('B'); // Fail. + } + + function testArrayMatching() { + $dummy = &new MockDummy(); + $dummy->expectArguments('a', array(array(32), array(33))); + $dummy->a(array(32), array(33)); + $dummy->a(array(32), array('33')); // Fail. + } + + function testObjectMatching() { + $a = new Dummy(); + $a->a = 'a'; + $b = new Dummy(); + $b->b = 'b'; + $dummy = &new MockDummy(); + $dummy->expectArguments('a', array($a, $b)); + $dummy->a($a, $b); + $dummy->a($a, $a); // Fail. + } + + function testBigList() { + $dummy = &new MockDummy(); + $dummy->expectArguments('a', array(false, 0, 1, 1.0)); + $dummy->a(false, 0, 1, 1.0); + $dummy->a(true, false, 2, 2.0); // Fail. + } + } + + class TestOfPastBugs extends UnitTestCase { + + function testMixedTypes() { + $this->assertEqual(array(), null, "%s -> Pass"); + $this->assertIdentical(array(), null, "%s -> Fail"); // Fail. + } + + function testMockWildcards() { + $dummy = &new MockDummy(); + $dummy->expectArguments('a', array('*', array(33))); + $dummy->a(array(32), array(33)); + $dummy->a(array(32), array('33')); // Fail. + } + } + + class TestOfVisualShell extends ShellTestCase { + + function testDump() { + $this->execute('ls'); + $this->dumpOutput(); + $this->execute('dir'); + $this->dumpOutput(); + } + + function testDumpOfList() { + $this->execute('ls'); + $this->dump($this->getOutputAsList()); + } + } + + class PassesAsWellReporter extends HtmlReporter { + + function _getCss() { + return parent::_getCss() . ' .pass { color: darkgreen; }'; + } + + function paintPass($message) { + parent::paintPass($message); + print "Pass: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode(" -> ", $breadcrumb); + print " -> " . htmlentities($message) . "
    \n"; + } + + function paintSignal($type, &$payload) { + print "$type: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode(" -> ", $breadcrumb); + print " -> " . htmlentities(serialize($payload)) . "
    \n"; + } + } + + class TestOfSkippingNoMatterWhat extends UnitTestCase { + + function skip() { + $this->skipIf(true, 'Always skipped -> %s'); + } + + function testFail() { + $this->fail('This really shouldn\'t have happened'); + } + } + + class TestOfSkippingOrElse extends UnitTestCase { + + function skip() { + $this->skipUnless(false, 'Always skipped -> %s'); + } + + function testFail() { + $this->fail('This really shouldn\'t have happened'); + } + } + + class TestOfSkippingTwiceOver extends UnitTestCase { + + function skip() { + $this->skipIf(true, 'First reason -> %s'); + $this->skipIf(true, 'Second reason -> %s'); + } + + function testFail() { + $this->fail('This really shouldn\'t have happened'); + } + } + + class TestThatShouldNotBeSkipped extends UnitTestCase { + + function skip() { + $this->skipIf(false); + $this->skipUnless(true); + } + + function testFail() { + $this->fail('We should see this message'); + } + + function testPass() { + $this->pass('We should see this message'); + } + } + + $test = &new TestSuite('Visual test with 50 passes, 50 fails and 7 exceptions'); + $test->addTestCase(new PassingUnitTestCaseOutput()); + $test->addTestCase(new FailingUnitTestCaseOutput()); + $test->addTestCase(new VisualTestOfErrors()); + $test->addTestCase(new TestOfMockObjectsOutput()); + $test->addTestCase(new TestOfPastBugs()); + $test->addTestCase(new TestOfVisualShell()); + $test->addTestCase(new TestOfSkippingNoMatterWhat()); + $test->addTestCase(new TestOfSkippingOrElse()); + $test->addTestCase(new TestOfSkippingTwiceOver()); + $test->addTestCase(new TestThatShouldNotBeSkipped()); + + if (isset($_GET['xml']) || in_array('xml', (isset($argv) ? $argv : array()))) { + $reporter = &new XmlReporter(); + } elseif (TextReporter::inCli()) { + $reporter = &new TextReporter(); + } else { + $reporter = &new PassesAsWellReporter(); + } + if (isset($_GET['dry']) || in_array('dry', (isset($argv) ? $argv : array()))) { + $reporter->makeDry(); + } + exit ($test->run($reporter) ? 0 : 1); +?> \ No newline at end of file diff --git a/tests/simpletest/test/web_tester_test.php b/tests/simpletest/test/web_tester_test.php new file mode 100644 index 00000000..eb052e71 --- /dev/null +++ b/tests/simpletest/test/web_tester_test.php @@ -0,0 +1,154 @@ +assertTrue($expectation->test('a')); + $this->assertTrue($expectation->test(array('a'))); + $this->assertFalse($expectation->test('A')); + } + + function testMatchesInteger() { + $expectation = new FieldExpectation('1'); + $this->assertTrue($expectation->test('1')); + $this->assertTrue($expectation->test(1)); + $this->assertTrue($expectation->test(array('1'))); + $this->assertTrue($expectation->test(array(1))); + } + + function testNonStringFailsExpectation() { + $expectation = new FieldExpectation('a'); + $this->assertFalse($expectation->test(null)); + } + + function testUnsetFieldCanBeTestedFor() { + $expectation = new FieldExpectation(false); + $this->assertTrue($expectation->test(false)); + } + + function testMultipleValuesCanBeInAnyOrder() { + $expectation = new FieldExpectation(array('a', 'b')); + $this->assertTrue($expectation->test(array('a', 'b'))); + $this->assertTrue($expectation->test(array('b', 'a'))); + $this->assertFalse($expectation->test(array('a', 'a'))); + $this->assertFalse($expectation->test('a')); + } + + function testSingleItemCanBeArrayOrString() { + $expectation = new FieldExpectation(array('a')); + $this->assertTrue($expectation->test(array('a'))); + $this->assertTrue($expectation->test('a')); + } + } + + class TestOfHeaderExpectations extends UnitTestCase { + + function testExpectingOnlyTheHeaderName() { + $expectation = new HttpHeaderExpectation('a'); + $this->assertIdentical($expectation->test(false), false); + $this->assertIdentical($expectation->test('a: A'), true); + $this->assertIdentical($expectation->test('A: A'), true); + $this->assertIdentical($expectation->test('a: B'), true); + $this->assertIdentical($expectation->test(' a : A '), true); + } + + function testHeaderValueAsWell() { + $expectation = new HttpHeaderExpectation('a', 'A'); + $this->assertIdentical($expectation->test(false), false); + $this->assertIdentical($expectation->test('a: A'), true); + $this->assertIdentical($expectation->test('A: A'), true); + $this->assertIdentical($expectation->test('A: a'), false); + $this->assertIdentical($expectation->test('a: B'), false); + $this->assertIdentical($expectation->test(' a : A '), true); + $this->assertIdentical($expectation->test(' a : AB '), false); + } + + function testHeaderValueWithColons() { + $expectation = new HttpHeaderExpectation('a', 'A:B:C'); + $this->assertIdentical($expectation->test('a: A'), false); + $this->assertIdentical($expectation->test('a: A:B'), false); + $this->assertIdentical($expectation->test('a: A:B:C'), true); + $this->assertIdentical($expectation->test('a: A:B:C:D'), false); + } + + function testMultilineSearch() { + $expectation = new HttpHeaderExpectation('a', 'A'); + $this->assertIdentical($expectation->test("aa: A\r\nb: B\r\nc: C"), false); + $this->assertIdentical($expectation->test("aa: A\r\na: A\r\nb: B"), true); + } + + function testMultilineSearchWithPadding() { + $expectation = new HttpHeaderExpectation('a', ' A '); + $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), false); + $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), true); + } + + function testPatternMatching() { + $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/')); + $this->assertIdentical($expectation->test('a: A'), true); + $this->assertIdentical($expectation->test('A: A'), true); + $this->assertIdentical($expectation->test('A: a'), false); + $this->assertIdentical($expectation->test('a: B'), false); + $this->assertIdentical($expectation->test(' a : A '), true); + $this->assertIdentical($expectation->test(' a : AB '), true); + } + + function testCaseInsensitivePatternMatching() { + $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/i')); + $this->assertIdentical($expectation->test('a: a'), true); + $this->assertIdentical($expectation->test('a: B'), false); + $this->assertIdentical($expectation->test(' a : A '), true); + $this->assertIdentical($expectation->test(' a : BAB '), true); + $this->assertIdentical($expectation->test(' a : bab '), true); + } + + function testUnwantedHeader() { + $expectation = new NoHttpHeaderExpectation('a'); + $this->assertIdentical($expectation->test(''), true); + $this->assertIdentical($expectation->test('stuff'), true); + $this->assertIdentical($expectation->test('b: B'), true); + $this->assertIdentical($expectation->test('a: A'), false); + $this->assertIdentical($expectation->test('A: A'), false); + } + + function testMultilineUnwantedSearch() { + $expectation = new NoHttpHeaderExpectation('a'); + $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), true); + $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), false); + } + + function testLocationHeaderSplitsCorrectly() { + $expectation = new HttpHeaderExpectation('Location', 'http://here/'); + $this->assertIdentical($expectation->test('Location: http://here/'), true); + } + } + + class TestOfTextExpectations extends UnitTestCase { + + function testMatchingSubString() { + $expectation = new TextExpectation('wanted'); + $this->assertIdentical($expectation->test(''), false); + $this->assertIdentical($expectation->test('Wanted'), false); + $this->assertIdentical($expectation->test('wanted'), true); + $this->assertIdentical($expectation->test('the wanted text is here'), true); + } + + function testNotMatchingSubString() { + $expectation = new NoTextExpectation('wanted'); + $this->assertIdentical($expectation->test(''), true); + $this->assertIdentical($expectation->test('Wanted'), true); + $this->assertIdentical($expectation->test('wanted'), false); + $this->assertIdentical($expectation->test('the wanted text is here'), false); + } + } + + class TestOfGenericAssertionsInWebTester extends WebTestCase { + + function testEquality() { + $this->assertEqual('a', 'a'); + $this->assertNotEqual('a', 'A'); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test/xml_test.php b/tests/simpletest/test/xml_test.php new file mode 100644 index 00000000..931d2a9a --- /dev/null +++ b/tests/simpletest/test/xml_test.php @@ -0,0 +1,187 @@ + 2)); + $this->assertEqual($nesting->getSize(), 2); + } + } + + class TestOfXmlStructureParsing extends UnitTestCase { + + function testValidXml() { + $listener = &new MockSimpleScorer(); + $listener->expectNever('paintGroupStart'); + $listener->expectNever('paintGroupEnd'); + $listener->expectNever('paintCaseStart'); + $listener->expectNever('paintCaseEnd'); + $parser = &new SimpleTestXmlParser($listener); + $this->assertTrue($parser->parse("\n")); + $this->assertTrue($parser->parse("\n")); + $this->assertTrue($parser->parse("\n")); + } + + function testEmptyGroup() { + $listener = &new MockSimpleScorer(); + $listener->expectOnce('paintGroupStart', array('a_group', 7)); + $listener->expectOnce('paintGroupEnd', array('a_group')); + $parser = &new SimpleTestXmlParser($listener); + $parser->parse("\n"); + $parser->parse("\n"); + $this->assertTrue($parser->parse("\n")); + $this->assertTrue($parser->parse("a_group\n")); + $this->assertTrue($parser->parse("\n")); + $parser->parse("\n"); + } + + function testEmptyCase() { + $listener = &new MockSimpleScorer(); + $listener->expectOnce('paintCaseStart', array('a_case')); + $listener->expectOnce('paintCaseEnd', array('a_case')); + $parser = &new SimpleTestXmlParser($listener); + $parser->parse("\n"); + $parser->parse("\n"); + $this->assertTrue($parser->parse("\n")); + $this->assertTrue($parser->parse("a_case\n")); + $this->assertTrue($parser->parse("\n")); + $parser->parse("\n"); + } + + function testEmptyMethod() { + $listener = &new MockSimpleScorer(); + $listener->expectOnce('paintCaseStart', array('a_case')); + $listener->expectOnce('paintCaseEnd', array('a_case')); + $listener->expectOnce('paintMethodStart', array('a_method')); + $listener->expectOnce('paintMethodEnd', array('a_method')); + $parser = &new SimpleTestXmlParser($listener); + $parser->parse("\n"); + $parser->parse("\n"); + $parser->parse("\n"); + $parser->parse("a_case\n"); + $this->assertTrue($parser->parse("\n")); + $this->assertTrue($parser->parse("a_method\n")); + $this->assertTrue($parser->parse("\n")); + $parser->parse("\n"); + $parser->parse("\n"); + } + + function testNestedGroup() { + $listener = &new MockSimpleScorer(); + $listener->expectArgumentsAt(0, 'paintGroupStart', array('a_group', 7)); + $listener->expectArgumentsAt(1, 'paintGroupStart', array('b_group', 3)); + $listener->expectCallCount('paintGroupStart', 2); + $listener->expectArgumentsAt(0, 'paintGroupEnd', array('b_group')); + $listener->expectArgumentsAt(1, 'paintGroupEnd', array('a_group')); + $listener->expectCallCount('paintGroupEnd', 2); + + $parser = &new SimpleTestXmlParser($listener); + $parser->parse("\n"); + $parser->parse("\n"); + + $this->assertTrue($parser->parse("\n")); + $this->assertTrue($parser->parse("a_group\n")); + $this->assertTrue($parser->parse("\n")); + $this->assertTrue($parser->parse("b_group\n")); + $this->assertTrue($parser->parse("\n")); + $this->assertTrue($parser->parse("\n")); + $parser->parse("\n"); + } + } + + class AnyOldSignal { + var $stuff = true; + } + + class TestOfXmlResultsParsing extends UnitTestCase { + + function sendValidStart(&$parser) { + $parser->parse("\n"); + $parser->parse("\n"); + $parser->parse("\n"); + $parser->parse("a_case\n"); + $parser->parse("\n"); + $parser->parse("a_method\n"); + } + + function sendValidEnd(&$parser) { + $parser->parse("\n"); + $parser->parse("\n"); + $parser->parse("\n"); + } + + function testPass() { + $listener = &new MockSimpleScorer(); + $listener->expectOnce('paintPass', array('a_message')); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse("a_message\n")); + $this->sendValidEnd($parser); + } + + function testFail() { + $listener = &new MockSimpleScorer(); + $listener->expectOnce('paintFail', array('a_message')); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse("a_message\n")); + $this->sendValidEnd($parser); + } + + function testException() { + $listener = &new MockSimpleScorer(); + $listener->expectOnce('paintError', array('a_message')); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse("a_message\n")); + $this->sendValidEnd($parser); + } + + function testSkip() { + $listener = &new MockSimpleScorer(); + $listener->expectOnce('paintSkip', array('a_message')); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse("a_message\n")); + $this->sendValidEnd($parser); + } + + function testSignal() { + $signal = new AnyOldSignal(); + $signal->stuff = "Hello"; + $listener = &new MockSimpleScorer(); + $listener->expectOnce('paintSignal', array('a_signal', $signal)); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse( + "\n")); + $this->sendValidEnd($parser); + } + + function testMessage() { + $listener = &new MockSimpleScorer(); + $listener->expectOnce('paintMessage', array('a_message')); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse("a_message\n")); + $this->sendValidEnd($parser); + } + + function testFormattedMessage() { + $listener = &new MockSimpleScorer(); + $listener->expectOnce('paintFormattedMessage', array("\na\tmessage\n")); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse("\n")); + $this->sendValidEnd($parser); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/test_case.php b/tests/simpletest/test_case.php new file mode 100644 index 00000000..0a5a84e9 --- /dev/null +++ b/tests/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__) . DIRECTORY_SEPARATOR); + } + /**#@-*/ + + /** + * Basic test case. This is the smallest unit of a test + * suite. It searches for + * all methods that start with the the string "test" and + * runs them. Working test cases extend this class. + * @package SimpleTest + * @subpackage UnitTester + */ + class SimpleTestCase { + var $_label = false; + var $_reporter; + var $_observers; + var $_should_skip = false; + + /** + * Sets up the test with no display. + * @param string $label If no test name is given then + * the class name is used. + * @access public + */ + function 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); + } + + /** + * This is a placeholder for skipping tests. In this + * method you place skipIf() and skipUnless() calls to + * set the skipping state. + * @access public + */ + function skip() { + } + + /** + * Will issue a message to the reporter and tell the test + * case to skip if the incoming flag is true. + * @param string $should_skip Condition causing the tests to be skipped. + * @param string $message Text of skip condition. + * @access public + */ + function skipIf($should_skip, $message = '%s') { + if ($should_skip && ! $this->_should_skip) { + $this->_should_skip = true; + $message = sprintf($message, 'Skipping [' . get_class($this) . ']'); + $this->_reporter->paintSkip($message . $this->getAssertionLine()); + } + } + + /** + * Will issue a message to the reporter and tell the test + * case to skip if the incoming flag is false. + * @param string $shouldnt_skip Condition causing the tests to be run. + * @param string $message Text of skip condition. + * @access public + */ + function skipUnless($shouldnt_skip, $message = false) { + $this->skipIf(! $shouldnt_skip, $message); + } + + /** + * Used to invoke the single tests. + * @return SimpleInvoker Individual test runner. + * @access public + */ + function &createInvoker() { + $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. + * @return boolean True if all tests passed. + * @access public + */ + function run(&$reporter) { + $context = &SimpleTest::getContext(); + $context->setTest($this); + $context->setReporter($reporter); + $this->_reporter = &$reporter; + $reporter->paintCaseStart($this->getLabel()); + $this->skip(); + if (! $this->_should_skip) { + foreach ($this->getTests() as $method) { + if ($reporter->shouldInvoke($this->getLabel(), $method)) { + $invoker = &$this->_reporter->createInvoker($this->createInvoker()); + $invoker->before($method); + $invoker->invoke($method); + $invoker->after($method); + } + } + } + $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); + } + $this->_reporter->paintMethodEnd($method); + } + + /** + * Sets up an observer for the test end. + * @param object $observer Must have atTestEnd() + * method. + * @access public + */ + function tell(&$observer) { + $this->_observers[] = &$observer; + } + + /** + * @deprecated + */ + function pass($message = "Pass") { + if (! isset($this->_reporter)) { + trigger_error('Can only make assertions within test methods'); + } + $this->_reporter->paintPass( + $message . $this->getAssertionLine()); + return true; + } + + /** + * Sends a fail event with a message. + * @param string $message Message to send. + * @access public + */ + function fail($message = "Fail") { + if (! isset($this->_reporter)) { + trigger_error('Can only make assertions within test methods'); + } + $this->_reporter->paintFail( + $message . $this->getAssertionLine()); + return false; + } + + /** + * Formats a PHP error and dispatches it to the + * reporter. + * @param integer $severity PHP error code. + * @param string $message Text of error. + * @param string $file File error occoured in. + * @param integer $line Line number of error. + * @access public + */ + function error($severity, $message, $file, $line) { + if (! isset($this->_reporter)) { + trigger_error('Can only make assertions within test methods'); + } + $this->_reporter->paintError( + "Unexpected PHP error [$message] severity [$severity] in [$file line $line]"); + } + + /** + * Formats an exception and dispatches it to the + * reporter. + * @param Exception $exception Object thrown. + * @access public + */ + function exception($exception) { + $this->_reporter->paintException($exception); + } + + /** + * @deprecated + */ + function signal($type, &$payload) { + if (! isset($this->_reporter)) { + trigger_error('Can only make assertions within test methods'); + } + $this->_reporter->paintSignal($type, $payload); + } + + /** + * Runs an expectation directly, for extending the + * tests with new expectation classes. + * @param SimpleExpectation $expectation Expectation subclass. + * @param mixed $compare Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assert(&$expectation, $compare, $message = '%s') { + if ($expectation->test($compare)) { + return $this->pass(sprintf( + $message, + $expectation->overlayMessage($compare, $this->_reporter->getDumper()))); + } else { + return $this->fail(sprintf( + $message, + $expectation->overlayMessage($compare, $this->_reporter->getDumper()))); + } + } + + /** + * @deprecated + */ + function assertExpectation(&$expectation, $compare, $message = '%s') { + return $this->assert($expectation, $compare, $message); + } + + /** + * Uses a stack trace to find the line of an assertion. + * @return string Line number of first assert* + * method embedded in format string. + * @access public + */ + function getAssertionLine() { + $trace = new SimpleStackTrace(array('assert', 'expect', 'pass', 'fail', 'skip')); + return $trace->traceMethod(); + } + + /** + * Sends a formatted dump of a variable to the + * test suite for those emergency debugging + * situations. + * @param mixed $variable Variable to display. + * @param string $message Message to display. + * @return mixed The original variable. + * @access public + */ + function dump($variable, $message = false) { + $dumper = $this->_reporter->getDumper(); + $formatted = $dumper->dump($variable); + if ($message) { + $formatted = $message . "\n" . $formatted; + } + $this->_reporter->paintFormattedMessage($formatted); + return $variable; + } + + /** + * @deprecated + */ + 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 TestSuite { + var $_label; + var $_test_cases; + var $_old_track_errors; + var $_xdebug_is_enabled; + + /** + * Sets the name of the test suite. + * @param string $label Name sent at the start and end + * of the test. + * @access public + */ + function TestSuite($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) == 'testsuite' || $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 BadTestSuite($test_file, $error)); + return; + } + $classes = $this->_selectRunnableTests($existing_classes, get_declared_classes()); + if (count($classes) == 0) { + $this->addTestCase(new BadTestSuite($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/i', + '/var: Deprecated/i', + '/Non-static method/i'); + foreach ($self_inflicted_errors as $pattern) { + if (preg_match($pattern, $error)) { + 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 TestSuite Group loaded with the new + * test cases. + * @access private + */ + function &_createGroupFromClasses($title, $classes) { + SimpleTest::ignoreParentsIfIgnored($classes); + $group = &new TestSuite($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 == 'testsuite' || $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); + unset($test); + } else { + $this->_test_cases[$i]->run($reporter); + } + } + $reporter->paintGroupEnd($this->getLabel()); + return $reporter->getStatus(); + } + + /** + * Number of contained test cases. + * @return integer Total count of cases in the group. + * @access public + */ + function getSize() { + $count = 0; + foreach ($this->_test_cases as $case) { + if (is_string($case)) { + $count++; + } else { + $count += $case->getSize(); + } + } + return $count; + } + } + + /** + * @package SimpleTest + * @subpackage UnitTester + * @deprecated + */ + class GroupTest extends TestSuite { } + + /** + * This is a failing group test for when a test suite hasn't + * loaded properly. + * @package SimpleTest + * @subpackage UnitTester + */ + class BadTestSuite { + var $_label; + var $_error; + + /** + * Sets the name of the test suite and error message. + * @param string $label Name sent at the start and end + * of the test. + * @access public + */ + function BadTestSuite($label, $error) { + $this->_label = $label; + $this->_error = $error; + } + + /** + * Accessor for the test name for subclasses. + * @return string Name of the test. + * @access public + */ + function getLabel() { + return $this->_label; + } + + /** + * Sends a single error to the reporter. + * @param SimpleReporter $reporter Current test reporter. + * @access public + */ + function run(&$reporter) { + $reporter->paintGroupStart($this->getLabel(), $this->getSize()); + $reporter->paintFail('Bad TestSuite [' . $this->getLabel() . + '] with error [' . $this->_error . ']'); + $reporter->paintGroupEnd($this->getLabel()); + return $reporter->getStatus(); + } + + /** + * Number of contained test cases. Always zero. + * @return integer Total count of cases in the group. + * @access public + */ + function getSize() { + return 0; + } + } + + /** + * @package SimpleTest + * @subpackage UnitTester + * @deprecated + */ + class BadGroupTest extends BadTestSuite { } +?> \ No newline at end of file diff --git a/tests/simpletest/ui/array_reporter.php b/tests/simpletest/ui/array_reporter.php new file mode 100644 index 00000000..57c0f42a --- /dev/null +++ b/tests/simpletest/ui/array_reporter.php @@ -0,0 +1,66 @@ +SimpleReporter(); + $this->_results = array(); + } + + function paintPass($message) { + parent::paintPass($message); + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + $test = implode("->", $breadcrumb); + + $result["time"] = time(); + $result["status"] = "Passed"; + $result["test"] = $test; + $result["message"] = $message; + $this->_results[] = $result; + } + + function paintFail($message) { + parent::paintFail($message); + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + $test = implode("->", $breadcrumb); + + $result["time"] = time(); + $result["status"] = "Failed"; + $result["test"] = $test; + $result["message"] = $message; + $this->_results[] = $result; + } + + function getStatus() { + return $this->_results; + } +} + +?> \ No newline at end of file diff --git a/tests/simpletest/ui/array_reporter/sample_test.php b/tests/simpletest/ui/array_reporter/sample_test.php new file mode 100644 index 00000000..9c0b26cf --- /dev/null +++ b/tests/simpletest/ui/array_reporter/sample_test.php @@ -0,0 +1,15 @@ +assertTrue(true); + } + + function testFalseIsTrue() { + $this->assertFalse(true); + } + + } +?> \ No newline at end of file diff --git a/tests/simpletest/ui/array_reporter/test.php b/tests/simpletest/ui/array_reporter/test.php new file mode 100644 index 00000000..b4d29365 --- /dev/null +++ b/tests/simpletest/ui/array_reporter/test.php @@ -0,0 +1,38 @@ +addTestFile(dirname(__FILE__) . '/sample_test.php'); + $result = $test->run(new ArrayReporter()); + $this->assertEqual(count($result), 2); + + $this->assertEqual(count($result[0]), 4); + $this->assertPattern("/".substr(time(), 9)."/", $result[0]['time']); + $this->assertEqual($result[0]['status'], "Passed"); + $this->assertPattern("/test\.php->SampleTestForArrayReporter->testTrueIsTrue/", $result[0]['test']); + $this->assertPattern("/ at \[.*array_reporter\/sample_test\.php line 7\]/", $result[0]['message']); + + $this->assertEqual(count($result[1]), 4); + $this->assertPattern("/".substr(time(), 9)."/", $result[1]['time']); + $this->assertEqual($result[1]['status'], "Failed"); + $this->assertPattern("/test\.php->SampleTestForArrayReporter->testFalseIsTrue/", $result[1]['test']); + $this->assertPattern("/Expected false, got \[Boolean: true\] at \[.*array_reporter\/sample_test\.php line 11\]/", $result[1]['message']); + } + } + + $test = &new GroupTest('Tests for the "array reporter"'); + $test->addTestClass('TestOfArrayReporter'); + if (SimpleReporter::inCli()) { + $result = $test->run(new TextReporter()); + return ($result ? 0 : 1); + } + $test->run(new HtmlReporter()); + +?> \ No newline at end of file diff --git a/tests/simpletest/ui/colortext_reporter.php b/tests/simpletest/ui/colortext_reporter.php new file mode 100644 index 00000000..51de860b --- /dev/null +++ b/tests/simpletest/ui/colortext_reporter.php @@ -0,0 +1,86 @@ + + * @package SimpleTest + * @subpackage UnitTester + */ +class ColorTextReporter extends TextReporter { + var $_failColor = 41; + var $_passColor = 42; + + /** + * Handle initialization + * + * @param {@link TextReporter} + */ + function ColorTextReporter() { + parent::TextReporter(); + } + + /** + * Capture the attempt to display the final test results and insert the + * ANSI-color codes in place. + * + * @param string + * @see TextReporter + * @access public + */ + function paintFooter($test_name) { + ob_start(); + parent::paintFooter($test_name); + $output = trim(ob_get_clean()); + if ($output) { + if (($this->getFailCount() + $this->getExceptionCount()) == 0) { + $color = $this->_passColor; + } else { + $color = $this->_failColor; + } + + $this->_setColor($color); + echo $output; + $this->_resetColor(); + } + } + + + /** + * Sets the terminal to an ANSI-standard $color + * + * @param int + * @access protected + */ + function _setColor($color) { + printf("%s[%sm\n", chr(27), $color); + } + + + /** + * Resets the color back to normal. + * + * @access protected + */ + function _resetColor() { + $this->_setColor(0); + } +} + diff --git a/tests/simpletest/ui/css/webunit.css b/tests/simpletest/ui/css/webunit.css new file mode 100644 index 00000000..49da468f --- /dev/null +++ b/tests/simpletest/ui/css/webunit.css @@ -0,0 +1,78 @@ +html { + font-face: Verdana, Arial, Helvetica, sans-serif; + font-weight: bold; + color: black; + } + +.pass { color: green; } +.fail { color: red; } +.activetab { + position: relative; + background: white; + border-color: black; + border-style: solid; + border-weight: 1; + border-top-color: white; + border-style: solid; + border-weight: 1; +} +.inactivetab{ + position: relative; + background: silver; + border-color: black; + border-style: solid; + border-weight: 1; +} +span.inactivetab a:link , +span.activetab a:link { + text-decoration: none; + color: black; +} +pre { background-color: lightgray; } +#wait { + background: #B7B8DD; + position: absolute; + visibility: hidden; + text-align: center; + border-color: blue; + border-style: solid; + border-weight: 2; + } +#webunit { + position: absolute; + visibility: hidden; + background: silver; + border-color: black; + border-style: solid; + border-weight: 2; + } +#visible_tab { + position: relative; + visibility: hidden; + overflow: auto; + background: white; + width: 100%; + height: 100%; + border-color: black; + border-style: solid; + border-weight: 1; + } +#visible_tab a:link { + text-decoration: none; + color: inherit; +} +#msg { + position: absolute; + visibility: hidden; + overflow: auto; + background: white; + border-color: black; + border-style: solid; + border-weight: 1; + } +#fail, +#tree { + position: absolute; + visibility: hidden; +} + diff --git a/tests/simpletest/ui/img/wait.gif b/tests/simpletest/ui/img/wait.gif new file mode 100644 index 0000000000000000000000000000000000000000..9e8f1090259b2d6bc90e05db42af5baef9e148ea GIT binary patch literal 1426 zcmZ?wbhEHbJi#Esa8-^$*1lfOu1?XmR>7`L*|tX2wpz`mO2xKD$EsZ4vP{paOw+nj z%eq3trpnqh-^wiC)+E=|yvW?V(9FEZ*rM3Lvc$-u#KfZ5!mJ=#J2p}$E?z4-Rx8F| zKZSvT!NDZQ)hN@;FwNH>)x#(wNG~ZsKP6N*Awe@r+P*=?zJbA^fyKR-&8>&uxt-Is zo5QV}+qIL+wTs84gU_Wyz`0Gxsa4FeS=6yb#HmHnp;5x2Ny?#df}C5MqWAy*|AAI0 z{^#~{4GDI33~)8lGhk)}3H@YY|HP7_lQ~xNFRUo> zS{t?g#+tI(v1=pNOxI?cd@^mV*xInecXP~Q^V+=_nHn1#3N$2mc)59aI5@aCMMcF# zw0iscCrq3)dCJsj(`U?_HG8_NcFcl>ixw~O(wet)<*LDF_Zp}@%8#?B|>(C}fQQU||+ zMdqCo8y6q<`QX$g<5}b_faG||jv2A~L=pTktB&o3MX`rKz}2?xmMFGWtj4ci*D z{swng-}&oBLTBq%O?85Ym*?;@y_g(be738{07{-x0|Q zX$EEnaRxr16%ueOkOMa&TL2LgMx-eABt>xoDT>QUQQSw0;-#c0-UC$32@W~|)Sx@2 zfCw@cBonbEUX<_!MTQ>OL?v7){q)n*WcWCq9A>X|P*84CR8(q{RaNOy>rs>Hmz0!|kycli17+$tbLY(mWokL? zCCgWUGWFWEb{jSVGqv5abvt$fGxg%F`?qf2d-%xFWAhK3+-P(B?78zhPMxy7aP`{t zxtC7fxO4aXtpoQSJ>K(R|C1LlS3TSM>fQSjZ#IAU^7Yf_uRmXX-}LL>lRrs+rElme P=rnPxmHZ;e!e9*mI_nZT literal 0 HcmV?d00001 diff --git a/tests/simpletest/ui/js/tests/TestOfWebunit.js.html b/tests/simpletest/ui/js/tests/TestOfWebunit.js.html new file mode 100644 index 00000000..08f62491 --- /dev/null +++ b/tests/simpletest/ui/js/tests/TestOfWebunit.js.html @@ -0,0 +1,34 @@ + + + +JsUnit Tests of webunit.js + + + + + + + + +

    JsUnit Tests of webunit.js

    + +

    This page contains tests for the webunit.js file functions.

    +
    +
    + + \ No newline at end of file diff --git a/tests/simpletest/ui/js/webunit.js b/tests/simpletest/ui/js/webunit.js new file mode 100644 index 00000000..62c588c7 --- /dev/null +++ b/tests/simpletest/ui/js/webunit.js @@ -0,0 +1,194 @@ +// jsreporter.js +// Script to support JsReporter class +// Relies heavily on the X library in x.js +// X v3.14.1, Cross-Browser DHTML Library from Cross-Browser.com +// Copyright (c) 2004 Jason E. Sweat (jsweat_php@yahoo.com) +// +// SimpleTest - http://simpletest.sf.net/ +// Copyright (c) 2003,2004 Marcus Baker (marcus@lastcraft.com) +// $Id: webunit.js,v 1.10 2004/02/14 18:24:13 jsweat Exp $ + + +// Variables: +min_x=500; +min_y=400; +groups = new Array(); +cases = new Array(); +methods = new Array(); +current_group=0; +current_case=0; +current_method=0; + +Hash = { + Set : function(foo,bar) {this[foo] = bar;}, + Get : function(foo) {return this[foo];} +} + +// Functions: +function wait_start() { + var wait_x; + var wait_y; + + wait_x = xWidth('wait'); + wait_y = xHeight('wait'); + xMoveTo('wait', (xClientWidth()-wait_x)/2, (xClientHeight()-wait_y)/2); + xShow('wait'); +} + +function layout() { + xResizeTo('webunit', max(xClientWidth()-30,min_x), max(xClientHeight()-20,min_y)); + xMoveTo('webunit', 5, 5); + xResizeTo('tabs', xWidth('webunit')-10, xHeight('webunit')/3); + xLeft('tabs', 5); + xShow('webunit'); + xShow('tabs'); + activate_tab('fail'); + xShow('visible_tab'); + xZIndex('visible_tab', 2) + xResizeTo('msg', xWidth('webunit')-17, xHeight('webunit')/3-20); + xLeft('msg', 2); + xTop('msg',2*xHeight('webunit')/3); + xShow('msg'); +} + +function set_div_content(div, content) { + xGetElementById(div).innerHTML = content; +} + +function copy_div_content(divsrc, divtrgt) { + xGetElementById(divtrgt).innerHTML = xGetElementById(divsrc).innerHTML; +} + +function activate_tab(tab) { + if (tab == 'fail') { + copy_div_content('fail', 'visible_tab'); + xGetElementById('failtab').className = 'activetab'; + xZIndex('failtab', 3) + xGetElementById('treetab').className = 'inactivetab'; + xZIndex('treetab', 1) + } + if (tab == 'tree') { + copy_div_content('tree', 'visible_tab'); + xGetElementById('failtab').className = 'inactivetab'; + xZIndex('failtab', 1) + xGetElementById('treetab').className = 'activetab'; + xZIndex('treetab', 3) + } +} + +function add_group(group_name) { + var add; + + add = { + Set : function(foo,bar) {this[foo] = bar;}, + Get : function(foo) {return this[foo];} + } + add.Set('desc', group_name); + add.Set('pass', true); + groups[groups.length] = add; + current_group = groups.length - 1; + cases[current_group] = new Array(); + methods[current_group] = new Array(); +} + +function add_case(case_name) { + var curgroup; + var add; + + add = { + Set : function(foo,bar) {this[foo] = bar;}, + Get : function(foo) {return this[foo];} + } + add.Set('desc', case_name); + add.Set('pass', true); + curgroup = cases[current_group]; + cases[current_group][curgroup.length] = add; + current_case = curgroup.length - 1; + methods[current_group][current_case] = new Array(); +} + +function add_method(method_name) { + var curcase; + var add; + + add = { + Set : function(foo,bar) {this[foo] = bar;}, + Get : function(foo) {return this[foo];} + } + add.Set('desc', method_name); + add.Set('pass', true); + add.Set('msg',''); + curcase = methods[current_group][current_case]; + methods[current_group][current_case][curcase.length] = add; + current_method = curcase.length - 1; +} + +function add_fail(msg) { + var oldmsg; + add_log(msg); + groups[current_group].Set('pass', false); + cases[current_group][current_case].Set('pass', false); + methods[current_group][current_case][current_method].Set('pass', false); + oldmsg = methods[current_group][current_case][current_method].Get('msg'); + methods[current_group][current_case][current_method].Set('msg', oldmsg+msg); +} + +function add_log(msg) { + var faildiv; + faildiv = xGetElementById('fail'); + faildiv.innerHTML = faildiv.innerHTML + msg; +} + +function set_msg(gid, cid, mid) { + var passfail; + var msg=methods[gid][cid][mid].Get('msg'); + if ('' == msg) { + passfail = (methods[gid][cid][mid].Get('pass')) ? 'pass' : 'fail'; + msg = 'No output for ' + + groups[gid].Get('desc') + '->' + + cases[gid][cid].Get('desc') + '->' + + methods[gid][cid][mid].Get('desc') + '
    '; + } + xGetElementById('msg').innerHTML = msg; +} + +function make_tree() { + var content; + var passfail; + content = '
      '; + for (x in groups) { + passfail = (groups[x].Get('pass')) ? 'pass' : 'fail'; + content += '
    • '+groups[x].Get('desc')+'
        '; + for (y in cases[x]) { + passfail = (cases[x][y].Get('pass')) ? 'pass' : 'fail'; + content += '
      • '+cases[x][y].Get('desc')+'
          '; + for (z in methods[x][y]) { + passfail = (methods[x][y][z].Get('pass')) ? 'pass' : 'fail'; + content += '
        • '+methods[x][y][z].Get('desc')+'
        • '; + } + content += '
      • '; + } + content += '
    • '; + } + content += '
    '; + xGetElementById('tree').innerHTML = content; + if (xGetElementById('treetab').className == 'activetab') { + activate_tab('tree'); + } else { + activate_tab('fail'); + } +} + +function make_output(data) { +} + +function make_fail_msg(id, msg) { +} + +function max(n1, n2) { + if (n1 > n2) { + return n1; + } else { + return n2; + } +} diff --git a/tests/simpletest/ui/js/x.js b/tests/simpletest/ui/js/x.js new file mode 100644 index 00000000..53604bed --- /dev/null +++ b/tests/simpletest/ui/js/x.js @@ -0,0 +1,423 @@ +// x.js +// X v3.14.1, Cross-Browser DHTML Library from Cross-Browser.com +// Copyright (c) 2002,2003 Michael Foster (mike@cross-browser.com) +// This library is distributed under the terms of the LGPL (gnu.org) + +// Variables: +var xVersion='3.14.1',xOp7=false,xOp5or6=false,xIE4Up=false,xNN4=false,xUA=navigator.userAgent.toLowerCase(); +if(window.opera){ + xOp7=(xUA.indexOf('opera 7')!=-1 || xUA.indexOf('opera/7')!=-1); + if (!xOp7) xOp5or6=(xUA.indexOf('opera 5')!=-1 || xUA.indexOf('opera/5')!=-1 || xUA.indexOf('opera 6')!=-1 || xUA.indexOf('opera/6')!=-1); +} +else if(document.layers) {xNN4=true;} +else {xIE4Up=document.all && xUA.indexOf('msie')!=-1 && parseInt(navigator.appVersion)>=4;} +// Object: +function xGetElementById(e) { + if(typeof(e)!='string') return e; + if(document.getElementById) e=document.getElementById(e); + else if(document.all) e=document.all[e]; + else if(document.layers) e=xLayer(e); + else e=null; + return e; +} +function xParent(e,bNode){ + if (!(e=xGetElementById(e))) return null; + var p=null; + if (!bNode && xDef(e.offsetParent)) p=e.offsetParent; + else if (xDef(e.parentNode)) p=e.parentNode; + else if (xDef(e.parentElement)) p=e.parentElement; + else if (xDef(e.parentLayer)){if (e.parentLayer!=window) p=e.parentLayer;} + return p; +} +function xDef() { + for(var i=0; iwindow.innerHeight) w-=16; + } + return w; +} +function xClientHeight() { + var h=0; + if(xOp5or6) h=window.innerHeight; + else if(!window.opera && document.documentElement && document.documentElement.clientHeight) // v3.12 + h=document.documentElement.clientHeight; + else if(document.body && document.body.clientHeight) + h=document.body.clientHeight; + else if(xDef(window.innerWidth,window.innerHeight,document.width)) { + h=window.innerHeight; + if(document.width>window.innerWidth) h-=16; + } + return h; +} +// Animation: +function xSlideTo(e,x,y,uTime) { + if (!(e=xGetElementById(e))) return; + if (!e.timeout) e.timeout = 25; + e.xTarget = x; e.yTarget = y; e.slideTime = uTime; e.stop = false; + e.yA = e.yTarget - xTop(e); e.xA = e.xTarget - xLeft(e); // A = distance + e.B = Math.PI / (2 * e.slideTime); // B = period + e.yD = xTop(e); e.xD = xLeft(e); // D = initial position + var d = new Date(); e.C = d.getTime(); + if (!e.moving) xSlide(e); +} +function xSlide(e) { + if (!(e=xGetElementById(e))) return; + var now, s, t, newY, newX; + now = new Date(); + t = now.getTime() - e.C; + if (e.stop) { e.moving = false; } + else if (t < e.slideTime) { + setTimeout("xSlide('"+e.id+"')", e.timeout); + s = Math.sin(e.B * t); + newX = Math.round(e.xA * s + e.xD); + newY = Math.round(e.yA * s + e.yD); + xMoveTo(e, newX, newY); + e.moving = true; + } + else { + xMoveTo(e, e.xTarget, e.yTarget); + e.moving = false; + } +} +// Event: +function xAddEventListener(e,eventType,eventListener,useCapture) { + if(!(e=xGetElementById(e))) return; + eventType=eventType.toLowerCase(); + if((!xIE4Up && !xOp7) && e==window) { + if(eventType=='resize') { window.xPCW=xClientWidth(); window.xPCH=xClientHeight(); window.xREL=eventListener; xResizeEvent(); return; } + if(eventType=='scroll') { window.xPSL=xScrollLeft(); window.xPST=xScrollTop(); window.xSEL=eventListener; xScrollEvent(); return; } + } + var eh='e.on'+eventType+'=eventListener'; + if(e.addEventListener) e.addEventListener(eventType,eventListener,useCapture); + else if(e.attachEvent) e.attachEvent('on'+eventType,eventListener); + else if(e.captureEvents) { + if(useCapture||(eventType.indexOf('mousemove')!=-1)) { e.captureEvents(eval('Event.'+eventType.toUpperCase())); } + eval(eh); + } + else eval(eh); +} +function xRemoveEventListener(e,eventType,eventListener,useCapture) { + if(!(e=xGetElementById(e))) return; + eventType=eventType.toLowerCase(); + if((!xIE4Up && !xOp7) && e==window) { + if(eventType=='resize') { window.xREL=null; return; } + if(eventType=='scroll') { window.xSEL=null; return; } + } + var eh='e.on'+eventType+'=null'; + if(e.removeEventListener) e.removeEventListener(eventType,eventListener,useCapture); + else if(e.detachEvent) e.detachEvent('on'+eventType,eventListener); + else if(e.releaseEvents) { + if(useCapture||(eventType.indexOf('mousemove')!=-1)) { e.releaseEvents(eval('Event.'+eventType.toUpperCase())); } + eval(eh); + } + else eval(eh); +} +function xEvent(evt) { // cross-browser event object prototype + this.type = ''; + this.target = null; + this.pageX = 0; + this.pageY = 0; + this.offsetX = 0; + this.offsetY = 0; + this.keyCode = 0; + var e = evt ? evt : window.event; + if(!e) return; + if(e.type) this.type = e.type; + if(e.target) this.target = e.target; + else if(e.srcElement) this.target = e.srcElement; + else if(xNN4) this.target = xLayerFromPoint(e.pageX, e.pageY); + if(xOp5or6) { this.pageX = e.clientX; this.pageY = e.clientY; } + else if(xDef(e.pageX,e.pageY)) { this.pageX = e.pageX; this.pageY = e.pageY; } // v3.14 + else if(xDef(e.clientX,e.clientY)) { this.pageX = e.clientX + xScrollLeft(); this.pageY = e.clientY + xScrollTop(); } + if(xDef(e.offsetX,e.offsetY)) { this.offsetX = e.offsetX; this.offsetY = e.offsetY; } + else if(xDef(e.layerX,e.layerY)) { this.offsetX = e.layerX; this.offsetY = e.layerY; } + else { this.offsetX = this.pageX - xPageX(this.target); this.offsetY = this.pageY - xPageY(this.target); } + if (e.keyCode) { this.keyCode = e.keyCode; } // for moz/fb, if keyCode==0 use which + else if (xDef(e.which)) { this.keyCode = e.which; } +} +function xResizeEvent() { // window resize event simulation + if (window.xREL) setTimeout('xResizeEvent()', 250); + var cw = xClientWidth(), ch = xClientHeight(); + if (window.xPCW != cw || window.xPCH != ch) { window.xPCW = cw; window.xPCH = ch; if (window.xREL) window.xREL(); } +} +function xScrollEvent() { // window scroll event simulation + if (window.xSEL) setTimeout('xScrollEvent()', 250); + var sl = xScrollLeft(), st = xScrollTop(); + if (window.xPSL != sl || window.xPST != st) { window.xPSL = sl; window.xPST = st; if (window.xSEL) window.xSEL(); } +} +// end x.js diff --git a/tests/simpletest/ui/webunit_reporter.php b/tests/simpletest/ui/webunit_reporter.php new file mode 100644 index 00000000..61e3024d --- /dev/null +++ b/tests/simpletest/ui/webunit_reporter.php @@ -0,0 +1,286 @@ + + +%s + + + + + + +
    +

     Running %s 

    + Please wait...
    +
      +
    + +
    +

    +
    +
    visible tab content
    +     Fail   +   Tree   +
    +
    Click on a failed test case method in the tree tab to view output here.
    +
    +
    +
    + +'.$this->outputScript("xHide('wait');"); + $colour = ($this->getFailCount() + $this->getExceptionCount() > 0 ? "red" : "green"); + $content = "

    $test_name

    \n"; + $content .= "
    "; + $content .= $this->getTestCaseProgress() . "/" . $this->getTestCaseCount(); + $content .= " test cases complete:\n"; + $content .= "" . $this->getPassCount() . " passes, "; + $content .= "" . $this->getFailCount() . " fails and "; + $content .= "" . $this->getExceptionCount() . " exceptions."; + $content .= "
    \n"; + + echo $this->outputScript('foo = "'.$this->toJsString($content).'";'."\nset_div_content('run', foo);"); + echo "\n\n\n"; + } + + + /** + * Paints formatted text such as dumped variables. + * @param string $message Text to show. + * @access public + */ + function paintFormattedMessage($message) { + echo "add_log(\"".$this->toJsString("
    $message
    ", true)."\");\n"; + } + + /** + * Paints the start of a group test. Will also paint + * the page header and footer if this is the + * first test. Will stash the size if the first + * start. + * @param string $test_name Name of test that is starting. + * @param integer $size Number of test cases starting. + * @access public + */ + function paintGroupStart($test_name, $size) { + Parent::paintGroupStart($test_name, $size); + echo "add_group('$test_name');\n"; + } + + /** + * Paints the start of a test case. Will also paint + * the page header and footer if this is the + * first test. Will stash the size if the first + * start. + * @param string $test_name Name of test that is starting. + * @access public + */ + function paintCaseStart($test_name) { + Parent::paintCaseStart($test_name); + echo "add_case('$test_name');\n"; + } + + + /** + * Paints the start of a test method. + * @param string $test_name Name of test that is starting. + * @access public + */ + function paintMethodStart($test_name) { + Parent::paintMethodStart($test_name); + echo "add_method('$test_name');\n"; + } + + /** + * Paints the end of a test method. + * @param string $test_name Name of test that is ending. + * @access public + */ + function paintMethodEnd($test_name) { + Parent::paintMethodEnd($test_name); + } + + /** + * Paints the test failure with a breadcrumbs + * trail of the nesting test suites below the + * top level test. + * @param string $message Failure message displayed in + * the context of the other tests. + * @access public + */ + function paintFail($message) { + parent::paintFail($message); + $msg = "Fail: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + $msg .= implode("->", $breadcrumb); + $msg .= "->" . htmlentities($message) . "
    "; + echo "add_fail('$msg');\n"; + } + + /** + * Paints a PHP error or exception. + * @param string $message Message is ignored. + * @access public + * @abstract + */ + function paintException($message) { + parent::paintException($message); + $msg = "Exception: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + $msg .= implode("->", $breadcrumb); + $msg .= "->" . htmlentities($message) . "
    "; + echo "add_fail('$msg');\n"; + } + + /** + * Returns the script passed in wrapped in script tags. + * + * @param string $script the script to output + * @return string the script wrapped with script tags + */ + function outputScript($script) + { + return "\n"; + } + + + /** + * Transform a string into a format acceptable to JavaScript + * @param string $str the string to transform + * @return string + */ + function toJsString($str, $preserveCr=false) { + $cr = ($preserveCr) ? '\\n' : ''; + return str_replace( + array('"' + ,"\n") + ,array('\"' + ,"$cr\"\n\t+\"") + ,$str + ); + } + } + +?> \ No newline at end of file diff --git a/tests/simpletest/unit_tester.php b/tests/simpletest/unit_tester.php new file mode 100644 index 00000000..5e06b8c6 --- /dev/null +++ b/tests/simpletest/unit_tester.php @@ -0,0 +1,419 @@ +SimpleTestCase($label); + } + + /** + * Called from within the test methods to register + * passes and failures. + * @param boolean $result Pass on true. + * @param string $message Message to display describing + * the test state. + * @return boolean True on pass + * @access public + */ + function assertTrue($result, $message = false) { + return $this->assert(new TrueExpectation(), $result, $message); + } + + /** + * Will be true on false and vice versa. False + * is the PHP definition of false, so that null, + * empty strings, zero and an empty array all count + * as false. + * @param boolean $result Pass on false. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertFalse($result, $message = '%s') { + return $this->assert(new FalseExpectation(), $result, $message); + } + + /** + * Will be true if the value is null. + * @param null $value Supposedly null value. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertNull($value, $message = '%s') { + $dumper = &new SimpleDumper(); + $message = sprintf( + $message, + '[' . $dumper->describeValue($value) . '] should be null'); + return $this->assertTrue(! isset($value), $message); + } + + /** + * Will be true if the value is set. + * @param mixed $value Supposedly set value. + * @param string $message Message to display. + * @return boolean True on pass. + * @access public + */ + function assertNotNull($value, $message = '%s') { + $dumper = &new SimpleDumper(); + $message = sprintf( + $message, + '[' . $dumper->describeValue($value) . '] should not be null'); + return $this->assertTrue(isset($value), $message); + } + + /** + * Type and class test. Will pass if class + * matches the type name or is a subclass or + * if not an object, but the type is correct. + * @param mixed $object Object to test. + * @param string $type Type name as string. + * @param string $message Message to display. + * @return boolean True on pass. + * @access public + */ + function assertIsA($object, $type, $message = '%s') { + return $this->assert( + new IsAExpectation($type), + $object, + $message); + } + + /** + * Type and class mismatch test. Will pass if class + * name or underling type does not match the one + * specified. + * @param mixed $object Object to test. + * @param string $type Type name as string. + * @param string $message Message to display. + * @return boolean True on pass. + * @access public + */ + function assertNotA($object, $type, $message = '%s') { + return $this->assert( + new NotAExpectation($type), + $object, + $message); + } + + /** + * Will trigger a pass if the two parameters have + * the same value only. Otherwise a fail. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertEqual($first, $second, $message = '%s') { + return $this->assert( + new EqualExpectation($first), + $second, + $message); + } + + /** + * Will trigger a pass if the two parameters have + * a different value. Otherwise a fail. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertNotEqual($first, $second, $message = '%s') { + return $this->assert( + new NotEqualExpectation($first), + $second, + $message); + } + + /** + * Will trigger a pass if the if the first parameter + * is near enough to the second by the margin. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param mixed $margin Fuzziness of match. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertWithinMargin($first, $second, $margin, $message = '%s') { + return $this->assert( + new WithinMarginExpectation($first, $margin), + $second, + $message); + } + + /** + * Will trigger a pass if the two parameters differ + * by more than the margin. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param mixed $margin Fuzziness of match. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertOutsideMargin($first, $second, $margin, $message = '%s') { + return $this->assert( + new OutsideMarginExpectation($first, $margin), + $second, + $message); + } + + /** + * Will trigger a pass if the two parameters have + * the same value and same type. Otherwise a fail. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertIdentical($first, $second, $message = '%s') { + return $this->assert( + new IdenticalExpectation($first), + $second, + $message); + } + + /** + * Will trigger a pass if the two parameters have + * the different value or different type. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertNotIdentical($first, $second, $message = '%s') { + return $this->assert( + new NotIdenticalExpectation($first), + $second, + $message); + } + + /** + * Will trigger a pass if both parameters refer + * to the same object. Fail otherwise. + * @param mixed $first Object reference to check. + * @param mixed $second Hopefully the same object. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertReference(&$first, &$second, $message = '%s') { + $dumper = &new SimpleDumper(); + $message = sprintf( + $message, + '[' . $dumper->describeValue($first) . + '] and [' . $dumper->describeValue($second) . + '] should reference the same object'); + return $this->assertTrue( + SimpleTestCompatibility::isReference($first, $second), + $message); + } + + /** + * Will trigger a pass if both parameters refer + * to 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( + $message, + "[" . $dumper->describeValue($first) . + "] and [" . $dumper->describeValue($second) . + "] should not be the same object"); + return $this->assertFalse( + SimpleTestCompatibility::isReference($first, $second), + $message); + } + + /** + * Will trigger a pass if the Perl regex pattern + * is found in the subject. Fail otherwise. + * @param string $pattern Perl regex to look for including + * the regex delimiters. + * @param string $subject String to search in. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertPattern($pattern, $subject, $message = '%s') { + return $this->assert( + new PatternExpectation($pattern), + $subject, + $message); + } + + /** + * @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. + * @param string $pattern Perl regex to look for including + * the regex delimiters. + * @param string $subject String to search in. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertNoPattern($pattern, $subject, $message = '%s') { + return $this->assert( + new NoPatternExpectation($pattern), + $subject, + $message); + } + + /** + * @deprecated + */ + function assertNoUnwantedPattern($pattern, $subject, $message = '%s') { + return $this->assertNoPattern($pattern, $subject, $message); + } + + /** + * @deprecated + */ + function swallowErrors() { + $context = &SimpleTest::getContext(); + $queue = &$context->get('SimpleErrorQueue'); + $queue->clear(); + } + + /** + * @deprecated + */ + function assertNoErrors($message = '%s') { + $context = &SimpleTest::getContext(); + $queue = &$context->get('SimpleErrorQueue'); + return $queue->assertNoErrors($message); + } + + /** + * @deprecated + */ + function assertError($expected = false, $message = '%s') { + $context = &SimpleTest::getContext(); + $queue = &$context->get('SimpleErrorQueue'); + return $queue->assertError($this->_coerceExpectation($expected), $message); + } + + /** + * Prepares for an error. If the error mismatches it + * passes through, otherwise it is swallowed. Any + * left over errors trigger failures. + * @param SimpleExpectation/string $expected The error to match. + * @param string $message Message on failure. + * @access public + */ + function expectError($expected = false, $message = '%s') { + $context = &SimpleTest::getContext(); + $queue = &$context->get('SimpleErrorQueue'); + $queue->expectError($this->_coerceExpectation($expected), $message); + } + + /** + * Prepares for an exception. If the error mismatches it + * passes through, otherwise it is swallowed. Any + * left over errors trigger failures. + * @param SimpleExpectation/Exception $expected The error to match. + * @param string $message Message on failure. + * @access public + */ + function expectException($expected = false, $message = '%s') { + $context = &SimpleTest::getContext(); + $queue = &$context->get('SimpleExceptionTrap'); + $queue->expectException($expected, $message . $this->getAssertionLine()); + } + + /** + * 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 _coerceExpectation($expected) { + if ($expected == false) { + return new AnythingExpectation(); + } + if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) { + return $expected; + } + if(is_string($expected)) { + $expected = str_replace('%', '%%', $expected); + } + return new EqualExpectation($expected); + } + + /** + * @deprecated + */ + function assertErrorPattern($pattern, $message = '%s') { + return $this->assertError(new PatternExpectation($pattern), $message); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/url.php b/tests/simpletest/url.php new file mode 100644 index 00000000..532e8afb --- /dev/null +++ b/tests/simpletest/url.php @@ -0,0 +1,525 @@ +_chompCoordinates($url); + $this->setCoordinates($x, $y); + $this->_scheme = $this->_chompScheme($url); + list($this->_username, $this->_password) = $this->_chompLogin($url); + $this->_host = $this->_chompHost($url); + $this->_port = false; + if (preg_match('/(.*?):(.*)/', $this->_host, $host_parts)) { + $this->_host = $host_parts[1]; + $this->_port = (integer)$host_parts[2]; + } + $this->_path = $this->_chompPath($url); + $this->_request = $this->_parseRequest($this->_chompRequest($url)); + $this->_fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false); + $this->_target = false; + } + + /** + * Extracts the X, Y coordinate pair from an image map. + * @param string $url URL so far. The coordinates will be + * removed. + * @return array X, Y as a pair of integers. + * @access private + */ + function _chompCoordinates(&$url) { + if (preg_match('/(.*)\?(\d+),(\d+)$/', $url, $matches)) { + $url = $matches[1]; + return array((integer)$matches[2], (integer)$matches[3]); + } + return array(false, false); + } + + /** + * Extracts the scheme part of an incoming URL. + * @param string $url URL so far. The scheme will be + * removed. + * @return string Scheme part or false. + * @access private + */ + function _chompScheme(&$url) { + if (preg_match('/(.*?):(\/\/)(.*)/', $url, $matches)) { + $url = $matches[2] . $matches[3]; + return $matches[1]; + } + return false; + } + + /** + * Extracts the username and password from the + * incoming URL. The // prefix will be reattached + * to the URL after the doublet is extracted. + * @param string $url URL so far. The username and + * password are removed. + * @return array Two item list of username and + * password. Will urldecode() them. + * @access private + */ + function _chompLogin(&$url) { + $prefix = ''; + if (preg_match('/^(\/\/)(.*)/', $url, $matches)) { + $prefix = $matches[1]; + $url = $matches[2]; + } + if (preg_match('/(.*?)@(.*)/', $url, $matches)) { + $url = $prefix . $matches[2]; + $parts = split(":", $matches[1]); + return array( + urldecode($parts[0]), + isset($parts[1]) ? urldecode($parts[1]) : false); + } + $url = $prefix . $url; + return array(false, false); + } + + /** + * Extracts the host part of an incoming URL. + * Includes the port number part. Will extract + * the host if it starts with // or it has + * a top level domain or it has at least two + * dots. + * @param string $url URL so far. The host will be + * removed. + * @return string Host part guess or false. + * @access private + */ + function _chompHost(&$url) { + if (preg_match('/^(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) { + $url = $matches[3]; + return $matches[2]; + } + if (preg_match('/(.*?)(\.\.\/|\.\/|\/|\?|#|$)(.*)/', $url, $matches)) { + $tlds = SimpleUrl::getAllTopLevelDomains(); + if (preg_match('/[a-z0-9\-]+\.(' . $tlds . ')/i', $matches[1])) { + $url = $matches[2] . $matches[3]; + return $matches[1]; + } elseif (preg_match('/[a-z0-9\-]+\.[a-z0-9\-]+\.[a-z0-9\-]+/i', $matches[1])) { + $url = $matches[2] . $matches[3]; + return $matches[1]; + } + } + return false; + } + + /** + * Extracts the path information from the incoming + * URL. Strips this path from the URL. + * @param string $url URL so far. The host will be + * removed. + * @return string Path part or '/'. + * @access private + */ + function _chompPath(&$url) { + if (preg_match('/(.*?)(\?|#|$)(.*)/', $url, $matches)) { + $url = $matches[2] . $matches[3]; + return ($matches[1] ? $matches[1] : ''); + } + return ''; + } + + /** + * Strips off the request data. + * @param string $url URL so far. The request will be + * removed. + * @return string Raw request part. + * @access private + */ + function _chompRequest(&$url) { + if (preg_match('/\?(.*?)(#|$)(.*)/', $url, $matches)) { + $url = $matches[2] . $matches[3]; + return $matches[1]; + } + return ''; + } + + /** + * Breaks the request down into an object. + * @param string $raw Raw request. + * @return SimpleFormEncoding Parsed data. + * @access private + */ + function _parseRequest($raw) { + $this->_raw = $raw; + $request = new SimpleGetEncoding(); + foreach (split("&", $raw) as $pair) { + if (preg_match('/(.*?)=(.*)/', $pair, $matches)) { + $request->add($matches[1], urldecode($matches[2])); + } elseif ($pair) { + $request->add($pair, ''); + } + } + return $request; + } + + /** + * Accessor for protocol part. + * @param string $default Value to use if not present. + * @return string Scheme name, e.g "http". + * @access public + */ + function getScheme($default = false) { + return $this->_scheme ? $this->_scheme : $default; + } + + /** + * Accessor for user name. + * @return string Username preceding host. + * @access public + */ + function getUsername() { + return $this->_username; + } + + /** + * Accessor for password. + * @return string Password preceding host. + * @access public + */ + function getPassword() { + return $this->_password; + } + + /** + * Accessor for hostname and port. + * @param string $default Value to use if not present. + * @return string Hostname only. + * @access public + */ + function getHost($default = false) { + return $this->_host ? $this->_host : $default; + } + + /** + * Accessor for top level domain. + * @return string Last part of host. + * @access public + */ + function getTld() { + $path_parts = pathinfo($this->getHost()); + return (isset($path_parts['extension']) ? $path_parts['extension'] : false); + } + + /** + * Accessor for port number. + * @return integer TCP/IP port number. + * @access public + */ + function getPort() { + return $this->_port; + } + + /** + * Accessor for path. + * @return string Full path including leading slash if implied. + * @access public + */ + function getPath() { + if (! $this->_path && $this->_host) { + return '/'; + } + return $this->_path; + } + + /** + * Accessor for page if any. This may be a + * directory name if ambiguious. + * @return Page name. + * @access public + */ + function getPage() { + if (! preg_match('/([^\/]*?)$/', $this->getPath(), $matches)) { + return false; + } + return $matches[1]; + } + + /** + * Gets the path to the page. + * @return string Path less the page. + * @access public + */ + function getBasePath() { + if (! preg_match('/(.*\/)[^\/]*?$/', $this->getPath(), $matches)) { + return false; + } + return $matches[1]; + } + + /** + * Accessor for fragment at end of URL after the "#". + * @return string Part after "#". + * @access public + */ + function getFragment() { + return $this->_fragment; + } + + /** + * Sets image coordinates. Set to false to clear + * them. + * @param integer $x Horizontal position. + * @param integer $y Vertical position. + * @access public + */ + function setCoordinates($x = false, $y = false) { + if (($x === false) || ($y === false)) { + $this->_x = $this->_y = false; + return; + } + $this->_x = (integer)$x; + $this->_y = (integer)$y; + } + + /** + * Accessor for horizontal image coordinate. + * @return integer X value. + * @access public + */ + function getX() { + return $this->_x; + } + + /** + * Accessor for vertical image coordinate. + * @return integer Y value. + * @access public + */ + function getY() { + return $this->_y; + } + + /** + * Accessor for current request parameters + * in URL string form. Will return teh original request + * if at all possible even if it doesn't make much + * sense. + * @return string Form is string "?a=1&b=2", etc. + * @access public + */ + function getEncodedRequest() { + if ($this->_raw) { + $encoded = $this->_raw; + } else { + $encoded = $this->_request->asUrlRequest(); + } + if ($encoded) { + return '?' . preg_replace('/^\?/', '', $encoded); + } + return ''; + } + + /** + * Adds an additional parameter to the request. + * @param string $key Name of parameter. + * @param string $value Value as string. + * @access public + */ + function addRequestParameter($key, $value) { + $this->_raw = false; + $this->_request->add($key, $value); + } + + /** + * Adds additional parameters to the request. + * @param hash/SimpleFormEncoding $parameters Additional + * parameters. + * @access public + */ + function addRequestParameters($parameters) { + $this->_raw = false; + $this->_request->merge($parameters); + } + + /** + * Clears down all parameters. + * @access public + */ + function clearRequest() { + $this->_raw = false; + $this->_request = &new SimpleGetEncoding(); + } + + /** + * Gets the frame target if present. Although + * not strictly part of the URL specification it + * acts as similarily to the browser. + * @return boolean/string Frame name or false if none. + * @access public + */ + function getTarget() { + return $this->_target; + } + + /** + * Attaches a frame target. + * @param string $frame Name of frame. + * @access public + */ + function setTarget($frame) { + $this->_raw = false; + $this->_target = $frame; + } + + /** + * Renders the URL back into a string. + * @return string URL in canonical form. + * @access public + */ + function asString() { + $scheme = $identity = $host = $path = $encoded = $fragment = ''; + if ($this->_username && $this->_password) { + $identity = $this->_username . ':' . $this->_password . '@'; + } + if ($this->getHost()) { + $scheme = $this->getScheme() ? $this->getScheme() : 'http'; + $host = $this->getHost(); + } + if (substr($this->_path, 0, 1) == '/') { + $path = $this->normalisePath($this->_path); + } + $encoded = $this->getEncodedRequest(); + $fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; + $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); + return "$scheme://$identity$host$path$encoded$fragment$coords"; + } + + /** + * Replaces unknown sections to turn a relative + * URL into an absolute one. The base URL can + * be either a string or a SimpleUrl object. + * @param string/SimpleUrl $base Base URL. + * @access public + */ + function makeAbsolute($base) { + if (! is_object($base)) { + $base = new SimpleUrl($base); + } + $scheme = $this->getScheme() ? $this->getScheme() : $base->getScheme(); + 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)); + $encoded = $this->getEncodedRequest(); + $fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; + $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); + return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords"); + } + + /** + * Replaces unknown sections of the path with base parts + * to return a complete absolute one. + * @param string/SimpleUrl $base Base URL. + * @param string Absolute path. + * @access private + */ + function _extractAbsolutePath($base) { + if ($this->getHost()) { + return $this->_path; + } + if (! $this->_isRelativePath($this->_path)) { + return $this->_path; + } + if ($this->_path) { + return $base->getBasePath() . $this->_path; + } + return $base->getPath(); + } + + /** + * Simple test to see if a path part is relative. + * @param string $path Path to test. + * @return boolean True if starts with a "/". + * @access private + */ + function _isRelativePath($path) { + return (substr($path, 0, 1) != '/'); + } + + /** + * Extracts the username and password for use in rendering + * a URL. + * @return string/boolean Form of username:password or false. + * @access public + */ + function getIdentity() { + if ($this->_username && $this->_password) { + return $this->_username . ':' . $this->_password; + } + return false; + } + + /** + * Replaces . and .. sections of the path. + * @param string $path Unoptimised path. + * @return string Path with dots removed if possible. + * @access public + */ + function normalisePath($path) { + $path = preg_replace('|/\./|', '/', $path); + return preg_replace('|/[^/]+/\.\./|', '/', $path); + } + + /** + * A pipe seperated list of all TLDs that result in two part + * domain names. + * @return string Pipe separated list. + * @access public + * @static + */ + function getAllTopLevelDomains() { + return 'com|edu|net|org|gov|mil|int|biz|info|name|pro|aero|coop|museum'; + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/user_agent.php b/tests/simpletest/user_agent.php new file mode 100644 index 00000000..da60a243 --- /dev/null +++ b/tests/simpletest/user_agent.php @@ -0,0 +1,333 @@ +_cookie_jar = &new SimpleCookieJar(); + $this->_authenticator = &new SimpleAuthenticator(); + } + + /** + * Removes expired and temporary cookies as if + * the browser was closed and re-opened. Authorisation + * has to be obtained again as well. + * @param string/integer $date Time when session restarted. + * If omitted then all persistent + * cookies are kept. + * @access public + */ + function restart($date = false) { + $this->_cookie_jar->restartSession($date); + $this->_authenticator->restartSession(); + } + + /** + * Adds a header to every fetch. + * @param string $header Header line to add to every + * request until cleared. + * @access public + */ + function addHeader($header) { + $this->_additional_headers[] = $header; + } + + /** + * Ages the cookies by the specified time. + * @param integer $interval Amount in seconds. + * @access public + */ + function ageCookies($interval) { + $this->_cookie_jar->agePrematurely($interval); + } + + /** + * Sets an additional cookie. If a cookie has + * the same name and path it is replaced. + * @param string $name Cookie key. + * @param string $value Value of cookie. + * @param string $host Host upon which the cookie is valid. + * @param string $path Cookie path if not host wide. + * @param string $expiry Expiry date. + * @access public + */ + function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { + $this->_cookie_jar->setCookie($name, $value, $host, $path, $expiry); + } + + /** + * Reads the most specific cookie value from the + * browser cookies. + * @param string $host Host to search. + * @param string $path Applicable path. + * @param string $name Name of cookie to read. + * @return string False if not present, else the + * value as a string. + * @access public + */ + function getCookieValue($host, $path, $name) { + return $this->_cookie_jar->getCookieValue($host, $path, $name); + } + + /** + * Reads the current cookies within the base URL. + * @param string $name Key of cookie to find. + * @param SimpleUrl $base Base URL to search from. + * @return string/boolean Null if there is no base URL, false + * if the cookie is not set. + * @access public + */ + function getBaseCookieValue($name, $base) { + if (! $base) { + return null; + } + return $this->getCookieValue($base->getHost(), $base->getPath(), $name); + } + + /** + * Switches off cookie sending and recieving. + * @access public + */ + function ignoreCookies() { + $this->_cookies_enabled = false; + } + + /** + * Switches back on the cookie sending and recieving. + * @access public + */ + function useCookies() { + $this->_cookies_enabled = true; + } + + /** + * Sets the socket timeout for opening a connection. + * @param integer $timeout Maximum time in seconds. + * @access public + */ + function setConnectionTimeout($timeout) { + $this->_connection_timeout = $timeout; + } + + /** + * Sets the maximum number of redirects before + * a page will be loaded anyway. + * @param integer $max Most hops allowed. + * @access public + */ + function setMaximumRedirects($max) { + $this->_max_redirects = $max; + } + + /** + * Sets proxy to use on all requests for when + * testing from behind a firewall. Set URL + * to false to disable. + * @param string $proxy Proxy URL. + * @param string $username Proxy username for authentication. + * @param string $password Proxy password for authentication. + * @access public + */ + function useProxy($proxy, $username, $password) { + if (! $proxy) { + $this->_proxy = false; + return; + } + if ((strncmp($proxy, 'http://', 7) != 0) && (strncmp($proxy, 'https://', 8) != 0)) { + $proxy = 'http://'. $proxy; + } + $this->_proxy = &new SimpleUrl($proxy); + $this->_proxy_username = $username; + $this->_proxy_password = $password; + } + + /** + * Test to see if the redirect limit is passed. + * @param integer $redirects Count so far. + * @return boolean True if over. + * @access private + */ + function _isTooManyRedirects($redirects) { + return ($redirects > $this->_max_redirects); + } + + /** + * Sets the identity for the current realm. + * @param string $host Host to which realm applies. + * @param string $realm Full name of realm. + * @param string $username Username for realm. + * @param string $password Password for realm. + * @access public + */ + function setIdentity($host, $realm, $username, $password) { + $this->_authenticator->setIdentityForRealm($host, $realm, $username, $password); + } + + /** + * Fetches a URL as a response object. Will keep trying if redirected. + * It will also collect authentication realm information. + * @param string/SimpleUrl $url Target to fetch. + * @param SimpleEncoding $encoding Additional parameters for request. + * @return SimpleHttpResponse Hopefully the target page. + * @access public + */ + function &fetchResponse($url, $encoding) { + if ($encoding->getMethod() != 'POST') { + $url->addRequestParameters($encoding); + $encoding->clear(); + } + $response = &$this->_fetchWhileRedirected($url, $encoding); + if ($headers = $response->getHeaders()) { + if ($headers->isChallenge()) { + $this->_authenticator->addRealm( + $url, + $headers->getAuthentication(), + $headers->getRealm()); + } + } + return $response; + } + + /** + * Fetches the page until no longer redirected or + * until the redirect limit runs out. + * @param SimpleUrl $url Target to fetch. + * @param SimpelFormEncoding $encoding Additional parameters for request. + * @return SimpleHttpResponse Hopefully the target page. + * @access private + */ + function &_fetchWhileRedirected($url, $encoding) { + $redirects = 0; + do { + $response = &$this->_fetch($url, $encoding); + if ($response->isError()) { + return $response; + } + $headers = $response->getHeaders(); + $location = new SimpleUrl($headers->getLocation()); + $url = $location->makeAbsolute($url); + if ($this->_cookies_enabled) { + $headers->writeCookiesToJar($this->_cookie_jar, $url); + } + if (! $headers->isRedirect()) { + break; + } + $encoding = new SimpleGetEncoding(); + } while (! $this->_isTooManyRedirects(++$redirects)); + return $response; + } + + /** + * Actually make the web request. + * @param SimpleUrl $url Target to fetch. + * @param SimpleFormEncoding $encoding Additional parameters for request. + * @return SimpleHttpResponse Headers and hopefully content. + * @access protected + */ + function &_fetch($url, $encoding) { + $request = &$this->_createRequest($url, $encoding); + $response = &$request->fetch($this->_connection_timeout); + return $response; + } + + /** + * Creates a full page request. + * @param SimpleUrl $url Target to fetch as url object. + * @param SimpleFormEncoding $encoding POST/GET parameters. + * @return SimpleHttpRequest New request. + * @access private + */ + function &_createRequest($url, $encoding) { + $request = &$this->_createHttpRequest($url, $encoding); + $this->_addAdditionalHeaders($request); + if ($this->_cookies_enabled) { + $request->readCookiesFromJar($this->_cookie_jar, $url); + } + $this->_authenticator->addHeaders($request, $url); + return $request; + } + + /** + * Builds the appropriate HTTP request object. + * @param SimpleUrl $url Target to fetch as url object. + * @param SimpleFormEncoding $parameters POST/GET parameters. + * @return SimpleHttpRequest New request object. + * @access protected + */ + function &_createHttpRequest($url, $encoding) { + $request = &new SimpleHttpRequest($this->_createRoute($url), $encoding); + return $request; + } + + /** + * Sets up either a direct route or via a proxy. + * @param SimpleUrl $url Target to fetch as url object. + * @return SimpleRoute Route to take to fetch URL. + * @access protected + */ + function &_createRoute($url) { + if ($this->_proxy) { + $route = &new SimpleProxyRoute( + $url, + $this->_proxy, + $this->_proxy_username, + $this->_proxy_password); + } else { + $route = &new SimpleRoute($url); + } + return $route; + } + + /** + * Adds additional manual headers. + * @param SimpleHttpRequest $request Outgoing request. + * @access private + */ + function _addAdditionalHeaders(&$request) { + foreach ($this->_additional_headers as $header) { + $request->addHeaderLine($header); + } + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/web_tester.php b/tests/simpletest/web_tester.php new file mode 100644 index 00000000..2e24d505 --- /dev/null +++ b/tests/simpletest/web_tester.php @@ -0,0 +1,1541 @@ +SimpleExpectation($message); + if (is_array($value)) { + sort($value); + } + $this->_value = $value; + } + + /** + * Tests the expectation. True if it matches + * a string value or an array value in any order. + * @param mixed $compare Comparison value. False for + * an unset field. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + if ($this->_value === false) { + return ($compare === false); + } + if ($this->_isSingle($this->_value)) { + return $this->_testSingle($compare); + } + if (is_array($this->_value)) { + return $this->_testMultiple($compare); + } + return false; + } + + /** + * Tests for valid field comparisons with a single option. + * @param mixed $value Value to type check. + * @return boolean True if integer, string or float. + * @access private + */ + function _isSingle($value) { + return is_string($value) || is_integer($value) || is_float($value); + } + + /** + * String comparison for simple field with a single option. + * @param mixed $compare String to test against. + * @returns boolean True if matching. + * @access private + */ + function _testSingle($compare) { + if (is_array($compare) && count($compare) == 1) { + $compare = $compare[0]; + } + if (! $this->_isSingle($compare)) { + return false; + } + return ($this->_value == $compare); + } + + /** + * List comparison for multivalue field. + * @param mixed $compare List in any order to test against. + * @returns boolean True if matching. + * @access private + */ + function _testMultiple($compare) { + if (is_string($compare)) { + $compare = array($compare); + } + if (! is_array($compare)) { + return false; + } + sort($compare); + return ($this->_value === $compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = &$this->_getDumper(); + if (is_array($compare)) { + sort($compare); + } + if ($this->test($compare)) { + return "Field expectation [" . $dumper->describeValue($this->_value) . "]"; + } else { + return "Field expectation [" . $dumper->describeValue($this->_value) . + "] fails with [" . + $dumper->describeValue($compare) . "] " . + $dumper->describeDifference($this->_value, $compare); + } + } + } + + /** + * Test for a specific HTTP header within a header block. + * @package SimpleTest + * @subpackage WebTester + */ + class HttpHeaderExpectation extends SimpleExpectation { + var $_expected_header; + var $_expected_value; + + /** + * Sets the field and value to compare against. + * @param string $header Case insenstive trimmed header name. + * @param mixed $value Optional value to compare. If not + * given then any value will match. If + * an expectation object then that will + * be used instead. + * @param string $message Optiona message override. Can use %s as + * a placeholder for the original message. + */ + function HttpHeaderExpectation($header, $value = false, $message = '%s') { + $this->SimpleExpectation($message); + $this->_expected_header = $this->_normaliseHeader($header); + $this->_expected_value = $value; + } + + /** + * Accessor for aggregated object. + * @return mixed Expectation set in constructor. + * @access protected + */ + function _getExpectation() { + return $this->_expected_value; + } + + /** + * Removes whitespace at ends and case variations. + * @param string $header Name of header. + * @param string Trimmed and lowecased header + * name. + * @access private + */ + function _normaliseHeader($header) { + return strtolower(trim($header)); + } + + /** + * Tests the expectation. True if it matches + * a string value or an array value in any order. + * @param mixed $compare Raw header block to search. + * @return boolean True if header present. + * @access public + */ + function test($compare) { + return is_string($this->_findHeader($compare)); + } + + /** + * Searches the incoming result. Will extract the matching + * line as text. + * @param mixed $compare Raw header block to search. + * @return string Matching header line. + * @access protected + */ + function _findHeader($compare) { + $lines = split("\r\n", $compare); + foreach ($lines as $line) { + if ($this->_testHeaderLine($line)) { + return $line; + } + } + return false; + } + + /** + * Compares a single header line against the expectation. + * @param string $line A single line to compare. + * @return boolean True if matched. + * @access private + */ + function _testHeaderLine($line) { + if (count($parsed = split(':', $line, 2)) < 2) { + return false; + } + list($header, $value) = $parsed; + if ($this->_normaliseHeader($header) != $this->_expected_header) { + return false; + } + return $this->_testHeaderValue($value, $this->_expected_value); + } + + /** + * Tests the value part of the header. + * @param string $value Value to test. + * @param mixed $expected Value to test against. + * @return boolean True if matched. + * @access protected + */ + function _testHeaderValue($value, $expected) { + if ($expected === false) { + return true; + } + if (SimpleExpectation::isExpectation($expected)) { + return $expected->test(trim($value)); + } + return (trim($value) == trim($expected)); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Raw header block to search. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if (SimpleExpectation::isExpectation($this->_expected_value)) { + $message = $this->_expected_value->overlayMessage($compare, $this->_getDumper()); + } else { + $message = $this->_expected_header . + ($this->_expected_value ? ': ' . $this->_expected_value : ''); + } + if (is_string($line = $this->_findHeader($compare))) { + return "Searching for header [$message] found [$line]"; + } else { + return "Failed to find header [$message]"; + } + } + } + + /** + * Test for a specific HTTP header within a header block that + * should not be found. + * @package SimpleTest + * @subpackage WebTester + */ + class NoHttpHeaderExpectation extends HttpHeaderExpectation { + var $_expected_header; + var $_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 NoHttpHeaderExpectation($unwanted, $message = '%s') { + $this->HttpHeaderExpectation($unwanted, false, $message); + } + + /** + * Tests that the unwanted header is not found. + * @param mixed $compare Raw header block to search. + * @return boolean True if header present. + * @access public + */ + function test($compare) { + return ($this->_findHeader($compare) === false); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Raw header block to search. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $expectation = $this->_getExpectation(); + if (is_string($line = $this->_findHeader($compare))) { + return "Found unwanted header [$expectation] with [$line]"; + } else { + return "Did not find unwanted header [$expectation]"; + } + } + } + + /** + * Test for a text substring. + * @package SimpleTest + * @subpackage UnitTester + */ + class TextExpectation extends SimpleExpectation { + var $_substring; + + /** + * Sets the value to compare against. + * @param string $substring Text to search for. + * @param string $message Customised message on failure. + * @access public + */ + function TextExpectation($substring, $message = '%s') { + $this->SimpleExpectation($message); + $this->_substring = $substring; + } + + /** + * Accessor for the substring. + * @return string Text to match. + * @access protected + */ + function _getSubstring() { + return $this->_substring; + } + + /** + * Tests the expectation. True if the text contains the + * substring. + * @param string $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return (strpos($compare, $this->_substring) !== false); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if ($this->test($compare)) { + return $this->_describeTextMatch($this->_getSubstring(), $compare); + } else { + $dumper = &$this->_getDumper(); + return "Text [" . $this->_getSubstring() . + "] not detected in [" . + $dumper->describeValue($compare) . "]"; + } + } + + /** + * Describes a pattern match including the string + * found and it's position. + * @param string $substring Text to search for. + * @param string $subject Subject to search. + * @access protected + */ + function _describeTextMatch($substring, $subject) { + $position = strpos($subject, $substring); + $dumper = &$this->_getDumper(); + return "Text [$substring] detected at character [$position] in [" . + $dumper->describeValue($subject) . "] in region [" . + $dumper->clipString($subject, 100, $position) . "]"; + } + } + + /** + * Fail if a substring is detected within the + * comparison text. + * @package SimpleTest + * @subpackage UnitTester + */ + class NoTextExpectation extends TextExpectation { + + /** + * Sets the reject pattern + * @param string $substring Text to search for. + * @param string $message Customised message on failure. + * @access public + */ + function NoTextExpectation($substring, $message = '%s') { + $this->TextExpectation($substring, $message); + } + + /** + * Tests the expectation. False if the substring appears + * in the text. + * @param string $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return ! parent::test($compare); + } + + /** + * Returns a human readable test message. + * @param string $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if ($this->test($compare)) { + $dumper = &$this->_getDumper(); + return "Text [" . $this->_getSubstring() . + "] not detected in [" . + $dumper->describeValue($compare) . "]"; + } else { + return $this->_describeTextMatch($this->_getSubstring(), $compare); + } + } + } + + /** + * Test case for testing of web pages. Allows + * fetching of pages, parsing of HTML and + * submitting forms. + * @package SimpleTest + * @subpackage WebTester + */ + class WebTestCase extends SimpleTestCase { + var $_browser; + var $_ignore_errors = false; + + /** + * Creates an empty test case. Should be subclassed + * with test methods for a functional test case. + * @param string $label Name of test case. Will use + * the class name if none specified. + * @access public + */ + function WebTestCase($label = false) { + $this->SimpleTestCase($label); + } + + /** + * Announces the start of the test. + * @param string $method Test method just started. + * @access public + */ + function before($method) { + parent::before($method); + $this->setBrowser($this->createBrowser()); + } + + /** + * Announces the end of the test. Includes private clean up. + * @param string $method Test method just finished. + * @access public + */ + function after($method) { + $this->unsetBrowser(); + parent::after($method); + } + + /** + * Gets a current browser reference for setting + * special expectations or for detailed + * examination of page fetches. + * @return SimpleBrowser Current test browser object. + * @access public + */ + function &getBrowser() { + return $this->_browser; + } + + /** + * Gets a current browser reference for setting + * special expectations or for detailed + * examination of page fetches. + * @param SimpleBrowser $browser New test browser object. + * @access public + */ + function setBrowser(&$browser) { + return $this->_browser = &$browser; + } + + /** + * Clears the current browser reference to help the + * PHP garbage collector. + * @access public + */ + function unsetBrowser() { + unset($this->_browser); + } + + /** + * Creates a new default web browser object. + * Will be cleared at the end of the test method. + * @return TestBrowser New browser. + * @access public + */ + function &createBrowser() { + $browser = &new SimpleBrowser(); + return $browser; + } + + /** + * Gets the last response error. + * @return string Last low level HTTP error. + * @access public + */ + function getTransportError() { + return $this->_browser->getTransportError(); + } + + /** + * Accessor for the currently selected URL. + * @return string Current location or false if + * no page yet fetched. + * @access public + */ + function getUrl() { + return $this->_browser->getUrl(); + } + + /** + * Dumps the current request for debugging. + * @access public + */ + function showRequest() { + $this->dump($this->_browser->getRequest()); + } + + /** + * Dumps the current HTTP headers for debugging. + * @access public + */ + function showHeaders() { + $this->dump($this->_browser->getHeaders()); + } + + /** + * Dumps the current HTML source for debugging. + * @access public + */ + function showSource() { + $this->dump($this->_browser->getContent()); + } + + /** + * Dumps the visible text only for debugging. + * @access public + */ + function showText() { + $this->dump(wordwrap($this->_browser->getContentAsText(), 80)); + } + + /** + * Simulates the closing and reopening of the browser. + * Temporary cookies will be discarded and timed + * cookies will be expired if later than the + * specified time. + * @param string/integer $date Time when session restarted. + * If ommitted then all persistent + * cookies are kept. Time is either + * Cookie format string or timestamp. + * @access public + */ + function restart($date = false) { + if ($date === false) { + $date = time(); + } + $this->_browser->restart($date); + } + + /** + * Moves cookie expiry times back into the past. + * Useful for testing timeouts and expiries. + * @param integer $interval Amount to age in seconds. + * @access public + */ + function ageCookies($interval) { + $this->_browser->ageCookies($interval); + } + + /** + * Disables frames support. Frames will not be fetched + * and the frameset page will be used instead. + * @access public + */ + function ignoreFrames() { + $this->_browser->ignoreFrames(); + } + + /** + * Switches off cookie sending and recieving. + * @access public + */ + function ignoreCookies() { + $this->_browser->ignoreCookies(); + } + + /** + * Skips errors for the next request only. You might + * want to confirm that a page is unreachable for + * example. + * @access public + */ + function ignoreErrors() { + $this->_ignore_errors = true; + } + + /** + * Issues a fail if there is a transport error anywhere + * in the current frameset. Only one such error is + * reported. + * @param string/boolean $result HTML or failure. + * @return string/boolean $result Passes through result. + * @access private + */ + function _failOnError($result) { + if (! $this->_ignore_errors) { + if ($error = $this->_browser->getTransportError()) { + $this->fail($error); + } + } + $this->_ignore_errors = false; + return $result; + } + + /** + * Adds a header to every fetch. + * @param string $header Header line to add to every + * request until cleared. + * @access public + */ + function addHeader($header) { + $this->_browser->addHeader($header); + } + + /** + * Sets the maximum number of redirects before + * the web page is loaded regardless. + * @param integer $max Maximum hops. + * @access public + */ + function setMaximumRedirects($max) { + if (! $this->_browser) { + trigger_error( + 'Can only set maximum redirects in a test method, setUp() or tearDown()'); + } + $this->_browser->setMaximumRedirects($max); + } + + /** + * Sets the socket timeout for opening a connection and + * receiving at least one byte of information. + * @param integer $timeout Maximum time in seconds. + * @access public + */ + function setConnectionTimeout($timeout) { + $this->_browser->setConnectionTimeout($timeout); + } + + /** + * Sets proxy to use on all requests for when + * testing from behind a firewall. Set URL + * to false to disable. + * @param string $proxy Proxy URL. + * @param string $username Proxy username for authentication. + * @param string $password Proxy password for authentication. + * @access public + */ + function useProxy($proxy, $username = false, $password = false) { + $this->_browser->useProxy($proxy, $username, $password); + } + + /** + * Fetches a page into the page buffer. If + * there is no base for the URL then the + * current base URL is used. After the fetch + * the base URL reflects the new location. + * @param string $url URL to fetch. + * @param hash $parameters Optional additional GET data. + * @return boolean/string Raw page on success. + * @access public + */ + function get($url, $parameters = false) { + return $this->_failOnError($this->_browser->get($url, $parameters)); + } + + /** + * Fetches a page by POST into the page buffer. + * If there is no base for the URL then the + * current base URL is used. After the fetch + * the base URL reflects the new location. + * @param string $url URL to fetch. + * @param hash $parameters Optional additional GET data. + * @return boolean/string Raw page on success. + * @access public + */ + function post($url, $parameters = false) { + return $this->_failOnError($this->_browser->post($url, $parameters)); + } + + /** + * Does a HTTP HEAD fetch, fetching only the page + * headers. The current base URL is unchanged by this. + * @param string $url URL to fetch. + * @param hash $parameters Optional additional GET data. + * @return boolean True on success. + * @access public + */ + function head($url, $parameters = false) { + return $this->_failOnError($this->_browser->head($url, $parameters)); + } + + /** + * Equivalent to hitting the retry button on the + * browser. Will attempt to repeat the page fetch. + * @return boolean True if fetch succeeded. + * @access public + */ + function retry() { + return $this->_failOnError($this->_browser->retry()); + } + + /** + * Equivalent to hitting the back button on the + * browser. + * @return boolean True if history entry and + * fetch succeeded. + * @access public + */ + function back() { + return $this->_failOnError($this->_browser->back()); + } + + /** + * Equivalent to hitting the forward button on the + * browser. + * @return boolean True if history entry and + * fetch succeeded. + * @access public + */ + function forward() { + return $this->_failOnError($this->_browser->forward()); + } + + /** + * Retries a request after setting the authentication + * for the current realm. + * @param string $username Username for realm. + * @param string $password Password for realm. + * @return boolean/string HTML on successful fetch. Note + * that authentication may still have + * failed. + * @access public + */ + function authenticate($username, $password) { + return $this->_failOnError( + $this->_browser->authenticate($username, $password)); + } + + /** + * Gets the cookie value for the current browser context. + * @param string $name Name of cookie. + * @return string Value of cookie or false if unset. + * @access public + */ + function getCookie($name) { + return $this->_browser->getCurrentCookieValue($name); + } + + /** + * Sets a cookie in the current browser. + * @param string $name Name of cookie. + * @param string $value Cookie value. + * @param string $host Host upon which the cookie is valid. + * @param string $path Cookie path if not host wide. + * @param string $expiry Expiry date. + * @access public + */ + function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { + $this->_browser->setCookie($name, $value, $host, $path, $expiry); + } + + /** + * Accessor for current frame focus. Will be + * false if no frame has focus. + * @return integer/string/boolean Label if any, otherwise + * the position in the frameset + * or false if none. + * @access public + */ + function getFrameFocus() { + return $this->_browser->getFrameFocus(); + } + + /** + * Sets the focus by index. The integer index starts from 1. + * @param integer $choice Chosen frame. + * @return boolean True if frame exists. + * @access public + */ + function setFrameFocusByIndex($choice) { + return $this->_browser->setFrameFocusByIndex($choice); + } + + /** + * Sets the focus by name. + * @param string $name Chosen frame. + * @return boolean True if frame exists. + * @access public + */ + function setFrameFocus($name) { + return $this->_browser->setFrameFocus($name); + } + + /** + * Clears the frame focus. All frames will be searched + * for content. + * @access public + */ + function clearFrameFocus() { + return $this->_browser->clearFrameFocus(); + } + + /** + * Clicks a visible text item. Will first try buttons, + * then links and then images. + * @param string $label Visible text or alt text. + * @return string/boolean Raw page or false. + * @access public + */ + function click($label) { + return $this->_failOnError($this->_browser->click($label)); + } + + /** + * Checks for a click target. + * @param string $label Visible text or alt text. + * @return boolean True if click target. + * @access public + */ + function assertClickable($label, $message = '%s') { + return $this->assertTrue( + $this->_browser->isClickable($label), + sprintf($message, "Click target [$label] should exist")); + } + + /** + * Clicks the submit button by label. The owning + * form will be submitted by this. + * @param string $label Button label. An unlabeled + * button can be triggered by 'Submit'. + * @param hash $additional Additional form values. + * @return boolean/string Page on success, else false. + * @access public + */ + function clickSubmit($label = 'Submit', $additional = false) { + return $this->_failOnError( + $this->_browser->clickSubmit($label, $additional)); + } + + /** + * Clicks the submit button by name attribute. The owning + * form will be submitted by this. + * @param string $name Name attribute of button. + * @param hash $additional Additional form values. + * @return boolean/string Page on success. + * @access public + */ + function clickSubmitByName($name, $additional = false) { + return $this->_failOnError( + $this->_browser->clickSubmitByName($name, $additional)); + } + + /** + * Clicks the submit button by ID attribute. The owning + * form will be submitted by this. + * @param string $id ID attribute of button. + * @param hash $additional Additional form values. + * @return boolean/string Page on success. + * @access public + */ + function clickSubmitById($id, $additional = false) { + return $this->_failOnError( + $this->_browser->clickSubmitById($id, $additional)); + } + + /** + * Checks for a valid button label. + * @param string $label Visible text. + * @return boolean True if click target. + * @access public + */ + function assertSubmit($label, $message = '%s') { + return $this->assertTrue( + $this->_browser->isSubmit($label), + sprintf($message, "Submit button [$label] should exist")); + } + + /** + * Clicks the submit image by some kind of label. Usually + * the alt tag or the nearest equivalent. The owning + * form will be submitted by this. Clicking outside of + * the boundary of the coordinates will result in + * a failure. + * @param string $label Alt attribute of button. + * @param integer $x X-coordinate of imaginary click. + * @param integer $y Y-coordinate of imaginary click. + * @param hash $additional Additional form values. + * @return boolean/string Page on success. + * @access public + */ + function clickImage($label, $x = 1, $y = 1, $additional = false) { + return $this->_failOnError( + $this->_browser->clickImage($label, $x, $y, $additional)); + } + + /** + * Clicks the submit image by the name. Usually + * the alt tag or the nearest equivalent. The owning + * form will be submitted by this. Clicking outside of + * the boundary of the coordinates will result in + * a failure. + * @param string $name Name attribute of button. + * @param integer $x X-coordinate of imaginary click. + * @param integer $y Y-coordinate of imaginary click. + * @param hash $additional Additional form values. + * @return boolean/string Page on success. + * @access public + */ + function clickImageByName($name, $x = 1, $y = 1, $additional = false) { + return $this->_failOnError( + $this->_browser->clickImageByName($name, $x, $y, $additional)); + } + + /** + * Clicks the submit image by ID attribute. The owning + * form will be submitted by this. Clicking outside of + * the boundary of the coordinates will result in + * a failure. + * @param integer/string $id ID attribute of button. + * @param integer $x X-coordinate of imaginary click. + * @param integer $y Y-coordinate of imaginary click. + * @param hash $additional Additional form values. + * @return boolean/string Page on success. + * @access public + */ + function clickImageById($id, $x = 1, $y = 1, $additional = false) { + return $this->_failOnError( + $this->_browser->clickImageById($id, $x, $y, $additional)); + } + + /** + * Checks for a valid image with atht alt text or title. + * @param string $label Visible text. + * @return boolean True if click target. + * @access public + */ + function assertImage($label, $message = '%s') { + return $this->assertTrue( + $this->_browser->isImage($label), + sprintf($message, "Image with text [$label] should exist")); + } + + /** + * Submits a form by the ID. + * @param string $id Form ID. No button information + * is submitted this way. + * @return boolean/string Page on success. + * @access public + */ + function submitFormById($id) { + return $this->_failOnError($this->_browser->submitFormById($id)); + } + + /** + * Follows a link by name. Will click the first link + * found with this link text by default, or a later + * one if an index is given. Match is case insensitive + * with normalised space. + * @param string $label Text between the anchor tags. + * @param integer $index Link position counting from zero. + * @return boolean/string Page on success. + * @access public + */ + function clickLink($label, $index = 0) { + return $this->_failOnError($this->_browser->clickLink($label, $index)); + } + + /** + * Follows a link by id attribute. + * @param string $id ID attribute value. + * @return boolean/string Page on success. + * @access public + */ + function clickLinkById($id) { + return $this->_failOnError($this->_browser->clickLinkById($id)); + } + + /** + * Tests for the presence of a link label. Match is + * case insensitive with normalised space. + * @param string $label Text between the anchor tags. + * @param mixed $expected Expected URL or expectation object. + * @param string $message Message to display. Default + * can be embedded with %s. + * @return boolean True if link present. + * @access public + */ + function assertLink($label, $expected = true, $message = '%s') { + $url = $this->_browser->getLink($label); + if ($expected === true) { + return $this->assertTrue($url !== false, sprintf($message, "Link [$label] should exist")); + } + if (! SimpleExpectation::isExpectation($expected)) { + $expected = new IdenticalExpectation($expected); + } + return $this->assert($expected, $url->asString(), sprintf($message, "Link [$label] should match")); + } + + /** + * Tests for the non-presence of a link label. Match is + * case insensitive with normalised space. + * @param string/integer $label Text between the anchor tags + * or ID attribute. + * @param string $message Message to display. Default + * can be embedded with %s. + * @return boolean True if link missing. + * @access public + */ + function assertNoLink($label, $message = '%s') { + return $this->assertTrue( + $this->_browser->getLink($label) === false, + sprintf($message, "Link [$label] should not exist")); + } + + /** + * Tests for the presence of a link id attribute. + * @param string $id Id attribute value. + * @param mixed $expected Expected URL or expectation object. + * @param string $message Message to display. Default + * can be embedded with %s. + * @return boolean True if link present. + * @access public + */ + function assertLinkById($id, $expected = true, $message = '%s') { + $url = $this->_browser->getLinkById($id); + if ($expected === true) { + return $this->assertTrue($url !== false, sprintf($message, "Link ID [$id] should exist")); + } + if (! SimpleExpectation::isExpectation($expected)) { + $expected = new IdenticalExpectation($expected); + } + return $this->assert($expected, $url->asString(), sprintf($message, "Link ID [$id] should match")); + } + + /** + * Tests for the non-presence of a link label. Match is + * case insensitive with normalised space. + * @param string $id Id attribute value. + * @param string $message Message to display. Default + * can be embedded with %s. + * @return boolean True if link missing. + * @access public + */ + function assertNoLinkById($id, $message = '%s') { + return $this->assertTrue( + $this->_browser->getLinkById($id) === false, + sprintf($message, "Link ID [$id] should not exist")); + } + + /** + * Sets all form fields with that label, or name if there + * is no label attached. + * @param string $name Name of field in forms. + * @param string $value New value of field. + * @return boolean True if field exists, otherwise false. + * @access public + */ + function setField($label, $value) { + return $this->_browser->setField($label, $value); + } + + /** + * Sets all form fields with that name. + * @param string $name Name of field in forms. + * @param string $value New value of field. + * @return boolean True if field exists, otherwise false. + * @access public + */ + function setFieldByName($name, $value) { + return $this->_browser->setFieldByName($name, $value); + } + + /** + * Sets all form fields with that name. + * @param string/integer $id Id of field in forms. + * @param string $value New value of field. + * @return boolean True if field exists, otherwise false. + * @access public + */ + function setFieldById($id, $value) { + return $this->_browser->setFieldById($id, $value); + } + + /** + * Confirms that the form element is currently set + * to the expected value. A missing form will always + * fail. If no value is given then only the existence + * of the field is checked. + * @param string $name Name of field in forms. + * @param mixed $expected Expected string/array value or + * false for unset fields. + * @param string $message Message to display. Default + * can be embedded with %s. + * @return boolean True if pass. + * @access public + */ + function assertField($label, $expected = true, $message = '%s') { + $value = $this->_browser->getField($label); + return $this->_assertFieldValue($label, $value, $expected, $message); + } + + /** + * Confirms that the form element is currently set + * to the expected value. A missing form element will always + * fail. If no value is given then only the existence + * of the field is checked. + * @param string $name Name of field in forms. + * @param mixed $expected Expected string/array value or + * false for unset fields. + * @param string $message Message to display. Default + * can be embedded with %s. + * @return boolean True if pass. + * @access public + */ + function assertFieldByName($name, $expected = true, $message = '%s') { + $value = $this->_browser->getFieldByName($name); + return $this->_assertFieldValue($name, $value, $expected, $message); + } + + /** + * Confirms that the form element is currently set + * to the expected value. A missing form will always + * fail. If no ID is given then only the existence + * of the field is checked. + * @param string/integer $id Name of field in forms. + * @param mixed $expected Expected string/array value or + * false for unset fields. + * @param string $message Message to display. Default + * can be embedded with %s. + * @return boolean True if pass. + * @access public + */ + function assertFieldById($id, $expected = true, $message = '%s') { + $value = $this->_browser->getFieldById($id); + return $this->_assertFieldValue($id, $value, $expected, $message); + } + + /** + * Tests the field value against the expectation. + * @param string $identifier Name, ID or label. + * @param mixed $value Current field value. + * @param mixed $expected Expected value to match. + * @param string $message Failure message. + * @return boolean True if pass + * @access protected + */ + function _assertFieldValue($identifier, $value, $expected, $message) { + if ($expected === true) { + return $this->assertTrue( + isset($value), + sprintf($message, "Field [$identifier] should exist")); + } + if (! SimpleExpectation::isExpectation($expected)) { + $identifier = str_replace('%', '%%', $identifier); + $expected = new FieldExpectation( + $expected, + "Field [$identifier] should match with [%s]"); + } + return $this->assert($expected, $value, $message); + } + + /** + * Checks the response code against a list + * of possible values. + * @param array $responses Possible responses for a pass. + * @param string $message Message to display. Default + * can be embedded with %s. + * @return boolean True if pass. + * @access public + */ + function assertResponse($responses, $message = '%s') { + $responses = (is_array($responses) ? $responses : array($responses)); + $code = $this->_browser->getResponseCode(); + $message = sprintf($message, "Expecting response in [" . + implode(", ", $responses) . "] got [$code]"); + return $this->assertTrue(in_array($code, $responses), $message); + } + + /** + * Checks the mime type against a list + * of possible values. + * @param array $types Possible mime types for a pass. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertMime($types, $message = '%s') { + $types = (is_array($types) ? $types : array($types)); + $type = $this->_browser->getMimeType(); + $message = sprintf($message, "Expecting mime type in [" . + implode(", ", $types) . "] got [$type]"); + return $this->assertTrue(in_array($type, $types), $message); + } + + /** + * Attempt to match the authentication type within + * the security realm we are currently matching. + * @param string $authentication Usually basic. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertAuthentication($authentication = false, $message = '%s') { + if (! $authentication) { + $message = sprintf($message, "Expected any authentication type, got [" . + $this->_browser->getAuthentication() . "]"); + return $this->assertTrue( + $this->_browser->getAuthentication(), + $message); + } else { + $message = sprintf($message, "Expected authentication [$authentication] got [" . + $this->_browser->getAuthentication() . "]"); + return $this->assertTrue( + strtolower($this->_browser->getAuthentication()) == strtolower($authentication), + $message); + } + } + + /** + * Checks that no authentication is necessary to view + * the desired page. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertNoAuthentication($message = '%s') { + $message = sprintf($message, "Expected no authentication type, got [" . + $this->_browser->getAuthentication() . "]"); + return $this->assertFalse($this->_browser->getAuthentication(), $message); + } + + /** + * Attempts to match the current security realm. + * @param string $realm Name of security realm. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertRealm($realm, $message = '%s') { + if (! SimpleExpectation::isExpectation($realm)) { + $realm = new EqualExpectation($realm); + } + return $this->assert( + $realm, + $this->_browser->getRealm(), + "Expected realm -> $message"); + } + + /** + * Checks each header line for the required value. If no + * value is given then only an existence check is made. + * @param string $header Case insensitive header name. + * @param mixed $value Case sensitive trimmed string to + * match against. An expectation object + * can be used for pattern matching. + * @return boolean True if pass. + * @access public + */ + function assertHeader($header, $value = false, $message = '%s') { + return $this->assert( + new HttpHeaderExpectation($header, $value), + $this->_browser->getHeaders(), + $message); + } + + /** + * @deprecated + */ + function assertHeaderPattern($header, $pattern, $message = '%s') { + return $this->assert( + new HttpHeaderExpectation($header, new PatternExpectation($pattern)), + $this->_browser->getHeaders(), + $message); + } + + /** + * Confirms that the header type has not been received. + * Only the landing page is checked. If you want to check + * redirect pages, then you should limit redirects so + * as to capture the page you want. + * @param string $header Case insensitive header name. + * @return boolean True if pass. + * @access public + */ + function assertNoHeader($header, $message = '%s') { + return $this->assert( + new NoHttpHeaderExpectation($header), + $this->_browser->getHeaders(), + $message); + } + + /** + * @deprecated + */ + function assertNoUnwantedHeader($header, $message = '%s') { + return $this->assertNoHeader($header, $message); + } + + /** + * Tests the text between the title tags. + * @param string/SimpleExpectation $title Expected title. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertTitle($title = false, $message = '%s') { + if (! SimpleExpectation::isExpectation($title)) { + $title = new EqualExpectation($title); + } + return $this->assert($title, $this->_browser->getTitle(), $message); + } + + /** + * Will trigger a pass if the text is found in the plain + * text form of the page. + * @param string $text Text to look for. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertText($text, $message = '%s') { + return $this->assert( + new TextExpectation($text), + $this->_browser->getContentAsText(), + $message); + } + + /** + * @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. + * @param string $text Text to look for. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertNoText($text, $message = '%s') { + return $this->assert( + new NoTextExpectation($text), + $this->_browser->getContentAsText(), + $message); + } + + /** + * @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. + * @param string $pattern Perl regex to look for including + * the regex delimiters. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertPattern($pattern, $message = '%s') { + return $this->assert( + new PatternExpectation($pattern), + $this->_browser->getContent(), + $message); + } + + /** + * @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. + * @param string $pattern Perl regex to look for including + * the regex delimiters. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertNoPattern($pattern, $message = '%s') { + return $this->assert( + new NoPatternExpectation($pattern), + $this->_browser->getContent(), + $message); + } + + /** + * @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. + * @param string $name Name of cookie to test. + * @param string $expected Expected value as a string or + * false if any value will do. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertCookie($name, $expected = false, $message = '%s') { + $value = $this->getCookie($name); + if (! $expected) { + return $this->assertTrue( + $value, + sprintf($message, "Expecting cookie [$name]")); + } + if (! SimpleExpectation::isExpectation($expected)) { + $expected = new EqualExpectation($expected); + } + return $this->assert($expected, $value, "Expecting cookie [$name] -> $message"); + } + + /** + * Checks that no cookie is present or that it has + * been successfully cleared. + * @param string $name Name of cookie to test. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertNoCookie($name, $message = '%s') { + return $this->assertTrue( + $this->getCookie($name) === false, + sprintf($message, "Not expecting cookie [$name]")); + } + + /** + * Called from within the test methods to register + * passes and failures. + * @param boolean $result Pass on true. + * @param string $message Message to display describing + * the test state. + * @return boolean True on pass + * @access public + */ + function assertTrue($result, $message = false) { + return $this->assert(new TrueExpectation(), $result, $message); + } + + /** + * Will be true on false and vice versa. False + * is the PHP definition of false, so that null, + * empty strings, zero and an empty array all count + * as false. + * @param boolean $result Pass on false. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertFalse($result, $message = '%s') { + return $this->assert(new FalseExpectation(), $result, $message); + } + + /** + * Will trigger a pass if the two parameters have + * the same value only. Otherwise a fail. This + * is for testing hand extracted text, etc. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertEqual($first, $second, $message = '%s') { + return $this->assert( + new EqualExpectation($first), + $second, + $message); + } + + /** + * Will trigger a pass if the two parameters have + * a different value. Otherwise a fail. This + * is for testing hand extracted text, etc. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertNotEqual($first, $second, $message = '%s') { + return $this->assert( + new NotEqualExpectation($first), + $second, + $message); + } + + /** + * Uses a stack trace to find the line of an assertion. + * @return string Line number of first assert* + * method embedded in format string. + * @access public + */ + function getAssertionLine() { + $trace = new SimpleStackTrace(array('assert', 'click', 'pass', 'fail')); + return $trace->traceMethod(); + } + } +?> \ No newline at end of file diff --git a/tests/simpletest/xml.php b/tests/simpletest/xml.php new file mode 100644 index 00000000..e64caa9f --- /dev/null +++ b/tests/simpletest/xml.php @@ -0,0 +1,647 @@ +SimpleReporter(); + $this->_namespace = ($namespace ? $namespace . ':' : ''); + $this->_indent = $indent; + } + + /** + * Calculates the pretty printing indent level + * from the current level of nesting. + * @param integer $offset Extra indenting level. + * @return string Leading space. + * @access protected + */ + function _getIndent($offset = 0) { + return str_repeat( + $this->_indent, + count($this->getTestList()) + $offset); + } + + /** + * Converts character string to parsed XML + * entities string. + * @param string text Unparsed character data. + * @return string Parsed character data. + * @access public + */ + function toParsedXml($text) { + return str_replace( + array('&', '<', '>', '"', '\''), + array('&', '<', '>', '"', '''), + $text); + } + + /** + * Paints the start of a group test. + * @param string $test_name Name of test that is starting. + * @param integer $size Number of test cases starting. + * @access public + */ + function paintGroupStart($test_name, $size) { + parent::paintGroupStart($test_name, $size); + print $this->_getIndent(); + print "<" . $this->_namespace . "group size=\"$size\">\n"; + print $this->_getIndent(1); + print "<" . $this->_namespace . "name>" . + $this->toParsedXml($test_name) . + "_namespace . "name>\n"; + } + + /** + * Paints the end of a group test. + * @param string $test_name Name of test that is ending. + * @access public + */ + function paintGroupEnd($test_name) { + print $this->_getIndent(); + print "_namespace . "group>\n"; + parent::paintGroupEnd($test_name); + } + + /** + * Paints the start of a test case. + * @param string $test_name Name of test that is starting. + * @access public + */ + function paintCaseStart($test_name) { + parent::paintCaseStart($test_name); + print $this->_getIndent(); + print "<" . $this->_namespace . "case>\n"; + print $this->_getIndent(1); + print "<" . $this->_namespace . "name>" . + $this->toParsedXml($test_name) . + "_namespace . "name>\n"; + } + + /** + * Paints the end of a test case. + * @param string $test_name Name of test that is ending. + * @access public + */ + function paintCaseEnd($test_name) { + print $this->_getIndent(); + print "_namespace . "case>\n"; + parent::paintCaseEnd($test_name); + } + + /** + * Paints the start of a test method. + * @param string $test_name Name of test that is starting. + * @access public + */ + function paintMethodStart($test_name) { + parent::paintMethodStart($test_name); + print $this->_getIndent(); + print "<" . $this->_namespace . "test>\n"; + print $this->_getIndent(1); + print "<" . $this->_namespace . "name>" . + $this->toParsedXml($test_name) . + "_namespace . "name>\n"; + } + + /** + * Paints the end of a test method. + * @param string $test_name Name of test that is ending. + * @param integer $progress Number of test cases ending. + * @access public + */ + function paintMethodEnd($test_name) { + print $this->_getIndent(); + print "_namespace . "test>\n"; + parent::paintMethodEnd($test_name); + } + + /** + * Paints pass as XML. + * @param string $message Message to encode. + * @access public + */ + function paintPass($message) { + parent::paintPass($message); + print $this->_getIndent(1); + print "<" . $this->_namespace . "pass>"; + print $this->toParsedXml($message); + print "_namespace . "pass>\n"; + } + + /** + * Paints failure as XML. + * @param string $message Message to encode. + * @access public + */ + function paintFail($message) { + parent::paintFail($message); + print $this->_getIndent(1); + print "<" . $this->_namespace . "fail>"; + print $this->toParsedXml($message); + print "_namespace . "fail>\n"; + } + + /** + * Paints error as XML. + * @param string $message Message to encode. + * @access public + */ + function paintError($message) { + parent::paintError($message); + print $this->_getIndent(1); + print "<" . $this->_namespace . "exception>"; + print $this->toParsedXml($message); + print "_namespace . "exception>\n"; + } + + /** + * Paints exception as XML. + * @param Exception $exception Exception to encode. + * @access public + */ + function paintException($exception) { + parent::paintException($exception); + print $this->_getIndent(1); + print "<" . $this->_namespace . "exception>"; + $message = 'Unexpected exception of type [' . get_class($exception) . + '] with message ['. $exception->getMessage() . + '] in ['. $exception->getFile() . + ' line ' . $exception->getLine() . ']'; + print $this->toParsedXml($message); + print "_namespace . "exception>\n"; + } + + /** + * Paints the skipping message and tag. + * @param string $message Text to display in skip tag. + * @access public + */ + function paintSkip($message) { + parent::paintSkip($message); + print $this->_getIndent(1); + print "<" . $this->_namespace . "skip>"; + print $this->toParsedXml($message); + print "_namespace . "skip>\n"; + } + + /** + * Paints a simple supplementary message. + * @param string $message Text to display. + * @access public + */ + function paintMessage($message) { + parent::paintMessage($message); + print $this->_getIndent(1); + print "<" . $this->_namespace . "message>"; + print $this->toParsedXml($message); + print "_namespace . "message>\n"; + } + + /** + * Paints a formatted ASCII message such as a + * variable dump. + * @param string $message Text to display. + * @access public + */ + function paintFormattedMessage($message) { + parent::paintFormattedMessage($message); + print $this->_getIndent(1); + print "<" . $this->_namespace . "formatted>"; + print ""; + print "_namespace . "formatted>\n"; + } + + /** + * Serialises the event object. + * @param string $type Event type as text. + * @param mixed $payload Message or object. + * @access public + */ + function paintSignal($type, &$payload) { + parent::paintSignal($type, $payload); + print $this->_getIndent(1); + print "<" . $this->_namespace . "signal type=\"$type\">"; + print ""; + print "_namespace . "signal>\n"; + } + + /** + * Paints the test document header. + * @param string $test_name First test top level + * to start. + * @access public + * @abstract + */ + function paintHeader($test_name) { + if (! SimpleReporter::inCli()) { + header('Content-type: text/xml'); + } + print "_namespace) { + print " xmlns:" . $this->_namespace . + "=\"www.lastcraft.com/SimpleTest/Beta3/Report\""; + } + print "?>\n"; + print "<" . $this->_namespace . "run>\n"; + } + + /** + * Paints the test document footer. + * @param string $test_name The top level test. + * @access public + * @abstract + */ + function paintFooter($test_name) { + print "_namespace . "run>\n"; + } + } + + /** + * Accumulator for incoming tag. Holds the + * incoming test structure information for + * later dispatch to the reporter. + * @package SimpleTest + * @subpackage UnitTester + */ + class NestingXmlTag { + var $_name; + var $_attributes; + + /** + * Sets the basic test information except + * the name. + * @param hash $attributes Name value pairs. + * @access public + */ + function NestingXmlTag($attributes) { + $this->_name = false; + $this->_attributes = $attributes; + } + + /** + * Sets the test case/method name. + * @param string $name Name of test. + * @access public + */ + function setName($name) { + $this->_name = $name; + } + + /** + * Accessor for name. + * @return string Name of test. + * @access public + */ + function getName() { + return $this->_name; + } + + /** + * Accessor for attributes. + * @return hash All attributes. + * @access protected + */ + function _getAttributes() { + return $this->_attributes; + } + } + + /** + * Accumulator for incoming method tag. Holds the + * incoming test structure information for + * later dispatch to the reporter. + * @package SimpleTest + * @subpackage UnitTester + */ + class NestingMethodTag extends NestingXmlTag { + + /** + * Sets the basic test information except + * the name. + * @param hash $attributes Name value pairs. + * @access public + */ + function NestingMethodTag($attributes) { + $this->NestingXmlTag($attributes); + } + + /** + * Signals the appropriate start event on the + * listener. + * @param SimpleReporter $listener Target for events. + * @access public + */ + function paintStart(&$listener) { + $listener->paintMethodStart($this->getName()); + } + + /** + * Signals the appropriate end event on the + * listener. + * @param SimpleReporter $listener Target for events. + * @access public + */ + function paintEnd(&$listener) { + $listener->paintMethodEnd($this->getName()); + } + } + + /** + * Accumulator for incoming case tag. Holds the + * incoming test structure information for + * later dispatch to the reporter. + * @package SimpleTest + * @subpackage UnitTester + */ + class NestingCaseTag extends NestingXmlTag { + + /** + * Sets the basic test information except + * the name. + * @param hash $attributes Name value pairs. + * @access public + */ + function NestingCaseTag($attributes) { + $this->NestingXmlTag($attributes); + } + + /** + * Signals the appropriate start event on the + * listener. + * @param SimpleReporter $listener Target for events. + * @access public + */ + function paintStart(&$listener) { + $listener->paintCaseStart($this->getName()); + } + + /** + * Signals the appropriate end event on the + * listener. + * @param SimpleReporter $listener Target for events. + * @access public + */ + function paintEnd(&$listener) { + $listener->paintCaseEnd($this->getName()); + } + } + + /** + * Accumulator for incoming group tag. Holds the + * incoming test structure information for + * later dispatch to the reporter. + * @package SimpleTest + * @subpackage UnitTester + */ + class NestingGroupTag extends NestingXmlTag { + + /** + * Sets the basic test information except + * the name. + * @param hash $attributes Name value pairs. + * @access public + */ + function NestingGroupTag($attributes) { + $this->NestingXmlTag($attributes); + } + + /** + * Signals the appropriate start event on the + * listener. + * @param SimpleReporter $listener Target for events. + * @access public + */ + function paintStart(&$listener) { + $listener->paintGroupStart($this->getName(), $this->getSize()); + } + + /** + * Signals the appropriate end event on the + * listener. + * @param SimpleReporter $listener Target for events. + * @access public + */ + function paintEnd(&$listener) { + $listener->paintGroupEnd($this->getName()); + } + + /** + * The size in the attributes. + * @return integer Value of size attribute or zero. + * @access public + */ + function getSize() { + $attributes = $this->_getAttributes(); + if (isset($attributes['SIZE'])) { + return (integer)$attributes['SIZE']; + } + return 0; + } + } + + /** + * Parser for importing the output of the XmlReporter. + * Dispatches that output to another reporter. + * @package SimpleTest + * @subpackage UnitTester + */ + class SimpleTestXmlParser { + var $_listener; + var $_expat; + var $_tag_stack; + var $_in_content_tag; + var $_content; + var $_attributes; + + /** + * Loads a listener with the SimpleReporter + * interface. + * @param SimpleReporter $listener Listener of tag events. + * @access public + */ + function SimpleTestXmlParser(&$listener) { + $this->_listener = &$listener; + $this->_expat = &$this->_createParser(); + $this->_tag_stack = array(); + $this->_in_content_tag = false; + $this->_content = ''; + $this->_attributes = array(); + } + + /** + * Parses a block of XML sending the results to + * the listener. + * @param string $chunk Block of text to read. + * @return boolean True if valid XML. + * @access public + */ + function parse($chunk) { + if (! xml_parse($this->_expat, $chunk)) { + trigger_error('XML parse error with ' . + xml_error_string(xml_get_error_code($this->_expat))); + return false; + } + return true; + } + + /** + * Sets up expat as the XML parser. + * @return resource Expat handle. + * @access protected + */ + function &_createParser() { + $expat = xml_parser_create(); + xml_set_object($expat, $this); + xml_set_element_handler($expat, '_startElement', '_endElement'); + xml_set_character_data_handler($expat, '_addContent'); + xml_set_default_handler($expat, '_default'); + return $expat; + } + + /** + * Opens a new test nesting level. + * @return NestedXmlTag The group, case or method tag + * to start. + * @access private + */ + function _pushNestingTag($nested) { + array_unshift($this->_tag_stack, $nested); + } + + /** + * Accessor for current test structure tag. + * @return NestedXmlTag The group, case or method tag + * being parsed. + * @access private + */ + function &_getCurrentNestingTag() { + return $this->_tag_stack[0]; + } + + /** + * Ends a nesting tag. + * @return NestedXmlTag The group, case or method tag + * just finished. + * @access private + */ + function _popNestingTag() { + return array_shift($this->_tag_stack); + } + + /** + * Test if tag is a leaf node with only text content. + * @param string $tag XML tag name. + * @return @boolean True if leaf, false if nesting. + * @private + */ + function _isLeaf($tag) { + return in_array($tag, array( + 'NAME', 'PASS', 'FAIL', 'EXCEPTION', 'SKIP', 'MESSAGE', 'FORMATTED', 'SIGNAL')); + } + + /** + * Handler for start of event element. + * @param resource $expat Parser handle. + * @param string $tag Element name. + * @param hash $attributes Name value pairs. + * Attributes without content + * are marked as true. + * @access protected + */ + function _startElement($expat, $tag, $attributes) { + $this->_attributes = $attributes; + if ($tag == 'GROUP') { + $this->_pushNestingTag(new NestingGroupTag($attributes)); + } elseif ($tag == 'CASE') { + $this->_pushNestingTag(new NestingCaseTag($attributes)); + } elseif ($tag == 'TEST') { + $this->_pushNestingTag(new NestingMethodTag($attributes)); + } elseif ($this->_isLeaf($tag)) { + $this->_in_content_tag = true; + $this->_content = ''; + } + } + + /** + * End of element event. + * @param resource $expat Parser handle. + * @param string $tag Element name. + * @access protected + */ + function _endElement($expat, $tag) { + $this->_in_content_tag = false; + if (in_array($tag, array('GROUP', 'CASE', 'TEST'))) { + $nesting_tag = $this->_popNestingTag(); + $nesting_tag->paintEnd($this->_listener); + } elseif ($tag == 'NAME') { + $nesting_tag = &$this->_getCurrentNestingTag(); + $nesting_tag->setName($this->_content); + $nesting_tag->paintStart($this->_listener); + } elseif ($tag == 'PASS') { + $this->_listener->paintPass($this->_content); + } elseif ($tag == 'FAIL') { + $this->_listener->paintFail($this->_content); + } elseif ($tag == 'EXCEPTION') { + $this->_listener->paintError($this->_content); + } elseif ($tag == 'SKIP') { + $this->_listener->paintSkip($this->_content); + } elseif ($tag == 'SIGNAL') { + $this->_listener->paintSignal( + $this->_attributes['TYPE'], + unserialize($this->_content)); + } elseif ($tag == 'MESSAGE') { + $this->_listener->paintMessage($this->_content); + } elseif ($tag == 'FORMATTED') { + $this->_listener->paintFormattedMessage($this->_content); + } + } + + /** + * Content between start and end elements. + * @param resource $expat Parser handle. + * @param string $text Usually output messages. + * @access protected + */ + function _addContent($expat, $text) { + if ($this->_in_content_tag) { + $this->_content .= $text; + } + return true; + } + + /** + * XML and Doctype handler. Discards all such content. + * @param resource $expat Parser handle. + * @param string $default Text of default content. + * @access protected + */ + function _default($expat, $default) { + } + } +?>
    +
    + +
    +
    + +

    + SimpleTest 1.0.1 beta release is the latest version. + It's very stable although PHP5 users will find it doesn't + run with E_STRICT : it's still fully PHP4 compatible. +

    +
    +
    + +

    + Familiar with unit testing ? Just dive directly into SimpleTest with + the one-page starter and + the complete API. +
    + Otherwise see the ongoing + documentation. +
    + And for example test cases check out the + tutorial. +

    +
    +
    + +

    + Need help on your testing strategy ? + Feel free to join the + SimpleTest support mailing-list. +

    +

    + If you need some new functionnality in SimpleTest, you may want to look at + the features tracker. + Also the bug and + patches trackers can be useful. +

    +
    +
    + + SourceForge.net Logo + +
    +
    +
    +
    +

    + SimpleTest v1.0.1beta is available for download. +

    +

    + The SimpleTest PHP unit tester + is available for download from your nearest + SourceForge. + It is a PHP unit test and web test framework. + Users of JUnit will be + familiar with most of the interface. + The JWebUnit + style functionality is more complete now. + It has support for SSL, forms, frames, proxies and basic authentication. + The current CVS code should become the 1.0.1 release real soon now and + includes file upload and many small improvements. + The idea is that common but fiddly PHP tasks, such as logging into a site, + can be tested easily. +

    +

    Screenshots

    +

    + Here's what the result of your first test would look like : +

    +

    + test with 1 pass +

    +

    + Well not quite. In true TDD fashion, you should see a failing test case : +

    +

    + test with 1 fail +

    +

    + You may also prefer doing your testing with the command-line : +

    +

    + test in cli +

    +

    Documentation

    +

    + While (still) very scattered around different sites, the SimpleTest documentation is quite dense and thorough. +

    + +

    + Other type of interesting stuff while starting out with Test Driven Development and SimpleTest include : +

    + +

    + A couple of books do use SimpleTest quite extensively : +

    + +

    Contributing

    +

    + For translators the documentation is available in XML format : + we're always please to add new languages to our code base. +

    +

    + And while we do try our best keeping this tool bug-free, detecting defects and + submitting failing test cases and/or patches can come very handy ! Interested ? + Drop by the mailing-list, + most things tend to happen there... +

    +
    +