From 55c4ac1bfe565f1ca7f537fdd8b7a201be28e581 Mon Sep 17 00:00:00 2001 From: xue <> Date: Thu, 10 Nov 2005 12:47:19 +0000 Subject: Initial import of prado framework --- .gitattributes | 190 +++ demos/controls/index.php | 8 + demos/controls/protected/application.xml | 21 + demos/controls/protected/pages/HomePage.php | 14 + demos/controls/protected/pages/HomePage.tpl | 12 + demos/controls/protected/pages/LoginPage.php | 15 + demos/controls/protected/pages/LoginPage.tpl | 6 + demos/controls/protected/pages/PlainPage.tpl | 1 + demos/controls/protected/pages/config.xml | 12 + .../protected/pages/private/MemberPage.php | 12 + .../protected/pages/private/MemberPage.tpl | 8 + demos/controls/protected/pages/private/config.xml | 10 + demos/images/fungii_logo.gif | Bin 0 -> 5473 bytes docs/conceptual-structure.vsd | Bin 0 -> 201728 bytes docs/request-sequence.vsd | Bin 0 -> 184832 bytes framework/.htaccess | 1 + framework/Collections/TList.php | 452 ++++++ framework/Collections/TMap.php | 384 +++++ framework/Data/TMemCache.php | 268 ++++ framework/Data/TSqliteCache.php | 277 ++++ framework/Data/TXmlDocument.php | 446 ++++++ framework/Exceptions/TErrorHandler.php | 48 + framework/Exceptions/TException.php | 175 +++ framework/Exceptions/messages.en | 28 + framework/IO/TTextWriter.php | 19 + framework/Security/TAuthManager.php | 205 +++ framework/Security/TAuthorizationRule.php | 213 +++ framework/Security/TMembershipManager.php | 109 ++ framework/Security/TStaticMembershipProvider.php | 324 +++++ framework/Security/TUserManager.php | 192 +++ framework/TApplication.php | 766 ++++++++++ framework/TComponent.php | 535 +++++++ framework/TODO.txt | 306 ++++ framework/Web/Javascripts/WebForms.js | 298 ++++ framework/Web/Services/TAssetService.php | 70 + framework/Web/Services/TPageService.php | 625 ++++++++ framework/Web/TCacheManager.php | 116 ++ framework/Web/THttpRequest.php | 824 +++++++++++ framework/Web/THttpResponse.php | 289 ++++ framework/Web/THttpSession.php | 504 +++++++ framework/Web/THttpUtility.php | 33 + framework/Web/UI/TClientScriptManager.php | 236 +++ framework/Web/UI/TControl.php | 1518 ++++++++++++++++++++ framework/Web/UI/TForm.php | 128 ++ .../Web/UI/THiddenFieldPageStatePersister.php | 59 + framework/Web/UI/THtmlTextWriter.php | 235 +++ framework/Web/UI/TPage.php | 617 ++++++++ framework/Web/UI/TPageStatePersister.php | 22 + framework/Web/UI/TPostBackOptions.php | 36 + framework/Web/UI/TTemplate.php | 494 +++++++ framework/Web/UI/TTemplateControl.php | 215 +++ framework/Web/UI/TTemplateManager.php | 66 + framework/Web/UI/TTheme.php | 64 + framework/Web/UI/WebControls/TButton.php | 291 ++++ framework/Web/UI/WebControls/TCheckBox.php | 399 +++++ framework/Web/UI/WebControls/TContent.php | 47 + .../Web/UI/WebControls/TContentPlaceHolder.php | 47 + framework/Web/UI/WebControls/TExpression.php | 61 + framework/Web/UI/WebControls/TFont.php | 276 ++++ framework/Web/UI/WebControls/THiddenField.php | 123 ++ framework/Web/UI/WebControls/THyperLink.php | 144 ++ framework/Web/UI/WebControls/TImage.php | 122 ++ framework/Web/UI/WebControls/TImageButton.php | 320 +++++ framework/Web/UI/WebControls/TLabel.php | 106 ++ framework/Web/UI/WebControls/TLiteral.php | 79 + framework/Web/UI/WebControls/TPanel.php | 162 +++ framework/Web/UI/WebControls/TPlaceHolder.php | 25 + framework/Web/UI/WebControls/TStatements.php | 61 + framework/Web/UI/WebControls/TStyle.php | 334 +++++ framework/Web/UI/WebControls/TTextBox.php | 444 ++++++ framework/Web/UI/WebControls/TWebControl.php | 368 +++++ framework/core.php | 735 ++++++++++ framework/prado.php | 56 + tests/UnitTests/TODO.txt | 5 + tests/UnitTests/framework/Collections/utList.php | 321 +++++ tests/UnitTests/framework/Collections/utMap.php | 245 ++++ tests/UnitTests/framework/Data/CacheTestCase.php | 98 ++ tests/UnitTests/framework/Data/utMemCache.php | 66 + tests/UnitTests/framework/Data/utSqliteCache.php | 59 + tests/UnitTests/framework/Data/utXmlDocument.php | 68 + tests/UnitTests/framework/Data/xml/data1.xml | 45 + tests/UnitTests/framework/Data/xml/data1.xml.out | 41 + tests/UnitTests/framework/Data/xml/data2.xml | 41 + tests/UnitTests/framework/Data/xml/data2.xml.out | 40 + tests/UnitTests/framework/Data/xml/data3.xml | 46 + tests/UnitTests/framework/Data/xml/data3.xml.out | 45 + .../framework/TestSystem/protected/application.xml | 21 + .../framework/TestSystem/protected/data/test.db | Bin 0 -> 5120 bytes .../TestSystem/protected/pages/config.xml | 12 + tests/UnitTests/framework/Web/UI/utControl.php | 420 ++++++ tests/UnitTests/framework/common.php | 26 + tests/UnitTests/framework/index.php | 100 ++ tests/UnitTests/framework/utApplication.php | 25 + tests/UnitTests/framework/utComponent.php | 224 +++ tests/UnitTests/framework/utPradoBase.php | 111 ++ tests/UnitTests/simpletest/CHANGELOG | 6 + .../simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE | 201 +++ .../simpletest/HtmlReporterWithCoverage.php | 268 ++++ tests/UnitTests/simpletest/LICENSE | 49 + tests/UnitTests/simpletest/README | 110 ++ tests/UnitTests/simpletest/VERSION | 1 + tests/UnitTests/simpletest/authentication.php | 219 +++ tests/UnitTests/simpletest/browser.php | 1016 +++++++++++++ .../docs/en/authentication_documentation.html | 320 +++++ .../simpletest/docs/en/browser_documentation.html | 386 +++++ tests/UnitTests/simpletest/docs/en/docs.css | 84 ++ .../docs/en/expectation_documentation.html | 356 +++++ .../docs/en/form_testing_documentation.html | 277 ++++ .../docs/en/group_test_documentation.html | 357 +++++ tests/UnitTests/simpletest/docs/en/index.html | 467 ++++++ .../docs/en/mock_objects_documentation.html | 713 +++++++++ tests/UnitTests/simpletest/docs/en/overview.html | 422 ++++++ .../docs/en/partial_mocks_documentation.html | 426 ++++++ .../simpletest/docs/en/reporter_documentation.html | 515 +++++++ .../docs/en/server_stubs_documentation.html | 388 +++++ .../docs/en/unit_test_documentation.html | 387 +++++ .../docs/en/web_tester_documentation.html | 508 +++++++ .../docs/fr/authentication_documentation.html | 264 ++++ .../simpletest/docs/fr/browser_documentation.html | 329 +++++ tests/UnitTests/simpletest/docs/fr/docs.css | 84 ++ .../docs/fr/expectation_documentation.html | 263 ++++ .../docs/fr/form_testing_documentation.html | 235 +++ .../docs/fr/group_test_documentation.html | 288 ++++ tests/UnitTests/simpletest/docs/fr/index.html | 343 +++++ .../docs/fr/mock_objects_documentation.html | 492 +++++++ tests/UnitTests/simpletest/docs/fr/overview.html | 294 ++++ .../docs/fr/partial_mocks_documentation.html | 333 +++++ .../simpletest/docs/fr/reporter_documentation.html | 386 +++++ .../docs/fr/server_stubs_documentation.html | 279 ++++ .../docs/fr/unit_test_documentation.html | 306 ++++ .../docs/fr/web_tester_documentation.html | 397 +++++ tests/UnitTests/simpletest/dumper.php | 380 +++++ tests/UnitTests/simpletest/encoding.php | 156 ++ tests/UnitTests/simpletest/errors.php | 141 ++ tests/UnitTests/simpletest/expectation.php | 568 ++++++++ .../simpletest/extensions/pear_test_case.php | 199 +++ .../simpletest/extensions/phpunit_test_case.php | 108 ++ tests/UnitTests/simpletest/form.php | 619 ++++++++ tests/UnitTests/simpletest/frames.php | 673 +++++++++ tests/UnitTests/simpletest/http.php | 853 +++++++++++ tests/UnitTests/simpletest/mock_objects.php | 1323 +++++++++++++++++ tests/UnitTests/simpletest/mytests/log_test.php | 18 + tests/UnitTests/simpletest/options.php | 366 +++++ tests/UnitTests/simpletest/page.php | 961 +++++++++++++ tests/UnitTests/simpletest/parser.php | 750 ++++++++++ tests/UnitTests/simpletest/remote.php | 115 ++ tests/UnitTests/simpletest/reporter.php | 241 ++++ tests/UnitTests/simpletest/runner.php | 300 ++++ tests/UnitTests/simpletest/scorer.php | 378 +++++ tests/UnitTests/simpletest/shell_tester.php | 271 ++++ tests/UnitTests/simpletest/simple_test.php | 553 +++++++ tests/UnitTests/simpletest/socket.php | 216 +++ tests/UnitTests/simpletest/tag.php | 1241 ++++++++++++++++ .../UnitTests/simpletest/test/acceptance_test.php | 1106 ++++++++++++++ tests/UnitTests/simpletest/test/adapter_test.php | 74 + tests/UnitTests/simpletest/test/all_tests.php | 31 + .../simpletest/test/authentication_test.php | 141 ++ tests/UnitTests/simpletest/test/browser_test.php | 870 +++++++++++ tests/UnitTests/simpletest/test/dumper_test.php | 87 ++ tests/UnitTests/simpletest/test/encoding_test.php | 134 ++ tests/UnitTests/simpletest/test/errors_test.php | 139 ++ .../UnitTests/simpletest/test/expectation_test.php | 282 ++++ tests/UnitTests/simpletest/test/form_test.php | 326 +++++ tests/UnitTests/simpletest/test/frames_test.php | 569 ++++++++ tests/UnitTests/simpletest/test/http_test.php | 567 ++++++++ tests/UnitTests/simpletest/test/live_test.php | 47 + tests/UnitTests/simpletest/test/options_test.php | 95 ++ tests/UnitTests/simpletest/test/page_test.php | 792 ++++++++++ .../UnitTests/simpletest/test/parse_error_test.php | 10 + tests/UnitTests/simpletest/test/parser_test.php | 648 +++++++++ .../UnitTests/simpletest/test/real_sites_test.php | 29 + tests/UnitTests/simpletest/test/remote_test.php | 17 + tests/UnitTests/simpletest/test/shell_test.php | 38 + .../simpletest/test/shell_tester_test.php | 37 + .../UnitTests/simpletest/test/simple_mock_test.php | 648 +++++++++ tests/UnitTests/simpletest/test/socket_test.php | 26 + tests/UnitTests/simpletest/test/tag_test.php | 462 ++++++ .../simpletest/test/test_with_parse_error.php | 8 + .../UnitTests/simpletest/test/unit_tester_test.php | 52 + tests/UnitTests/simpletest/test/unit_tests.php | 49 + tests/UnitTests/simpletest/test/url_test.php | 369 +++++ .../UnitTests/simpletest/test/user_agent_test.php | 546 +++++++ tests/UnitTests/simpletest/test/visual_test.php | 386 +++++ .../UnitTests/simpletest/test/web_tester_test.php | 133 ++ tests/UnitTests/simpletest/test/xml_test.php | 189 +++ tests/UnitTests/simpletest/unit_tester.php | 303 ++++ tests/UnitTests/simpletest/url.php | 508 +++++++ tests/UnitTests/simpletest/user_agent.php | 490 +++++++ tests/UnitTests/simpletest/web_tester.php | 1330 +++++++++++++++++ tests/UnitTests/simpletest/xml.php | 615 ++++++++ 190 files changed, 52117 insertions(+) create mode 100644 .gitattributes create mode 100644 demos/controls/index.php create mode 100644 demos/controls/protected/application.xml create mode 100644 demos/controls/protected/pages/HomePage.php create mode 100644 demos/controls/protected/pages/HomePage.tpl create mode 100644 demos/controls/protected/pages/LoginPage.php create mode 100644 demos/controls/protected/pages/LoginPage.tpl create mode 100644 demos/controls/protected/pages/PlainPage.tpl create mode 100644 demos/controls/protected/pages/config.xml create mode 100644 demos/controls/protected/pages/private/MemberPage.php create mode 100644 demos/controls/protected/pages/private/MemberPage.tpl create mode 100644 demos/controls/protected/pages/private/config.xml create mode 100644 demos/images/fungii_logo.gif create mode 100644 docs/conceptual-structure.vsd create mode 100644 docs/request-sequence.vsd create mode 100644 framework/.htaccess create mode 100644 framework/Collections/TList.php create mode 100644 framework/Collections/TMap.php create mode 100644 framework/Data/TMemCache.php create mode 100644 framework/Data/TSqliteCache.php create mode 100644 framework/Data/TXmlDocument.php create mode 100644 framework/Exceptions/TErrorHandler.php create mode 100644 framework/Exceptions/TException.php create mode 100644 framework/Exceptions/messages.en create mode 100644 framework/IO/TTextWriter.php create mode 100644 framework/Security/TAuthManager.php create mode 100644 framework/Security/TAuthorizationRule.php create mode 100644 framework/Security/TMembershipManager.php create mode 100644 framework/Security/TStaticMembershipProvider.php create mode 100644 framework/Security/TUserManager.php create mode 100644 framework/TApplication.php create mode 100644 framework/TComponent.php create mode 100644 framework/TODO.txt create mode 100644 framework/Web/Javascripts/WebForms.js create mode 100644 framework/Web/Services/TAssetService.php create mode 100644 framework/Web/Services/TPageService.php create mode 100644 framework/Web/TCacheManager.php create mode 100644 framework/Web/THttpRequest.php create mode 100644 framework/Web/THttpResponse.php create mode 100644 framework/Web/THttpSession.php create mode 100644 framework/Web/THttpUtility.php create mode 100644 framework/Web/UI/TClientScriptManager.php create mode 100644 framework/Web/UI/TControl.php create mode 100644 framework/Web/UI/TForm.php create mode 100644 framework/Web/UI/THiddenFieldPageStatePersister.php create mode 100644 framework/Web/UI/THtmlTextWriter.php create mode 100644 framework/Web/UI/TPage.php create mode 100644 framework/Web/UI/TPageStatePersister.php create mode 100644 framework/Web/UI/TPostBackOptions.php create mode 100644 framework/Web/UI/TTemplate.php create mode 100644 framework/Web/UI/TTemplateControl.php create mode 100644 framework/Web/UI/TTemplateManager.php create mode 100644 framework/Web/UI/TTheme.php create mode 100644 framework/Web/UI/WebControls/TButton.php create mode 100644 framework/Web/UI/WebControls/TCheckBox.php create mode 100644 framework/Web/UI/WebControls/TContent.php create mode 100644 framework/Web/UI/WebControls/TContentPlaceHolder.php create mode 100644 framework/Web/UI/WebControls/TExpression.php create mode 100644 framework/Web/UI/WebControls/TFont.php create mode 100644 framework/Web/UI/WebControls/THiddenField.php create mode 100644 framework/Web/UI/WebControls/THyperLink.php create mode 100644 framework/Web/UI/WebControls/TImage.php create mode 100644 framework/Web/UI/WebControls/TImageButton.php create mode 100644 framework/Web/UI/WebControls/TLabel.php create mode 100644 framework/Web/UI/WebControls/TLiteral.php create mode 100644 framework/Web/UI/WebControls/TPanel.php create mode 100644 framework/Web/UI/WebControls/TPlaceHolder.php create mode 100644 framework/Web/UI/WebControls/TStatements.php create mode 100644 framework/Web/UI/WebControls/TStyle.php create mode 100644 framework/Web/UI/WebControls/TTextBox.php create mode 100644 framework/Web/UI/WebControls/TWebControl.php create mode 100644 framework/core.php create mode 100644 framework/prado.php create mode 100644 tests/UnitTests/TODO.txt create mode 100644 tests/UnitTests/framework/Collections/utList.php create mode 100644 tests/UnitTests/framework/Collections/utMap.php create mode 100644 tests/UnitTests/framework/Data/CacheTestCase.php create mode 100644 tests/UnitTests/framework/Data/utMemCache.php create mode 100644 tests/UnitTests/framework/Data/utSqliteCache.php create mode 100644 tests/UnitTests/framework/Data/utXmlDocument.php create mode 100644 tests/UnitTests/framework/Data/xml/data1.xml create mode 100644 tests/UnitTests/framework/Data/xml/data1.xml.out create mode 100644 tests/UnitTests/framework/Data/xml/data2.xml create mode 100644 tests/UnitTests/framework/Data/xml/data2.xml.out create mode 100644 tests/UnitTests/framework/Data/xml/data3.xml create mode 100644 tests/UnitTests/framework/Data/xml/data3.xml.out create mode 100644 tests/UnitTests/framework/TestSystem/protected/application.xml create mode 100644 tests/UnitTests/framework/TestSystem/protected/data/test.db create mode 100644 tests/UnitTests/framework/TestSystem/protected/pages/config.xml create mode 100644 tests/UnitTests/framework/Web/UI/utControl.php create mode 100644 tests/UnitTests/framework/common.php create mode 100644 tests/UnitTests/framework/index.php create mode 100644 tests/UnitTests/framework/utApplication.php create mode 100644 tests/UnitTests/framework/utComponent.php create mode 100644 tests/UnitTests/framework/utPradoBase.php create mode 100644 tests/UnitTests/simpletest/CHANGELOG create mode 100644 tests/UnitTests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE create mode 100644 tests/UnitTests/simpletest/HtmlReporterWithCoverage.php create mode 100644 tests/UnitTests/simpletest/LICENSE create mode 100644 tests/UnitTests/simpletest/README create mode 100644 tests/UnitTests/simpletest/VERSION create mode 100644 tests/UnitTests/simpletest/authentication.php create mode 100644 tests/UnitTests/simpletest/browser.php create mode 100644 tests/UnitTests/simpletest/docs/en/authentication_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/en/browser_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/en/docs.css create mode 100644 tests/UnitTests/simpletest/docs/en/expectation_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/en/form_testing_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/en/group_test_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/en/index.html create mode 100644 tests/UnitTests/simpletest/docs/en/mock_objects_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/en/overview.html create mode 100644 tests/UnitTests/simpletest/docs/en/partial_mocks_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/en/reporter_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/en/server_stubs_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/en/unit_test_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/en/web_tester_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/fr/authentication_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/fr/browser_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/fr/docs.css create mode 100644 tests/UnitTests/simpletest/docs/fr/expectation_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/fr/form_testing_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/fr/group_test_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/fr/index.html create mode 100644 tests/UnitTests/simpletest/docs/fr/mock_objects_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/fr/overview.html create mode 100644 tests/UnitTests/simpletest/docs/fr/partial_mocks_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/fr/reporter_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/fr/server_stubs_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/fr/unit_test_documentation.html create mode 100644 tests/UnitTests/simpletest/docs/fr/web_tester_documentation.html create mode 100644 tests/UnitTests/simpletest/dumper.php create mode 100644 tests/UnitTests/simpletest/encoding.php create mode 100644 tests/UnitTests/simpletest/errors.php create mode 100644 tests/UnitTests/simpletest/expectation.php create mode 100644 tests/UnitTests/simpletest/extensions/pear_test_case.php create mode 100644 tests/UnitTests/simpletest/extensions/phpunit_test_case.php create mode 100644 tests/UnitTests/simpletest/form.php create mode 100644 tests/UnitTests/simpletest/frames.php create mode 100644 tests/UnitTests/simpletest/http.php create mode 100644 tests/UnitTests/simpletest/mock_objects.php create mode 100644 tests/UnitTests/simpletest/mytests/log_test.php create mode 100644 tests/UnitTests/simpletest/options.php create mode 100644 tests/UnitTests/simpletest/page.php create mode 100644 tests/UnitTests/simpletest/parser.php create mode 100644 tests/UnitTests/simpletest/remote.php create mode 100644 tests/UnitTests/simpletest/reporter.php create mode 100644 tests/UnitTests/simpletest/runner.php create mode 100644 tests/UnitTests/simpletest/scorer.php create mode 100644 tests/UnitTests/simpletest/shell_tester.php create mode 100644 tests/UnitTests/simpletest/simple_test.php create mode 100644 tests/UnitTests/simpletest/socket.php create mode 100644 tests/UnitTests/simpletest/tag.php create mode 100644 tests/UnitTests/simpletest/test/acceptance_test.php create mode 100644 tests/UnitTests/simpletest/test/adapter_test.php create mode 100644 tests/UnitTests/simpletest/test/all_tests.php create mode 100644 tests/UnitTests/simpletest/test/authentication_test.php create mode 100644 tests/UnitTests/simpletest/test/browser_test.php create mode 100644 tests/UnitTests/simpletest/test/dumper_test.php create mode 100644 tests/UnitTests/simpletest/test/encoding_test.php create mode 100644 tests/UnitTests/simpletest/test/errors_test.php create mode 100644 tests/UnitTests/simpletest/test/expectation_test.php create mode 100644 tests/UnitTests/simpletest/test/form_test.php create mode 100644 tests/UnitTests/simpletest/test/frames_test.php create mode 100644 tests/UnitTests/simpletest/test/http_test.php create mode 100644 tests/UnitTests/simpletest/test/live_test.php create mode 100644 tests/UnitTests/simpletest/test/options_test.php create mode 100644 tests/UnitTests/simpletest/test/page_test.php create mode 100644 tests/UnitTests/simpletest/test/parse_error_test.php create mode 100644 tests/UnitTests/simpletest/test/parser_test.php create mode 100644 tests/UnitTests/simpletest/test/real_sites_test.php create mode 100644 tests/UnitTests/simpletest/test/remote_test.php create mode 100644 tests/UnitTests/simpletest/test/shell_test.php create mode 100644 tests/UnitTests/simpletest/test/shell_tester_test.php create mode 100644 tests/UnitTests/simpletest/test/simple_mock_test.php create mode 100644 tests/UnitTests/simpletest/test/socket_test.php create mode 100644 tests/UnitTests/simpletest/test/tag_test.php create mode 100644 tests/UnitTests/simpletest/test/test_with_parse_error.php create mode 100644 tests/UnitTests/simpletest/test/unit_tester_test.php create mode 100644 tests/UnitTests/simpletest/test/unit_tests.php create mode 100644 tests/UnitTests/simpletest/test/url_test.php create mode 100644 tests/UnitTests/simpletest/test/user_agent_test.php create mode 100644 tests/UnitTests/simpletest/test/visual_test.php create mode 100644 tests/UnitTests/simpletest/test/web_tester_test.php create mode 100644 tests/UnitTests/simpletest/test/xml_test.php create mode 100644 tests/UnitTests/simpletest/unit_tester.php create mode 100644 tests/UnitTests/simpletest/url.php create mode 100644 tests/UnitTests/simpletest/user_agent.php create mode 100644 tests/UnitTests/simpletest/web_tester.php create mode 100644 tests/UnitTests/simpletest/xml.php diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..bdbd62cf --- /dev/null +++ b/.gitattributes @@ -0,0 +1,190 @@ +* text=auto !eol +demos/controls/index.php -text +demos/controls/protected/application.xml -text +demos/controls/protected/pages/HomePage.php -text +demos/controls/protected/pages/HomePage.tpl -text +demos/controls/protected/pages/LoginPage.php -text +demos/controls/protected/pages/LoginPage.tpl -text +demos/controls/protected/pages/PlainPage.tpl -text +demos/controls/protected/pages/config.xml -text +demos/controls/protected/pages/private/MemberPage.php -text +demos/controls/protected/pages/private/MemberPage.tpl -text +demos/controls/protected/pages/private/config.xml -text +demos/images/fungii_logo.gif -text +docs/conceptual-structure.vsd -text +docs/request-sequence.vsd -text +framework/.htaccess -text +framework/Collections/TList.php -text +framework/Collections/TMap.php -text +framework/Data/TMemCache.php -text +framework/Data/TSqliteCache.php -text +framework/Data/TXmlDocument.php -text +framework/Exceptions/TErrorHandler.php -text +framework/Exceptions/TException.php -text +framework/Exceptions/messages.en -text +framework/IO/TTextWriter.php -text +framework/Security/TAuthManager.php -text +framework/Security/TAuthorizationRule.php -text +framework/Security/TMembershipManager.php -text +framework/Security/TStaticMembershipProvider.php -text +framework/Security/TUserManager.php -text +framework/TApplication.php -text +framework/TComponent.php -text +framework/TODO.txt -text +framework/Web/Javascripts/WebForms.js -text +framework/Web/Services/TAssetService.php -text +framework/Web/Services/TPageService.php -text +framework/Web/TCacheManager.php -text +framework/Web/THttpRequest.php -text +framework/Web/THttpResponse.php -text +framework/Web/THttpSession.php -text +framework/Web/THttpUtility.php -text +framework/Web/UI/TClientScriptManager.php -text +framework/Web/UI/TControl.php -text +framework/Web/UI/TForm.php -text +framework/Web/UI/THiddenFieldPageStatePersister.php -text +framework/Web/UI/THtmlTextWriter.php -text +framework/Web/UI/TPage.php -text +framework/Web/UI/TPageStatePersister.php -text +framework/Web/UI/TPostBackOptions.php -text +framework/Web/UI/TTemplate.php -text +framework/Web/UI/TTemplateControl.php -text +framework/Web/UI/TTemplateManager.php -text +framework/Web/UI/TTheme.php -text +framework/Web/UI/WebControls/TButton.php -text +framework/Web/UI/WebControls/TCheckBox.php -text +framework/Web/UI/WebControls/TContent.php -text +framework/Web/UI/WebControls/TContentPlaceHolder.php -text +framework/Web/UI/WebControls/TExpression.php -text +framework/Web/UI/WebControls/TFont.php -text +framework/Web/UI/WebControls/THiddenField.php -text +framework/Web/UI/WebControls/THyperLink.php -text +framework/Web/UI/WebControls/TImage.php -text +framework/Web/UI/WebControls/TImageButton.php -text +framework/Web/UI/WebControls/TLabel.php -text +framework/Web/UI/WebControls/TLiteral.php -text +framework/Web/UI/WebControls/TPanel.php -text +framework/Web/UI/WebControls/TPlaceHolder.php -text +framework/Web/UI/WebControls/TStatements.php -text +framework/Web/UI/WebControls/TStyle.php -text +framework/Web/UI/WebControls/TTextBox.php -text +framework/Web/UI/WebControls/TWebControl.php -text +framework/core.php -text +framework/prado.php -text +tests/UnitTests/TODO.txt -text +tests/UnitTests/framework/Collections/utList.php -text +tests/UnitTests/framework/Collections/utMap.php -text +tests/UnitTests/framework/Data/CacheTestCase.php -text +tests/UnitTests/framework/Data/utMemCache.php -text +tests/UnitTests/framework/Data/utSqliteCache.php -text +tests/UnitTests/framework/Data/utXmlDocument.php -text +tests/UnitTests/framework/Data/xml/data1.xml -text +tests/UnitTests/framework/Data/xml/data1.xml.out -text +tests/UnitTests/framework/Data/xml/data2.xml -text +tests/UnitTests/framework/Data/xml/data2.xml.out -text +tests/UnitTests/framework/Data/xml/data3.xml -text +tests/UnitTests/framework/Data/xml/data3.xml.out -text +tests/UnitTests/framework/TestSystem/protected/application.xml -text +tests/UnitTests/framework/TestSystem/protected/data/test.db -text +tests/UnitTests/framework/TestSystem/protected/pages/config.xml -text +tests/UnitTests/framework/Web/UI/utControl.php -text +tests/UnitTests/framework/common.php -text +tests/UnitTests/framework/index.php -text +tests/UnitTests/framework/utApplication.php -text +tests/UnitTests/framework/utComponent.php -text +tests/UnitTests/framework/utPradoBase.php -text +tests/UnitTests/simpletest/CHANGELOG -text +tests/UnitTests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE -text +tests/UnitTests/simpletest/HtmlReporterWithCoverage.php -text +tests/UnitTests/simpletest/LICENSE -text +tests/UnitTests/simpletest/README -text +tests/UnitTests/simpletest/VERSION -text +tests/UnitTests/simpletest/authentication.php -text +tests/UnitTests/simpletest/browser.php -text +tests/UnitTests/simpletest/docs/en/authentication_documentation.html -text +tests/UnitTests/simpletest/docs/en/browser_documentation.html -text +tests/UnitTests/simpletest/docs/en/docs.css -text +tests/UnitTests/simpletest/docs/en/expectation_documentation.html -text +tests/UnitTests/simpletest/docs/en/form_testing_documentation.html -text +tests/UnitTests/simpletest/docs/en/group_test_documentation.html -text +tests/UnitTests/simpletest/docs/en/index.html -text +tests/UnitTests/simpletest/docs/en/mock_objects_documentation.html -text +tests/UnitTests/simpletest/docs/en/overview.html -text +tests/UnitTests/simpletest/docs/en/partial_mocks_documentation.html -text +tests/UnitTests/simpletest/docs/en/reporter_documentation.html -text +tests/UnitTests/simpletest/docs/en/server_stubs_documentation.html -text +tests/UnitTests/simpletest/docs/en/unit_test_documentation.html -text +tests/UnitTests/simpletest/docs/en/web_tester_documentation.html -text +tests/UnitTests/simpletest/docs/fr/authentication_documentation.html -text +tests/UnitTests/simpletest/docs/fr/browser_documentation.html -text +tests/UnitTests/simpletest/docs/fr/docs.css -text +tests/UnitTests/simpletest/docs/fr/expectation_documentation.html -text +tests/UnitTests/simpletest/docs/fr/form_testing_documentation.html -text +tests/UnitTests/simpletest/docs/fr/group_test_documentation.html -text +tests/UnitTests/simpletest/docs/fr/index.html -text +tests/UnitTests/simpletest/docs/fr/mock_objects_documentation.html -text +tests/UnitTests/simpletest/docs/fr/overview.html -text +tests/UnitTests/simpletest/docs/fr/partial_mocks_documentation.html -text +tests/UnitTests/simpletest/docs/fr/reporter_documentation.html -text +tests/UnitTests/simpletest/docs/fr/server_stubs_documentation.html -text +tests/UnitTests/simpletest/docs/fr/unit_test_documentation.html -text +tests/UnitTests/simpletest/docs/fr/web_tester_documentation.html -text +tests/UnitTests/simpletest/dumper.php -text +tests/UnitTests/simpletest/encoding.php -text +tests/UnitTests/simpletest/errors.php -text +tests/UnitTests/simpletest/expectation.php -text +tests/UnitTests/simpletest/extensions/pear_test_case.php -text +tests/UnitTests/simpletest/extensions/phpunit_test_case.php -text +tests/UnitTests/simpletest/form.php -text +tests/UnitTests/simpletest/frames.php -text +tests/UnitTests/simpletest/http.php -text +tests/UnitTests/simpletest/mock_objects.php -text +tests/UnitTests/simpletest/mytests/log_test.php -text +tests/UnitTests/simpletest/options.php -text +tests/UnitTests/simpletest/page.php -text +tests/UnitTests/simpletest/parser.php -text +tests/UnitTests/simpletest/remote.php -text +tests/UnitTests/simpletest/reporter.php -text +tests/UnitTests/simpletest/runner.php -text +tests/UnitTests/simpletest/scorer.php -text +tests/UnitTests/simpletest/shell_tester.php -text +tests/UnitTests/simpletest/simple_test.php -text +tests/UnitTests/simpletest/socket.php -text +tests/UnitTests/simpletest/tag.php -text +tests/UnitTests/simpletest/test/acceptance_test.php -text +tests/UnitTests/simpletest/test/adapter_test.php -text +tests/UnitTests/simpletest/test/all_tests.php -text +tests/UnitTests/simpletest/test/authentication_test.php -text +tests/UnitTests/simpletest/test/browser_test.php -text +tests/UnitTests/simpletest/test/dumper_test.php -text +tests/UnitTests/simpletest/test/encoding_test.php -text +tests/UnitTests/simpletest/test/errors_test.php -text +tests/UnitTests/simpletest/test/expectation_test.php -text +tests/UnitTests/simpletest/test/form_test.php -text +tests/UnitTests/simpletest/test/frames_test.php -text +tests/UnitTests/simpletest/test/http_test.php -text +tests/UnitTests/simpletest/test/live_test.php -text +tests/UnitTests/simpletest/test/options_test.php -text +tests/UnitTests/simpletest/test/page_test.php -text +tests/UnitTests/simpletest/test/parse_error_test.php -text +tests/UnitTests/simpletest/test/parser_test.php -text +tests/UnitTests/simpletest/test/real_sites_test.php -text +tests/UnitTests/simpletest/test/remote_test.php -text +tests/UnitTests/simpletest/test/shell_test.php -text +tests/UnitTests/simpletest/test/shell_tester_test.php -text +tests/UnitTests/simpletest/test/simple_mock_test.php -text +tests/UnitTests/simpletest/test/socket_test.php -text +tests/UnitTests/simpletest/test/tag_test.php -text +tests/UnitTests/simpletest/test/test_with_parse_error.php -text +tests/UnitTests/simpletest/test/unit_tester_test.php -text +tests/UnitTests/simpletest/test/unit_tests.php -text +tests/UnitTests/simpletest/test/url_test.php -text +tests/UnitTests/simpletest/test/user_agent_test.php -text +tests/UnitTests/simpletest/test/visual_test.php -text +tests/UnitTests/simpletest/test/web_tester_test.php -text +tests/UnitTests/simpletest/test/xml_test.php -text +tests/UnitTests/simpletest/unit_tester.php -text +tests/UnitTests/simpletest/url.php -text +tests/UnitTests/simpletest/user_agent.php -text +tests/UnitTests/simpletest/web_tester.php -text +tests/UnitTests/simpletest/xml.php -text diff --git a/demos/controls/index.php b/demos/controls/index.php new file mode 100644 index 00000000..2349623f --- /dev/null +++ b/demos/controls/index.php @@ -0,0 +1,8 @@ +run(); + +?> \ No newline at end of file diff --git a/demos/controls/protected/application.xml b/demos/controls/protected/application.xml new file mode 100644 index 00000000..6211399b --- /dev/null +++ b/demos/controls/protected/application.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/demos/controls/protected/pages/HomePage.php b/demos/controls/protected/pages/HomePage.php new file mode 100644 index 00000000..4cfc3b0a --- /dev/null +++ b/demos/controls/protected/pages/HomePage.php @@ -0,0 +1,14 @@ +BackColor==='') + $sender->BackColor='blue'; + else + $sender->BackColor=''; + } +} + +?> \ No newline at end of file diff --git a/demos/controls/protected/pages/HomePage.tpl b/demos/controls/protected/pages/HomePage.tpl new file mode 100644 index 00000000..fdef6fdd --- /dev/null +++ b/demos/controls/protected/pages/HomePage.tpl @@ -0,0 +1,12 @@ + + + + +
+ (requires membership)
+
+ +
+ | + +
\ No newline at end of file diff --git a/demos/controls/protected/pages/LoginPage.php b/demos/controls/protected/pages/LoginPage.php new file mode 100644 index 00000000..3a3b8432 --- /dev/null +++ b/demos/controls/protected/pages/LoginPage.php @@ -0,0 +1,15 @@ +Application->AuthManager; + if($manager->login($this->username->Text,$this->password->Text)) + $this->Application->Response->redirect($this->Application->Request->Items['ReturnUrl']); + else + $this->error->Text='login failed'; + } +} + +?> \ No newline at end of file diff --git a/demos/controls/protected/pages/LoginPage.tpl b/demos/controls/protected/pages/LoginPage.tpl new file mode 100644 index 00000000..cbbd683b --- /dev/null +++ b/demos/controls/protected/pages/LoginPage.tpl @@ -0,0 +1,6 @@ + +Username:
+Password:
+ + +
\ No newline at end of file diff --git a/demos/controls/protected/pages/PlainPage.tpl b/demos/controls/protected/pages/PlainPage.tpl new file mode 100644 index 00000000..7591d700 --- /dev/null +++ b/demos/controls/protected/pages/PlainPage.tpl @@ -0,0 +1 @@ +This is a page without explicitly defined page class. \ No newline at end of file diff --git a/demos/controls/protected/pages/config.xml b/demos/controls/protected/pages/config.xml new file mode 100644 index 00000000..224a058c --- /dev/null +++ b/demos/controls/protected/pages/config.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/demos/controls/protected/pages/private/MemberPage.php b/demos/controls/protected/pages/private/MemberPage.php new file mode 100644 index 00000000..61fd113d --- /dev/null +++ b/demos/controls/protected/pages/private/MemberPage.php @@ -0,0 +1,12 @@ +Application->AuthManager->logout(); + $this->Application->Response->redirect($this->Application->Service->constructUrl('home')); + } +} + +?> \ No newline at end of file diff --git a/demos/controls/protected/pages/private/MemberPage.tpl b/demos/controls/protected/pages/private/MemberPage.tpl new file mode 100644 index 00000000..cf92f22c --- /dev/null +++ b/demos/controls/protected/pages/private/MemberPage.tpl @@ -0,0 +1,8 @@ + +Congratulations, Application->User->Name%> />!
+<%= + $this->Application->User->Name; +%> +You have reached this member-only area. + +
\ No newline at end of file diff --git a/demos/controls/protected/pages/private/config.xml b/demos/controls/protected/pages/private/config.xml new file mode 100644 index 00000000..ecfb6b00 --- /dev/null +++ b/demos/controls/protected/pages/private/config.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/demos/images/fungii_logo.gif b/demos/images/fungii_logo.gif new file mode 100644 index 00000000..b667c73e Binary files /dev/null and b/demos/images/fungii_logo.gif differ diff --git a/docs/conceptual-structure.vsd b/docs/conceptual-structure.vsd new file mode 100644 index 00000000..4418b646 Binary files /dev/null and b/docs/conceptual-structure.vsd differ diff --git a/docs/request-sequence.vsd b/docs/request-sequence.vsd new file mode 100644 index 00000000..579366cb Binary files /dev/null and b/docs/request-sequence.vsd differ diff --git a/framework/.htaccess b/framework/.htaccess new file mode 100644 index 00000000..e0198322 --- /dev/null +++ b/framework/.htaccess @@ -0,0 +1 @@ +deny from all diff --git a/framework/Collections/TList.php b/framework/Collections/TList.php new file mode 100644 index 00000000..09d9516b --- /dev/null +++ b/framework/Collections/TList.php @@ -0,0 +1,452 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Collections + */ + +/** + * TList class + * + * TList implements an integer-indexed collection class. + * + * You can access, append, insert, remove an item by using + * {@link itemAt}, {@link add}, {@link addAt}, {@link remove}, and {@link removeAt}. + * To get the number of the items in the list, use {@link getCount}. + * TList can also be used like a regular array as follows, + * + * $list[]=$item; // append at the end + * $list[$index]=$item; // $index must be between 0 and $list->Count + * unset($list[$index]); // remove the item at $index + * if(isset($list[$index])) // if the list has an item at $index + * foreach($list as $index=>$item) // traverse each item in the list + * + * Note, count($list) will always return 1. You should use {@link getCount()} + * to determine the number of items in the list. + * + * To extend TList by doing additional operations with each added or removed item, + * you can override {@link addedItem} and {@link removedItem}. + * You can also override {@link canAddItem} and {@link canRemoveItem} to + * control whether to add or remove a particular item. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Collections + * @since 3.0 + */ +class TList extends TComponent implements IteratorAggregate,ArrayAccess +{ + /** + * internal data storage + * @var array + */ + private $_d=array(); + /** + * number of items + * @var integer + */ + private $_c=0; + + /** + * Constructor. + * Initializes the list with an array or an iterable object. + * @param array|Iterator the intial data. Default is null, meaning no initialization. + * @throws TInvalidDataTypeException If data is not null and neither an array nor an iterator. + */ + public function __construct($data=null) + { + parent::__construct(); + if($data!==null) + $this->copyFrom($data); + } + + /** + * Returns an iterator for traversing the items in the list. + * This method is required by the interface IteratorAggregate. + * @return Iterator an iterator for traversing the items in the list. + */ + public function getIterator() + { + return new TListIterator($this->_d); + } + + /** + * @return integer the number of items in the list + */ + public function getCount() + { + return $this->_c; + } + + /** + * Returns the item at the specified offset. + * This method is exactly the same as {@link offsetGet}. + * @param integer the index of the item + * @return mixed the item at the index + * @throws TIndexOutOfRangeException if the index is out of the range + */ + public function itemAt($index) + { + if(isset($this->_d[$index])) + return $this->_d[$index]; + else + throw new TIndexOutOfRangeException('list_index_invalid',$index); + } + + /** + * Appends an item at the end of the list. + * @param mixed new item + * @throws TInvalidOperationException If the item is not allowed to be added + */ + public function add($item) + { + if($this->canAddItem($item)) + { + $this->_d[$this->_c++]=$item; + $this->addedItem($item); + } + else + throw new TInvalidOperationException('list_addition_disallowed'); + } + + /** + * Inserts an item at the specified position. + * Original item at the position and the next items + * will be moved one step towards the end. + * @param integer the speicified position. + * @param mixed new item + * @throws TIndexOutOfRangeException If the index specified exceeds the bound + * @throws TInvalidOperationException If the item is not allowed to be added + */ + public function addAt($index,$item) + { + if($this->canAddItem($item)) + { + if($index===$this->_c) + $this->add($item); + else if($index>=0 && $index<$this->_c) + { + array_splice($this->_d,$index,0,array($item)); + $this->_c++; + $this->addedItem($item); + } + else + throw new TIndexOutOfRangeException('list_index_invalid',$index); + } + else + throw new TInvalidOperationException('list_addition_disallowed'); + + } + + /** + * Removes an item from the list. + * The list will first search for the item. + * The first item found will be removed from the list. + * @param mixed the item to be removed. + * @throws TInvalidOperationException If the item cannot be removed + * @throws TInvalidDataValueException If the item does not exist + */ + public function remove($item) + { + if(($index=$this->indexOf($item))>=0) + { + if($this->canRemoveItem($item)) + $this->removeAt($index); + else + throw new TInvalidOperationException('list_item_unremovable'); + } + else + throw new TInvalidDataValueException('list_item_inexistent'); + } + + /** + * Removes an item at the specified position. + * @param integer the index of the item to be removed. + * @return mixed the removed item. + * @throws TOutOfRangeException If the index specified exceeds the bound + * @throws TInvalidOperationException If the item cannot be removed + */ + public function removeAt($index) + { + if(isset($this->_d[$index])) + { + $item=$this->_d[$index]; + if($this->canRemoveItem($item)) + { + if($index===$this->_c-1) + unset($this->_d[$index]); + else + array_splice($this->_d,$index,1); + $this->_c--; + $this->removedItem($item); + return $item; + } + else + throw new TInvalidOperationException('list_item_unremovable'); + } + else + throw new TIndexOutOfRangeException('list_index_invalid',$index); + } + + /** + * Removes all items in the list. + */ + public function clear() + { + for($i=$this->_c-1;$i>=0;--$i) + $this->removeAt($i); + } + + /** + * @param mixed the item + * @return boolean whether the list contains the item + */ + public function contains($item) + { + return $this->indexOf($item)>=0; + } + + /** + * @param mixed the item + * @return integer the index of the item in the list (0 based), -1 if not found. + */ + public function indexOf($item) + { + if(($index=array_search($item,$this->_d,true))===false) + return -1; + else + return $index; + } + + /** + * @return array the list of items in array + */ + public function toArray() + { + return $this->_d; + } + + /** + * Copies iterable data into the list. + * Note, existing data in the list will be cleared first. + * @param mixed the data to be copied from, must be an array or object implementing Traversable + * @throws TInvalidDataTypeException If data is neither an array nor a Traversable. + */ + public function copyFrom($data) + { + if(is_array($data) || ($data instanceof Traversable)) + { + if($this->_c>0) + $this->clear(); + foreach($data as $item) + $this->add($item); + } + else + throw new TInvalidDataTypeException('list_data_not_iterable'); + } + + /** + * Merges iterable data into the map. + * New data will be appended to the end of the existing data. + * @param mixed the data to be merged with, must be an array or object implementing Traversable + * @throws TInvalidDataTypeException If data is neither an array nor an iterator. + */ + public function mergeWith($data) + { + if(is_array($data) || ($data instanceof Traversable)) + { + foreach($data as $item) + $this->add($item); + } + else + throw new TInvalidDataTypeException('list_data_not_iterable'); + } + + /** + * Returns whether there is an item at the specified offset. + * This method is required by the interface ArrayAccess. + * @param integer the offset to check on + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->_d[$offset]); + } + + /** + * Returns the item at the specified offset. + * This method is required by the interface ArrayAccess. + * @param integer the offset to retrieve item. + * @return mixed the item at the offset + * @throws TIndexOutOfRangeException if the offset is invalid + */ + public function offsetGet($offset) + { + if(isset($this->_d[$offset])) + return $this->_d[$offset]; + else + throw new TIndexOutOfRangeException('list_index_invalid',$offset); + } + + /** + * Sets the item at the specified offset. + * This method is required by the interface ArrayAccess. + * @param integer the offset to set item + * @param mixed the item value + * @throws TOutOfRangeException If the index specified exceeds the bound + */ + public function offsetSet($offset,$item) + { + if($offset===null || $offset===$this->_c) + $this->add($item); + else + { + $this->removeAt($offset); + $this->addAt($offset,$item); + } + } + + /** + * Unsets the item at the specified offset. + * This method is required by the interface ArrayAccess. + * @param integer the offset to unset item + * @throws TOutOfRangeException If the index specified exceeds the bound + */ + public function offsetUnset($offset) + { + $this->removeAt($offset); + } + + /** + * This method is invoked after an item is successfully added to the list. + * You can override this method to provide customized processing of the addition. + * @param mixed the newly added item + */ + protected function addedItem($item) + { + } + + /** + * This method is invoked after an item is successfully removed from the list. + * You can override this method to provide customized processing of the removal. + * @param mixed the removed item + */ + protected function removedItem($item) + { + } + + /** + * This method is invoked before adding an item to the list. + * If it returns true, the item will be added to the list, otherwise not. + * You can override this method to decide whether a specific can be added. + * @param mixed item to be added + * @return boolean whether the item can be added to the list + */ + protected function canAddItem($item) + { + return true; + } + + /** + * This method is invoked before removing an item from the list. + * If it returns true, the item will be removed from the list, otherwise not. + * You can override this method to decide whether a specific can be removed. + * @param mixed item to be removed + * @return boolean whether the item can be removed to the list + */ + protected function canRemoveItem($item) + { + return true; + } +} + + +/** + * TListIterator class + * + * TListIterator implements Iterator interface. + * + * TListIterator is used by TList. It allows TList to return a new iterator + * for traversing the items in the list. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Collections + * @since 3.0 + */ +class TListIterator implements Iterator +{ + /** + * @var array the data to be iterated through + */ + private $_d; + /** + * @var integer index of the current item + */ + private $_i; + + /** + * Constructor. + * @param array the data to be iterated through + */ + public function __construct(&$data) + { + $this->_d=&$data; + $this->_i=0; + } + + /** + * Rewinds internal array pointer. + * This method is required by the interface Iterator. + */ + public function rewind() + { + $this->_i=0; + } + + /** + * Returns the key of the current array item. + * This method is required by the interface Iterator. + * @return integer the key of the current array item + */ + public function key() + { + return $this->_i; + } + + /** + * Returns the current array item. + * This method is required by the interface Iterator. + * @return mixed the current array item + */ + public function current() + { + return $this->_d[$this->_i]; + } + + /** + * Moves the internal pointer to the next array item. + * This method is required by the interface Iterator. + */ + public function next() + { + $this->_i++; + } + + /** + * Returns whether there is an item at current position. + * This method is required by the interface Iterator. + * @return boolean + */ + public function valid() + { + return isset($this->_d[$this->_i]); + } +} + +?> \ No newline at end of file diff --git a/framework/Collections/TMap.php b/framework/Collections/TMap.php new file mode 100644 index 00000000..7c2333d9 --- /dev/null +++ b/framework/Collections/TMap.php @@ -0,0 +1,384 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Collections + */ + +/** + * TMap class + * + * TMap implements a collection that takes key-value pairs. + * + * You can access, add or remove an item with a key by using + * {@link itemAt}, {@link add}, and {@link remove}. + * To get the number of the items in the map, use {@link getCount}. + * TMap can also be used like a regular array as follows, + * + * $map[$key]=$value; // add a key-value pair + * unset($map[$key]); // remove the value with the specified key + * if(isset($map[$key])) // if the map contains the key + * foreach($map as $key=>$value) // traverse the items in the map + * + * Note, count($map) will always return 1. You should use {@link getCount()} + * to determine the number of items in the map. + * + * To extend TMap by doing additional operations with each added or removed item, + * you can override {@link addedItem} and {@link removedItem}. + * You can also override {@link canAddItem} and {@link canRemoveItem} to + * control whether to add or remove a particular item. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Collections + * @since 3.0 + */ +class TMap extends TComponent implements IteratorAggregate,ArrayAccess +{ + /** + * @var array internal data storage + */ + private $_d=array(); + + /** + * Constructor. + * Initializes the list with an array or an iterable object. + * @param array|Iterator the intial data. Default is null, meaning no initialization. + * @throws TInvalidDataTypeException If data is not null and neither an array nor an iterator. + */ + public function __construct($data=null) + { + parent::__construct(); + if($data!==null) + $this->copyFrom($data); + } + + /** + * Returns an iterator for traversing the items in the list. + * This method is required by the interface IteratorAggregate. + * @return Iterator an iterator for traversing the items in the list. + */ + public function getIterator() + { + return new TMapIterator($this->_d); + } + + /** + * @return integer the number of items in the map + */ + public function getCount() + { + return count($this->_d); + } + + /** + * @return array the key list + */ + public function getKeys() + { + return array_keys($this->_d); + } + + /** + * Returns the item with the specified key. + * This method is exactly the same as {@link offsetGet}. + * @param mixed the key + * @return mixed the element at the offset, null if no element is found at the offset + */ + public function itemAt($key) + { + return isset($this->_d[$key]) ? $this->_d[$key] : null; + } + + /** + * Adds an item into the map. + * Note, if the specified key already exists, the old value will be removed first. + * @param mixed key + * @param mixed value + * @throws TInvalidOperationException if the item cannot be added + */ + public function add($key,$value) + { + if($this->canAddItem($key,$value)) + { + if(isset($this->_d[$key])) + $this->remove($key); + $this->_d[$key]=$value; + $this->addedItem($key,$value); + } + else + throw new TInvalidOperationException('map_item_invalid'); + } + + /** + * Removes an item from the map by its key. + * @param mixed the key of the item to be removed + * @return mixed the removed value, null if no such key exists. + * @throws TInvalidOperationException if the item cannot be removed + */ + public function remove($key) + { + if(isset($this->_d[$key])) + { + $value=$this->_d[$key]; + if($this->canRemoveItem($key,$value)) + { + unset($this->_d[$key]); + $this->removedItem($key,$value); + return $value; + } + else + throw new TInvalidOperationException('map_item_unremovable'); + } + else + return null; + } + + /** + * Removes all items in the map. + */ + public function clear() + { + foreach(array_keys($this->_d) as $key) + $this->remove($key); + } + + /** + * @param mixed the key + * @return boolean whether the map contains an item with the specified key + */ + public function contains($key) + { + return isset($this->_d[$key]); + } + + /** + * @return array the list of items in array + */ + public function toArray() + { + return $this->_d; + } + + /** + * Copies iterable data into the map. + * Note, existing data in the map will be cleared first. + * @param mixed the data to be copied from, must be an array or object implementing Traversable + * @throws TInvalidDataTypeException If data is neither an array nor an iterator. + */ + public function copyFrom($data) + { + if(is_array($data) || $data instanceof Traversable) + { + if($this->getCount()>0) + $this->clear(); + foreach($data as $key=>$value) + $this->add($key,$value); + } + else + throw new TInvalidDataTypeException('map_data_not_iterable'); + } + + /** + * Merges iterable data into the map. + * Existing data in the map will be kept and overwritten if the keys are the same. + * @param mixed the data to be merged with, must be an array or object implementing Traversable + * @throws TInvalidDataTypeException If data is neither an array nor an iterator. + */ + public function mergeWith($data) + { + if(is_array($data) || $data instanceof Traversable) + { + foreach($data as $key=>$value) + $this->add($key,$value); + } + else + throw new TInvalidDataTypeException('map_data_not_iterable'); + } + + /** + * Returns whether there is an element at the specified offset. + * This method is required by the interface ArrayAccess. + * @param mixed the offset to check on + * @return boolean + */ + public function offsetExists($offset) + { + return $this->contains($offset); + } + + /** + * Returns the element at the specified offset. + * This method is required by the interface ArrayAccess. + * @param integer the offset to retrieve element. + * @return mixed the element at the offset, null if no element is found at the offset + */ + public function offsetGet($offset) + { + return isset($this->_d[$offset]) ? $this->_d[$offset] : null; + } + + /** + * Sets the element at the specified offset. + * This method is required by the interface ArrayAccess. + * @param integer the offset to set element + * @param mixed the element value + */ + public function offsetSet($offset,$item) + { + $this->add($offset,$item); + } + + /** + * Unsets the element at the specified offset. + * This method is required by the interface ArrayAccess. + * @param mixed the offset to unset element + */ + public function offsetUnset($offset) + { + $this->remove($offset); + } + + /** + * This method is invoked after an item is successfully added to the map. + * You can override this method provide customized processing of the addition. + * @param string key to the item + * @param mixed the newly added item + */ + protected function addedItem($key,$item) + { + } + + /** + * This method is invoked after an item is successfully removed from the map. + * You can override this method provide customized processing of the removal. + * @param string key to the item + * @param mixed the removed item + */ + protected function removedItem($key,$item) + { + } + + /** + * This method is invoked before adding an item to the map. + * If it returns true, the item will be added to the map, otherwise not. + * You can override this method to decide whether a specific can be added. + * @param string key to the item + * @param mixed item to be added + * @return boolean whether the item can be added to the map + */ + protected function canAddItem($key,$item) + { + return true; + } + + /** + * This method is invoked before removing an item from the map. + * If it returns true, the item will be removed from the map, otherwise not. + * You can override this method to decide whether a specific can be removed. + * @param string key to the item + * @param mixed item to be removed + * @return boolean whether the item can be removed to the map + */ + protected function canRemoveItem($key,$item) + { + return true; + } +} + +/** + * TMapIterator class + * + * TMapIterator implements Iterator interface. + * + * TMapIterator is used by TMap. It allows TMap to return a new iterator + * for traversing the items in the map. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Collections + * @since 3.0 + */ +class TMapIterator implements Iterator +{ + /** + * @var array the data to be iterated through + */ + private $_d; + /** + * @var array list of keys in the map + */ + private $_keys; + /** + * @var mixed current key + */ + private $_key; + + /** + * Constructor. + * @param array the data to be iterated through + */ + public function __construct(&$data) + { + $this->_d=&$data; + $this->_keys=array_keys($data); + } + + /** + * Rewinds internal array pointer. + * This method is required by the interface Iterator. + */ + public function rewind() + { + $this->_key=reset($this->_keys); + } + + /** + * Returns the key of the current array element. + * This method is required by the interface Iterator. + * @return mixed the key of the current array element + */ + public function key() + { + return $this->_key; + } + + /** + * Returns the current array element. + * This method is required by the interface Iterator. + * @return mixed the current array element + */ + public function current() + { + return $this->_d[$this->_key]; + } + + /** + * Moves the internal pointer to the next array element. + * This method is required by the interface Iterator. + */ + public function next() + { + do + { + $this->_key=next($this->_keys); + } + while(!isset($this->_d[$this->_key]) && $this->_key!==false); + } + + /** + * Returns whether there is an element at current position. + * This method is required by the interface Iterator. + * @return boolean + */ + public function valid() + { + return $this->_key!==false; + } +} +?> \ No newline at end of file diff --git a/framework/Data/TMemCache.php b/framework/Data/TMemCache.php new file mode 100644 index 00000000..73eec99f --- /dev/null +++ b/framework/Data/TMemCache.php @@ -0,0 +1,268 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Data + */ + +/** + * TMemCache class + * + * TMemCache implements a cache application module based on {@link http://www.danga.com/memcached/ memcached}. + * + * TMemCache can be configured with the Host and Port properties, which + * specify the host and port of the memcache server to be used. + * By default, they take the value 'localhost' and 11211, respectively. + * These properties must be set before {@link init} is invoked. + * + * The following basic cache operations are implemented: + * - {@link get} : retrieve the value with a key (if any) from cache + * - {@link set} : store the value with a key into cache + * - {@link add} : store the value only if cache does not have this key + * - {@link replace} : store the value only if cache has this key + * - {@link delete} : delete the value with the specified key from cache + * - {@link flush} : delete all values from cache + * + * Each value is associated with an expiration time. The {@link get} operation + * ensures that any expired value will not be returned. The expiration time can + * be specified by the number of seconds (maximum 60*60*24*30) + * or a UNIX timestamp. A expiration time 0 represents never expire. + * + * By definition, cache does not ensure the existence of a value + * even if it never expires. Cache is not meant to be an persistent storage. + * + * Also note, there is no security measure to protected data in memcache. + * All data in memcache can be accessed by any process running in the system. + * + * To use this module, the memcache PHP extension must be loaded. + * + * Some usage examples of TMemCache are as follows, + * + * $cache=new TMemCache; // TMemCache may also be loaded as a Prado application module + * $cache->init(null); + * $cache->add('object',$object); + * $object2=$cache->get('object'); + * + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Data + * @since 3.0 + */ +class TMemCache extends TComponent implements IModule, ICache +{ + /** + * @var boolean if the module is initialized + */ + private $_initialized=false; + /** + * @var Memcache the Memcache instance + */ + private $_cache=null; + /** + * @var string a unique prefix used to identify this cache instance from the others + */ + private $_prefix=null; + /** + * @var string host name of the memcache server + */ + private $_host='localhost'; + /** + * @var integer the port number of the memcache server + */ + private $_port=11211; + /** + * @var string ID of this module + */ + private $_id=''; + + /** + * Destructor. + * Disconnect the memcache server. + */ + public function __destruct() + { + if($this->_cache!==null) + $this->_cache->close(); + parent::__destruct(); + } + + /** + * Initializes this module. + * This method is required by the IModule interface. It makes sure that + * UniquePrefix has been set, creates a Memcache instance and connects + * to the memcache server. + * @param IApplication Prado application, can be null + * @param TXmlElement configuration for this module, can be null + * @throws TConfigurationException if memcache extension is not installed or memcache sever connection fails + */ + public function init($application,$config) + { + if(!extension_loaded('memcache')) + throw new TConfigurationException('memcache_extension_required'); + $this->_cache=new Memcache; + if($this->_cache->connect($this->_host,$this->_port)===false) + throw new TInvalidConfigurationException('memcache_connection_failed'); + if($application instanceof IApplication) + $this->_prefix=$application->getUniqueID(); + $this->_initialized=true; + } + + /** + * @return string id of this module + */ + public function getID() + { + return $this->_id; + } + + /** + * @param string id of this module + */ + public function setID($value) + { + $this->_id=$value; + } + + /** + * @return string host name of the memcache server + */ + public function getHost() + { + return $this->_host; + } + + /** + * @param string host name of the memcache server + * @throws TInvalidOperationException if the module is already initialized + */ + public function setHost($value) + { + if($this->_initialized) + throw new TInvalidOperationException('memcache_host_unchangeable'); + else + $this->_host=$value; + } + + /** + * @return integer port number of the memcache server + */ + public function getPort() + { + return $this->_port; + } + + /** + * @param integer port number of the memcache server + * @throws TInvalidOperationException if the module is already initialized + */ + public function setPort($value) + { + if($this->_initialized) + throw new TInvalidOperationException('memcache_port_unchangeable'); + else + $this->_port=TPropertyValue::ensureInteger($value); + } + + /** + * Retrieves a value from cache with a specified key. + * @return mixed the value stored in cache, false if the value is not in the cache or expired. + */ + public function get($key) + { + return $this->_cache->get($this->generateUniqueKey($key)); + } + + /** + * Stores a value identified by a key into cache. + * If the cache already contains such a key, the existing value and + * expiration time will be replaced with the new ones. + * + * Note, avoid using this method whenever possible. Database insertion is + * very expensive. Try using {@link add} instead, which will not store the value + * if the key is already in cache. + * + * @param string the key identifying the value to be cached + * @param mixed the value to be cached + * @param integer the expiration time of the value, + * 0 means never expire, + * a number less or equal than 60*60*24*30 means the number of seconds that the value will remain valid. + * a number greater than 60 means a UNIX timestamp after which the value will expire. + * @return boolean true if the value is successfully stored into cache, false otherwise + */ + public function set($key,$value,$expire=0) + { + return $this->_cache->set($this->generateUniqueKey($key),$value,0,$expire); + } + + /** + * Stores a value identified by a key into cache if the cache does not contain this key. + * Nothing will be done if the cache already contains the key. + * @param string the key identifying the value to be cached + * @param mixed the value to be cached + * @param integer the expiration time of the value, + * 0 means never expire, + * a number less or equal than 60*60*24*30 means the number of seconds that the value will remain valid. + * a number greater than 60 means a UNIX timestamp after which the value will expire. + * @return boolean true if the value is successfully stored into cache, false otherwise + */ + public function add($key,$value,$expiry=0) + { + return $this->_cache->add($this->generateUniqueKey($key),$value,0,$expire); + } + + /** + * Stores a value identified by a key into cache only if the cache contains this key. + * The existing value and expiration time will be overwritten with the new ones. + * @param string the key identifying the value to be cached + * @param mixed the value to be cached + * @param integer the expiration time of the value, + * 0 means never expire, + * a number less or equal than 60*60*24*30 means the number of seconds that the value will remain valid. + * a number greater than 60 means a UNIX timestamp after which the value will expire. + * @return boolean true if the value is successfully stored into cache, false otherwise + */ + public function replace($key,$value,$expiry=0) + { + return $this->_cache->replace($this->generateUniqueKey($key),$value,0,$expire); + } + + /** + * Deletes a value with the specified key from cache + * @param string the key of the value to be deleted + * @return boolean if no error happens during deletion + */ + public function delete($key) + { + return $this->_cache->delete($this->generateUniqueKey($key)); + } + + /** + * Deletes all values from cache. + * Be careful of performing this operation if the cache is shared by multiple applications. + */ + public function flush() + { + return $this->_cache->flush(); + } + + /** + * Generates a unique key based on a given user key. + * This method generates a unique key with the memcache. + * The key is made unique by prefixing with a unique string that is supposed + * to be unique among applications using the same memcache. + * @param string user key + * @param string a unique key + */ + protected function generateUniqueKey($key) + { + return md5($this->_prefix.$key); + } +} + +?> \ No newline at end of file diff --git a/framework/Data/TSqliteCache.php b/framework/Data/TSqliteCache.php new file mode 100644 index 00000000..8d59b035 --- /dev/null +++ b/framework/Data/TSqliteCache.php @@ -0,0 +1,277 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Data + */ + +/** + * TSqliteCache class + * + * TSqliteCache implements a cache application module based on SQLite database. + * + * The database file is specified by the DbFile property. This property must + * be set before {@link init} is invoked. If the specified database file does not + * exist, it will be created automatically. Make sure the database file is writable. + * + * The following basic cache operations are implemented: + * - {@link get} : retrieve the value with a key (if any) from cache + * - {@link set} : store the value with a key into cache + * - {@link add} : store the value only if cache does not have this key + * - {@link replace} : store the value only if cache has this key + * - {@link delete} : delete the value with the specified key from cache + * - {@link flush} : delete all values from cache + * + * Each value is associated with an expiration time. The {@link get} operation + * ensures that any expired value will not be returned. The expiration time can + * be specified by the number of seconds (maximum 60*60*24*30) + * or a UNIX timestamp. A expiration time 0 represents never expire. + * + * By definition, cache does not ensure the existence of a value + * even if it never expires. Cache is not meant to be an persistent storage. + * + * Do not use the same database file for multiple applications using TSqliteCache. + * Also note, cache is shared by all user sessions of an application. + * + * To use this module, the sqlite PHP extension must be loaded. Sqlite extension + * is no longer loaded by default since PHP 5.1. + * + * Some usage examples of TSqliteCache are as follows, + * + * $cache=new TSqliteCache; // TSqliteCache may also be loaded as a Prado application module + * $cache->setDbFile($dbFilePath); + * $cache->init(null); + * $cache->add('object',$object); + * $object2=$cache->get('object'); + * + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Data + * @since 3.0 + */ +class TSqliteCache extends TComponent implements IModule, ICache +{ + /** + * name of the table storing cache data + */ + const CACHE_TABLE='cache'; + /** + * extension of the db file name + */ + const DB_FILE_EXT='.db'; + /** + * maximum number of seconds specified as expire + */ + const EXPIRE_LIMIT=2592000; // 30 days + + /** + * @var boolean if the module has been initialized + */ + private $_initialized=false; + /** + * @var SQLiteDatabase the sqlite database instance + */ + private $_db=null; + /** + * @var string the database file name + */ + private $_file=null; + /** + * @var string id of this module + */ + private $_id=''; + + /** + * Destructor. + * Disconnect the db connection. + */ + public function __destruct() + { + $this->_db=null; + parent::__destruct(); + } + + /** + * Initializes this module. + * This method is required by the IModule interface. It checks if the DbFile + * property is set, and creates a SQLiteDatabase instance for it. + * The database or the cache table does not exist, they will be created. + * Expired values are also deleted. + * @param IApplication Prado application, can be null + * @param TXmlElement configuration for this module, can be null + * @throws TConfigurationException if sqlite extension is not installed, + * DbFile is set invalid, or any error happens during creating database or cache table. + */ + public function init($application,$config) + { + if(!function_exists('sqlite_open')) + throw new TConfigurationException('sqlitecache_extension_required'); + if($this->_file===null) + throw new TConfigurationException('sqlitecache_filename_required'); + $error=''; + if(($fname=Prado::getPathOfNamespace($this->_file,self::DB_FILE_EXT))===null) + throw new TConfigurationException('sqlitecache_dbfile_invalid',$this->_file); + if(($this->_db=new SQLiteDatabase($fname,0666,$error))===false) + throw new TConfigurationException('sqlitecache_connection_failed',$error); + if(($res=$this->_db->query('SELECT * FROM sqlite_master WHERE tbl_name=\''.self::CACHE_TABLE.'\' AND type=\'table\''))!=false) + { + if($res->numRows()===0) + { + if($this->_db->query('CREATE TABLE '.self::CACHE_TABLE.' (key CHAR(128) PRIMARY KEY, value BLOB, serialized INT, expire INT)')===false) + throw new TConfigurationException('sqlitecache_table_creation_failed',sqlite_error_string(sqlite_last_error())); + } + } + else + throw new TConfigurationException('sqlitecache_table_creation_failed',sqlite_error_string(sqlite_last_error())); + $this->_initialized=true; + $this->_db->query('DELETE FROM '.self::CACHE_TABLE.' WHERE expire<>0 AND expire<'.time()); + } + + /** + * @return string id of this module + */ + public function getID() + { + return $this->_id; + } + + /** + * @param string id of this module + */ + public function setID($value) + { + $this->_id=$value; + } + + /** + * @return string database file path (in namespace form) + */ + public function getDbFile() + { + return $this->_file; + } + + /** + * @param string database file path (in namespace form) + * @throws TInvalidOperationException if the module is already initialized + */ + public function setDbFile($value) + { + if($this->_initialized) + throw new TInvalidOperationException('sqlitecache_dbfile_unchangeable'); + else + $this->_file=$value; + } + + /** + * Retrieves a value from cache with a specified key. + * @return mixed the value stored in cache, false if the value is not in the cache or expired. + */ + public function get($key) + { + $sql='SELECT serialized,value FROM '.self::CACHE_TABLE.' WHERE key=\''.md5($key).'\' AND (expire=0 OR expire>'.time().')'; + if(($ret=$this->_db->query($sql))!=false && ($row=$ret->fetch(SQLITE_ASSOC))!==false) + return $row['serialized']?Prado::unserialize($row['value']):$row['value']; + else + return false; + } + + /** + * Stores a value identified by a key into cache. + * If the cache already contains such a key, the existing value and + * expiration time will be replaced with the new ones. + * + * Note, avoid using this method whenever possible. Database insertion is + * very expensive. Try using {@link add} instead, which will not store the value + * if the key is already in cache. + * + * @param string the key identifying the value to be cached + * @param mixed the value to be cached + * @param integer the expiration time of the value, + * 0 means never expire, + * a number less or equal than 60*60*24*30 means the number of seconds that the value will remain valid. + * a number greater than 60 means a UNIX timestamp after which the value will expire. + * @return boolean true if the value is successfully stored into cache, false otherwise + */ + public function set($key,$value,$expire=0) + { + $serialized=is_string($value)?0:1; + $value1=sqlite_escape_string($serialized?Prado::serialize($value):$value); + if($expire && $expire<=self::EXPIRE_LIMIT) + $expire=time()+$expire; + $sql='REPLACE INTO '.self::CACHE_TABLE.' VALUES(\''.md5($key).'\',\''.$value1.'\','.$serialized.','.$expire.')'; + return $this->_db->query($sql)!==false; + } + + /** + * Stores a value identified by a key into cache if the cache does not contain this key. + * Nothing will be done if the cache already contains the key. + * @param string the key identifying the value to be cached + * @param mixed the value to be cached + * @param integer the expiration time of the value, + * 0 means never expire, + * a number less or equal than 60*60*24*30 means the number of seconds that the value will remain valid. + * a number greater than 60 means a UNIX timestamp after which the value will expire. + * @return boolean true if the value is successfully stored into cache, false otherwise + */ + public function add($key,$value,$expire=0) + { + $serialized=is_string($value)?0:1; + $value1=sqlite_escape_string($serialized?Prado::serialize($value):$value); + if($expire && $expire<=self::EXPIRE_LIMIT) + $expire=time()+$expire; + $sql='INSERT INTO '.self::CACHE_TABLE.' VALUES(\''.md5($key).'\',\''.$value1.'\','.$serialized.','.$expire.')'; + return @$this->_db->query($sql)!==false; + } + + /** + * Stores a value identified by a key into cache only if the cache contains this key. + * The existing value and expiration time will be overwritten with the new ones. + * @param string the key identifying the value to be cached + * @param mixed the value to be cached + * @param integer the expiration time of the value, + * 0 means never expire, + * a number less or equal than 60*60*24*30 means the number of seconds that the value will remain valid. + * a number greater than 60 means a UNIX timestamp after which the value will expire. + * @return boolean true if the value is successfully stored into cache, false otherwise + */ + public function replace($key,$value,$expire=0) + { + $serialized=is_string($value)?0:1; + $value1=sqlite_escape_string($serialized?Prado::serialize($value):$value); + if($expire && $expire<=self::EXPIRE_LIMIT) + $expire=time()+$expire; + $sql='UPDATE '.self::CACHE_TABLE.' SET value=\''.$value1.'\', serialized='.$serialized.',expire='.$expire.' WHERE key=\''.md5($key).'\''; + $this->_db->query($sql); + $ret=$this->_db->query('SELECT serialized FROM '.self::CACHE_TABLE.' WHERE key=\''.md5($key).'\''); + return ($ret!=false && $ret->numRows()>0); + } + + /** + * Deletes a value with the specified key from cache + * @param string the key of the value to be deleted + * @return boolean if no error happens during deletion + */ + public function delete($key) + { + $sql='DELETE FROM '.self::CACHE_TABLE.' WHERE key=\''.md5($key).'\''; + return $this->_db->query($sql)!==false; + } + + /** + * Deletes all values from cache. + * Be careful of performing this operation if the cache is shared by multiple applications. + */ + public function flush() + { + return $this->_db->query('DELETE FROM '.self::CACHE_TABLE)!==false; + } +} + +?> \ No newline at end of file diff --git a/framework/Data/TXmlDocument.php b/framework/Data/TXmlDocument.php new file mode 100644 index 00000000..f8ba5dc2 --- /dev/null +++ b/framework/Data/TXmlDocument.php @@ -0,0 +1,446 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Data + */ + +/** + * TXmlElement class. + * + * TXmlElement represents an XML element node. + * You can obtain its tagname, attributes, text between the openning and closing + * tags via the TagName, Attributes, and Value properties, respectively. + * You can also retrieve its parent and child elements by Parent and Elements + * properties, respectively. + * + * TBD: xpath + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System + * @since 3.0 + */ +class TXmlElement extends TComponent +{ + /** + * @var TXmlElement parent of this element + */ + private $_parent=null; + /** + * @var string tagname of this element + */ + private $_tagName; + /** + * @var string text enclosed between openning and closing tags of this element + */ + private $_value; + /** + * @var TXmlElementList list of child elements of this element + */ + private $_elements=null; + /** + * @var TMap attributes of this element + */ + private $_attributes=null; + + /** + * Constructor. + * @param string tagname for this element + */ + public function __construct($tagName) + { + parent::__construct(); + $this->setTagName($tagName); + } + + /** + * @return TXmlElement parent element of this element + */ + public function getParent() + { + return $this->_parent; + } + + /** + * @param TXmlElement parent element of this element + */ + public function setParent($parent) + { + $this->_parent=$parent; + } + + /** + * @return string tagname of this element + */ + public function getTagName() + { + return $this->_tagName; + } + + /** + * @param string tagname of this element + */ + public function setTagName($tagName) + { + $this->_tagName=$tagName; + } + + /** + * @return string text enclosed between opening and closing tag of this element + */ + public function getValue() + { + return $this->_value; + } + + /** + * @param string text enclosed between opening and closing tag of this element + */ + public function setValue($value) + { + $this->_value=$value; + } + + /** + * @return boolean true if this element has child elements + */ + public function getHasElement() + { + return $this->_elements!==null && $this->_elements->getCount()>0; + } + + /** + * @return boolean true if this element has attributes + */ + public function getHasAttribute() + { + return $this->_attributes!==null && $this->_attributes->getCount()>0; + } + + /** + * @return string the attribute specified by the name, null if no such attribute + */ + public function getAttribute($name) + { + if($this->_attributes!==null) + return $this->_attributes->itemAt($name); + else + return null; + } + + /** + * @return TXmlElementList list of child elements + */ + public function getElements() + { + if(!$this->_elements) + $this->_elements=new TXmlElementList($this); + return $this->_elements; + } + + /** + * @return TMap list of attributes + */ + public function getAttributes() + { + if(!$this->_attributes) + $this->_attributes=new TMap; + return $this->_attributes; + } + + /** + * @return TXmlElement the first child element that has the specified tagname, null if not found + */ + public function getElementByTagName($tagName) + { + if($this->_elements) + { + foreach($this->_elements as $element) + if($element->_tagName===$tagName) + return $element; + } + return null; + } + + /** + * @return TList list of all child elements that have the specified tagname + */ + public function getElementsByTagName($tagName) + { + $list=new TList; + if($this->_elements) + { + foreach($this->_elements as $element) + if($element->_tagName===$tagName) + $list->add($element); + } + return $list; + } + + /** + * @return string string representation of this element + */ + public function toString($indent=0) + { + $attr=''; + if($this->_attributes!==null) + { + foreach($this->_attributes as $name=>$value) + $attr.=" $name=\"$value\""; + } + $prefix=str_repeat(' ',$indent*4); + if($this->getHasElement()) + { + $str=$prefix."<{$this->_tagName}$attr>\n"; + foreach($this->getElements() as $element) + $str.=$element->toString($indent+1)."\n"; + $str.=$prefix."_tagName}>"; + return $str; + } + else if($this->getValue()!=='') + { + return $prefix."<{$this->_tagName}$attr>{$this->_value}_tagName}>"; + } + else + return $prefix."<{$this->_tagName}$attr />"; + } +} + +/** + * TXmlDocument class. + * + * TXmlDocument represents a DOM representation of an XML file. + * Besides all properties and methods inherited from {@link TXmlElement}, + * you can load an XML file or string by {@link loadFromFile} or {@link loadFromString}. + * You can also get the version and encoding of the XML document by + * the Version and Encoding properties. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System + * @since 3.0 + */ +class TXmlDocument extends TXmlElement +{ + /** + * @var string version of this XML document + */ + private $_version; + /** + * @var string encoding of this XML document + */ + private $_encoding; + + /** + * Constructor. + * @param string version of this XML document + * @param string encoding of this XML document + */ + public function __construct($version='1.0',$encoding='') + { + parent::__construct(''); + $this->setversion($version); + $this->setEncoding($encoding); + } + + /** + * @return string version of this XML document + */ + public function getVersion() + { + return $this->_version; + } + + /** + * @param string version of this XML document + */ + public function setVersion($version) + { + $this->_version=$version; + } + + /** + * @return string encoding of this XML document + */ + public function getEncoding() + { + return $this->_encoding; + } + + /** + * @param string encoding of this XML document + */ + public function setEncoding($encoding) + { + $this->_encoding=$encoding; + } + + /** + * Loads and parses an XML document. + * @param string the XML file path + * @throws TIOException if the file fails to be opened. + */ + public function loadFromFile($file) + { + if(($str=file_get_contents($file))!==false) + $this->loadFromString($str); + else + throw new TIOException('xmldocument_file_read_failed',$file); + } + + /** + * Loads and parses an XML string. + * The version and encoding will be determined based on the parsing result. + * @param string the XML string + */ + public function loadFromString($string) + { + $doc=new DOMDocument(); + $doc->loadXML($string); + + $this->setEncoding($doc->encoding); + $this->setVersion($doc->version); + + $element=$doc->documentElement; + $this->setTagName($element->tagName); + $this->setValue($element->nodeValue); + $elements=$this->getElements(); + $attributes=$this->getAttributes(); + $elements->clear(); + $attributes->clear(); + foreach($element->attributes as $name=>$attr) + $attributes->add($name,$attr->value); + foreach($element->childNodes as $child) + { + if($child instanceof DOMElement) + $elements->add($this->buildElement($child)); + } + } + + /** + * Saves this XML document as an XML file. + * @param string the name of the file to be stored with XML output + * @throws TIOException if the file cannot be written + */ + public function saveToFile($file) + { + if(($fw=fopen($file,'w'))!==false) + { + fwrite($fw,$this->saveToString()); + fclose($fw); + } + else + throw new TIOException('xmldocument_file_write_failed',$file); + } + + /** + * Saves this XML document as an XML string + * @return string the XML string of this XML document + */ + public function saveToString() + { + $version=empty($this->_version)?' version="1.0"':' version="'.$this->_version.'"'; + $encoding=empty($this->_encoding)?'':' encoding="'.$this->_encoding.'"'; + return "\n".$this->toString(0); + } + + /** + * Recursively converts DOM XML nodes into TXmlElement + * @param DOMXmlNode the node to be converted + * @return TXmlElement the converted TXmlElement + */ + private function buildElement($node) + { + $element=new TXmlElement($node->tagName); + $element->setValue($node->nodeValue); + foreach($node->attributes as $name=>$attr) + $element->getAttributes()->add($name,$attr->value); + foreach($node->childNodes as $child) + { + if($child instanceof DOMElement) + $element->getElements()->add($this->buildElement($child)); + } + return $element; + } +} + + +/** + * TXmlElement class. + * + * TXmlElement represents an XML element node. + * You can obtain its tagname, attributes, text between the openning and closing + * tags via the TagName, Attributes, and Value properties, respectively. + * You can also retrieve its parent and child elements by Parent and Elements + * properties, respectively. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System + * @since 3.0 + */ +class TXmlElementList extends TList +{ + /** + * @var TXmlElement owner of this list + */ + private $_o; + + /** + * Constructor. + * @param TXmlElement owner of this list + */ + public function __construct(TXmlElement $owner) + { + parent::__construct(); + $this->_o=$owner; + } + + /** + * @return TXmlElement owner of this list + */ + protected function getOwner() + { + return $this->_o; + } + + /** + * Overrides the parent implementation with customized processing of the newly added item. + * @param mixed the newly added item + */ + protected function addedItem($item) + { + if($item->getParent()!==null) + $item->getParent()->getElements()->remove($item); + $item->setParent($this->_o); + } + + /** + * Overrides the parent implementation with customized processing of the removed item. + * @param mixed the removed item + */ + protected function removedItem($item) + { + $item->setParent(null); + } + + /** + * This method is invoked before adding an item to the map. + * If it returns true, the item will be added to the map, otherwise not. + * You can override this method to decide whether a specific can be added. + * @param mixed item to be added + * @return boolean whether the item can be added to the map + */ + protected function canAddItem($item) + { + return ($item instanceof TXmlElement); + } +} + +?> \ No newline at end of file diff --git a/framework/Exceptions/TErrorHandler.php b/framework/Exceptions/TErrorHandler.php new file mode 100644 index 00000000..458d3169 --- /dev/null +++ b/framework/Exceptions/TErrorHandler.php @@ -0,0 +1,48 @@ +attachEventHandler('Error',array($this,'handle')); + $this->_initialized=true; + } + + /** + * @return string id of this module + */ + public function getID() + { + return $this->_id; + } + + /** + * @param string id of this module + */ + public function setID($value) + { + $this->_id=$value; + } + + public function handle($sender,$param) + { echo '...........................'; + echo $param; + } +} + +?> \ No newline at end of file diff --git a/framework/Exceptions/TException.php b/framework/Exceptions/TException.php new file mode 100644 index 00000000..0c51e1f1 --- /dev/null +++ b/framework/Exceptions/TException.php @@ -0,0 +1,175 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Exceptions + */ + +/** + * TException class + * + * TException is the base class for all PRADO exceptions. + * TException + * TSystemException + * TNullReferenceException + * TIndexOutOfRangeException + * TArithmeticException + * TInvalidValueException + * TInvalidTypeException + * TInvalidFormatException + * TInvalidOperationException + * TConfigurationException + * TSecurityException + * TIOException + * TDBException + * THttpException + * TNotSupportedException + * TApplicationException + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Exceptions + * @since 3.0 + */ +class TException extends Exception +{ + private $_errorCode=''; + + public function __construct($errorCode) + { + $this->_errorCode=$errorCode; + $args=func_get_args(); + $args[0]=$this->translateErrorCode($errorCode); + $str=call_user_func_array('sprintf',$args); + parent::__construct($str); + } + + protected function translateErrorCode($key) + { + // $msgFile=dirname(__FILE__).'/messages.'.Prado::getLocale(); + // if(!is_file($msgFile)) + $msgFile=dirname(__FILE__).'/messages.en'; + if(($entries=@file($msgFile))===false) + return $key; + else + { + foreach($entries as $entry) + { + @list($code,$message)=explode('=',$entry,2); + if(trim($code)===$key) + return trim($message); + } + return $key; + } + } + + public function getErrorCode() + { + return $this->_errorCode; + } + + public function setErrorCode($errorCode) + { + $this->_errorCode=$errorCode; + } + + public function getErrorMessage() + { + return $this->getMessage(); + } + + public function setErrorMessage($msg) + { + $this->message=$msg; + } +} + +class TSystemException extends TException +{ +} + +class TApplicationException extends TException +{ +} + +class TNullReferenceException extends TSystemException +{ +} + +class TIndexOutOfRangeException extends TSystemException +{ +} + +class TArithmeticException extends TSystemException +{ +} + +class TInvalidOperationException extends TSystemException +{ +} + +class TInvalidDataTypeException extends TSystemException +{ +} + +class TInvalidDataValueException extends TSystemException +{ +} + +class TInvalidDataFormatException extends TSystemException +{ +} + +class TConfigurationException extends TSystemException +{ +} + +class TIOException extends TException +{ +} + +class TDBException extends TException +{ +} + +class TSecurityException extends TException +{ +} + +class THttpException extends TException +{ +} + +class TNotSupportedException extends TException +{ +} + +class TPhpErrorException extends TException +{ + public function __construct($errno,$errstr,$errfile,$errline) + { + static $errorTypes=array( + E_ERROR => "Error", + E_WARNING => "Warning", + E_PARSE => "Parsing Error", + E_NOTICE => "Notice", + E_CORE_ERROR => "Core Error", + E_CORE_WARNING => "Core Warning", + E_COMPILE_ERROR => "Compile Error", + E_COMPILE_WARNING => "Compile Warning", + E_USER_ERROR => "User Error", + E_USER_WARNING => "User Warning", + E_USER_NOTICE => "User Notice", + E_STRICT => "Runtime Notice" + ); + $errorType=isset($errorTypes[$errno])?$errorTypes[$errno]:'Unknown Error'; + parent::__construct("[$errorType] $errstr (@line $errline in file $errfile)."); + } +} + +?> \ No newline at end of file diff --git a/framework/Exceptions/messages.en b/framework/Exceptions/messages.en new file mode 100644 index 00000000..d949d88a --- /dev/null +++ b/framework/Exceptions/messages.en @@ -0,0 +1,28 @@ +body_contents_not_allowed = %s: body contents are not allowed. +control_id_not_unique = Control ID '%s' is not unique for control type '%s'. +control_not_found = Unable to find a control with ID '%s'. +control_not_in_form = Control '%s' is not enclosed within a server form. +data_not_iterable = Data is not iterable. An array or an object implementing Traversable is required. +event_not_defined = %s: event is not defined. +expecting_closing_tag = Line %d: expecting closing tag %s. +index_out_of_range = Index '%s' is out of range. +invalid_accesskey = %s.AccessKey: only one character is allowed. +invalid_control_id = Invalid control ID '%s' for control type '%s'. +invalid_enum_value = Invalid value '%s' for enumeration type (%s) +invalid_event_handler = Invalid event handler '%s' for event '%s'. +invalid_expression = Invalid expression '%s': %s. +invalid_statements = Invalid statements '%s': %s. +invalid_subproperty = Invalid sub-property '%s'. +invalid_style_value = %s.Style: only string is allowed. +multiple_form_not_allowed = Multiple server forms are not allowed. +must_be_component = %s must extend from TComponent. +no_comments_in_property = Line %d: comments are not allowed in property values. +property_not_defined = %s: property is not defined. +property_read_only = %s: property is read-only. +skinid_set_after_applied = %s: SkinID cannot be set after the skin is applied. +skinid_set_after_preinit = %s: SkinID cannot be set after PreInit stage. +stylesheet_applied = %s: StyleSheet skin is already applied. +enabletheming_after_preinit = %s: EnableTheme cannot be set after PreInit stage. +nonunique_template_directive = Line %d: at most one template directive is allowed. +unexpected_closing_tag = Line %d: unexpected closing tag %s. +unexpected_matching = Unexpected matching: %s. Please report this problem to PRADO developer team. diff --git a/framework/IO/TTextWriter.php b/framework/IO/TTextWriter.php new file mode 100644 index 00000000..17829acf --- /dev/null +++ b/framework/IO/TTextWriter.php @@ -0,0 +1,19 @@ +write($str."\n"); + } +} + +?> \ No newline at end of file diff --git a/framework/Security/TAuthManager.php b/framework/Security/TAuthManager.php new file mode 100644 index 00000000..c12ee245 --- /dev/null +++ b/framework/Security/TAuthManager.php @@ -0,0 +1,205 @@ +_id; + } + + /** + * @param string id of this module + */ + public function setID($value) + { + $this->_id=$value; + } + + /** + * Initializes this module. + * This method is required by the IModule interface. + * @param IApplication Prado application, can be null + * @param TXmlElement configuration for this module, can be null + */ + public function init($application,$config) + { + $this->_application=$application; + $application->attachEventHandler('Authentication',array($this,'doAuthentication')); + $application->attachEventHandler('EndRequest',array($this,'leave')); + $application->attachEventHandler('Authorization',array($this,'doAuthorization')); + $this->_initialized=true; + } + + public function getGuestName() + { + return $this->_guest; + } + + public function setGuestName($value) + { + $this->_guest=$value; + } + + public function getUserManager() + { + if($this->_users instanceof TUserManager) + return $this->_users; + else + { + if(($users=$this->_application->getModule($this->_users))===null) + throw new TConfigurationException('authenticator_usermanager_inexistent',$this->_users); + if(!($users instanceof TUserManager)) + throw new TConfigurationException('authenticator_usermanager_invalid',$this->_users); + $this->_users=$users; + return $users; + } + } + + public function setUserManager($provider) + { + $this->_users=$provider; + } + + public function getLoginPage() + { + return $this->_loginPage; + } + + public function setLoginPage($pagePath) + { + $this->_loginPage=$pagePath; + } + + public function doAuthentication($sender,$param) + { + $this->onAuthenticate($param); + + $service=$this->_application->getService(); + if(($service instanceof TPageService) && $service->isRequestingPage($this->getLoginPage())) + $this->_skipAuthorization=true; + } + + public function doAuthorization($sender,$param) + { + if(!$this->_skipAuthorization) + { + $this->onAuthorize($param); + } + } + + public function leave($sender,$param) + { + if($this->_application->getResponse()->getStatusCode()===401) + { + $service=$this->_application->getService(); + if($service instanceof TPageService) + { + $returnUrl=$this->_application->getRequest()->getRequestUri(); + $url=$service->constructUrl($this->getLoginPage(),array(self::RETURN_URL_VAR=>$returnUrl)); + $this->_application->getResponse()->redirect($url); + } + } + } + + public function onAuthenticate($param) + { + if($this->hasEventHandler('Authenticate')) + $this->raiseEvent('Authenticate',$this,$this->_application); + if($this->_application->getUser()!==null) + return; + + if(($session=$this->_application->getSession())===null) + throw new TConfigurationException('authenticator_session_required'); + $session->open(); + if(($userManager=$this->getUserManager())===null) + throw new TConfigurationException('authenticator_usermanager_required'); + $sessionInfo=$session->getItems()->itemAt($this->generateUserSessionKey()); + $user=$userManager->getUser(null)->loadFromString($sessionInfo); + $this->_application->setUser($user); + } + + public function onAuthorize($param) + { + if($this->hasEventHandler('Authenticate')) + $this->raiseEvent('Authorize',$this,$this->_application); + if($this->_authRules!==null && !$this->_authRules->isUserAllowed($this->_application->getUser(),$this->_application->getRequest()->getRequestType())) + { + $this->_application->getResponse()->setStatusCode(401); + $this->_application->completeRequest(); + } + } + + protected function generateUserSessionKey() + { + return md5($this->_application->getUniqueID().'prado:user'); + } + + public function updateSessionUser($user) + { + if(!$user->getIsGuest()) + { + if(($session=$this->_application->getSession())===null) + throw new TConfigurationException('authenticator_session_required'); + else + $session->getItems()->add($this->generateUserSessionKey(),$user->saveToString()); + } + } + + public function login($username,$password) + { + if(($userManager=$this->getUserManager())===null) + throw new TConfigurationException('authenticator_usermanager_required'); + else + { + if($userManager->validateUser($username,$password)) + { + $user=$userManager->getUser($username); + $this->updateSessionUser($user); + $this->_application->setUser($user); + return true; + } + else + return false; + } + } + + public function logout() + { + if(($userManager=$this->getUserManager())===null) + throw new TConfigurationException('authenticator_usermanager_required'); + else if(($session=$this->_application->getSession())===null) + throw new TConfigurationException('authenticator_session_required'); + else + { + $userManager->logout($this->_application->getUser()); + $session->destroy(); + } + } + /** + * @return TAuthorizationRuleCollection list of authorization rules that may be applied + */ + + public function getAuthorizationRules() + { + if($this->_authRules===null) + $this->_authRules=new TAuthorizationRuleCollection; + return $this->_authRules; + } +} + +?> \ No newline at end of file diff --git a/framework/Security/TAuthorizationRule.php b/framework/Security/TAuthorizationRule.php new file mode 100644 index 00000000..2ee6de49 --- /dev/null +++ b/framework/Security/TAuthorizationRule.php @@ -0,0 +1,213 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Security + */ +/** + * TAuthorizationRule class + * + * TAuthorizationRule represents a single authorization rule. + * A rule is specified by an action (required), a list of users (optional), + * a list of roles (optional), and a verb (optional). + * Action can be either 'allow' or 'deny'. + * Guest (anonymous, unauthenticated) users are represented by question mark '?'. + * All users (including guest users) are represented by asterisk '*'. + * Users/roles are case-insensitive. + * Different users/roles are separated by comma ','. + * Verb can be either 'get' or 'post'. If it is absent, it means both. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Security + * @since 3.0 + */ +class TAuthorizationRule extends TComponent +{ + /** + * @var string action, either 'allow' or 'deny' + */ + private $_action; + /** + * @var array list of user IDs + */ + private $_users; + /** + * @var array list of roles + */ + private $_roles; + /** + * @var string verb, may be empty, 'get', or 'post'. + */ + private $_verb; + /** + * @var boolean if this rule applies to everyone + */ + private $_everyone; + /** + * @var boolean if this rule applies to guest user + */ + private $_guest; + + /** + * Constructor. + * @param string action, either 'deny' or 'allow' + * @param string a comma separated user list + * @param string a comma separated role list + * @param string verb, can be empty, 'get', or 'post' + */ + public function __construct($action,$users,$roles,$verb='') + { + parent::__construct(); + $action=strtolower(trim($action)); + if($action==='allow' || $action==='deny') + $this->_action=$action; + else + throw new TInvalidDataValueException('authorizationrule_action_invalid',$action); + $this->_users=array(); + $this->_roles=array(); + $this->_everyone=false; + $this->_guest=false; + foreach(explode(',',$users) as $user) + { + if(($user=trim(strtolower($user)))!=='') + { + if($user==='*') + $this->_everyone=true; + else if($user==='?') + $this->_guest=true; + else + $this->_users[]=$user; + } + } + foreach(explode(',',$roles) as $role) + { + if(($role=trim(strtolower($role)))!=='') + $this->_roles[]=$role; + } + $verb=trim(strtolower($verb)); + if($verb==='' || $verb==='get' || $verb==='post') + $this->_verb=$verb; + else + throw new TInvalidDataValueException('authorizationrule_verb_invalid',$verb); + } + + /** + * @return string action, either 'allow' or 'deny' + */ + public function getAction() + { + return $this->_action; + } + + /** + * @return array list of user IDs + */ + public function getUsers() + { + return $this->_users; + } + + /** + * @return array list of roles + */ + public function getRoles() + { + return $this->_roles; + } + + /** + * @return string verb, may be empty, 'get', or 'post'. + */ + public function getVerb() + { + return $this->_verb; + } + + /** + * @return boolean if this rule applies to everyone + */ + public function getGuestApplied() + { + return $this->_guest; + } + + /** + * @var boolean if this rule applies to everyone + */ + public function getEveryoneApplied() + { + return $this->_everyone; + } + + /** + * @return integer 1 if the user is allowed, -1 if the user is denied, 0 if the rule does not apply to the user + */ + public function isUserAllowed(IUser $user,$verb) + { + $decision=($this->_action==='allow')?1:-1; + if($this->_verb==='' || strcasecmp($verb,$this->_verb)===0) + { + if($this->_everyone || ($this->_guest && $user->getIsGuest())) + return $decision; + if(in_array(strtolower($user->getName()),$this->_users)) + return $decision; + foreach($this->_roles as $role) + if($user->isInRole($role)) + return $decision; + } + return 0; + } +} + + +/** + * TAuthorizationRuleCollection class. + * TAuthorizationRuleCollection represents a collection of authorization rules {@link TAuthorizationRule}. + * To check if a user is allowed, call {@link isUserAllowed}. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Security + * @since 3.0 + */ +class TAuthorizationRuleCollection extends TList +{ + /** + * @param IUser the user to be authorized + * @param string verb, can be empty, 'post' or 'get'. + * @return boolean whether the user is allowed + */ + public function isUserAllowed($user,$verb) + { + if($user instanceof IUser) + { + $verb=strtolower(trim($verb)); + foreach($this as $rule) + { + if(($decision=$rule->isUserAllowed($user,$verb))!==0) + return ($decision>0); + } + return true; + } + else + return false; + } + + /** + * Ensures that only instance of TAuthorizationRule is added to the collection. + * @param mixed item to be added to the collection + * @return boolean whether the item can be added to the collection + */ + protected function canAddItem($item) + { + return ($item instanceof TAuthorizationRule); + } +} + +?> \ No newline at end of file diff --git a/framework/Security/TMembershipManager.php b/framework/Security/TMembershipManager.php new file mode 100644 index 00000000..a3c1ae55 --- /dev/null +++ b/framework/Security/TMembershipManager.php @@ -0,0 +1,109 @@ + \ No newline at end of file diff --git a/framework/Security/TStaticMembershipProvider.php b/framework/Security/TStaticMembershipProvider.php new file mode 100644 index 00000000..857a8f26 --- /dev/null +++ b/framework/Security/TStaticMembershipProvider.php @@ -0,0 +1,324 @@ +using System; +using System.Xml; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration.Provider; +using System.Web.Security; +using System.Web.Hosting; +using System.Web.Management; +using System.Security.Permissions; +using System.Web; + +public class ReadOnlyXmlMembershipProvider : MembershipProvider +{ + private Dictionary _Users; + private string _XmlFileName; + + // MembershipProvider Properties + public override string ApplicationName + { + get { throw new NotSupportedException(); } + set { throw new NotSupportedException(); } + } + + public override bool EnablePasswordRetrieval + { + get { return false; } + } + + public override bool EnablePasswordReset + { + get { return false; } + } + + public override int MaxInvalidPasswordAttempts + { + get { throw new NotSupportedException(); } + } + + public override int MinRequiredNonAlphanumericCharacters + { + get { throw new NotSupportedException(); } + } + + public override int MinRequiredPasswordLength + { + get { throw new NotSupportedException(); } + } + + public override int PasswordAttemptWindow + { + get { throw new NotSupportedException(); } + } + + public override MembershipPasswordFormat PasswordFormat + { + get { throw new NotSupportedException(); } + } + + public override string PasswordStrengthRegularExpression + { + get { throw new NotSupportedException(); } + } + + public override bool RequiresQuestionAndAnswer + { + get { throw new NotSupportedException(); } + } + + public override bool RequiresUniqueEmail + { + get { throw new NotSupportedException(); } + } + + // MembershipProvider Methods + public override void Initialize (string name, + NameValueCollection config) + { + // Verify that config isn't null + if (config == null) + throw new ArgumentNullException ("config"); + + // Assign the provider a default name if it doesn't have one + if (String.IsNullOrEmpty (name)) + name = "ReadOnlyXmlMembershipProvider"; + + // Add a default "description" attribute to config if the + // attribute doesn't exist or is empty + if (string.IsNullOrEmpty (config["description"])) { + config.Remove ("description"); + config.Add ("description", + "Read-only XML membership provider"); + } + + // Call the base class's Initialize method + base.Initialize(name, config); + + // Initialize _XmlFileName and make sure the path + // is app-relative + string path = config["xmlFileName"]; + + if (String.IsNullOrEmpty (path)) + path = "~/App_Data/Users.xml"; + + if (!VirtualPathUtility.IsAppRelative(path)) + throw new ArgumentException + ("xmlFileName must be app-relative"); + + string fullyQualifiedPath = VirtualPathUtility.Combine + (VirtualPathUtility.AppendTrailingSlash + (HttpRuntime.AppDomainAppVirtualPath), path); + + _XmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath); + config.Remove ("xmlFileName"); + + // Make sure we have permission to read the XML data source and + // throw an exception if we don't + FileIOPermission permission = + new FileIOPermission(FileIOPermissionAccess.Read, + _XmlFileName); + permission.Demand(); + + // Throw an exception if unrecognized attributes remain + if (config.Count > 0) { + string attr = config.GetKey (0); + if (!String.IsNullOrEmpty (attr)) + throw new ProviderException + ("Unrecognized attribute: " + attr); + } + } + + public override bool ValidateUser(string username, string password) + { + // Validate input parameters + if (String.IsNullOrEmpty(username) || + String.IsNullOrEmpty(password)) + return false; + + try + { + // Make sure the data source has been loaded + ReadMembershipDataStore(); + + // Validate the user name and password + MembershipUser user; + if (_Users.TryGetValue (username, out user)) + { + if (user.Comment == password) // Case-sensitive + { + // NOTE: A read/write membership provider + // would update the user's LastLoginDate here. + // A fully featured provider would also fire + // an AuditMembershipAuthenticationSuccess + // Web event + return true; + } + } + + // NOTE: A fully featured membership provider would + // fire an AuditMembershipAuthenticationFailure + // Web event here + return false; + } + catch (Exception) + { + return false; + } + } + + public override MembershipUser GetUser(string username, + bool userIsOnline) + { + // Note: This implementation ignores userIsOnline + + // Validate input parameters + if (String.IsNullOrEmpty(username)) + return null; + + // Make sure the data source has been loaded + ReadMembershipDataStore(); + + // Retrieve the user from the data source + MembershipUser user; + if (_Users.TryGetValue (username, out user)) + return user; + + return null; + } + + public override MembershipUserCollection GetAllUsers(int pageIndex, + int pageSize, out int totalRecords) + { + // Note: This implementation ignores pageIndex and pageSize, + // and it doesn't sort the MembershipUser objects returned + + // Make sure the data source has been loaded + ReadMembershipDataStore(); + + MembershipUserCollection users = + new MembershipUserCollection(); + + foreach (KeyValuePair pair in _Users) + users.Add(pair.Value); + + totalRecords = users.Count; + return users; + } + + public override int GetNumberOfUsersOnline() + { + throw new NotSupportedException(); + } + + public override bool ChangePassword(string username, + string oldPassword, string newPassword) + { + throw new NotSupportedException(); + } + + public override bool + ChangePasswordQuestionAndAnswer(string username, + string password, string newPasswordQuestion, + string newPasswordAnswer) + { + throw new NotSupportedException(); + } + + public override MembershipUser CreateUser(string username, + string password, string email, string passwordQuestion, + string passwordAnswer, bool isApproved, object providerUserKey, + out MembershipCreateStatus status) + { + throw new NotSupportedException(); + } + + public override bool DeleteUser(string username, + bool deleteAllRelatedData) + { + throw new NotSupportedException(); + } + + public override MembershipUserCollection + FindUsersByEmail(string emailToMatch, int pageIndex, + int pageSize, out int totalRecords) + { + throw new NotSupportedException(); + } + + public override MembershipUserCollection + FindUsersByName(string usernameToMatch, int pageIndex, + int pageSize, out int totalRecords) + { + throw new NotSupportedException(); + } + + public override string GetPassword(string username, string answer) + { + throw new NotSupportedException(); + } + + public override MembershipUser GetUser(object providerUserKey, + bool userIsOnline) + { + throw new NotSupportedException(); + } + + public override string GetUserNameByEmail(string email) + { + throw new NotSupportedException(); + } + + public override string ResetPassword(string username, + string answer) + { + throw new NotSupportedException(); + } + + public override bool UnlockUser(string userName) + { + throw new NotSupportedException(); + } + + public override void UpdateUser(MembershipUser user) + { + throw new NotSupportedException(); + } + + // Helper method + private void ReadMembershipDataStore() + { + lock (this) + { + if (_Users == null) + { + _Users = new Dictionary + (16, StringComparer.InvariantCultureIgnoreCase); + XmlDocument doc = new XmlDocument(); + doc.Load(_XmlFileName); + XmlNodeList nodes = doc.GetElementsByTagName("User"); + + foreach (XmlNode node in nodes) + { + MembershipUser user = new MembershipUser( + Name, // Provider name + node["UserName"].InnerText, // Username + null, // providerUserKey + node["EMail"].InnerText, // Email + String.Empty, // passwordQuestion + node["Password"].InnerText, // Comment + true, // isApproved + false, // isLockedOut + DateTime.Now, // creationDate + DateTime.Now, // lastLoginDate + DateTime.Now, // lastActivityDate + DateTime.Now, // lastPasswordChangedDate + new DateTime(1980, 1, 1) // lastLockoutDate + ); + + _Users.Add(user.UserName, user); + } + } + } + } +} + diff --git a/framework/Security/TUserManager.php b/framework/Security/TUserManager.php new file mode 100644 index 00000000..882c5d5c --- /dev/null +++ b/framework/Security/TUserManager.php @@ -0,0 +1,192 @@ + + * @version $Revision: $ $Date: $ + * @package System.Security + * @since 3.0 + */ +interface IUser +{ + public function getManager(); + public function getName(); + public function setName($value); + public function getIsGuest(); + public function setIsGuest($value); + public function getRoles(); + public function setRoles($value); + /** + * @param string role to be tested + * @return boolean whether the user is of this role + */ + public function isInRole($role); + public function saveToString(); + public function loadFromString($string); +} + +class TUser extends TComponent implements IUser +{ + private $_manager; + private $_isGuest=false; + private $_name=''; + private $_roles=array(); + + public function __construct($manager=null) + { + parent::__construct(); + $this->_manager=$manager; + } + + public function getManager() + { + return $this->_manager; + } + + public function getName() + { + return $this->_name; + } + + public function setName($value) + { + $this->_name=$value; + } + + public function getIsGuest() + { + return $this->_isGuest; + } + + public function setIsGuest($value) + { + $this->_isGuest=TPropertyValue::ensureBoolean($value); + if($this->_isGuest) + { + $this->_name=''; + $this->_roles=array(); + } + } + + public function getRoles() + { + return $this->_roles; + } + + public function setRoles($value) + { + if(is_array($value)) + $this->_roles=$value; + else + { + $this->_roles=array(); + foreach(explode(',',$value) as $role) + $this->_roles[]=trim($value); + } + } + + public function isInRole($role) + { + return in_array($role,$this->_roles); + } + + public function saveToString() + { + return serialize(array($this->_name,$this->_roles,$this->_isGuest)); + } + + public function loadFromString($data) + { + if(!empty($data)) + { + $array=unserialize($data); + $this->_name=$array[0]; + $this->_roles=$array[1]; + $this->_isGuest=$array[2]; + } + return $this; + } +} + + +class TUserManager extends TComponent implements IModule +{ + private $_id; + private $_users=array(); + private $_guestName='Guest'; + private $_passwordMode='MD5'; + + public function init($application,$config) + { + foreach($config->getElementsByTagName('user') as $node) + $this->_users[$node->getAttribute('name')]=$node->getAttribute('password'); + } + + public function getID() + { + return $this->_id; + } + + public function setID($value) + { + $this->_id=$value; + } + + public function getGuestName() + { + return $this->_guestName; + } + + public function setGuestName($value) + { + $this->_guestName=$value; + } + + public function getPasswordMode() + { + return $this->_passwordMode; + } + + public function setPasswordMode($value) + { + $this->_passwordMode=TPropertyValue::ensureEnum($value,array('Clear','MD5','SHA1')); + } + + public function validateUser($username,$password) + { + if($this->_passwordMode==='MD5') + $password=md5($password); + else if($this->_passwordMode==='SHA1') + $password=sha1($password); + return (isset($this->_users[$username]) && $this->_users[$username]===$password); + } + + public function logout($user) + { + $user->setIsGuest(true); + $user->setName($this->getGuestName()); + } + + public function getUser($username=null) + { + if($username===null) + { + $user=new TUser($this); + $user->setIsGuest($username===null); + return $user; + } + else if(isset($this->_users[$username])) + { + $user=new TUser($this); + $user->setName($username); + return $user; + } + else + return null; + } +} + +?> \ No newline at end of file diff --git a/framework/TApplication.php b/framework/TApplication.php new file mode 100644 index 00000000..973032e5 --- /dev/null +++ b/framework/TApplication.php @@ -0,0 +1,766 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System + */ + +/** + * Includes TPageService class (default service) + */ +require_once(PRADO_DIR.'/Web/Services/TPageService.php'); + +/** + * TApplication class. + * + * TApplication coordinates modules and services, and serves as a configuration + * context for all Prado components. + * + * TApplication adopts a modular structure. A TApplication instance is a composition + * of multiple modules. A module is an instance of class implementing + * {@link IModule} interface. Each module accomplishes certain functionalities + * that are shared by all Prado components in an application. + * There are default modules and user-defined modules. The latter offers extreme + * flexibility of extending TApplication in a plug-and-play fashion. + * Modules cooperate with each other to serve a user request by following + * a sequence of lifecycles predefined in TApplication. + * + * TApplication dispatches each user request to a particular service which + * finishes the actual work for the request with the aid from the application + * modules. + * + * TApplication uses a configuration file to specify the settings of + * the application, the modules, the services, the parameters, and so on. + * + * Examples: + * + * $application=new TApplication($configFile); + * $application->run(); + * + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System + * @since 3.0 + */ +class TApplication extends TComponent implements IApplication +{ + /** + * Default service ID + */ + const DEFAULT_SERVICE='page'; + /** + * @var array list of events that define application lifecycles + */ + private static $_steps=array( + 'BeginRequest', + 'Authentication', + 'PostAuthentication', + 'Authorization', + 'PostAuthorization', + 'LoadState', + 'PostLoadState', + 'PreRunService', + 'RunService', + 'PostRunService', + 'SaveState', + 'PostSaveState', + 'EndRequest' + ); + /** + * @var array list of types that the named modules must be of + */ + private static $_moduleTypes=array( + 'request'=>'THttpRequest', + 'response'=>'THttpResponse', + 'session'=>'THttpSession', + 'cache'=>'ICache', + 'error'=>'IErrorHandler' + ); + + /** + * @var string application ID + */ + private $_id; + /** + * @var string unique application ID + */ + private $_uniqueID; + /** + * @var boolean whether the request is completed + */ + private $_requestCompleted=false; + /** + * @var integer application state + */ + private $_step; + /** + * @var IService current service instance + */ + private $_service; + /** + * @var array list of application modules + */ + private $_modules; + /** + * @var TMap list of application parameters + */ + private $_parameters; + /** + * @var string configuration file + */ + private $_configFile; + /** + * @var string cache file + */ + private $_cacheFile; + /** + * @var string user type + */ + private $_userType='System.Security.TUser'; + /** + * @var IUser user instance + */ + private $_user=null; + + /** + * Constructor. + * Loads application configuration and initializes application. + * If a cache is specified and present, it will be used instead of the configuration file. + * If the cache file is specified but is not present, the configuration file + * will be parsed and the result is saved in the cache file. + * @param string configuration file path (absolute or relative to current running script) + * @param string cache file path + */ + public function __construct($configFile,$cacheFile='') + { + parent::__construct(); + Prado::setApplication($this); + $this->_configFile=$configFile; + $this->_cacheFile=$cacheFile; + } + + /** + * Executes the lifecycles of the application. + */ + public function run() + { + try + { + $this->initApplication($this->_configFile,$this->_cacheFile); + $n=count(self::$_steps); + $this->_step=0; + $this->_requestCompleted=false; + while($this->_step<$n) + { + $method='on'.self::$_steps[$this->_step]; + $this->$method(null); + if($this->_requestCompleted && $this->_step<$n-1) + $this->_step=$n-1; + else + $this->_step++; + } + } + catch(Exception $e) + { + $this->onError($e); + } + } + + /** + * Completes current request processing. + * This method can be used to exit the application lifecycles after finishing + * the current cycle. + */ + public function completeRequest() + { + $this->_requestCompleted=true; + } + + /** + * @return string application ID + */ + public function getID() + { + return $this->_id; + } + + /** + * @param string application ID + */ + public function setID($value) + { + $this->_id=$value; + } + + /** + * @return string an ID that unique identifies this Prado application from the others + */ + public function getUniqueID() + { + return $this->_uniqueID; + } + + /** + * @return IService the currently requested service + */ + public function getService() + { + return $this->_service; + } + + /** + * Adds a module to application. + * Note, this method does not do module initialization. + * Also, if there is already a module with the same ID, an exception will be raised. + * @param string ID of the module + * @param IModule module object + * @throws TInvalidOperationException if a module with the same ID already exists + */ + public function setModule($id,IModule $module) + { + if(isset($this->_modules[$id])) + throw new TInvalidOperationException('application_module_existing',$id); + else + $this->_modules[$id]=$module; + } + + /** + * @return IModule the module with the specified ID, null if not found + */ + public function getModule($id) + { + return isset($this->_modules[$id])?$this->_modules[$id]:null; + } + + /** + * @return array list of loaded application modules, indexed by module IDs + */ + public function getModules() + { + return $this->_modules; + } + + /** + * @return TMap the list of application parameters + */ + public function getParameters() + { + return $this->_parameters; + } + + /** + * @return THttpRequest the request object + */ + public function getRequest() + { + return isset($this->_modules['request'])?$this->_modules['request']:null; + } + + /** + * @return THttpResponse the response object + */ + public function getResponse() + { + return isset($this->_modules['response'])?$this->_modules['response']:null; + } + + /** + * @return THttpSession the session object + */ + public function getSession() + { + return isset($this->_modules['session'])?$this->_modules['session']:null; + } + + /** + * @return ICache the cache object, null if not exists + */ + public function getCache() + { + return isset($this->_modules['cache'])?$this->_modules['cache']:null; + } + + /** + * @return IErrorHandler the error hanlder module + */ + public function getErrorHandler() + { + return isset($this->_modules['error'])?$this->_modules['error']:null; + } + + /** + * @return IRoleProvider provider for user auth management + */ + public function getAuthManager() + { + return isset($this->_modules['auth'])?$this->_modules['auth']:null; + } + + /** + * @return IUser the application user + */ + public function getUser() + { + return $this->_user; + } + + /** + * @param IUser the application user + */ + public function setUser(IUser $user) + { + $this->_user=$user; + } + + /** + * Loads configuration and initializes application. + * Configuration file will be read and parsed (if a valid cache version exists, + * it will be used instead). Then, modules are created and initialized; + * The requested service is created and initialized. + * @param string configuration file path (absolute or relative to current executing script) + * @param string cache file path, empty if no present or needed + * @throws TConfigurationException if config file is not given, or module is redefined of invalid type, or service not defined or of invalid type + */ + protected function initApplication($configFile,$cacheFile) + { + if($cacheFile==='' || @filemtime($cacheFile)loadFromFile($configFile); + if($cacheFile!=='') + { + if(($fp=fopen($cacheFile,'wb'))!==false) + { + fputs($fp,Prado::serialize($config)); + fclose($fp); + } + else + syslog(LOG_WARNING,'Prado application config cache file '.$cacheFile.' cannot be created.'); + } + } + else + { + $config=Prado::unserialize(file_get_contents($cacheFile)); + } + + // generates unique ID by hashing the configuration file path + $this->_uniqueID=md5(realpath($configFile)); + + // set path aliases and using namespaces + foreach($config->getAliases() as $alias=>$path) + Prado::setPathOfAlias($alias,$path); + foreach($config->getUsings() as $using) + Prado::using($using); + + // set application properties + foreach($config->getProperties() as $name=>$value) + $this->setPropertyByPath($name,$value); + + // load parameters + $this->_parameters=new TMap; + foreach($config->getParameters() as $id=>$parameter) + { + if(is_string($parameter)) + $this->_parameters->add($id,$parameter); + else + { + $component=Prado::createComponent($parameter[0]); + foreach($parameter[1] as $name=>$value) + $component->setPropertyByPath($name,$value); + $this->_parameters->add($id,$component); + } + } + + // load and init modules specified in app config + $this->_modules=array(); + foreach($config->getModules() as $id=>$moduleConfig) + { + if(isset($this->_modules[$id])) + throw new TConfigurationException('application_module_redefined',$id); + $module=Prado::createComponent($moduleConfig[0]); + if(isset(self::$_moduleTypes[$id]) && !($module instanceof self::$_moduleTypes[$id])) + throw new TConfigurationException('application_module_invalid',$id,self::$_moduleTypes[$id]); + $this->_modules[$id]=$module; + foreach($moduleConfig[1] as $name=>$value) + $module->setPropertyByPath($name,$value); + $module->init($this,$moduleConfig[2]); + } + + if(($serviceID=$this->getRequest()->getServiceID())===null) + $serviceID=self::DEFAULT_SERVICE; + if(($serviceConfig=$config->getService($serviceID))!==null) + { + $service=Prado::createComponent($serviceConfig[0]); + if(!($service instanceof IService)) + throw new TConfigurationException('application_service_invalid',$serviceID); + $this->_service=$service; + foreach($serviceConfig[1] as $name=>$value) + $service->setPropertyByPath($name,$value); + $service->init($this,$serviceConfig[2]); + $this->attachEventHandler('RunService',array($service,'run')); + } + else + throw new TConfigurationException('application_service_unknown',$serviceID); + } + + /** + * Raises Error event. + * This method is invoked when an exception is raised during the lifecycles + * of the application. + * @param mixed event parameter + */ + public function onError($param) + { + if($this->hasEventHandler('Error')) + $this->raiseEvent('Error',$this,$param); + else + echo $param; + } + + /** + * Raises BeginRequest event. + * At the time when this method is invoked, application modules are loaded + * and initialized, user request is resolved and the corresponding service + * is loaded and initialized. The application is about to start processing + * the user request. + * @param mixed event parameter + */ + public function onBeginRequest($param) + { + $this->raiseEvent('BeginRequest',$this,$param); + } + + /** + * Raises Authentication event. + * This method is invoked when the user request needs to be authenticated. + * @param mixed event parameter + */ + public function onAuthentication($param) + { + $this->raiseEvent('Authentication',$this,$param); + } + + /** + * Raises PostAuthentication event. + * This method is invoked right after the user request is authenticated. + * @param mixed event parameter + */ + public function onPostAuthentication($param) + { + $this->raiseEvent('PostAuthentication',$this,$param); + } + + /** + * Raises Authorization event. + * This method is invoked when the user request needs to be authorized. + * @param mixed event parameter + */ + public function onAuthorization($param) + { + $this->raiseEvent('Authorization',$this,$param); + } + + /** + * Raises PostAuthorization event. + * This method is invoked right after the user request is authorized. + * @param mixed event parameter + */ + public function onPostAuthorization($param) + { + $this->raiseEvent('PostAuthorization',$this,$param); + } + + /** + * Raises LoadState event. + * This method is invoked when the application needs to load state (probably stored in session). + * @param mixed event parameter + */ + public function onLoadState($param) + { + $this->raiseEvent('LoadState',$this,$param); + } + + /** + * Raises PostLoadState event. + * This method is invoked right after the application state has been loaded. + * @param mixed event parameter + */ + public function onPostLoadState($param) + { + $this->raiseEvent('PostLoadState',$this,$param); + } + + /** + * Raises PreRunService event. + * This method is invoked right before the service is to be run. + * @param mixed event parameter + */ + public function onPreRunService($param) + { + $this->raiseEvent('PreRunService',$this,$param); + } + + /** + * Raises RunService event. + * This method is invoked when the service runs. + * @param mixed event parameter + */ + public function onRunService($param) + { + $this->raiseEvent('RunService',$this,$param); + } + + /** + * Raises PostRunService event. + * This method is invoked right after the servie is run. + * @param mixed event parameter + */ + public function onPostRunService($param) + { + $this->raiseEvent('PostRunService',$this,$param); + } + + /** + * Raises SaveState event. + * This method is invoked when the application needs to save state (probably stored in session). + * @param mixed event parameter + */ + public function onSaveState($param) + { + $this->raiseEvent('SaveState',$this,$param); + } + + /** + * Raises PostSaveState event. + * This method is invoked right after the application state has been saved. + * @param mixed event parameter + */ + public function onPostSaveState($param) + { + $this->raiseEvent('PostSaveState',$this,$param); + } + + /** + * Raises EndRequest event. + * This method is invoked when the application completes the processing of the request. + * @param mixed event parameter + */ + public function onEndRequest($param) + { + $this->raiseEvent('EndRequest',$this,$param); + } +} + + +/** + * TApplicationConfiguration class. + * + * This class is used internally by TApplication to parse and represent application configuration. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System + * @since 3.0 + */ +class TApplicationConfiguration extends TComponent +{ + /** + * @var array list of application initial property values, indexed by property names + */ + private $_properties=array(); + /** + * @var array list of namespaces to be used + */ + private $_usings=array(); + /** + * @var array list of path aliases, indexed by alias names + */ + private $_aliases=array(); + /** + * @var array list of module configurations + */ + private $_modules=array( + 'request'=>array('THttpRequest',array(),null), + 'response'=>array('THttpResponse',array(),null), + 'error'=>array('TErrorHandler',array(),null) + ); + /** + * @var array list of service configurations + */ + private $_services=array( + 'page'=>array('TPageService',array(),null) + ); + /** + * @var array list of parameters + */ + private $_parameters=array(); + + /** + * Parses the application configuration file. + * @param string configuration file name + * @throws TConfigurationException if config file cannot be read or any parsing error is found + */ + public function loadFromFile($fname) + { + if(!is_file($fname)) + throw new TConfigurationException('application_configuration_inexistent',$fname); + $configPath=dirname($fname); + $dom=new TXmlDocument; + $dom->loadFromFile($fname); + + // application properties + foreach($dom->getAttributes() as $name=>$value) + $this->_properties[$name]=$value; + + // paths + if(($pathsNode=$dom->getElementByTagName('paths'))!==null) + { + foreach($pathsNode->getElementsByTagName('alias') as $aliasNode) + { + if(($id=$aliasNode->getAttribute('id'))!==null && ($path=$aliasNode->getAttribute('path'))!==null) + { + $path=str_replace('\\','/',$path); + if(preg_match('/^\\/|.:\\//',$path)) // if absolute path + $p=realpath($path); + else + $p=realpath($configPath.'/'.$path); + if($p===false || !is_dir($p)) + throw new TConfigurationException('application_alias_path_invalid',$id,$path); + $this->_aliases[$id]=$p; + } + else + throw new TConfigurationException('application_alias_element_invalid'); + } + foreach($pathsNode->getElementsByTagName('using') as $usingNode) + { + if(($namespace=$usingNode->getAttribute('namespace'))!==null) + $this->_usings[]=$namespace; + else + throw new TConfigurationException('application_using_element_invalid'); + } + } + + // application modules + if(($modulesNode=$dom->getElementByTagName('modules'))!==null) + { + foreach($modulesNode->getElementsByTagName('module') as $node) + { + $properties=$node->getAttributes(); + if(($id=$properties->itemAt('id'))===null) + throw new TConfigurationException('application_module_element_invalid'); + if(($type=$properties->remove('type'))===null && isset($this->_modules[$id]) && $this->_modules[$id][2]===null) + { + $type=$this->_modules[$id][0]; + unset($this->_modules[$id]); + } + if($type===null) + throw new TConfigurationException('application_module_element_invalid'); + if(isset($this->_modules[$id])) + throw new TConfigurationException('application_module_redefined',$id); + else + { + $node->setParent(null); + $this->_modules[$id]=array($type,$properties->toArray(),$node); + } + } + } + + // services + if(($servicesNode=$dom->getElementByTagName('services'))!==null) + { + foreach($servicesNode->getElementsByTagName('service') as $node) + { + $properties=$node->getAttributes(); + if(($id=$properties->itemAt('id'))===null) + throw new TConfigurationException('application_service_element_invalid'); + if(($type=$properties->remove('type'))===null && isset($this->_services[$id]) && $this->_services[$id][2]===null) + { + $type=$this->_services[$id][0]; + unset($this->_services[$id]); + } + if($type===null) + throw new TConfigurationException('application_service_element_invalid'); + if(isset($this->_services[$id])) + throw new TConfigurationException('application_service_redefined',$id); + else + { + $node->setParent(null); + $this->_services[$id]=array($type,$properties->toArray(),$node); + } + } + } + + // parameters + if(($parametersNode=$dom->getElementByTagName('parameters'))!==null) + { + foreach($parametersNode->getElementsByTagName('parameter') as $node) + { + $properties=$node->getAttributes(); + if(($id=$properties->remove('id'))===null) + throw new TConfigurationException('application_parameter_element_invalid'); + if(($type=$properties->remove('type'))===null) + $this->_parameters[$id]=$node->getValue(); + else + $this->_parameters[$id]=array($type,$properties->toArray()); + } + } + } + + /** + * @return array list of application initial property values, indexed by property names + */ + public function getProperties() + { + return $this->_properties; + } + + /** + * @return array list of path aliases, indexed by alias names + */ + public function getAliases() + { + return $this->_aliases; + } + + /** + * @return array list of namespaces to be used + */ + public function getUsings() + { + return $this->_usings; + } + + /** + * @return array list of module configurations + */ + public function getModules() + { + return $this->_modules; + } + + /** + * @return array list of service configurations + */ + public function getService($id) + { + return isset($this->_services[$id])?$this->_services[$id]:null; + } + + /** + * @return array list of parameters + */ + public function getParameters() + { + return $this->_parameters; + } +} + +?> \ No newline at end of file diff --git a/framework/TComponent.php b/framework/TComponent.php new file mode 100644 index 00000000..36a06632 --- /dev/null +++ b/framework/TComponent.php @@ -0,0 +1,535 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System + */ + +/** + * TComponent class + * + * TComponent is the base class for all PRADO components. + * TComponent implements the protocol of defining, using properties and events. + * + * A property is defined by a getter method, and/or a setter method. + * Properties can be accessed in the way like accessing normal object members. + * Reading or writing a property will cause the invocation of the corresponding + * getter or setter method, e.g., + * + * $a=$this->Text; // equivalent to $a=$this->getText(); + * $this->Text='abc'; // equivalent to $this->setText('abc'); + * + * The signatures of getter and setter methods are as follows, + * + * // getter, defines a readable property 'Text' + * function getText() { ... } + * // setter, defines a writable property 'Text', with $value being the value to be set to the property + * function setText($value) { ... } + * + * Property names are case-insensitive. It is recommended that they are written + * in the format of concatenated words, with the first letter of each word + * capitalized (e.g. DisplayMode, ItemStyle). + * + * An event is defined by the presence of a method whose name is the event name prefixed with 'on'. + * The event name is case-insensitive. + * An event can be attached with one or several methods (called event handlers). + * An event can be raised by calling {@link raiseEvent} method, upon which + * the attached event handlers will be invoked automatically in the order they + * are attached to the event. Event handlers must have the following signature, + * + * function eventHandlerFuncName($sender,$param) { ... } + * + * where $sender refers to the object who is responsible for the raising of the event, + * and $param refers to a structure that may contain event-specific information. + * To raise an event (assuming named as 'Click') of a component, use + * + * $component->raiseEvent('Click'); + * + * To attach an event handler to an event, use one of the following ways, + * + * $component->Click=$callback; // or $component->Click->add($callback); + * $$component->attachEventHandler('Click',$callback); + * + * The first two ways make use of the fact that $component->Click refers to + * the event handler list {@link TList} for the 'Click' event. + * The variable $callback contains the definition of the event handler that can + * be either a string referring to a global function name, or an array whose + * first element refers to an object and second element a method name/path that + * is reachable by the object, e.g. + * - 'buttonClicked' : buttonClicked($sender,$param); + * - array($object,'buttonClicked') : $object->buttonClicked($sender,$param); + * - array($object,'MainContent.SubmitButton.buttonClicked') : + * $object->MainContent->SubmitButton->buttonClicked($sender,$param); + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System + * @since 3.0 + */ +class TComponent +{ + /** + * @var array event handler lists + */ + private $_e=array(); + + /** + * Constructor. + */ + public function __construct() + { + } + + /** + * Destructor. + */ + public function __destruct() + { + } + + /** + * Returns a property value or an event handler list by property or event name. + * Do not call this method. This is a PHP magic method that we override + * to allow using the following syntax to read a property: + * + * $value=$component->PropertyName; + * + * and to obtain the event handler list for an event, + * + * $eventHandlerList=$component->EventName; + * + * @param string the property name or the event name + * @return mixed the property value or the event handler list + * @throws TInvalidOperationException if the property/event is not defined. + */ + public function __get($name) + { + $getter='get'.$name; + if(method_exists($this,$getter)) + { + // getting a property + return $this->$getter(); + } + else if(method_exists($this,'on'.$name)) + { + // getting an event (handler list) + $name=strtolower($name); + if(!isset($this->_e[$name])) + $this->_e[$name]=new TList; + return $this->_e[$name]; + } + else + { + throw new TInvalidOperationException('component_property_undefined',get_class($this),$name); + } + } + + /** + * Sets value of a component property. + * Do not call this method. This is a PHP magic method that we override + * to allow using the following syntax to set a property or attach an event handler. + * + * $this->PropertyName=$value; + * $this->EventName=$handler; + * + * @param string the property name or event name + * @param mixed the property value or event handler + * @throws TInvalidOperationException If the property is not defined or read-only. + */ + public function __set($name,$value) + { + $setter='set'.$name; + if(method_exists($this,$setter)) + { + $this->$setter($value); + } + else if(method_exists($this,'on'.$name)) + { + $this->attachEventHandler($name,$value); + } + else if(method_exists($this,'get'.$name)) + { + throw new TInvalidOperationException('component_property_readonly',get_class($this),$name); + } + else + { + throw new TInvalidOperationException('component_property_undefined',get_class($this),$name); + } + } + + /** + * Determines whether a property is defined. + * A property is defined if there is a getter or setter method + * defined in the class. Note, property names are case-insensitive. + * @param string the property name + * @return boolean whether the property is defined + */ + final public function hasProperty($name) + { + return method_exists($this,'get'.$name) || method_exists($this,'set'.$name); + } + + /** + * Determines whether a property can be read. + * A property can be read if the class has a getter method + * for the property name. Note, property name is case-insensitive. + * @param string the property name + * @return boolean whether the property can be read + */ + final public function canGetProperty($name) + { + return method_exists($this,'get'.$name); + } + + /** + * Determines whether a property can be set. + * A property can be written if the class has a setter method + * for the property name. Note, property name is case-insensitive. + * @param string the property name + * @return boolean whether the property can be written + */ + final public function canSetProperty($name) + { + return method_exists($this,'set'.$name); + } + + /** + * Evaluates a property path. + * A property path is a sequence of property names concatenated by '.' character. + * For example, 'Parent.Page' refers to the 'Page' property of the component's + * 'Parent' property value (which should be a component also). + * @param string property path + * @return mixed the property path value + */ + public function getPropertyByPath($path) + { + $object=$this; + foreach(explode('.',$path) as $property) + $object=$object->$property; + return $object; + } + + /** + * Sets a value to a property path. + * A property path is a sequence of property names concatenated by '.' character. + * For example, 'Parent.Page' refers to the 'Page' property of the component's + * 'Parent' property value (which should be a component also). + * @param string property path + * @param mixed the property path value + */ + public function setPropertyByPath($path,$value) + { + $object=$this; + if(($pos=strrpos($path,'.'))===false) + $property=$path; + else + { + $object=$this->getPropertyByPath(substr($path,0,$pos)); + $property=substr($path,$pos+1); + } + $object->$property=$value; + } + + /** + * Determines whether an event is defined. + * An event is defined if the class has a method whose name is the event name prefixed with 'on'. + * Note, event name is case-insensitive. + * @param string the event name + * @return boolean + */ + public function hasEvent($name) + { + return method_exists($this,'on'.$name); + } + + /** + * @return boolean whether an event has been attached one or several handlers + */ + public function hasEventHandler($name) + { + $name=strtolower($name); + return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0; + } + + /** + * Returns the list of attached event handlers for an event. + * @return TList list of attached event handlers for an event + * @throws TInvalidOperationException if the event is not defined + */ + public function getEventHandlers($name) + { + if(method_exists($this,'on'.$name)) + { + $name=strtolower($name); + if(!isset($this->_e[$name])) + $this->_e[$name]=new TList; + return $this->_e[$name]; + } + else + throw new TInvalidOperationException('component_event_undefined',get_class($this),$name); + } + + /** + * Attaches an event handler to an event. + * + * The handler must be a valid PHP callback, i.e., a string referring to + * a global function name, or an array containing two elements with + * the first element being an object and the second element a method name + * of the object. In Prado, you can also use method path to refer to + * an event handler. For example, array($object,'Parent.buttonClicked') + * uses a method path that refers to the method $object->Parent->buttonClicked(...). + * + * The event handler must be of the following signature, + * + * function handlerName($sender,$param) {} + * + * where $sender represents the object that raises the event, + * and $param is the event parameter. + * + * This is a convenient method to add an event handler. + * It is equivalent to {@link getEventHandlers}($name)->add($handler). + * For complete management of event handlers, use {@link getEventHandlers} + * to get the event handler list first, and then do various + * {@link TList} operations to append, insert or remove + * event handlers. You may also do these operations like + * getting and setting properties, e.g., + * + * $component->Click[]=array($object,'buttonClicked'); + * $component->Click->addAt(0,array($object,'buttonClicked')); + * + * which are equivalent to the following + * + * $component->getEventHandlers('Click')->add(array($object,'buttonClicked')); + * $component->getEventHandlers('Click')->addAt(0,array($object,'buttonClicked')); + * + * + * @param string the event name + * @param callback the event handler + * @throws TInvalidOperationException if the event does not exist + */ + public function attachEventHandler($name,$handler) + { + $this->getEventHandlers($name)->add($handler); + } + + /** + * Raises an event. + * This method represents the happening of an event and will + * invoke all attached event handlers for the event. + * @param string the event name + * @param mixed the event sender object + * @param TEventParameter the event parameter + * @throws TInvalidOperationException if the event is undefined + * @throws TInvalidDataValueException If an event handler is invalid + */ + public function raiseEvent($name,$sender,$param) + { + $name=strtolower($name); + if(isset($this->_e[$name])) + { + foreach($this->_e[$name] as $handler) + { + if(is_string($handler)) + { + call_user_func($handler,$sender,$param); + } + else if(is_callable($handler,true)) + { + // an array: 0 - object, 1 - method name/path + list($object,$method)=$handler; + if(($pos=strrpos($method,'.'))!==false) + { + $object=$this->getPropertyByPath(substr($method,0,$pos)); + $method=substr($method,$pos+1); + } + $object->$method($sender,$param); + } + else + throw new TInvalidDataValueException('component_event_handler_invalid',$handler); + } + } + else if(!$this->hasEvent($name)) + throw new TInvalidOperationException('component_event_undefined',get_class($this),$name); + } + + /** + * Evaluates a PHP expression in the context of this control. + * @return mixed the expression result + * @throws TInvalidOperationException if the expression is invalid + */ + public function evaluateExpression($expression) + { + try + { + if(eval("\$result=$expression;")===false) + throw new Exception(''); + return $result; + } + catch(Exception $e) + { + throw new TInvalidOperationException('component_expression_invalid',$expression,$e->getMessage()); + } + } + + /** + * Evaluates a list of PHP statements. + * @param string PHP statements + * @return string content echoed or printed by the PHP statements + * @throw TInvalidOperationException if the statements are invalid + */ + public function evaluateStatements($statements) + { + try + { + ob_start(); + if(eval($statements)===false) + throw new Exception(''); + $content=ob_get_contents(); + ob_end_clean(); + return $content; + } + catch(Exception $e) + { + throw new TInvalidOperationException('component_statements_invalid',$statements,$e->getMessage()); + } + } +} + +/** + * TPropertyValue class + * + * TPropertyValue is a utility class that provides static methods + * to convert component property values to specific types. + * + * TPropertyValue is commonly used in component setter methods to ensure + * the new property value is of specific type. + * For example, a boolean-typed property setter method would be as follows, + * + * function setPropertyName($value) { + * $value=TPropertyValue::ensureBoolean($value); + * // $value is now of boolean type + * } + * + * + * Properties can be of the following types with specific type conversion rules: + * - string: a boolean value will be converted to 'true' or 'false'. + * - boolean: string 'true' (case-insensitive) will be converted to true, + * string 'false' (case-insensitive) will be converted to false. + * - integer + * - float + * - array + * - object + * - enum: enumerable type, represented by an array of strings. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System + * @since 3.0 + */ +class TPropertyValue +{ + /** + * Converts a value to boolean type. + * Note, string 'true' (case-insensitive) will be converted to true, + * string 'false' (case-insensitive) will be converted to false. + * @param mixed the value to be converted. + * @return boolean + */ + public static function ensureBoolean($value) + { + if (is_string($value)) + return strcasecmp($value,'true')==0; + else + return (boolean)$value; + } + + /** + * Converts a value to string type. + * Note, a boolean value will be converted to 'true' if it is true + * and 'false' if it is false. + * @param mixed the value to be converted. + * @return string + */ + public static function ensureString($value) + { + if (is_bool($value)) + return $value?'true':'false'; + else + return (string)$value; + } + + /** + * Converts a value to integer type. + * @param mixed the value to be converted. + * @return integer + */ + public static function ensureInteger($value) + { + return (integer)$value; + } + + /** + * Converts a value to float type. + * @param mixed the value to be converted. + * @return float + */ + public static function ensureFloat($value) + { + return (float)$value; + } + + /** + * Converts a value to array type. + * @param mixed the value to be converted. + * @return array + */ + public static function ensureArray($value) + { + return (array)$value; + } + + /** + * Converts a value to object type. + * @param mixed the value to be converted. + * @return object + */ + public static function ensureObject($value) + { + return (object)$value; + } + + /** + * Converts a value to enum type. + * @param mixed the value to be converted. + * @param array array of strings representing the enum type. + * @return string + * @throws TInvalidDataValueException if the original value is not in the string array. + */ + public static function ensureEnum($value,$enum) + { + if(($index=array_search($value,$enum))!==false) + return $enum[$index]; + else + throw new TInvalidDataValueException('propertyvalue_enumvalue_invalid',$value,implode(',',$enum)); + } +} + +/** + * TEventParameter class. + * TEventParameter is the base class for all event parameter classes. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System + * @since 3.0 + */ +class TEventParameter extends TComponent +{ +} + +?> \ No newline at end of file diff --git a/framework/TODO.txt b/framework/TODO.txt new file mode 100644 index 00000000..0bfaab26 --- /dev/null +++ b/framework/TODO.txt @@ -0,0 +1,306 @@ + +think more about encoding/decoding +<%@ MasterClass="Pages.MasterPage" %> +THtmlTextWriter::addStyleAttribute(), also change how TStyle renders its content. + + +callback + +http://www.xisc.com/index.php?page=homepage + +Features to be implemented later: +- SmartNavigation: TForm, TPage +- DefaultButton: TForm, TClientScriptManager + +Main Problems: +1. How to solve viewstate ID mapping problems? What if a control has changed its ID before saving viewstate? +5. What if in a getter, it needs to address a sibling or child control? +6. learn more details about WebParts +http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odc_sp2003_ta/html/sharepoint_northwindwebparts.asp + +When a page is requested, asp.net 2.0 does the following +- application creates the page instance by new operator +- application invokes page.processrequest +- page.frameworkinitialize is invoked +- ... ControlBuilder.InitObject(page) +- ... ... set SkinID +- ... ... apply stylesheet skin +- ... ... init simple properties (basic property types) +- ... ... init complex proprerties (e.g. Font-Name), may need to call InitObject on Font +- ... ... init data bindings +- ... ... call BuildChildren if item implements IParserAccessor (Control implements it) +- ... ... ... for each body item +- ... ... ... ... get the control builder for the control class +- ... ... ... ... call ControlBuilder.BuildObject +- ... ... ... ... ... call InitObject +- ... ... ... ... if it is user control (control with template) +- ... ... ... ... ... call UserControl.InitializeAsUserControl(page) +- ... ... ... ... ... ... call frameworkinitialize (won't call InitObject anymore) +- ... ... ... ... call control.AddParsedSubObject(item) +- ... ... init template properties (should be a property with template type, will use TemplateBuilder to build the object) +- ... ... bind field to control (pass some fields from TemplateControl to the new control) + +How is a UserControl initialized if created dynamically? +- ... InitializeAsUserControl invoked in OnInit (which will be caught up if the control is dynamically created) + + + + +Findings: + + +Control lifecycles: + +const CS_CONSTRUCTED=0; // after constructor +const CS_FRAMEWORK_INITIALIZED=1; // after children created and properties set +const CS_CHILDREN_INITIALIZED=2; // right before OnInit (also before applySkin, but after children OnInit) +const CS_INITIALIZED=3; // right after OnInit +const CS_STATE_LOADED=4; // right after loading state +const CS_LOADED=5; // right after loaded +const CS_PRERENDERED=6; // right after prerender + +stylesheet is applied before setting control properties (after skinID is set) +skin is applied right before OnInit + + + +ControlBuilder is responsible to call AddParsedSubObject +Its BuildChildren is + +My understanding of lifecycles: + +Page constructed (using new operator) +Page.ProcessRequest + Page.FrameworkInitialize + Page.InitializeStyleSheet + Page.determinePostBackMode + Page.loadScrollPosition + Page.performPreInit + Page.initRecursive + Page.onInitComplete + Page.loadAllState + Page.processPostData + Page.onPreLoad + Page.loadRecursive + Page.processPostData + Page.raiseChangedEvents + Page.raisePostBackEvent + Page.onLoadComplete + Page.raiseCallBackEvent -> exit + Page.preRenderRecursive + Page.performPreRenderComplete + Page.saveAllState + Page.onSaveStateComplete + Page.renderControl + Page.unloadRecursive + + +Possible solution for SkinID: setting SkinID will cause skin change immediately. +With control hierarchy storing: + + +Page constructed (template parsed but not instantiated) +Page.loadAllState <---- page state totally restored +Page.loadRecursive +Page.processPostData +Page.raiseChangedEvents +Page.raisePostBackEvent or Page.raiseCallBackEvent +Page.preRenderRecursive +Page.saveAllState +Page.renderControl +Page.unloadRecursive + + + +Page constructed +Page.frameworkInitialize (instantiating template) +Page.initRecursive +Page.saveAllState +Page.renderControl +Page.unloadRecursive + + + + +edit distance. +(UIUC) Jiawei Han: graph similarity mining + +module service? +page service? + + +index.php?page=path.to.page + + +TODOs + +renderer?? +Dispose +-->> viewstate id-based or index-based, structure keeping?? <<-- +HttpContext, url/path +template path +adapter +parser + + +class metadata attributes: +e.g. the body content of a control can be parsed as child controls, or property values +or list items + +Imagine a usecase (hmmm...could have problem....) How to specify two list properties for a single control? + +abc + + xxx + yyy + + + + +how to define a control with template?? +TemplateControl.LoadControl or LoadTemplate is used for controls that allows taking template contents for their attributes. + + +UserControl! starting from the template instead of class + + + +idNotCalculated = 1; +marked = 2; +disableViewState = 4; +controlsCreated = 8; +invisible = 0x10; +visibleDirty = 0x20; +idNotRequired = 0x40; +isNamingContainer = 0x80; +creatingControls = 0x100; +notVisibleOnPage = 0x200; +themeApplied = 0x400; +mustRenderID = 0x800; +disableTheming = 0x1000; +enableThemingSet = 0x2000; +styleSheetApplied = 0x4000; +controlAdapterResolved = 0x8000; +designMode = 0x10000; +designModeChecked = 0x20000; +disableChildControlState = 0x40000; +isWebControlDisabled = 0x80000; +controlStateApplied = 0x100000; +useGeneratedID = 0x200000; + +TODO: + +clean up ID, namingcontainer things: + +A control can be added into page hierarchy in the following ways +- newly created in template + - manual ID + - need automatic ID +- dynamically created in code + - manual ID + - need automatic ID +- a previously removed control + - manual ID + - need automatic ID +When a control changes its ID, the following things are necessary: +- If it is a namingContainer + - all its descendant must update their unique ID +- If it is a normal control, nothing needs to be done +- In both cases, the namingContainer's nametable has to be updated +When a control changes its page, ...? +- All its children have to change the page too +When a control changes its parent, ...? +- This is like remvoedControl + addedControl. +When a control changes its namingcontainer ...? +- All its child controls have to change namingcontainer recursively + The old namingContainer nametable must also be changed recursively. +When a control changes its templateControl...?? +- Nothing to be done. + + + +ControlState +============ +Constructed +Initialized +ViewStateLoaded +Loaded +PreRendered + + + +asp.net 2.0 lifecycles +======================== +Application: BeginRequest +Application: PreAuthenticateRequest +Application: AuthenticateRequest +Application: PostAuthenticateRequest +Application: PreAuthorizeRequest +Application: AuthorizeRequest +Application: PostAuthorizeRequest +Application: PreResolveRequestCache +Application: ResolveRequestCache +Application: PostResolveRequestCache +Application: PreMapRequestHandler +Page: Construct +Application: PostMapRequestHandler +Application: PreAcquireRequestState +Application: AcquireRequestState +Application: PostAcquireRequestState +Application: PreRequestHandlerExecute +Page: AddParsedSubObject +Page: CreateControlCollection +Page: AddedControl +Page: AddParsedSubObject +Page: AddedControl +Page: ResolveAdapter +Page: DeterminePostBackMode +Page: PreInit +Control: ResolveAdapter +Control: Init +Control: TrackViewState +Page: Init +Page: TrackViewState +Page: InitComplete +Page: LoadPageStateFromPersistenceMedium +Control: LoadViewState +Page: EnsureChildControls +Page: CreateChildControls +Page: PreLoad +Page: Load +Control: DataBind +Control: Load +Page: EnsureChildControls +Page: LoadComplete +Page: EnsureChildControls +Page: PreRender +Control: EnsureChildControls +Control: PreRender +Page: PreRenderComplete +Page: SaveViewState +Control: SaveViewState +Page: SaveViewState +Control: SaveViewState +Page: SavePageStateToPersistenceMedium +Page: SaveStateComplete +Page: CreateHtmlTextWriter +Page: RenderControl +Page: Render +Page: RenderChildren +Control: RenderControl +Page: VerifyRenderingInServerForm +Page: CreateHtmlTextWriter +Control: Unload +Control: Dispose +Page: Unload +Page: Dispose +Application: PostRequestHandlerExecute +Application: PreReleaseRequestState +Application: ReleaseRequestState +Application: PostReleaseRequestState +Application: PreUpdateRequestCache +Application: UpdateRequestCache +Application: PostUpdateRequestCache +Application: EndRequest +Application: PreSendRequestHeaders +Application: PreSendRequestContent \ No newline at end of file diff --git a/framework/Web/Javascripts/WebForms.js b/framework/Web/Javascripts/WebForms.js new file mode 100644 index 00000000..79e0eeaa --- /dev/null +++ b/framework/Web/Javascripts/WebForms.js @@ -0,0 +1,298 @@ +function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit) { + this.eventTarget = eventTarget; + this.eventArgument = eventArgument; + this.validation = validation; + this.validationGroup = validationGroup; + this.actionUrl = actionUrl; + this.trackFocus = trackFocus; + this.clientSubmit = clientSubmit; +} +function WebForm_DoPostBackWithOptions(options) { + var validationResult = true; + if (options.validation) { + if (typeof(Page_ClientValidate) == 'function') { + validationResult = Page_ClientValidate(options.validationGroup); + } + } + if (validationResult) { + if ((typeof(options.actionUrl) != "undefined") && (options.actionUrl != null) && (options.actionUrl.length > 0)) { + theForm.action = options.actionUrl; + } + if (options.trackFocus) { + var lastFocus = theForm.elements["__LASTFOCUS"]; + if ((typeof(lastFocus) != "undefined") && (lastFocus != null)) { + if (typeof(document.activeElement) == "undefined") { + lastFocus.value = options.eventTarget; + } + else { + var active = document.activeElement; + if ((typeof(active.id) != "undefined") && (active != null)) { + if ((typeof(active.id) != "undefined") && (active.id != null) && (active.id.length > 0)) { + lastFocus.value = active.id; + } + else if (typeof(active.name) != "undefined") { + lastFocus.value = active.name; + } + } + } + } + } + } + if (options.clientSubmit) { + __doPostBack(options.eventTarget, options.eventArgument); + } +} +var __callbackObject = new Object(); +function WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync) { + var postData = __theFormPostData + + "__CALLBACKID=" + WebForm_EncodeCallback(eventTarget) + + "&__CALLBACKPARAM=" + WebForm_EncodeCallback(eventArgument); + var xmlRequest; + var usePost = false; + if (__nonMSDOMBrowser) { + // http: + // And: http: + xmlRequest = new XMLHttpRequest(); + if (pageUrl.length + postData.length + 1 > 10000) { + usePost = true; + } + if (usePost) { + xmlRequest.open("POST", pageUrl, false); + xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + xmlRequest.send(postData); + } + else { + if (pageUrl.indexOf("?") != -1) { + xmlRequest.open("GET", pageUrl + "&" + postData, false); + } + else { + xmlRequest.open("GET", pageUrl + "?" + postData, false); + } + xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + xmlRequest.send(null); + } + var response = xmlRequest.responseText; + if (response.charAt(0) == "s") { + if ((typeof(eventCallback) != "undefined") && (eventCallback != null)) { + eventCallback(response.substring(1), context); + } + } + else { + if ((typeof(errorCallback) != "undefined") && (errorCallback != null)) { + errorCallback(response.substring(1), context); + } + } + } + else { + xmlRequest = new ActiveXObject("Microsoft.XMLHTTP"); + xmlRequest.onreadystatechange = WebForm_CallbackComplete; + __callbackObject.xmlRequest = xmlRequest; + __callbackObject.eventCallback = eventCallback; + __callbackObject.context = context; + __callbackObject.errorCallback = errorCallback; + if (pageUrl.length + postData.length + 1 > 2067) { + usePost = true; + } + if (usePost) { + xmlRequest.open("POST", pageUrl, useAsync); + xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + xmlRequest.send(postData); + } + else { + if (pageUrl.indexOf("?") != -1) { + xmlRequest.open("GET", pageUrl + "&" + postData, useAsync); + } + else { + xmlRequest.open("GET", pageUrl + "?" + postData, useAsync); + } + xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + xmlRequest.send(); + } + } +} +function WebForm_CallbackComplete() { + if (__callbackObject.xmlRequest.readyState == 4) { + var response = __callbackObject.xmlRequest.responseText; + if (response.charAt(0) == "s") { + if ((typeof(__callbackObject.eventCallback) != "undefined") && (__callbackObject.eventCallback != null)) { + __callbackObject.eventCallback(response.substring(1), __callbackObject.context); + } + } + else { + if ((typeof(__callbackObject.errorCallback) != "undefined") && (__callbackObject.errorCallback != null)) { + __callbackObject.errorCallback(response.substring(1), __callbackObject.context); + } + } + } +} +var __nonMSDOMBrowser = (window.navigator.appName.toLowerCase().indexOf('explorer') == -1); +var __theFormPostData = ""; +function WebForm_InitCallback() { + var count = theForm.elements.length; + var element; + for (var i = 0; i < count; i++) { + element = theForm.elements[i]; + var tagName = element.tagName.toLowerCase(); + if (tagName == "input") { + var type = element.type; + if (type == "text" || type == "hidden" || type == "password" || + ((type == "checkbox" || type == "radio") && element.checked)) { + __theFormPostData += element.name + "=" + WebForm_EncodeCallback(element.value) + "&"; + } + } + else if (tagName == "select") { + var selectCount = element.children.length; + for (var j = 0; j < selectCount; j++) { + var selectChild = element.children[j]; + if ((selectChild.tagName.toLowerCase() == "option") && (selectChild.selected == true)) { + __theFormPostData += element.name + "=" + WebForm_EncodeCallback(selectChild.value) + "&"; + } + } + } + else if (tagName == "textarea") { + __theFormPostData += element.name + "=" + WebForm_EncodeCallback(element.value) + "&"; + } + } +} +function WebForm_EncodeCallback(parameter) { + if (encodeURIComponent) { + return encodeURIComponent(parameter); + } + else { + return escape(parameter); + } +} +var __disabledControlArray = new Array(); +function WebForm_ReEnableControls() { + if (typeof(__enabledControlArray) == 'undefined') { + return false; + } + var disabledIndex = 0; + for (var i = 0; i < __enabledControlArray.length; i++) { + var c; + if (__nonMSDOMBrowser) { + c = document.getElementById(__enabledControlArray[i]); + } + else { + c = document.all[__enabledControlArray[i]]; + } + if ((typeof(c) != "undefined") && (c != null) && (c.disabled == true)) { + c.disabled = false; + __disabledControlArray[disabledIndex++] = c; + } + } + setTimeout("WebForm_ReDisableControls()", 0); + return true; +} +function WebForm_ReDisableControls() { + for (var i = 0; i < __disabledControlArray.length; i++) { + __disabledControlArray[i].disabled = true; + } +} +var __defaultFired = false; +function WebForm_FireDefaultButton(event, target) { + if (!__defaultFired && event.keyCode == 13) { + var defaultButton; + if (__nonMSDOMBrowser) { + defaultButton = document.getElementById(target); + } + else { + defaultButton = document.all[target]; + } + if (defaultButton.click != "undefined") { + __defaultFired = true; + defaultButton.click(); + event.cancelBubble = true; + return false; + } + } + return true; +} +function WebForm_GetScrollX() { + if (__nonMSDOMBrowser) { + return window.pageXOffset; + } + else { + if (document.documentElement && document.documentElement.scrollLeft) { + return document.documentElement.scrollLeft; + } + else if (document.body) { + return document.body.scrollLeft; + } + } + return 0; +} +function WebForm_GetScrollY() { + if (__nonMSDOMBrowser) { + return window.pageYOffset; + } + else { + if (document.documentElement && document.documentElement.scrollTop) { + return document.documentElement.scrollTop; + } + else if (document.body) { + return document.body.scrollTop; + } + } + return 0; +} +function WebForm_SaveScrollPositionSubmit() { + if (__nonMSDOMBrowser) { + theForm.elements['__SCROLLPOSITIONY'].value = window.pageYOffset; + theForm.elements['__SCROLLPOSITIONX'].value = window.pageXOffset; + } + else { + theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX(); + theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY(); + } + if ((typeof(WebForm_ScrollPositionSubmit) != "undefined") && (WebForm_ScrollPositionSubmit != null)) { + if (WebForm_ScrollPositionSubmit.apply) { + return WebForm_ScrollPositionSubmit.apply(this); + } + else { + return WebForm_ScrollPositionSubmit(); + } + } + return true; +} +function WebForm_SaveScrollPositionOnSubmit() { + theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX(); + theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY(); + if ((typeof(WebForm_ScrollPositionOnSubmit) != "undefined") && (WebForm_ScrollPositionOnSubmit != null)) { + if (WebForm_ScrollPositionOnSubmit.apply) { + return WebForm_ScrollPositionOnSubmit.apply(this); + } + else { + return WebForm_ScrollPositionOnSubmit(); + } + } + return true; +} +function WebForm_RestoreScrollPosition() { + if (__nonMSDOMBrowser) { + window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value); + } + else { + window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value); + } + if ((typeof(WebForm_ScrollPositionLoad) != "undefined") && (WebForm_ScrollPositionLoad != null)) { + if (WebForm_ScrollPositionLoad.apply) { + return WebForm_ScrollPositionLoad.apply(this); + } + else { + return WebForm_ScrollPositionLoad(); + } + } + return true; +} +function WebForm_TextBoxKeyHandler() { + if (event.keyCode == 13) { + if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) { + if (typeof(event.srcElement.onchange) != "undefined") { + event.srcElement.onchange(); + return false; + } + } + } + return true; +} diff --git a/framework/Web/Services/TAssetService.php b/framework/Web/Services/TAssetService.php new file mode 100644 index 00000000..914aa1a5 --- /dev/null +++ b/framework/Web/Services/TAssetService.php @@ -0,0 +1,70 @@ + + */ +class TAssetManager extends TComponent implements IModule +{ + private $_pubDir=null; + private $_pubUrl=null; + + public function init($context) + { + if(is_null($this->_pubDir)) + throw new TCongiruationException('cache_public_location_required'); + if(is_null($this->_pubUrl)) + throw new TCongiruationException('cache_public_url_required'); + } + + public function getPublicLocation() + { + return $this->_pubDir; + } + + public function setPublicLocation($value) + { + if(is_dir($value)) + $this->_pubDir=realpath($value); + else + throw new TInvalidDataValueException('cache_public_location_invalid'); + } + + public function getPublicUrl() + { + return $this->_pubUrl; + } + + public function setPublicUrl($value) + { + $this->_pubUrl=rtrim($value,'/'); + } + + public function publishLocation($path,$forceOverwrite=false) + { + $name=basename($path); + $prefix=md5(dirname($path)); + } + + public function publishFile($path,$forceOverwrite=false) + { + if(($fullpath=realpath($path))!==false) + { + return $this->_pubUrl.'/'.$fullpath; + } + else + throw new TInvalidDataValueException('cachemanager_path_unpublishable'); + } + + public function unpublishPath($path) + { + } +} + +class TMemcache extends TComponent +{ +} + +class TSqliteCache extends TComponent +{ +} +?> \ No newline at end of file diff --git a/framework/Web/Services/TPageService.php b/framework/Web/Services/TPageService.php new file mode 100644 index 00000000..6a19273d --- /dev/null +++ b/framework/Web/Services/TPageService.php @@ -0,0 +1,625 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Web.Services + */ + +Prado::using('System.Web.UI.TPage'); +/** + * TPageService class. + * + * TPageService implements a service that can serve user requested pages. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Services + * @since 3.0 + */ +class TPageService extends TComponent implements IService +{ + /** + * Configuration file name + */ + const CONFIG_FILE='config.xml'; + /** + * Prefix of ID used for storing parsed configuration in cache + */ + const CONFIG_CACHE_PREFIX='prado:pageservice:'; + /** + * @var string id of this service (page) + */ + private $_id; + /** + * @var string root path of pages + */ + private $_rootPath; + /** + * @var string default page + */ + private $_defaultPage=null; + /** + * @var string requested page (path) + */ + private $_pagePath; + /** + * @var string requested page type + */ + private $_pageType; + /** + * @var array list of initial page property values + */ + private $_properties; + /** + * @var integer cache expiration + */ + private $_cacheExpire=-1; + /** + * @var boolean whether service is initialized + */ + private $_initialized=false; + /** + * @var IApplication application + */ + private $_application; + + /** + * Initializes the service. + * This method is required by IService interface and is invoked by application. + * @param IApplication application + * @param TXmlElement service configuration + */ + public function init($application,$config) + { + $this->_application=$application; + + if(($rootPath=Prado::getPathOfNamespace($this->_rootPath))===null || !is_dir($rootPath)) + throw new TConfigurationException('pageservice_rootpath_invalid',$this->_rootPath); + + $this->_pagePath=$application->getRequest()->getServiceParameter(); + if(empty($this->_pagePath)) + $this->_pagePath=$this->_defaultPage; + if(empty($this->_pagePath)) + throw new THttpException('pageservice_page_required'); + + if(($cache=$application->getCache())===null) + { + $config=new TPageConfiguration; + $config->loadConfiguration($this->_pagePath,$rootPath); + } + else + { + $configCached=true; + $arr=$cache->get(self::CONFIG_CACHE_PREFIX.$this->_pagePath); + if(is_array($arr)) + { + list($config,$timestamp)=$arr; + if($this->_cacheExpire<0) + { + // check to see if cache is the latest + $paths=explode('.',$this->_pagePath); + array_pop($paths); + $configPath=$rootPath; + foreach($paths as $path) + { + if(@filemtime($configPath.'/'.self::CONFIG_FILE)>$timestamp) + { + $configCached=false; + break; + } + $configPath.='/'.$path; + } + if(@filemtime($configPath.'/'.self::CONFIG_FILE)>$timestamp) + $configCached=false; + } + } + else + $configCached=false; + if(!$configCached) + { + $config=new TPageConfiguration; + $config->loadConfiguration($this->_pagePath,$rootPath); + $cache->set(self::CONFIG_CACHE_PREFIX.$this->_pagePath,array($config,time()),$this->_cacheExpire<0?0:$this->_cacheExpire); + } + } + + $this->_pageType=$config->getPageType(); + + // set path aliases and using namespaces + foreach($config->getAliases() as $alias=>$path) + Prado::setPathAlias($alias,$path); + foreach($config->getUsings() as $using) + Prado::using($using); + + $this->_properties=$config->getProperties(); + + // load parameters + $parameters=$application->getParameters(); + foreach($config->getParameters() as $id=>$parameter) + { + if(is_string($parameter)) + $parameters->add($id,$parameter); + else + { + $component=Prado::createComponent($parameter[0]); + foreach($parameter[1] as $name=>$value) + $component->setPropertyByPath($name,$value); + $parameters->add($id,$component); + } + } + + // load modules specified in app config + foreach($config->getModules() as $id=>$moduleConfig) + { + $module=Prado::createComponent($moduleConfig[0]); + $application->setModule($id,$module); + foreach($moduleConfig[1] as $name=>$value) + $module->setPropertyByPath($name,$value); + $module->init($this->_application,$moduleConfig[2]); + } + + if(($auth=$application->getAuthManager())!==null) + $auth->getAuthorizationRules()->mergeWith($config->getRules()); + + $this->_initialized=true; + } + + /** + * @return string id of this module + */ + public function getID() + { + return $this->_id; + } + + /** + * @param string id of this module + */ + public function setID($value) + { + $this->_id=$value; + } + + /** + * @return TTemplateManager template manager + */ + public function getTemplateManager() + { + return $this->_application->getModule('template'); + } + + /** + * @return boolean true if the pagepath is currently being requested, false otherwise + */ + public function isRequestingPage($pagePath) + { + return $this->_pagePath===$pagePath; + } + + /** + * @return integer the expiration time of the configuration saved in cache, + * -1 (default) ensures the cached configuration always catches up the latest configuration files, + * 0 means never expire, + * a number less or equal than 60*60*24*30 means the number of seconds that the value will remain valid. + * a number greater than 60 means a UNIX timestamp after which the value will expire. + */ + public function getCacheExpire() + { + return $this->_cacheExpire; + } + + /** + * Sets the expiration time of the configuration saved in cache. + * TPageService will try to use cache to save parsed configuration files. + * CacheExpire is used to control the caching policy. + * If you have changed this property, make sure to clean up cache first. + * @param integer the expiration time of the configuration saved in cache, + * -1 (default) ensures the cached configuration always catches up the latest configuration files, + * 0 means never expire, + * a number less or equal than 60*60*24*30 means the number of seconds that the value will remain valid. + * a number greater than 60 means a UNIX timestamp after which the value will expire. + * @throws TInvalidOperationException if the service is already initialized + */ + public function setCacheExpire($value) + { + if($this->_initialized) + throw new TInvalidOperationException('pageservice_cacheexpire_unchangeable'); + else + $this->_cacheExpire=TPropertyValue::ensureInteger($value); + } + + /** + * @return string default page path to be served if no explicit page is request + */ + public function getDefaultPage() + { + return $this->_defaultPage; + } + + /** + * @param string default page path to be served if no explicit page is request + * @throws TInvalidOperationException if the page service is initialized + */ + public function setDefaultPage($value) + { + if($this->_initialized) + throw new TInvalidOperationException('pageservice_defaultpage_unchangeable'); + else + $this->_defaultPage=$value; + } + + /** + * @return string root directory (in namespace form) storing pages + */ + public function getRootPath() + { + return $this->_rootPath; + } + + /** + * @param string root directory (in namespace form) storing pages + * @throws TInvalidOperationException if application is initialized + */ + public function setRootPath($value) + { + if($this->_initialized) + throw new TInvalidOperationException('pageservice_rootpath_unchangeable'); + else + $this->_rootPath=$value; + } + + /** + * Runs the service. + * This will create the requested page, initializes it with the property values + * specified in the configuration, and executes the page. + */ + public function run() + { + $page=null; + if(($pos=strpos($this->_pageType,'.'))===false) + { + $className=$this->_pageType; + if(!class_exists($className,false)) + { + $p=explode('.',$this->_pagePath); + array_pop($p); + array_push($p,$className); + $path=Prado::getPathOfNamespace($this->_rootPath).'/'.implode('/',$p).Prado::CLASS_FILE_EXT; + require_once($path); + } + } + else + { + $className=substr($this->_pageType,$pos+1); + if(($path=self::getPathOfNamespace($this->_pageType,Prado::CLASS_FILE_EXT))!==null) + { + if(!class_exists($className,false)) + { + require_once($path); + } + } + } + if(class_exists($className,false)) + $page=new $className($this->_properties); + else + throw new THttpException('pageservice_page_unknown',$this->_pageType); + $writer=new THtmlTextWriter($this->_application->getResponse()); + $page->run($writer); + $writer->flush(); + } + + /** + * Constructs a URL with specified page path and GET parameters. + * @param string page path + * @param array list of GET parameters, null if no GET parameters required + * @return string URL for the page and GET parameters + */ + public function constructUrl($pagePath,$getParams=null) + { + return $this->_application->getRequest()->constructUrl($this->_id,$pagePath,$getParams); + } +} + + +/** + * TPageConfiguration class + * + * TPageConfiguration represents the configuration for a page. + * The page is specified by a dot-connected path. + * Configurations along this path are merged together to be provided for the page. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Services + * @since 3.0 + */ +class TPageConfiguration extends TComponent +{ + /** + * @var array list of page initial property values + */ + private $_properties=array(); + /** + * @var string page type + */ + private $_pageType=null; + /** + * @var array list of namespaces to be used + */ + private $_usings=array(); + /** + * @var array list of path aliases + */ + private $_aliases=array(); + /** + * @var array list of module configurations + */ + private $_modules=array( + 'template'=>array('System.Web.UI.TTemplateManager',array(),null), + ); + /** + * @var array list of parameters + */ + private $_parameters=array(); + /** + * @var TAuthorizationRuleCollection list of authorization rules + */ + private $_rules=array(); + + /** + * Returns list of page initial property values. + * Each array element represents a single property with the key + * being the property name and the value the initial property value. + * @return array list of page initial property values + */ + public function getProperties() + { + return $this->_properties; + } + + /** + * @return string the requested page type + */ + public function getPageType() + { + return $this->_pageType; + } + + /** + * Returns list of path alias definitions. + * The definitions are aggregated (top-down) from configuration files along the path + * to the specified page. Each array element represents a single alias definition, + * with the key being the alias name and the value the absolute path. + * @return array list of path alias definitions + */ + public function getAliases() + { + return $this->_aliases; + } + + /** + * Returns list of namespaces to be used. + * The namespaces are aggregated (top-down) from configuration files along the path + * to the specified page. Each array element represents a single namespace usage, + * with the value being the namespace to be used. + * @return array list of namespaces to be used + */ + public function getUsings() + { + return $this->_usings; + } + + /** + * Returns list of module configurations. + * The module configurations are aggregated (top-down) from configuration files + * along the path to the specified page. Each array element represents + * a single module configuration, with the key being the module ID and + * the value the module configuration. Each module configuration is + * stored in terms of an array with the following content + * ([0]=>module type, [1]=>module properties, [2]=>complete module configuration) + * The module properties are an array of property values indexed by property names. + * The complete module configuration is a TXmlElement object representing + * the raw module configuration which may contain contents enclosed within + * module tags. + * @return array list of module configurations to be used + */ + public function getModules() + { + return $this->_modules; + } + + /** + * Returns list of parameter definitions. + * The parameter definitions are aggregated (top-down) from configuration files + * along the path to the specified page. Each array element represents + * a single parameter definition, with the key being the parameter ID and + * the value the parameter definition. A parameter definition can be either + * a string representing a string-typed parameter, or an array. + * The latter defines a component-typed parameter whose format is as follows, + * ([0]=>component type, [1]=>component properties) + * The component properties are an array of property values indexed by property names. + * @return array list of parameter definitions to be used + */ + public function getParameters() + { + return $this->_parameters; + } + + /** + * Returns list of authorization rules. + * The authorization rules are aggregated (bottom-up) from configuration files + * along the path to the specified page. + * @return TAuthorizationRuleCollection collection of authorization rules + */ + public function getRules() + { + return $this->_rules; + } + + /** + * Loads configuration for a page specified in a path format. + * @param string path to the page (dot-connected format) + * @param string root path for pages + */ + public function loadConfiguration($pagePath,$rootPath) + { + $paths=explode('.',$pagePath); + $page=array_pop($paths); + $path=$rootPath; + foreach($paths as $p) + { + $this->loadFromFile($path.'/'.TPageService::CONFIG_FILE,null); + $path.='/'.$p; + } + $this->loadFromFile($path.'/'.TPageService::CONFIG_FILE,$page); + $this->_rules=new TAuthorizationRuleCollection($this->_rules); + } + + /** + * Loads a specific config file. + * @param string config file name + * @param string page name, null if page is not required + */ + private function loadFromFile($fname,$page) + { + if(empty($fname) || !is_file($fname)) + { + if($page===null) + return; + } + $configPath=dirname($fname); + $dom=new TXmlDocument; + $dom->loadFromFile($fname); + + // paths + if(($pathsNode=$dom->getElementByTagName('paths'))!==null) + { + foreach($pathsNode->getElementsByTagName('alias') as $aliasNode) + { + if(($id=$aliasNode->getAttribute('id'))!==null && ($p=$aliasNode->getAttribute('path'))!==null) + { + $p=str_replace('\\','/',$p); + $path=realpath(preg_match('/^\\/|.:\\//',$p)?$p:$configPath.'/'.$p); + if($path===false || !is_dir($path)) + throw new TConfigurationException('pageservice_alias_path_invalid',$fname,$id,$p); + if(isset($this->_aliases[$id])) + throw new TConfigurationException('pageservice_alias_redefined',$fname,$id); + $this->_aliases[$id]=$path; + } + else + throw new TConfigurationException('pageservice_alias_element_invalid',$fname); + } + foreach($pathsNode->getElementsByTagName('using') as $usingNode) + { + if(($namespace=$usingNode->getAttribute('namespace'))!==null) + $this->_usings[]=$namespace; + else + throw new TConfigurationException('pageservice_using_element_invalid',$fname); + } + } + + // modules + if(($modulesNode=$dom->getElementByTagName('modules'))!==null) + { + foreach($modulesNode->getElementsByTagName('module') as $node) + { + $properties=$node->getAttributes(); + $type=$properties->remove('type'); + if(($id=$properties->itemAt('id'))===null) + throw new TConfigurationException('pageservice_module_element_invalid',$fname); + if(isset($this->_modules[$id])) + { + if($type===null) + { + $this->_modules[$id][1]=array_merge($this->_modules[$id][1],$properties->toArray()); + $elements=$this->_modules[$id][2]->getElements(); + foreach($node->getElements() as $element) + $elements->add($element); + } + else + throw new TConfigurationException('pageservice_module_redefined',$fname,$id); + } + else if($type===null) + throw new TConfigurationException('pageservice_module_element_invalid',$fname); + else + { + $node->setParent(null); + $this->_modules[$id]=array($type,$properties->toArray(),$node); + } + } + } + + // parameters + if(($parametersNode=$dom->getElementByTagName('parameters'))!==null) + { + foreach($parametersNode->getElementsByTagName('parameter') as $node) + { + $properties=$node->getAttributes(); + if(($id=$properties->remove('id'))===null) + throw new TConfigurationException('pageservice_parameter_element_invalid'); + if(($type=$properties->remove('type'))===null) + $this->_parameters[$id]=$node->getValue(); + else + $this->_parameters[$id]=array($type,$properties->toArray()); + } + } + + // authorization + if(($authorizationNode=$dom->getElementByTagName('authorization'))!==null) + { + $rules=array(); + foreach($authorizationNode->getElements() as $node) + { + $pages=$node->getAttribute('pages'); + $ruleApplies=false; + if(empty($pages)) + $ruleApplies=true; + else if($page!==null) + { + $ps=explode(',',$pages); + foreach($ps as $p) + { + if($page===trim($p)) + { + $ruleApplies=true; + break; + } + } + } + if($ruleApplies) + $rules[]=new TAuthorizationRule($node->getTagName(),$node->getAttribute('users'),$node->getAttribute('roles'),$node->getAttribute('verb')); + } + $this->_rules=array_merge($rules,$this->_rules); + } + + // pages + if($page!==null && ($pagesNode=$dom->getElementByTagName('pages'))!==null) + { + $baseProperties=$pagesNode->getAttributes(); + foreach($pagesNode->getElementsByTagName('page') as $node) + { + $properties=$node->getAttributes(); + $type=$properties->remove('type'); + $id=$properties->itemAt('id'); + if($id===null || $type===null) + throw new TConfigurationException('pageservice_page_element_invalid',$fname); + if($id===$page) + { + $this->_properties=array_merge($baseProperties->toArray(),$properties->toArray()); + $this->_pageType=$type; + } + } + } + if($page!==null && $this->_pageType===null) + throw new THttpException('pageservice_page_inexistent',$page); + } +} + + + +?> \ No newline at end of file diff --git a/framework/Web/TCacheManager.php b/framework/Web/TCacheManager.php new file mode 100644 index 00000000..f1c9edd8 --- /dev/null +++ b/framework/Web/TCacheManager.php @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + // need to investigate the security of memory cache + */ + +/** + +*/ + +/** + +*/ + + +class TAuthencator extends TComponent +{ +} + +class TAuthorizer extends TComponent +{ +} + +$cm->generateUniqueID('button:',$id) +$cm->saveValue('template:'.$tmpFile,$template); +$cm->saveValue('application:ID',$appID); +$cm->saveValue('application:hashkey',$key); + +class TTemplateManager extends TComponent implements IModule +{ +} + +class TAssetManager extends TComponent implements IModule +{ + private $_pubDir=null; + private $_pubUrl=null; + + public function init($context) + { + if(is_null($this->_pubDir)) + throw new TCongiruationException('cache_public_location_required'); + if(is_null($this->_pubUrl)) + throw new TCongiruationException('cache_public_url_required'); + } + + public function getPublicLocation() + { + return $this->_pubDir; + } + + public function setPublicLocation($value) + { + if(is_dir($value)) + $this->_pubDir=realpath($value); + else + throw new TInvalidDataValueException('cache_public_location_invalid'); + } + + public function getPublicUrl() + { + return $this->_pubUrl; + } + + public function setPublicUrl($value) + { + $this->_pubUrl=rtrim($value,'/'); + } + + public function publishLocation($path,$forceOverwrite=false) + { + $name=basename($path); + $prefix=md5(dirname($path)); + } + + public function publishFile($path,$forceOverwrite=false) + { + if(($fullpath=realpath($path))!==false) + { + return $this->_pubUrl.'/'.$fullpath; + } + else + throw new TInvalidDataValueException('cachemanager_path_unpublishable'); + } + + public function unpublishPath($path) + { + } +} + +class TMemcache extends TComponent +{ +} + +class TSqliteCache extends TComponent +{ +} +?> \ No newline at end of file diff --git a/framework/Web/THttpRequest.php b/framework/Web/THttpRequest.php new file mode 100644 index 00000000..25d3027e --- /dev/null +++ b/framework/Web/THttpRequest.php @@ -0,0 +1,824 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Web + */ + +/** + * THttpRequest class + * + * THttpRequest provides storage and access scheme for user request sent via HTTP. + * It also encapsulates a uniform way to parse and construct URLs. + * + * THttpRequest is the default "request" module for prado application. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web + * @since 3.0 + */ +class THttpRequest extends TComponent implements IModule +{ + /** + * GET variable name to store service information + */ + const SERVICE_VAR='sp'; + /** + * @var boolean whether the module is initialized + */ + private $_initialized=false; + /** + * @var string module ID + */ + private $_id; + /** + * @var string requested service ID + */ + private $_serviceID=null; + /** + * @var string requested service parameter + */ + private $_serviceParam=null; + /** + * @var THttpCookieCollection cookies sent from user + */ + private $_cookies=null; + /** + * @var string requested URI (URL w/o host info) + */ + private $_requestUri; + /** + * @var string path info of URL + */ + private $_pathInfo; + /** + * @var TMap list of input variables (including GET and POST) + */ + private $_items; + + private $_authenticated=false; + + /** + * Constructor. + * Analyzes and resolves user request. + */ + public function __construct() + { + // Info about server variables: + // PHP_SELF contains real URI (w/ path info, w/o query string) + // SCRIPT_NAME is the real URI for the requested script (w/o path info and query string) + // REQUEST_URI contains the URI part entered in the browser address bar + // SCRIPT_FILENAME is the file path to the executing script + parent::__construct(); + if(isset($_SERVER['REQUEST_URI'])) + $this->_requestUri=$_SERVER['REQUEST_URI']; + else // TBD: in this case, SCRIPT_NAME need to be escaped + $this->_requestUri=$_SERVER['SCRIPT_NAME'].(empty($_SERVER['QUERY_STRING'])?'':'?'.$_SERVER['QUERY_STRING']); + + if(isset($_SERVER['PATH_INFO'])) + $this->_pathInfo=$_SERVER['PATH_INFO']; + else if(strpos($_SERVER['PHP_SELF'],$_SERVER['SCRIPT_NAME'])===0) + $this->_pathInfo=substr($_SERVER['PHP_SELF'],strlen($_SERVER['SCRIPT_NAME'])); + else + $this->_pathInfo=''; + + if(get_magic_quotes_gpc()) + { + if(isset($_GET)) + $_GET=array_map(array($this,'stripSlashes'),$_GET); + if(isset($_POST)) + $_POST=array_map(array($this,'stripSlashes'),$_POST); + if(isset($_REQUEST)) + $_REQUEST=array_map(array($this,'stripSlashes'),$_REQUEST); + if(isset($_COOKIE)) + $_COOKIE=array_map(array($this,'stripSlashes'),$_COOKIE); + } + + $this->_items=new TMap(array_merge($_POST,$_GET)); + + $this->resolveRequest(); + } + + /** + * Strips slashes from input data. + * This method is applied when magic quotes is enabled. + * Do not call this method. + * @param mixed input data to be processed + * @param mixed processed data + */ + public function stripSlashes(&$data) + { + return is_array($data)?array_map('pradoStripSlashes',$data):stripslashes($data); + } + + /** + * Initializes the module. + * This method is required by IModule and is invoked by application. + * @param IApplication application + * @param TXmlElement module configuration + */ + public function init($application,$config) + { + $this->_initialized=true; + } + + /** + * @return string id of this module + */ + public function getID() + { + return $this->_id; + } + + /** + * @param string id of this module + */ + public function setID($value) + { + $this->_id=$value; + } + + /** + * @return TUri the request URL + */ + public function getUrl() + { + if($this->_url===null) + { + $secure=$this->getIsSecureConnection(); + $url=$secure?'https://':'http://'; + if(empty($_SERVER['HTTP_HOST'])) + { + $url.=$_SERVER['SERVER_NAME']; + $port=$_SERVER['SERVER_PORT']; + if(($port!=80 && !$secure) || ($port!=443 && $secure)) + $url.=':'.$port; + } + else + $url.=$_SERVER['HTTP_HOST']; + $url.=$this->getRequestUri(); + $this->_url=new TUri($url); + } + return $this->_url; + } + + /** + * @return string request type, can be GET, POST, HEAD, or PUT + */ + public function getRequestType() + { + return $_SERVER['REQUEST_METHOD']; + } + + /** + * @return boolean if the request is sent via secure channel (https) + */ + public function getIsSecureConnection() + { + return !empty($_SERVER['HTTPS']); + } + + /** + * @return string part of the request URL after script name and before question mark. + */ + public function getPathInfo() + { + return $this->_pathInfo; + } + + /** + * @return string part of that request URL after the question mark + */ + public function getQueryString() + { + return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:''; + } + + /** + * @return string part of that request URL after the host info (including pathinfo and query string) + */ + public function getRequestUri() + { + return $this->_requestUri; + } + + /** + * @return string entry script URL (w/o host part) + */ + public function getApplicationPath() + { + return $_SERVER['SCRIPT_NAME']; + } + + /** + * @return string application entry script file path + */ + public function getPhysicalApplicationPath() + { + return $_SERVER['SCRIPT_FILENAME']; + } + + /** + * @return string server name + */ + public function getServerName() + { + return $_SERVER['SERVER_NAME']; + } + + /** + * @return integer server port number + */ + public function getServerPort() + { + return $_SERVER['SERVER_PORT']; + } + + /** + * @return string URL referrer, null if not present + */ + public function getUrlReferrer() + { + return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null; + } + + /** + * @return array user browser capabilities + * @see get_browser + */ + public function getBrowser() + { + return get_browser(); + } + + /** + * @return string user agent + */ + public function getUserAgent() + { + return $_SERVER['HTTP_USER_AGENT']; + } + + /** + * @return string user IP address + */ + public function getUserHostAddress() + { + return $_SERVER['REMOTE_ADDR']; + } + + /** + * @return string user host name, null if cannot be determined + */ + public function getUserHost() + { + return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null; + } + + /** + * @return string user browser accept types + */ + public function getAcceptTypes() + { + // TBD: break it into array?? + return $_SERVER['HTTP_ACCEPT']; + } + + /** + * @return string languages user browser supports + */ + public function getUserLanguages() + { + // TBD ask wei about this + return $_SERVER['HTTP_ACCEPT_LANGUAGE']; + } + + /** + * @return TMap list of input variables, include GET, POST + */ + public function getItems() + { + return $this->_items; + } + + /** + * @return THttpCookieCollection list of cookies to be sent + */ + public function getCookies() + { + if($this->_cookies===null) + { + $this->_cookies=new THttpCookieCollection; + foreach($_COOKIE as $key=>$value) + $this->_cookies->add(new THttpCookie($key,$value)); + } + return $this->_cookies; + } + + /** + * @return TMap list of uploaded files. + */ + public function getUploadedFiles() + { + if($this->_files===null) + $this->_files=new TMap($_FILES); + return $this->_files; + } + + /** + * @return TMap list of server variables. + */ + public function getServerVariables() + { + if($this->_server===null) + $this->_server=new TMap($_SERVER); + return $this->_server; + } + + /** + * @return TMap list of environment variables. + */ + public function getEnvironmentVariables() + { + if($this->_env===null) + $this->_env=new TMap($_ENV); + return $this->_env; + } + + /** + * Constructs a URL that is recognizable by Prado. + * You may override this method to provide your own way of URL formatting. + * The URL is constructed as the following format: + * /entryscript.php?sp=serviceID.serviceParameter&get1=value1&... + * @param string service ID + * @param string service parameter + * @param array GET parameters, null if not needed + * @return string URL + */ + public function constructUrl($serviceID,$serviceParam,$getItems=null) + { + $url=$this->getApplicationPath(); + $url.='?'.self::SERVICE_VAR.'='.$serviceID; + if(!empty($serviceParam)) + $url.='.'.$serviceParam; + if(is_array($getItems) || $getItems instanceof Traversable) + { + foreach($getItems as $name=>$value) + $url.='&'.urlencode($name).'='.urlencode($value); + } + if(defined('SID') && SID != '') + $url.='&'.SID; + return $url; + } + + /** + * Resolves the requested servie. + * This method implements a URL-based service resolution. + * A URL in the format of /index.php?sp=serviceID.serviceParameter + * will be resolved with the serviceID and the serviceParameter. + * You may override this method to provide your own way of service resolution. + * @see constructUrl + */ + protected function resolveRequest() + { + if(($sp=$this->_items->itemAt(self::SERVICE_VAR))!==null) + { + if(($pos=strpos($sp,'.'))===false) + $this->setServiceID($sp); + else + { + $this->setServiceID(substr($sp,0,$pos)); + $this->setServiceParameter(substr($sp,$pos+1)); + } + } + } + + /** + * @return string requested service ID + */ + public function getServiceID() + { + return $this->_serviceID; + } + + /** + * Sets the requested service ID. + * @param string requested service ID + */ + protected function setServiceID($value) + { + $this->_serviceID=$value; + } + + /** + * @return string requested service parameter + */ + public function getServiceParameter() + { + return $this->_serviceParam; + } + + /** + * Sets the requested service parameter. + * @param string requested service parameter + */ + protected function setServiceParameter($value) + { + $this->_serviceParam=$value; + } + + public function getIsAuthenticated() + { + return $this->_authenticated; + } + + public function setIsAuthenticated($value) + { + $this->_authenticated=$value; + } +} + +/** + * THttpCookieCollection class. + * + * THttpCookieCollection implements a collection class to store cookies. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web + * @since 3.0 + */ +class THttpCookieCollection extends TList +{ + /** + * @var mixed owner of this collection + */ + private $_o; + + /** + * Constructor. + * @param mixed owner of this collection. + */ + public function __construct($owner=null) + { + parent::__construct(); + $this->_o=$owner; + } + + /** + * Adds the cookie if owner of this collection is of THttpResponse. + * This method will be invoked whenever an item is added to the collection. + */ + protected function addedItem($item) + { + if($this->_o instanceof THttpResponse) + $this->_o->addCookie($item); + } + + /** + * Removes the cookie if owner of this collection is of THttpResponse. + * This method will be invoked whenever an item is removed from the collection. + */ + protected function removedItem($item) + { + if($this->_o instanceof THttpResponse) + $this->_o->removeCookie($item); + } + + /** + * Restricts acceptable item of this collection to THttpCookie. + * This method will be invoked whenever an item is to be added into the collection. + */ + protected function canAddItem($item) + { + return ($item instanceof THttpCookie); + } +} + +/** + * THttpCookie class. + * + * A THttpCookie instance stores a single cookie, including the cookie name, value, + * domain, path, expire, and secure. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web + * @since 3.0 + */ +class THttpCookie extends TComponent +{ + /** + * @var string domain of the cookie + */ + private $_domain=''; + /** + * @var string name of the cookie + */ + private $_name; + /** + * @var string value of the cookie + */ + private $_value=0; + /** + * @var integer expire of the cookie + */ + private $_expire=0; + /** + * @var string path of the cookie + */ + private $_path='/'; + /** + * @var boolean whether cookie should be sent via secure connection + */ + private $_secure=false; + + /** + * Constructor. + * @param string name of this cookie + * @param string value of this cookie + */ + public function __construct($name,$value) + { + parent::__construct(); + $this->_name=$name; + $this->_value=$value; + } + + /** + * @return string the domain to associate the cookie with + */ + public function getDomain() + { + return $this->_domain; + } + + /** + * @param string the domain to associate the cookie with + */ + public function setDomain($value) + { + $this->_domain=$value; + } + + /** + * @return integer the time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. + */ + public function getExpire() + { + return $this->_expire; + } + + /** + * @param integer the time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. + */ + public function setExpire($value) + { + $this->_expire=TPropertyValue::ensureInteger($value); + } + + /** + * @return string the name of the cookie + */ + public function getName() + { + return $this->_name; + } + + /** + * @param string the name of the cookie + */ + public function setName($value) + { + $this->_name=$value; + } + + /** + * @return string the value of the cookie + */ + public function getValue() + { + return $this->_value; + } + + /** + * @param string the value of the cookie + */ + public function setValue($value) + { + $this->_value=$value; + } + + /** + * @return string the path on the server in which the cookie will be available on, default is '/' + */ + public function getPath() + { + return $this->_path; + } + + /** + * @param string the path on the server in which the cookie will be available on + */ + public function setPath($value) + { + $this->_path=$value; + } + + /** + * @return boolean whether the cookie should only be transmitted over a secure HTTPS connection + */ + public function getSecure() + { + return $this->_secure; + } + + /** + * @param boolean ether the cookie should only be transmitted over a secure HTTPS connection + */ + public function setSecure($value) + { + $this->_secure=TPropertyValue::ensureBoolean($value); + } +} + +/** + * TUri class + * + * TUri represents a URI. Given a URI + * http://joe:whatever@example.com:8080/path/to/script.php?param=value#anchor + * it will be decomposed as follows, + * - scheme: http + * - host: example.com + * - port: 8080 + * - user: joe + * - password: whatever + * - path: /path/to/script.php + * - query: param=value + * - fragment: anchor + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web + * @since 3.0 + */ +class TUri extends TComponent +{ + /** + * @var array list of default ports for known schemes + */ + private static $_defaultPort=array( + 'ftp'=>21, + 'gopher'=>70, + 'http'=>80, + 'https'=>443, + 'news'=>119, + 'nntp'=>119, + 'wais'=>210, + 'telnet'=>23 + ); + /** + * @var string scheme of the URI + */ + private $_scheme; + /** + * @var string host name of the URI + */ + private $_host; + /** + * @var integer port of the URI + */ + private $_port; + /** + * @var string user of the URI + */ + private $_user; + /** + * @var string password of the URI + */ + private $_pass; + /** + * @var string path of the URI + */ + private $_path; + /** + * @var string query string of the URI + */ + private $_query; + /** + * @var string fragment of the URI + */ + private $_fragment; + /** + * @var string the URI + */ + private $_uri; + + /** + * Constructor. + * Decomposes the specified URI into parts. + * @param string URI to be represented + * @throws TInvalidDataValueException if URI is of bad format + */ + public function __construct($uri) + { + parent::__construct(); + if(($ret=@parse_url($uri))!==false) + { + // decoding??? + $this->_scheme=$ret['scheme']; + $this->_host=$ret['host']; + $this->_port=$ret['port']; + $this->_user=$ret['user']; + $this->_pass=$ret['pass']; + $this->_path=$ret['path']; + $this->_query=$ret['query']; + $this->_fragment=$ret['fragment']; + $this->_uri=$uri; + } + else + { + throw new TInvalidDataValueException('uri_format_invalid',$uri); + } + } + + /** + * @return string URI + */ + public function getUri() + { + return $this->_uri; + } + + /** + * @return string scheme of the URI, such as 'http', 'https', 'ftp', etc. + */ + public function getScheme() + { + return $this->_scheme; + } + + /** + * @return string hostname of the URI + */ + public function getHost() + { + return $this->_host; + } + + /** + * @return integer port number of the URI + */ + public function getPort() + { + return $this->_port; + } + + /** + * @return string username of the URI + */ + public function getUser() + { + return $this->_user; + } + + /** + * @return string password of the URI + */ + public function getPassword() + { + return $this->_pass; + } + + /** + * @return string path of the URI + */ + public function getPath() + { + return $this->_path; + } + + /** + * @return string query string of the URI + */ + public function getQuery() + { + return $this->_query; + } + + /** + * @return string fragment of the URI + */ + public function getFragment() + { + return $this->_fragment; + } +} + +?> \ No newline at end of file diff --git a/framework/Web/THttpResponse.php b/framework/Web/THttpResponse.php new file mode 100644 index 00000000..96859300 --- /dev/null +++ b/framework/Web/THttpResponse.php @@ -0,0 +1,289 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Web + */ + +/** + * THttpResponse class + * + * THttpResponse implements a scheme to output response to user requests. + * + * THttpResponse is the default "response" module for prado application. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web + * @since 3.0 + */ +class THttpResponse extends TComponent implements IModule, ITextWriter +{ + /** + * @var string id of this module (response) + */ + private $_id; + /** + * @var boolean whether to buffer output + */ + private $_bufferOutput=true; + /** + * @var boolean if the application is initialized + */ + private $_initialized=false; + /** + * @var THttpCookieCollection list of cookies to return + */ + private $_cookies=null; + /** + * @var integer status code + */ + private $_status=200; + + /** + * Destructor. + * Flushes any existing content in buffer. + */ + public function __destruct() + { + if($this->_bufferOutput) + @ob_end_flush(); + parent::__destruct(); + } + + /** + * Initializes the module. + * This method is required by IModule and is invoked by application. + * It starts output buffer if it is enabled. + * @param IApplication application + * @param TXmlElement module configuration + */ + public function init($application,$config) + { + if($this->_bufferOutput) + ob_start(); + $this->_initialized=true; + } + + /** + * @return string id of this module + */ + public function getID() + { + return $this->_id; + } + + /** + * @param string id of this module + */ + public function setID($value) + { + $this->_id=$value; + } + + + /** + * @return integer time-to-live for cached session pages in minutes, this has no effect for nocache limiter. Defaults to 180. + */ + public function getCacheExpire() + { + return session_cache_expire(); + } + + /** + * @param integer time-to-live for cached session pages in minutes, this has no effect for nocache limiter. + */ + public function setCacheExpire($value) + { + session_cache_expire(TPropertyValue::ensureInteger($value)); + } + + /** + * @return string cache control method to use for session pages + */ + public function getCacheControl() + { + return session_cache_limiter(); + } + + /** + * @param string cache control method to use for session pages. Valid values + * include none/nocache/private/private_no_expire/public + */ + public function setCacheControl($value) + { + session_cache_limiter(TPropertyValue::ensureEnum($value,array('none','nocache','private','private_no_expire','public'))); + } + + /** + * @return boolean whether to enable output buffer + */ + public function getBufferOutput() + { + return $this->_bufferOutput; + } + + /** + * @param boolean whether to enable output buffer + * @throws TInvalidOperationException if session is started already + */ + public function setBufferOutput($value) + { + if($this->_initialized) + throw new TInvalidOperationException('httpresponse_bufferoutput_unchangeable'); + else + $this->_bufferOutput=TPropertyValue::ensureBoolean($value); + } + + /** + * @return integer HTTP status code, defaults to 200 + */ + public function getStatusCode() + { + return $this->_status; + } + + /** + * @param integer HTTP status code + */ + public function setStatusCode($status) + { + $this->_status=TPropertyValue::ensureInteger($status); + } + + /** + * @return THttpCookieCollection list of output cookies + */ + public function getCookies() + { + if($this->_cookies===null) + $this->_cookies=new THttpCookieCollection($this); + return $this->_cookies; + } + + /** + * Outputs a string. + * It may not be sent back to user immediately if output buffer is enabled. + * @param string string to be output + */ + public function write($str) + { + echo $str; + } + + /** + * Sends a file back to user. + * Make sure not to output anything else after calling this method. + * @param string file name + * @throws TInvalidDataValueException if the file cannot be found + */ + public function writeFile($fileName) + { + static $defaultMimeTypes=array( + 'css'=>'text/css', + 'gif'=>'image/gif', + 'jpg'=>'image/jpeg', + 'jpeg'=>'image/jpeg', + 'htm'=>'text/html', + 'html'=>'text/html', + 'js'=>'javascript/js' + ); + + if(!is_file($fileName)) + throw new TInvalidDataValueException('httpresponse_file_inexistent',$fileName); + header('Pragma: public'); + header('Expires: 0'); + header('Cache-Component: must-revalidate, post-check=0, pre-check=0'); + $mimeType='text/plain'; + if(function_exists('mime_content_type')) + $mimeType=mime_content_type($fileName); + else + { + $ext=array_pop(explode('.',$fileName)); + if(isset($defaultMimeTypes[$ext])) + $mimeType=$defaultMimeTypes[$ext]; + } + $fn=basename($fileName); + header("Content-type: $mimeType"); + header('Content-Length: '.filesize($fileName)); + header("Content-Disposition: attachment; filename=\"$fn\""); + header('Content-Transfer-Encoding: binary'); + readfile($fileName); + } + + /** + * Redirects the browser to the specified URL. + * The current application will be terminated after this method is invoked. + * @param string URL to be redirected to + */ + public function redirect($url) + { + header('Location:'.$url); + exit(); + } + + /** + * Outputs the buffered content. + */ + public function flush() + { + if($this->_bufferOutput) + ob_flush(); + } + + /** + * Clears any existing buffered content. + */ + public function clear() + { + if($this->_bufferOutput) + ob_clean(); + } + + /** + * Sends a header. + * @param string header + */ + public function appendHeader($value) + { + header($value); + } + + /** + * Writes a log message into system log. + * @param string message to be written + * @param integer priority level of this message + * @see http://us2.php.net/manual/en/function.syslog.php + */ + public function appendLog($message,$priority=LOG_INFO) + { + syslog($priority,$message); + } + + /** + * Sends a cookie. + * Do not call this method directly. Operate with the result of {@link getCookies} instead. + * @param THttpCookie cook to be sent + */ + public function addCookie($cookie) + { + setcookie($cookie->getName(),$cookie->getValue(),$cookie->getExpire(),$cookie->getPath(),$cookie->getDomain(),$cookie->getSecure()); + } + + /** + * Deletes a cookie. + * Do not call this method directly. Operate with the result of {@link getCookies} instead. + * @param THttpCookie cook to be deleted + */ + public function removeCookie($cookie) + { + setcookie($cookie->getName(),null,0,$cookie->getPath(),$cookie->getDomain(),$cookie->getSecure()); + } +} + +?> \ No newline at end of file diff --git a/framework/Web/THttpSession.php b/framework/Web/THttpSession.php new file mode 100644 index 00000000..fc8f99c6 --- /dev/null +++ b/framework/Web/THttpSession.php @@ -0,0 +1,504 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Web + */ + +/** + * THttpSession class + * + * THttpSession provides session-level data management and the related configurations. + * To start the session, call {@open}; to complete and send out session data, call {@close}; + * to destroy the session, call {@destroy}. If AutoStart is true, then the session + * will be started once the session module is loaded and initialized. + * + * To access data stored in session, use the Items property. For example, + * + * $session=new THttpSession; + * $session->open(); + * foreach($session->Items as $key=>$value) + * ; // read data in session + * $session->Items['key']=$data; // store new data into session + * + * + * The following configurations are available for session: + * AutoStart, Cookie, CacheExpire, CacheLimiter, SavePath, Storage, GCProbability, CookieUsage, Timeout. + * See the corresponding setter and getter documentation for more information. + * Note, these properties must be set before the session is started. + * + * THttpSession can be inherited with customized session storage method. + * Override {@link _open}, {@link _close}, {@link _read}, {@link _write}, {@link _destroy} and {@link _gc} + * and set Storage as 'user' to store session using methods other than files and shared memory. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web + * @since 3.0 + */ +class THttpSession extends TComponent implements IModule +{ + /** + * @var string ID of this module + */ + private $_id; + /** + * @var THttpSessionCollection list of session variables + */ + private $_items; + /** + * @var boolean whether this module has been initialized + */ + private $_initialized=false; + /** + * @var boolean whether the session has started + */ + private $_started=false; + /** + * @var boolean whether the session should be started when the module is initialized + */ + private $_autoStart=false; + /** + * @var THttpCookie cookie to be used to store session ID and other data + */ + private $_cookie=null; + + /** + * Initializes the module. + * This method is required by IModule. + * If AutoStart is true, the session will be started. + * @param IApplication prado application instance + */ + public function init($application,$config) + { + if($this->_autoStart) + session_start(); + $this->_initialized=true; + } + + /** + * Starts the session if it has not started yet. + */ + public function open() + { + if(!$this->_started) + { + if($this->_cookie!==null) + session_set_cookie_params($this->_cookie->getExpire(),$this->_cookie->getPath(),$this->_cookie->getDomain(),$this->_cookie->getSecure()); + session_start(); + $this->_started=true; + } + } + + /** + * Ends the current session and store session data. + */ + public function close() + { + if($this->_started) + { + session_write_close(); + $this->_started=false; + } + } + + /** + * Destroys all data registered to a session. + */ + public function destroy() + { + if($this->_started) + { + session_destroy(); + $this->_started=false; + } + } + + /** + * @return string the ID of this session module (not session ID) + */ + public function getID() + { + return $this->_id; + } + + /** + * @param string the ID of this session module (not session ID) + */ + public function setID($value) + { + $this->_id=$value; + } + + /** + * @return THttpSessionCollection list of session variables + */ + public function getItems() + { + if($this->_items===null) + $this->_items=new THttpSessionCollection($_SESSION); + return $this->_items; + } + + /** + * @return boolean whether the session has started + */ + public function getIsStarted() + { + return $this->_started; + } + + /** + * @return string the current session ID + */ + public function getSessionID() + { + return session_id(); + } + + /** + * @param string the session ID for the current session + * @throws TInvalidOperationException if session is started already + */ + public function setSessionID($value) + { + if($this->_started) + throw new TInvalidOperationException('httpsession_sessionid_unchangeable'); + else + session_id($value); + } + + /** + * @return string the current session name + */ + public function getSessionName() + { + return session_name(); + } + + /** + * @param string the session name for the current session, must be an alphanumeric string, defaults to PHPSESSID + * @throws TInvalidOperationException if session is started already + */ + public function setSessionName($value) + { + if($this->_started) + throw new TInvalidOperationException('httpsession_sessionname_unchangeable'); + else if(ctype_alnum($value)) + session_name($value); + else + throw new TInvalidDataValueException('httpsession_sessionname_invalid',$name); + } + + /** + * @return string the current session save path, defaults to '/tmp'. + */ + public function getSavePath() + { + return session_save_path(); + } + + /** + * @param string the current session save path + * @throws TInvalidOperationException if session is started already + */ + public function setSavePath($value) + { + if($this->_started) + throw new TInvalidOperationException('httpsession_cachelimiter_unchangeable'); + else if(is_dir($value)) + session_save_path($value); + else + throw new TInvalidDataValueException('httpsession_savepath_invalid',$value); + } + + /** + * @return string (files|mm|user) storage mode of session, defaults to 'files'. + */ + public function getStorage() + { + return session_module_name(); + } + + /** + * @param string (files|mm|user) storage mode of session. By default, the session + * data is stored in files. You may change to shared memory (mm) for better performance. + * Or you may choose your own storage (user). If you do so, make sure you + * override {@link _open}, {@link _close}, {@link _read}, {@link _write}, + * {@link _destroy}, and {@link _gc}. + * @throws TInvalidOperationException if session is started already + */ + public function setStorage($value) + { + if($this->_started) + throw new TInvalidOperationException('httpsession_storage_unchangeable'); + else + { + $value=TPropertyValue::ensureEnum($value,array('files','mm','user')); + if($value==='user') + session_set_save_handler(array($this,'_open'),array($this,'_close'),array($this,'_read'),array($this,'_write'),array($this,'_destroy'),array($this,'_gc')); + session_module_name($value); + } + } + + /** + * @return THttpCookie cookie that will be used to store session ID + */ + public function getCookie() + { + if($this->_cookie===null) + $this->_cookie=new THttpCookie($this->getSessionName(),$this->getSessionID()); + return $this->_cookie; + } + + /** + * @return string (none|allow|only) how to use cookie to store session ID + * 'none' means not using cookie, 'allow' means using cookie, and 'only' means using cookie only, defaults to 'allow'. + */ + public function getCookieMode() + { + if(ini_get('session.use_cookies')==='0') + return 'none'; + else if(ini_get('session.use_only_cookies')==='0') + return 'allow'; + else + return 'only'; + } + + /** + * @param string (none|allow|only) how to use cookie to store session ID + * 'none' means not using cookie, 'allow' means using cookie, and 'only' means using cookie only. + * @throws TInvalidOperationException if session is started already + */ + public function setCookieMode($value) + { + if($this->_started) + throw new TInvalidOperationException('httpsession_cookiemode_unchangeable'); + else + { + $value=TPropertyValue::ensureEnum($value,array('none','allow','only')); + if($value==='none') + ini_set('session.use_cookies','0'); + else if($value==='allow') + { + ini_set('session.use_cookies','1'); + ini_set('session.use_only_cookies','0'); + } + else + { + ini_set('session.use_cookies','1'); + ini_set('session.use_only_cookies','1'); + } + } + } + + /** + * @return boolean whether the session should be automatically started when the session module is initialized, defaults to false. + */ + public function getAutoStart() + { + return $this->_autoStart; + } + + /** + * @param boolean whether the session should be automatically started when the session module is initialized, defaults to false. + * @throws TInvalidOperationException if session is started already + */ + public function setAutoStart($value) + { + if($this->_initialized) + throw new TInvalidOperationException('httpsession_autostart_unchangeable'); + else + $this->_autoStart=TPropertyValue::ensureBoolean($value); + } + + /** + * @return integer the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance. + */ + public function getGCProbability() + { + return TPropertyValue::ensureInteger(ini_get('session.gc_probability')); + } + + /** + * @param integer the probability (percentage) that the gc (garbage collection) process is started on every session initialization. + * @throws TInvalidOperationException if session is started already + * @throws TInvalidDataValueException if the value is beyond [0,100]. + */ + public function setGCProbability($value) + { + if($this->_started) + throw new TInvalidOperationException('httpsession_gcprobability_unchangeable'); + else + { + $value=TPropertyValue::ensureInteger($value); + if($value>=0 && $value<=100) + { + ini_set('session.gc_probability',$value); + ini_set('session.gc_divisor','100'); + } + else + throw new TInvalidDataValueException('httpsession_gcprobability_invalid',$value); + } + } + + /** + * @return boolean whether transparent sid support is enabled or not, defaults to false. + */ + public function getUseTransparentSessionID() + { + return ini_get('session.use_trans_sid')==='1'?true:false; + } + + /** + * @param boolean whether transparent sid support is enabled or not. + */ + public function setUseTransparentSessionID($value) + { + if($this->_started) + throw new TInvalidOperationException('httpsession_transid_unchangeable'); + else + ini_set('session.use_only_cookies',TPropertyValue::ensureBoolean($value)?'1':'0'); + } + + /** + * @return integer the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds. + */ + public function getTimeout() + { + return TPropertyValue::ensureInteger(ini_get('session.gc_maxlifetime')); + } + + /** + * @param integer the number of seconds after which data will be seen as 'garbage' and cleaned up + * @throws TInvalidOperationException if session is started already + */ + public function setTimeout($value) + { + if($this->_started) + throw new TInvalidOperationException('httpsession_maxlifetime_unchangeable'); + else + ini_set('session.gc_maxlifetime',$value); + } + + /** + * Session open handler. + * This method should be overriden if session Storage is set as 'user'. + * @param string session save path + * @param string session name + * @return boolean whether session is opened successfully + */ + public function _open($savePath,$sessionName) + { + return true; + } + + /** + * Session close handler. + * This method should be overriden if session Storage is set as 'user'. + * @return boolean whether session is closed successfully + */ + public function _close() + { + return true; + } + + /** + * Session read handler. + * This method should be overriden if session Storage is set as 'user'. + * @param string session ID + * @return string the session data + */ + public function _read($id) + { + return ''; + } + + /** + * Session write handler. + * This method should be overriden if session Storage is set as 'user'. + * @param string session ID + * @param string session data + * @return boolean whether session write is successful + */ + public function _write($id,$data) + { + return true; + } + + /** + * Session destroy handler. + * This method should be overriden if session Storage is set as 'user'. + * @param string session ID + * @return boolean whether session is destroyed successfully + */ + public function _destroy($id) + { + return true; + } + + /** + * Session GC (garbage collection) handler. + * This method should be overriden if session Storage is set as 'user'. + * @param integer the number of seconds after which data will be seen as 'garbage' and cleaned up. + * @return boolean whether session is GCed successfully + */ + public function _gc($maxLifetime) + { + return true; + } +} + +/** + * THttpSessionCollection class. + * + * THttpSessionCollection implements a collection class to store session data items. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web + * @since 3.0 + */ +class THttpSessionCollection extends TMap +{ + /** + * @var boolean whether the initial session data has been loaded into the collection + */ + private $_initialized=false; + + /** + * Constructor. + * Initializes the list with an array or an iterable object. + * @param array|Iterator the intial data. + */ + public function __construct($data=null) + { + parent::__construct($data); + $this->_initialized=true; + } + + /** + * Adds the item into session. + * This method will be invoked whenever an item is added to the collection. + */ + protected function addedItem($key,$value) + { + if($this->_initialized) + $_SESSION[$key]=$value; + } + + /** + * Removes the item from session. + * This method will be invoked whenever an item is removed from the collection. + */ + protected function removedItem($key,$value) + { + unset($_SESSION[$key]); + } +} +?> \ No newline at end of file diff --git a/framework/Web/THttpUtility.php b/framework/Web/THttpUtility.php new file mode 100644 index 00000000..9d2aa7b2 --- /dev/null +++ b/framework/Web/THttpUtility.php @@ -0,0 +1,33 @@ +'%25',"\t"=>'\t',"\n"=>'\n',"\r"=>'\r','"'=>'\"','\''=>'\\\'','\\'=>'\\\\')); + else + return strtr($js,array("\t"=>'\t',"\n"=>'\n',"\r"=>'\r','"'=>'\"','\''=>'\\\'','\\'=>'\\\\')); + } +} + +?> \ No newline at end of file diff --git a/framework/Web/UI/TClientScriptManager.php b/framework/Web/UI/TClientScriptManager.php new file mode 100644 index 00000000..0f760251 --- /dev/null +++ b/framework/Web/UI/TClientScriptManager.php @@ -0,0 +1,236 @@ +_owner=$owner; + } + + final public function getPostBackEventReference($options) + { + if($options->RequiresJavaScriptProtocol) + $str='javascript:'; + else + $str=''; + if($options->AutoPostBack) + $str.="setTimeout('"; + if(!$options->PerformValidation && !$options->TrackFocus && $options->ClientSubmit && $options->ActionUrl==='') + { + $this->_owner->registerPostBackScript(); + $postback="__doPostBack('".$options->TargetControl->getUniqueID()."','".THttpUtility::quoteJavaScriptString($options->Argument)."')"; + if($options->AutoPostBack) + { + $str.=THttpUtility::quoteJavaScriptString($postback); + $str.="',0)"; + } + else + $str.=$postback; + return $str; + } + $str.='WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("'; + $str.=$options->TargetControl->getUniqueID().'", '; + if(($arg=$options->Argument)==='') + $str.='"", '; + else + $str.='"'.THttpUtility::quoteJavaScriptString($arg).'", '; + $flag=false; + if($options->PerformValidation) + { + $flag=true; + $str.='true, '; + } + else + $str.='false, '; + if($options->ValidationGroup!=='') + { + $flag=true; + $str.='"'.$options->ValidationGroup.'", '; + } + else + $str.='"", '; + if($options->ActionUrl!=='') + { + $flag=true; + $this->_owner->setContainsCrossPagePost(true); + $str.='"'.THttpUtility::quoteJavaScriptString($options->ActionUrl).'", '; + } + else + $str.='"", '; + if($options->TrackFocus) + { + $this->_owner->registerFocusScript(); + $flag=true; + $str.='true, '; + } + else + $str.='false, '; + if($options->ClientSubmit) + { + $flag=true; + $this->_owner->registerPostBackScript(); + $str.='true))'; + } + else + $str.='false))'; + if($options->AutoPostBack) + $str.="', 0)"; + if($flag) + { + $this->_owner->registerWebFormsScript(); + return $str; + } + else + return ''; + } + + final public function isHiddenFieldRegistered($key) + { + return isset($this->_hiddenFields[$key]); + } + + final public function isClientScriptBlockRegistered($key) + { + return isset($this->_scriptBlocks[$key]); + } + + final public function isClientScriptIncludeRegistered($key) + { + return isset($this->_scriptIncludes[$key]); + } + + final public function isStartupScriptRegistered($key) + { + return isset($this->_startupScripts[$key]); + } + + final public function isOnSubmitStatementRegistered($key) + { + return isset($this->_onSubmitStatements[$key]); + } + + final public function registerArrayDeclaration($name,$value) + { + $this->_arrayDeclares[$name][]=$value; + } + + final public function registerClientScriptBlock($key,$script) + { + $this->_criptBlocks[$key]=$script; + } + + final public function registerClientScriptInclude($key,$url) + { + $this->_scriptIncludes[$key]=$url; + } + + // todo: register an asset + + final public function registerHiddenField($name,$value) + { + $this->_hiddenFields[$name]=$value; + } + + final public function registerOnSubmitStatement($key,$script) + { + $this->_onSubmitStatements[$key]=$script; + } + + final public function registerStartupScript($key,$script) + { + $this->_startupScripts[$key]=$script; + } + + final public function renderArrayDeclarations($writer) + { + if(count($this->_arrayDeclares)) + { + $str="\n\n"; + $writer->write($str); + } + } + + final public function renderClientScriptBlocks($writer) + { + $str=''; + foreach($this->_scriptBlocks as $script) + $str.=$script; + if($this->_owner->getClientOnSubmitEvent()!=='' && $this->_owner->getClientSupportsJavaScript()) + { + $str.="function WebForm_OnSubmit() {\n"; + foreach($this->_onSubmitStatements as $script) + $str.=$script; + $str.="\nreturn true;\n}"; + } + if($str!=='') + $writer->write("\n\n"); + } + + final public function renderClientStartupScripts($writer) + { + if(count($this->_startupScripts)) + { + $str="\n\n"; + $writer->write($str); + } + } + + final public function renderHiddenFields($writer) + { + $str=''; + foreach($this->_hiddenFields as $name=>$value) + { + $value=THttpUtility::htmlEncode($value); + $str.="\n"; + } + if($str!=='') + $writer->write($str); + $this->_hiddenFields=array(); + } + + /** + * @internal + */ + final public function getHasHiddenFields() + { + return count($this->_hiddenFields)>0; + } + + /** + * @internal + */ + final public function getHasSubmitStatements() + { + return count($this->_onSubmitStatements)>0; + } +} + +?> \ No newline at end of file diff --git a/framework/Web/UI/TControl.php b/framework/Web/UI/TControl.php new file mode 100644 index 00000000..0d7fb333 --- /dev/null +++ b/framework/Web/UI/TControl.php @@ -0,0 +1,1518 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Web.UI + */ + +/** + * TControl class + * + * TControl is the base class for all components on a page hierarchy. + * It implements the following features for UI-related functionalities: + * - databinding feature + * - naming container and containee relationship + * - parent and child relationship + * - viewstate and controlstate features + * - rendering scheme + * - control lifecycles + * + * A property can be data-bound with an expression. By calling {@link dataBind} + * expressions bound to properties will be evaluated and the results will be + * set to the corresponding properties. + * + * A naming container control implements INamingContainer and ensures that + * its containee controls can be differentiated by their ID property values. + * Naming container and containee realtionship specifies a protocol to uniquely + * identify an arbitrary control on a page hierarchy by an ID path (concatenation + * of all naming containers' IDs and the target control's ID). + * + * Parent and child relationship determines how the presentation of controls are + * enclosed within each other. A parent will determine where to place + * the presentation of its child controls. For example, a TPanel will enclose + * all its child controls' presentation within a div html tag. + * + * Viewstate and controlstate are two approaches to preserve state across + * page postback requests. ViewState is mainly related with UI specific state + * and can be disabled if not needed. ControlState represents crucial logic state + * and cannot be disabled. + * + * Each control on a page will undergo a series of lifecycles, including + * control construction, OnInit, OnLoad, OnPreRender, Render, and OnUnload. + * They work together with page lifecycles to process a page request. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web.UI + * @since 3.0 + */ +class TControl extends TComponent +{ + /** + * format of control ID + */ + const ID_FORMAT='/^[a-zA-Z_]\\w*$/'; + /** + * separator char between IDs in a UniqueID + */ + const ID_SEPARATOR='$'; + /** + * separator char between IDs in a ClientID + */ + const CLIENT_ID_SEPARATOR='_'; + /** + * prefix to an ID automatically generated + */ + const AUTOMATIC_ID_PREFIX='ctl'; + + /** + * the stage of lifecycles that the control is currently at + */ + const CS_CONSTRUCTED=0; + const CS_CHILD_INITIALIZED=1; + const CS_INITIALIZED=2; + const CS_STATE_LOADED=3; + const CS_LOADED=4; + const CS_PRERENDERED=5; + + /** + * State bits. + */ + const IS_ID_SET=0x01; + const IS_INVISIBLE=0x02; + const IS_DISABLE_VIEWSTATE=0x04; + const IS_SKIN_APPLIED=0x08; + const IS_STYLESHEET_APPLIED=0x10; + const IS_DISABLE_THEMING=0x20; + const IS_CHILD_CREATED=0x40; + const IS_CREATING_CHILD=0x80; + + /** + * Indexes for the rare fields. + * In order to save memory, rare fields will only be created if they are needed. + */ + const RF_CONTROLS=0; // cihld controls + const RF_CHILD_STATE=1; // child state field + const RF_NAMED_CONTROLS=2; // list of controls whose namingcontainer is this control + const RF_NAMED_CONTROLS_ID=3; // counter for automatic id + const RF_SKIN_ID=4; // skin ID + const RF_DATA_BINDINGS=5; // data bindings + const RF_EVENTS=6; // event handlers + const RF_CONTROLSTATE=7; // controlstate + const RF_NAMED_OBJECTS=8; // controls declared with ID on template + + /** + * @var string control ID + */ + private $_id=''; + /** + * @var string control unique ID + */ + private $_uid=''; + /** + * @var TControl parent of the control + */ + private $_parent=null; + /** + * @var TPage page that the control resides in + */ + private $_page=null; + /** + * @var TControl naming container of the control + */ + private $_namingContainer=null; + /** + * @var TTemplateControl control whose template contains the control + */ + private $_tplControl=null; + /** + * @var TMap viewstate data + */ + private $_viewState=array(); + /** + * @var integer the current stage of the control lifecycles + */ + private $_stage=0; + /** + * @var integer representation of the state bits + */ + private $_flags=0; + /** + * @var array a collection of rare control data + */ + private $_rf=array(); + + + /** + * Returns a property value by name or a control by ID. + * This overrides the parent implementation by allowing accessing + * a control via its ID using the following syntax, + * + * $menuBar=$this->menuBar; + * + * Note, the control must be configured in the template + * with explicit ID. If the name matches both a property and a control ID, + * the control ID will take the precedence. + * + * @param string the property name or control ID + * @return mixed the property value or the target control + * @throws TInvalidOperationException if the property is not defined. + * @see registerObject + */ + public function __get($name) + { + if(isset($this->_rf[self::RF_NAMED_OBJECTS][$name])) + return $this->_rf[self::RF_NAMED_OBJECTS][$name]; + else + return parent::__get($name); + } + + /** + * @return TControl the parent of this control + */ + public function getParent() + { + return $this->_parent; + } + + /** + * @return TControl the naming container of this control + */ + public function getNamingContainer() + { + if(!$this->_namingContainer && $this->_parent) + $this->_namingContainer=$this->_parent->getNamingContainer(); + return $this->_namingContainer; + } + + /** + * @return TPage the page that contains this control + */ + public function getPage() + { + if(!$this->_page && $this->_parent) + $this->_page=$this->_parent->getPage(); + return $this->_page; + } + + /** + * Sets the page for a control. + * Only framework developers should use this method. + * @param TPage the page that contains this control + */ + public function setPage($page) + { + $this->_page=$page; + } + + /** + * Sets the control whose template contains this control. + * Only framework developers should use this method. + * @param TTemplateControl the control whose template contains this control + */ + public function setTemplateControl($control) + { + $this->_tplControl=$control; + } + + /** + * @return TTemplateControl the control whose template contains this control + */ + public function getTemplateControl() + { + if(!$this->_tplControl && $this->_parent) + $this->_tplControl=$this->_parent->getTemplateControl(); + return $this->_tplControl; + } + + /** + * @return IApplication the application object that the current page is using + */ + public function getApplication() + { + return Prado::getApplication(); + } + + /** + * Returns the id of the control. + * Control ID can be either manually set or automatically generated. + * If $hideAutoID is true, automatically generated ID will be returned as an empty string. + * @param boolean whether to hide automatically generated ID + * @return string the ID of the control + */ + public function getID($hideAutoID=true) + { + if($hideAutoID) + return ($this->_flags & self::IS_ID_SET) ? $this->_id : ''; + else + return $this->_id; + } + + /** + * @param string the new control ID. The value must consist of word characters [a-zA-Z0-9_] only + * @throws TInvalidDataValueException if ID is in a bad format + */ + public function setID($id) + { + if(!preg_match(self::ID_FORMAT,$id)) + throw new TInvalidDataValueException('control_id_invalid',$id,get_class($this)); + $this->_id=$id; + $this->_flags |= self::IS_ID_SET; + $this->clearCachedUniqueID($this instanceof INamingContainer); + if($this->_namingContainer) + $this->_namingContainer->clearNameTable(); + } + + /** + * Returns a unique ID that identifies the control in the page hierarchy. + * A unique ID is the contenation of all naming container controls' IDs and the control ID. + * These IDs are separated by '$' character. + * Control users should not rely on the specific format of UniqueID, however. + * @return string a unique ID that identifies the control in the page hierarchy + */ + public function getUniqueID() + { + if($this->_uid==='') // need to build the UniqueID + { + if($namingContainer=$this->getNamingContainer()) + { + if($this->_page===$namingContainer) + return ($this->_uid=$this->_id); + else if(($prefix=$namingContainer->getUniqueID())==='') + return $this->_id; + else + return ($this->_uid=$prefix.self::ID_SEPARATOR.$this->_id); + } + else // no naming container + return $this->_id; + } + else + return $this->_uid; + } + + /** + * Returns the client ID of the control. + * The client ID can be used to uniquely identify + * the control in client-side scripts (such as JavaScript). + * Do not rely on the explicit format of the return ID. + * @return string the client ID of the control + */ + public function getClientID() + { + return strtr($this->getUniqueID(),self::ID_SEPARATOR,self::CLIENT_ID_SEPARATOR); + } + + /** + * @return string the skin ID of this control + */ + public function getSkinID() + { + return isset($this->_rf[self::RF_SKIN_ID])?$this->_rf[self::RF_SKIN_ID]:''; + } + + /** + * @param string the skin ID of this control + * @throws TInvalidOperationException if the SkinID is set in a stage later than PreInit, or if the skin is applied already. + */ + public function setSkinID($value) + { + if(($this->_flags & self::IS_SKIN_APPLIED) || $this->_stage>=self::CS_CHILD_INITIALIZED) + throw new TInvalidOperationException('control_skinid_unchangeable',get_class($this),$this->getUniqueID()); + else + $this->_rf[self::RF_SKIN_ID]=$value; + } + + /** + * @return boolean whether theming is enabled for this control. + * The theming is enabled if the control and all its parents have it enabled. + */ + public function getEnableTheming() + { + if($this->_flags & self::IS_DISABLE_THEMING) + return false; + else + return $this->_parent?$this->_parent->getEnableTheming():true; + } + + /** + * @param boolean whether to enable theming + * @throws TInvalidOperationException if this method is invoked after OnPreInit + */ + public function setEnableTheming($value) + { + if($this->_stage>=self::CS_CHILD_INITIALIZED) + throw new TInvalidOperationException('control_enabletheming_unchangeable',get_class($this),$this->getUniqueID()); + else if(TPropertyValue::ensureBoolean($value)) + $this->_flags &= ~self::IS_DISABLE_THEMING; + else + $this->_flags |= self::IS_DISABLE_THEMING; + } + + /** + * @return boolean whether the control has child controls + */ + public function getHasControls() + { + return isset($this->_rf[self::RF_CONTROLS]) && $this->_rf[self::RF_CONTROLS]->getCount()>0; + } + + /** + * @return TControlList the child control collection + */ + public function getControls() + { + if(!isset($this->_rf[self::RF_CONTROLS])) + $this->_rf[self::RF_CONTROLS]=new TControlList($this); + return $this->_rf[self::RF_CONTROLS]; + } + + /** + * @param boolean whether the control is visible + */ + public function setVisible($value) + { + if(TPropertyValue::ensureBoolean($value)) + $this->_flags &= ~self::IS_INVISIBLE; + else + $this->_flags |= self::IS_INVISIBLE; + } + + /** + * @return boolean whether the control is visible (default=true). + * A control is visible if all its parents and itself are visible. + */ + public function getVisible() + { + if($this->_flags & self::IS_INVISIBLE) + return false; + else + return $this->_parent?$this->_parent->getVisible():true; + } + + /** + * Returns a value indicating whether the control is enabled. + * A control is enabled if it allows client user interaction. + * If $checkParents is true, all parent controls will be checked, + * and unless they are all enabled, false will be returned. + * The property Enabled is mainly used for {@link TWebControl} + * derived controls. + * @param boolean whether the parents should also be checked enabled + * @return boolean whether the control is enabled. + */ + public function getEnabled($checkParents=false) + { + if($checkParents) + { + for($control=$this;$control;$control=$control->_parent) + if(!$control->getEnabled()) + return false; + return true; + } + else + return $this->getViewState('Enabled',true); + } + + /** + * @param boolean whether the control is to be enabled. + */ + public function setEnabled($value) + { + $this->setViewState('Enabled',TPropertyValue::ensureBoolean($value),true); + } + + /** + * @return boolean whether the control has custom attributes + */ + public function getHasAttributes() + { + if($attributes=$this->getViewState('Attributes',null)) + return $attributes->getCount()>0; + else + return false; + } + + /** + * Returns a value indicating whether this control type can take attributes in template. + * This method can be overriden. + * Only framework developers and control developers should use this method. + * @return boolean whether the control allows attributes in template (default=true) + */ + public function getAllowCustomAttributes() + { + return true; + } + + /** + * Returns the list of custom attributes. + * Custom attributes are name-value pairs that may be rendered + * as HTML tags' attributes. + * @return TMap the list of custom attributes + */ + public function getAttributes() + { + if($attributes=$this->getViewState('Attributes',null)) + return $attributes; + else + { + $attributes=new TMap; + $this->setViewState('Attributes',$attributes,null); + return $attributes; + } + } + + /** + * @return boolean whether viewstate is enabled + */ + public function getEnableViewState() + { + return !($this->_flags & self::IS_DISABLE_VIEWSTATE); + } + + /** + * @param boolean set whether to enable viewstate + */ + public function setEnableViewState($value) + { + if(TPropertyValue::ensureBoolean($value)) + $this->_flags &= ~self::IS_DISABLE_VIEWSTATE; + else + $this->_flags |= self::IS_DISABLE_VIEWSTATE; + } + + /** + * Returns a controlstate value. + * + * This function is mainly used in defining getter functions for control properties + * that must be kept in controlstate. + * @param string the name of the controlstate value to be returned + * @param mixed the default value. If $key is not found in controlstate, $defaultValue will be returned + * @return mixed the controlstate value corresponding to $key + */ + protected function getControlState($key,$defaultValue=null) + { + return isset($this->_rf[self::RF_CONTROLSTATE][$key])?$this->_rf[self::RF_CONTROLSTATE][$key]:$defaultValue; + } + + /** + * Sets a controlstate value. + * + * This function is very useful in defining setter functions for control properties + * that must be kept in controlstate. + * Make sure that the controlstate value must be serializable and unserializable. + * @param string the name of the controlstate value + * @param mixed the controlstate value to be set + * @param mixed default value. If $value===$defaultValue, the item will be cleared from controlstate + */ + protected function setControlState($key,$value,$defaultValue=null) + { + if($value===$defaultValue) + unset($this->_rf[self::RF_CONTROLSTATE][$key]); + else + $this->_rf[self::RF_CONTROLSTATE][$key]=$value; + } + + /** + * Returns a viewstate value. + * + * This function is very useful in defining getter functions for component properties + * that must be kept in viewstate. + * @param string the name of the viewstate value to be returned + * @param mixed the default value. If $key is not found in viewstate, $defaultValue will be returned + * @return mixed the viewstate value corresponding to $key + */ + protected function getViewState($key,$defaultValue=null) + { + return isset($this->_viewState[$key])?$this->_viewState[$key]:$defaultValue; + } + + /** + * Sets a viewstate value. + * + * This function is very useful in defining setter functions for control properties + * that must be kept in viewstate. + * Make sure that the viewstate value must be serializable and unserializable. + * @param string the name of the viewstate value + * @param mixed the viewstate value to be set + * @param mixed default value. If $value===$defaultValue, the item will be cleared from the viewstate. + */ + protected function setViewState($key,$value,$defaultValue=null) + { + if($value===$defaultValue) + unset($this->_viewState[$key]); + else + $this->_viewState[$key]=$value; + } + + /** + * Sets up the binding between a property (or property path) and an expression. + * The context of the expression is the control itself. + * @param string the property name, or property path + * @param string the expression + */ + public function bindProperty($name,$expression) + { + $this->_rf[self::RF_DATA_BINDINGS][$name]=$expression; + } + + /** + * Breaks the binding between a property (or property path) and an expression. + * @param string the property name (or property path) + */ + public function unbindProperty($name) + { + unset($this->_rf[self::RF_DATA_BINDINGS][$name]); + } + + /** + * Performs the databinding for this component. + * Databinding a property includes evaluating the binded expression + * and setting the property with the evaluation result. + * @param boolean whether to raise OnDataBinding event. + * @throws TInvalidOperationException if some bounded property is invalid + * @throws TExpressionInvalidException if some bounded expression is invalid + */ + public function dataBind($raiseOnDataBinding=true) + { + if(isset($this->_rf[self::RF_DATA_BINDINGS])) + { + foreach($this->_rf[self::RF_DATA_BINDINGS] as $property=>$expression) + $this->setPropertyByPath($property,$this->evaluateExpression($expression)); + if($raiseOnDataBinding) + $this->onDataBinding(null); + if(isset($this->_rf[self::RF_CONTROLS])) + { + foreach($this->_rf[self::RF_CONTROLS] as $control) + if($control instanceof TControl) + $control->dataBind($raiseOnDataBinding); + } + } + } + + /** + * @return boolean whether child controls have been created + */ + final protected function getChildControlsCreated() + { + return ($this->_flags & self::IS_CHILD_CREATED)!==0; + } + + /** + * Sets a value indicating whether child controls are created. + * If false, any existing child controls will be cleared up. + * @param boolean whether child controls are created + */ + final protected function setChildControlsCreated($value) + { + if($value) + $this->_flags |= self::IS_CHILD_CREATED; + else + { + if($this->hasControl() && ($this->_flags & self::IS_CHILD_CREATED)) + $this->getControls()->clear(); + $this->_flags &= ~self::IS_CHILD_CREATED; + } + } + + /** + * Ensures child controls are created. + * If child controls are not created yet, this method will invoke + * {@link createChildControl} to create them. + */ + public function ensureChildControls() + { + if(!($this->_flags & self::IS_CHILD_CREATED) && !($this->_flags & self::IS_CREATING_CHILD)) + { + try + { + $this->_flags |= self::IS_CREATING_CHILD; + $this->createChildControls(); + $this->_flags &= ~self::IS_CREATING_CHILD; + $this->_flags |= self::IS_CHILD_CREATED; + } + catch(Exception $e) + { + $this->_flags &= ~self::IS_CREATING_CHILD; + $this->_flags |= self::IS_CHILD_CREATED; + throw $e; + } + } + } + + /** + * Creates child controls. + * This method can be overriden for controls who want to have their controls. + * Do not call this method directly. Instead, call {@link ensureChildControls} + * to ensure child controls are created only once. + */ + protected function createChildControls() + { + } + + /** + * Finds a control by ID path within the current naming container. + * The current naming container is either the control itself + * if it implements {@link INamingContainer} or the control's naming container. + * The ID path is an ID sequence separated by {@link TControl::ID_SEPARATOR}. + * For example, 'Repeater1:Item1:Button1' looks for a control with ID 'Button1' + * whose naming container is 'Item1' whose naming container is 'Repeater1'. + * @param string ID of the control to be looked up + * @return TControl|null the control found, null if not found + * @throws TInvalidDataValueException if a control's ID is found not unique within its naming container. + */ + public function findControl($id) + { + $container=($this instanceof INamingContainer)?$this:$this->getNamingContainer(); + if(!$container || !$container->getHasControls()) + return null; + if(!isset($container->_rf[self::RF_NAMED_CONTROLS])) + { + $container->_rf[self::RF_NAMED_CONTROLS]=array(); + $container->fillNameTable($container,$container->_rf[self::RF_CONTROLS]); + } + if(($pos=strpos($id,self::ID_SEPARATOR))===false) + return isset($container->_rf[self::RF_NAMED_CONTROLS][$id])?$container->_rf[self::RF_NAMED_CONTROLS][$id]:null; + else + { + $cid=substr($id,0,$pos); + $sid=substr($id,$pos+1); + if(isset($container->_rf[self::RF_NAMED_CONTROLS][$cid])) + return $container->_rf[self::RF_NAMED_CONTROLS][$cid]->findControl($sid); + else + return null; + } + } + + /** + * Resets the control as a naming container. + * Only framework developers should use this method. + */ + public function clearNamingContainer() + { + unset($this->_rf[self::RF_NAMED_CONTROLS_ID]); + $this->clearNameTable(); + } + + /** + * Registers an object by a name. + * A registered object can be accessed like a public member variable. + * This method should only be used by framework and control developers. + * @param string name of the object + * @param object object to be declared + * @see __get + */ + public function registerObject($name,$object) + { + $this->_rf[self::RF_NAMED_OBJECTS][$name]=$object; + } + + /** + * This method is invoked after the control is instantiated by a template. + * When this method is invoked, the control should have a valid TemplateControl + * and has its properties initialized according to template configurations. + * The control, however, has not been added to the page hierarchy yet. + * The default implementation of this method will invoke + * the potential parent control's {@link addParsedObject} to add the control as a child. + * This method can be overriden. + * @param TControl potential parent of this control + * @see addParsedObject + */ + public function createdOnTemplate($parent) + { + $parent->addParsedObject($this); + } + + /** + * Processes an object that is created during parsing template. + * The object can be either a control or a static text string. + * By default, the object will be added into the child control collection. + * This method can be overriden to customize the handling of newly created objects in template. + * Only framework developers and control developers should use this method. + * @param string|TComponent text string or component parsed and instantiated in template + * @see createdOnTemplate + */ + public function addParsedObject($object) + { + $this->getControls()->add($object); + } + + /** + * Clears up the child state data. + * After a control loads its state, those state that do not belong to + * any existing child controls are stored as child state. + * This method will remove these state. + * Only frameworker developers and control developers should use this method. + */ + final protected function clearChildState() + { + unset($this->_rf[self::RF_CHILD_STATE]); + } + + /** + * @param TControl the potential ancestor control + * @return boolean if the control is a descendent (parent, parent of parent, etc.) + * of the specified control + */ + final protected function isDescendentOf($ancestor) + { + $control=$this; + while($control!==$ancestor && $control->_parent) + $control=$control->_parent; + return $control===$ancestor; + } + + /** + * Adds a control into the child collection of the control. + * Control lifecycles will be caught up during the addition. + * Only framework developers should use this method. + * @param TControl the new child control + */ + public function addedControl($control) + { + if($control->_parent) + $control->_parent->getControls()->remove($control); + $control->_parent=$this; + $control->_page=$this->getPage(); + $namingContainer=($this instanceof INamingContainer)?$this:$this->_namingContainer; + if($namingContainer) + { + $control->_namingContainer=$namingContainer; + if($control->_id==='') + $control->generateAutomaticID(); + else + $namingContainer->clearNameTable(); + } + + if($this->_stage>=self::CS_INITIALIZED) + { + $control->initRecursive($namingContainer); + if($this->_stage>=self::CS_STATE_LOADED) + { + if(isset($this->_rf[self::RF_CHILD_STATE])) + $state=$this->_rf[self::RF_CHILD_STATE]->remove($control->_id); + else + $state=null; + $control->loadStateRecursive($state,!($this->_flags & self::IS_DISABLE_VIEWSTATE)); + if($this->_stage>=self::CS_LOADED) + { + $control->loadRecursive(); + if($this->_stage>=self::CS_PRERENDERED) + $control->preRenderRecursive(); + } + } + } + } + + /** + * Removes a control from the child collection of the control. + * Only framework developers should use this method. + * @param TControl the child control removed + */ + public function removedControl($control) + { + if($this->_namingContainer) + $this->_namingContainer->clearNameTable(); + $control->unloadRecursive(); + $control->_parent=null; + $control->_page=null; + $control->_namingContainer=null; + $control->_tplControl=null; + if(!($control->_flags & self::IS_ID_SET)) + $control->_id=''; + $control->clearCachedUniqueID(true); + } + + /** + * Performs the Init step for the control and all its child controls. + * Only framework developers should use this method. + * @param TControl the naming container control + */ + protected function initRecursive($namingContainer) + { + $this->ensureChildControls(); + if($this->getHasControls()) + { + if($this instanceof INamingContainer) + $namingContainer=$this; + $page=$this->getPage(); + foreach($this->_rf[self::RF_CONTROLS] as $control) + { + if($control instanceof TControl) + { + $control->_namingContainer=$namingContainer; + $control->_page=$page; + if($control->_id==='' && $namingContainer) + $control->generateAutomaticID(); + $control->initRecursive($namingContainer); + } + } + } + if($this->_stage_stage=self::CS_CHILD_INITIALIZED; + if(($page=$this->getPage()) && $page->getContainsTheme() && $this->getEnableTheming() && !($this->_flags & self::IS_SKIN_APPLIED)) + { + $page->applyControlSkin($this); + $this->_flags |= self::IS_SKIN_APPLIED; + } + $this->onInit(null); + $this->_stage=self::CS_INITIALIZED; + } + } + + /** + * Performs the Load step for the control and all its child controls. + * Only framework developers should use this method. + */ + protected function loadRecursive() + { + if($this->_stageonLoad(null); + if($this->getHasControls()) + { + foreach($this->_rf[self::RF_CONTROLS] as $control) + if($control instanceof TControl) + $control->loadRecursive(); + } + if($this->_stage_stage=self::CS_LOADED; + } + + /** + * Performs the PreRender step for the control and all its child controls. + * Only framework developers should use this method. + */ + protected function preRenderRecursive() + { + if($this->getVisible()) + { + $this->_flags &= ~self::IS_INVISIBLE; + $this->onPreRender(null); + if($this->getHasControls()) + { + foreach($this->_rf[self::RF_CONTROLS] as $control) + if($control instanceof TControl) + $control->preRenderRecursive(); + } + } + else + { + $this->_flags |= self::IS_INVISIBLE; + } + $this->_stage=self::CS_PRERENDERED; + } + + /** + * Performs the Unload step for the control and all its child controls. + * Only framework developers should use this method. + */ + protected function unloadRecursive() + { + if(!($this->_flags & self::IS_ID_SET)) + $this->_id=''; + if($this->getHasControls()) + { + foreach($this->_rf[self::RF_CONTROLS] as $control) + if($control instanceof TControl) + $control->unloadRecursive(); + } + $this->onUnload(null); + } + + /** + * This method is invoked when the control enters 'Init' stage. + * The method raises 'Init' event. + * If you override this method, be sure to call the parent implementation + * so that the event handlers can be invoked. + * @param TEventParameter event parameter to be passed to the event handlers + */ + protected function onInit($param) + { + $this->raiseEvent('Init',$this,$param); + } + + /** + * This method is invoked when the control enters 'Load' stage. + * The method raises 'Load' event. + * If you override this method, be sure to call the parent implementation + * so that the event handlers can be invoked. + * @param TEventParameter event parameter to be passed to the event handlers + */ + protected function onLoad($param) + { + $this->raiseEvent('Load',$this,$param); + } + + /** + * Raises 'DataBinding' event. + * This method is invoked when {@link dataBind} is invoked. + * @param TEventParameter event parameter to be passed to the event handlers + */ + protected function onDataBinding($param) + { + $this->raiseEvent('DataBinding',$this,$param); + } + + + /** + * This method is invoked when the control enters 'Unload' stage. + * The method raises 'Unload' event. + * If you override this method, be sure to call the parent implementation + * so that the event handlers can be invoked. + * @param TEventParameter event parameter to be passed to the event handlers + */ + protected function onUnload($param) + { + $this->raiseEvent('Unload',$this,$param); + } + + /** + * This method is invoked when the control enters 'PreRender' stage. + * The method raises 'PreRender' event. + * If you override this method, be sure to call the parent implementation + * so that the event handlers can be invoked. + * @param TEventParameter event parameter to be passed to the event handlers + */ + protected function onPreRender($param) + { + $this->raiseEvent('PreRender',$this,$param); + } + + /** + * Invokes the parent's onBubbleEvent method. + * A control who wants to bubble an event must call this method in its onEvent method. + * @param TControl sender of the event + * @param TEventParameter event parameter + * @see onBubbleEvent + */ + protected function raiseBubbleEvent($sender,$param) + { + $control=$this; + while($control=$control->_parent) + { + if($control->onBubbleEvent($sender,$param)) + break; + } + } + + /** + * This method responds to a bubbled event. + * This method should be overriden to provide customized response to a bubbled event. + * Check the type of event parameter to determine what event is bubbled currently. + * @param TControl sender of the event + * @param TEventParameter event parameters + * @return boolean true if the event bubbling is handled and no more bubbling. + * @see raiseBubbleEvent + */ + protected function onBubbleEvent($sender,$param) + { + return false; + } + + /** + * Renders the control. + * Only when the control is visible will the control be rendered. + * @param THtmlTextWriter the writer used for the rendering purpose + */ + protected function renderControl($writer) + { + if(!($this->_flags & self::IS_INVISIBLE)) + $this->render($writer); + } + + /** + * Renders the control. + * This method is invoked by {@link renderControl} when the control is visible. + * You can override this method to provide customized rendering of the control. + * By default, the control simply renders all its child contents. + * @param THtmlTextWriter the writer used for the rendering purpose + */ + protected function render($writer) + { + $this->renderChildren($writer); + } + + /** + * Renders the children of the control. + * This method iterates through all child controls and static text strings + * and renders them in order. + * @param THtmlTextWriter the writer used for the rendering purpose + */ + protected function renderChildren($writer) + { + if($this->getHasControls()) + { + foreach($this->_rf[self::RF_CONTROLS] as $control) + { + if($control instanceof TControl) + $control->renderControl($writer); + else if(is_string($control)) + $writer->write($control); + } + } + } + + /** + * This method is invoked when control state is to be saved. + * You can override this method to do last step state saving. + * Parent implementation must be invoked. + * @param TEventParameter event parameter + */ + protected function onSaveState($param) + { + $this->setViewState('Visible',!($this->_flags & self::IS_INVISIBLE),true); + $this->raiseEvent('SaveState',$this,$param); + } + + /** + * This method is invoked right after the control has loaded its state. + * You can override this method to initialize data from the control state. + * Parent implementation must be invoked. + * @param TEventParameter + */ + protected function onLoadState($param) + { + $this->setVisible($this->getViewState('Visible',true)); + $this->raiseEvent('LoadState',$this,$param); + } + + /** + * Loads state (viewstate and controlstate) into a control and its children. + * @param TMap the collection of the state + * @param boolean whether the viewstate should be loaded + */ + final protected function loadStateRecursive(&$state,$needViewState=true) + { + // A null state means the stateful properties all take default values. + // So if the state is enabled, we have to assign the null value. + $needViewState=($needViewState && !($this->_flags & self::IS_DISABLE_VIEWSTATE)); + if(is_array($state)) + { + if(isset($state[1])) + { + $this->_rf[self::RF_CONTROLSTATE]=&$state[1]; + unset($state[1]); + } + else + unset($this->_rf[self::RF_CONTROLSTATE]); + if($needViewState) + { + if(isset($state[0])) + $this->_viewState=&$state[0]; + else + $this->_viewState=array(); + } + unset($state[0]); + if($this->getHasControls()) + { + foreach($this->_rf[self::RF_CONTROLS] as $control) + { + if($control instanceof TControl) + { + if(isset($state[$control->_id])) + { + $s=&$state[$control->_id]; + unset($state[$control->_id]); + } + else + $s=null; + $control->loadStateRecursive($s,$needViewState); + } + } + } + if(!empty($state)) + $this->_rf[self::RF_CHILD_STATE]=&$state; + } + else + { + unset($this->_rf[self::RF_CONTROLSTATE]); + if($needViewState) + $this->_viewState=array(); + if($this->getHasControls()) + { + foreach($this->_rf[self::RF_CONTROLS] as $control) + { + $s=null; + if($control instanceof TControl) + $control->loadStateRecursive($s,$needViewState); + } + } + } + $this->onLoadState(null); + $this->_stage=self::CS_STATE_LOADED; + } + + /** + * Saves the all control state (viewstate and controlstate) as a collection. + * @param boolean whether the viewstate should be saved + * @return TMap the collection of the control state (including its children's state). + */ + final protected function &saveStateRecursive($needViewState=true) + { + $this->onSaveState(null); + $needViewState=($needViewState && !($this->_flags & self::IS_DISABLE_VIEWSTATE)); + $state=array(); + if($this->getHasControls()) + { + foreach($this->_rf[self::RF_CONTROLS] as $control) + { + if($control instanceof TControl) + { + $cs=&$control->saveStateRecursive($needViewState); + if(!empty($cs)) + $state[$control->_id]=&$cs; + } + } + } + if($needViewState && !empty($this->_viewState)) + $state[0]=&$this->_viewState; + if(isset($this->_rf[self::RF_CONTROLSTATE]) && !empty($this->_rf[self::RF_CONTROLSTATE])) + $state[1]=&$this->_rf[self::RF_CONTROLSTATE]; + return $state; + } + + /** + * Applies a stylesheet skin to a control. + * @param TPage the page containing the control + * @throws TInvalidOperationException if the stylesheet skin is applied already + */ + public function applyStyleSheetSkin($page) + { + if($page && !($this->_flags & self::IS_STYLESHEET_APPLIED)) + { + $page->applyControlStyleSheet($this); + $this->_flags |= self::IS_STYLESHEET_APPLIED; + } + else if($this->_flags & self::IS_STYLESHEET_APPLIED) + throw new TInvalidOperationException('control_stylesheet_applied',get_class($this),$this->getUniqueID()); + } + + /** + * Clears the cached UniqueID. + * If $recursive=true, all children's cached UniqueID will be cleared as well. + * @param boolean whether the clearing is recursive. + */ + private function clearCachedUniqueID($recursive) + { + $this->_uid=''; + if($recursive && isset($this->_rf[self::RF_CONTROLS])) + { + foreach($this->_rf[self::RF_CONTROLS] as $control) + if($control instanceof TControl) + $control->clearCachedUniqueID($recursive); + } + } + + /** + * Generates an automatic ID for the control. + */ + private function generateAutomaticID() + { + $this->_flags &= ~self::IS_ID_SET; + if(!isset($this->_namingContainer->_rf[self::RF_NAMED_CONTROLS_ID])) + $this->_namingContainer->_rf[self::RF_NAMED_CONTROLS_ID]=0; + $id=$this->_namingContainer->_rf[self::RF_NAMED_CONTROLS_ID]++; + $this->_id=self::AUTOMATIC_ID_PREFIX . $id; + $this->_namingContainer->clearNameTable(); + } + + /** + * Clears the list of the controls whose IDs are managed by the specified naming container. + */ + private function clearNameTable() + { + unset($this->_rf[self::RF_NAMED_CONTROLS]); + } + + /** + * Updates the list of the controls whose IDs are managed by the specified naming container. + * @param TControl the naming container + * @param TControlList list of controls + * @throws TInvalidDataValueException if a control's ID is not unique within its naming container. + */ + private function fillNameTable($container,$controls) + { + foreach($controls as $control) + { + if($control instanceof TControl) + { + if($control->_id!=='') + { + if(isset($container->_rf[self::RF_NAMED_CONTROLS][$control->_id])) + throw new TInvalidDataValueException('control_id_not_unique',$control->_id,get_class($control)); + else + $container->_rf[self::RF_NAMED_CONTROLS][$control->_id]=$control; + } + if(!($control instanceof INamingContainer) && $control->getHasControls()) + $this->fillNameTable($container,$control->_rf[self::RF_CONTROLS]); + } + } + } +} + + +/** + * TControlList class + * + * TControlList implements a collection that enables + * controls to maintain a list of their child controls. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web.UI + * @since 3.0 + */ +class TControlList extends TList +{ + /** + * the control that owns this collection. + * @var TControl + */ + private $_o; + + /** + * Constructor. + * @param TControl the control that owns this collection. + */ + public function __construct(TControl $owner) + { + parent::__construct(); + $this->_o=$owner; + } + + /** + * @return TControl the control that owns this collection. + */ + protected function getOwner() + { + return $this->_o; + } + + /** + * Overrides the parent implementation with customized processing of the newly added item. + * @param mixed the newly added item + */ + protected function addedItem($item) + { + if($item instanceof TControl) + $this->_o->addedControl($item); + } + + /** + * Overrides the parent implementation with customized processing of the removed item. + * @param mixed the removed item + */ + protected function removedItem($item) + { + if($item instanceof TControl) + $this->_o->removedControl($item); + } + + /** + * Only string or instance of TControl can be added into collection. + * @param mixed the item to be added + */ + protected function canAddItem($item) + { + return is_string($item) || ($item instanceof TControl); + } + + /** + * Overrides the parent implementation by invoking {@link TControl::clearNamingContainer} + */ + public function clear() + { + parent::clear(); + if($this->_o instanceof INamingContainer) + $this->_o->clearNamingContainer(); + } +} + +/** + * INamingContainer interface. + * INamingContainer marks a control as a naming container. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web.UI + * @since 3.0 + */ +interface INamingContainer +{ +} + +/** + * IPostBackEventHandler interface + * + * If a control wants to respond to postback event, it must implement this interface. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web.UI + * @since 3.0 + */ +interface IPostBackEventHandler +{ + /** + * Raises postback event. + * The implementation of this function should raise appropriate event(s) (e.g. OnClick, OnCommand) + * indicating the component is responsible for the postback event. + * @param string the parameter associated with the postback event + */ + public function raisePostBackEvent($param); +} + + +/** + * IPostBackDataHandler interface + * + * If a control wants to load post data, it must implement this interface. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web.UI + * @since 3.0 + */ +interface IPostBackDataHandler +{ + /** + * Loads user input data. + * The implementation of this function can use $values[$key] to get the user input + * data that are meant for the particular control. + * @param string the key that can be used to retrieve data from the input data collection + * @param array the input data collection + * @return boolean whether the data of the control has been changed + */ + public function loadPostData($key,$values); + /** + * Raises postdata changed event. + * The implementation of this function should raise appropriate event(s) (e.g. OnTextChanged) + * indicating the control data is changed. + */ + public function raisePostDataChangedEvent(); +} + + +/** + * IValidator interface + * + * If a control wants to validate user input, it must implement this interface. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web.UI + * @since 3.0 + */ +interface IValidator +{ + /** + * Validates certain data. + * The implementation of this function should validate certain data + * (e.g. data entered into TTextBox control). + * @return boolean whether the data passes the validation + */ + public function validate(); + /** + * @return boolean whether the previous {@link validate()} is successful. + */ + public function getIsValid(); + /** + * @param boolean whether the validator validates successfully + */ + public function setIsValid($value); + /** + * @return string error message during last validate + */ + public function getErrorMessage(); + /** + * @param string error message for the validation + */ + public function setErrorMessage($value); +} + + +/** + * IValidatable interface + * + * If a control wants to be validated by a validator, it must implement this interface. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web.UI + * @since 3.0 + */ +interface IValidatable +{ + /** + * @return mixed the value of the property to be validated. + */ + public function getValidationPropertyValue(); +} + +/** + * TCommandEventParameter class + * + * TCommandEventParameter encapsulates the parameter data for OnCommand + * event of button controls. You can access the name of the command via + * Name property, and the parameter carried with the command via + * Parameter property. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web.UI + * @since 3.0 + */ +class TCommandEventParameter extends TEventParameter +{ + private $_name; + private $_param; + + /** + * Constructor. + * @param string name of the command + * @param string parameter of the command + */ + public function __construct($name='',$parameter='') + { + $this->_name=$name; + $this->_param=$parameter; + } + + /** + * @return string name of the command + */ + public function getName() + { + return $this->_name; + } + + /** + * @param string name of the command + */ + public function setName($value) + { + $this->_name=$value; + } + + /** + * @return string parameter of the command + */ + public function getParameter() + { + return $this->_param; + } + + /** + * @param string parameter of the command + */ + public function setParameter($value) + { + $this->_param=$value; + } +} + +?> \ No newline at end of file diff --git a/framework/Web/UI/TForm.php b/framework/Web/UI/TForm.php new file mode 100644 index 00000000..0edb976b --- /dev/null +++ b/framework/Web/UI/TForm.php @@ -0,0 +1,128 @@ +getPage()->setForm($this); + } + + protected function addAttributesToRender($writer) + { + $attributes=$this->getAttributes(); + $writer->addAttribute('name',$this->getName()); + $writer->addAttribute('method',$this->getMethod()); + $writer->addAttribute('action',$this->getApplication()->getRequest()->getRequestURI()); + $attributes->remove('name'); + $attributes->remove('method'); + $attributes->remove('action'); + + $page=$this->getPage(); + $onsubmit=$page->getClientOnSubmitEvent(); + if($onsubmit!=='') + { + if(($existing=$attributes->itemAt('onsubmit'))!=='') + { + $page->getClientScript()->registerOnSubmitStatement('TForm:OnSubmitScript',$existing); + $attributes->remove('onsubmit'); + } + if($page->getClientSupportsJavaScript()) + $writer->addAttribute('onsubmit',$onsubmit); + } + if($this->getDefaultButton()!=='') + {//todo + $control=$this->findControl($this->getDefaultButton()); + if(!$control) + $control=$page->findControl($this->getDefaultButton()); + if($control instanceof IButtonControl) + $page->getClientScript()->registerDefaultButtonScript($control,$writer,false); + else + throw new Exception('Only IButtonControl can be default button.'); + } + $writer->addAttribute('id',$this->getUniqueID()); + foreach($attributes as $name=>$value) + $writer->addAttribute($name,$value); + } + + /** + * @internal + */ + protected function render($writer) + { + $this->addAttributesToRender($writer); + $writer->renderBeginTag('form'); + $page=$this->getPage(); + $page->beginFormRender($writer); + $this->renderChildren($writer); + $page->endFormRender($writer); + $writer->renderEndTag(); + } + + public function getDefaultButton() + { + return $this->getViewState('DefaultButton',''); + } + + public function setDefaultButton($value) + { + $this->setViewState('DefaultButton',$value,''); + } + + public function getDefaultFocus() + { + return $this->getViewState('DefaultFocus',''); + } + + public function setDefaultFocus($value) + { + $this->setViewState('DefaultFocus',$value,''); + } + + public function getMethod() + { + return $this->getViewState('Method','post'); + } + + public function setMethod($value) + { + $this->setViewState('Method',$value,'post'); + } + + public function getEnctype() + { + return $this->getViewState('Enctype',''); + } + + public function setEnctype($value) + { + $this->setViewState('Enctype',$value,''); + } + + public function getSubmitDisabledControls() + { + return $this->getViewState('SubmitDisabledControls',false); + } + + public function setSubmitDisabledControls($value) + { + $this->setViewState('SubmitDisabledControls',TPropertyValue::ensureBoolean($value),false); + } + + public function getName() + { + return $this->getUniqueID(); + } + + public function getTarget() + { + return $this->getViewState('Target',''); + } + + public function setTarget($value) + { + $this->setViewState('Target',$value,''); + } +} + +?> \ No newline at end of file diff --git a/framework/Web/UI/THiddenFieldPageStatePersister.php b/framework/Web/UI/THiddenFieldPageStatePersister.php new file mode 100644 index 00000000..d2cb5226 --- /dev/null +++ b/framework/Web/UI/THiddenFieldPageStatePersister.php @@ -0,0 +1,59 @@ +_page=$page; + } + + public function save($state) + { + $data=Prado::serialize($state); + $hmac=$this->computeHMAC($data,$this->getKey()); + if(function_exists('gzuncompress') && function_exists('gzcompress')) + $data=gzcompress($hmac.$data); + else + $data=$hmac.$data; + $this->_page->saveStateField($data); + } + + public function load() + { + $str=$this->_page->loadStateField(); + if($str==='') + return null; + if(function_exists('gzuncompress') && function_exists('gzcompress')) + $data=gzuncompress($str); + else + $data=$str; + if($data!==false && strlen($data)>32) + { + $hmac=substr($data,0,32); + $state=substr($data,32); + if($hmac===$this->computeHMAC($state,$this->getKey())) + return Prado::unserialize($state); + } + throw new Exception('viewstate data is corrupted.'); + } + + private function getKey() + { + return 'abcdefe'; + } + + private function computeHMAC($data,$key) + { + if (strlen($key) > 64) + $key = pack('H32', md5($key)); + elseif (strlen($key) < 64) + $key = str_pad($key, 64, "\0"); + return md5((str_repeat("\x5c", 64) ^ substr($key, 0, 64)) . pack('H32', md5((str_repeat("\x36", 64) ^ substr($key, 0, 64)) . $data))); + } +} + +?> \ No newline at end of file diff --git a/framework/Web/UI/THtmlTextWriter.php b/framework/Web/UI/THtmlTextWriter.php new file mode 100644 index 00000000..4ea78383 --- /dev/null +++ b/framework/Web/UI/THtmlTextWriter.php @@ -0,0 +1,235 @@ +2, + 'a'=>0, + 'acronym'=>0, + 'address'=>2, + 'area'=>1, + 'b'=>0, + 'base'=>1, + 'basefont'=>1, + 'bdo'=>0, + 'bgsound'=>1, + 'big'=>0, + 'blockquote'=>2, + 'body'=>2, + 'br'=>2, + 'button'=>0, + 'caption'=>2, + 'center'=>2, + 'cite'=>0, + 'code'=>0, + 'col'=>1, + 'colgroup'=>2, + 'del'=>0, + 'dd'=>0, + 'dfn'=>0, + 'dir'=>2, + 'div'=>2, + 'dl'=>2, + 'dt'=>0, + 'em'=>0, + 'embed'=>1, + 'fieldset'=>2, + 'font'=>0, + 'form'=>2, + 'frame'=>1, + 'frameset'=>2, + 'h1'=>2, + 'h2'=>2, + 'h3'=>2, + 'h4'=>2, + 'h5'=>2, + 'h6'=>2, + 'head'=>2, + 'hr'=>1, + 'html'=>2, + 'i'=>0, + 'iframe'=>2, + 'img'=>1, + 'input'=>1, + 'ins'=>0, + 'isindex'=>1, + 'kbd'=>0, + 'label'=>0, + 'legend'=>2, + 'li'=>0, + 'link'=>1, + 'map'=>2, + 'marquee'=>2, + 'menu'=>2, + 'meta'=>1, + 'nobr'=>0, + 'noframes'=>2, + 'noscript'=>2, + 'object'=>2, + 'ol'=>2, + 'option'=>2, + 'p'=>0, + 'param'=>2, + 'pre'=>2, + 'ruby'=>2, + 'rt'=>2, + 'q'=>0, + 's'=>0, + 'samp'=>0, + 'script'=>2, + 'select'=>2, + 'small'=>2, + 'span'=>0, + 'strike'=>0, + 'strong'=>0, + 'style'=>2, + 'sub'=>0, + 'sup'=>0, + 'table'=>2, + 'tbody'=>2, + 'td'=>0, + 'textarea'=>0, + 'tfoot'=>2, + 'th'=>0, + 'thead'=>2, + 'title'=>2, + 'tr'=>2, + 'tt'=>0, + 'u'=>0, + 'ul'=>2, + 'var'=>0, + 'wbr'=>1, + 'xml'=>2 + ); + private static $_attrEncode=array( + 'abbr'=>true, + 'accesskey'=>true, + 'align'=>false, + 'alt'=>true, + 'autocomplete'=>false, + 'axis'=>true, + 'background'=>true, + 'bgcolor'=>false, + 'border'=>false, + 'bordercolor'=>false, + 'cellpadding'=>false, + 'cellspacing'=>false, + 'checked'=>false, + 'class'=>true, + 'cols'=>false, + 'colspan'=>false, + 'content'=>true, + 'coords'=>false, + 'dir'=>false, + 'disabled'=>false, + 'for'=>false, + 'headers'=>true, + 'height'=>false, + 'href'=>true, + 'id'=>false, + 'longdesc'=>true, + 'maxlength'=>false, + 'multiple'=>false, + 'name'=>false, + 'nowrap'=>false, + 'onclick'=>true, + 'onchange'=>true, + 'readonly'=>false, + 'rel'=>false, + 'rows'=>false, + 'rowspan'=>false, + 'rules'=>false, + 'scope'=>false, + 'selected'=>false, + 'shape'=>false, + 'size'=>false, + 'src'=>true, + 'style'=>false, + 'tabindex'=>false, + 'target'=>false, + 'title'=>true, + 'type'=>false, + 'usemap'=>false, + 'valign'=>false, + 'value'=>true, + 'vcard_name'=>false, + 'width'=>false, + 'wrap'=>false + ); + + private $_attributes=array(); + private $_openTags=array(); + private $_writer=null; + + public function __construct($writer) + { + $this->_writer=$writer; + } + + public function isValidFormAttribute($name) + { + return true; + } + + public function addAttribute($name,$value) + { + $this->_attributes[$name]=isset(self::$_attrEncode[$name])?THttpUtility::htmlEncode($value):$value; + } + + public function flush() + { + $this->_writer->flush(); + } + + public function write($str) + { + $this->_writer->write($str); + } + + public function writeLine($str='') + { + $this->_writer->write($str.self::CHAR_NEWLINE); + } + + public function writeAttribute($name,$value,$encode=false) + { + $this->_writer->write(' '.$name.='"'.($encode?THttpUtility::htmlEncode($value):$value).'"'); + } + + public function renderBeginTag($tagName) + { + $tagType=isset(self::$_tagTypes[$tagName])?self::$_tagTypes[$tagName]:self::TAG_OTHER; + $str='<'.$tagName; + foreach($this->_attributes as $name=>$value) + $str.=' '.$name.'="'.$value.'"'; + if($tagType===self::TAG_NONCLOSING) + { + $str.=' />'; + array_push($this->_openTags,''); + } + else + { + $str.='>'; + array_push($this->_openTags,$tagName); + } + $this->_writer->write($str); + $this->_attributes=array(); + } + + public function renderEndTag() + { + if(!empty($this->_openTags) && ($tagName=array_pop($this->_openTags))!=='') + $this->_writer->write(''); + } +} + +?> \ No newline at end of file diff --git a/framework/Web/UI/TPage.php b/framework/Web/UI/TPage.php new file mode 100644 index 00000000..bb8f2253 --- /dev/null +++ b/framework/Web/UI/TPage.php @@ -0,0 +1,617 @@ +_application=Prado::getApplication(); + $this->setPage($this); + if(is_array($initProperties)) + { + foreach($initProperties as $name=>$value) + $this->setPropertyByPath($name,$value); + } + parent::__construct(); + } + + /** + * Loads and parses the control template + * @return ITemplate the parsed template structure + */ + protected function loadTemplate() + { + if($this->_templateFile===null) + return parent::loadTemplate(); + else + { + $template=Prado::getApplication()->getService()->getTemplateManager()->loadTemplateByFileName(Prado::getPathOfNamespace($this->_templateFile,'.tpl')); + $this->setTemplate($template); + return $template; + } + } + + public function getTemplateFile() + { + return $this->_templateFile; + } + + public function setTemplateFile($value) + { + $this->_templateFile=$value; + } + + final public function setForm($form) + { + $this->_form=$form; + } + + final public function getForm() + { + return $this->_form; + } + + public function validate($validationGroup='') + { + $this->_validated=true; + if($validationGroup==='') + { + foreach($this->_validators as $validator) + $validator->validate(); + } + else + { + foreach($this->_validators as $validator) + if($validator->getValidationGroup()===$validationGroup) + $validator->validate(); + } + } + + public function RegisterEnabledControl($control) + { + $this->getEna.EnabledControls.Add(control); + } + + + + /** + * @internal + */ + public function registerPostBackScript() + { + if($this->getClientSupportsJavaScript() && !$this->_postBackScriptRendered) + { + if(!$this->_requirePostBackScript) + { + $this->getClientScript()->registerHiddenField('__EVENTTARGET',''); + $this->getClientScript()->registerHiddenField('__EVENTPARAM',''); + $this->_requirePostBackScript=true; + } + } + } + + public function registerWebFormsScript() + { + if($this->getClientSupportsJavaScript() && !$this->_webFormsScriptRendered) + { + $this->registerPostBackScript(); + $this->_requireWebFormsScript=true; + } + } + + + public function ensureRenderInForm($control) + { + if(!$this->_inFormRender) + throw new THttpException('control_not_in_form',$control->getUniqueID()); + } + + /** + * @internal + */ + final protected function addContentTemplate($name,$template) + { + if(!$this->_contentTemplateCollection) + $this->_contentTemplateCollection=new TMap; + if($this->_contentTemplateCollection->has($name)) + throw new Exception("Content '$name' duplicated."); + $this->_contentTemplateCollection->add($name,$template); + } + + /** + * @internal + */ + final public function applyControlSkin($control) + { + if($this->_theme) + $this->_theme->applySkin($control); + } + + /** + * @internal + */ + final public function applyControlStyleSheet($control) + { + if($this->_styleSheet) + { + $this->_styleSheet->applySkin($control); + return true; + } + else + return false; + } + + private function renderStateFields($writer) + { + $writer->write("\n_pageState."\" />\n"); + } + + private function renderPostBackScript($writer) + { + $id=$this->_form->getUniqueID(); + $str=<< + +\n +EOD; + $writer->write($str); + $this->_postBackScriptRendered=true; + } + + private function renderWebFormsScript($writer) + { + $writer->write("\n\n"); + $this->_webFormsScriptRendered=true; + } + + final public function getClientSupportsJavaScript() + { + // todo + return true; + } + + /** + * @internal + */ + final public function beginFormRender($writer) + { + if($this->_formRendered) + throw new THttpException('multiple_form_not_allowed'); + $this->_formRendered=true; + $this->_inFormRender=true; + + $this->getClientScript()->renderHiddenFields($writer); + //$this->renderStateFields($writer); + if($this->getClientSupportsJavaScript()) + { + /* + if($this->getMaintainScrollPositionOnPostBack() && !$this->_requireScrollScript) + { + $cs=$this->getClientScript(); + $cs->registerHiddenField('_SCROLLPOSITIONX',$this->_scrollPositionX); + $cs->registerHiddenField('_SCROLLPOSITIONY',$this->_scrollPositionY); + $cs->registerStartupScript(get_class($this),"PageScrollPositionScript", "\r\nvar WebForm_ScrollPositionSubmit = theForm.submit;\r\ntheForm.submit = WebForm_SaveScrollPositionSubmit;\r\n\r\nvar WebForm_ScrollPositionOnSubmit = theForm.onsubmit;\r\ntheForm.onsubmit = WebForm_SaveScrollPositionOnSubmit;\r\n\r\nvar WebForm_ScrollPositionLoad = window.onload;\r\nwindow.onload = WebForm_RestoreScrollPosition;\r\n", true); + $this->registerWebFormScript(); + $this->_requireScrollScript=true; + } + */ + if($this->_requirePostBackScript) + $this->renderPostBackScript($writer,$this->_form->getUniqueID()); + if($this->_requireWebFormsScript) + $this->renderWebFormsScript($writer); + } + $this->getClientScript()->renderClientScriptBlocks($writer); + // todo: more .... + } + + final public function getIsPostBackEventControlRegistered() + { + return $this->_registeredControlThatRequireRaiseEvent!==null; + } + + /** + * @internal + */ + final public function endFormRender($writer) + { + $cs=$this->getClientScript(); + if($this->getClientSupportsJavaScript()) + $cs->renderArrayDeclarations($writer); + $cs->renderHiddenFields($writer); + if($this->getClientSupportsJavaScript()) + { + if($this->_requirePostBackScript && !$this->_postBackScriptRendered) + $this->renderPostBackScript($writer); + if($this->_requireWebFormsScript && !$this->_webFormsScriptRendered) + $this->renderWebFormsScript($writer); + } + $cs->renderClientStartupScripts($writer); + $this->_inFormRender=false; + } + + final public function getClientScript() + { + if(!$this->_clientScript) + $this->_clientScript=new TClientScriptManager($this); + return $this->_clientScript; + } + + final public function getClientOnSubmitEvent() + { + // todo + if($this->getClientScript()->getHasSubmitStatements()) + return 'javascript:return WebForm_OnSubmit();'; + else + return ''; + } + + final public function getValidators($validationGroup='') + { + if(!$this->_validators) + $this->_validators=new TList; + if($validationGroup==='') + return $this->_validators; + $list=new TList; + foreach($this->_validators as $validator) + if($validator->getValidationGroup()===$validationGroup) + $list->add($validator); + return $list; + } + + protected function initializeCulture() + { + } + + /** + * @internal + */ + public function initializeStyleSheet() + { + if($this->_styleSheet!=='') + $this->_styleSheet=new TTheme($this->_styleSheetName); + } + + private function initializeThemes() + { + if($this->_themeName!=='') + $this->_theme=new TTheme($this->_themeName); + if($this->_styleSheetName!=='') + $this->_styleSheet=new TTheme($this->_styleSheetName); + } + + /** + * @internal + */ + public function loadScrollPosition() + { + if($this->_previousPagePath==='' && $this->_requestValueCollection) + { + if(isset($_REQUEST['__SCROLLPOSITIONX'])) + $this->_scrollPositionX=(integer)$_REQUEST['__SCROLLPOSITIONX']; + if(isset($_REQUEST['__SCROLLPOSITIONY'])) + $this->_scrollPositionX=(integer)$_REQUEST['__SCROLLPOSITIONY']; + } + } + + protected function onInit($param) + { + parent::onInit($param);/* + if($this->_theme) + $this->_theme->setStyleSheet(); + if($this->_styleSheet) + $this->_styleSheet->setStyleSheet();*/ + } + + protected function onInitComplete($param) + { + $this->raiseEvent('InitComplete',$this,$param); + } + + protected function onLoadComplete($param) + { + $this->raiseEvent('LoadComplete',$this,$param); + } + + protected function onPreInit($param) + { + $this->raiseEvent('PreInit',$this,$param); + } + + protected function onPreLoad($param) + { + $this->raiseEvent('PreLoad',$this,$param); + } + + protected function onPreRenderComplete($param) + { + $this->raiseEvent('PreRenderComplete',$this,$param); + } + + protected function onSaveStateComplete($param) + { + $this->raiseEvent('SaveStateComplete',$this,$param); + } + + final public function registerAsyncTask() + { + } + + final public function registerRequiresPostBack($control) + { + if(!$this->_registeredControlsThatRequirePostBack) + $this->_registeredControlsThatRequirePostBack=new TList; + $this->_registeredControlsThatRequirePostBack->add($control->getUniqueID()); + } + + final public function registerRequiresRaiseEvent($control) + { + $this->_registeredControlThatRequireRaiseEvent=$control; + } + + public function getApplication() + { + return $this->_application; + } + + public function loadStateField() + { + return base64_decode($this->_postData->itemAt('__STATE')); + } + + public function saveStateField($state) + { + $this->getClientScript()->registerHiddenField('__STATE',base64_encode($state)); + } + + protected function determinePostBackMode() + { + /* + $application=$this->getApplication(); + if($application->getPreventPostBack()) + return null; + */ + $postData=new TMap($this->_application->getRequest()->getItems()); + if($postData->itemAt('__STATE')!==null || $postData->itemAt('__EVENTTARGET')!==null) + return $postData; + else + return null; + } + + final public function getIsPostBack() + { + if($this->_postData) + { + if($this->_isCrossPagePostBack) + return true; + if($this->_previousPagePath!=='') + return false; + return !$this->_pageStateChanged; + } + else + return false; + } + + protected function getPageStatePersister() + { + require_once(PRADO_DIR.'/Web/UI/THiddenFieldPageStatePersister.php'); + return new THiddenFieldPageStatePersister($this); + } + + protected function loadPageState() + { + $persister=$this->getPageStatePersister(); + $state=$persister->load(); + $this->loadStateRecursive($state,$this->getEnableViewState()); + } + + protected function savePageState() + { + $state=&$this->saveStateRecursive($this->getEnableViewState()); + $persister=$this->getPageStatePersister(); + $persister->save($state); + } + + protected function processPostData($postData,$beforeLoad) + { + $eventTarget=$postData->itemAt('__EVENTTARGET'); + foreach($postData as $key=>$value) + { + if(in_array($key,self::$_systemPostFields)) + continue; + else if($control=$this->findControl($key)) + { + if($control instanceof IPostBackDataHandler) + { + if($control->loadPostData($key,$this->_postData)) + $this->_changedPostDataConsumers[]=$control; + unset($this->_controlsRequiringPostBack[$key]); + } + else + { + if(empty($eventTarget)) + { + if($control instanceof IPostBackEventHandler) + $this->registerRequiresRaiseEvent($control); + } + else + unset($this->_controlsRequiringPostBack[$key]); + } + } + else if($beforeLoad) + $this->_restPostData->add($key,$value); + } + $list=new TMap; + foreach($this->_controlsRequiringPostBack as $key=>$value) + { + if($control=$this->findControl($key)) + { + if($control instanceof IPostBackDataHandler) + { + if($control->loadPostData($key,$this->_postData)) + $this->_changedPostDataConsumers->add($control); + } + else + throw new THttpException('postback_control_not_found',$key); + } + else if($beforeLoad) + $list->add($key,null); + } + $this->_controlsRequiringPostBack=$list; + } + + final public function getAutoPostBackControl() + { + return $this->_autoPostBackControl; + } + + final public function setAutoPostBackControl($control) + { + $this->_autoPostBackControl=$control; + } + + private function raiseChangedEvents() + { + foreach($this->_changedPostDataConsumers as $control) + $control->raisePostDataChangedEvent(); + } + + private function raisePostBackEvent($postData) + { + if($this->_registeredControlThatRequireRaiseEvent) + { + $this->_registeredControlThatRequireRaiseEvent->raisePostBackEvent(null); + } + else + { + $eventTarget=$postData->itemAt('__EVENTTARGET'); + if(!empty($eventTarget) || $this->getAutoPostBackControl()) + { + if(!empty($eventTarget)) + $control=$this->findControl($eventTarget); + else + $control=null; + if($control instanceof IPostBackEventHandler) + $control->raisePostBackEvent($postData->itemAt('__EVENTPARAM')); + } + else + $this->validate(); + } + } + + public function run($writer) + { + $this->_postData=$this->determinePostBackMode(); + $this->_restPostData=new TMap; + + $this->onPreInit(null); + $this->initializeThemes(); + $this->_preInitWorkComplete=true; + + $this->initRecursive(null); + $this->onInitComplete(null); + + if($this->getIsPostBack()) + { + $this->loadPageState(); + $this->processPostData($this->_postData,true); + } + + $this->onPreLoad(null); + $this->loadRecursive(null); + if($this->getIsPostBack()) + { + $this->processPostData($this->_restPostData,false); + $this->raiseChangedEvents(); + $this->raisePostBackEvent($this->_postData); + } + $this->onLoadComplete(null); + + $this->preRenderRecursive(); + $this->onPreRenderComplete(null); + + $this->savePageState(); + $this->onSaveStateComplete(null); + + $this->renderControl($writer); + $this->unloadRecursive(); + } + + public function getTheme() + { + return $this->_themeName; + } + + public function setTheme($value) + { + $this->_themeName=$value; + } + + public function getStyleSheetTheme() + { + return $this->_styleSheetName; + } + + public function setStyleSheetTheme($value) + { + $this->_styleSheetName=$value; + } + + public function getContainsTheme() + { + return $this->_theme!==null; + } +} + +?> \ No newline at end of file diff --git a/framework/Web/UI/TPageStatePersister.php b/framework/Web/UI/TPageStatePersister.php new file mode 100644 index 00000000..6ec9527b --- /dev/null +++ b/framework/Web/UI/TPageStatePersister.php @@ -0,0 +1,22 @@ +_page=$page; + } + + public function getPage() + { + return $this->_page; + } + + abstract public function load(); + + abstract public function save($state); +} + +?> \ No newline at end of file diff --git a/framework/Web/UI/TPostBackOptions.php b/framework/Web/UI/TPostBackOptions.php new file mode 100644 index 00000000..ee615d0b --- /dev/null +++ b/framework/Web/UI/TPostBackOptions.php @@ -0,0 +1,36 @@ +ActionUrl=$actionUrl; + $this->AutoPostBack=$autoPostBack; + $this->ClientSubmit=$clientSubmit; + $this->PerformValidation=$performValidation; + $this->RequiresJavaScriptProtocol=$requiresJavaScriptProtocol; + $this->TargetControl=$targetControl; + $this->TrackFocus=$trackFocus; + $this->ValidationGroup=$validationGroup; + } +} + +?> \ No newline at end of file diff --git a/framework/Web/UI/TTemplate.php b/framework/Web/UI/TTemplate.php new file mode 100644 index 00000000..df9bf813 --- /dev/null +++ b/framework/Web/UI/TTemplate.php @@ -0,0 +1,494 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Web.UI + */ + +/** + * TTemplate implements PRADO template parsing logic. + * A TTemplate object represents a parsed PRADO control template. + * It can instantiate the template as child controls of a specified control. + * The template format is like HTML, with the following special tags introduced, + * - component tags: a component tag represents the configuration of a component. + * The tag name is in the format of com:ComponentType, where ComponentType is the component + * class name. Component tags must be well-formed. Attributes of the component tag + * are treated as either property initial values, event handler attachment, or regular + * tag attributes. + * - property tags: property tags are used to set large block of attribute values. + * The property tag name is in the format of prop:AttributeName, where AttributeName + * can be a property name, an event name or a regular tag attribute name. + * - directive: directive specifies the property values for the template owner. + * It is in the format of <% properyt name-value pairs %> + * - expressions: expressions are shorthand of {@link TExpression} and {@link TStatements} + * controls. They are in the formate of <= PHP expression > and < PHP statements > + * - comments: There are two kinds of comments, regular HTML comments and special template comments. + * The former is in the format of <!-- comments -->, which will be treated as text strings. + * The latter is in the format of <%* comments %>, which will be stripped out. + * + * Tags are not required to be well-formed. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Web.UI + * @since 3.0 + */ +class TTemplate extends TComponent implements ITemplate +{ + /** + * '' - template comments + * '' - HTML comments + * '<\/?com:([\w\.]+)((?:\s*[\w\.]+=\'.*?\'|\s*[\w\.]+=".*?"|\s*[\w\.]+=<%.*?%>)*)\s*\/?>' - component tags + * '<\/?prop:([\w\.]+)\s*>' - property tags + * '<%@\s*(\w+)((?:\s*[\w\.]+=\'.*?\'|\s*[\w\.]+=".*?")*)\s*%>' - directives + * '<%=?(.*?)%>' - expressions + */ + const REGEX_RULES='/||<\/?com:([\w\.]+)((?:\s*[\w\.]+=\'.*?\'|\s*[\w\.]+=".*?"|\s*[\w\.]+=<%.*?%>)*)\s*\/?>|<\/?prop:([\w\.]+)\s*>|<%@\s*((?:\s*[\w\.]+=\'.*?\'|\s*[\w\.]+=".*?")*)\s*%>|<%=?(.*?)%>/msS'; + + /** + * @var array list of component tags and strings + */ + private $_tpl=array(); + /** + * @var array list of directive settings + */ + private $_directive=array(); + + /** + * Constructor. + * The template will be parsed after construction. + * @param string the template string + */ + public function __construct($template) + { + $this->parse($template); + } + + /** + * @return array name-value pairs declared in the directive + */ + public function getDirective() + { + return $this->_directive; + } + + /** + * Instantiates the template. + * Content in the template will be instantiated as components and text strings + * and passed to the specified parent control. + * @param TControl the parent control + * @throws TTemplateRuntimeException if an error is encountered during the instantiation. + */ + public function instantiateIn($tplControl) + { + $page=$tplControl->getPage(); + $controls=array(); + foreach($this->_tpl as $key=>$object) + { + if(isset($object[2])) // component + { + if(strpos($object[1],'.')===false) + $component=new $object[1]; + else + $component=Prado::createComponent($object[1]); + if($component instanceof TControl) + { + $controls[$key]=$component; + $component->setTemplateControl($tplControl); + if(isset($object[2]['id'])) + $tplControl->registerObject($object[2]['id'],$component); + if(isset($object[2]['skinid'])) + { + $component->setSkinID($object[2]['skinid']); + unset($object[2]['skinid']); + } + $component->applyStyleSheetSkin($page); + // apply attributes + foreach($object[2] as $name=>$value) + { + if($component->hasEvent($name)) // is an event + { + if(is_string($value)) + { + if(strpos($value,'.')===false) + $component->attachEventHandler($name,array($component,'TemplateControl.'.$value)); + else + $component->attachEventHandler($name,array($component,$value)); + } + else + throw new TTemplateRuntimeException('template_event_invalid',$name); + } + else if(strpos($name,'.')===false) // is simple property or custom attribute + { + if($component->hasProperty($name)) + { + if($component->canSetProperty($name)) + { + $setter='set'.$name; + if(is_string($value)) + $component->$setter($value); + else if($value[0]===0) + $component->bindProperty($name,$value[1]); + else + $component->$setter($component->evaluateExpression($value[1])); + } + else + throw new TTemplateRuntimeException('property_read_only',get_class($component).'.'.$name); + } + else if($component->getAllowCustomAttributes()) + $component->getAttributes()->add($name,$value); + else + throw new TTemplateRuntimeException('property_not_defined',get_class($component).'.'.$name); + } + else // complex property + { + if(is_string($value)) + $component->setPropertyByPath($name,$value); + else if($value[0]===0) + $component->bindProperty($name,$value[1]); + else + $component->setPropertyByPath($component->evaluateExpression($value[1])); + } + } + $parent=isset($controls[$object[0]])?$controls[$object[0]]:$tplControl; + $component->createdOnTemplate($parent); + } + else if($component instanceof TComponent) + { + if(isset($object[2]['id'])) + { + $tplControl->registerObject($object[2]['id'],$component); + if(!$component->hasProperty('id')) + unset($object[2]['id']); + } + foreach($object[2] as $name=>$value) + { + if($component->hasProperty($name)) + { + if($component->canSetProperty($name)) + { + $setter='set'.$name; + if(is_string($value)) + $component->$setter($value); + else if($value[0]===1) + $component->$setter($component->evaluateExpression($value[1])); + else + throw new TTemplateRuntimeException('template_component_property_unbindable',get_class($component),$name); + } + else + throw new TTemplateRuntimeException('property_read_only',get_class($component).'.'.$name); + } + else + throw new TTemplateRuntimeException('property_not_defined',get_class($component).'.'.$name); + } + $parent=isset($controls[$object[0]])?$controls[$object[0]]:$tplControl; + $parent->addParsedObject($component); + } + else + throw new TTemplateRuntimeException('must_be_component',$object[1]); + } + else // string + { + if(isset($controls[$object[0]])) + $controls[$object[0]]->addParsedObject($object[1]); + else + $tplControl->addParsedObject($object[1]); + } + } + } + + /** + * NOTE, this method is currently not used!!! + * Processes an attribute set in a component tag. + * The attribute will be checked to see if it represents a property or an event. + * If so, the value will be set to the property, or the value will be treated + * as an event handler and attached to the event. + * Otherwise, it will be added as regualr attribute if the control allows so. + * @param TComponent the component represented by the tag + * @param string attribute name + * @param string attribute value + * @throws TTemplateRuntimeException + */ + public static function applyAttribute($component,$name,$value) + { + $target=$component; + if(strpos($name,'.')===false) + $property=$name; + else + { + $names=explode('.',$name); + $property=array_pop($names); + foreach($names as $p) + { + if(($target instanceof TComponent) && $target->canGetProperty($p)) + { + $getter='get'.$p; + $target=$target->$getter(); + } + else + throw new TTemplateRuntimeException('invalid_subproperty',$name); + } + } + if($target instanceof TControl) + { + if($target->hasProperty($property)) + { + $setter='set'.$property; + if(is_string($value)) + $target->$setter($value); + else if($value[0]===0) + $target->bindProperty($property,$value[1]); + else + { + $target->$setter($target->evaluateExpression($value[1])); + } + } + else if($target->hasEvent($property)) + { + if(strpos($value,'.')===false) + $target->attachEventHandler($property,'TemplateControl.'.$value); + else + $target->attachEventHandler($property,$value); + } + else if($target->getAllowCustomAttributes()) + $target->getAttributes()->add($property,$value); + else + throw new TTemplateRuntimeException('property_not_defined',get_class($target).'.'.$property); + } + else if($target instanceof TComponent) + { + $setter='set'.$property; + $target->$setter($value); + } + else + throw new TTemplateRuntimeException('must_extend_TComponent',get_class($target)); + } + + /** + * Parses a template string. + * + * This template parser recognizes five types of data: + * regular string, well-formed component tags, well-formed property tags, directives, and expressions. + * + * The parsing result is returned as an array. Each array element can be of three types: + * - a string, 0: container index; 1: string content; + * - a component tag, 0: container index; 1: component type; 2: attributes (name=>value pairs) + * If a directive is found in the template, it will be parsed and can be + * retrieved via {@link getDirective}, which returns an array consisting of + * name-value pairs in the directive. + * + * Note, attribute names are treated as case-insensitive and will be turned into lower cases. + * Component and directive types are case-sensitive. + * Container index is the index to the array element that stores the container object. + * If an object has no container, its container index is -1. + * + * @param string the template string + * @return array the parsed result + * @throws TTemplateParsingException if a parsing error is encountered + */ + protected function &parse($input) + { + $tpl=&$this->_tpl; + $n=preg_match_all(self::REGEX_RULES,$input,$matches,PREG_SET_ORDER|PREG_OFFSET_CAPTURE); + $expectPropEnd=false; + $textStart=0; + $stack=array(); + $container=-1; + $c=0; + for($i=0;$i<$n;++$i) + { + $match=&$matches[$i]; + $str=$match[0][0]; + $matchStart=$match[0][1]; + $matchEnd=$matchStart+strlen($str)-1; + if(strpos($str,'$textStart) + $tpl[$c++]=array($container,substr($input,$textStart,$matchStart-$textStart)); + $textStart=$matchEnd+1; + $type=$match[1][0]; + $attributes=$this->parseAttributes($match[2][0]); + $tpl[$c++]=array($container,$type,$attributes); + if($str[strlen($str)-2]!=='/') // open tag + { + array_push($stack,$type); + $container=$c-1; + } + } + else if(strpos($str,'$textStart) + $tpl[$c++]=array($container,substr($input,$textStart,$matchStart-$textStart)); + $textStart=$matchEnd+1; + $type=$match[1][0]; + + if(empty($stack)) + { + $line=count(explode("\n",substr($input,0,$matchEnd+1))); + throw new TTemplateParsingException('unexpected_closing_tag',$line,""); + } + + $name=array_pop($stack); + if($name!==$type) + { + if($name[0]==='@') + $tag=''; + else + $tag=''; + $line=count(explode("\n",substr($input,0,$matchEnd+1))); + throw new TTemplateParsingException('expecting_closing_tag',$line,$tag); + } + $container=$tpl[$container][0]; + } + else if(strpos($str,'<%@')===0) // directive + { + if($expectPropEnd) + continue; + if($matchStart>$textStart) + $tpl[$c++]=array($container,substr($input,$textStart,$matchStart-$textStart)); + $textStart=$matchEnd+1; + if(isset($tpl[0])) + { + $line=count(explode("\n",substr($input,0,$matchEnd+1))); + throw new TTemplateParsingException('nonunique_template_directive',$line); + } + $this->_directive=$this->parseAttributes($match[4][0]); + } + else if(strpos($str,'<%')===0) // expression + { + if($expectPropEnd) + continue; + if($matchStart>$textStart) + $tpl[$c++]=array($container,substr($input,$textStart,$matchStart-$textStart)); + $textStart=$matchEnd+1; + if($str[2]==='=') + $tpl[$c++]=array($container,'TExpression',array('Expression'=>$match[5][0])); + else + $tpl[$c++]=array($container,'TStatements',array('Statements'=>$match[5][0])); + } + else if(strpos($str,'$textStart) + $tpl[$c++]=array($container,substr($input,$textStart,$matchStart-$textStart)); + $textStart=$matchEnd+1; + $expectPropEnd=true; + } + } + else if(strpos($str,'"); + } + $name=array_pop($stack); + if($name!=='@'.$prop) + { + if($name[0]==='@') + $tag=''; + else + $tag=''; + $line=count(explode("\n",substr($input,0,$matchEnd+1))); + throw new TTemplateParsingException('expecting_closing_tag',$line,$tag); + } + if(($last=count($stack))<1 || $stack[$last-1][0]!=='@') + { + if($matchStart>$textStart && $container>=0) + { + $value=substr($input,$textStart,$matchStart-$textStart); + if(preg_match('/^<%.*?%>$/msS',$value)) + { + if($value[2]==='#') // databind + $tpl[$container][2][$prop]=array(0,substr($value,3,strlen($value)-5)); + else if($value[2]==='=') // a dynamic initialization + $tpl[$container][2][$prop]=array(1,substr($value,3,strlen($value)-5)); + else + $tpl[$container][2][$prop]=$value; + } + else + $tpl[$container][2][$prop]=$value; + $textStart=$matchEnd+1; + } + $expectPropEnd=false; + } + } + else if(strpos($str,' + + + + + + diff --git a/tests/UnitTests/framework/Data/xml/data1.xml.out b/tests/UnitTests/framework/Data/xml/data1.xml.out new file mode 100644 index 00000000..de491e4c --- /dev/null +++ b/tests/UnitTests/framework/Data/xml/data1.xml.out @@ -0,0 +1,41 @@ + + + My lists + + My books + + + + + + Title + Author + Language + ISBN + + + + + The Grapes of Wrath + John Steinbeck + en + 0140186409 + + + The Pearl + John Steinbeck + en + 014017737X + + + Samarcande + Amine Maalouf + fr + 2253051209 + + + + + + + \ No newline at end of file diff --git a/tests/UnitTests/framework/Data/xml/data2.xml b/tests/UnitTests/framework/Data/xml/data2.xml new file mode 100644 index 00000000..9231ef7b --- /dev/null +++ b/tests/UnitTests/framework/Data/xml/data2.xml @@ -0,0 +1,41 @@ + + + + 我的书 + + + + + + 标题 + 作者 + 语言 + ISBN + + + + + The Grapes of Wrath + John Steinbeck + en + 0140186409 + + + The Pearl + John Steinbeck + en + 014017737X + + + Samarcande + Amine Maalouf + fr + 2253051209 + + + + + + + + diff --git a/tests/UnitTests/framework/Data/xml/data2.xml.out b/tests/UnitTests/framework/Data/xml/data2.xml.out new file mode 100644 index 00000000..d688884c --- /dev/null +++ b/tests/UnitTests/framework/Data/xml/data2.xml.out @@ -0,0 +1,40 @@ + + + + 我的书 + + + + + + 标题 + 作者 + 语言 + ISBN + + + + + The Grapes of Wrath + John Steinbeck + en + 0140186409 + + + The Pearl + John Steinbeck + en + 014017737X + + + Samarcande + Amine Maalouf + fr + 2253051209 + + + + + + + \ No newline at end of file diff --git a/tests/UnitTests/framework/Data/xml/data3.xml b/tests/UnitTests/framework/Data/xml/data3.xml new file mode 100644 index 00000000..9e66a7f0 --- /dev/null +++ b/tests/UnitTests/framework/Data/xml/data3.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + qiang.xue@gmail.com + + + diff --git a/tests/UnitTests/framework/Data/xml/data3.xml.out b/tests/UnitTests/framework/Data/xml/data3.xml.out new file mode 100644 index 00000000..a87d0558 --- /dev/null +++ b/tests/UnitTests/framework/Data/xml/data3.xml.out @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + qiang.xue@gmail.com + + + \ No newline at end of file diff --git a/tests/UnitTests/framework/TestSystem/protected/application.xml b/tests/UnitTests/framework/TestSystem/protected/application.xml new file mode 100644 index 00000000..0ee5f172 --- /dev/null +++ b/tests/UnitTests/framework/TestSystem/protected/application.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + value 1 + + + + + \ No newline at end of file diff --git a/tests/UnitTests/framework/TestSystem/protected/data/test.db b/tests/UnitTests/framework/TestSystem/protected/data/test.db new file mode 100644 index 00000000..9bc20c39 Binary files /dev/null and b/tests/UnitTests/framework/TestSystem/protected/data/test.db differ diff --git a/tests/UnitTests/framework/TestSystem/protected/pages/config.xml b/tests/UnitTests/framework/TestSystem/protected/pages/config.xml new file mode 100644 index 00000000..6a49df82 --- /dev/null +++ b/tests/UnitTests/framework/TestSystem/protected/pages/config.xml @@ -0,0 +1,12 @@ + + + + + + + value 1 + + + + + \ No newline at end of file diff --git a/tests/UnitTests/framework/Web/UI/utControl.php b/tests/UnitTests/framework/Web/UI/utControl.php new file mode 100644 index 00000000..8498f7c0 --- /dev/null +++ b/tests/UnitTests/framework/Web/UI/utControl.php @@ -0,0 +1,420 @@ +setPage($this); + $this->_context=$context; + } + + public function getContext() + { + return $this->_context; + } + + public function clicked($sender,$param) + { + $this->eventRaised=true; + } + + public function getContainsTheme() + { + return false; + } + + public function runTo($lifecycle) + { + switch($lifecycle) + { + case 'init': + $this->initRecursive(null); + break; + case 'load': + $this->initRecursive(null); + $this->loadRecursive(); + break; + case 'prerender': + $this->initRecursive(null); + $this->loadRecursive(); + $this->preRenderRecursive(); + break; + } + } +} + +class WebControl extends TControl +{ + public function getText() + { + return $this->getViewState('Text',''); + } + + public function setText($value) + { + return $this->setViewState('Text',$value,''); + } + + public function getData() + { + return $this->getControlState('Data',''); + } + + public function setData($value) + { + $this->setControlState('Data',$value,''); + } + + public function onClick($param) + { + $this->raiseEvent('OnClick',$this,$param); + } +} + +class testControl extends UnitTestCase +{ + private $context; + private $button1; + private $button2; + private $page; + private $form; + private $panel; + + public function setUp() + { + // we mock up a page consisting of a form which encloses a panel. + // in the panel there are two buttons, button1 and button2 + // The panel is a naming container + $this->context=new TContext; + $this->page=new PageControl($this->context); + $this->form=new WebControl; + $this->panel=new ContainerControl; + $this->button1=new WebControl; + $this->button2=new WebControl; + $this->form->setTemplateControl($this->page); + $this->panel->setTemplateControl($this->page); + $this->button1->setTemplateControl($this->page); + $this->button2->setTemplateControl($this->page); + $this->page->getControls()->add($this->form); + $this->form->getControls()->add($this->panel); + $this->panel->getControls()->add($this->button1); + $this->panel->getControls()->add($this->button2); + $this->button1->setID('button1'); + $this->page->declareObject('button1',$this->button1); + } + + public function tearDown() + { + $this->page=null; + $this->form=null; + $this->panel=null; + $this->button1=null; + $this->button2=null; + $this->context=null; + TContext::$_instance=null; + } + + public function testOverload() + { + $this->assertEqual($this->page->button1,$this->button1); + try + { + $button=$this->page->button2; + $this->fail('non exception raised when accessing non-declared control'); + } + catch(TInvalidOperationException $e) + { + $this->pass(); + } + } + + public function testParent() + { + $this->assertEqual(null,$this->page->getParent()); + $this->assertEqual($this->page,$this->form->getParent()); + } + + public function testNamingContainer() + { + $this->assertEqual(null,$this->page->getNamingContainer()); + $this->assertEqual($this->page,$this->panel->getNamingContainer()); + $this->assertEqual($this->panel,$this->button1->getNamingContainer()); + } + + public function testPage() + { + $this->assertEqual($this->page,$this->page->getPage()); + $this->assertEqual($this->page,$this->panel->getPage()); + $this->assertEqual($this->page,$this->button1->getPage()); + } + + public function testTemplateControl() + { + $this->assertEqual(null,$this->page->getTemplateControl()); + $this->assertEqual($this->page,$this->panel->getTemplateControl()); + $this->assertEqual($this->page,$this->button1->getTemplateControl()); + } + + public function testContext() + { + $this->assertEqual($this->context,$this->button1->getContext()); + } + + public function testSkinID() + { + $this->assertEqual('',$this->button1->getSkinID()); + $this->button1->setSkinID('buttonSkin'); + $this->assertEqual('buttonSkin',$this->button1->getSkinID()); + $this->page->runTo('init'); + try + { + $this->button1->setSkinID('buttonSkin2'); + $this->fail('no exception raised when SkinID is set after PreInit'); + } + catch(TInvalidOperationException $e) + { + $this->pass(); + } + } + + public function testID() + { + $this->assertEqual('button1',$this->button1->getID()); + $this->assertEqual('',$this->button2->getID()); + $this->assertEqual('ctl1',$this->button2->getID(false)); + $this->button2->setID('button2'); + $this->assertEqual('button2',$this->button2->getID()); + try + { + $this->button2->setID('123'); + $this->fail('exception not raised when control is set with an invalid ID'); + } + catch(TInvalidDataValueException $e) + { + $this->pass(); + } + } + + public function testUniqueID() + { + $sep=TControl::ID_SEPARATOR; + $this->assertEqual('ctl0',$this->form->getUniqueID()); + $this->assertEqual('ctl1',$this->panel->getUniqueID()); + $this->assertEqual('ctl1'.$sep.'button1',$this->button1->getUniqueID()); + $this->assertEqual('ctl1'.$sep.'ctl1',$this->button2->getUniqueID()); + $this->button2->setID('button2'); + $this->assertEqual('ctl1'.$sep.'button2',$this->button2->getUniqueID()); + $this->panel->setID('panel'); + $this->assertEqual('panel'.$sep.'button2',$this->button2->getUniqueID()); + } + + public function testEnableTheming() + { + $this->assertEqual(true,$this->button1->getEnableTheming()); + $this->page->setEnableTheming(false); + $this->assertEqual(false,$this->button1->getEnableTheming()); + $this->page->setEnableTheming(true); + $this->assertEqual(true,$this->button1->getEnableTheming()); + $this->button1->setEnableTheming(false); + $this->assertEqual(false,$this->button1->getEnableTheming()); + + $this->page->runTo('init'); + try + { + $this->button1->setEnableTheming(true); + $this->fail('no exception raised when EnableTheming is set after PreInit'); + } + catch(TInvalidOperationException $e) + { + $this->pass(); + } + } + + public function testHasControls() + { + $this->assertEqual(true,$this->page->getHasControls()); + $this->assertEqual(false,$this->button1->getHasControls()); + } + + public function testControls() + { + $this->assertEqual(1,$this->page->getControls()->getCount()); + $control=new WebControl; + $this->panel->getControls()->add($control); + $this->assertEqual(3,$this->panel->getControls()->getCount()); + $this->panel->getControls()->remove($this->button1); + $this->assertEqual(2,$this->panel->getControls()->getCount()); + } + + public function testVisible() + { + $this->assertEqual(true,$this->button1->getVisible()); + $this->page->setVisible(false); + $this->assertEqual(false,$this->button1->getVisible()); + $this->page->setVisible(true); + $this->assertEqual(true,$this->button1->getVisible()); + $this->button1->setVisible(false); + $this->assertEqual(false,$this->button1->getVisible()); + } + + public function testEnabled() + { + $this->assertEqual(true,$this->button1->getEnabled()); + $this->page->setEnabled(false); + $this->assertEqual(true,$this->button1->getEnabled()); + $this->assertEqual(false,$this->button1->getEnabled(true)); + $this->page->setEnabled(true); + $this->assertEqual(true,$this->button1->getEnabled(true)); + $this->button1->setEnabled(false); + $this->assertEqual(false,$this->button1->getEnabled(true)); + $this->assertEqual(false,$this->button1->getEnabled()); + } + + public function testHasAttributes() + { + $this->assertEqual(false,$this->button1->getHasAttributes()); + $this->button1->getAttributes()->add('name','value'); + $this->assertEqual(true,$this->button1->getHasAttributes()); + $this->button1->getAttributes()->clear(); + $this->assertEqual(false,$this->button1->getHasAttributes()); + } + + public function testAttributes() + { + $this->assertEqual(0,$this->button1->getAttributes()->getCount()); + $this->button1->getAttributes()->add('name1','value1'); + $this->button1->getAttributes()->add('name2','value2'); + $this->assertEqual(2,$this->button1->getAttributes()->getCount()); + $this->button1->getAttributes()->remove('name1'); + $this->assertEqual(1,$this->button1->getAttributes()->getCount()); + } + + public function testEnableViewState() + { + $this->assertEqual(true,$this->button1->getEnableViewState()); + $this->button1->setEnableViewState(false); + $this->assertEqual(false,$this->button1->getEnableViewState()); + + } + + public function testViewState() + { + $this->assertEqual('',$this->button1->getText()); + $this->button1->setText('abc'); + $this->assertEqual('abc',$this->button1->getText()); + } + + public function testControlState() + { + $this->assertEqual('',$this->button1->getData()); + $this->button1->setData('abc'); + $this->assertEqual('abc',$this->button1->getData()); + } + + public function testEventScheme() + { + $this->assertEqual(true,$this->button1->hasEvent('OnClick')); + $this->assertEqual(false,$this->button1->hasEvent('Click')); + $this->button1->attachEventHandler('OnClick','Page.clicked'); + $this->assertEqual(false,$this->page->eventRaised); + $this->button1->raiseEvent('OnClick',$this,null); + $this->assertEqual(true,$this->page->eventRaised); + $this->button1->getEventHandlers('OnClick')->clear(); + try + { + $this->button1->attachEventHandler('Click','clicked'); + $this->fail('no exception raised when undefined event is raised'); + } + catch(TInvalidOperationException $e) + { + $this->pass(); + } + $this->assertEqual(0,$this->button1->getEventHandlers('OnClick')->getCount()); + $this->button1->attachEventHandler('OnClick','Pages.clicked'); + try + { + $this->button1->raiseEvent('OnClick',$this,null); + $this->fail('no exception raised when undefined event handler is invoked'); + } + catch(TInvalidOperationException $e) + { + $this->pass(); + } + } + + public function testDataBindingScheme() + { + $this->button1->bindProperty('Text','"abc"."def"'); + $this->button1->dataBind(); + $this->assertEqual('abcdef',$this->button1->getText()); + $this->button2->bindProperty('Text','"abc"."def"'); + $this->button2->unbindProperty('Text'); + $this->button2->dataBind(); + $this->assertEqual('',$this->button2->getText()); + $this->button1->bindProperty('Texts','"abc"."def"'); + try + { + $this->button1->dataBind(); + $this->fail('no exception raised for invalid databinding'); + } + catch(TInvalidOperationException $e) + { + $this->pass(); + } + } + + public function testFindControl() + { + $this->assertEqual($this->button1,$this->panel->findControl('button1')); + $this->assertEqual(null,$this->panel->findControl('button2')); + $this->assertEqual($this->button1,$this->page->findControl($this->panel->getID(false).TControl::ID_SEPARATOR.'button1')); + $this->button1->setID('button3'); + $this->assertEqual($this->button1,$this->panel->findControl('button3')); + } + + public function testAddRemoveControl() + { + + } +} + + +if(!defined('RUN_ALL_TESTS')) +{ + $className=basename(__FILE__,'.php'); + $test = new $className; + $test->run(new HtmlReporter()); +} + +?> \ No newline at end of file diff --git a/tests/UnitTests/framework/common.php b/tests/UnitTests/framework/common.php new file mode 100644 index 00000000..dc268e28 --- /dev/null +++ b/tests/UnitTests/framework/common.php @@ -0,0 +1,26 @@ + \ No newline at end of file diff --git a/tests/UnitTests/framework/index.php b/tests/UnitTests/framework/index.php new file mode 100644 index 00000000..802e979e --- /dev/null +++ b/tests/UnitTests/framework/index.php @@ -0,0 +1,100 @@ +url="$rootUri?target=".strtr(substr($path,strlen($rootPath)+1),"\\",'/'); + $this->name=basename($path); + $dir=opendir($path); + while(($entry=readdir($dir))!==false) + { + $fullpath="$path/$entry"; + if($entry!=='.' && $entry!=='..' && is_dir($fullpath)) + { + $folder=new TestFolder($fullpath,$rootPath,$rootUri); + if(!empty($folder->subFolders) || !empty($folder->testFiles)) + $this->subFolders[]=$folder; + } + else if(is_file($fullpath) && strncmp($entry,'ut',2)===0) + { + $this->testFiles[$entry]="$rootUri?target=".strtr(substr($fullpath,strlen($rootPath)+1),"\\",'/'); + } + } + closedir($dir); + } + + public function getHtml($level=0) + { + $str=str_repeat(' ',$level*4)."[ url}\">{$this->name} ]
\n"; + foreach($this->subFolders as $folder) + $str.=$folder->getHtml($level+1); + foreach($this->testFiles as $name=>$url) + $str.=str_repeat(' ',($level+1)*4)."$name
\n"; + return $str; + } +} + + +function addTests($test,$path,$recursive) +{ + $dir=opendir($path); + while(($entry=readdir($dir))!==false) + { + if(is_file($path.'/'.$entry) && strncmp($entry,'ut',2)===0) + $test->addTestFile($path.'/'.$entry); + else if($entry!=='.' && $entry!=='..' && is_dir($path.'/'.$entry) && $recursive) + addTests($test,$path.'/'.$entry,$recursive); + } + closedir($dir); +} + + +$rootPath=realpath(dirname(__FILE__)); +$rootUri=dirname($_SERVER['PHP_SELF']); + +if(isset($_GET['target'])) +{ + $target=$_GET['target']; + $recursive=true; + $fullpath=realpath("$rootPath/$target"); + if($fullpath===false || strpos($fullpath,$rootPath)!==0) + die('invalid test target'); + + require_once($rootPath.'/common.php'); + + if(is_dir($fullpath)) + { + $test=new GroupTest(basename($rootPath)."/$target"); + addTests($test,$fullpath,$recursive); + $test->run(new HtmlReporterWithCoverage(__FILE__,$rootPath)); + } + else + { + $testClass=basename($fullpath,'.php'); + require_once($fullpath); + $test=new $testClass(basename($rootPath)."/$target"); + $test->run(new HtmlReporter()); + } +} +else +{ + echo " + +utList + + + +

Prado Framework Unit Tests

+"; + $root=new TestFolder($rootPath,$rootPath,$rootUri); + echo $root->getHtml(); + echo "\n"; +} + +?> \ No newline at end of file diff --git a/tests/UnitTests/framework/utApplication.php b/tests/UnitTests/framework/utApplication.php new file mode 100644 index 00000000..603f9fc3 --- /dev/null +++ b/tests/UnitTests/framework/utApplication.php @@ -0,0 +1,25 @@ +pass(); + } + chdir($dir); + } +} + +?> \ No newline at end of file diff --git a/tests/UnitTests/framework/utComponent.php b/tests/UnitTests/framework/utComponent.php new file mode 100644 index 00000000..2683652a --- /dev/null +++ b/tests/UnitTests/framework/utComponent.php @@ -0,0 +1,224 @@ +_text; + } + + public function setText($value) + { + $this->_text=$value; + } + + public function getObject() + { + if(!$this->_object) + { + $this->_object=new NewComponent; + $this->_object->_text='object text'; + } + return $this->_object; + } + + public function onMyEvent($param) + { + $this->raiseEvent('MyEvent',$this,$param); + } + + public function myEventHandler($sender,$param) + { + $this->_eventHandled=true; + } + + public function isEventHandled() + { + return $this->_eventHandled; + } +} + +class utComponent extends UnitTestCase +{ + protected $component; + + public function setUp() + { + $this->component=new NewComponent; + } + + public function tearDown() + { + $this->component=null; + } + + public function testHasProperty() + { + $this->assertTrue($this->component->hasProperty('Text')); + $this->assertTrue($this->component->hasProperty('text')); + $this->assertFalse($this->component->hasProperty('Caption')); + } + + public function testCanGetProperty() + { + $this->assertTrue($this->component->canGetProperty('Text')); + $this->assertTrue($this->component->canGetProperty('text')); + $this->assertFalse($this->component->canGetProperty('Caption')); + } + + public function testCanSetProperty() + { + $this->assertTrue($this->component->canSetProperty('Text')); + $this->assertTrue($this->component->canSetProperty('text')); + $this->assertFalse($this->component->canSetProperty('Caption')); + } + + public function testGetProperty() + { + $this->assertTrue('default'===$this->component->Text); + try + { + $value2=$this->component->Caption; + $this->fail('exception not raised when getting undefined property'); + } + catch(TInvalidOperationException $e) + { + $this->pass(); + } + } + + public function testSetProperty() + { + $value='new value'; + $this->component->Text=$value; + $text=$this->component->Text; + $this->assertTrue($value===$this->component->Text); + try + { + $this->component->NewMember=$value; + $this->fail('exception not raised when setting undefined property'); + } + catch(TInvalidOperationException $e) + { + $this->pass(); + } + } + + public function testGetPropertyByPath() + { + $this->assertTrue('object text'===$this->component->getPropertyByPath('Object.Text')); + } + + public function testSetPropertyByPath() + { + $this->component->setPropertyByPath('Object.Text','new object text'); + $this->assertEqual('new object text',$this->component->getPropertyByPath('Object.Text')); + } + + public function testHasEvent() + { + $this->assertTrue($this->component->hasEvent('MyEvent')); + $this->assertTrue($this->component->hasEvent('myevent')); + $this->assertFalse($this->component->hasEvent('YourEvent')); + } + + public function testHasEventHandler() + { + $this->assertFalse($this->component->hasEventHandler('MyEvent')); + $this->component->attachEventHandler('MyEvent','foo'); + $this->assertTrue($this->component->hasEventHandler('MyEvent')); + } + + public function testGetEventHandlers() + { + $list=$this->component->getEventHandlers('MyEvent'); + $this->assertTrue(($list instanceof TList) && ($list->getCount()===0)); + $this->component->attachEventHandler('MyEvent','foo'); + $this->assertTrue(($list instanceof TList) && ($list->getCount()===1)); + try + { + $list=$this->component->getEventHandlers('YourEvent'); + $this->fail('exception not raised when getting event handlers for undefined event'); + } + catch(TInvalidOperationException $e) + { + $this->pass(); + } + } + + public function testAttachEventHandler() + { + $this->component->attachEventHandler('MyEvent','foo'); + $this->assertTrue($this->component->getEventHandlers('MyEvent')->getCount()===1); + try + { + $this->component->attachEventHandler('YourEvent','foo'); + $this->fail('exception not raised when attaching event handlers for undefined event'); + } + catch(TInvalidOperationException $e) + { + $this->pass(); + } + $this->component->MyEvent[]='foo2'; + $this->assertTrue($this->component->getEventHandlers('MyEvent')->getCount()===2); + $this->component->getEventHandlers('MyEvent')->add('foo3'); + $this->assertTrue($this->component->getEventHandlers('MyEvent')->getCount()===3); + $this->component->MyEvent[0]='foo4'; + $this->assertTrue($this->component->getEventHandlers('MyEvent')->getCount()===3); + $this->component->getEventHandlers('MyEvent')->addAt(0,'foo5'); + $this->assertTrue($this->component->MyEvent->Count===4 && $this->component->MyEvent[0]==='foo5'); + $this->component->MyEvent='foo6'; + $this->assertTrue($this->component->MyEvent->Count===5 && $this->component->MyEvent[4]==='foo6'); + } + + public function testRaiseEvent() + { + $this->component->attachEventHandler('MyEvent',array($this->component,'myEventHandler')); + $this->assertFalse($this->component->isEventHandled()); + $this->component->raiseEvent('MyEvent',$this,null); + $this->assertTrue($this->component->isEventHandled()); + $this->component->attachEventHandler('MyEvent',array($this->component,'Object.myEventHandler')); + $this->assertFalse($this->component->Object->isEventHandled()); + $this->component->raiseEvent('MyEvent',$this,null); + $this->assertTrue($this->component->Object->isEventHandled()); + } + + public function testEvaluateExpression() + { + $expression="1+2"; + $this->assertTrue(3===$this->component->evaluateExpression($expression)); + try + { + $button=$this->component->evaluateExpression('$this->button'); + $this->fail('exception not raised when evaluating an invalid exception'); + } + catch(Exception $e) + { + $this->pass(); + } + } + + public function testEvaluateStatements() + { + $statements='$a="test string"; echo $a;'; + $this->assertEqual('test string',$this->component->evaluateStatements($statements)); + try + { + $statements='$a=new NewComponent; echo $a->button;'; + $button=$this->component->evaluateStatements($statements); + $this->fail('exception not raised when evaluating an invalid statement'); + } + catch(Exception $e) + { + $this->pass(); + } + } +} + +?> \ No newline at end of file diff --git a/tests/UnitTests/framework/utPradoBase.php b/tests/UnitTests/framework/utPradoBase.php new file mode 100644 index 00000000..f7861c57 --- /dev/null +++ b/tests/UnitTests/framework/utPradoBase.php @@ -0,0 +1,111 @@ +data=$data; + } +} + +class utPradoBase extends UnitTestCase +{ + public function testFrameworkPath() + { + $this->assertTrue(FRAMEWORK_DIR===Prado::getFrameworkPath()); + } + + public function testSerialization() + { + $object=new TComponent; + $number=12345.123; + $string='12345\'"'; + $array=array('123'=>123,'abc'=>'def'); + $this->assertFalse($object===Prado::unserialize(Prado::serialize($object))); + $this->assertTrue(Prado::unserialize(Prado::serialize($object)) instanceof TComponent); + $this->assertTrue($number===Prado::unserialize(Prado::serialize($number))); + $this->assertTrue($string===Prado::unserialize(Prado::serialize($string))); + $this->assertTrue($array===Prado::unserialize(Prado::serialize($array))); + + // test complex object reference structure grandparent <-> parent <-> child + $grandp=new testNode('grandp'); + $parent=new testNode('parent'); + $child=new testNode('child'); + $grandp->child=$parent; + $parent->child=$child; + $child->parent=$parent; + $parent->parent=$grandp; + + $newGrandp=Prado::unserialize(Prado::serialize($grandp)); + $this->assertTrue($newGrandp!==$grandp); + $this->assertTrue($newGrandp instanceof testNode); + $this->assertTrue($newGrandp->parent===null); + $this->assertTrue($newGrandp->data==='grandp'); + + $newParent=$newGrandp->child; + $this->assertTrue($newParent!==$parent); + $this->assertTrue($newParent instanceof testNode); + $this->assertTrue($newParent->parent===$newGrandp); + $this->assertTrue($newParent->data==='parent'); + + $newChild=$newParent->child; + $this->assertTrue($newChild!==$child); + $this->assertTrue($newChild instanceof testNode); + $this->assertTrue($newChild->parent===$newParent); + $this->assertTrue($newChild->child===null); + $this->assertTrue($newChild->data==='child'); + } + + public function testCreateComponent() + { + $this->assertTrue(Prado::createComponent('TComponent') instanceof TComponent); + $this->assertTrue(Prado::createComponent('System.TComponent') instanceof TComponent); + try + { + Prado::createComponent('System2.TComponent'); + $this->fail('exception not raised when creating a nonexistent component'); + } + catch(TInvalidDataValueException $e) + { + $this->pass(); + } + } + + public function testNamespace() + { + $this->assertTrue(FRAMEWORK_DIR===Prado::getPathOfAlias('System')); + $this->assertTrue(Prado::getPathOfAlias('System2')===null); + $testSystem=dirname(__FILE__).'/TestSystem'; + + Prado::setPathOfAlias('TestSystem',$testSystem); + $this->assertTrue(realpath($testSystem)===Prado::getPathOfAlias('TestSystem')); + + $this->assertTrue(Prado::getPathOfNamespace('TestSystem.*')===realpath($testSystem)); + $this->assertTrue(Prado::getPathOfNamespace('TestSystem.protected.*')===realpath($testSystem).'/protected'); + $this->assertTrue(Prado::getPathOfNamespace('TestSystem')===null); + + // test repeatedly using the same namespaces + Prado::using('System.*'); + Prado::using('System.*'); + Prado::using('System.TComponent'); + Prado::using('System.TComponent'); + + try + { + Prado::using('System'); + $this->fail('no exception raised when using an invalid namespace for a directory'); + } + catch(TInvalidDataValueException $e) + { + $this->pass(); + } + // TODO: using new namespaces to see if classes can be automatically loaded or found + } +} + +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/CHANGELOG b/tests/UnitTests/simpletest/CHANGELOG new file mode 100644 index 00000000..e416f9a6 --- /dev/null +++ b/tests/UnitTests/simpletest/CHANGELOG @@ -0,0 +1,6 @@ +June 7, 2005, by Qiang Xue (qiang.xue@gmail.com) +------------------------------------------------ +- changed all class memeber declarations from 'var $varname' to 'private $varname'. +- removed all reference usages, including creating new objects, returning and passing objects. +- modified expectation.php line 106 from 'function test($compare, &$nasty=false) {' to 'function test($compare) {'. +- added HtmlReporterWithCoverage.php \ No newline at end of file diff --git a/tests/UnitTests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE b/tests/UnitTests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE new file mode 100644 index 00000000..357ff092 --- /dev/null +++ b/tests/UnitTests/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE @@ -0,0 +1,201 @@ +Simple Test interface changes +============================= +Because the SimpleTest tool set is still evolving it is likely that tests +written with earlier versions will fail with the newest ones. The most +dramatic changes are in the alpha releases. Here is a list of possible +problems... + +No HTML when matching page elements +----------------------------------- +This behaviour has been switched to using plain text as if it +were seen by the user of the browser. This means that HTML tags +are suppressed, entities are converted and whitespace is +normalised. This should make it easier to match items in forms. +Also images are replaced with their "alt" text so that they +can be matched as well. + +No method SimpleRunner::_getTestCase() +-------------------------------------- +This was made public as getTestCase() in 1.0RC2. + +No method restartSession() +-------------------------- +This was renamed to restart() in the WebTestCase, SimpleBrowser +and the underlying SimpleUserAgent in 1.0RC2. Because it was +undocumented anyway, no attempt was made at backward +compatibility. + +My custom test case ignored by tally() +-------------------------------------- +The _assertTrue method has had it's signature changed due to a bug +in the PHP 5.0.1 release. You must now use getTest() from within +that method to get the test case. + +Broken code extending SimpleRunner +---------------------------------- +This was replaced with SimpleScorer so that I could use the runner +name in another class. This happened in RC1 development and there +is no easy backward compatibility fix. The solution is simply to +extend SimpleScorer instead. + +Missing method getBaseCookieValue() +----------------------------------- +This was renamed getCurrentCookieValue() in RC1. + +Missing files from the SimpleTest suite +--------------------------------------- +Versions of SimpleTest prior to Beta6 required a SIMPLE_TEST constant +to point at the SimpleTest folder location before any of the toolset +was loaded. This is no longer documented as it is now unnecessary +for later versions. If you are using an earlier version you may +need this constant. Consult the documentation that was bundled with +the release that you are using or upgrade to Beta6 or later. + +No method SimpleBrowser::getCurrentUrl() +-------------------------------------- +This is replaced with the more versatile showRequest() for +debugging. It only existed in this context for version Beta5. +Later versions will have SimpleBrowser::getHistory() for tracking +paths through pages. It is renamed as getUrl() since 1.0RC1. + +No method Stub::setStubBaseClass() +---------------------------------- +This method has finally been removed in 1.0RC1. Use +SimpleTestOptions::setStubBaseClass() instead. + +No class CommandLineReporter +---------------------------- +This was renamed to TextReporter in Beta3 and the deprecated version +was removed in 1.0RC1. + +No method requireReturn() +------------------------- +This was deprecated in Beta3 and is now removed. + +No method expectCookie() +------------------------ +This method was abruptly removed in Beta4 so as to simplify the internals +until another mechanism can replace it. As a workaround it is necessary +to assert that the cookie has changed by setting it before the page +fetch and then assert the desired value. + +No method clickSubmitByFormId() +------------------------------- +This method had an incorrect name as no button was involved. It was +renamed to submitByFormId() in Beta4 and the old version deprecated. +Now removed. + +No method paintStart() or paintEnd() +------------------------------------ +You should only get this error if you have subclassed the lower level +reporting and test runner machinery. These methods have been broken +down into events for test methods, events for test cases and events +for group tests. The new methods are... + +paintStart() --> paintMethodStart(), paintCaseStart(), paintGroupStart() +paintEnd() --> paintMethodEnd(), paintCaseEnd(), paintGroupEnd() + +This change was made in Beta3, ironically to make it easier to subclass +the inner machinery. Simply duplicating the code you had in the previous +methods should provide a temporary fix. + +No class TestDisplay +-------------------- +This has been folded into SimpleReporter in Beta3 and is now deprecated. +It was removed in RC1. + +No method WebTestCase::fetch() +------------------------------ +This was renamed get() in Alpha8. It is removed in Beta3. + +No method submit() +------------------ +This has been renamed clickSubmit() in Beta1. The old method was +removed in Beta2. + +No method clearHistory() +------------------------ +This method is deprecated in Beta2 and removed in RC1. + +No method getCallCount() +------------------------ +This method has been deprecated since Beta1 and has now been +removed. There are now more ways to set expectations on counts +and so this method should be unecessery. Removed in RC1. + +Cannot find file * +------------------ +The following public name changes have occoured... + +simple_html_test.php --> reporter.php +simple_mock.php --> mock_objects.php +simple_unit.php --> unit_tester.php +simple_web.php --> web_tester.php + +The old names were deprecated in Alpha8 and removed in Beta1. + +No method attachObserver() +-------------------------- +Prior to the Alpha8 release the old internal observer pattern was +gutted and replaced with a visitor. This is to trade flexibility of +test case expansion against the ease of writing user interfaces. + +Code such as... + +$test = &new MyTestCase(); +$test->attachObserver(new TestHtmlDisplay()); +$test->run(); + +...should be rewritten as... + +$test = &new MyTestCase(); +$test->run(new HtmlReporter()); + +If you previously attached multiple observers then the workaround +is to run the tests twice, once with each, until they can be combined. +For one observer the old method is simulated in Alpha 8, but is +removed in Beta1. + +No class TestHtmlDisplay +------------------------ +This class has been renamed to HtmlReporter in Alpha8. It is supported, +but deprecated in Beta1 and removed in Beta2. If you have subclassed +the display for your own design, then you will have to extend this +class (HtmlReporter) instead. + +If you have accessed the event queue by overriding the notify() method +then I am afraid you are in big trouble :(. The reporter is now +carried around the test suite by the runner classes and the methods +called directly. In the unlikely event that this is a problem and +you don't want to upgrade the test tool then simplest is to write your +own runner class and invoke the tests with... + +$test->accept(new MyRunner(new MyReporter())); + +...rather than the run method. This should be easier to extend +anyway and gives much more control. Even this method is overhauled +in Beta3 where the runner class can be set within the test case. Really +the best thing to do is to upgrade to this version as whatever you were +trying to achieve before should now be very much easier. + +Missing set options method +-------------------------- +All test suite options are now in one class called SimpleTestOptions. +This means that options are set differently... + +GroupTest::ignore() --> SimpleTestOptions::ignore() +Mock::setMockBaseClass() --> SimpleTestOptions::setMockBaseClass() + +These changed in Alpha8 and the old versions are now removed in RC1. + +No method setExpected*() +------------------------ +The mock expectations changed their names in Alpha4 and the old names +ceased to be supported in Alpha8. The changes are... + +setExpectedArguments() --> expectArguments() +setExpectedArgumentsSequence() --> expectArgumentsAt() +setExpectedCallCount() --> expectCallCount() +setMaximumCallCount() --> expectMaximumCallCount() + +The parameters remained the same. diff --git a/tests/UnitTests/simpletest/HtmlReporterWithCoverage.php b/tests/UnitTests/simpletest/HtmlReporterWithCoverage.php new file mode 100644 index 00000000..dd900051 --- /dev/null +++ b/tests/UnitTests/simpletest/HtmlReporterWithCoverage.php @@ -0,0 +1,268 @@ +painter = $painter; + $this->base_dir = $base_dir; + } + + function paintHeader($test_name, $charset="UTF-8") + { + $this->sendNoCacheHeaders(); + header('Content-Type: text/html; Charset='.$charset); + print "\n\n$test_name\n"; + print ""; + print "\n"; + print "\n\n"; + print "

$test_name

\n"; + flush(); + + if (extension_loaded('xdebug')) + xdebug_start_code_coverage(XDEBUG_CC_UNUSED); + + } + + /** + * + */ + function _getCss() + { + $contents = parent::_getCss()."\n "; + $contents .= ' + .bar { float: left; display: inline; border: 1px solid #eee; width: 300px; white-space: nowrap;} + .percentage { float: left; background-color: #eef; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; font-size: 0.65em; padding: 5px; margin-right: } + .coverage {margin: 0.4em; } + .coverage a { + padding-left: 0.5em; + } + .coverage:after { + content: "."; + display: block; + height: 0; + clear: both; + visibility: hidden; + } + .coverage {display: inline-block;} + /* Hides from IE-mac \*/ + * html .coverage {height: 1%;} + .coverage {display: block;} + /* End hide from IE-mac */ + '; + Return $contents; + } + + function paintFooter($test_name) + { + if (extension_loaded('xdebug')) + { + $this->coverage = xdebug_get_code_coverage(); + xdebug_stop_code_coverage(); + } + + $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"; + $this->paintCoverage(); + print "\n\n"; + } + + function paintCoverage() + { + $dir = dirname(__FILE__); + if(count($this->coverage) > 0) + print '

Code Coverage

'; + + + ksort($this->coverage); + + $details = array(); + foreach($this->coverage as $file => $coverage) + { + if(is_int(strpos($file, $dir)) == false + && is_int(strpos($file, 'simpletest')) == false + && is_int(strpos($file, $this->base_dir))) + { + $total = HTMLCoverageReport::codelines($file); + $executed = count($coverage); + $percentage = sprintf('%01d',$executed/$total*100); + $width = $percentage * 3; + $filename = str_replace($this->base_dir, '',$file); + $link = $this->constructURL($filename, $coverage); + + $detail['total'] = $total; + $detail['executed'] = $executed; + $detail['width'] = $width; + $detail['filename'] = $filename; + $detail['link'] = $link; + $details[$percentage][] = $detail; + } + } + krsort($details); + foreach($details as $percentage => $files) + { + foreach($files as $detail) + { + $total = $detail['total']; + $executed = $detail['executed']; + $width = $detail['width']; + $filename = $detail['filename']; + $link = $detail['link']; + + print "
"; + print ""; + print ""; + print "$executed/$total\n"; + print "$percentage%\n"; + print "{$filename}\n"; + print "
\n"; + } + } + } + + function constructURL($file, $coverage) + { + $file = rawurlencode($file); + $lines = implode(',', array_keys($coverage)); + return $this->painter.'?file='.$file.'&lines='.$lines; + } +} + + +class HTMLCoverageReport extends HtmlReporter +{ + protected $file; + protected $lines; + protected $name; + + function __construct($file, $name, $lines) + { + $this->file = $file; + $this->lines = $lines; + $this->name = $name; + } + + function show() + { + $this->paintHeader($this->name); + + $contents = file($this->file); + foreach($contents as $count => $line) + { + $num = ($count+1); + $line = preg_replace("/\\n|\\r/",'',$line); + $line = htmlspecialchars($line); + $line = str_replace(' ',' ',$line); + $line = str_replace("\t",'    ',$line); + if(in_array($count+1, $this->lines)) + echo "
$num $line
\n"; + else + echo "$num $line
\n"; + } + + $this->paintFooter(); + } + + function paintHeader($file, $charset="UTF-8") + { + $total = $this->codelines($this->file); + $executed = count($this->lines); + $percentage = sprintf('%01.2f',$executed/$total*100); + + $this->sendNoCacheHeaders(); + header('Content-Type: text/html Charset='.$charset); + print "\n\nCode Coverage: $file\n"; + print ""; + print "\n"; + print "\n\n"; + print "

Code Coverage

\n"; + print "
$file
"; + print "
    Total code lines: {$total}
Total lines executed: {$executed} ({$percentage}%)
"; + flush(); + } + + function paintFooter($test_name) + { + print "\n\n"; + } + + static function codelines($file) + { + $source = file_get_contents($file); + $tokens = @token_get_all($source); + + $lines = ''; + + foreach ($tokens as $token) + { + if (is_string($token)) + { + // simple 1-character token + $lines .= $token; + } + else + { + // token array + list($id, $text) = $token; + + switch ($id) + { + case T_COMMENT: + case T_ML_COMMENT: // we've defined this + case T_DOC_COMMENT: // and this + // no action on comments + break; + + default: + // anything else -> output "as is" + //echo $text; + $lines .= $text; + break; + } + } + } + + $lines = preg_replace('/\\n\s*$/m',"",$lines); + $codelines = explode("\n",$lines); + $count = 0; + $patterns[] = '^\s*{\s*$'; + $patterns[] = '<\?'; + $patterns[] = '^\s*(private|protected|public)\s+\$'; + $pattern = '/'.implode('|', $patterns).'/'; + foreach($codelines as $line) + { + if(!preg_match($pattern, $line)) + $count++; + } + return $count; + //var_dump($codelines); + //return count($codelines); + } +} + +?> diff --git a/tests/UnitTests/simpletest/LICENSE b/tests/UnitTests/simpletest/LICENSE new file mode 100644 index 00000000..78d032ad --- /dev/null +++ b/tests/UnitTests/simpletest/LICENSE @@ -0,0 +1,49 @@ +The Open Group Test Suite License + +Preamble + +The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. + +Testing is essential for proper development and maintenance of standards-based products. + +For buyers: adequate conformance testing leads to reduced integration costs and protection of investments in applications, software and people. + +For software developers: conformance testing of platforms and middleware greatly reduces the cost of developing and maintaining multi-platform application software. + +For suppliers: In-depth testing increases customer satisfaction and keeps development and support costs in check. API conformance is highly measurable and suppliers who claim it must be able to substantiate that claim. + +As such, since these are benchmark measures of conformance, we feel the integrity of test tools is of importance. In order to preserve the integrity of the existing conformance modes of this test package and to permit recipients of modified versions of this package to run the original test modes, this license requires that the original test modes be preserved. + +If you find a bug in one of the standards mode test cases, please let us know so we can feed this back into the original, and also raise any specification issues with the appropriate bodies (for example the POSIX committees). + +Definitions: + + * "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. + * "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. + * "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. + * "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) +* "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. + +1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. + +2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. + +3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least the following: + +rename any non-standard executables and testcases so the names do not conflict with standard executables and testcases, which must also be provided, and provide a separate manual page for each non-standard executable and testcase that clearly documents how it differs from the Standard Version. + +4. You may distribute the programs of this Package in object code or executable form, provided that you do at least the following: + +accompany any non-standard executables and testcases with their corresponding Standard Version executables and testcases, giving the non-standard executables and testcases non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. + +5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. + +6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. + +7.Subroutines supplied by you and linked into this Package shall not be considered part of this Package. + +8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. + +9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + +The End diff --git a/tests/UnitTests/simpletest/README b/tests/UnitTests/simpletest/README new file mode 100644 index 00000000..b8dd6d1a --- /dev/null +++ b/tests/UnitTests/simpletest/README @@ -0,0 +1,110 @@ +SimpleTest +========== +You probably got this package from... +http://sourceforge.net/projects/simpletest/ + +If there is no licence agreement with this package please download +a version from the location above. You must read and accept that +licence to use this software. The file is titled simply LICENSE. + +What is it? It's a framework for unit testing, web site testing and +mock objects for PHP 4.2.0+. + +If you have used JUnit you will find this PHP unit testing version very +similar. Also included is a mock objects and server stubs generator. +The stubs can have return values set for different arguments, can have +sequences set also by arguments and can return items by reference. +The mocks inherit all of this functionality and can also have +expectations set, again in sequences and for different arguments. + +A web tester similar in concept to JWebUnit is also included. There is no +JavaScript or tables support, but forms, authentication, cookies and +frames are handled. + +You are not tied to just using SimpleTest, though. The mocks and stubs +will work with other test frameworks and SimpleTest can use other +framework's (PHPUnit, PEAR::PhpUnit) test cases as it's own. The +web browser part of the web tester can also be used independently either +in other testers or as part of a scripting solution. + +You can see a release schedule at http://www.lastcraft.com/overview.php +which is also copied to the documentation folder with this release. +A full PHPDocumenter API documentation exists at +http://simpletest.sourceforge.net/. + +The user interface is minimal +in the extreme, but a lot of information flows from the test suite. +After version 1.0 we will release a better web UI, but we are leaving XUL +and GTk versions to volunteers as everybody has their own opinion +on a good GUI, and we don't want to discourage development by shipping +one with the toolkit. + +You are looking at a first full release. The unit tests for SimpleTest +itself can be run here... + +simpletest/test/unit_tests.php + +And tests involving live network connections as well are here... + +simpletest/test/all_tests.php + +The full tests will typically overrun the 8Mb limit usually allowed +to a PHP process. A workaround is to run the tests on the command +with a custom php.ini file if you do not have access to your server +version. + +You will have to edit the all_tests.php file if you are accesssing +the internet through a proxy server. See the comments in all_tests.php +for instructions. + +The full tests read some test data from the LastCraft site. If the site +is down or has been modified for a later version then you will get +spurious errors. A unit_tests.php failure on the other hand would be +very serious. As far as we know we haven't yet managed to check in any +test failures so please correct us if you find one. + +Even if all of the tests run please verify that your existing test suites +also function as expected. If they don't see the file... + +HELP_MY_TESTS_DONT_WORK_ANYMORE + +This contains information on interface changes. It also points out +deprecated interfaces so you should read this even if all of +your current tests appear to run. + +There is a documentation folder which contains the core reference information +in English and French, although this information is fairly basic. +You can find a tutorial on http://www.lastcraft.com/first_test_tutorial.php +to get you started and this material will eventually become included +with the project documentation. A French translation exists at +http://www.onpk.net/index.php/2005/01/12/254-tutoriel-simpletest-decouvrir-les-tests-unitaires. + +If you download and use and possibly even extend this tool, please let us +know. Any feedback, even bad, is always welcome and we will work to get +your suggestions into the version one release. Ideally please send your +comments to... + +simpletest-support@lists.sourceforge.net + +...so that others can read them too. We usually try to respond within 48 +hours. + +There is no change log as yet except at Sourceforge. You can visit the +release notes to see the completed TODO list after each cycle and also the +status of any bugs, but if the bug is recent then it will be fixed in CVS only. +The CVS check-ins always have all the tests passing and so CVS snapshots should +be pretty usable, although the code may not look so good internally. + +Oh, yes. It is called "Simple" because it should be simple to +use. We intend to add a complete set of tools for a test first +and "test as you code" type of development. "Simple" does not +mean "Lite" in this context. + +Thanks to everyone who has sent comments and offered suggestions. They +really are invaluable, but sadly you are too many to mention in full. +Thanks to all on the advanced PHP forum on SitePoint, especially Harry +Feucks. Early adopters are always an inspiration. + +yours Marcus Baker, Jason Sweat and Perrick Penet. +-- +marcus@lastcraft.com diff --git a/tests/UnitTests/simpletest/VERSION b/tests/UnitTests/simpletest/VERSION new file mode 100644 index 00000000..d69d4fac --- /dev/null +++ b/tests/UnitTests/simpletest/VERSION @@ -0,0 +1 @@ +1.0 diff --git a/tests/UnitTests/simpletest/authentication.php b/tests/UnitTests/simpletest/authentication.php new file mode 100644 index 00000000..6ec7bc0c --- /dev/null +++ b/tests/UnitTests/simpletest/authentication.php @@ -0,0 +1,219 @@ +_type = $type; + $this->_root = $url->getBasePath(); + $this->_username = false; + $this->_password = false; + } + + /** + * Adds another location to the realm. + * @param SimpleUrl $url Somewhere in realm. + * @access public + */ + function stretch($url) { + $this->_root = $this->_getCommonPath($this->_root, $url->getPath()); + } + + /** + * Finds the common starting path. + * @param string $first Path to compare. + * @param string $second Path to compare. + * @return string Common directories. + * @access private + */ + function _getCommonPath($first, $second) { + $first = explode('/', $first); + $second = explode('/', $second); + for ($i = 0; $i < min(count($first), count($second)); $i++) { + if ($first[$i] != $second[$i]) { + return implode('/', array_slice($first, 0, $i)) . '/'; + } + } + return implode('/', $first) . '/'; + } + + /** + * Sets the identity to try within this realm. + * @param string $username Username in authentication dialog. + * @param string $username Password in authentication dialog. + * @access public + */ + function setIdentity($username, $password) { + $this->_username = $username; + $this->_password = $password; + } + + /** + * Accessor for current identity. + * @return string Last succesful username. + * @access public + */ + function getUsername() { + return $this->_username; + } + + /** + * Accessor for current identity. + * @return string Last succesful password. + * @access public + */ + function getPassword() { + return $this->_password; + } + + /** + * Test to see if the URL is within the directory + * tree of the realm. + * @param SimpleUrl $url URL to test. + * @return boolean True if subpath. + * @access public + */ + function isWithin($url) { + return (strpos($url->getBasePath(), $this->_root) === 0); + } + } + + /** + * Manages security realms. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleAuthenticator { + protected $_realms; + + /** + * Clears the realms. + * @access public + */ + function SimpleAuthenticator() { + $this->restartSession(); + } + + /** + * Starts with no realms set up. + * @access public + */ + function restartSession() { + $this->_realms = array(); + } + + /** + * Adds a new realm centered the current URL. + * Browsers vary wildly on their behaviour in this + * regard. Mozilla ignores the realm and presents + * only when challenged, wasting bandwidth. IE + * just carries on presenting until a new challenge + * occours. SimpleTest tries to follow the spirit of + * the original standards committee and treats the + * base URL as the root of a file tree shaped realm. + * @param SimpleUrl $url Base of realm. + * @param string $type Authentication type for this + * realm. Only Basic authentication + * is currently supported. + * @param string $realm Name of realm. + * @access public + */ + function addRealm($url, $type, $realm) { + $this->_realms[$url->getHost()][$realm] = new SimpleRealm($type, $url); + } + + /** + * Sets the current identity to be presented + * against that realm. + * @param string $host Server hosting realm. + * @param string $realm Name of realm. + * @param string $username Username for realm. + * @param string $password Password for realm. + * @access public + */ + function setIdentityForRealm($host, $realm, $username, $password) { + if (isset($this->_realms[$host][$realm])) { + $this->_realms[$host][$realm]->setIdentity($username, $password); + } + } + + /** + * Finds the name of the realm by comparing URLs. + * @param SimpleUrl $url URL to test. + * @return SimpleRealm Name of realm. + * @access private + */ + function _findRealmFromUrl($url) { + if (! isset($this->_realms[$url->getHost()])) { + return false; + } + foreach ($this->_realms[$url->getHost()] as $name => $realm) { + if ($realm->isWithin($url)) { + return $realm; + } + } + return false; + } + + /** + * Presents the appropriate headers for this location. + * @param SimpleHttpRequest $request Request to modify. + * @param SimpleUrl $url Base of realm. + * @access public + */ + function addHeaders($request, $url) { + if ($url->getUsername() && $url->getPassword()) { + $username = $url->getUsername(); + $password = $url->getPassword(); + } elseif ($realm = $this->_findRealmFromUrl($url)) { + $username = $realm->getUsername(); + $password = $realm->getPassword(); + } else { + return; + } + $this->addBasicHeaders($request, $username, $password); + } + + /** + * Presents the appropriate headers for this + * location for basic authentication. + * @param SimpleHttpRequest $request Request to modify. + * @param string $username Username for realm. + * @param string $password Password for realm. + * @access public + * @static + */ + function addBasicHeaders($request, $username, $password) { + if ($username && $password) { + $request->addHeaderLine( + 'Authorization: Basic ' . base64_encode("$username:$password")); + } + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/browser.php b/tests/UnitTests/simpletest/browser.php new file mode 100644 index 00000000..0e281e5a --- /dev/null +++ b/tests/UnitTests/simpletest/browser.php @@ -0,0 +1,1016 @@ +_sequence = array(); + $this->_position = -1; + } + + /** + * Test for no entries yet. + * @return boolean True if empty. + * @access private + */ + function _isEmpty() { + return ($this->_position == -1); + } + + /** + * Test for being at the beginning. + * @return boolean True if first. + * @access private + */ + function _atBeginning() { + return ($this->_position == 0) && ! $this->_isEmpty(); + } + + /** + * Test for being at the last entry. + * @return boolean True if last. + * @access private + */ + function _atEnd() { + return ($this->_position + 1 >= count($this->_sequence)) && ! $this->_isEmpty(); + } + + /** + * Adds a successfully fetched page to the history. + * @param string $method GET or POST. + * @param SimpleUrl $url URL of fetch. + * @param SimpleFormEncoding $parameters Any post data with the fetch. + * @access public + */ + function recordEntry($method, $url, $parameters) { + $this->_dropFuture(); + array_push( + $this->_sequence, + array('method' => $method, 'url' => $url, 'parameters' => $parameters)); + $this->_position++; + } + + /** + * Last fetching method for current history + * position. + * @return string GET or POST for this point in + * the history. + * @access public + */ + function getMethod() { + if ($this->_isEmpty()) { + return false; + } + return $this->_sequence[$this->_position]['method']; + } + + /** + * Last fully qualified URL for current history + * position. + * @return SimpleUrl URL for this position. + * @access public + */ + function getUrl() { + if ($this->_isEmpty()) { + return false; + } + return $this->_sequence[$this->_position]['url']; + } + + /** + * Parameters of last fetch from current history + * position. + * @return SimpleFormEncoding Post parameters. + * @access public + */ + function getParameters() { + if ($this->_isEmpty()) { + return false; + } + return $this->_sequence[$this->_position]['parameters']; + } + + /** + * Step back one place in the history. Stops at + * the first page. + * @return boolean True if any previous entries. + * @access public + */ + function back() { + if ($this->_isEmpty() || $this->_atBeginning()) { + return false; + } + $this->_position--; + return true; + } + + /** + * Step forward one place. If already at the + * latest entry then nothing will happen. + * @return boolean True if any future entries. + * @access public + */ + function forward() { + if ($this->_isEmpty() || $this->_atEnd()) { + return false; + } + $this->_position++; + return true; + } + + /** + * Ditches all future entries beyond the current + * point. + * @access private + */ + function _dropFuture() { + if ($this->_isEmpty()) { + return; + } + while (! $this->_atEnd()) { + array_pop($this->_sequence); + } + } + } + + /** + * Simulated web browser. This is an aggregate of + * the user agent, the HTML parsing, request history + * and the last header set. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleBrowser { + protected $_user_agent; + protected $_page; + protected $_history; + protected $_ignore_frames; + protected $_maximum_nested_frames; + + /** + * Starts with a fresh browser with no + * cookie or any other state information. The + * exception is that a default proxy will be + * set up if specified in the options. + * @access public + */ + function SimpleBrowser() { + $this->_user_agent = $this->_createUserAgent(); + $this->_user_agent->useProxy( + SimpleTestOptions::getDefaultProxy(), + SimpleTestOptions::getDefaultProxyUsername(), + SimpleTestOptions::getDefaultProxyPassword()); + $this->_page = new SimplePage(); + $this->_history = $this->_createHistory(); + $this->_ignore_frames = false; + $this->_maximum_nested_frames = DEFAULT_MAX_NESTED_FRAMES; + } + + /** + * Creates the underlying user agent. + * @return SimpleFetcher Content fetcher. + * @access protected + */ + function _createUserAgent() { + return new SimpleUserAgent(); + } + + /** + * Creates a new empty history list. + * @return SimpleBrowserHistory New list. + * @access protected + */ + function _createHistory() { + return new SimpleBrowserHistory(); + } + + /** + * Disables frames support. Frames will not be fetched + * and the frameset page will be used instead. + * @access public + */ + function ignoreFrames() { + $this->_ignore_frames = true; + } + + /** + * Enables frames support. Frames will be fetched from + * now on. + * @access public + */ + function useFrames() { + $this->_ignore_frames = false; + } + + /** + * Parses the raw content into a page. Will load further + * frame pages unless frames are disabled. + * @param SimpleHttpResponse $response Response from fetch. + * @param integer $depth Nested frameset depth. + * @return SimplePage Parsed HTML. + * @access protected + */ + function _parse($response, $depth = 0) { + $builder = new SimplePageBuilder(); + $page = $builder->parse($response); + if ($this->_ignore_frames || ! $page->hasFrames() || ($depth > $this->_maximum_nested_frames)) { + return $page; + } + $frameset = new SimpleFrameset($page); + foreach ($page->getFrameset() as $key => $url) { + $frame = $this->_fetch('GET', $url, array(), $depth + 1); + $frameset->addFrame($frame, $key); + } + return $frameset; + } + + /** + * Fetches a page. + * @param string $method GET or POST. + * @param string/SimpleUrl $url Target to fetch as string. + * @param SimpleFormEncoding $parameters POST parameters. + * @param integer $depth Nested frameset depth protection. + * @return SimplePage Parsed page. + * @access private + */ + function _fetch($method, $url, $parameters, $depth = 0) { + $response = $this->_user_agent->fetchResponse($method, $url, $parameters); + if ($response->isError()) { + return new SimplePage($response); + } + return $this->_parse($response, $depth); + } + + /** + * Fetches a page or a single frame if that is the current + * focus. + * @param string $method GET or POST. + * @param string/SimpleUrl $url Target to fetch as string. + * @param SimpleFormEncoding $parameters POST parameters. + * @return string Raw content of page. + * @access private + */ + function _load($method, $url, $parameters = false) { + $frame = $url->getTarget(); + if (! $frame || ! $this->_page->hasFrames() || (strtolower($frame) == '_top')) { + return $this->_loadPage($method, $url, $parameters); + } + return $this->_loadFrame(array($frame), $method, $url, $parameters); + } + + /** + * Fetches a page and makes it the current page/frame. + * @param string $method GET or POST. + * @param string/SimpleUrl $url Target to fetch as string. + * @param SimpleFormEncoding $parameters POST parameters. + * @return string Raw content of page. + * @access private + */ + function _loadPage($method, $url, $parameters = false) { + $this->_page = $this->_fetch(strtoupper($method), $url, $parameters); + $this->_history->recordEntry( + $this->_page->getMethod(), + $this->_page->getUrl(), + $this->_page->getRequestData()); + return $this->_page->getRaw(); + } + + /** + * Fetches a frame into the existing frameset replacing the + * original. + * @param array $frames List of names to drill down. + * @param string $method GET or POST. + * @param string/SimpleUrl $url Target to fetch as string. + * @param SimpleFormEncoding $parameters POST parameters. + * @return string Raw content of page. + * @access private + */ + function _loadFrame($frames, $method, $url, $parameters = false) { + $page = $this->_fetch(strtoupper($method), $url, $parameters); + $this->_page->setFrame($frames, $page); + } + + /** + * Removes expired and temporary cookies as if + * the browser was closed and re-opened. + * @param string/integer $date Time when session restarted. + * If omitted then all persistent + * cookies are kept. + * @access public + */ + function restart($date = false) { + $this->_user_agent->restart($date); + } + + /** + * Adds a header to every fetch. + * @param string $header Header line to add to every + * request until cleared. + * @access public + */ + function addHeader($header) { + $this->_user_agent->addHeader($header); + } + + /** + * Ages the cookies by the specified time. + * @param integer $interval Amount in seconds. + * @access public + */ + function ageCookies($interval) { + $this->_user_agent->ageCookies($interval); + } + + /** + * Sets an additional cookie. If a cookie has + * the same name and path it is replaced. + * @param string $name Cookie key. + * @param string $value Value of cookie. + * @param string $host Host upon which the cookie is valid. + * @param string $path Cookie path if not host wide. + * @param string $expiry Expiry date. + * @access public + */ + function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { + $this->_user_agent->setCookie($name, $value, $host, $path, $expiry); + } + + /** + * Reads the most specific cookie value from the + * browser cookies. + * @param string $host Host to search. + * @param string $path Applicable path. + * @param string $name Name of cookie to read. + * @return string False if not present, else the + * value as a string. + * @access public + */ + function getCookieValue($host, $path, $name) { + return $this->_user_agent->getCookieValue($host, $path, $name); + } + + /** + * Reads the current cookies for the current URL. + * @param string $name Key of cookie to find. + * @return string Null if there is no current URL, false + * if the cookie is not set. + * @access public + */ + function getCurrentCookieValue($name) { + return $this->_user_agent->getBaseCookieValue($name, $this->_page->getUrl()); + } + + /** + * Sets the maximum number of redirects before + * a page will be loaded anyway. + * @param integer $max Most hops allowed. + * @access public + */ + function setMaximumRedirects($max) { + $this->_user_agent->setMaximumRedirects($max); + } + + /** + * Sets the maximum number of nesting of framed pages + * within a framed page to prevent loops. + * @param integer $max Highest depth allowed. + * @access public + */ + function setMaximumNestedFrames($max) { + $this->_maximum_nested_frames = $max; + } + + /** + * Sets the socket timeout for opening a connection. + * @param integer $timeout Maximum time in seconds. + * @access public + */ + function setConnectionTimeout($timeout) { + $this->_user_agent->setConnectionTimeout($timeout); + } + + /** + * Sets proxy to use on all requests for when + * testing from behind a firewall. Set URL + * to false to disable. + * @param string $proxy Proxy URL. + * @param string $username Proxy username for authentication. + * @param string $password Proxy password for authentication. + * @access public + */ + function useProxy($proxy, $username = false, $password = false) { + $this->_user_agent->useProxy($proxy, $username, $password); + } + + /** + * Fetches the page content with a HEAD request. + * Will affect cookies, but will not change the base URL. + * @param string/SimpleUrl $url Target to fetch as string. + * @param hash/SimpleFormEncoding $parameters Additional parameters for + * HEAD request. + * @return boolean True if successful. + * @access public + */ + function head($url, $parameters = false) { + if (! is_object($url)) { + $url = new SimpleUrl($url); + } + if (is_array($parameters)) { + $parameters = new SimpleFormEncoding($parameters); + } + if ($this->getUrl()) { + $url = $url->makeAbsolute($this->getUrl()); + } + $response = $this->_user_agent->fetchResponse( + 'HEAD', + $url, + $parameters); + return ! $response->isError(); + } + + /** + * Fetches the page content with a simple GET request. + * @param string/SimpleUrl $url Target to fetch. + * @param hash/SimpleFormEncoding $parameters Additional parameters for + * GET request. + * @return string Content of page or false. + * @access public + */ + function get($url, $parameters = false) { + if (! is_object($url)) { + $url = new SimpleUrl($url); + } + if (is_array($parameters)) { + $parameters = new SimpleFormEncoding($parameters); + } + if ($this->getUrl()) { + $url = $url->makeAbsolute($this->getUrl()); + } + return $this->_load('GET', $url, $parameters); + } + + /** + * Fetches the page content with a POST request. + * @param string/SimpleUrl $url Target to fetch as string. + * @param hash/SimpleFormEncoding $parameters POST parameters. + * @return string Content of page. + * @access public + */ + function post($url, $parameters = false) { + if (! is_object($url)) { + $url = new SimpleUrl($url); + } + if (is_array($parameters)) { + $parameters = new SimpleFormEncoding($parameters); + } + if ($this->getUrl()) { + $url = $url->makeAbsolute($this->getUrl()); + } + return $this->_load('POST', $url, $parameters); + } + + /** + * Equivalent to hitting the retry button on the + * browser. Will attempt to repeat the page fetch. If + * there is no history to repeat it will give false. + * @return string/boolean Content if fetch succeeded + * else false. + * @access public + */ + function retry() { + $frames = $this->_page->getFrameFocus(); + if (count($frames) > 0) { + $this->_loadFrame( + $frames, + $this->_page->getMethod(), + $this->_page->getUrl(), + $this->_page->getRequestData()); + return $this->_page->getRaw(); + } + if ($method = $this->_history->getMethod()) { + $this->_page = $this->_fetch( + $method, + $this->_history->getUrl(), + $this->_history->getParameters()); + return $this->_page->getRaw(); + } + return false; + } + + /** + * Equivalent to hitting the back button on the + * browser. The browser history is unchanged on + * failure. + * @return boolean True if history entry and + * fetch succeeded + * @access public + */ + function back() { + if (! $this->_history->back()) { + return false; + } + $content = $this->retry(); + if (! $content) { + $this->_history->forward(); + } + return $content; + } + + /** + * Equivalent to hitting the forward button on the + * browser. The browser history is unchanged on + * failure. + * @return boolean True if history entry and + * fetch succeeded + * @access public + */ + function forward() { + if (! $this->_history->forward()) { + return false; + } + $content = $this->retry(); + if (! $content) { + $this->_history->back(); + } + return $content; + } + + /** + * Retries a request after setting the authentication + * for the current realm. + * @param string $username Username for realm. + * @param string $password Password for realm. + * @return boolean True if successful fetch. Note + * that authentication may still have + * failed. + * @access public + */ + function authenticate($username, $password) { + if (! $this->_page->getRealm()) { + return false; + } + $url = $this->_page->getUrl(); + if (! $url) { + return false; + } + $this->_user_agent->setIdentity( + $url->getHost(), + $this->_page->getRealm(), + $username, + $password); + return $this->retry(); + } + + /** + * Accessor for a breakdown of the frameset. + * @return array Hash tree of frames by name + * or index if no name. + * @access public + */ + function getFrames() { + return $this->_page->getFrames(); + } + + /** + * Accessor for current frame focus. Will be + * false if no frame has focus. + * @return integer/string/boolean Label if any, otherwise + * the position in the frameset + * or false if none. + * @access public + */ + function getFrameFocus() { + return $this->_page->getFrameFocus(); + } + + /** + * Sets the focus by index. The integer index starts from 1. + * @param integer $choice Chosen frame. + * @return boolean True if frame exists. + * @access public + */ + function setFrameFocusByIndex($choice) { + return $this->_page->setFrameFocusByIndex($choice); + } + + /** + * Sets the focus by name. + * @param string $name Chosen frame. + * @return boolean True if frame exists. + * @access public + */ + function setFrameFocus($name) { + return $this->_page->setFrameFocus($name); + } + + /** + * Clears the frame focus. All frames will be searched + * for content. + * @access public + */ + function clearFrameFocus() { + return $this->_page->clearFrameFocus(); + } + + /** + * Accessor for last error. + * @return string Error from last response. + * @access public + */ + function getTransportError() { + return $this->_page->getTransportError(); + } + + /** + * Accessor for current MIME type. + * @return string MIME type as string; e.g. 'text/html' + * @access public + */ + function getMimeType() { + return $this->_page->getMimeType(); + } + + /** + * Accessor for last response code. + * @return integer Last HTTP response code received. + * @access public + */ + function getResponseCode() { + return $this->_page->getResponseCode(); + } + + /** + * Accessor for last Authentication type. Only valid + * straight after a challenge (401). + * @return string Description of challenge type. + * @access public + */ + function getAuthentication() { + return $this->_page->getAuthentication(); + } + + /** + * Accessor for last Authentication realm. Only valid + * straight after a challenge (401). + * @return string Name of security realm. + * @access public + */ + function getRealm() { + return $this->_page->getRealm(); + } + + /** + * Accessor for current URL of page or frame if + * focused. + * @return string Location of current page or frame as + * a string. + */ + function getUrl() { + $url = $this->_page->getUrl(); + return $url ? $url->asString() : false; + } + + /** + * Accessor for raw bytes sent down the wire. + * @return string Original text sent. + * @access public + */ + function getRequest() { + return $this->_page->getRequest(); + } + + /** + * Accessor for raw header information. + * @return string Header block. + * @access public + */ + function getHeaders() { + return $this->_page->getHeaders(); + } + + /** + * Accessor for raw page information. + * @return string Original text content of web page. + * @access public + */ + function getContent() { + return $this->_page->getRaw(); + } + + /** + * Accessor for plain text version of the page. + * @return string Normalised text representation. + * @access public + */ + function getContentAsText() { + return $this->_page->getText(); + } + + /** + * Accessor for parsed title. + * @return string Title or false if no title is present. + * @access public + */ + function getTitle() { + return $this->_page->getTitle(); + } + + /** + * Accessor for a list of all fixed links in current page. + * @return array List of urls with scheme of + * http or https and hostname. + * @access public + */ + function getAbsoluteUrls() { + return $this->_page->getAbsoluteUrls(); + } + + /** + * Accessor for a list of all relative links. + * @return array List of urls without hostname. + * @access public + */ + function getRelativeUrls() { + return $this->_page->getRelativeUrls(); + } + + /** + * Sets all form fields with that name. + * @param string $name Name of field in forms. + * @param string $value New value of field. + * @return boolean True if field exists, otherwise false. + * @access public + */ + function setField($name, $value) { + return $this->_page->setField($name, $value); + } + + /** + * Sets all form fields with that id attribute. + * @param string/integer $id Id of field in forms. + * @param string $value New value of field. + * @return boolean True if field exists, otherwise false. + * @access public + */ + function setFieldById($id, $value) { + return $this->_page->setFieldById($id, $value); + } + + /** + * Accessor for a form element value within the page. + * Finds the first match. + * @param string $name Field name. + * @return string/boolean A string if the field is + * present, false if unchecked + * and null if missing. + * @access public + */ + function getField($name) { + return $this->_page->getField($name); + } + + /** + * Accessor for a form element value within the page. + * @param string/integer $id Id of field in forms. + * @return string/boolean A string if the field is + * present, false if unchecked + * and null if missing. + * @access public + */ + function getFieldById($id) { + return $this->_page->getFieldById($id); + } + + /** + * Clicks the submit button by label. The owning + * form will be submitted by this. + * @param string $label Button label. An unlabeled + * button can be triggered by 'Submit'. + * @param hash $additional Additional form data. + * @return string/boolean Page on success. + * @access public + */ + function clickSubmit($label = 'Submit', $additional = false) { + if (! ($form = $this->_page->getFormBySubmitLabel($label))) { + return false; + } + $success = $this->_load( + $form->getMethod(), + $form->getAction(), + $form->submitButtonByLabel($label, $additional)); + return ($success ? $this->getContent() : $success); + } + + /** + * Clicks the submit button by name attribute. The owning + * form will be submitted by this. + * @param string $name Button name. + * @param hash $additional Additional form data. + * @return string/boolean Page on success. + * @access public + */ + function clickSubmitByName($name, $additional = false) { + if (! ($form = $this->_page->getFormBySubmitName($name))) { + return false; + } + $success = $this->_load( + $form->getMethod(), + $form->getAction(), + $form->submitButtonByName($name, $additional)); + return ($success ? $this->getContent() : $success); + } + + /** + * Clicks the submit button by ID attribute of the button + * itself. The owning form will be submitted by this. + * @param string $id Button ID. + * @param hash $additional Additional form data. + * @return string/boolean Page on success. + * @access public + */ + function clickSubmitById($id, $additional = false) { + if (! ($form = $this->_page->getFormBySubmitId($id))) { + return false; + } + $success = $this->_load( + $form->getMethod(), + $form->getAction(), + $form->submitButtonById($id, $additional)); + return ($success ? $this->getContent() : $success); + } + + /** + * Clicks the submit image by some kind of label. Usually + * the alt tag or the nearest equivalent. The owning + * form will be submitted by this. Clicking outside of + * the boundary of the coordinates will result in + * a failure. + * @param string $label ID attribute of button. + * @param integer $x X-coordinate of imaginary click. + * @param integer $y Y-coordinate of imaginary click. + * @param hash $additional Additional form data. + * @return string/boolean Page on success. + * @access public + */ + function clickImage($label, $x = 1, $y = 1, $additional = false) { + if (! ($form = $this->_page->getFormByImageLabel($label))) { + return false; + } + $success = $this->_load( + $form->getMethod(), + $form->getAction(), + $form->submitImageByLabel($label, $x, $y, $additional)); + return ($success ? $this->getContent() : $success); + } + + /** + * Clicks the submit image by the name. Usually + * the alt tag or the nearest equivalent. The owning + * form will be submitted by this. Clicking outside of + * the boundary of the coordinates will result in + * a failure. + * @param string $name Name attribute of button. + * @param integer $x X-coordinate of imaginary click. + * @param integer $y Y-coordinate of imaginary click. + * @param hash $additional Additional form data. + * @return string/boolean Page on success. + * @access public + */ + function clickImageByName($name, $x = 1, $y = 1, $additional = false) { + if (! ($form = $this->_page->getFormByImageName($name))) { + return false; + } + $success = $this->_load( + $form->getMethod(), + $form->getAction(), + $form->submitImageByName($name, $x, $y, $additional)); + return ($success ? $this->getContent() : $success); + } + + /** + * Clicks the submit image by ID attribute. The owning + * form will be submitted by this. Clicking outside of + * the boundary of the coordinates will result in + * a failure. + * @param integer/string $id ID attribute of button. + * @param integer $x X-coordinate of imaginary click. + * @param integer $y Y-coordinate of imaginary click. + * @param hash $additional Additional form data. + * @return string/boolean Page on success. + * @access public + */ + function clickImageById($id, $x = 1, $y = 1, $additional = false) { + if (! ($form = $this->_page->getFormByImageId($id))) { + return false; + } + $success = $this->_load( + $form->getMethod(), + $form->getAction(), + $form->submitImageById($id, $x, $y, $additional)); + return ($success ? $this->getContent() : $success); + } + + /** + * Submits a form by the ID. + * @param string $id The form ID. No submit button value + * will be sent. + * @return string/boolean Page on success. + * @access public + */ + function submitFormById($id) { + if (! ($form = $this->_page->getFormById($id))) { + return false; + } + $success = $this->_load( + $form->getMethod(), + $form->getAction(), + $form->submit()); + return ($success ? $this->getContent() : $success); + } + + /** + * Follows a link by label. Will click the first link + * found with this link text by default, or a later + * one if an index is given. The match ignores case and + * white space issues. + * @param string $label Text between the anchor tags. + * @param integer $index Link position counting from zero. + * @return string/boolean Page on success. + * @access public + */ + function clickLink($label, $index = 0) { + $urls = $this->_page->getUrlsByLabel($label); + if (count($urls) == 0) { + return false; + } + if (count($urls) < $index + 1) { + return false; + } + $this->_load('GET', $urls[$index]); + return $this->getContent(); + } + + /** + * Tests to see if a link is present by label. + * @param string $label Text of value attribute. + * @return boolean True if link present. + * @access public + */ + function isLink($label) { + return (count($this->_page->getUrlsByLabel($label)) > 0); + } + + /** + * Follows a link by id attribute. + * @param string $id ID attribute value. + * @return string/boolean Page on success. + * @access public + */ + function clickLinkById($id) { + if (! ($url = $this->_page->getUrlById($id))) { + return false; + } + $this->_load('GET', $url); + return $this->getContent(); + } + + /** + * Tests to see if a link is present by ID attribute. + * @param string $id Text of id attribute. + * @return boolean True if link present. + * @access public + */ + function isLinkById($id) { + return (boolean)$this->_page->getUrlById($id); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/docs/en/authentication_documentation.html b/tests/UnitTests/simpletest/docs/en/authentication_documentation.html new file mode 100644 index 00000000..a83f448b --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/authentication_documentation.html @@ -0,0 +1,320 @@ + + + +SimpleTest documentation for testing log-in and authentication + + + + +

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

+

+ 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 testAuthentication() {
+        $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. +

+

+ 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->clickSubmit('Log in');
+        $this->assertWantedPattern('/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->assertWantedPattern('/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->clickSubmit('Log in');
+        $this->assertWantedPattern('/Welcome Me/');
+        
+        $this->restart();
+        $this->get('http://www.my-site.com/restricted.php');
+        $this->assertWantedPattern('/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->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/');
+    }
+}
+
+ 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/UnitTests/simpletest/docs/en/browser_documentation.html b/tests/UnitTests/simpletest/docs/en/browser_documentation.html new file mode 100644 index 00000000..18c4d353 --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/browser_documentation.html @@ -0,0 +1,386 @@ + + + +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->clickLink('reporting bugs');
+    $browser->clickLink('statistics');
+    $page = $browser->clickLink('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
+ The methods SimpleBrowser::setConnectionTimeout() + SimpleBrowser::setMaximumRedirects(), + SimpleBrowser::setMaximumNestedFrames(), + SimpleBrowser::ignoreFrames() and + SimpleBrowser::useFrames() continue to apply + to every subsequent request. + The other methods are frames aware. + This means that if you have an individual frame that is not + loading, navigate to it using SimpleBrowser::setFrameFocus() + and you can then use SimpleBrowser::getRequest(), etc to + see what happened. +

+ +

+ +

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->clickSubmit('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->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');
+    }
+}
+
+ 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/UnitTests/simpletest/docs/en/docs.css b/tests/UnitTests/simpletest/docs/en/docs.css new file mode 100644 index 00000000..c59b9cd2 --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/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/UnitTests/simpletest/docs/en/expectation_documentation.html b/tests/UnitTests/simpletest/docs/en/expectation_documentation.html new file mode 100644 index 00000000..ed1484a9 --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/expectation_documentation.html @@ -0,0 +1,356 @@ + + + + + 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() {
+        $writer = &new MockWriter($this);
+        $writer->expectOnce('write', array(
+                'Cannot connect to news service ' .
+                '"BBC News" at this time. ' .
+                'Please try again later.'));
+        
+        $service = &new NewsService('BBC News');
+        $service->publish($writer);
+        
+        $writer->tally();
+    }
+}
+
+ This is a good example of a brittle test. + If we decide to add additional instructions, such as + suggesting an alternative news source, we will break + our tests even though no underlying functionality + has been altered. +

+

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

+class TestOfNewsService extends UnitTestCase {
+    ...
+    function testConnectionFailure() {
+        $writer = &new MockWriter($this);
+        $writer->expectOnce(
+                'write',
+                array(new WantedPatternExpectation('/cannot connect/i')));
+        
+        $service = &new NewsService('BBC News');
+        $service->publish($writer);
+        
+        $writer->tally();
+    }
+}
+
+ 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
WantedPatternExpectationUses a Perl Regex to match a string
NoUnwantedPatternExpectationPasses 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 either + the + mock objects + or the + server stubs. + Anywhere a list of arguments is given, a list of expectation objects + can be inserted instead. +

+

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

+Stub::generate('Authorisation');
+
+$authorisation = new StubAuthorisation();
+$authorisation->setReturnValue(
+        'isAllowed',
+        true,
+        array(new IsAExpectation('Session', 'Must be a session')));
+$authorisation->setReturnValue('isAllowed', false);
+
+ We have set the default stub behaviour to return false when + isAllowed is called. + When we call the method with a single parameter that + is a Session object, it will return true. + We have also added a second parameter as a message. + This will be displayed as part of the mock object + failure message if this expectation is the cause of + a failure. +

+

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

+ +

+ +

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::assertExpectation() method to + test against it directly... +

+class TestOfNetworking extends UnitTestCase {
+    ...
+    function testGetValidIp() {
+        $server = &new Server();
+        $this->assertExpectation(
+                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->assertExpectation(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/UnitTests/simpletest/docs/en/form_testing_documentation.html b/tests/UnitTests/simpletest/docs/en/form_testing_documentation.html new file mode 100644 index 00000000..597db3b0 --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/form_testing_documentation.html @@ -0,0 +1,277 @@ + + + +Simple Test documentation for testing HTML forms + + + + +

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

+

+ 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->clickSubmit('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->clickSubmit('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->assertNoUnwantedPattern('/user created/i');
+    }
+}
+
+ By adding data to the WebTestCase::post() + method, we are attempting to fetch the page as a form submission. +

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/en/group_test_documentation.html b/tests/UnitTests/simpletest/docs/en/group_test_documentation.html new file mode 100644 index 00000000..e7a067ec --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/group_test_documentation.html @@ -0,0 +1,357 @@ + + + +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 {
+        ...
+    }
+    SimpleTestOptions::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/UnitTests/simpletest/docs/en/index.html b/tests/UnitTests/simpletest/docs/en/index.html new file mode 100644 index 00000000..d5a30d31 --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/index.html @@ -0,0 +1,467 @@ + + + + + Download the Simple Test testing framework - + Unit tests and mock objects for PHP + + + + + +

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');
+?>
+
+ Here the simpletest folder is either local or in the path. + You would have to edit these locations depending on where you + placed the toolset. + Next we create a test case... +
+<?php
+require_once('simpletest/unit_tester.php');
+require_once('simpletest/reporter.php');
+require_once('../classes/log.php');
+
+class TestOfLogging extends UnitTestCase {
+}
+?>
+
+ 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($this);
+        $log->expectOnce('message', array('User fred logged in.'));
+        $session_pool = &new SessionPool($log);
+        $session_pool->logIn('fred');
+        $log->tally();
+    }
+}
+?>
+
+ The tally() call is needed to + tell the mock object that time is up for the expected call + count. + Without it the mock would wait forever for the method + call to come in without ever actually notifying the test case. + The other test will be triggered when the call to + message() is invoked on the + MockLog object. + The mock call will trigger a parameter comparison and then send the + resulting pass or fail event to the test display. + Wildcards can be included here too so as to prevent tests + becoming too specific. +

+

+ The mock objects in the SimpleTest suite can have arbitrary + return values set, sequences of returns, return values + selected according to the incoming arguments, sequences of + parameter expectations and limits on the number of times + a method is to be invoked. +

+

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

+ +

+ +

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->clickLink('About');
+    }
+    
+    function testSearchEngineOptimisations() {
+        $this->assertTitle('A long title about us for search engines');
+        $this->assertWantedPattern('/a popular keyphrase/i');
+    }
+}
+$test = &new TestOfAbout();
+$test->run(new HtmlReporter());
+?>
+
+ With this code as an acceptance test you can ensure that + the content always meets the specifications of both the + developers and the other project stakeholders. +

+

+ SourceForge.net Logo +

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/en/mock_objects_documentation.html b/tests/UnitTests/simpletest/docs/en/mock_objects_documentation.html new file mode 100644 index 00000000..126b58dd --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/mock_objects_documentation.html @@ -0,0 +1,713 @@ + + + +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. +

+

+ 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($this);
+    }
+}
+
+ 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. + As with stubs we can replace the default null return values... +

+$connection->setReturnValue('query', 37);
+
+ Now every time we call + $connection->query() we get + the result of 37. + As with the stubs we can set wildcards and we can overload the + wildcard parameter. + We can also add extra methods to the mock when generating it + and choose our own class name... +
+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. +

+

+ All of the patterns available with server stubs are available + to mock objects... +

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

+

+ A repeat of the stubbed information holder with name/value pairs... +

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

+

+ There are times when you want a specific object to be + dished out by the mock rather than a copy. + Again this is identical to the server stubs mechanism... +

+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($this);
+$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. +

+ +

+ +

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($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();
+    }
+}
+
+ We start by creating a dummy session. + We don't have to be too fussy about this as the check + for which session we want is done elsewhere. + We only need to check that it was the same one that came + from the session pool. +

+

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

+

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

+

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

+

+ We start to run our tests when we create the new + LoggingSessionPool and feed + it our preset mock objects. + Everything is now under our control. + Finally we confirm that the + $session we gave our decorator + is the one that we get back and tell the mocks to run their + internal call count tests with the + tally() calls. +

+

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

+

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

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

+

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

+ +

+ +

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(&$test, $wildcard = '*') {
+            $this->BasicMockConnection($test, $wildcard);
+            $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. +

+ +

+ +

I think SimpleTest stinks!

+ +

+

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

+

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

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

+

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

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

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

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. + A released feature is marked as "Done". + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureDescriptionRelease
Unit test caseCore test case class and assertionsDone
Html displaySimplest possible displayDone
Autoloading of test cases + Reading a file with test cases and loading them into a + group test automatically + Done
Mock objects code generator + Objects capable of simulating other objects removing + test dependencies + Done
Server stubs + Mocks without expectations to be used outside of test cases, + e.g. for prototyping + Done
Integration of other unit testers + The ability to read and simulate test cases from PHPUnit + and PEAR::PhpUnit + Done
Web test caseBasic pattern matching of fetched pagesDone
HTML parsing of pagesAllows link following and title tag matchingDone
Partial mocks + Mocking parts of a class for testing less than a class + or for complex simulations + Done
Web cookie handlingCorrect handling of cookies when fetching pagesDone
Following redirectsPage fetching automatically follows 300 redirectsDone
Form parsingAbility to submit simple forms and read default form valuesDone
Command line interfaceTest display without the need of a web browserDone
Exposure of expectation classesCan create precise tests with mocks as well as test casesDone
XML output and parsing + Allows multi host testing and the integration of acceptance + testing extensions + Done
Command line test caseAllows testing of utilities and file handlingDone
PHP Documentor compatibilityFully generated class level documentationDone
Browser interface + Exposure of lower level web browser interface for more + detailed test cases + Done
HTTP authentication + Fetching protected web pages with basic authentication + only + Done
Browser navigation buttonsBack, forward and retryDone
SSL supportCan connect to https: pagesDone
Proxy supportCan connect via. common proxiesDone
Frames supportHandling of frames in web test casesDone
Improved displayBetter web GUI with tree display of test cases1.1
LocalisationMessages abstracted and code generated from XML1.1
File upload testingCan simulate the input type file tag1.1
Mocking interfacesCan generate mock objects to interfaces as well as classes2.0
Testing exceptionsSimilar to testing PHP errors2.0
XPath searching of elementsCan make use of HTML tidy for faster and more flexible content matching2.0
+ PHP5 migraton will start straight after the version 1.1 series, + whereupon PHP4 will no longer be supported. + SimpleTest is currently compatible with PHP5, but will not + make use of all of the new features until version 2. +

+ +

+ +

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

+

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

+

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

+

+ There are plenty of web testing tools, but most are written in Java and + tutorials and advice are rather thin on the ground. + The only hope is to look at the documentation for + HTTPUnit, + HTMLUnit + or JWebUnit and hope for clues. + There are some XML driven test frameworks, but again most + require Java to run. + As SimpleTest does not support JavaScript you would probably + have to look at these tools anyway if you have highly dynamic + pages. +

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/en/partial_mocks_documentation.html b/tests/UnitTests/simpletest/docs/en/partial_mocks_documentation.html new file mode 100644 index 00000000..f4a6af00 --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/partial_mocks_documentation.html @@ -0,0 +1,426 @@ + + + +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/UnitTests/simpletest/docs/en/reporter_documentation.html b/tests/UnitTests/simpletest/docs/en/reporter_documentation.html new file mode 100644 index 00000000..2794c5ab --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/reporter_documentation.html @@ -0,0 +1,515 @@ + + + +SimpleTest for PHP test runner and display documentation + + + + +

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/UnitTests/simpletest/docs/en/server_stubs_documentation.html b/tests/UnitTests/simpletest/docs/en/server_stubs_documentation.html new file mode 100644 index 00000000..445ba63e --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/server_stubs_documentation.html @@ -0,0 +1,388 @@ + + + +SimpleTest for PHP server stubs documentation + + + + +

Server stubs documentation

+
+

+ +

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

+ +

+ +

Creating 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 stub version of the class we need to include the + server stub library and run the generator... +
+require_once('simpletest/mock_objects.php');
+require_once('database_connection.php');
+Stub::generate('DatabaseConnection');
+
+ This generates a clone class called + StubDatabaseConnection. + We can now create instances of the new class within + our prototype script... +
+require_once('simpletest/mock_objects.php');
+require_once('database_connection.php');
+Stub::generate('DatabaseConnection');
+
+$connection = new StubDatabaseConnection();
+
+
+ The stub version of a class has all the methods of the original + so that operations like + $connection->query() are still + legal. + The return value will be null, + but we can change that with... +
+$connection->setReturnValue('query', 37)
+
+ Now every time we call + $connection->query() we get + the result of 37. + We can set the return value to anything, say a hash of + imaginary database results or a list of persistent objects. + Parameters are irrelevant here, we always get the same + values back each time once they have been set up this way. + That may not sound like a convincing replica of a + database connection, but for the half a dozen lines of + a test method it is usually all you need. +

+ +

+ +

Simulation patterns

+ +

+

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

+

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

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

+

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

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

+class Thing {
+}
+
+class Vector {
+    function Vector() {
+    }
+    
+    function get($index) {
+    }
+}
+
+ In this case you can set a reference into the stub's + return list... +
+Stub::generate('Vector');
+
+$thing = new Thing();
+$vector = &new StubVector();
+$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. +

+

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

+$complex = &new StubComplexThing();
+$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 stubbed using the mechanics above. +

+

+ Here's how... +

+Stub::generate('DatabaseConnection');
+Stub::generate('ResultIterator');
+
+class DatabaseTest extends UnitTestCase {
+    
+    function testUserFinder() {
+        $result = &new StubResultIterator();
+        $result->setReturnValue('next', false);
+        $result->setReturnValueAt(0, 'next', array(1, 'tom'));
+        $result->setReturnValueAt(1, 'next', array(3, 'dick'));
+        $result->setReturnValueAt(2, 'next', array(6, 'harry'));
+        
+        $connection = &new StubDatabaseConnection();
+        $connection->setReturnValue('query', false);
+        $connection->setReturnReference(
+                'query',
+                $result,
+                array('select id, name from users'));
+                
+        $finder = &new UserFinder($connection);
+        $this->assertIdentical(
+                $finder->findNames(),
+                array('tom', 'dick', 'harry'));
+    }
+}
+
+ 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. +

+ +

+ +

Stub creation options

+ +

+

+ There are some additional options when creating stubs. + At the generation stage we can change the class name... +

+Stub::generate('Iterator', 'MyStubIterator');
+$iterator = &new MyStubIterator();
+
+
+ This is not very useful in itself as there would be no difference + in this class and the default except for the name. + However we can also add additional methods not found in the + original interface... +
+class Iterator {
+}
+Stub::generate('Iterator', 'PrototypeIterator', array('next', 'isError'));
+$iterator = &new PrototypeIterator();
+$iterator->setReturnValue('next', 0);
+
+
+ The next() and + isError() methods can now have + return values set just as if they existed in the original class. +

+

+ One other esoteric way of customising the stubs is to change + the default wildcard used for parameter matching. +

+Stub::generate('Connection');
+$iterator = &new StubConnection('wild');
+$iterator->setReturnValue('query', array('id' => 33), array('wild'));
+
+
+ The only reason to do this is if you genuinely wanted to test + against the literal string "*" and didn't want it + interpreted as "any". +

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/en/unit_test_documentation.html b/tests/UnitTests/simpletest/docs/en/unit_test_documentation.html new file mode 100644 index 00000000..ddc2f0f0 --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/unit_test_documentation.html @@ -0,0 +1,387 @@ + + + +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
assertIdentical($x, $y)Fail if $x == $y is false or a type mismatch
assertNotIdentical($x, $y)Fail if $x == $y is true and types match
assertReference($x, $y)Fail unless $x and $y are the same variable
assertCopy($x, $y)Fail if $x and $y are the same variable
assertWantedPattern($p, $x)Fail unless the regex $p matches $x
assertNoUnwantedPattern($p, $x)Fail if the regex $p matches $x
assertNoErrors()Fail if any PHP error occoured
assertError($x)Fail if no PHP error or incorrect message
assertErrorPattern($p)Fail unless the error matches the regex $p
+ All assertion methods can take an optional description to + label the displayed result with. + If omitted a default message is sent instead which is usually + sufficient. + This default message can still be embedded in your own message + if you include "%s" within the string. + All the assertions return true on a pass or false on failure. +

+

+ Some examples... +

+$variable = null;
+$this->assertNull($variable, 'Should be cleared');
+
+ ...will pass and normally show no message. + If you have + set up the tester to display passes + as well then the message will be displayed as is. +
+$this->assertIdentical(0, false, 'Zero is not false [%s]');
+
+ This will fail as it performs a type + check as well as a comparison between the two values. + The "%s" part is replaced by the default + error message that would have been shown if we had not + supplied our own. + This also allows us to nest test messages. +
+$a = 1;
+$b = $a;
+$this->assertReference($a, $b);
+
+ Will fail as the variable $a is a copy of $b. +
+$this->assertWantedPattern('/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/UnitTests/simpletest/docs/en/web_tester_documentation.html b/tests/UnitTests/simpletest/docs/en/web_tester_documentation.html new file mode 100644 index 00000000..0ad5303c --- /dev/null +++ b/tests/UnitTests/simpletest/docs/en/web_tester_documentation.html @@ -0,0 +1,508 @@ + + + +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->assertWantedPattern('/why the last craft/i');
+    }
+}
+
+ The page from the last fetch is held in a buffer in + the test case, so there is no need to refer to it directly. + The pattern match is always made against the buffer. +

+

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

+

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

+$this->assertTitle('The Last Craft? Web developer tutorials on PHP, Extreme programming and Object Oriented development');
+
+ As well as the simple HTML content checks we can check + that the MIME type is in a list of allowed types with... +
+$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('About Last Craft');
+    }
+}
+
+ The parameter is the text of the link. +

+

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

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

+

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

+

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

+

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

+

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

+

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

+ +

+ +

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/UnitTests/simpletest/docs/fr/authentication_documentation.html b/tests/UnitTests/simpletest/docs/fr/authentication_documentation.html new file mode 100644 index 00000000..39e21421 --- /dev/null +++ b/tests/UnitTests/simpletest/docs/fr/authentication_documentation.html @@ -0,0 +1,264 @@ + + + +Documentation Simple Test : tester l'authentification + + + + +

Documentation sur l'authentification

+
+ +

+ Un des secteurs à la fois délicat et important lors d'un test de site web reste la sécurité. Tester ces schémas est au coeur des objectifs du testeur web de SimpleTest. +

+ +

+ +

Authentification HTTP basique

+ +

+

+ Si vous allez chercher une page web protégée par une authentification basique, vous hériterez d'une entête 401. Nous pouvons représenter ceci par ce test... +

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

File test

+
+HTTP/1.1 401 Authorization Required
+Date: Sat, 18 Sep 2004 19:25:18 GMT
+Server: Apache/1.3.29 (Unix) PHP/4.3.4
+WWW-Authenticate: Basic realm="SimpleTest basic authentication"
+Connection: close
+Content-Type: text/html; charset=iso-8859-1
+
+
1/1 test cases complete. + 0 passes, 0 fails and 0 exceptions.
+
+ Sauf que nous voulons éviter l'inspection visuelle, on souhaite que SimpleTest puisse nous dire si oui ou non la page est protégée. Voici un test en profondeur sur nos entêtes... +
+class AuthenticationTest extends WebTestCase {
+    function test401Header() {
+        $this->get('http://www.lastcraft.com/protected/');
+        $this->assertAuthentication('Basic');
+        $this->assertResponse(401);
+        $this->assertRealm('SimpleTest basic authentication');
+    }
+}
+
+ N'importe laquelle de ces assertions suffirait, tout dépend de la masse de détails que vous souhaitez voir. +

+

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

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

+

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

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

+

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

+ +

+ +

Cookies

+ +

+

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

+

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

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

+

+

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

+

+ Supposons que, durant le chargement de la page, un cookie ait été inscrit avec un numéro d'identifiant de session. Nous n'allons pas encore remplir le formulaire, juste tester que nous pistons bien l'utilisateur. Voici le test... +

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

+

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

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

+

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

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

+ +

+ +

Sessions de navigateur

+ +

+

+ Si vous testez un système d'authentification, la reconnexion par un utilisateur est un point sensible. Essayons de simuler ce qui se passe dans ce cas : +

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

+

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

+

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

+class LogInTest extends WebTestCase {
+    ...
+    function testLoseAuthenticationAfterOneHour() {
+        $this->get('http://www.my-site.com/login.php');
+        $this->setField('u', 'Me');
+        $this->setField('p', 'Secret');
+        $this->clickSubmit('Log in');
+        $this->assertWantedPattern('/Welcome Me/');
+        
+        $this->ageCookies(3600);
+        $this->restart();
+        $this->get('http://www.my-site.com/restricted.php');
+        $this->assertWantedPattern('/Access denied/');
+    }
+}
+
+ Après le redémarrage, les cookies seront plus vieux d'une heure et que tous ceux dont la date d'expiration sera passée auront disparus. +

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

Documentation sur le navigateur scriptable

+
+ +

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

+ +

+ +

Le navigateur scriptable

+ +

+

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

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

+

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

+

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

+

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

+ +

+ +

Où sont les erreurs ?

+ +

+

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

+ +

+ +

Tests unitaires complexes avec des navigateurs multiples

+ +

+

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

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

+

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

+

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

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

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/fr/docs.css b/tests/UnitTests/simpletest/docs/fr/docs.css new file mode 100644 index 00000000..c59b9cd2 --- /dev/null +++ b/tests/UnitTests/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/UnitTests/simpletest/docs/fr/expectation_documentation.html b/tests/UnitTests/simpletest/docs/fr/expectation_documentation.html new file mode 100644 index 00000000..bbadfa02 --- /dev/null +++ b/tests/UnitTests/simpletest/docs/fr/expectation_documentation.html @@ -0,0 +1,263 @@ + + + +Documentation SimpleTest : étendre le testeur unitaire avec des classes d'attentes supplémentaires + + + + +

Documentation sur les attentes

+
+

+ +

Plus de contrôle sur les objets fantaisie

+ +

+

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

+

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

+

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

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

+

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

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

+

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

+

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

+ +

+ +

Utiliser les attentes pour contrôler les bouchons serveur

+ +

+

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

+

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

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

+

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

+ +

+ +

Créer vos propres attentes

+ +

+

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

+

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

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

+

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

+ +

+ +

Sous le capot du testeur unitaire

+ +

+

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

+

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

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

+

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

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

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/fr/form_testing_documentation.html b/tests/UnitTests/simpletest/docs/fr/form_testing_documentation.html new file mode 100644 index 00000000..39ec01ce --- /dev/null +++ b/tests/UnitTests/simpletest/docs/fr/form_testing_documentation.html @@ -0,0 +1,235 @@ + + + +Documentation SimpleTest : tester des formulaires HTML + + + + +

Documentation sur les tests de formulaire

+
+

+ +

Valider un formulaire simple

+ +

+

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

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

+

+

+ + +
+

+

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

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

+

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

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

+

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

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

+

+

+ Select type of user to add: + +
+

+

+ Le test suivant le confirmera... +

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

+

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

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

+

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

+ +

+ +

Champs à valeurs multiples

+ +

+

+ SimpleTest peut gérer deux types de commandes à valeur multiple : les menus déroulants à sélection multiple et les cases à cocher avec le même nom à l'intérieur même d'un formulaire. La nature de ceux-ci implique que leur initialisation et leur test sont légèrement différents. Voici un exemple avec des cases à cocher... +

+<form class="demo">
+    <strong>Create privileges allowed:</strong>
+    <input type="checkbox" name="crud" value="c" checked><br>
+    <strong>Retrieve privileges allowed:</strong>
+    <input type="checkbox" name="crud" value="r" checked><br>
+    <strong>Update privileges allowed:</strong>
+    <input type="checkbox" name="crud" value="u" checked><br>
+    <strong>Destroy privileges allowed:</strong>
+    <input type="checkbox" name="crud" value="d" checked><br>
+    <input type="submit" value="Enable Privileges">
+</form>
+
+ Qui se traduit par... +

+

+

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

+

+ Si nous souhaitons désactiver tous les privilèges sauf ceux de téléchargement (Retrieve) et transmettre cette information, nous pouvons y arriver par... +

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

+

+ +

Envoi brut

+ +

+

+ Si vous souhaitez tester un gestionnaire de formulaire mais que vous ne l'avez pas écrit ou que vous n'y avez pas encore accès, vous pouvez créer un envoi de formulaire à la main. +

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

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/fr/group_test_documentation.html b/tests/UnitTests/simpletest/docs/fr/group_test_documentation.html new file mode 100644 index 00000000..b406f21e --- /dev/null +++ b/tests/UnitTests/simpletest/docs/fr/group_test_documentation.html @@ -0,0 +1,288 @@ + + + +Documentation SimpleTest : Grouper des tests + + + + +

Documentation sur le groupement des tests

+
+

+ +

Grouper des tests

+ +

+

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

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

+

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

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

+

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

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

+

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

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

+ +

+ +

Groupements de plus haut niveau

+ +

+

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

+

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

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

+ +

+ +

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

+ +

+

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

+

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

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

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

Simple Test pour PHP

+
+ +

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

+ +

+ +

Utiliser le testeur rapidement

+ +

+

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

+

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

+

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

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

+

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

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

+

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

+

testoflogging

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

testoflogging

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

+ +

+ +

Construire des groupes de tests

+ +

+

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

+

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

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

+

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

+

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

+ +

+ +

Utiliser les objets fantaisie

+ +

+

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

+

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

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

+

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

+

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

+

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

+

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

+

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

+ +

+ +

Tester une page web

+ +

+

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

+

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

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

+

+ SourceForge.net Logo +

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/fr/mock_objects_documentation.html b/tests/UnitTests/simpletest/docs/fr/mock_objects_documentation.html new file mode 100644 index 00000000..1a836083 --- /dev/null +++ b/tests/UnitTests/simpletest/docs/fr/mock_objects_documentation.html @@ -0,0 +1,492 @@ + + + +Documentation SimpleTest : les objets fantaise + + + + +

Documentation sur les objets fantaisie

+
+

+ +

Que sont les objets fantaisie ?

+ +

+

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

+

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

+

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

+

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

+ +

+ +

Créer des objets fantaisie

+ +

+

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

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

+

+ +

Objets fantaisie en action

+ +

+

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

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

+

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

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

+

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

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

+

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

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

+ +

+ +

Objets fantaisie en critique

+ +

+

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

+

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

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

+

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

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

+

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

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

+

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

+

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

+

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

+

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

+

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

+

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

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

+

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

+ +

+ +

D'autres approches

+ +

+

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

+

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

+

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

+

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

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

+

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

+ +

+ +

Je pense que SimpleTest pue !

+ +

+

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

+

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

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

+

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

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

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

Apercu de SimpleTest

+
+

+ +

Qu'est-ce que SimpleTest ?

+ +

+

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

+

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

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

+

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

+

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

+

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

+

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

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

+ +

+ +

Liste des fonctionnalites

+ +

+

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

+ +

+ +

Ressources sur le web pour les tests

+ +

+

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

+

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

+

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

+

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

+

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

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/fr/partial_mocks_documentation.html b/tests/UnitTests/simpletest/docs/fr/partial_mocks_documentation.html new file mode 100644 index 00000000..e71bffdb --- /dev/null +++ b/tests/UnitTests/simpletest/docs/fr/partial_mocks_documentation.html @@ -0,0 +1,333 @@ + + + +Documentation SimpleTest : les objets fantaisie partiels + + + + +

Documentation sur les objets fantaisie partiels

+
+ +

+ Un objet fantaisie partiel n'est ni plus ni moins qu'un modèle de conception pour soulager un problème spécifique du test avec des objets fantaisie, celui de placer des objets fantaisie dans des coins serrés. Il s'agit d'un outil assez limité et peut-être même une idée pas si bonne que ça. Elle est incluse dans SimpleTest pour la simple raison que je l'ai trouvée utile à plus d'une occasion et qu'elle m'a épargnée pas mal de travail dans ces moments-là. +

+ +

+ +

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

+ +

+

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

+

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

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

+

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

+

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

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

+

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

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

+

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

+<?php
+    require_once('socket.php');
+    
+    class Telnet {
+        function Telnet(&$network) {
+            $this->_network = &$network;
+        }
+        ...
+        function &connect($ip, $port, $username, $password) {
+            $socket = &$this->_network->createSocket($ip, $port);
+            $socket->read( ... );
+            ...
+            return $socket;
+        }
+    }
+?>
+
+ Il s'agit là probablement de la réponse la plus travaillée étant donné que la création est maintenant située dans une petite classe spécialisée. La fabrique réseau peut être testée séparément et utilisée en tant que fantaisie quand nous testons la classe telnet... +
+class TelnetTest extends UnitTestCase {
+    ...
+    function testConnection() {
+        $socket = &new MockSocket($this);
+        ...
+        $network = &new MockNetwork($this);
+        $network->setReturnReference('createSocket', $socket);
+        $telnet = &new Telnet($network);
+        $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
+        ...
+    }
+}
+
+ Le problème reste que nous ajoutons beaucoup de classes à la bibliothèque. Et aussi que nous utilisons beaucoup de fabriques ce qui rend notre code un peu moins intuitif. La solution la plus flexible, mais aussi la plus complexe. +

+

+ Peut-on trouver un juste milieu ? +

+ +

+ +

Méthode fabrique protégée

+ +

+

+ Il existe une technique pour palier à ce problème sans créer de nouvelle classe dans l'application; par contre elle induit la création d'une sous-classe au moment du test. Premièrement nous déplaçons la création de la socket dans sa propre méthode... +

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

+

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

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

+

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

+class TelnetTest extends UnitTestCase {
+    ...
+    function testConnection() {
+        $socket = &new MockSocket($this);
+        ...
+        $telnet = &new TelnetTestVersion($socket);
+        $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
+        ...
+    }
+}
+
+ Cette nouvelle classe est très simple bien sûr. Elle ne fait qu'initier une valeur renvoyée, à la manière d'une fantaisie. Ce serait pas mal non plus si elle pouvait vérifier les paramètres entrants. Exactement comme un objet fantaisie. Il se pourrait bien que nous ayons à réaliser cette astuce régulièrement : serait-il possible d'automatiser la création de cette sous-classe ? +

+ +

+ +

Un objet fantaisie partiel

+ +

+

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

+

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

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

+

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

+

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

+

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

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

+ +

+ +

Tester moins qu'une classe

+ +

+

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

+

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

+

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

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/fr/reporter_documentation.html b/tests/UnitTests/simpletest/docs/fr/reporter_documentation.html new file mode 100644 index 00000000..86c1607c --- /dev/null +++ b/tests/UnitTests/simpletest/docs/fr/reporter_documentation.html @@ -0,0 +1,386 @@ + + + +Documentation SimpleTest : le rapporteur de test + + + + +

Documentation sur le rapporteur de test

+
+ +

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

+ +

+ +

Les résultats rapportés au format HTML

+ +

+

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

+

File test

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

File test

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

+

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

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

+

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

+

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

+ +

+ +

Etendre le rapporteur

+ +

+

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

+

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

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

+ +

+ +

Le rapporteur en ligne de commande

+ +

+

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

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

+

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

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

+ +

+ +

Test distant

+ +

+

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

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

+

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

+

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

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

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/fr/server_stubs_documentation.html b/tests/UnitTests/simpletest/docs/fr/server_stubs_documentation.html new file mode 100644 index 00000000..f5ddcc04 --- /dev/null +++ b/tests/UnitTests/simpletest/docs/fr/server_stubs_documentation.html @@ -0,0 +1,279 @@ + + + +Documentation SimpleTest : les bouchons serveur + + + + +

Documentation sur les bouchons serveur

+
+

+ +

Que sont les bouchons serveur ?

+ +

+

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

+ +

+ +

Créer des bouchons serveur

+ +

+

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

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

+ +

+ +

Modèles de simulation

+ +

+

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

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

+

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

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

+

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

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

+

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

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

+

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

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

+

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

+

+ Voici comment... +

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

+ +

+ +

Options de création pour les bouchons

+ +

+

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

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

+

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

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

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/fr/unit_test_documentation.html b/tests/UnitTests/simpletest/docs/fr/unit_test_documentation.html new file mode 100644 index 00000000..fbbd728b --- /dev/null +++ b/tests/UnitTests/simpletest/docs/fr/unit_test_documentation.html @@ -0,0 +1,306 @@ + + + +Documenation SimpleTest pour les tests de régression en PHP + + + + +

Documentation sur les tests unitaires en PHP

+
+

+ +

Scénarios de tests unitaires

+ +

+

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

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

+

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

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

+

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

+

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

+

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

+

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

+

+ D'autres exemples... +

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

+

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

+

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

+ +

+ +

Etendre les scénarios de test

+ +

+

+ Bien sûr des méthodes supplémentaires de test peuvent être ajoutées pour créer d'autres types de scénario de test afin d'étendre le framework... +

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

+

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

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

+

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

+ +

+ +

Lancer un unique scénario de test

+ +

+

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

+<?php
+    require_once('simpletest/unit_tester.php');
+    require_once('simpletest/reporter.php');
+    require_once('../classes/writer.php');
+
+    class FileTestCase extends UnitTestCase {
+        function FileTestCase() {
+            $this->UnitTestCase('File test');
+        }
+    }
+    
+    $test = &new FileTestCase();
+    $test->run(new HtmlReporter());
+?>
+
+ Ce script sera lancé tel que mais il n'y aura aucun succès ou échec avant que des méthodes de test soient ajoutées. +

+ +
+ + + diff --git a/tests/UnitTests/simpletest/docs/fr/web_tester_documentation.html b/tests/UnitTests/simpletest/docs/fr/web_tester_documentation.html new file mode 100644 index 00000000..7a2603a0 --- /dev/null +++ b/tests/UnitTests/simpletest/docs/fr/web_tester_documentation.html @@ -0,0 +1,397 @@ + + + +Documentation SimpleTest : tester des scripts web + + + + +

Documentation sur le testeur web

+
+

+ +

Télécharger une page

+ +

+

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

+

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

+

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

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

+

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

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

+

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

+Web site tests
+OK
+Test cases run: 1/1, Failures: 0, Exceptions: 0
+
+ Nous avons vérifié qu'une page, de n'importe quel type, a bien été renvoyée. Nous ne savons pas encore s'il s'agit de celle que nous souhaitions. +

+ +

+ +

Tester le contenu d'une page

+ +

+

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

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

+

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

+

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

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

+ +

+ +

Navigeur dans un site web

+ +

+

+ Les utilisateurs ne naviguent pas souvent en tapant les URLs, mais surtout en cliquant sur des liens et des boutons. Ici nous confirmons que les informations sur le contact peuvent être atteintes depuis la page d'accueil... +

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

+

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

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

+

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

+

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

+

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

+

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

+

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

+ +

+ +

Modifier la requête

+ +

+

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

+ +
+ + + diff --git a/tests/UnitTests/simpletest/dumper.php b/tests/UnitTests/simpletest/dumper.php new file mode 100644 index 00000000..d6182e36 --- /dev/null +++ b/tests/UnitTests/simpletest/dumper.php @@ -0,0 +1,380 @@ +getType($value); + switch($type) { + case "Null": + return "NULL"; + case "Boolean": + return "Boolean: " . ($value ? "true" : "false"); + case "Array": + return "Array: " . count($value) . " items"; + case "Object": + return "Object: of " . get_class($value); + case "String": + return "String: " . $this->clipString($value, 100); + default: + return "$type: $value"; + } + return "Unknown"; + } + + /** + * Gets the string representation of a type. + * @param mixed $value Variable to check against. + * @return string Type. + * @access public + */ + function getType($value) { + if (! isset($value)) { + return "Null"; + } elseif (is_bool($value)) { + return "Boolean"; + } elseif (is_string($value)) { + return "String"; + } elseif (is_integer($value)) { + return "Integer"; + } elseif (is_float($value)) { + return "Float"; + } elseif (is_array($value)) { + return "Array"; + } elseif (is_resource($value)) { + return "Resource"; + } elseif (is_object($value)) { + return "Object"; + } + return "Unknown"; + } + + /** + * Creates a human readable description of the + * difference between two variables. Uses a + * dynamic call. + * @param mixed $first First variable. + * @param mixed $second Value to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Description of difference. + * @access public + */ + function describeDifference($first, $second, $identical = false) { + if ($identical) { + if (! $this->_isTypeMatch($first, $second)) { + return "with type mismatch as [" . $this->describeValue($first) . + "] does not match [" . $this->describeValue($second) . "]"; + } + } + $type = $this->getType($first); + if ($type == "Unknown") { + return "with unknown type"; + } + $method = '_describe' . $type . 'Difference'; + return $this->$method($first, $second, $identical); + } + + /** + * Tests to see if types match. + * @param mixed $first First variable. + * @param mixed $second Value to compare with. + * @return boolean True if matches. + * @access private + */ + function _isTypeMatch($first, $second) { + return ($this->getType($first) == $this->getType($second)); + } + + /** + * Clips a string to a maximum length. + * @param string $value String to truncate. + * @param integer $size Minimum string size to show. + * @param integer $position Centre of string section. + * @return string Shortened version. + * @access public + */ + function clipString($value, $size, $position = 0) { + $length = strlen($value); + if ($length <= $size) { + return $value; + } + $position = min($position, $length); + $start = ($size/2 > $position ? 0 : $position - $size/2); + if ($start + $size > $length) { + $start = $length - $size; + } + $value = substr($value, $start, $size); + return ($start > 0 ? "..." : "") . $value . ($start + $size < $length ? "..." : ""); + } + + /** + * Creates a human readable description of the + * difference between two variables. The minimal + * version. + * @param null $first First value. + * @param mixed $second Value to compare with. + * @return string Human readable description. + * @access private + */ + function _describeGenericDifference($first, $second) { + return "as [" . $this->describeValue($first) . + "] does not match [" . + $this->describeValue($second) . "]"; + } + + /** + * Creates a human readable description of the + * difference between a null and another variable. + * @param null $first First null. + * @param mixed $second Null to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeNullDifference($first, $second, $identical) { + return $this->_describeGenericDifference($first, $second); + } + + /** + * Creates a human readable description of the + * difference between a boolean and another variable. + * @param boolean $first First boolean. + * @param mixed $second Boolean to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeBooleanDifference($first, $second, $identical) { + return $this->_describeGenericDifference($first, $second); + } + + /** + * Creates a human readable description of the + * difference between a string and another variable. + * @param string $first First string. + * @param mixed $second String to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeStringDifference($first, $second, $identical) { + if (is_object($second) || is_array($second)) { + return $this->_describeGenericDifference($first, $second); + } + $position = $this->_stringDiffersAt($first, $second); + $message = "at character $position"; + $message .= " with [" . + $this->clipString($first, 100, $position) . "] and [" . + $this->clipString($second, 100, $position) . "]"; + return $message; + } + + /** + * Creates a human readable description of the + * difference between an integer and another variable. + * @param integer $first First number. + * @param mixed $second Number to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeIntegerDifference($first, $second, $identical) { + if (is_object($second) || is_array($second)) { + return $this->_describeGenericDifference($first, $second); + } + return "because [" . $this->describeValue($first) . + "] differs from [" . + $this->describeValue($second) . "] by " . + abs($first - $second); + } + + /** + * Creates a human readable description of the + * difference between two floating point numbers. + * @param float $first First float. + * @param mixed $second Float to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeFloatDifference($first, $second, $identical) { + if (is_object($second) || is_array($second)) { + return $this->_describeGenericDifference($first, $second); + } + return "because " . $this->describeValue($first) . + "] differs from [" . + $this->describeValue($second) . "]"; + } + + /** + * Creates a human readable description of the + * difference between two arrays. + * @param array $first First array. + * @param mixed $second Array to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeArrayDifference($first, $second, $identical) { + if (! is_array($second)) { + return $this->_describeGenericDifference($first, $second); + } + if (! $this->_isMatchingKeys($first, $second, $identical)) { + return "as key list [" . + implode(", ", array_keys($first)) . "] does not match key list [" . + implode(", ", array_keys($second)) . "]"; + } + foreach (array_keys($first) as $key) { + if ($identical && ($first[$key] === $second[$key])) { + continue; + } + if (! $identical && ($first[$key] == $second[$key])) { + continue; + } + return "with member [$key] " . $this->describeDifference( + $first[$key], + $second[$key], + $identical); + } + return ""; + } + + /** + * Compares two arrays to see if their key lists match. + * For an identical match, the ordering and types of the keys + * is significant. + * @param array $first First array. + * @param array $second Array to compare with. + * @param boolean $identical If true then type anomolies count. + * @return boolean True if matching. + * @access private + */ + function _isMatchingKeys($first, $second, $identical) { + $first_keys = array_keys($first); + $second_keys = array_keys($second); + if ($identical) { + return ($first_keys === $second_keys); + } + sort($first_keys); + sort($second_keys); + return ($first_keys == $second_keys); + } + + /** + * Creates a human readable description of the + * difference between a resource and another variable. + * @param resource $first First resource. + * @param mixed $second Resource to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeResourceDifference($first, $second, $identical) { + return $this->_describeGenericDifference($first, $second); + } + + /** + * Creates a human readable description of the + * difference between two objects. + * @param object $first First object. + * @param mixed $second Object to compare with. + * @param boolean $identical If true then type anomolies count. + * @return string Human readable description. + * @access private + */ + function _describeObjectDifference($first, $second, $identical) { + if (! is_object($second)) { + return $this->_describeGenericDifference($first, $second); + } + return $this->_describeArrayDifference( + get_object_vars($first), + get_object_vars($second), + $identical); + } + + /** + * Find the first character position that differs + * in two strings by binary chop. + * @param string $first First string. + * @param string $second String to compare with. + * @return integer Position of first differing + * character. + * @access private + */ + function _stringDiffersAt($first, $second) { + if (! $first || ! $second) { + return 0; + } + if (strlen($first) < strlen($second)) { + list($first, $second) = array($second, $first); + } + $position = 0; + $step = strlen($first); + while ($step > 1) { + $step = (integer)(($step + 1)/2); + if (strncmp($first, $second, $position + $step) == 0) { + $position += $step; + } + } + return $position; + } + + /** + * Sends a formatted dump of a variable to a string. + * @param mixed $variable Variable to display. + * @return string Output from print_r(). + * @access public + * @static + */ + function dump($variable) { + ob_start(); + print_r($variable); + $formatted = ob_get_contents(); + ob_end_clean(); + return $formatted; + } + + /** + * Extracts the last assertion that was not within + * Simpletest itself. The name must start with "assert". + * @param array $stack List of stack frames. + * @param string $format String formatting. + * @param string $prefix Prefix of method to search for. + * @access public + * @static + */ + function getFormattedAssertionLine($stack, $format = '%d', $prefix = 'assert') { + foreach ($stack as $frame) { + if (isset($frame['file']) && strpos($frame['file'], 'simpletest') !== false) { // dirname() is a bit slow. + if (substr(dirname($frame['file']), -10) == 'simpletest') { + continue; + } + } + if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) { + return sprintf($format, $frame['line']); + } + } + return ''; + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/encoding.php b/tests/UnitTests/simpletest/encoding.php new file mode 100644 index 00000000..fd2d918a --- /dev/null +++ b/tests/UnitTests/simpletest/encoding.php @@ -0,0 +1,156 @@ +_request = array(); + $this->setCoordinates(); + $this->merge($query); + } + + /** + * Adds a parameter to the query. + * @param string $key Key to add value to. + * @param string/array $value New data. + * @access public + */ + function add($key, $value) { + if ($value === false) { + return; + } + if (! isset($this->_request[$key])) { + $this->_request[$key] = array(); + } + if (is_array($value)) { + foreach ($value as $item) { + $this->_request[$key][] = $item; + } + } else { + $this->_request[$key][] = $value; + } + } + + /** + * Adds a set of parameters to this query. + * @param array/SimpleQueryString $query Multiple values are + * as lists on a single key. + * @access public + */ + function merge($query) { + if (is_object($query)) { + foreach ($query->getKeys() as $key) { + $this->add($key, $query->getValue($key)); + } + if ($query->getX() !== false) { + $this->setCoordinates($query->getX(), $query->getY()); + } + } elseif (is_array($query)) { + foreach ($query as $key => $value) { + $this->add($key, $value); + } + } + } + + /** + * Sets image coordinates. Set to false to clear + * them. + * @param integer $x Horizontal position. + * @param integer $y Vertical position. + * @access public + */ + function setCoordinates($x = false, $y = false) { + if (($x === false) || ($y === false)) { + $this->_x = $this->_y = false; + return; + } + $this->_x = (integer)$x; + $this->_y = (integer)$y; + } + + /** + * Accessor for horizontal image coordinate. + * @return integer X value. + * @access public + */ + function getX() { + return $this->_x; + } + + /** + * Accessor for vertical image coordinate. + * @return integer Y value. + * @access public + */ + function getY() { + return $this->_y; + } + + /** + * Accessor for single value. + * @return string/array False if missing, string + * if present and array if + * multiple entries. + * @access public + */ + function getValue($key) { + if (! isset($this->_request[$key])) { + return false; + } elseif (count($this->_request[$key]) == 1) { + return $this->_request[$key][0]; + } else { + return $this->_request[$key]; + } + } + + /** + * Accessor for key list. + * @return array List of keys present. + * @access public + */ + function getKeys() { + return array_keys($this->_request); + } + + /** + * Renders the query string as a URL encoded + * request part. + * @return string Part of URL. + * @access public + */ + function asString() { + $statements = array(); + foreach ($this->_request as $key => $values) { + foreach ($values as $value) { + $statements[] = "$key=" . urlencode($value); + } + } + $coords = ($this->_x !== false) ? '?' . $this->_x . ',' . $this->_y : ''; + return implode('&', $statements) . $coords; + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/errors.php b/tests/UnitTests/simpletest/errors.php new file mode 100644 index 00000000..a1fbe546 --- /dev/null +++ b/tests/UnitTests/simpletest/errors.php @@ -0,0 +1,141 @@ +clear(); + } + + /** + * Adds an error to the front of the queue. + * @param $severity PHP error code. + * @param $message Text of error. + * @param $filename File error occoured in. + * @param $line Line number of error. + * @param $super_globals Hash of PHP super global arrays. + * @access public + */ + function add($severity, $message, $filename, $line, $super_globals) { + array_push( + $this->_queue, + array($severity, $message, $filename, $line, $super_globals)); + } + + /** + * Pulls the earliest error from the queue. + * @return False if none, or a list of error + * information. Elements are: severity + * as the PHP error code, the error message, + * the file with the error, the line number + * and a list of PHP super global arrays. + * @access public + */ + function extract() { + if (count($this->_queue)) { + return array_shift($this->_queue); + } + return false; + } + + /** + * Discards the contents of the error queue. + * @access public + */ + function clear() { + $this->_queue = array(); + } + + /** + * Tests to see if the queue is empty. + * @return True if empty. + */ + function isEmpty() { + return (count($this->_queue) == 0); + } + + /** + * Global access to a single error queue. + * @return Global error queue object. + * @access public + * @static + */ + static function instance() { + static $queue = false; + if (! $queue) { + $queue = new SimpleErrorQueue(); + } + return $queue; + } + + /** + * Converst an error code into it's string + * representation. + * @param $severity PHP integer error code. + * @return String version of error code. + * @access public + * @static + */ + static function getSeverityAsString($severity) { + static $map = array( + E_STRICT => 'E_STRICT', + E_ERROR => 'E_ERROR', + E_WARNING => 'E_WARNING', + E_PARSE => 'E_PARSE', + E_NOTICE => 'E_NOTICE', + E_CORE_ERROR => 'E_CORE_ERROR', + E_CORE_WARNING => 'E_CORE_WARNING', + E_COMPILE_ERROR => 'E_COMPILE_ERROR', + E_COMPILE_WARNING => 'E_COMPILE_WARNING', + E_USER_ERROR => 'E_USER_ERROR', + E_USER_WARNING => 'E_USER_WARNING', + E_USER_NOTICE => 'E_USER_NOTICE'); + return $map[$severity]; + } + } + + /** + * Error handler that simply stashes any errors into the global + * error queue. Simulates the existing behaviour with respect to + * logging errors, but this feature may be removed in future. + * @param $severity PHP error code. + * @param $message Text of error. + * @param $filename File error occoured in. + * @param $line Line number of error. + * @param $super_globals Hash of PHP super global arrays. + * @static + * @access public + */ + function simpleTestErrorHandler($severity, $message, $filename, $line, $super_globals) { + if ($severity = $severity & error_reporting()) { + restore_error_handler(); + if (ini_get('log_errors')) { + $label = SimpleErrorQueue::getSeverityAsString($severity); + error_log("$label: $message in $filename on line $line"); + } + $queue = SimpleErrorQueue::instance(); + $queue->add($severity, $message, $filename, $line, $super_globals); + set_error_handler('simpleTestErrorHandler'); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/expectation.php b/tests/UnitTests/simpletest/expectation.php new file mode 100644 index 00000000..ffc61376 --- /dev/null +++ b/tests/UnitTests/simpletest/expectation.php @@ -0,0 +1,568 @@ +_dumper = new SimpleDumper(); + $this->_message = $message; + } + + /** + * Tests the expectation. True if correct. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + * @abstract + */ + function test($compare) { + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + * @abstract + */ + function testMessage($compare) { + } + + /** + * Overlays the generated message onto the stored user + * message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function overlayMessage($compare) { + return sprintf($this->_message, $this->testMessage($compare)); + } + + /** + * Accessor for the dumper. + * @return SimpleDumper Current value dumper. + * @access protected + */ + function _getDumper() { + return $this->_dumper; + } + } + + /** + * Test for equality. + * @package SimpleTest + * @subpackage UnitTester + */ + class EqualExpectation extends SimpleExpectation { + protected $_value; + + /** + * Sets the value to compare against. + * @param mixed $value Test value to match. + * @param string $message Customised message on failure. + * @access public + */ + function EqualExpectation($value, $message = '%s') { + $this->SimpleExpectation($message); + $this->_value = $value; + } + + /** + * Tests the expectation. True if it matches the + * held value. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return (($this->_value == $compare) && ($compare == $this->_value)); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if ($this->test($compare)) { + return "Equal expectation [" . $this->_dumper->describeValue($this->_value) . "]"; + } else { + return "Equal expectation fails " . + $this->_dumper->describeDifference($this->_value, $compare); + } + } + + /** + * Accessor for comparison value. + * @return mixed Held value to compare with. + * @access protected + */ + function _getValue() { + return $this->_value; + } + } + + /** + * Test for inequality. + * @package SimpleTest + * @subpackage UnitTester + */ + class NotEqualExpectation extends EqualExpectation { + + /** + * Sets the value to compare against. + * @param mixed $value Test value to match. + * @param string $message Customised message on failure. + * @access public + */ + function NotEqualExpectation($value, $message = '%s') { + $this->EqualExpectation($value, $message); + } + + /** + * Tests the expectation. True if it differs from the + * held value. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return ! parent::test($compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = $this->_getDumper(); + if ($this->test($compare)) { + return "Not equal expectation passes " . + $dumper->describeDifference($this->_getValue(), $compare); + } else { + return "Not equal expectation fails [" . + $dumper->describeValue($this->_getValue()) . + "] matches"; + } + } + } + + /** + * Test for identity. + * @package SimpleTest + * @subpackage UnitTester + */ + class IdenticalExpectation extends EqualExpectation { + + /** + * Sets the value to compare against. + * @param mixed $value Test value to match. + * @param string $message Customised message on failure. + * @access public + */ + function IdenticalExpectation($value, $message = '%s') { + $this->EqualExpectation($value, $message); + } + + /** + * Tests the expectation. True if it exactly + * matches the held value. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return SimpleTestCompatibility::isIdentical($this->_getValue(), $compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = $this->_getDumper(); + if ($this->test($compare)) { + return "Identical expectation [" . $dumper->describeValue($this->_getValue()) . "]"; + } else { + return "Identical expectation [" . $dumper->describeValue($this->_getValue()) . + "] fails with [" . + $dumper->describeValue($compare) . "] " . + $dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS); + } + } + } + + /** + * Test for non-identity. + * @package SimpleTest + * @subpackage UnitTester + */ + class NotIdenticalExpectation extends IdenticalExpectation { + + /** + * Sets the value to compare against. + * @param mixed $value Test value to match. + * @param string $message Customised message on failure. + * @access public + */ + function NotIdenticalExpectation($value, $message = '%s') { + $this->IdenticalExpectation($value, $message); + } + + /** + * Tests the expectation. True if it differs from the + * held value. + * @param mixed $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return ! parent::test($compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = $this->_getDumper(); + if ($this->test($compare)) { + return "Not identical expectation passes " . + $dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS); + } else { + return "Not identical expectation [" . $dumper->describeValue($this->_getValue()) . "] matches"; + } + } + } + + /** + * Test for a pattern using Perl regex rules. + * @package SimpleTest + * @subpackage UnitTester + */ + class WantedPatternExpectation extends SimpleExpectation { + protected $_pattern; + + /** + * Sets the value to compare against. + * @param string $pattern Pattern to search for. + * @param string $message Customised message on failure. + * @access public + */ + function WantedPatternExpectation($pattern, $message = '%s') { + $this->SimpleExpectation($message); + $this->_pattern = $pattern; + } + + /** + * Accessor for the pattern. + * @return string Perl regex as string. + * @access protected + */ + function _getPattern() { + return $this->_pattern; + } + + /** + * Tests the expectation. True if the Perl regex + * matches the comparison value. + * @param string $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return (boolean)preg_match($this->_getPattern(), $compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if ($this->test($compare)) { + return $this->_describePatternMatch($this->_getPattern(), $compare); + } else { + $dumper = $this->_getDumper(); + return "Pattern [" . $this->_getPattern() . + "] not detected in [" . + $dumper->describeValue($compare) . "]"; + } + } + + /** + * Describes a pattern match including the string + * found and it's position. + * @param string $pattern Regex to match against. + * @param string $subject Subject to search. + * @access protected + */ + function _describePatternMatch($pattern, $subject) { + preg_match($pattern, $subject, $matches); + $position = strpos($subject, $matches[0]); + $dumper = $this->_getDumper(); + return "Pattern [$pattern] detected at character [$position] in [" . + $dumper->describeValue($subject) . "] as [" . + $matches[0] . "] in region [" . + $dumper->clipString($subject, 100, $position) . "]"; + } + } + + /** + * Fail if a pattern is detected within the + * comparison. + * @package SimpleTest + * @subpackage UnitTester + */ + class UnwantedPatternExpectation extends WantedPatternExpectation { + + /** + * Sets the reject pattern + * @param string $pattern Pattern to search for. + * @param string $message Customised message on failure. + * @access public + */ + function UnwantedPatternExpectation($pattern, $message = '%s') { + $this->WantedPatternExpectation($pattern, $message); + } + + /** + * Tests the expectation. False if the Perl regex + * matches the comparison value. + * @param string $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return ! parent::test($compare); + } + + /** + * Returns a human readable test message. + * @param string $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + if ($this->test($compare)) { + $dumper = $this->_getDumper(); + return "Pattern [" . $this->_getPattern() . + "] not detected in [" . + $dumper->describeValue($compare) . "]"; + } else { + return $this->_describePatternMatch($this->_getPattern(), $compare); + } + } + } + + /** + * Tests either type or class name if it's an object. + * @package SimpleTest + * @subpackage UnitTester + */ + class IsAExpectation extends SimpleExpectation { + protected $_type; + + /** + * Sets the type to compare with. + * @param string $type Type or class name. + * @param string $message Customised message on failure. + * @access public + */ + function IsAExpectation($type, $message = '%s') { + $this->SimpleExpectation($message); + $this->_type = $type; + } + + /** + * Accessor for type to check against. + * @return string Type or class name. + * @access protected + */ + function _getType() { + return $this->_type; + } + + /** + * Tests the expectation. True if the type or + * class matches the string value. + * @param string $compare Comparison value. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + if (is_object($compare)) { + return SimpleTestCompatibility::isA($compare, $this->_type); + } else { + return (strtolower(gettype($compare)) == $this->_canonicalType($this->_type)); + } + } + + /** + * Coerces type name into a gettype() match. + * @param string $type User type. + * @return string Simpler type. + * @access private + */ + function _canonicalType($type) { + $type = strtolower($type); + $map = array( + 'bool' => 'boolean', + 'float' => 'double', + 'real' => 'double', + 'int' => 'integer'); + if (isset($map[$type])) { + $type = $map[$type]; + } + return $type; + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = $this->_getDumper(); + return "Value [" . $dumper->describeValue($compare) . + "] should be type [" . $this->_type . "]"; + } + } + + /** + * Tests either type or class name if it's an object. + * Will succeed if the type does not match. + * @package SimpleTest + * @subpackage UnitTester + */ + class NotAExpectation extends IsAExpectation { + protected $_type; + + /** + * Sets the type to compare with. + * @param string $type Type or class name. + * @param string $message Customised message on failure. + * @access public + */ + function NotAExpectation($type, $message = '%s') { + $this->IsAExpectation($type, $message); + } + + /** + * Tests the expectation. False if the type or + * class matches the string value. + * @param string $compare Comparison value. + * @return boolean True if different. + * @access public + */ + function test($compare) { + return ! parent::test($compare); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = $this->_getDumper(); + return "Value [" . $dumper->describeValue($compare) . + "] should not be type [" . $this->_getType() . "]"; + } + } + + /** + * Tests for existance of a method in an object + * @package SimpleTest + * @subpackage UnitTester + */ + class MethodExistsExpectation extends SimpleExpectation { + protected $_method; + + /** + * Sets the value to compare against. + * @param string $method Method to check. + * @param string $message Customised message on failure. + * @access public + * @return void + */ + function MethodExistsExpectation($method, $message = '%s') { + $this->SimpleExpectation($message); + $this->_method = $method; + } + + /** + * Tests the expectation. True if the method exists in the test object. + * @param string $compare Comparison method name. + * @return boolean True if correct. + * @access public + */ + function test($compare) { + return (boolean)(is_object($compare) && method_exists($compare, $this->_method)); + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = $this->_getDumper(); + if (! is_object($compare)) { + return 'No method on non-object [' . $dumper->describeValue($compare) . ']'; + } + $method = $this->_method; + return "Object [" . $dumper->describeValue($compare) . + "] should contain method [$method]"; + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/extensions/pear_test_case.php b/tests/UnitTests/simpletest/extensions/pear_test_case.php new file mode 100644 index 00000000..c9ac0743 --- /dev/null +++ b/tests/UnitTests/simpletest/extensions/pear_test_case.php @@ -0,0 +1,199 @@ +SimpleTestCase($label); + $this->_loosely_typed = false; + } + + /** + * Will test straight equality if set to loose + * typing, or identity if not. + * @param $first First value. + * @param $second Comparison value. + * @param $message Message to display. + * @public + */ + function assertEquals($first, $second, $message = "%s", $delta = 0) { + if ($this->_loosely_typed) { + $expectation = &new EqualExpectation($first); + } else { + $expectation = &new IdenticalExpectation($first); + } + $this->assertExpectation($expectation, $second, $message); + } + + /** + * Passes if the value tested is not null. + * @param $value Value to test against. + * @param $message Message to display. + * @public + */ + function assertNotNull($value, $message = "%s") { + parent::assertTrue(isset($value), $message); + } + + /** + * Passes if the value tested is null. + * @param $value Value to test against. + * @param $message Message to display. + * @public + */ + function assertNull($value, $message = "%s") { + parent::assertTrue(!isset($value), $message); + } + + /** + * In PHP5 the identity test tests for the same + * object. This is a reference test in PHP4. + * @param $first First object handle. + * @param $second Hopefully the same handle. + * @param $message Message to display. + * @public + */ + function assertSame(&$first, &$second, $message = "%s") { + $dumper = &new SimpleDumper(); + $message = sprintf( + $message, + "[" . $dumper->describeValue($first) . + "] and [" . $dumper->describeValue($second) . + "] should reference the same object"); + return $this->assertTrue( + SimpleTestCompatibility::isReference($first, $second), + $message); + } + + /** + * In PHP5 the identity test tests for the same + * object. This is a reference test in PHP4. + * @param $first First object handle. + * @param $second Hopefully a different handle. + * @param $message Message to display. + * @public + */ + function assertNotSame(&$first, &$second, $message = "%s") { + $dumper = &new SimpleDumper(); + $message = sprintf( + $message, + "[" . $dumper->describeValue($first) . + "] and [" . $dumper->describeValue($second) . + "] should not be the same object"); + return $this->assertFalse( + SimpleTestCompatibility::isReference($first, $second), + $message); + } + + /** + * Sends pass if the test condition resolves true, + * a fail otherwise. + * @param $condition Condition to test true. + * @param $message Message to display. + * @public + */ + function assertTrue($condition, $message = "%s") { + parent::assertTrue($condition, $message); + } + + /** + * Sends pass if the test condition resolves false, + * a fail otherwise. + * @param $condition Condition to test false. + * @param $message Message to display. + * @public + */ + function assertFalse($condition, $message = "%s") { + parent::assertTrue(!$condition, $message); + } + + /** + * Tests a regex match. Needs refactoring. + * @param $pattern Regex to match. + * @param $subject String to search in. + * @param $message Message to display. + * @public + */ + function assertRegExp($pattern, $subject, $message = "%s") { + $this->assertExpectation( + new WantedPatternExpectation($pattern), + $subject, + $message); + } + + /** + * Tests the type of a value. + * @param $value Value to take type of. + * @param $type Hoped for type. + * @param $message Message to display. + * @public + */ + function assertType($value, $type, $message = "%s") { + parent::assertTrue(gettype($value) == strtolower($type), $message); + } + + /** + * Sets equality operation to act as a simple equal + * comparison only, allowing a broader range of + * matches. + * @param $loosely_typed True for broader comparison. + * @public + */ + function setLooselyTyped($loosely_typed) { + $this->_loosely_typed = $loosely_typed; + } + + /** + * For progress indication during + * a test amongst other things. + * @return Usually one. + * @public + */ + function countTestCases() { + return $this->getSize(); + } + + /** + * Accessor for name, normally just the class + * name. + * @public + */ + function getName() { + return $this->getLabel(); + } + + /** + * Does nothing. For compatibility only. + * @param $name Dummy + * @public + */ + function setName($name) { + } + } +?> diff --git a/tests/UnitTests/simpletest/extensions/phpunit_test_case.php b/tests/UnitTests/simpletest/extensions/phpunit_test_case.php new file mode 100644 index 00000000..4c6fa54e --- /dev/null +++ b/tests/UnitTests/simpletest/extensions/phpunit_test_case.php @@ -0,0 +1,108 @@ +SimpleTestCase($label); + } + + /** + * Sends pass if the test condition resolves true, + * a fail otherwise. + * @param $condition Condition to test true. + * @param $message Message to display. + * @public + */ + function assert($condition, $message = false) { + parent::assertTrue($condition, $message); + } + + /** + * Will test straight equality if set to loose + * typing, or identity if not. + * @param $first First value. + * @param $second Comparison value. + * @param $message Message to display. + * @public + */ + function assertEquals($first, $second, $message = false) { + $this->assertExpectation( + new EqualExpectation($first), + $second, + $message); + } + + /** + * Will test straight equality if set to loose + * typing, or identity if not. + * @param $first First value. + * @param $second Comparison value. + * @param $message Message to display. + * @public + */ + function assertEqualsMultilineStrings($first, $second, $message = false) { + $this->assertExpectation( + new EqualExpectation($first), + $second, + $message); + } + + /** + * Tests a regex match. + * @param $pattern Regex to match. + * @param $subject String to search in. + * @param $message Message to display. + * @public + */ + function assertRegexp($pattern, $subject, $message = false) { + $this->assertExpectation( + new WantedPatternExpectation($pattern), + $subject, + $message); + } + + /** + * Sends an error which we interpret as a fail + * with a different message for compatibility. + * @param $message Message to display. + * @public + */ + function error($message) { + parent::assertTrue(false, "Error triggered [$message]"); + } + + /** + * Accessor for name. + * @public + */ + function name() { + return $this->getLabel(); + } + } +?> diff --git a/tests/UnitTests/simpletest/form.php b/tests/UnitTests/simpletest/form.php new file mode 100644 index 00000000..05f5c72a --- /dev/null +++ b/tests/UnitTests/simpletest/form.php @@ -0,0 +1,619 @@ +_name = $name; + } + + /** + * Comparison. Compares with name attribute of + * widget. + * @param SimpleWidget $widget Control to compare. + * @access public + */ + function isMatch($widget) { + return ($widget->getName() == $this->_name); + } + } + + /** + * Used to extract form elements for testing against. + * Searches by visible label or alt text. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleLabelSelector { + protected $_label; + + /** + * Stashes the name for later comparison. + * @param string $label Visible text to match. + */ + function SimpleLabelSelector($label) { + $this->_label = $label; + } + + /** + * Comparison. Compares visible text of widget. + * @param SimpleWidget $widget Control to compare. + * @access public + */ + function isMatch($widget) { + return (trim($widget->getLabel()) == trim($this->_label)); + } + } + + /** + * Used to extract form elements for testing against. + * Searches dy id attribute. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleIdSelector { + protected $_id; + + /** + * Stashes the name for later comparison. + * @param string $id ID atribute to match. + */ + function SimpleIdSelector($id) { + $this->_id = $id; + } + + /** + * Comparison. Compares id attribute of widget. + * @param SimpleWidget $widget Control to compare. + * @access public + */ + function isMatch($widget) { + return $widget->isId($this->_id); + } + } + + /** + * Form tag class to hold widget values. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleForm { + protected $_method; + protected $_action; + protected $_default_target; + protected $_id; + protected $_buttons; + protected $_images; + protected $_widgets; + protected $_radios; + protected $_checkboxes; + + /** + * Starts with no held controls/widgets. + * @param SimpleTag $tag Form tag to read. + * @param SimpleUrl $url Location of holding page. + */ + function SimpleForm($tag, $url) { + $this->_method = $tag->getAttribute('method'); + $this->_action = $this->_createAction($tag->getAttribute('action'), $url); + $this->_default_target = false; + $this->_id = $tag->getAttribute('id'); + $this->_buttons = array(); + $this->_images = array(); + $this->_widgets = array(); + $this->_radios = array(); + $this->_checkboxes = array(); + } + + /** + * Sets the frame target within a frameset. + * @param string $frame Name of frame. + * @access public + */ + function setDefaultTarget($frame) { + $this->_default_target = $frame; + } + + /** + * Accessor for form action. + * @return string Either get or post. + * @access public + */ + function getMethod() { + return ($this->_method ? strtolower($this->_method) : 'get'); + } + + /** + * Combined action attribute with current location + * to get an absolute form target. + * @param string $action Action attribute from form tag. + * @param SimpleUrl $base Page location. + * @return SimpleUrl Absolute form target. + */ + function _createAction($action, $base) { + if ($action === false) { + return $base; + } + if ($action === true) { + $url = new SimpleUrl(''); + } else { + $url = new SimpleUrl($action); + } + return $url->makeAbsolute($base); + } + + /** + * Absolute URL of the target. + * @return SimpleUrl URL target. + * @access public + */ + function getAction() { + $url = $this->_action; + if ($this->_default_target && ! $url->getTarget()) { + $url->setTarget($this->_default_target); + } + return $url; + } + + /** + * ID field of form for unique identification. + * @return string Unique tag ID. + * @access public + */ + function getId() { + return $this->_id; + } + + /** + * Adds a tag contents to the form. + * @param SimpleWidget $tag Input tag to add. + * @access public + */ + function addWidget($tag) { + if (strtolower($tag->getAttribute('type')) == 'submit') { + $this->_buttons[] = $tag; + } elseif (strtolower($tag->getAttribute('type')) == 'image') { + $this->_images[] = $tag; + } elseif ($tag->getName()) { + $this->_setWidget($tag); + } + } + + /** + * Sets the widget into the form, grouping radio + * buttons if any. + * @param SimpleWidget $tag Incoming form control. + * @access private + */ + function _setWidget($tag) { + if (strtolower($tag->getAttribute('type')) == 'radio') { + $this->_addRadioButton($tag); + } elseif (strtolower($tag->getAttribute('type')) == 'checkbox') { + $this->_addCheckbox($tag); + } else { + $this->_widgets[] = $tag; + } + } + + /** + * Adds a radio button, building a group if necessary. + * @param SimpleRadioButtonTag $tag Incoming form control. + * @access private + */ + function _addRadioButton($tag) { + if (! isset($this->_radios[$tag->getName()])) { + $this->_widgets[] = new SimpleRadioGroup(); + $this->_radios[$tag->getName()] = count($this->_widgets) - 1; + } + $this->_widgets[$this->_radios[$tag->getName()]]->addWidget($tag); + } + + /** + * Adds a checkbox, making it a group on a repeated name. + * @param SimpleCheckboxTag $tag Incoming form control. + * @access private + */ + function _addCheckbox($tag) { + if (! isset($this->_checkboxes[$tag->getName()])) { + $this->_widgets[] = $tag; + $this->_checkboxes[$tag->getName()] = count($this->_widgets) - 1; + } else { + $index = $this->_checkboxes[$tag->getName()]; + if (! SimpleTestCompatibility::isA($this->_widgets[$index], 'SimpleCheckboxGroup')) { + $previous = $this->_widgets[$index]; + $this->_widgets[$index] = new SimpleCheckboxGroup(); + $this->_widgets[$index]->addWidget($previous); + } + $this->_widgets[$index]->addWidget($tag); + } + } + + /** + * Extracts current value from form. + * @param SimpleSelector $selector Criteria to apply. + * @return string/array Value(s) as string or null + * if not set. + * @access public + */ + function _getValueBySelector($selector) { + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($selector->isMatch($this->_widgets[$i])) { + return $this->_widgets[$i]->getValue(); + } + } + foreach ($this->_buttons as $button) { + if ($selector->isMatch($button)) { + return $button->getValue(); + } + } + return null; + } + + /** + * Extracts current value from form. + * @param string $name Keyed by widget name. + * @return string/array Value(s) or null + * if not set. + * @access public + */ + function getValue($name) { + return $this->_getValueBySelector(new SimpleNameSelector($name)); + } + + /** + * Extracts current value from form by the ID. + * @param string/integer $id Keyed by widget ID attribute. + * @return string/array Value(s) or null + * if not set. + * @access public + */ + function getValueById($id) { + return $this->_getValueBySelector(new SimpleIdSelector($id)); + } + + /** + * Sets a widget value within the form. + * @param SimpleSelector $selector Criteria to apply. + * @param string $value Value to input into the widget. + * @return boolean True if value is legal, false + * otherwise. If the field is not + * present, nothing will be set. + * @access public + */ + function _setFieldBySelector($selector, $value) { + $success = false; + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($selector->isMatch($this->_widgets[$i])) { + if ($this->_widgets[$i]->setValue($value)) { + $success = true; + } + } + } + return $success; + } + + /** + * Sets a widget value within the form. + * @param string $name Name of widget tag. + * @param string $value Value to input into the widget. + * @return boolean True if value is legal, false + * otherwise. If the field is not + * present, nothing will be set. + * @access public + */ + function setField($name, $value) { + return $this->_setFieldBySelector(new SimpleNameSelector($name), $value); + } + + /** + * Sets a widget value within the form by using the ID. + * @param string/integer $id Name of widget tag. + * @param string $value Value to input into the widget. + * @return boolean True if value is legal, false + * otherwise. If the field is not + * present, nothing will be set. + * @access public + */ + function setFieldById($id, $value) { + return $this->_setFieldBySelector(new SimpleIdSelector($id), $value); + } + + /** + * Creates the encoding for the current values in the + * form. + * @return SimpleFormEncoding Request to submit. + * @access private + */ + function _getEncoding() { + $encoding = new SimpleFormEncoding(); + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + $encoding->add( + $this->_widgets[$i]->getName(), + $this->_widgets[$i]->getValue()); + } + return $encoding; + } + + /** + * Test to see if a form has a submit button. + * @param SimpleSelector $selector Criteria to apply. + * @return boolean True if present. + * @access private + */ + function _hasSubmitBySelector($selector) { + foreach ($this->_buttons as $button) { + if ($selector->isMatch($button)) { + return true; + } + } + return false; + } + + /** + * Test to see if a form has a submit button with this + * name attribute. + * @param string $name Name to look for. + * @return boolean True if present. + * @access public + */ + function hasSubmitName($name) { + return $this->_hasSubmitBySelector(new SimpleNameSelector($name)); + } + + /** + * Test to see if a form has a submit button with this + * value attribute. + * @param string $label Button label to search for. + * @return boolean True if present. + * @access public + */ + function hasSubmitLabel($label) { + return $this->_hasSubmitBySelector(new SimpleLabelSelector($label)); + } + + /** + * Test to see if a form has a submit button with this + * ID attribute. + * @param string $id Button ID attribute to search for. + * @return boolean True if present. + * @access public + */ + function hasSubmitId($id) { + return $this->_hasSubmitBySelector(new SimpleIdSelector($id)); + } + + /** + * Test to see if a form has an image control. + * @param SimpleSelector $selector Criteria to apply. + * @return boolean True if present. + * @access public + */ + function _hasImageBySelector($selector) { + foreach ($this->_images as $image) { + if ($selector->isMatch($image)) { + return true; + } + } + return false; + } + + /** + * Test to see if a form has a submit button with this + * name attribute. + * @param string $label Button alt attribute to search for + * or nearest equivalent. + * @return boolean True if present. + * @access public + */ + function hasImageLabel($label) { + return $this->_hasImageBySelector(new SimpleLabelSelector($label)); + } + + /** + * Test to see if a form has a submittable image with this + * field name. + * @param string $name Image name to search for. + * @return boolean True if present. + * @access public + */ + function hasImageName($name) { + return $this->_hasImageBySelector(new SimpleNameSelector($name)); + } + + /** + * Test to see if a form has a submittable image with this + * ID attribute. + * @param string $id Button ID attribute to search for. + * @return boolean True if present. + * @access public + */ + function hasImageId($id) { + return $this->_hasImageBySelector(new SimpleIdSelector($id)); + } + + /** + * Gets the submit values for a selected button. + * @param SimpleSelector $selector Criteria to apply. + * @param hash $additional Additional data for the form. + * @return SimpleEncoding Submitted values or false + * if there is no such button + * in the form. + * @access public + */ + function _submitButtonBySelector($selector, $additional) { + foreach ($this->_buttons as $button) { + if ($selector->isMatch($button)) { + $encoding = $this->_getEncoding(); + $encoding->merge($button->getSubmitValues()); + if ($additional) { + $encoding->merge($additional); + } + return $encoding; + } + } + return false; + } + + /** + * Gets the submit values for a named button. + * @param string $name Button label to search for. + * @param hash $additional Additional data for the form. + * @return SimpleEncoding Submitted values or false + * if there is no such button in the + * form. + * @access public + */ + function submitButtonByName($name, $additional = false) { + return $this->_submitButtonBySelector( + new SimpleNameSelector($name), + $additional); + } + + /** + * Gets the submit values for a named button. + * @param string $label Button label to search for. + * @param hash $additional Additional data for the form. + * @return SimpleEncoding Submitted values or false + * if there is no such button in the + * form. + * @access public + */ + function submitButtonByLabel($label, $additional = false) { + return $this->_submitButtonBySelector( + new SimpleLabelSelector($label), + $additional); + } + + /** + * Gets the submit values for a button identified by the ID. + * @param string $id Button ID attribute to search for. + * @param hash $additional Additional data for the form. + * @return SimpleEncoding Submitted values or false + * if there is no such button in the + * form. + * @access public + */ + function submitButtonById($id, $additional = false) { + return $this->_submitButtonBySelector( + new SimpleIdSelector($id), + $additional); + } + + /** + * Gets the submit values for an image. + * @param SimpleSelector $selector Criteria to apply. + * @param integer $x X-coordinate of click. + * @param integer $y Y-coordinate of click. + * @param hash $additional Additional data for the form. + * @return SimpleEncoding Submitted values or false + * if there is no such button in the + * form. + * @access public + */ + function _submitImageBySelector($selector, $x, $y, $additional) { + foreach ($this->_images as $image) { + if ($selector->isMatch($image)) { + $encoding = $this->_getEncoding(); + $encoding->merge($image->getSubmitValues($x, $y)); + if ($additional) { + $encoding->merge($additional); + } + return $encoding; + } + } + return false; + } + + /** + * Gets the submit values for an image identified by the alt + * tag or nearest equivalent. + * @param string $label Button label to search for. + * @param integer $x X-coordinate of click. + * @param integer $y Y-coordinate of click. + * @param hash $additional Additional data for the form. + * @return SimpleEncoding Submitted values or false + * if there is no such button in the + * form. + * @access public + */ + function submitImageByLabel($label, $x, $y, $additional = false) { + return $this->_submitImageBySelector( + new SimpleLabelSelector($label), + $x, + $y, + $additional); + } + + /** + * Gets the submit values for an image identified by the ID. + * @param string $name Image name to search for. + * @param integer $x X-coordinate of click. + * @param integer $y Y-coordinate of click. + * @param hash $additional Additional data for the form. + * @return SimpleEncoding Submitted values or false + * if there is no such button in the + * form. + * @access public + */ + function submitImageByName($name, $x, $y, $additional = false) { + return $this->_submitImageBySelector( + new SimpleNameSelector($name), + $x, + $y, + $additional); + } + + /** + * Gets the submit values for an image identified by the ID. + * @param string/integer $id Button ID attribute to search for. + * @param integer $x X-coordinate of click. + * @param integer $y Y-coordinate of click. + * @param hash $additional Additional data for the form. + * @return SimpleEncoding Submitted values or false + * if there is no such button in the + * form. + * @access public + */ + function submitImageById($id, $x, $y, $additional = false) { + return $this->_submitImageBySelector( + new SimpleIdSelector($id), + $x, + $y, + $additional); + } + + /** + * Simply submits the form without the submit button + * value. Used when there is only one button or it + * is unimportant. + * @return hash Submitted values. + * @access public + */ + function submit() { + return $this->_getEncoding(); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/frames.php b/tests/UnitTests/simpletest/frames.php new file mode 100644 index 00000000..b18d28fc --- /dev/null +++ b/tests/UnitTests/simpletest/frames.php @@ -0,0 +1,673 @@ +_frameset = $page; + $this->_frames = array(); + $this->_focus = false; + $this->_names = array(); + } + + /** + * Adds a parsed page to the frameset. + * @param SimplePage $page Frame page. + * @param string $name Name of frame in frameset. + * @access public + */ + function addFrame($page, $name = false) { + $this->_frames[] = $page; + if ($name) { + $this->_names[$name] = count($this->_frames) - 1; + } + } + + /** + * Replaces existing frame with another. If the + * frame is nested, then the call is passed down + * one level. + * @param array $path Path of frame in frameset. + * @param SimplePage $page Frame source. + * @access public + */ + function setFrame($path, $page) { + $name = array_shift($path); + if (isset($this->_names[$name])) { + $index = $this->_names[$name]; + } else { + $index = $name - 1; + } + if (count($path) == 0) { + $this->_frames[$index] = $page; + return; + } + $this->_frames[$index]->setFrame($path, $page); + } + + /** + * Accessor for current frame focus. Will be + * false if no frame has focus. Will have the nested + * frame focus if any. + * @return array Labels or indexes of nested frames. + * @access public + */ + function getFrameFocus() { + if ($this->_focus === false) { + return array(); + } + return array_merge( + array($this->_getPublicNameFromIndex($this->_focus)), + $this->_frames[$this->_focus]->getFrameFocus()); + } + + /** + * Turns an internal array index into the frames list + * into a public name, or if none, then a one offset + * index. + * @param integer $subject Internal index. + * @return integer/string Public name. + * @access private + */ + function _getPublicNameFromIndex($subject) { + foreach ($this->_names as $name => $index) { + if ($subject == $index) { + return $name; + } + } + return $subject + 1; + } + + /** + * Sets the focus by index. The integer index starts from 1. + * If already focused and the target frame also has frames, + * then the nested frame will be focused. + * @param integer $choice Chosen frame. + * @return boolean True if frame exists. + * @access public + */ + function setFrameFocusByIndex($choice) { + if (is_integer($this->_focus)) { + if ($this->_frames[$this->_focus]->hasFrames()) { + return $this->_frames[$this->_focus]->setFrameFocusByIndex($choice); + } + } + if (($choice < 1) || ($choice > count($this->_frames))) { + return false; + } + $this->_focus = $choice - 1; + return true; + } + + /** + * Sets the focus by name. If already focused and the + * target frame also has frames, then the nested frame + * will be focused. + * @param string $name Chosen frame. + * @return boolean True if frame exists. + * @access public + */ + function setFrameFocus($name) { + if (is_integer($this->_focus)) { + if ($this->_frames[$this->_focus]->hasFrames()) { + return $this->_frames[$this->_focus]->setFrameFocus($name); + } + } + if (in_array($name, array_keys($this->_names))) { + $this->_focus = $this->_names[$name]; + return true; + } + return false; + } + + /** + * Clears the frame focus. + * @access public + */ + function clearFrameFocus() { + $this->_focus = false; + $this->_clearNestedFramesFocus(); + } + + /** + * Clears the frame focus for any nested frames. + * @access private + */ + function _clearNestedFramesFocus() { + for ($i = 0; $i < count($this->_frames); $i++) { + $this->_frames[$i]->clearFrameFocus(); + } + } + + /** + * Test for the presence of a frameset. + * @return boolean Always true. + * @access public + */ + function hasFrames() { + return true; + } + + /** + * Accessor for frames information. + * @return array/string Recursive hash of frame URL strings. + * The key is either a numerical + * index or the name attribute. + * @access public + */ + function getFrames() { + $report = array(); + for ($i = 0; $i < count($this->_frames); $i++) { + $report[$this->_getPublicNameFromIndex($i)] = + $this->_frames[$i]->getFrames(); + } + return $report; + } + + /** + * Accessor for raw text of either all the pages or + * the frame in focus. + * @return string Raw unparsed content. + * @access public + */ + function getRaw() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getRaw(); + } + $raw = ''; + for ($i = 0; $i < count($this->_frames); $i++) { + $raw .= $this->_frames[$i]->getRaw(); + } + return $raw; + } + + /** + * Accessor for plain text of either all the pages or + * the frame in focus. + * @return string Plain text content. + * @access public + */ + function getText() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getText(); + } + $raw = ''; + for ($i = 0; $i < count($this->_frames); $i++) { + $raw .= ' ' . $this->_frames[$i]->getText(); + } + return trim($raw); + } + + /** + * Accessor for last error. + * @return string Error from last response. + * @access public + */ + function getTransportError() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getTransportError(); + } + return $this->_frameset->getTransportError(); + } + + /** + * Request method used to fetch this frame. + * @return string GET, POST or HEAD. + * @access public + */ + function getMethod() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getMethod(); + } + return $this->_frameset->getMethod(); + } + + /** + * Original resource name. + * @return SimpleUrl Current url. + * @access public + */ + function getUrl() { + if (is_integer($this->_focus)) { + $url = $this->_frames[$this->_focus]->getUrl(); + $url->setTarget($this->_getPublicNameFromIndex($this->_focus)); + } else { + $url = $this->_frameset->getUrl(); + } + return $url; + } + + /** + * Original request data. + * @return mixed Sent content. + * @access public + */ + function getRequestData() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getRequestData(); + } + return $this->_frameset->getRequestData(); + } + + /** + * Accessor for current MIME type. + * @return string MIME type as string; e.g. 'text/html' + * @access public + */ + function getMimeType() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getMimeType(); + } + return $this->_frameset->getMimeType(); + } + + /** + * Accessor for last response code. + * @return integer Last HTTP response code received. + * @access public + */ + function getResponseCode() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getResponseCode(); + } + return $this->_frameset->getResponseCode(); + } + + /** + * Accessor for last Authentication type. Only valid + * straight after a challenge (401). + * @return string Description of challenge type. + * @access public + */ + function getAuthentication() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getAuthentication(); + } + return $this->_frameset->getAuthentication(); + } + + /** + * Accessor for last Authentication realm. Only valid + * straight after a challenge (401). + * @return string Name of security realm. + * @access public + */ + function getRealm() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getRealm(); + } + return $this->_frameset->getRealm(); + } + + /** + * Accessor for outgoing header information. + * @return string Header block. + * @access public + */ + function getRequest() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getRequest(); + } + return $this->_frameset->getRequest(); + } + + /** + * Accessor for raw header information. + * @return string Header block. + * @access public + */ + function getHeaders() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getHeaders(); + } + return $this->_frameset->getHeaders(); + } + + /** + * Accessor for parsed title. + * @return string Title or false if no title is present. + * @access public + */ + function getTitle() { + return $this->_frameset->getTitle(); + } + + /** + * Accessor for a list of all fixed links. + * @return array List of urls with scheme of + * http or https and hostname. + * @access public + */ + function getAbsoluteUrls() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getAbsoluteUrls(); + } + $urls = array(); + foreach ($this->_frames as $frame) { + $urls = array_merge($urls, $frame->getAbsoluteUrls()); + } + return array_values(array_unique($urls)); + } + + /** + * Accessor for a list of all relative links. + * @return array List of urls without hostname. + * @access public + */ + function getRelativeUrls() { + if (is_integer($this->_focus)) { + return $this->_frames[$this->_focus]->getRelativeUrls(); + } + $urls = array(); + foreach ($this->_frames as $frame) { + $urls = array_merge($urls, $frame->getRelativeUrls()); + } + return array_values(array_unique($urls)); + } + + /** + * Accessor for URLs by the link label. Label will match + * regardess of whitespace issues and case. + * @param string $label Text of link. + * @return array List of links with that label. + * @access public + */ + function getUrlsByLabel($label) { + if (is_integer($this->_focus)) { + return $this->_tagUrlsWithFrame( + $this->_frames[$this->_focus]->getUrlsByLabel($label), + $this->_focus); + } + $urls = array(); + foreach ($this->_frames as $index => $frame) { + $urls = array_merge( + $urls, + $this->_tagUrlsWithFrame( + $frame->getUrlsByLabel($label), + $index)); + } + return $urls; + } + + /** + * Accessor for a URL by the id attribute. If in a frameset + * then the first link found with that ID attribute is + * returned only. Focus on a frame if you want one from + * a specific part of the frameset. + * @param string $id Id attribute of link. + * @return string URL with that id. + * @access public + */ + function getUrlById($id) { + foreach ($this->_frames as $index => $frame) { + if ($url = $frame->getUrlById($id)) { + if (! $url->gettarget()) { + $url->setTarget($this->_getPublicNameFromIndex($index)); + } + return $url; + } + } + return false; + } + + /** + * Attaches the intended frame index to a list of URLs. + * @param array $urls List of SimpleUrls. + * @param string $frame Name of frame or index. + * @return array List of tagged URLs. + * @access private + */ + function _tagUrlsWithFrame($urls, $frame) { + $tagged = array(); + foreach ($urls as $url) { + if (! $url->getTarget()) { + $url->setTarget($this->_getPublicNameFromIndex($frame)); + } + $tagged[] = $url; + } + return $tagged; + } + + /** + * Finds a held form by button label. Will only + * search correctly built forms. The first form found + * either within the focused frame, or across frames, + * will be the one returned. + * @param string $label Button label, default 'Submit'. + * @return SimpleForm Form object containing the button. + * @access public + */ + function getFormBySubmitLabel($label) { + return $this->_findForm('getFormBySubmitLabel', $label); + } + + /** + * Finds a held form by button label. Will only + * search correctly built forms. The first form found + * either within the focused frame, or across frames, + * will be the one returned. + * @param string $name Button name attribute. + * @return SimpleForm Form object containing the button. + * @access public + */ + function getFormBySubmitName($name) { + return $this->_findForm('getFormBySubmitName', $name); + } + + /** + * Finds a held form by button id. Will only + * search correctly built forms. The first form found + * either within the focused frame, or across frames, + * will be the one returned. + * @param string $id Button ID attribute. + * @return SimpleForm Form object containing the button. + * @access public + */ + function getFormBySubmitId($id) { + return $this->_findForm('getFormBySubmitId', $id); + } + + /** + * Finds a held form by image label. Will only + * search correctly built forms. The first form found + * either within the focused frame, or across frames, + * will be the one returned. + * @param string $label Usually the alt attribute. + * @return SimpleForm Form object containing the image. + * @access public + */ + function getFormByImageLabel($label) { + return $this->_findForm('getFormByImageLabel', $label); + } + + /** + * Finds a held form by image button id. Will only + * search correctly built forms. The first form found + * either within the focused frame, or across frames, + * will be the one returned. + * @param string $name Image name. + * @return SimpleForm Form object containing the image. + * @access public + */ + function getFormByImageName($name) { + return $this->_findForm('getFormByImageName', $name); + } + + /** + * Finds a held form by image button id. Will only + * search correctly built forms. The first form found + * either within the focused frame, or across frames, + * will be the one returned. + * @param string $id Image ID attribute. + * @return SimpleForm Form object containing the image. + * @access public + */ + function getFormByImageId($id) { + return $this->_findForm('getFormByImageId', $id); + } + + /** + * Finds a held form by the form ID. A way of + * identifying a specific form when we have control + * of the HTML code. The first form found + * either within the focused frame, or across frames, + * will be the one returned. + * @param string $id Form label. + * @return SimpleForm Form object containing the matching ID. + * @access public + */ + function getFormById($id) { + return $this->_findForm('getFormById', $id); + } + + /** + * General form finder. Will search all the frames or + * just the one in focus. + * @param string $method Method to use to find in a page. + * @param string $attribute Label, name or ID. + * @return SimpleForm Form object containing the matching ID. + * @access protected + */ + function _findForm($method, $attribute) { + if (is_integer($this->_focus)) { + return $this->_findFormInFrame( + $this->_frames[$this->_focus], + $this->_focus, + $method, + $attribute); + } + for ($i = 0; $i < count($this->_frames); $i++) { + $form = $this->_findFormInFrame( + $this->_frames[$i], + $i, + $method, + $attribute); + if ($form) { + return $form; + } + } + return null; + } + + /** + * Finds a form in a page using a form finding method. Will + * also tag the form with the frame name it belongs in. + * @param SimplePage $page Page content of frame. + * @param integer $index Internal frame representation. + * @param string $method Method to use to find in a page. + * @param string $attribute Label, name or ID. + * @return SimpleForm Form object containing the matching ID. + * @access protected + */ + function _findFormInFrame($page, $index, $method, $attribute) { + $form = $this->_frames[$index]->$method($attribute); + if (isset($form)) { + $form->setDefaultTarget($this->_getPublicNameFromIndex($index)); + } + return $form; + } + + /** + * Sets a field on each form in which the field is + * available. + * @param string $name Field name. + * @param string $value Value to set field to. + * @return boolean True if value is valid. + * @access public + */ + function setField($name, $value) { + if (is_integer($this->_focus)) { + $this->_frames[$this->_focus]->setField($name, $value); + } else { + for ($i = 0; $i < count($this->_frames); $i++) { + $this->_frames[$i]->setField($name, $value); + } + } + } + + /** + * Sets a field on the form in which the unique field is + * available. + * @param string/integer $id Field ID attribute. + * @param string $value Value to set field to. + * @return boolean True if value is valid. + * @access public + */ + function setFieldById($id, $value) { + if (is_integer($this->_focus)) { + $this->_frames[$this->_focus]->setFieldById($id, $value); + } else { + for ($i = 0; $i < count($this->_frames); $i++) { + $this->_frames[$i]->setFieldById($id, $value); + } + } + } + + /** + * Accessor for a form element value within a frameset. + * Finds the first match amongst the frames. + * @param string $name Field name. + * @return string/boolean A string if the field is + * present, false if unchecked + * and null if missing. + * @access public + */ + function getField($name) { + for ($i = 0; $i < count($this->_frames); $i++) { + $value = $this->_frames[$i]->getField($name); + if (isset($value)) { + return $value; + } + } + return null; + } + + /** + * Accessor for a form element value within a page. + * Finds the first match. + * @param string/integer $id Field ID attribute. + * @return string/boolean A string if the field is + * present, false if unchecked + * and null if missing. + * @access public + */ + function getFieldById($id) { + for ($i = 0; $i < count($this->_frames); $i++) { + $value = $this->_frames[$i]->getFieldById($id); + if (isset($value)) { + return $value; + } + } + return null; + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/http.php b/tests/UnitTests/simpletest/http.php new file mode 100644 index 00000000..36cb395f --- /dev/null +++ b/tests/UnitTests/simpletest/http.php @@ -0,0 +1,853 @@ +_host = false; + $this->_name = $name; + $this->_value = $value; + $this->_path = ($path ? $this->_fixPath($path) : "/"); + $this->_expiry = false; + if (is_string($expiry)) { + $this->_expiry = strtotime($expiry); + } elseif (is_integer($expiry)) { + $this->_expiry = $expiry; + } + $this->_is_secure = $is_secure; + } + + /** + * Sets the host. The cookie rules determine + * that the first two parts are taken for + * certain TLDs and three for others. If the + * new host does not match these rules then the + * call will fail. + * @param string $host New hostname. + * @return boolean True if hostname is valid. + * @access public + */ + function setHost($host) { + if ($host = $this->_truncateHost($host)) { + $this->_host = $host; + return true; + } + return false; + } + + /** + * Accessor for the truncated host to which this + * cookie applies. + * @return string Truncated hostname. + * @access public + */ + function getHost() { + return $this->_host; + } + + /** + * Test for a cookie being valid for a host name. + * @param string $host Host to test against. + * @return boolean True if the cookie would be valid + * here. + */ + function isValidHost($host) { + return ($this->_truncateHost($host) === $this->getHost()); + } + + /** + * Extracts just the domain part that determines a + * cookie's host validity. + * @param string $host Host name to truncate. + * @return string Domain or false on a bad host. + * @access private + */ + function _truncateHost($host) { + $tlds = SimpleUrl::getAllTopLevelDomains(); + if (preg_match('/[a-z\-]+\.(' . $tlds . ')$/i', $host, $matches)) { + return $matches[0]; + } elseif (preg_match('/[a-z\-]+\.[a-z\-]+\.[a-z\-]+$/i', $host, $matches)) { + return $matches[0]; + } + return false; + } + + /** + * Accessor for name. + * @return string Cookie key. + * @access public + */ + function getName() { + return $this->_name; + } + + /** + * Accessor for value. A deleted cookie will + * have an empty string for this. + * @return string Cookie value. + * @access public + */ + function getValue() { + return $this->_value; + } + + /** + * Accessor for path. + * @return string Valid cookie path. + * @access public + */ + function getPath() { + return $this->_path; + } + + /** + * Tests a path to see if the cookie applies + * there. The test path must be longer or + * equal to the cookie path. + * @param string $path Path to test against. + * @return boolean True if cookie valid here. + * @access public + */ + function isValidPath($path) { + return (strncmp( + $this->_fixPath($path), + $this->getPath(), + strlen($this->getPath())) == 0); + } + + /** + * Accessor for expiry. + * @return string Expiry string. + * @access public + */ + function getExpiry() { + if (! $this->_expiry) { + return false; + } + return gmdate("D, d M Y H:i:s", $this->_expiry) . " GMT"; + } + + /** + * Test to see if cookie is expired against + * the cookie format time or timestamp. + * Will give true for a session cookie. + * @param integer/string $now Time to test against. Result + * will be false if this time + * is later than the cookie expiry. + * Can be either a timestamp integer + * or a cookie format date. + * @access public + */ + function isExpired($now) { + if (! $this->_expiry) { + return true; + } + if (is_string($now)) { + $now = strtotime($now); + } + return ($this->_expiry < $now); + } + + /** + * Ages the cookie by the specified number of + * seconds. + * @param integer $interval In seconds. + * @public + */ + function agePrematurely($interval) { + if ($this->_expiry) { + $this->_expiry -= $interval; + } + } + + /** + * Accessor for the secure flag. + * @return boolean True if cookie needs SSL. + * @access public + */ + function isSecure() { + return $this->_is_secure; + } + + /** + * Adds a trailing and leading slash to the path + * if missing. + * @param string $path Path to fix. + * @access private + */ + function _fixPath($path) { + if (substr($path, 0, 1) != '/') { + $path = '/' . $path; + } + if (substr($path, -1, 1) != '/') { + $path .= '/'; + } + return $path; + } + } + + /** + * Creates HTTP headers for the end point of + * a HTTP request. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleRoute { + protected $_url; + + /** + * Sets the target URL. + * @param SimpleUrl $url URL as object. + * @access public + */ + function SimpleRoute($url) { + $this->_url = $url; + } + + /** + * Resource name. + * @return SimpleUrl Current url. + * @access protected + */ + function getUrl() { + return $this->_url; + } + + /** + * Creates the first line which is the actual request. + * @param string $method HTTP request method, usually GET. + * @return string Request line content. + * @access protected + */ + function _getRequestLine($method) { + return $method . ' ' . $this->_url->getPath() . + $this->_url->getEncodedRequest() . ' HTTP/1.0'; + } + + /** + * Creates the host part of the request. + * @return string Host line content. + * @access protected + */ + function _getHostLine() { + $line = 'Host: ' . $this->_url->getHost(); + if ($this->_url->getPort()) { + $line .= ':' . $this->_url->getPort(); + } + return $line; + } + + /** + * Opens a socket to the route. + * @param string $method HTTP request method, usually GET. + * @param integer $timeout Connection timeout. + * @return SimpleSocket New socket. + * @access public + */ + function createConnection($method, $timeout) { + $default_port = ('https' == $this->_url->getScheme()) ? 443 : 80; + $socket = $this->_createSocket( + $this->_url->getScheme() ? $this->_url->getScheme() : 'http', + $this->_url->getHost(), + $this->_url->getPort() ? $this->_url->getPort() : $default_port, + $timeout); + if (! $socket->isError()) { + $socket->write($this->_getRequestLine($method) . "\r\n"); + $socket->write($this->_getHostLine() . "\r\n"); + $socket->write("Connection: close\r\n"); + } + return $socket; + } + + /** + * Factory for socket. + * @param string $scheme Protocol to use. + * @param string $host Hostname to connect to. + * @param integer $port Remote port. + * @param integer $timeout Connection timeout. + * @return SimpleSocket/SimpleSecureSocket New socket. + * @access protected + */ + function _createSocket($scheme, $host, $port, $timeout) { + if (in_array($scheme, array('https'))) { + return new SimpleSecureSocket($host, $port, $timeout); + } + return new SimpleSocket($host, $port, $timeout); + } + } + + /** + * Creates HTTP headers for the end point of + * a HTTP request via a proxy server. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleProxyRoute extends SimpleRoute { + protected $_proxy; + protected $_username; + protected $_password; + + /** + * Stashes the proxy address. + * @param SimpleUrl $url URL as object. + * @param string $proxy Proxy URL. + * @param string $username Username for autentication. + * @param string $password Password for autentication. + * @access public + */ + function SimpleProxyRoute($url, $proxy, $username = false, $password = false) { + $this->SimpleRoute($url); + $this->_proxy = $proxy; + $this->_username = $username; + $this->_password = $password; + } + + /** + * Creates the first line which is the actual request. + * @param string $method HTTP request method, usually GET. + * @param SimpleUrl $url URL as object. + * @return string Request line content. + * @access protected + */ + function _getRequestLine($method) { + $url = $this->getUrl(); + $scheme = $url->getScheme() ? $url->getScheme() : 'http'; + $port = $url->getPort() ? ':' . $url->getPort() : ''; + return $method . ' ' . $scheme . '://' . $url->getHost() . $port . + $url->getPath() . $url->getEncodedRequest() . ' HTTP/1.0'; + } + + /** + * Creates the host part of the request. + * @param SimpleUrl $url URL as object. + * @return string Host line content. + * @access protected + */ + function _getHostLine() { + $host = 'Host: ' . $this->_proxy->getHost(); + $port = $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080; + return "$host:$port"; + } + + /** + * Opens a socket to the route. + * @param string $method HTTP request method, usually GET. + * @param integer $timeout Connection timeout. + * @return SimpleSocket New socket. + * @access public + */ + function createConnection($method, $timeout) { + $socket = $this->_createSocket( + $this->_proxy->getScheme() ? $this->_proxy->getScheme() : 'http', + $this->_proxy->getHost(), + $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080, + $timeout); + if (! $socket->isError()) { + $socket->write($this->_getRequestLine($method) . "\r\n"); + $socket->write($this->_getHostLine() . "\r\n"); + if ($this->_username && $this->_password) { + $socket->write('Proxy-Authorization: Basic ' . + base64_encode($this->_username . ':' . $this->_password) . + "\r\n"); + } + $socket->write("Connection: close\r\n"); + } + return $socket; + } + } + + /** + * HTTP request for a web page. Factory for + * HttpResponse object. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleHttpRequest { + protected $_route; + protected $_method; + protected $_encoding; + protected $_headers; + protected $_cookies; + + /** + * Saves the URL ready for fetching. + * @param SimpleRoute $route Request route. + * @param string $method HTTP request method, + * usually GET. + * @param SimpleFormEncoding $encoding Content to send with + * request or false. + * @access public + */ + function SimpleHttpRequest($route, $method, $encoding = false) { + $this->_route = $route; + $this->_method = $method; + $this->_encoding = $encoding; + $this->_headers = array(); + $this->_cookies = array(); + } + + /** + * Fetches the content and parses the headers. + * @param integer $timeout Connection timeout. + * @return SimpleHttpResponse A response which may only have + * an error. + * @access public + */ + function fetch($timeout) { + $socket = $this->_route->createConnection($this->_method, $timeout); + if ($socket->isError()) { + return $this->_createResponse($socket); + } + $this->_dispatchRequest($socket, $this->_method, $this->_encoding); + return $this->_createResponse($socket); + } + + /** + * Sends the headers. + * @param SimpleSocket $socket Open socket. + * @param string $method HTTP request method, + * usually GET. + * @param SimpleFormEncoding $encoding Content to send with request. + * @access private + */ + function _dispatchRequest($socket, $method, $encoding) { + if ($encoding || ($method == 'POST')) { + $socket->write("Content-Length: " . $this->_getContentLength($encoding) . "\r\n"); + $socket->write("Content-Type: application/x-www-form-urlencoded\r\n"); + } + foreach ($this->_headers as $header_line) { + $socket->write($header_line . "\r\n"); + } + if (count($this->_cookies) > 0) { + $socket->write("Cookie: " . $this->_marshallCookies($this->_cookies) . "\r\n"); + } + $socket->write("\r\n"); + if ($encoding) { + $socket->write($encoding->asString()); + } + } + + /** + * Calculates the length of the encoded content. + * @param SimpleFormEncoding $encoding Content to send with + * request or false. + */ + function _getContentLength($encoding) { + if (! $encoding) { + return 0; + } + return (integer)strlen($encoding->asString()); + } + + /** + * Adds a header line to the request. + * @param string $header_line Text of header line. + * @access public + */ + function addHeaderLine($header_line) { + $this->_headers[] = $header_line; + } + + /** + * Adds a cookie to the request. + * @param SimpleCookie $cookie Additional cookie. + * @access public + */ + function setCookie($cookie) { + $this->_cookies[] = $cookie; + } + + /** + * Serialises the cookie hash ready for + * transmission. + * @param hash $cookies Parsed cookies. + * @return array Cookies in header form. + * @access private + */ + function _marshallCookies($cookies) { + $cookie_pairs = array(); + foreach ($cookies as $cookie) { + $cookie_pairs[] = $cookie->getName() . "=" . $cookie->getValue(); + } + return implode(";", $cookie_pairs); + } + + /** + * Wraps the socket in a response parser. + * @param SimpleSocket $socket Responding socket. + * @return SimpleHttpResponse Parsed response object. + * @access protected + */ + function _createResponse($socket) { + return new SimpleHttpResponse( + $socket, + $this->_method, + $this->_route->getUrl(), + $this->_encoding); + } + } + + /** + * Collection of header lines in the response. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleHttpHeaders { + protected $_raw_headers; + protected $_response_code; + protected $_http_version; + protected $_mime_type; + protected $_location; + protected $_cookies; + protected $_authentication; + protected $_realm; + + /** + * Parses the incoming header block. + * @param string $headers Header block. + * @access public + */ + function SimpleHttpHeaders($headers) { + $this->_raw_headers = $headers; + $this->_response_code = false; + $this->_http_version = false; + $this->_mime_type = ''; + $this->_location = false; + $this->_cookies = array(); + $this->_authentication = false; + $this->_realm = false; + foreach (split("\r\n", $headers) as $header_line) { + $this->_parseHeaderLine($header_line); + } + } + + /** + * Accessor for parsed HTTP protocol version. + * @return integer HTTP error code. + * @access public + */ + function getHttpVersion() { + return $this->_http_version; + } + + /** + * Accessor for raw header block. + * @return string All headers as raw string. + * @access public + */ + function getRaw() { + return $this->_raw_headers; + } + + /** + * Accessor for parsed HTTP error code. + * @return integer HTTP error code. + * @access public + */ + function getResponseCode() { + return (integer)$this->_response_code; + } + + /** + * Returns the redirected URL or false if + * no redirection. + * @return string URL or false for none. + * @access public + */ + function getLocation() { + return $this->_location; + } + + /** + * Test to see if the response is a valid redirect. + * @return boolean True if valid redirect. + * @access public + */ + function isRedirect() { + return in_array($this->_response_code, array(301, 302, 303, 307)) && + (boolean)$this->getLocation(); + } + + /** + * Test to see if the response is an authentication + * challenge. + * @return boolean True if challenge. + * @access public + */ + function isChallenge() { + return ($this->_response_code == 401) && + (boolean)$this->_authentication && + (boolean)$this->_realm; + } + + /** + * Accessor for MIME type header information. + * @return string MIME type. + * @access public + */ + function getMimeType() { + return $this->_mime_type; + } + + /** + * Accessor for authentication type. + * @return string Type. + * @access public + */ + function getAuthentication() { + return $this->_authentication; + } + + /** + * Accessor for security realm. + * @return string Realm. + * @access public + */ + function getRealm() { + return $this->_realm; + } + + /** + * Accessor for any new cookies. + * @return array List of new cookies. + * @access public + */ + function getNewCookies() { + return $this->_cookies; + } + + /** + * Called on each header line to accumulate the held + * data within the class. + * @param string $header_line One line of header. + * @access protected + */ + function _parseHeaderLine($header_line) { + if (preg_match('/HTTP\/(\d+\.\d+)\s+(.*?)\s/i', $header_line, $matches)) { + $this->_http_version = $matches[1]; + $this->_response_code = $matches[2]; + } + if (preg_match('/Content-type:\s*(.*)/i', $header_line, $matches)) { + $this->_mime_type = trim($matches[1]); + } + if (preg_match('/Location:\s*(.*)/i', $header_line, $matches)) { + $this->_location = trim($matches[1]); + } + if (preg_match('/Set-cookie:(.*)/i', $header_line, $matches)) { + $this->_cookies[] = $this->_parseCookie($matches[1]); + } + if (preg_match('/WWW-Authenticate:\s+(\S+)\s+realm=\"(.*?)\"/i', $header_line, $matches)) { + $this->_authentication = $matches[1]; + $this->_realm = trim($matches[2]); + } + } + + /** + * Parse the Set-cookie content. + * @param string $cookie_line Text after "Set-cookie:" + * @return SimpleCookie New cookie object. + * @access private + */ + function _parseCookie($cookie_line) { + $parts = split(";", $cookie_line); + $cookie = array(); + preg_match('/\s*(.*?)\s*=(.*)/', array_shift($parts), $cookie); + foreach ($parts as $part) { + if (preg_match('/\s*(.*?)\s*=(.*)/', $part, $matches)) { + $cookie[$matches[1]] = trim($matches[2]); + } + } + return new SimpleCookie( + $cookie[1], + trim($cookie[2]), + isset($cookie["path"]) ? $cookie["path"] : "", + isset($cookie["expires"]) ? $cookie["expires"] : false); + } + } + + /** + * Basic HTTP response. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleHttpResponse extends SimpleStickyError { + protected $_method; + protected $_url; + protected $_request_data; + protected $_sent; + protected $_content; + protected $_headers; + + /** + * Constructor. Reads and parses the incoming + * content and headers. + * @param SimpleSocket $socket Network connection to fetch + * response text from. + * @param string $method HTTP request method. + * @param SimpleUrl $url Resource name. + * @param mixed $request_data Record of content sent. + * @access public + */ + function SimpleHttpResponse($socket, $method, $url, $request_data = '') { + $this->SimpleStickyError(); + $this->_method = $method; + $this->_url = $url; + $this->_request_data = $request_data; + $this->_sent = $socket->getSent(); + $this->_content = false; + $raw = $this->_readAll($socket); + if ($socket->isError()) { + $this->_setError('Error reading socket [' . $socket->getError() . ']'); + return; + } + $this->_parse($raw); + } + + /** + * Splits up the headers and the rest of the content. + * @param string $raw Content to parse. + * @access private + */ + function _parse($raw) { + if (! $raw) { + $this->_setError('Nothing fetched'); + $this->_headers = new SimpleHttpHeaders(''); + } elseif (! strstr($raw, "\r\n\r\n")) { + $this->_setError('Could not parse headers'); + $this->_headers = new SimpleHttpHeaders($raw); + } else { + list($headers, $this->_content) = split("\r\n\r\n", $raw, 2); + $this->_headers = new SimpleHttpHeaders($headers); + } + } + + /** + * Original request method. + * @return string GET, POST or HEAD. + * @access public + */ + function getMethod() { + return $this->_method; + } + + /** + * Resource name. + * @return SimpleUrl Current url. + * @access public + */ + function getUrl() { + return $this->_url; + } + + /** + * Original request data. + * @return mixed Sent content. + * @access public + */ + function getRequestData() { + return $this->_request_data; + } + + /** + * Raw request that was sent down the wire. + * @return string Bytes actually sent. + * @access public + */ + function getSent() { + return $this->_sent; + } + + /** + * Accessor for the content after the last + * header line. + * @return string All content. + * @access public + */ + function getContent() { + return $this->_content; + } + + /** + * Accessor for header block. The response is the + * combination of this and the content. + * @return SimpleHeaders Wrapped header block. + * @access public + */ + function getHeaders() { + return $this->_headers; + } + + /** + * Accessor for any new cookies. + * @return array List of new cookies. + * @access public + */ + function getNewCookies() { + return $this->_headers->getNewCookies(); + } + + /** + * Reads the whole of the socket output into a + * single string. + * @param SimpleSocket $socket Unread socket. + * @return string Raw output if successful + * else false. + * @access private + */ + function _readAll($socket) { + $all = ''; + while (! $this->_isLastPacket($next = $socket->read())) { + $all .= $next; + } + return $all; + } + + /** + * Test to see if the packet from the socket is the + * last one. + * @param string $packet Chunk to interpret. + * @return boolean True if empty or EOF. + * @access private + */ + function _isLastPacket($packet) { + if (is_string($packet)) { + return $packet === ''; + } + return ! $packet; + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/mock_objects.php b/tests/UnitTests/simpletest/mock_objects.php new file mode 100644 index 00000000..6d7db4ce --- /dev/null +++ b/tests/UnitTests/simpletest/mock_objects.php @@ -0,0 +1,1323 @@ +SimpleExpectation(); + } + + /** + * Tests the expectation. Always true. + * @param mixed $compare Ignored. + * @return boolean True. + * @access public + */ + function test($compare) { + return true; + } + + /** + * Returns a human readable test message. + * @param mixed $compare Comparison value. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($compare) { + $dumper = $this->_getDumper(); + return 'Wildcard always matches [' . $dumper->describeValue($compare) . ']'; + } + } + + /** + * Parameter comparison assertion. + * @package SimpleTest + * @subpackage MockObjects + */ + class ParametersExpectation extends SimpleExpectation { + protected $_expected; + + /** + * Sets the expected parameter list. + * @param array $parameters Array of parameters including + * those that are wildcarded. + * If the value is not an array + * then it is considered to match any. + * @param mixed $wildcard Any parameter matching this + * will always match. + * @param string $message Customised message on failure. + * @access public + */ + function ParametersExpectation($expected = false, $message = '%s') { + $this->SimpleExpectation($message); + $this->_expected = $expected; + } + + /** + * Tests the assertion. True if correct. + * @param array $parameters Comparison values. + * @return boolean True if correct. + * @access public + */ + function test($parameters) { + if (! is_array($this->_expected)) { + return true; + } + if (count($this->_expected) != count($parameters)) { + return false; + } + for ($i = 0; $i < count($this->_expected); $i++) { + if (! $this->_testParameter($parameters[$i], $this->_expected[$i])) { + return false; + } + } + return true; + } + + /** + * Tests an individual parameter. + * @param mixed $parameter Value to test. + * @param mixed $expected Comparison value. + * @return boolean True if expectation + * fulfilled. + * @access private + */ + function _testParameter($parameter, $expected) { + $comparison = $this->_coerceToExpectation($expected); + return $comparison->test($parameter); + } + + /** + * Returns a human readable test message. + * @param array $comparison Incoming parameter list. + * @return string Description of success + * or failure. + * @access public + */ + function testMessage($parameters) { + if ($this->test($parameters)) { + return "Expectation of " . count($this->_expected) . + " arguments of [" . $this->_renderArguments($this->_expected) . + "] is correct"; + } else { + return $this->_describeDifference($this->_expected, $parameters); + } + } + + /** + * Message to display if expectation differs from + * the parameters actually received. + * @param array $expected Expected parameters as list. + * @param array $parameters Actual parameters received. + * @return string Description of difference. + * @access private + */ + function _describeDifference($expected, $parameters) { + if (count($expected) != count($parameters)) { + return "Expected " . count($expected) . + " arguments of [" . $this->_renderArguments($expected) . + "] but got " . count($parameters) . + " arguments of [" . $this->_renderArguments($parameters) . "]"; + } + $messages = array(); + for ($i = 0; $i < count($expected); $i++) { + $comparison = $this->_coerceToExpectation($expected[$i]); + if (! $comparison->test($parameters[$i])) { + $messages[] = "parameter " . ($i + 1) . " with [" . + $comparison->overlayMessage($parameters[$i]) . "]"; + } + } + return "Parameter expectation differs at " . implode(" and ", $messages); + } + + /** + * Creates an identical expectation if the + * object/value is not already some type + * of expectation. + * @param mixed $expected Expected value. + * @return SimpleExpectation Expectation object. + * @access private + */ + function _coerceToExpectation($expected) { + if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) { + return $expected; + } + return new IdenticalExpectation($expected); + } + + /** + * Renders the argument list as a string for + * messages. + * @param array $args Incoming arguments. + * @return string Simple description of type and value. + * @access private + */ + function _renderArguments($args) { + $descriptions = array(); + if (is_array($args)) { + foreach ($args as $arg) { + $dumper = new SimpleDumper(); + $descriptions[] = $dumper->describeValue($arg); + } + } + return implode(', ', $descriptions); + } + } + + /** + * Confirms that the number of calls on a method is as expected. + */ + class CallCountExpectation extends SimpleExpectation { + protected $_method; + protected $_count; + + /** + * Stashes the method and expected count for later + * reporting. + * @param string $method Name of method to confirm against. + * @param integer $count Expected number of calls. + * @param string $message Custom error message. + */ + function CallCountExpectation($method, $count, $message = '%s') { + $this->_method = $method; + $this->_count = $count; + $this->SimpleExpectation($message); + } + + /** + * Tests the assertion. True if correct. + * @param integer $compare Measured call count. + * @return boolean True if expected. + * @access public + */ + function test($compare) { + return ($this->_count == $compare); + } + + /** + * Reports the comparison. + * @param integer $compare Measured call count. + * @return string Message to show. + * @access public + */ + function testMessage($compare) { + return 'Expected call count for [' . $this->_method . + '] was [' . $this->_count . + '] got [' . $compare . ']'; + } + } + + /** + * Confirms that the number of calls on a method is as expected. + */ + class MinimumCallCountExpectation extends SimpleExpectation { + protected $_method; + protected $_count; + + /** + * Stashes the method and expected count for later + * reporting. + * @param string $method Name of method to confirm against. + * @param integer $count Minimum number of calls. + * @param string $message Custom error message. + */ + function MinimumCallCountExpectation($method, $count, $message = '%s') { + $this->_method = $method; + $this->_count = $count; + $this->SimpleExpectation($message); + } + + /** + * Tests the assertion. True if correct. + * @param integer $compare Measured call count. + * @return boolean True if enough. + * @access public + */ + function test($compare) { + return ($this->_count <= $compare); + } + + /** + * Reports the comparison. + * @param integer $compare Measured call count. + * @return string Message to show. + * @access public + */ + function testMessage($compare) { + return 'Minimum call count for [' . $this->_method . + '] was [' . $this->_count . + '] got [' . $compare . ']'; + } + } + + /** + * Confirms that the number of calls on a method is as expected. + */ + class MaximumCallCountExpectation extends SimpleExpectation { + protected $_method; + protected $_count; + + /** + * Stashes the method and expected count for later + * reporting. + * @param string $method Name of method to confirm against. + * @param integer $count Minimum number of calls. + * @param string $message Custom error message. + */ + function MaximumCallCountExpectation($method, $count, $message = '%s') { + $this->_method = $method; + $this->_count = $count; + $this->SimpleExpectation($message); + } + + /** + * Tests the assertion. True if correct. + * @param integer $compare Measured call count. + * @return boolean True if not over. + * @access public + */ + function test($compare) { + return ($this->_count >= $compare); + } + + /** + * Reports the comparison. + * @param integer $compare Measured call count. + * @return string Message to show. + * @access public + */ + function testMessage($compare) { + return 'Maximum call count for [' . $this->_method . + '] was [' . $this->_count . + '] got [' . $compare . ']'; + } + } + + /** + * Retrieves values and references by searching the + * parameter lists until a match is found. + * @package SimpleTest + * @subpackage MockObjects + */ + class CallMap { + protected $_map; + + /** + * Creates an empty call map. + * @access public + */ + function CallMap() { + $this->_map = array(); + } + + /** + * Stashes a value against a method call. + * @param array $parameters Arguments including wildcards. + * @param mixed $value Value copied into the map. + * @access public + */ + function addValue($parameters, $value) { + $this->addReference($parameters, $value); + } + + /** + * Stashes a reference against a method call. + * @param array $parameters Array of arguments (including wildcards). + * @param mixed $reference Array reference placed in the map. + * @access public + */ + function addReference($parameters, $reference) { + $place = count($this->_map); + $this->_map[$place] = array(); + $this->_map[$place]["params"] = new ParametersExpectation($parameters); + $this->_map[$place]["content"] = $reference; + } + + /** + * Searches the call list for a matching parameter + * set. Returned by reference. + * @param array $parameters Parameters to search by + * without wildcards. + * @return object Object held in the first matching + * slot, otherwise null. + * @access public + */ + function findFirstMatch($parameters) { + $slot = $this->_findFirstSlot($parameters); + if (!isset($slot)) { + return null; + } + return $slot["content"]; + } + + /** + * Searches the call list for a matching parameter + * set. True if successful. + * @param array $parameters Parameters to search by + * without wildcards. + * @return boolean True if a match is present. + * @access public + */ + function isMatch($parameters) { + return ($this->_findFirstSlot($parameters) != null); + } + + /** + * Searches the map for a matching item. + * @param array $parameters Parameters to search by + * without wildcards. + * @return array Reference to slot or null. + * @access private + */ + function _findFirstSlot($parameters) { + $count = count($this->_map); + for ($i = 0; $i < $count; $i++) { + if ($this->_map[$i]["params"]->test($parameters)) { + return $this->_map[$i]; + } + } + return null; + } + } + + /** + * An empty collection of methods that can have their + * return values set. Used for prototyping. + * @package SimpleTest + * @subpackage MockObjects + */ + class SimpleStub { + protected $_wildcard; + protected $_is_strict; + protected $_returns; + protected $_return_sequence; + protected $_call_counts; + + /** + * Sets up the wildcard and everything else empty. + * @param mixed $wildcard Parameter matching wildcard. + * @param boolean $is_strict Enables method name checks. + * @access public + */ + function SimpleStub($wildcard, $is_strict = true) { + $this->_wildcard = $wildcard; + $this->_is_strict = $is_strict; + $this->_returns = array(); + $this->_return_sequence = array(); + $this->_call_counts = array(); + } + + /** + * Replaces wildcard matches with wildcard + * expectations in the argument list. + * @param array $args Raw argument list. + * @return array Argument list with + * expectations. + * @access private + */ + function _replaceWildcards($args) { + if ($args === false) { + return false; + } + for ($i = 0; $i < count($args); $i++) { + if ($args[$i] === $this->_wildcard) { + $args[$i] = new WildcardExpectation(); + } + } + return $args; + } + + /** + * Returns the expected value for the method name. + * @param string $method Name of method to simulate. + * @param array $args Arguments as an array. + * @return mixed Stored return. + * @access private + */ + function _invoke($method, $args) { + $method = strtolower($method); + $step = $this->getCallCount($method); + $this->_addCall($method, $args); + return $this->_getReturn($method, $args, $step); + } + + /** + * Triggers a PHP error if the method is not part + * of this object. + * @param string $method Name of method. + * @param string $task Description of task attempt. + * @access protected + */ + function _dieOnNoMethod($method, $task) { + if ($this->_is_strict && !method_exists($this, $method)) { + trigger_error( + "Cannot $task as no ${method}() in class " . get_class($this), + E_USER_ERROR); + } + } + + /** + * Adds one to the call count of a method. + * @param string $method Method called. + * @param array $args Arguments as an array. + * @access protected + */ + function _addCall($method, $args) { + if (!isset($this->_call_counts[$method])) { + $this->_call_counts[$method] = 0; + } + $this->_call_counts[$method]++; + } + + /** + * Fetches the call count of a method so far. + * @param string $method Method name called. + * @return Number of calls so far. + * @access public + */ + function getCallCount($method) { + $this->_dieOnNoMethod($method, "get call count"); + $method = strtolower($method); + if (! isset($this->_call_counts[$method])) { + return 0; + } + return $this->_call_counts[$method]; + } + + /** + * Sets a return for a parameter list that will + * be passed by value for all calls to this method. + * @param string $method Method name. + * @param mixed $value Result of call passed by value. + * @param array $args List of parameters to match + * including wildcards. + * @access public + */ + function setReturnValue($method, $value, $args = false) { + $this->_dieOnNoMethod($method, "set return value"); + $args = $this->_replaceWildcards($args); + $method = strtolower($method); + if (! isset($this->_returns[$method])) { + $this->_returns[$method] = new CallMap(); + } + $this->_returns[$method]->addValue($args, $value); + } + + /** + * Sets a return for a parameter list that will + * be passed by value only when the required call count + * is reached. + * @param integer $timing Number of calls in the future + * to which the result applies. If + * not set then all calls will return + * the value. + * @param string $method Method name. + * @param mixed $value Result of call passed by value. + * @param array $args List of parameters to match + * including wildcards. + * @access public + */ + function setReturnValueAt($timing, $method, $value, $args = false) { + $this->_dieOnNoMethod($method, "set return value sequence"); + $args = $this->_replaceWildcards($args); + $method = strtolower($method); + if (! isset($this->_return_sequence[$method])) { + $this->_return_sequence[$method] = array(); + } + if (! isset($this->_return_sequence[$method][$timing])) { + $this->_return_sequence[$method][$timing] = new CallMap(); + } + $this->_return_sequence[$method][$timing]->addValue($args, $value); + } + + /** + * Sets a return for a parameter list that will + * be passed by reference for all calls. + * @param string $method Method name. + * @param mixed $reference Result of the call will be this object. + * @param array $args List of parameters to match + * including wildcards. + * @access public + */ + function setReturnReference($method, $reference, $args = false) { + $this->_dieOnNoMethod($method, "set return reference"); + $args = $this->_replaceWildcards($args); + $method = strtolower($method); + if (! isset($this->_returns[$method])) { + $this->_returns[$method] = new CallMap(); + } + $this->_returns[$method]->addReference($args, $reference); + } + + /** + * Sets a return for a parameter list that will + * be passed by value only when the required call count + * is reached. + * @param integer $timing Number of calls in the future + * to which the result applies. If + * not set then all calls will return + * the value. + * @param string $method Method name. + * @param mixed $reference Result of the call will be this object. + * @param array $args List of parameters to match + * including wildcards. + * @access public + */ + function setReturnReferenceAt($timing, $method, $reference, $args = false) { + $this->_dieOnNoMethod($method, "set return reference sequence"); + $args = $this->_replaceWildcards($args); + $method = strtolower($method); + if (! isset($this->_return_sequence[$method])) { + $this->_return_sequence[$method] = array(); + } + if (! isset($this->_return_sequence[$method][$timing])) { + $this->_return_sequence[$method][$timing] = new CallMap(); + } + $this->_return_sequence[$method][$timing]->addReference($args, $reference); + } + + /** + * Finds the return value matching the incoming + * arguments. If there is no matching value found + * then an error is triggered. + * @param string $method Method name. + * @param array $args Calling arguments. + * @param integer $step Current position in the + * call history. + * @return mixed Stored return. + * @access protected + */ + function _getReturn($method, $args, $step) { + if (isset($this->_return_sequence[$method][$step])) { + if ($this->_return_sequence[$method][$step]->isMatch($args)) { + return $this->_return_sequence[$method][$step]->findFirstMatch($args); + } + } + if (isset($this->_returns[$method])) { + return $this->_returns[$method]->findFirstMatch($args); + } + return null; + } + } + + /** + * An empty collection of methods that can have their + * return values set and expectations made of the + * calls upon them. The mock will assert the + * expectations against it's attached test case in + * addition to the server stub behaviour. + * @package SimpleTest + * @subpackage MockObjects + */ + class SimpleMock extends SimpleStub { + protected $_test; + protected $_expected_counts; + protected $_max_counts; + protected $_expected_args; + protected $_expected_args_at; + + /** + * Creates an empty return list and expectation list. + * All call counts are set to zero. + * @param SimpleTestCase $test Test case to test expectations in. + * @param mixed $wildcard Parameter matching wildcard. + * @param boolean $is_strict Enables method name checks on + * expectations. + * @access public + */ + function SimpleMock($test, $wildcard, $is_strict = true) { + $this->SimpleStub($wildcard, $is_strict); + if (! $test) { + trigger_error('No unit tester for mock object', E_USER_ERROR); + return; + } + $this->_test = SimpleMock::registerTest($test); + $this->_expected_counts = array(); + $this->_max_counts = array(); + $this->_expected_args = array(); + $this->_expected_args_at = array(); + } + + /** + * Accessor for attached unit test so that when + * subclassed, new expectations can be added easily. + * @return SimpleTestCase Unit test passed in constructor. + * @access public + */ + function getTest() { + return $this->_test; + } + + /** + * Die if bad arguments array is passed + * @param mixed $args The arguments value to be checked. + * @param string $task Description of task attempt. + * @return boolean Valid arguments + * @access private + */ + function _checkArgumentsIsArray($args, $task) { + if (! is_array($args)) { + trigger_error( + "Cannot $task as \$args parameter is not an array", + E_USER_ERROR); + } + } + + /** + * Sets up an expected call with a set of + * expected parameters in that call. All + * calls will be compared to these expectations + * regardless of when the call is made. + * @param string $method Method call to test. + * @param array $args Expected parameters for the call + * including wildcards. + * @param string $message Overridden message. + * @access public + */ + function expectArguments($method, $args, $message = '%s') { + $this->_dieOnNoMethod($method, 'set expected arguments'); + $this->_checkArgumentsIsArray($args, 'set expected arguments'); + $args = $this->_replaceWildcards($args); + $message .= Mock::getExpectationLine(' at line [%d]'); + $this->_expected_args[strtolower($method)] = + new ParametersExpectation($args, $message); + } + + /** + * Sets up an expected call with a set of + * expected parameters in that call. The + * expected call count will be adjusted if it + * is set too low to reach this call. + * @param integer $timing Number of calls in the future at + * which to test. Next call is 0. + * @param string $method Method call to test. + * @param array $args Expected parameters for the call + * including wildcards. + * @param string $message Overridden message. + * @access public + */ + function expectArgumentsAt($timing, $method, $args, $message = '%s') { + $this->_dieOnNoMethod($method, 'set expected arguments at time'); + $this->_checkArgumentsIsArray($args, 'set expected arguments at time'); + $args = $this->_replaceWildcards($args); + if (! isset($this->_expected_args_at[$timing])) { + $this->_expected_args_at[$timing] = array(); + } + $method = strtolower($method); + $message .= Mock::getExpectationLine(' at line [%d]'); + $this->_expected_args_at[$timing][$method] = + new ParametersExpectation($args, $message); + } + + /** + * Sets an expectation for the number of times + * a method will be called. The tally method + * is used to check this. + * @param string $method Method call to test. + * @param integer $count Number of times it should + * have been called at tally. + * @param string $message Overridden message. + * @access public + */ + function expectCallCount($method, $count, $message = '%s') { + $this->_dieOnNoMethod($method, 'set expected call count'); + $message .= Mock::getExpectationLine(' at line [%d]'); + $this->_expected_counts[strtolower($method)] = + new CallCountExpectation($method, $count, $message); + } + + /** + * Sets the number of times a method may be called + * before a test failure is triggered. + * @param string $method Method call to test. + * @param integer $count Most number of times it should + * have been called. + * @param string $message Overridden message. + * @access public + */ + function expectMaximumCallCount($method, $count, $message = '%s') { + $this->_dieOnNoMethod($method, 'set maximum call count'); + $message .= Mock::getExpectationLine(' at line [%d]'); + $this->_max_counts[strtolower($method)] = + new MaximumCallCountExpectation($method, $count, $message); + } + + /** + * Sets the number of times to call a method to prevent + * a failure on the tally. + * @param string $method Method call to test. + * @param integer $count Least number of times it should + * have been called. + * @param string $message Overridden message. + * @access public + */ + function expectMinimumCallCount($method, $count, $message = '%s') { + $this->_dieOnNoMethod($method, 'set minimum call count'); + $message .= Mock::getExpectationLine(' at line [%d]'); + $this->_expected_counts[strtolower($method)] = + new MinimumCallCountExpectation($method, $count, $message); + } + + /** + * Convenience method for barring a method + * call. + * @param string $method Method call to ban. + * @param string $message Overridden message. + * @access public + */ + function expectNever($method, $message = '%s') { + $this->expectMaximumCallCount($method, 0, $message); + } + + /** + * Convenience method for a single method + * call. + * @param string $method Method call to track. + * @param array $args Expected argument list or + * false for any arguments. + * @param string $message Overridden message. + * @access public + */ + function expectOnce($method, $args = false, $message = '%s') { + $this->expectCallCount($method, 1, $message); + if ($args !== false) { + $this->expectArguments($method, $args, $message); + } + } + + /** + * Convenience method for requiring a method + * call. + * @param string $method Method call to track. + * @param array $args Expected argument list or + * false for any arguments. + * @param string $message Overridden message. + * @access public + */ + function expectAtLeastOnce($method, $args = false, $message = '%s') { + $this->expectMinimumCallCount($method, 1, $message); + if ($args !== false) { + $this->expectArguments($method, $args, $message); + } + } + + /** + * Totals up the call counts and triggers a test + * assertion if a test is present for expected + * call counts. + * This method must be called explicitly for the call + * count assertions to be triggered. + * @access public + */ + function tally() { + foreach ($this->_expected_counts as $method => $expectation) { + $this->_assertTrue( + $expectation->test($this->getCallCount($method)), + $expectation->overlayMessage($this->getCallCount($method))); + } + foreach ($this->_max_counts as $method => $expectation) { + if ($expectation->test($this->getCallCount($method))) { + $this->_assertTrue( + true, + $expectation->overlayMessage($this->getCallCount($method))); + } + } + } + + /** + * Returns the expected value for the method name + * and checks expectations. Will generate any + * test assertions as a result of expectations + * if there is a test present. + * @param string $method Name of method to simulate. + * @param array $args Arguments as an array. + * @return mixed Stored return. + * @access private + */ + function _invoke($method, $args) { + $method = strtolower($method); + $step = $this->getCallCount($method); + $this->_addCall($method, $args); + $this->_checkExpectations($method, $args, $step); + return $this->_getReturn($method, $args, $step); + } + + /** + * Tests the arguments against expectations. + * @param string $method Method to check. + * @param array $args Argument list to match. + * @param integer $timing The position of this call + * in the call history. + * @access private + */ + function _checkExpectations($method, $args, $timing) { + if (isset($this->_max_counts[$method])) { + if (! $this->_max_counts[$method]->test($timing + 1)) { + $this->_assertTrue( + false, + $this->_max_counts[$method]->overlayMessage($timing + 1)); + } + } + if (isset($this->_expected_args_at[$timing][$method])) { + $this->_assertTrue( + $this->_expected_args_at[$timing][$method]->test($args), + "Mock method [$method] at [$timing] -> " . + $this->_expected_args_at[$timing][$method]->overlayMessage($args)); + } elseif (isset($this->_expected_args[$method])) { + $this->_assertTrue( + $this->_expected_args[$method]->test($args), + "Mock method [$method] -> " . $this->_expected_args[$method]->overlayMessage($args)); + } + } + + /** + * Triggers an assertion on the held test case. + * Should be overridden when using another test + * framework other than the SimpleTest one if the + * assertion method has a different name. + * @param boolean $assertion True will pass. + * @param string $message Message that will go with + * the test event. + * @access protected + */ + function _assertTrue($assertion, $message) { + $test =SimpleMock::injectTest($this->_test); + $test->assertTrue($assertion, $message); + } + + /** + * Stashes the test case for later recovery. + * @param SimpleTestCase $test Test case. + * @return string Key to find it again. + * @access public + * @static + */ + function registerTest($test) { + $registry =SimpleMock::_getRegistry(); + $registry[$class = get_class($test)] = $test; + return $class; + } + + /** + * Resolves the dependency on the test case. + * @param string $class Key to look up test case in. + * @return SimpleTestCase Test case to send results to. + * @access public + * @static + */ + function injectTest($key) { + $registry =SimpleMock::_getRegistry(); + return $registry[$key]; + } + + /** + * Registry for test cases. The reason for this is + * to break the reference between the test cases and + * the mocks. It was leading to a fatal error due to + * recursive dependencies during comparisons. See + * http://bugs.php.net/bug.php?id=31449 for the PHP + * bug. + * @return array List of references. + * @access private + * @static + */ + function _getRegistry() { + static $registry; + if (! isset($registry)) { + $registry = array(); + } + return $registry; + } + } + + /** + * Static methods only service class for code generation of + * server stubs. + * @package SimpleTest + * @subpackage MockObjects + */ + class Stub { + + /** + * Factory for server stub classes. + */ + function Stub() { + trigger_error('Stub factory methods are class only.'); + } + + /** + * Clones a class' interface and creates a stub version + * that can have return values set. + * @param string $class Class to clone. + * @param string $stub_class New class name. Default is + * the old name with "Stub" + * prepended. + * @param array $methods Additional methods to add beyond + * those in the cloned class. Use this + * to emulate the dynamic addition of + * methods in the cloned class or when + * the class hasn't been written yet. + * @static + * @access public + */ + function generate($class, $stub_class = false, $methods = false) { + if (! SimpleTestCompatibility::classExists($class)) { + return false; + } + if (! $stub_class) { + $stub_class = "Stub" . $class; + } + if (SimpleTestCompatibility::classExists($stub_class)) { + return false; + } + return eval(Stub::_createClassCode( + $class, + $stub_class, + $methods ? $methods : array()) . " return true;"); + } + + /** + * The new server stub class code in string form. + * @param string $class Class to clone. + * @param string $mock_class New class name. + * @param array $methods Additional methods. + * @static + * @access private + */ + function _createClassCode($class, $stub_class, $methods) { + $stub_base = SimpleTestOptions::getStubBaseClass(); + $code = "class $stub_class extends $stub_base {\n"; + $code .= " function $stub_class(\$wildcard = MOCK_WILDCARD) {\n"; + $code .= " \$this->$stub_base(\$wildcard);\n"; + $code .= " }\n"; + $code .= Stub::_createHandlerCode($class, $stub_base, $methods); + $code .= "}\n"; + return $code; + } + + /** + * Creates code within a class to generate replaced + * methods. All methods call the _invoke() handler + * with the method name and the arguments in an + * array. + * @param string $class Class to clone. + * @param string $base Base mock/stub class with methods that + * cannot be cloned. Otherwise you + * would be stubbing the accessors used + * to set the stubs. + * @param array $methods Additional methods. + * @static + * @access private + */ + function _createHandlerCode($class, $base, $methods) { + $code = ""; + $methods = array_merge($methods, get_class_methods($class)); + foreach ($methods as $method) { + if (Stub::_isSpecialMethod($method)) { + continue; + } + if (in_array($method, get_class_methods($base))) { + continue; + } + $code .= " function $method() {\n"; + $code .= " \$args = func_get_args();\n"; + $code .= " return \$this->_invoke(\"$method\", \$args);\n"; + $code .= " }\n"; + } + return $code; + } + + /** + * Tests to see if a special PHP method is about to + * be stubbed by mistake. + * @param string $method Method name. + * @return boolean True if special. + * @access private + * @static + */ + function _isSpecialMethod($method) { + return in_array( + strtolower($method), + array('__construct', '__clone', '__get', '__set', '__call')); + } + } + + /** + * Static methods only service class for code generation of + * mock objects. + * @package SimpleTest + * @subpackage MockObjects + */ + class Mock { + + /** + * Factory for mock object classes. + * @access public + */ + function Mock() { + trigger_error("Mock factory methods are class only."); + } + + /** + * Clones a class' interface and creates a mock version + * that can have return values and expectations set. + * @param string $class Class to clone. + * @param string $mock_class New class name. Default is + * the old name with "Mock" + * prepended. + * @param array $methods Additional methods to add beyond + * those in th cloned class. Use this + * to emulate the dynamic addition of + * methods in the cloned class or when + * the class hasn't been written yet. + * @static + * @access public + */ + function generate($class, $mock_class = false, $methods = false) { + if (! SimpleTestCompatibility::classExists($class)) { + return false; + } + if (! $mock_class) { + $mock_class = "Mock" . $class; + } + if (SimpleTestCompatibility::classExists($mock_class)) { + return false; + } + return eval(Mock::_createClassCode( + $class, + $mock_class, + $methods ? $methods : array()) . " return true;"); + } + + /** + * Generates a version of a class with selected + * methods mocked only. Inherits the old class + * and chains the mock methods of an aggregated + * mock object. + * @param string $class Class to clone. + * @param string $mock_class New class name. + * @param array $methods Methods to be overridden + * with mock versions. + * @static + * @access public + */ + function generatePartial($class, $mock_class, $methods) { + if (! SimpleTestCompatibility::classExists($class)) { + return false; + } + if (SimpleTestCompatibility::classExists($mock_class)) { + trigger_error("Partial mock class [$mock_class] already exists"); + return false; + } + return eval(Mock::_extendClassCode($class, $mock_class, $methods)); + } + + /** + * The new mock class code as a string. + * @param string $class Class to clone. + * @param string $mock_class New class name. + * @param array $methods Additional methods. + * @return string Code for new mock class. + * @static + * @access private + */ + function _createClassCode($class, $mock_class, $methods) { + $mock_base = SimpleTestOptions::getMockBaseClass(); + $code = "class $mock_class extends $mock_base {\n"; + $code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n"; + $code .= " \$this->$mock_base(\$test, \$wildcard);\n"; + $code .= " }\n"; + $code .= Stub::_createHandlerCode($class, $mock_base, $methods); + $code .= "}\n"; + return $code; + } + + /** + * The extension class code as a string. The class + * composites a mock object and chains mocked methods + * to it. + * @param string $class Class to extend. + * @param string $mock_class New class name. + * @param array $methods Mocked methods. + * @return string Code for a new class. + * @static + * @access private + */ + function _extendClassCode($class, $mock_class, $methods) { + $mock_base = SimpleTestOptions::getMockBaseClass(); + $code = "class $mock_class extends $class {\n"; + $code .= " var \$_mock;\n"; + $code .= Mock::_addMethodList($methods); + $code .= "\n"; + $code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n"; + $code .= " \$this->_mock = new $mock_base(\$test, \$wildcard, false);\n"; + $code .= " }\n"; + $code .= Mock::_chainMockReturns(); + $code .= Mock::_chainMockExpectations(); + $code .= Mock::_overrideMethods($methods); + $code .= SimpleTestOptions::getPartialMockCode(); + $code .= "}\n"; + return $code; + } + + /** + * Creates a list of mocked methods for error checking. + * @param array $methods Mocked methods. + * @return string Code for a method list. + * @access private + */ + function _addMethodList($methods) { + return " var \$_mocked_methods = array('" . implode("', '", $methods) . "');\n"; + } + + /** + * Creates code to abandon the expectation if not mocked. + * @param string $alias Parameter name of method name. + * @return string Code for bail out. + * @access private + */ + function _bailOutIfNotMocked($alias) { + $code = " if (! in_array($alias, \$this->_mocked_methods)) {\n"; + $code .= " trigger_error(\"Method [$alias] is not mocked\");\n"; + $code .= " return;\n"; + $code .= " }\n"; + return $code; + } + + /** + * Creates source code for chaining to the composited + * mock object. + * @return string Code for mock set up. + * @access private + */ + function _chainMockReturns() { + $code = " function setReturnValue(\$method, \$value, \$args = false) {\n"; + $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->setReturnValue(\$method, \$value, \$args);\n"; + $code .= " }\n"; + $code .= " function setReturnValueAt(\$timing, \$method, \$value, \$args = false) {\n"; + $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n"; + $code .= " }\n"; + $code .= " function setReturnReference(\$method, &\$ref, \$args = false) {\n"; + $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->setReturnReference(\$method, \$ref, \$args);\n"; + $code .= " }\n"; + $code .= " function setReturnReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n"; + $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->setReturnReferenceAt(\$timing, \$method, \$ref, \$args);\n"; + $code .= " }\n"; + return $code; + } + + /** + * Creates source code for chaining to an aggregated + * mock object. + * @return string Code for expectations. + * @access private + */ + function _chainMockExpectations() { + $code = " function expectArguments(\$method, \$args = false) {\n"; + $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectArguments(\$method, \$args);\n"; + $code .= " }\n"; + $code .= " function expectArgumentsAt(\$timing, \$method, \$args = false) {\n"; + $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args);\n"; + $code .= " }\n"; + $code .= " function expectCallCount(\$method, \$count) {\n"; + $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectCallCount(\$method, \$count);\n"; + $code .= " }\n"; + $code .= " function expectMaximumCallCount(\$method, \$count) {\n"; + $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectMaximumCallCount(\$method, \$count);\n"; + $code .= " }\n"; + $code .= " function expectMinimumCallCount(\$method, \$count) {\n"; + $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectMinimumCallCount(\$method, \$count);\n"; + $code .= " }\n"; + $code .= " function expectNever(\$method) {\n"; + $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectNever(\$method);\n"; + $code .= " }\n"; + $code .= " function expectOnce(\$method, \$args = false) {\n"; + $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectOnce(\$method, \$args);\n"; + $code .= " }\n"; + $code .= " function expectAtLeastOnce(\$method, \$args = false) {\n"; + $code .= Mock::_bailOutIfNotMocked("\$method"); + $code .= " \$this->_mock->expectAtLeastOnce(\$method, \$args);\n"; + $code .= " }\n"; + $code .= " function tally() {\n"; + $code .= " \$this->_mock->tally();\n"; + $code .= " }\n"; + return $code; + } + + /** + * Creates source code to override a list of methods + * with mock versions. + * @param array $methods Methods to be overridden + * with mock versions. + * @return string Code for overridden chains. + * @access private + */ + function _overrideMethods($methods) { + $code = ""; + foreach ($methods as $method) { + $code .= " function $method() {\n"; + $code .= " \$args = func_get_args();\n"; + $code .= " return \$this->_mock->_invoke(\"$method\", \$args);\n"; + $code .= " }\n"; + } + return $code; + } + + /** + * Uses a stack trace to find the line of an assertion. + * @param string $format String formatting. + * @param array $stack Stack frames top most first. Only + * needed if not using the PHP + * backtrace function. + * @return string Line number of first expect* + * method embedded in format string. + * @access public + * @static + */ + function getExpectationLine($format = '%d', $stack = false) { + if ($stack === false) { + $stack = SimpleTestCompatibility::getStackTrace(); + } + return SimpleDumper::getFormattedAssertionLine($stack, $format, 'expect'); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/mytests/log_test.php b/tests/UnitTests/simpletest/mytests/log_test.php new file mode 100644 index 00000000..d1254b7a --- /dev/null +++ b/tests/UnitTests/simpletest/mytests/log_test.php @@ -0,0 +1,18 @@ +assertFalse(false); + //$log->message('Should write this to a file'); + $this->assertTrue(true); + } +} + +$test = new TestOfLogging(); +$test->run(new HtmlReporter()); + +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/options.php b/tests/UnitTests/simpletest/options.php new file mode 100644 index 00000000..63b6b996 --- /dev/null +++ b/tests/UnitTests/simpletest/options.php @@ -0,0 +1,366 @@ + 'SimpleStub', + 'MockBaseClass' => 'SimpleMock', + 'IgnoreList' => array(), + 'AdditionalPartialMockCode' => '', + 'DefaultProxy' => false, + 'DefaultProxyUsername' => false, + 'DefaultProxyPassword' => false); + } + } + + /** + * Static methods for compatibility between different + * PHP versions. + * @package SimpleTest + */ + class SimpleTestCompatibility { + + /** + * Identity test. Drops back to equality + types for PHP5 + * objects as the === operator counts as the + * stronger reference constraint. + * @param mixed $first Test subject. + * @param mixed $second Comparison object. + * @access public + * @static + */ + function isIdentical($first, $second) { + if ($first != $second) { + return false; + } + if (version_compare(phpversion(), '5') >= 0) { + return SimpleTestCompatibility::_isIdenticalType($first, $second); + } + return ($first === $second); + } + + /** + * Recursive type test. + * @param mixed $first Test subject. + * @param mixed $second Comparison object. + * @access private + * @static + */ + function _isIdenticalType($first, $second) { + if (gettype($first) != gettype($second)) { + return false; + } + if (is_object($first) && is_object($second)) { + if (get_class($first) != get_class($second)) { + return false; + } + return SimpleTestCompatibility::_isArrayOfIdenticalTypes( + get_object_vars($first), + get_object_vars($second)); + } + if (is_array($first) && is_array($second)) { + return SimpleTestCompatibility::_isArrayOfIdenticalTypes($first, $second); + } + return true; + } + + /** + * Recursive type test for each element of an array. + * @param mixed $first Test subject. + * @param mixed $second Comparison object. + * @access private + * @static + */ + function _isArrayOfIdenticalTypes($first, $second) { + if (array_keys($first) != array_keys($second)) { + return false; + } + foreach (array_keys($first) as $key) { + $is_identical = SimpleTestCompatibility::_isIdenticalType( + $first[$key], + $second[$key]); + if (! $is_identical) { + return false; + } + } + return true; + } + + /** + * Test for two variables being aliases. + * @param mixed $first Test subject. + * @param mixed $second Comparison object. + * @access public + * @static + */ + function isReference($first, $second) { + if (version_compare(phpversion(), '5', '>=') + && is_object($first)) { + return ($first === $second); + } + $temp = $first; + $first = uniqid("test"); + $is_ref = ($first === $second); + $first = $temp; + return $is_ref; + } + + /** + * Test to see if an object is a member of a + * class hiearchy. + * @param object $object Object to test. + * @param string $class Root name of hiearchy. + * @access public + * @static + */ + function isA($object, $class) { + if (version_compare(phpversion(), '5') >= 0) { + if (! class_exists($class, false)) { + return false; + } + eval("\$is_a = \$object instanceof $class;"); + return $is_a; + } + if (function_exists('is_a')) { + return is_a($object, $class); + } + return ((strtolower($class) == get_class($object)) + or (is_subclass_of($object, $class))); + } + + /** + * Autoload safe version of class_exists(). + * @param string $class Name of class to look for. + * @return boolean True if class is defined. + * @access public + * @static + */ + function classExists($class) { + if (version_compare(phpversion(), '5') >= 0) { + return class_exists($class, false); + } else { + return class_exists($class); + } + } + + /** + * Sets a socket timeout for each chunk. + * @param resource $handle Socket handle. + * @param integer $timeout Limit in seconds. + * @access public + * @static + */ + function setTimeout($handle, $timeout) { + if (function_exists('stream_set_timeout')) { + stream_set_timeout($handle, $timeout, 0); + } elseif (function_exists('socket_set_timeout')) { + socket_set_timeout($handle, $timeout, 0); + } elseif (function_exists('set_socket_timeout')) { + set_socket_timeout($handle, $timeout, 0); + } + } + + /** + * Gets the current stack trace topmost first. + * @return array List of stack frames. + * @access public + * @static + */ + function getStackTrace() { + if (function_exists('debug_backtrace')) { + return array_reverse(debug_backtrace()); + } + return array(); + } + } +?> diff --git a/tests/UnitTests/simpletest/page.php b/tests/UnitTests/simpletest/page.php new file mode 100644 index 00000000..03091d3e --- /dev/null +++ b/tests/UnitTests/simpletest/page.php @@ -0,0 +1,961 @@ +SimpleSaxListener(); + } + + /** + * Reads the raw content and send events + * into the page to be built. + * @param $response SimpleHttpResponse Fetched response. + * @return SimplePage Newly parsed page. + * @access public + */ + function parse($response) { + $this->_tags = array(); + $this->_page = $this->_createPage($response); + $parser = $this->_createParser($this); + $parser->parse($response->getContent()); + $this->_page->acceptPageEnd(); + return $this->_page; + } + + /** + * Creates an empty page. + * @return SimplePage New unparsed page. + * @access protected + */ + function _createPage($response) { + return new SimplePage($response); + } + + /** + * Creates the parser used with the builder. + * @param $listener SimpleSaxListener Target of parser. + * @return SimpleSaxParser Parser to generate + * events for the builder. + * @access protected + */ + function _createParser($listener) { + return new SimpleSaxParser($listener); + } + + /** + * Make the keys lower case for case insensitive look-ups. + * @param hash $map Hash to convert. + * @return hash Unchanged values, but keys lower case. + * @access private + */ + function _keysToLowerCase($map) { + $lower = array(); + foreach ($map as $key => $value) { + $lower[strtolower($key)] = $value; + } + return $lower; + } + + /** + * Start of element event. Opens a new tag. + * @param string $name Element name. + * @param hash $attributes Attributes without content + * are marked as true. + * @return boolean False on parse error. + * @access public + */ + function startElement($name, $attributes) { + $tag = $this->_createTag($name, $this->_keysToLowerCase($attributes)); + if ($name == 'form') { + $this->_page->acceptFormStart($tag); + return true; + } + if ($name == 'frameset') { + $this->_page->acceptFramesetStart($tag); + return true; + } + if ($name == 'frame') { + $this->_page->acceptFrame($tag); + return true; + } + if ($tag->expectEndTag()) { + $this->_openTag($tag); + return true; + } + $this->_page->acceptTag($tag); + return true; + } + + /** + * End of element event. + * @param string $name Element name. + * @return boolean False on parse error. + * @access public + */ + function endElement($name) { + if ($name == 'form') { + $this->_page->acceptFormEnd(); + return true; + } + if ($name == 'frameset') { + $this->_page->acceptFramesetEnd(); + return true; + } + if (isset($this->_tags[$name]) && (count($this->_tags[$name]) > 0)) { + $tag = array_pop($this->_tags[$name]); + $this->_addContentTagToOpenTags($tag); + $this->_page->acceptTag($tag); + return true; + } + return true; + } + + /** + * Unparsed, but relevant data. The data is added + * to every open tag. + * @param string $text May include unparsed tags. + * @return boolean False on parse error. + * @access public + */ + function addContent($text) { + foreach (array_keys($this->_tags) as $name) { + for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) { + $this->_tags[$name][$i]->addContent($text); + } + } + return true; + } + + /** + * Parsed relevant data. The parsed tag is added + * to every open tag. + * @param SimpleTag $tag May include unparsed tags. + * @access private + */ + function _addContentTagToOpenTags($tag) { + if ($tag->getTagName() != 'option') { + return; + } + foreach (array_keys($this->_tags) as $name) { + for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) { + $this->_tags[$name][$i]->addTag($tag); + } + } + } + + /** + * Opens a tag for receiving content. Multiple tags + * will be receiving input at the same time. + * @param SimpleTag $tag New content tag. + * @access private + */ + function _openTag($tag) { + $name = $tag->getTagName(); + if (! in_array($name, array_keys($this->_tags))) { + $this->_tags[$name] = array(); + } + array_push($this->_tags[$name], $tag); + } + + /** + * Factory for the tag objects. Creates the + * appropriate tag object for the incoming tag name. + * @param string $name HTML tag name. + * @param hash $attributes Element attributes. + * @return SimpleTag Tag object. + * @access protected + */ + function _createTag($name, $attributes) { + if ($name == 'a') { + return new SimpleAnchorTag($attributes); + } elseif ($name == 'title') { + return new SimpleTitleTag($attributes); + } elseif ($name == 'input') { + return $this->_createInputTag($attributes); + } elseif ($name == 'button') { + return new SimpleButtonTag($attributes); + } elseif ($name == 'textarea') { + return new SimpleTextAreaTag($attributes); + } elseif ($name == 'select') { + return $this->_createSelectionTag($attributes); + } elseif ($name == 'option') { + return new SimpleOptionTag($attributes); + } elseif ($name == 'form') { + return new SimpleFormTag($attributes); + } elseif ($name == 'frame') { + return new SimpleFrameTag($attributes); + } + return new SimpleTag($name, $attributes); + } + + /** + * Factory for selection fields. + * @param hash $attributes Element attributes. + * @return SimpleTag Tag object. + * @access protected + */ + function _createSelectionTag($attributes) { + if (isset($attributes['multiple'])) { + return new MultipleSelectionTag($attributes); + } + return new SimpleSelectionTag($attributes); + } + + /** + * Factory for input tags. + * @param hash $attributes Element attributes. + * @return SimpleTag Tag object. + * @access protected + */ + function _createInputTag($attributes) { + if (! isset($attributes['type'])) { + return new SimpleTextTag($attributes); + } + $type = strtolower($attributes['type']); + if ($type == 'submit') { + return new SimpleSubmitTag($attributes); + } elseif ($type == 'image') { + return new SimpleImageSubmitTag($attributes); + } elseif ($type == 'checkbox') { + return new SimpleCheckboxTag($attributes); + } elseif ($type == 'radio') { + return new SimpleRadioButtonTag($attributes); + } else { + return new SimpleTextTag($attributes); + } + } + } + + /** + * A wrapper for a web page. + * @package SimpleTest + * @subpackage WebTester + */ + class SimplePage { + protected $_links; + protected $_title; + protected $_open_forms; + protected $_complete_forms; + protected $_frameset; + protected $_frames; + protected $_frameset_nesting_level; + protected $_transport_error; + protected $_raw; + protected $_text; + protected $_sent; + protected $_headers; + protected $_method; + protected $_url; + protected $_request_data; + + /** + * Parses a page ready to access it's contents. + * @param SimpleHttpResponse $response Result of HTTP fetch. + * @access public + */ + function SimplePage($response = false) { + $this->_links = array(); + $this->_title = false; + $this->_open_forms = array(); + $this->_complete_forms = array(); + $this->_frameset = false; + $this->_frames = array(); + $this->_frameset_nesting_level = 0; + $this->_text = false; + if ($response) { + $this->_extractResponse($response); + } else { + $this->_noResponse(); + } + } + + /** + * Extracts all of the response information. + * @param SimpleHttpResponse $response Response being parsed. + * @access private + */ + function _extractResponse($response) { + $this->_transport_error = $response->getError(); + $this->_raw = $response->getContent(); + $this->_sent = $response->getSent(); + $this->_headers = $response->getHeaders(); + $this->_method = $response->getMethod(); + $this->_url = $response->getUrl(); + $this->_request_data = $response->getRequestData(); + } + + /** + * Sets up a missing response. + * @access private + */ + function _noResponse() { + $this->_transport_error = 'No page fetched yet'; + $this->_raw = false; + $this->_sent = false; + $this->_headers = false; + $this->_method = 'GET'; + $this->_url = false; + $this->_request_data = false; + } + + /** + * Original request as bytes sent down the wire. + * @return mixed Sent content. + * @access public + */ + function getRequest() { + return $this->_sent; + } + + /** + * Accessor for raw text of page. + * @return string Raw unparsed content. + * @access public + */ + function getRaw() { + return $this->_raw; + } + + /** + * Accessor for plain text of page as a text browser + * would see it. + * @return string Plain text of page. + * @access public + */ + function getText() { + if (! $this->_text) { + $this->_text = SimpleSaxParser::normalise($this->_raw); + } + return $this->_text; + } + + /** + * Accessor for raw headers of page. + * @return string Header block as text. + * @access public + */ + function getHeaders() { + if ($this->_headers) { + return $this->_headers->getRaw(); + } + return false; + } + + /** + * Original request method. + * @return string GET, POST or HEAD. + * @access public + */ + function getMethod() { + return $this->_method; + } + + /** + * Original resource name. + * @return SimpleUrl Current url. + * @access public + */ + function getUrl() { + return $this->_url; + } + + /** + * Original request data. + * @return mixed Sent content. + * @access public + */ + function getRequestData() { + return $this->_request_data; + } + + /** + * Accessor for last error. + * @return string Error from last response. + * @access public + */ + function getTransportError() { + return $this->_transport_error; + } + + /** + * Accessor for current MIME type. + * @return string MIME type as string; e.g. 'text/html' + * @access public + */ + function getMimeType() { + if ($this->_headers) { + return $this->_headers->getMimeType(); + } + return false; + } + + /** + * Accessor for HTTP response code. + * @return integer HTTP response code received. + * @access public + */ + function getResponseCode() { + if ($this->_headers) { + return $this->_headers->getResponseCode(); + } + return false; + } + + /** + * Accessor for last Authentication type. Only valid + * straight after a challenge (401). + * @return string Description of challenge type. + * @access public + */ + function getAuthentication() { + if ($this->_headers) { + return $this->_headers->getAuthentication(); + } + return false; + } + + /** + * Accessor for last Authentication realm. Only valid + * straight after a challenge (401). + * @return string Name of security realm. + * @access public + */ + function getRealm() { + if ($this->_headers) { + return $this->_headers->getRealm(); + } + return false; + } + + /** + * Accessor for current frame focus. Will be + * false as no frames. + * @return array Always empty. + * @access public + */ + function getFrameFocus() { + return array(); + } + + /** + * Sets the focus by index. The integer index starts from 1. + * @param integer $choice Chosen frame. + * @return boolean Always false. + * @access public + */ + function setFrameFocusByIndex($choice) { + return false; + } + + /** + * Sets the focus by name. Always fails for a leaf page. + * @param string $name Chosen frame. + * @return boolean False as no frames. + * @access public + */ + function setFrameFocus($name) { + return false; + } + + /** + * Clears the frame focus. Does nothing for a leaf page. + * @access public + */ + function clearFrameFocus() { + } + + /** + * Adds a tag to the page. + * @param SimpleTag $tag Tag to accept. + * @access public + */ + function acceptTag($tag) { + if ($tag->getTagName() == "a") { + $this->_addLink($tag); + } elseif ($tag->getTagName() == "title") { + $this->_setTitle($tag); + } elseif ($this->_isFormElement($tag->getTagName())) { + for ($i = 0; $i < count($this->_open_forms); $i++) { + $this->_open_forms[$i]->addWidget($tag); + } + } + } + + /** + * Tests to see if a tag is a possible form + * element. + * @param string $name HTML element name. + * @return boolean True if form element. + * @access private + */ + function _isFormElement($name) { + return in_array($name, array('input', 'button', 'textarea', 'select')); + } + + /** + * Opens a form. New widgets go here. + * @param SimpleFormTag $tag Tag to accept. + * @access public + */ + function acceptFormStart($tag) { + $this->_open_forms[] = new SimpleForm($tag, $this->getUrl()); + } + + /** + * Closes the most recently opened form. + * @access public + */ + function acceptFormEnd() { + if (count($this->_open_forms)) { + $this->_complete_forms[] = array_pop($this->_open_forms); + } + } + + /** + * Opens a frameset. A frameset may contain nested + * frameset tags. + * @param SimpleFramesetTag $tag Tag to accept. + * @access public + */ + function acceptFramesetStart($tag) { + if (! $this->_isLoadingFrames()) { + $this->_frameset = $tag; + } + $this->_frameset_nesting_level++; + } + + /** + * Closes the most recently opened frameset. + * @access public + */ + function acceptFramesetEnd() { + if ($this->_isLoadingFrames()) { + $this->_frameset_nesting_level--; + } + } + + /** + * Takes a single frame tag and stashes it in + * the current frame set. + * @param SimpleFrameTag $tag Tag to accept. + * @access public + */ + function acceptFrame($tag) { + if ($this->_isLoadingFrames()) { + if ($tag->getAttribute('src')) { + $this->_frames[] = $tag; + } + } + } + + /** + * Test to see if in the middle of reading + * a frameset. + * @return boolean True if inframeset. + * @access private + */ + function _isLoadingFrames() { + if (! $this->_frameset) { + return false; + } + return ($this->_frameset_nesting_level > 0); + } + + /** + * Test to see if link is an absolute one. + * @param string $url Url to test. + * @return boolean True if absolute. + * @access protected + */ + function _linkIsAbsolute($url) { + $parsed = new SimpleUrl($url); + return (boolean)($parsed->getScheme() && $parsed->getHost()); + } + + /** + * Adds a link to the page. + * @param SimpleAnchorTag $tag Link to accept. + * @access protected + */ + function _addLink($tag) { + $this->_links[] = $tag; + } + + /** + * Marker for end of complete page. Any work in + * progress can now be closed. + * @access public + */ + function acceptPageEnd() { + while (count($this->_open_forms)) { + $this->_complete_forms[] = array_pop($this->_open_forms); + } + } + + /** + * Test for the presence of a frameset. + * @return boolean True if frameset. + * @access public + */ + function hasFrames() { + return (boolean)$this->_frameset; + } + + /** + * Accessor for frame name and source URL for every frame that + * will need to be loaded. Immediate children only. + * @return boolean/array False if no frameset or + * otherwise a hash of frame URLs. + * The key is either a numerical + * base one index or the name attribute. + * @access public + */ + function getFrameset() { + if (! $this->_frameset) { + return false; + } + $urls = array(); + for ($i = 0; $i < count($this->_frames); $i++) { + $name = $this->_frames[$i]->getAttribute('name'); + $url = new SimpleUrl($this->_frames[$i]->getAttribute('src')); + $urls[$name ? $name : $i + 1] = $url->makeAbsolute($this->getUrl()); + } + return $urls; + } + + /** + * Fetches a list of loaded frames. + * @return array/string Just the URL for a single page. + * @access public + */ + function getFrames() { + $url = $this->getUrl(); + return $url->asString(); + } + + /** + * Accessor for a list of all fixed links. + * @return array List of urls with scheme of + * http or https and hostname. + * @access public + */ + function getAbsoluteUrls() { + $all = array(); + foreach ($this->_links as $link) { + if ($this->_linkIsAbsolute($link->getHref())) { + $all[] = $link->getHref(); + } + } + return $all; + } + + /** + * Accessor for a list of all relative links. + * @return array List of urls without hostname. + * @access public + */ + function getRelativeUrls() { + $all = array(); + foreach ($this->_links as $link) { + if (! $this->_linkIsAbsolute($link->getHref())) { + $all[] = $link->getHref(); + } + } + return $all; + } + + /** + * Accessor for URLs by the link label. Label will match + * regardess of whitespace issues and case. + * @param string $label Text of link. + * @return array List of links with that label. + * @access public + */ + function getUrlsByLabel($label) { + $matches = array(); + foreach ($this->_links as $link) { + if ($link->getText() == $label) { + $matches[] = $this->_getUrlFromLink($link); + } + } + return $matches; + } + + /** + * Accessor for a URL by the id attribute. + * @param string $id Id attribute of link. + * @return SimpleUrl URL with that id of false if none. + * @access public + */ + function getUrlById($id) { + foreach ($this->_links as $link) { + if ($link->getAttribute('id') === (string)$id) { + return $this->_getUrlFromLink($link); + } + } + return false; + } + + /** + * Converts a link into a target URL. + * @param SimpleAnchor $link Parsed link. + * @return SimpleUrl URL with frame target if any. + * @access private + */ + function _getUrlFromLink($link) { + $url = $this->_makeAbsolute($link->getHref()); + if ($link->getAttribute('target')) { + $url->setTarget($link->getAttribute('target')); + } + return $url; + } + + /** + * Expands expandomatic URLs into fully qualified + * URLs. + * @param SimpleUrl $url Relative URL. + * @return SimpleUrl Absolute URL. + * @access protected + */ + function _makeAbsolute($url) { + if (! is_object($url)) { + $url = new SimpleUrl($url); + } + return $url->makeAbsolute($this->getUrl()); + } + + /** + * Sets the title tag contents. + * @param SimpleTitleTag $tag Title of page. + * @access protected + */ + function _setTitle($tag) { + $this->_title = $tag; + } + + /** + * Accessor for parsed title. + * @return string Title or false if no title is present. + * @access public + */ + function getTitle() { + if ($this->_title) { + return $this->_title->getText(); + } + return false; + } + + /** + * Finds a held form by button label. Will only + * search correctly built forms. + * @param string $label Button label, default 'Submit'. + * @return SimpleForm Form object containing the button. + * @access public + */ + function getFormBySubmitLabel($label) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->hasSubmitLabel($label)) { + return $this->_complete_forms[$i]; + } + } + return null; + } + + /** + * Finds a held form by button label. Will only + * search correctly built forms. + * @param string $name Button name attribute. + * @return SimpleForm Form object containing the button. + * @access public + */ + function getFormBySubmitName($name) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->hasSubmitName($name)) { + return $this->_complete_forms[$i]; + } + } + return null; + } + + /** + * Finds a held form by button id. Will only + * search correctly built forms. + * @param string $id Button ID attribute. + * @return SimpleForm Form object containing the button. + * @access public + */ + function getFormBySubmitId($id) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->hasSubmitId($id)) { + return $this->_complete_forms[$i]; + } + } + return null; + } + + /** + * Finds a held form by image label. Will only + * search correctly built forms. + * @param string $label Usually the alt attribute. + * @return SimpleForm Form object containing the image. + * @access public + */ + function getFormByImageLabel($label) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->hasImageLabel($label)) { + return $this->_complete_forms[$i]; + } + } + return null; + } + + /** + * Finds a held form by image button id. Will only + * search correctly built forms. + * @param string $name Image name. + * @return SimpleForm Form object containing the image. + * @access public + */ + function getFormByImageName($name) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->hasImageName($name)) { + return $this->_complete_forms[$i]; + } + } + return null; + } + + /** + * Finds a held form by image button id. Will only + * search correctly built forms. + * @param string $id Image ID attribute. + * @return SimpleForm Form object containing the image. + * @access public + */ + function getFormByImageId($id) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->hasImageId($id)) { + return $this->_complete_forms[$i]; + } + } + return null; + } + + /** + * Finds a held form by the form ID. A way of + * identifying a specific form when we have control + * of the HTML code. + * @param string $id Form label. + * @return SimpleForm Form object containing the matching ID. + * @access public + */ + function getFormById($id) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->getId() == $id) { + return $this->_complete_forms[$i]; + } + } + return null; + } + + /** + * Sets a field on each form in which the field is + * available. + * @param string $name Field name. + * @param string $value Value to set field to. + * @return boolean True if value is valid. + * @access public + */ + function setField($name, $value) { + $is_set = false; + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->setField($name, $value)) { + $is_set = true; + } + } + return $is_set; + } + + /** + * Sets a field on the form in which the unique field is + * available. + * @param string/integer $id Field ID attribute. + * @param string $value Value to set field to. + * @return boolean True if value is valid. + * @access public + */ + function setFieldById($id, $value) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + if ($this->_complete_forms[$i]->setFieldById($id, $value)) { + return true; + } + } + return false; + } + + /** + * Accessor for a form element value within a page. + * Finds the first match. + * @param string $name Field name. + * @return string/boolean A string if the field is + * present, false if unchecked + * and null if missing. + * @access public + */ + function getField($name) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + $value = $this->_complete_forms[$i]->getValue($name); + if (isset($value)) { + return $value; + } + } + return null; + } + + /** + * Accessor for a form element value within a page. + * Finds the first match. + * @param string/integer $id Field ID attribute. + * @return string/boolean A string if the field is + * present, false if unchecked + * and null if missing. + * @access public + */ + function getFieldById($id) { + for ($i = 0; $i < count($this->_complete_forms); $i++) { + $value = $this->_complete_forms[$i]->getValueById($id); + if (isset($value)) { + return $value; + } + } + return null; + } + } +?> diff --git a/tests/UnitTests/simpletest/parser.php b/tests/UnitTests/simpletest/parser.php new file mode 100644 index 00000000..cb9a3e75 --- /dev/null +++ b/tests/UnitTests/simpletest/parser.php @@ -0,0 +1,750 @@ +_case = $case; + $this->_patterns = array(); + $this->_labels = array(); + $this->_regex = null; + } + + /** + * Adds a pattern with an optional label. + * @param string $pattern Perl style regex, but ( and ) + * lose the usual meaning. + * @param string $label Label of regex to be returned + * on a match. + * @access public + */ + function addPattern($pattern, $label = true) { + $count = count($this->_patterns); + $this->_patterns[$count] = $pattern; + $this->_labels[$count] = $label; + $this->_regex = null; + } + + /** + * Attempts to match all patterns at once against + * a string. + * @param string $subject String to match against. + * @param string $match First matched portion of + * subject. + * @return boolean True on success. + * @access public + */ + function match($subject, $match) { + if (count($this->_patterns) == 0) { + return false; + } + if (! preg_match($this->_getCompoundedRegex(), $subject, $matches)) { + $match = ''; + return false; + } + $match = $matches[0]; + for ($i = 1; $i < count($matches); $i++) { + if ($matches[$i]) { + return $this->_labels[$i - 1]; + } + } + return true; + } + + /** + * Compounds the patterns into a single + * regular expression separated with the + * "or" operator. Caches the regex. + * Will automatically escape (, ) and / tokens. + * @param array $patterns List of patterns in order. + * @access private + */ + function _getCompoundedRegex() { + if ($this->_regex == null) { + for ($i = 0, $count = count($this->_patterns); $i < $count; $i++) { + $this->_patterns[$i] = '(' . str_replace( + array('/', '(', ')'), + array('\/', '\(', '\)'), + $this->_patterns[$i]) . ')'; + } + $this->_regex = "/" . implode("|", $this->_patterns) . "/" . $this->_getPerlMatchingFlags(); + } + return $this->_regex; + } + + /** + * Accessor for perl regex mode flags to use. + * @return string Perl regex flags. + * @access private + */ + function _getPerlMatchingFlags() { + return ($this->_case ? "msS" : "msSi"); + } + } + + /** + * States for a stack machine. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleStateStack { + protected $_stack; + + /** + * Constructor. Starts in named state. + * @param string $start Starting state name. + * @access public + */ + function SimpleStateStack($start) { + $this->_stack = array($start); + } + + /** + * Accessor for current state. + * @return string State. + * @access public + */ + function getCurrent() { + return $this->_stack[count($this->_stack) - 1]; + } + + /** + * Adds a state to the stack and sets it + * to be the current state. + * @param string $state New state. + * @access public + */ + function enter($state) { + array_push($this->_stack, $state); + } + + /** + * Leaves the current state and reverts + * to the previous one. + * @return boolean False if we drop off + * the bottom of the list. + * @access public + */ + function leave() { + if (count($this->_stack) == 1) { + return false; + } + array_pop($this->_stack); + return true; + } + } + + /** + * Accepts text and breaks it into tokens. + * Some optimisation to make the sure the + * content is only scanned by the PHP regex + * parser once. Lexer modes must not start + * with leading underscores. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleLexer { + protected $_regexes; + protected $_parser; + protected $_mode; + protected $_mode_handlers; + protected $_case; + + /** + * Sets up the lexer in case insensitive matching + * by default. + * @param SimpleSaxParser $parser Handling strategy by + * reference. + * @param string $start Starting handler. + * @param boolean $case True for case sensitive. + * @access public + */ + function SimpleLexer($parser, $start = "accept", $case = false) { + $this->_case = $case; + $this->_regexes = array(); + $this->_parser = $parser; + $this->_mode = new SimpleStateStack($start); + $this->_mode_handlers = array($start => $start); + } + + /** + * Adds a token search pattern for a particular + * parsing mode. The pattern does not change the + * current mode. + * @param string $pattern Perl style regex, but ( and ) + * lose the usual meaning. + * @param string $mode Should only apply this + * pattern when dealing with + * this type of input. + * @access public + */ + function addPattern($pattern, $mode = "accept") { + if (! isset($this->_regexes[$mode])) { + $this->_regexes[$mode] = new ParallelRegex($this->_case); + } + $this->_regexes[$mode]->addPattern($pattern); + if (! isset($this->_mode_handlers[$mode])) { + $this->_mode_handlers[$mode] = $mode; + } + } + + /** + * Adds a pattern that will enter a new parsing + * mode. Useful for entering parenthesis, strings, + * tags, etc. + * @param string $pattern Perl style regex, but ( and ) + * lose the usual meaning. + * @param string $mode Should only apply this + * pattern when dealing with + * this type of input. + * @param string $new_mode Change parsing to this new + * nested mode. + * @access public + */ + function addEntryPattern($pattern, $mode, $new_mode) { + if (! isset($this->_regexes[$mode])) { + $this->_regexes[$mode] = new ParallelRegex($this->_case); + } + $this->_regexes[$mode]->addPattern($pattern, $new_mode); + if (! isset($this->_mode_handlers[$new_mode])) { + $this->_mode_handlers[$new_mode] = $new_mode; + } + } + + /** + * Adds a pattern that will exit the current mode + * and re-enter the previous one. + * @param string $pattern Perl style regex, but ( and ) + * lose the usual meaning. + * @param string $mode Mode to leave. + * @access public + */ + function addExitPattern($pattern, $mode) { + if (! isset($this->_regexes[$mode])) { + $this->_regexes[$mode] = new ParallelRegex($this->_case); + } + $this->_regexes[$mode]->addPattern($pattern, "__exit"); + if (! isset($this->_mode_handlers[$mode])) { + $this->_mode_handlers[$mode] = $mode; + } + } + + /** + * Adds a pattern that has a special mode. Acts as an entry + * and exit pattern in one go, effectively calling a special + * parser handler for this token only. + * @param string $pattern Perl style regex, but ( and ) + * lose the usual meaning. + * @param string $mode Should only apply this + * pattern when dealing with + * this type of input. + * @param string $special Use this mode for this one token. + * @access public + */ + function addSpecialPattern($pattern, $mode, $special) { + if (! isset($this->_regexes[$mode])) { + $this->_regexes[$mode] = new ParallelRegex($this->_case); + } + $this->_regexes[$mode]->addPattern($pattern, "_$special"); + if (! isset($this->_mode_handlers[$special])) { + $this->_mode_handlers[$special] = $special; + } + } + + /** + * Adds a mapping from a mode to another handler. + * @param string $mode Mode to be remapped. + * @param string $handler New target handler. + * @access public + */ + function mapHandler($mode, $handler) { + $this->_mode_handlers[$mode] = $handler; + } + + /** + * Splits the page text into tokens. Will fail + * if the handlers report an error or if no + * content is consumed. If successful then each + * unparsed and parsed token invokes a call to the + * held listener. + * @param string $raw Raw HTML text. + * @return boolean True on success, else false. + * @access public + */ + function parse($raw) { + if (! isset($this->_parser)) { + return false; + } + $length = strlen($raw); + while (is_array($parsed = $this->_reduce($raw))) { + list($raw, $unmatched, $matched, $mode) = $parsed; + if (! $this->_dispatchTokens($unmatched, $matched, $mode)) { + return false; + } + if ($raw === '') { + return true; + } + if (strlen($raw) == $length) { + return false; + } + $length = strlen($raw); + } + if (! $parsed) { + return false; + } + return $this->_invokeParser($raw, LEXER_UNMATCHED); + } + + /** + * Sends the matched token and any leading unmatched + * text to the parser changing the lexer to a new + * mode if one is listed. + * @param string $unmatched Unmatched leading portion. + * @param string $matched Actual token match. + * @param string $mode Mode after match. A boolean + * false mode causes no change. + * @return boolean False if there was any error + * from the parser. + * @access private + */ + function _dispatchTokens($unmatched, $matched, $mode = false) { + if (! $this->_invokeParser($unmatched, LEXER_UNMATCHED)) { + return false; + } + if (is_bool($mode)) { + return $this->_invokeParser($matched, LEXER_MATCHED); + } + if ($this->_isModeEnd($mode)) { + if (! $this->_invokeParser($matched, LEXER_EXIT)) { + return false; + } + return $this->_mode->leave(); + } + if ($this->_isSpecialMode($mode)) { + $this->_mode->enter($this->_decodeSpecial($mode)); + if (! $this->_invokeParser($matched, LEXER_SPECIAL)) { + return false; + } + return $this->_mode->leave(); + } + $this->_mode->enter($mode); + return $this->_invokeParser($matched, LEXER_ENTER); + } + + /** + * Tests to see if the new mode is actually to leave + * the current mode and pop an item from the matching + * mode stack. + * @param string $mode Mode to test. + * @return boolean True if this is the exit mode. + * @access private + */ + function _isModeEnd($mode) { + return ($mode === "__exit"); + } + + /** + * Test to see if the mode is one where this mode + * is entered for this token only and automatically + * leaves immediately afterwoods. + * @param string $mode Mode to test. + * @return boolean True if this is the exit mode. + * @access private + */ + function _isSpecialMode($mode) { + return (strncmp($mode, "_", 1) == 0); + } + + /** + * Strips the magic underscore marking single token + * modes. + * @param string $mode Mode to decode. + * @return string Underlying mode name. + * @access private + */ + function _decodeSpecial($mode) { + return substr($mode, 1); + } + + /** + * Calls the parser method named after the current + * mode. Empty content will be ignored. The lexer + * has a parser handler for each mode in the lexer. + * @param string $content Text parsed. + * @param boolean $is_match Token is recognised rather + * than unparsed data. + * @access private + */ + function _invokeParser($content, $is_match) { + if (($content === '') || ($content === false)) { + return true; + } + $handler = $this->_mode_handlers[$this->_mode->getCurrent()]; + return $this->_parser->$handler($content, $is_match); + } + + /** + * Tries to match a chunk of text and if successful + * removes the recognised chunk and any leading + * unparsed data. Empty strings will not be matched. + * @param string $raw The subject to parse. This is the + * content that will be eaten. + * @return array/boolean Three item list of unparsed + * content followed by the + * recognised token and finally the + * action the parser is to take. + * True if no match, false if there + * is a parsing error. + * @access private + */ + function _reduce($raw) { + if ($action = $this->_regexes[$this->_mode->getCurrent()]->match($raw, $match)) { + $unparsed_character_count = strpos($raw, $match); + $unparsed = substr($raw, 0, $unparsed_character_count); + $raw = substr($raw, $unparsed_character_count + strlen($match)); + return array($raw, $unparsed, $match, $action); + } + return true; + } + } + + /** + * Converts HTML tokens into selected SAX events. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleSaxParser { + protected $_lexer; + protected $_listener; + protected $_tag; + protected $_attributes; + protected $_current_attribute; + + /** + * Sets the listener. + * @param SimpleSaxListener $listener SAX event handler. + * @access public + */ + function SimpleSaxParser($listener) { + $this->_listener = $listener; + $this->_lexer = $this->createLexer($this); + $this->_tag = ''; + $this->_attributes = array(); + $this->_current_attribute = ''; + } + + /** + * Runs the content through the lexer which + * should call back to the acceptors. + * @param string $raw Page text to parse. + * @return boolean False if parse error. + * @access public + */ + function parse($raw) { + return $this->_lexer->parse($raw); + } + + /** + * Sets up the matching lexer. Starts in 'text' mode. + * @param SimpleSaxParser $parser Event generator, usually $self. + * @return SimpleLexer Lexer suitable for this parser. + * @access public + * @static + */ + function createLexer($parser) { + $lexer = new SimpleLexer($parser, 'text'); + $lexer->mapHandler('text', 'acceptTextToken'); + SimpleSaxParser::_addSkipping($lexer); + foreach (SimpleSaxParser::_getParsedTags() as $tag) { + SimpleSaxParser::_addTag($lexer, $tag); + } + SimpleSaxParser::_addInTagTokens($lexer); + return $lexer; + } + + /** + * List of parsed tags. Others are ignored. + * @return array List of searched for tags. + * @access private + */ + function _getParsedTags() { + return array('a', 'title', 'form', 'input', 'button', 'textarea', 'select', + 'option', 'frameset', 'frame'); + } + + /** + * The lexer has to skip certain sections such + * as server code, client code and styles. + * @param SimpleLexer $lexer Lexer to add patterns to. + * @access private + * @static + */ + function _addSkipping($lexer) { + $lexer->mapHandler('css', 'ignore'); + $lexer->addEntryPattern('addExitPattern('', 'css'); + $lexer->mapHandler('js', 'ignore'); + $lexer->addEntryPattern('addExitPattern('', 'js'); + $lexer->mapHandler('comment', 'ignore'); + $lexer->addEntryPattern('', 'comment'); + } + + /** + * Pattern matches to start and end a tag. + * @param SimpleLexer $lexer Lexer to add patterns to. + * @param string $tag Name of tag to scan for. + * @access private + * @static + */ + function _addTag($lexer, $tag) { + $lexer->addSpecialPattern("", 'text', 'acceptEndToken'); + $lexer->addEntryPattern("<$tag", 'text', 'tag'); + } + + /** + * Pattern matches to parse the inside of a tag + * including the attributes and their quoting. + * @param SimpleLexer $lexer Lexer to add patterns to. + * @access private + * @static + */ + function _addInTagTokens($lexer) { + $lexer->mapHandler('tag', 'acceptStartToken'); + $lexer->addSpecialPattern('\s+', 'tag', 'ignore'); + SimpleSaxParser::_addAttributeTokens($lexer); + $lexer->addExitPattern('>', 'tag'); + } + + /** + * Matches attributes that are either single quoted, + * double quoted or unquoted. + * @param SimpleLexer $lexer Lexer to add patterns to. + * @access private + * @static + */ + function _addAttributeTokens($lexer) { + $lexer->mapHandler('dq_attribute', 'acceptAttributeToken'); + $lexer->addEntryPattern('=\s*"', 'tag', 'dq_attribute'); + $lexer->addPattern("\\\\\"", 'dq_attribute'); + $lexer->addExitPattern('"', 'dq_attribute'); + $lexer->mapHandler('sq_attribute', 'acceptAttributeToken'); + $lexer->addEntryPattern("=\s*'", 'tag', 'sq_attribute'); + $lexer->addPattern("\\\\'", 'sq_attribute'); + $lexer->addExitPattern("'", 'sq_attribute'); + $lexer->mapHandler('uq_attribute', 'acceptAttributeToken'); + $lexer->addSpecialPattern('=\s*[^>\s]*', 'tag', 'uq_attribute'); + } + + /** + * Accepts a token from the tag mode. If the + * starting element completes then the element + * is dispatched and the current attributes + * set back to empty. The element or attribute + * name is converted to lower case. + * @param string $token Incoming characters. + * @param integer $event Lexer event type. + * @return boolean False if parse error. + * @access public + */ + function acceptStartToken($token, $event) { + if ($event == LEXER_ENTER) { + $this->_tag = strtolower(substr($token, 1)); + return true; + } + if ($event == LEXER_EXIT) { + $success = $this->_listener->startElement( + $this->_tag, + $this->_attributes); + $this->_tag = ""; + $this->_attributes = array(); + return $success; + } + if ($token != "=") { + $this->_current_attribute = strtolower(SimpleSaxParser::decodeHtml($token)); + $this->_attributes[$this->_current_attribute] = ""; + } + return true; + } + + /** + * Accepts a token from the end tag mode. + * The element name is converted to lower case. + * @param string $token Incoming characters. + * @param integer $event Lexer event type. + * @return boolean False if parse error. + * @access public + */ + function acceptEndToken($token, $event) { + if (! preg_match('/<\/(.*)>/', $token, $matches)) { + return false; + } + return $this->_listener->endElement(strtolower($matches[1])); + } + + /** + * Part of the tag data. + * @param string $token Incoming characters. + * @param integer $event Lexer event type. + * @return boolean False if parse error. + * @access public + */ + function acceptAttributeToken($token, $event) { + if ($event == LEXER_UNMATCHED) { + $this->_attributes[$this->_current_attribute] .= + SimpleSaxParser::decodeHtml($token); + } + if ($event == LEXER_SPECIAL) { + $this->_attributes[$this->_current_attribute] .= + preg_replace('/^=\s*/' , '', SimpleSaxParser::decodeHtml($token)); + } + return true; + } + + /** + * A character entity. + * @param string $token Incoming characters. + * @param integer $event Lexer event type. + * @return boolean False if parse error. + * @access public + */ + function acceptEntityToken($token, $event) { + } + + /** + * Character data between tags regarded as + * important. + * @param string $token Incoming characters. + * @param integer $event Lexer event type. + * @return boolean False if parse error. + * @access public + */ + function acceptTextToken($token, $event) { + return $this->_listener->addContent($token); + } + + /** + * Incoming data to be ignored. + * @param string $token Incoming characters. + * @param integer $event Lexer event type. + * @return boolean False if parse error. + * @access public + */ + function ignore($token, $event) { + return true; + } + + /** + * Decodes any HTML entities. + * @param string $html Incoming HTML. + * @return string Outgoing plain text. + * @access public + * @static + */ + function decodeHtml($html) { + static $translations; + if (! isset($translations)) { + $translations = array_flip(get_html_translation_table(HTML_ENTITIES)); + } + return strtr($html, $translations); + } + + /** + * Turns HTML into text browser visible text. Images + * are converted to their alt text and tags are supressed. + * Entities are converted to their visible representation. + * @param string $html HTML to convert. + * @return string Plain text. + * @access public + * @static + */ + function normalise($html) { + $text = preg_replace('||', ' \1 ', $html); + $text = preg_replace('||', ' \1 ', $text); + $text = preg_replace('||', ' \1 ', $text); + $text = preg_replace('|<.*?>|', '', $text); + $text = SimpleSaxParser::decodeHtml($text); + $text = preg_replace('|\s+|', ' ', $text); + return trim($text); + } + } + + /** + * SAX event handler. + * @package SimpleTest + * @subpackage WebTester + * @abstract + */ + class SimpleSaxListener { + + /** + * Sets the document to write to. + * @access public + */ + function SimpleSaxListener() { + } + + /** + * Start of element event. + * @param string $name Element name. + * @param hash $attributes Name value pairs. + * Attributes without content + * are marked as true. + * @return boolean False on parse error. + * @access public + */ + function startElement($name, $attributes) { + } + + /** + * End of element event. + * @param string $name Element name. + * @return boolean False on parse error. + * @access public + */ + function endElement($name) { + } + + /** + * Unparsed, but relevant data. + * @param string $text May include unparsed tags. + * @return boolean False on parse error. + * @access public + */ + function addContent($text) { + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/remote.php b/tests/UnitTests/simpletest/remote.php new file mode 100644 index 00000000..2639ba8c --- /dev/null +++ b/tests/UnitTests/simpletest/remote.php @@ -0,0 +1,115 @@ +_url = $url; + $this->_dry_url = $dry_url ? $dry_url : $url; + $this->_size = false; + } + + /** + * Accessor for the test name for subclasses. + * @return string Name of the test. + * @access public + */ + function getLabel() { + return $this->_url; + } + + /** + * Runs the top level test for this class. Currently + * reads the data as a single chunk. I'll fix this + * once I have added iteration to the browser. + * @param SimpleReporter $reporter Target of test results. + * @returns boolean True if no failures. + * @access public + */ + function run($reporter) { + $browser = $this->_createBrowser(); + $xml = $browser->get($this->_url); + if (! $xml) { + trigger_error('Cannot read remote test URL [' . $this->_url . ']'); + return false; + } + $parser = $this->_createParser($reporter); + if (! $parser->parse($xml)) { + trigger_error('Cannot parse incoming XML from [' . $this->_url . ']'); + return false; + } + return true; + } + + /** + * Creates a new web browser object for fetching + * the XML report. + * @return SimpleBrowser New browser. + * @access protected + */ + function _createBrowser() { + return new SimpleBrowser(); + } + + /** + * Creates the XML parser. + * @param SimpleReporter $reporter Target of test results. + * @return SimpleTestXmlListener XML reader. + * @access protected + */ + function _createParser($reporter) { + return new SimpleTestXmlParser($reporter); + } + + /** + * Accessor for the number of subtests. + * @return integer Number of test cases. + * @access public + */ + function getSize() { + if ($this->_size === false) { + $browser = $this->_createBrowser(); + $xml = $browser->get($this->_dry_url); + if (! $xml) { + trigger_error('Cannot read remote test URL [' . $this->_dry_url . ']'); + return false; + } + $reporter = new SimpleReporter(); + $parser = $this->_createParser($reporter); + if (! $parser->parse($xml)) { + trigger_error('Cannot parse incoming XML from [' . $this->_dry_url . ']'); + return false; + } + $this->_size = $reporter->getTestCaseCount(); + } + return $this->_size; + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/reporter.php b/tests/UnitTests/simpletest/reporter.php new file mode 100644 index 00000000..8abb18fc --- /dev/null +++ b/tests/UnitTests/simpletest/reporter.php @@ -0,0 +1,241 @@ +SimpleReporter(); + $this->_character_set = $character_set; + } + + /** + * Paints the top of the web page setting the + * title to the name of the starting test. + * @param string $test_name Name class of test. + * @access public + */ + function paintHeader($test_name) { + $this->sendNoCacheHeaders(); + print "\n\n$test_name\n"; + print "\n"; + print "\n"; + print "\n\n"; + print "

$test_name

\n"; + flush(); + } + + /** + * Send the headers necessary to ensure the page is + * reloaded on every request. Otherwise you could be + * scratching your head over out of date test data. + * @access public + * @static + */ + function sendNoCacheHeaders() { + if (! headers_sent()) { + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); + header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); + header("Cache-Control: no-store, no-cache, must-revalidate"); + header("Cache-Control: post-check=0, pre-check=0", false); + header("Pragma: no-cache"); + } + } + + /** + * Paints the CSS. Add additional styles here. + * @return string CSS code as text. + * @access protected + */ + function _getCss() { + return ".fail { color: red; } pre { background-color: lightgray; }"; + } + + /** + * Paints the end of the test with a summary of + * the passes and failures. + * @param string $test_name Name class of test. + * @access public + */ + function paintFooter($test_name) { + $colour = ($this->getFailCount() + $this->getExceptionCount() > 0 ? "red" : "green"); + print "
"; + 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 or exception. + * @param string $message Message is ignored. + * @access public + * @abstract + */ + function paintException($message) { + parent::paintException($message); + print "Exception: "; + $breadcrumb = $this->getTestList(); + array_shift($breadcrumb); + print implode(" -> ", $breadcrumb); + print " -> " . $this->_htmlEntities($message) . "
\n"; + } + + /** + * Paints formatted text such as dumped variables. + * @param string $message Text to show. + * @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 is ignored. + * @access public + * @abstract + */ + function paintException($message) { + parent::paintException($message); + print "Exception " . $this->getExceptionCount() . "!\n$message\n"; + } + + /** + * Paints formatted text such as dumped variables. + * @param string $message Text to show. + * @access public + */ + function paintFormattedMessage($message) { + print "$message\n"; + flush(); + } + } +?> diff --git a/tests/UnitTests/simpletest/runner.php b/tests/UnitTests/simpletest/runner.php new file mode 100644 index 00000000..5a14332d --- /dev/null +++ b/tests/UnitTests/simpletest/runner.php @@ -0,0 +1,300 @@ +_test_case = $test_case; + } + + /** + * Accessor for test case being run. + * @return SimpleTestCase Test case. + * @access public + */ + function getTestCase() { + return $this->_test_case; + } + + /** + * Invokes a test method and buffered with setUp() + * and tearDown() calls. + * @param string $method Test method to call. + * @access public + */ + function invoke($method) { + $this->_test_case->setUp(); + $this->_test_case->$method(); + $this->_test_case->tearDown(); + } + } + + /** + * Do nothing decorator. Just passes the invocation + * straight through. + * @package SimpleTest + * @subpackage UnitTester + */ + class SimpleInvokerDecorator { + protected $_invoker; + + /** + * Stores the invoker to wrap. + * @param SimpleInvoker $invoker Test method runner. + */ + function SimpleInvokerDecorator($invoker) { + $this->_invoker = $invoker; + } + + /** + * Accessor for test case being run. + * @return SimpleTestCase Test case. + * @access public + */ + function getTestCase() { + return $this->_invoker->getTestCase(); + } + + /** + * Invokes a test method and buffered with setUp() + * and tearDown() calls. + * @param string $method Test method to call. + * @access public + */ + function invoke($method) { + $this->_invoker->invoke($method); + } + } + + /** + * Extension that traps errors into an error queue. + * @package SimpleTest + * @subpackage UnitTester + */ + class SimpleErrorTrappingInvoker extends SimpleInvokerDecorator { + + /** + /** + * Stores the invoker to wrap. + * @param SimpleInvoker $invoker Test method runner. + */ + function SimpleErrorTrappingInvoker($invoker) { + $this->SimpleInvokerDecorator($invoker); + } + + /** + * Invokes a test method and dispatches any + * untrapped errors. Called back from + * the visiting runner. + * @param string $method Test method to call. + * @access public + */ + function invoke($method) { + set_error_handler('simpleTestErrorHandler'); + parent::invoke($method); + $queue = SimpleErrorQueue::instance(); + while (list($severity, $message, $file, $line, $globals) = $queue->extract()) { + $test_case = $this->getTestCase(); + $test_case->error($severity, $message, $file, $line, $globals); + } + restore_error_handler(); + } + } + + /** + * The standard runner. Will run every method starting + * with test Basically the + * Mediator pattern. + * @package SimpleTest + * @subpackage UnitTester + */ + class SimpleRunner { + protected $_test_case; + protected $_scorer; + + /** + * Takes in the test case and reporter to mediate between. + * @param SimpleTestCase $test_case Test case to run. + * @param SimpleScorer $scorer Reporter to receive events. + */ + function SimpleRunner($test_case, $scorer) { + $this->_test_case = $test_case; + $this->_scorer = $scorer; + } + + /** + * Accessor for test case being run. + * @return SimpleTestCase Test case. + * @access public + */ + function getTestCase() { + return $this->_test_case; + } + + /** + * Runs the test methods in the test case. + * @param SimpleTest $test_case Test case to run test on. + * @param string $method Name of test method. + * @access public + */ + function run() { + $methods = get_class_methods(get_class($this->_test_case)); + $invoker = $this->_test_case->createInvoker(); + foreach ($methods as $method) { + if (! $this->_isTest($method)) { + continue; + } + if ($this->_isConstructor($method)) { + continue; + } + $this->_scorer->paintMethodStart($method); + if ($this->_scorer->shouldInvoke($this->_test_case->getLabel(), $method)) { + $invoker->invoke($method); + } + $this->_scorer->paintMethodEnd($method); + } + } + + /** + * Tests to see if the method is the constructor and + * so should be ignored. + * @param string $method Method name to try. + * @return boolean True if constructor. + * @access protected + */ + function _isConstructor($method) { + return SimpleTestCompatibility::isA( + $this->_test_case, + strtolower($method)); + } + + /** + * Tests to see if the method is a test that should + * be run. Currently any method that starts with 'test' + * is a candidate. + * @param string $method Method name to try. + * @return boolean True if test method. + * @access protected + */ + function _isTest($method) { + return strtolower(substr($method, 0, 4)) == 'test'; + } + + /** + * Paints the start of a test method. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintMethodStart($test_name) { + $this->_scorer->paintMethodStart($test_name); + } + + /** + * Paints the end of a test method. + * @param string $test_name Name of test or other label. + * @access public + */ + function paintMethodEnd($test_name) { + $this->_scorer->paintMethodEnd($test_name); + } + + /** + * Chains to the wrapped reporter. + * @param string $message Message is ignored. + * @access public + */ + function paintPass($message) { + $this->_scorer->paintPass($message); + } + + /** + * Chains to the wrapped reporter. + * @param string $message Message is ignored. + * @access public + */ + function paintFail($message) { + $this->_scorer->paintFail($message); + } + + /** + * Chains to the wrapped reporter. + * @param string $message Text of error formatted by + * the test case. + * @access public + */ + function paintError($message) { + $this->_scorer->paintError($message); + } + + /** + * Chains to the wrapped reporter. + * @param Exception $exception Object thrown. + * @access public + */ + function paintException($exception) { + $this->_scorer->paintException($exception); + } + + /** + * Chains to the wrapped reporter. + * @param string $message Text to display. + * @access public + */ + function paintMessage($message) { + $this->_scorer->paintMessage($message); + } + + /** + * Chains to the wrapped reporter. + * @param string $message Text to display. + * @access public + */ + function paintFormattedMessage($message) { + $this->_scorer->paintFormattedMessage($message); + } + + /** + * Chains to the wrapped reporter. + * @param string $type Event type as text. + * @param mixed $payload Message or object. + * @return boolean Should return false if this + * type of signal should fail the + * test suite. + * @access public + */ + function paintSignal($type, $payload) { + $this->_scorer->paintSignal($type, $payload); + } + } +?> diff --git a/tests/UnitTests/simpletest/scorer.php b/tests/UnitTests/simpletest/scorer.php new file mode 100644 index 00000000..de14883c --- /dev/null +++ b/tests/UnitTests/simpletest/scorer.php @@ -0,0 +1,378 @@ +_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. + */ + 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; + } + + /** + * 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 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) { + } + + /** + * 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 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) { + } + + /** + * 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->paintException($message); + } + + /** + * Deals with PHP 5 throwing an exception + * This isn't really implemented yet. + * @param Exception $exception Object thrown. + * @access public + */ + function paintException($exception) { + $this->_exceptions++; + } + + /** + * Accessor for the number of passes so far. + * @return integer Number of passes. + * @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 { + protected $_test_stack; + protected $_size; + protected $_progress; + + /** + * Starts the display with no results in. + * @access public + */ + function SimpleReporter() { + $this->SimpleScorer(); + $this->_test_stack = array(); + $this->_size = null; + $this->_progress = 0; + } + + /** + * Paints the start of a group test. Will also paint + * the page header and footer if this is the + * 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'; + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/shell_tester.php b/tests/UnitTests/simpletest/shell_tester.php new file mode 100644 index 00000000..aeb7cac0 --- /dev/null +++ b/tests/UnitTests/simpletest/shell_tester.php @@ -0,0 +1,271 @@ +_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 taht are external to the + * PHP code, but support it in some way. + * @package SimpleTest + * @subpackage UnitTester + */ + class ShellTestCase extends SimpleTestCase { + protected $_current_shell; + protected $_last_status; + protected $_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(); + } + + /** + * 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->assertExpectation( + 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->assertExpectation( + new WantedPatternExpectation($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->assertExpectation( + new UnwantedPatternExpectation($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->assertExpectation( + new WantedPatternExpectation($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->assertExpectation( + new UnwantedPatternExpectation($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() { + return new SimpleShell(); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/simple_test.php b/tests/UnitTests/simpletest/simple_test.php new file mode 100644 index 00000000..519bac09 --- /dev/null +++ b/tests/UnitTests/simpletest/simple_test.php @@ -0,0 +1,553 @@ +_label = $label ? $label : get_class($this); + $this->_runner = false; + } + + /** + * Accessor for the test name for subclasses. + * @return string Name of the test. + * @access public + */ + function getLabel() { + return $this->_label; + } + + /** + * Used to invoke the single tests. + * @return SimpleInvoker Individual test runner. + * @access public + */ + function createInvoker() { + return new SimpleErrorTrappingInvoker(new SimpleInvoker($this)); + } + + /** + * Can modify the incoming reporter so as to run + * the tests differently. This version simply + * passes it straight through. + * @param SimpleReporter $reporter Incoming observer. + * @return SimpleReporter + * @access protected + */ + function _createRunner($reporter) { + return new SimpleRunner($this, $reporter); + } + + /** + * Uses reflection to run every method within itself + * starting with the string "test" unless a method + * is specified. + * @param SimpleReporter $reporter Current test reporter. + * @access public + */ + function run($reporter) { + $reporter->paintCaseStart($this->getLabel()); + $this->_runner = $this->_createRunner($reporter); + $this->_runner->run(); + $reporter->paintCaseEnd($this->getLabel()); + return $reporter->getStatus(); + } + + /** + * Sets up unit test wide variables at the start + * of each test method. To be overridden in + * actual user test cases. + * @access public + */ + 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() { + } + + /** + * Sends a pass event with a message. + * @param string $message Message to send. + * @access public + */ + function pass($message = "Pass") { + $this->_runner->paintPass($message . $this->getAssertionLine(' at line [%d]')); + } + + /** + * Sends a fail event with a message. + * @param string $message Message to send. + * @access public + */ + function fail($message = "Fail") { + $this->_runner->paintFail($message . $this->getAssertionLine(' at line [%d]')); + } + + /** + * Formats a PHP error and dispatches it to the + * runner. + * @param integer $severity PHP error code. + * @param string $message Text of error. + * @param string $file File error occoured in. + * @param integer $line Line number of error. + * @param hash $globals PHP super global arrays. + * @access public + */ + function error($severity, $message, $file, $line, $globals) { + $severity = SimpleErrorQueue::getSeverityAsString($severity); + $this->_runner->paintError( + "Unexpected PHP error [$message] severity [$severity] in [$file] line [$line]"); + } + + /** + * Sends a user defined event to the test runner. + * This is for small scale extension where + * both the test case and either the runner or + * display are subclassed. + * @param string $type Type of event. + * @param mixed $payload Object or message to deliver. + * @access public + */ + function signal($type, $payload) { + $this->_runner->paintSignal($type, $payload); + } + + /** + * Cancels any outstanding errors. + * @access public + */ + function swallowErrors() { + $queue = SimpleErrorQueue::instance(); + $queue->clear(); + } + + /** + * Runs an expectation directly, for extending the + * tests with new expectation classes. + * @param SimpleExpectation $expectation Expectation subclass. + * @param mixed $test_value Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertExpectation($expectation, $test_value, $message = '%s') { + return $this->assertTrue( + $expectation->test($test_value), + sprintf($message, $expectation->overlayMessage($test_value))); + } + + /** + * Called from within the test methods to register + * passes and failures. + * @param boolean $result Pass on true. + * @param string $message Message to display describing + * the test state. + * @return boolean True on pass + * @access public + */ + function assertTrue($result, $message = false) { + if (! $message) { + $message = 'True assertion got ' . ($result ? 'True' : 'False'); + } + if ($result) { + $this->pass($message); + return true; + } else { + $this->fail($message); + return false; + } + } + + /** + * Will be true on false and vice versa. False + * is the PHP definition of false, so that null, + * empty strings, zero and an empty array all count + * as false. + * @param boolean $result Pass on false. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertFalse($result, $message = false) { + if (! $message) { + $message = 'False assertion got ' . ($result ? 'True' : 'False'); + } + return $this->assertTrue(! $result, $message); + } + + /** + * Uses a stack trace to find the line of an assertion. + * @param string $format String formatting. + * @param array $stack Stack frames top most first. Only + * needed if not using the PHP + * backtrace function. + * @return string Line number of first assert* + * method embedded in format string. + * @access public + */ + function getAssertionLine($format = '%d', $stack = false) { + if ($stack === false) { + $stack = SimpleTestCompatibility::getStackTrace(); + } + return SimpleDumper::getFormattedAssertionLine($stack, $format); + } + + /** + * Sends a formatted dump of a variable to the + * test suite for those emergency debugging + * situations. + * @param mixed $variable Variable to display. + * @param string $message Message to display. + * @return mixed The original variable. + * @access public + */ + function dump($variable, $message = false) { + $formatted = SimpleDumper::dump($variable); + if ($message) { + $formatted = $message . "\n" . $formatted; + } + $this->_runner->paintFormattedMessage($formatted); + return $variable; + } + + /** + * Dispatches a text message straight to the + * test suite. Useful for status bar displays. + * @param string $message Message to show. + * @access public + */ + function sendMessage($message) { + $this->_runner->PaintMessage($message); + } + + /** + * Accessor for the number of subtests. + * @return integer Number of test cases. + * @access public + * @static + */ + function getSize() { + return 1; + } + } + + /** + * This is a composite test class for combining + * test cases and other RunnableTest classes into + * a group test. + * @package SimpleTest + * @subpackage UnitTester + */ + class GroupTest { + protected $_label; + protected $_test_cases; + protected $_old_track_errors; + protected $_xdebug_is_enabled; + + /** + * Sets the name of the test suite. + * @param string $label Name sent at the start and end + * of the test. + * @access public + */ + function GroupTest($label) { + $this->_label = $label; + $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) { + $this->_test_cases[] = $class; + } + + /** + * Builds a group test from a library of test cases. + * The new group is composed into this one. + * @param string $test_file File name of library with + * test case classes. + * @access public + */ + function addTestFile($test_file) { + $existing_classes = get_declared_classes(); + if ($error = $this->_requireWithError($test_file)) { + $this->addTestCase(new BadGroupTest($test_file, $error)); + return; + } + $classes = $this->_selectRunnableTests($existing_classes, get_declared_classes()); + if (count($classes) == 0) { + $this->addTestCase(new BadGroupTest($test_file, 'No new test cases')); + return; + } + $this->addTestCase($this->_createGroupFromClasses($test_file, $classes)); + } + + /** + * Requires a source file recording any syntax errors. + * @param string $file File name to require in. + * @return string/boolean An error message on failure or false + * if no errors. + * @access private + */ + function _requireWithError($file) { + $this->_enableErrorReporting(); + include($file); + $error = isset($php_errormsg) ? $php_errormsg : false; + $this->_disableErrorReporting(); + $self_inflicted = array( + 'Assigning the return value of new by reference is deprecated', + 'var: Deprecated. Please use the public/private/protected modifiers'); + if (in_array($error, $self_inflicted)) { + 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. + * @param array $existing_classes Classes before require(). + * @param array $new_classes Classes after require(). + * @return array New classes which are test + * cases that shouldn't be ignored. + * @access private + */ + function _selectRunnableTests($existing_classes, $new_classes) { + $classes = array(); + foreach ($new_classes as $class) { + if (in_array($class, $existing_classes)) { + continue; + } + if (! $this->_isTestCase($class)) { + continue; + } + $classes[] = $class; + } + return $classes; + } + + /** + * Builds a group test from a class list. + * @param string $title Title of new group. + * @param array $classes Test classes. + * @return GroupTest Group loaded with the new + * test cases. + * @access private + */ + function _createGroupFromClasses($title, $classes) { + $group = new GroupTest($title); + foreach ($classes as $class) { + if (SimpleTestOptions::isIgnored($class)) { + continue; + } + $group->addTestClass($class); + } + return $group; + } + + /** + * Test to see if a class is derived from the + * TestCase class. + * @param string $class Class name. + * @access private + */ + function _isTestCase($class) { + while ($class = get_parent_class($class)) { + $class = strtolower($class); + if ($class == "simpletestcase" || $class == "grouptest") { + return true; + } + } + return false; + } + + /** + * Invokes run() on all of the held test cases, instantiating + * them if necessary. + * @param SimpleReporter $reporter Current test reporter. + * @access public + */ + function run($reporter) { + $reporter->paintGroupStart($this->getLabel(), $this->getSize()); + for ($i = 0, $count = count($this->_test_cases); $i < $count; $i++) { + if (is_string($this->_test_cases[$i])) { + $class = $this->_test_cases[$i]; + $test = new $class(); + $test->run($reporter); + } else { + $this->_test_cases[$i]->run($reporter); + } + } + $reporter->paintGroupEnd($this->getLabel()); + return $reporter->getStatus(); + } + + /** + * Number of contained test cases. + * @return integer Total count of cases in the group. + * @access public + */ + function getSize() { + $count = 0; + foreach ($this->_test_cases as $case) { + if (is_string($case)) { + $count++; + } else { + $count += $case->getSize(); + } + } + return $count; + } + } + + /** + * This is a failing group test for when a test suite hasn't + * loaded properly. + * @package SimpleTest + * @subpackage UnitTester + */ + class BadGroupTest { + protected $_label; + protected $_error; + + /** + * Sets the name of the test suite and error message. + * @param string $label Name sent at the start and end + * of the test. + * @access public + */ + function BadGroupTest($label, $error) { + $this->_label = $label; + $this->_error = $error; + } + + /** + * Accessor for the test name for subclasses. + * @return string Name of the test. + * @access public + */ + function getLabel() { + return $this->_label; + } + + /** + * Sends a single error to the reporter. + * @param SimpleReporter $reporter Current test reporter. + * @access public + */ + function run($reporter) { + $reporter->paintGroupStart($this->getLabel(), $this->getSize()); + $reporter->paintFail('Bad GroupTest [' . $this->getLabel() . + '] with error [' . $this->_error . ']'); + $reporter->paintGroupEnd($this->getLabel()); + return $reporter->getStatus(); + } + + /** + * Number of contained test cases. Always zero. + * @return integer Total count of cases in the group. + * @access public + */ + function getSize() { + return 0; + } + } +?> diff --git a/tests/UnitTests/simpletest/socket.php b/tests/UnitTests/simpletest/socket.php new file mode 100644 index 00000000..77ee9c71 --- /dev/null +++ b/tests/UnitTests/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 { + protected $_handle; + protected $_is_open; + protected $_sent; + + /** + * Opens a socket for reading and writing. + * @param string $host Hostname to send request to. + * @param integer $port Port on remote machine to open. + * @param integer $timeout Connection timeout in seconds. + * @access public + */ + function SimpleSocket($host, $port, $timeout) { + $this->SimpleStickyError(); + $this->_is_open = false; + $this->_sent = ''; + if (! ($this->_handle = $this->_openSocket($host, $port, $error_number, $error, $timeout))) { + $this->_setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds"); + return; + } + $this->_is_open = true; + 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. + * @param integer $block_size Size of chunk to read. + * @return integer Incoming bytes. False + * on error. + * @access public + */ + function read($block_size = 255) { + if ($this->isError() || ! $this->isOpen()) { + return false; + } + $raw = @fread($this->_handle, $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/UnitTests/simpletest/tag.php b/tests/UnitTests/simpletest/tag.php new file mode 100644 index 00000000..dd674da2 --- /dev/null +++ b/tests/UnitTests/simpletest/tag.php @@ -0,0 +1,1241 @@ +_name = $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; + } + + /** + * 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 oflegal 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; + } + if ($this->_attributes[$label] === '') { + return true; + } + 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 SimpleSaxParser::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 { + protected $_value; + protected $_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->_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() { + $default = $this->getAttribute('value'); + if ($default === true) { + $default = ''; + } + if ($default === false) { + $default = ''; + } + return $default; + } + + /** + * 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; + } + } + + /** + * 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('name') === false) { + $this->_setAttribute('name', 'submit'); + } + 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(); + } + + /** + * Gets the values submitted as a form. + * @return array Hash of name and values. + * @access public + */ + function getSubmitValues() { + return array($this->getName() => $this->getValue()); + } + } + + /** + * 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'); + } + + /** + * Gets the values submitted as a form. + * @return array Hash of name and values. + * @access public + */ + function getSubmitValues($x, $y) { + return array( + $this->getName() . '.x' => $x, + $this->getName() . '.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(); + } + + /** + * Gets the values submitted as a form. Gone + * for the Mozilla defaults values. + * @return array Hash of name and values. + * @access public + */ + function getSubmitValues() { + if ($this->getAttribute('name') === false) { + return array(); + } + if ($this->getAttribute('value') === false) { + return array($this->getName() => ''); + } + return array($this->getName() => $this->getValue()); + } + } + + /** + * 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() { + if ($this->_wrapIsEnabled()) { + return wordwrap( + $this->getContent(), + (integer)$this->getAttribute('cols'), + "\n"); + } + return $this->getContent(); + } + + /** + * Applies word wrapping if needed. + * @param string $value New value. + * @return boolean True if allowed. + * @access public + */ + function setValue($value) { + if ($this->_wrapIsEnabled()) { + $value = wordwrap( + $value, + (integer)$this->getAttribute('cols'), + "\n"); + } + return parent::setValue($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; + } + } + + /** + * 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". + * @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. The default + * value is "on". + * @return string Parsed value. + * @access public + */ + function getDefault() { + if ($this->getAttribute('checked')) { + return $this->getAttribute('value'); + } + return false; + } + } + + /** + * Drop down widget. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleSelectionTag extends SimpleWidget { + protected $_options; + protected $_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')) { + 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 (trim($this->_options[$i]->getContent()) == trim($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 { + protected $_options; + protected $_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')) { + $default[] = $this->_options[$i]->getDefault(); + } + } + return $default; + } + + /** + * Can only set allowed values. + * @param array $values New choices. + * @return boolean True if allowed. + * @access public + */ + function setValue($values) { + foreach ($values as $value) { + $is_option = false; + for ($i = 0, $count = count($this->_options); $i < $count; $i++) { + if (trim($this->_options[$i]->getContent()) == trim($value)) { + $is_option = true; + break; + } + } + if (! $is_option) { + return false; + } + } + $this->_values = $values; + 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; + } + + /** + * 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'); + } + } + + /** + * 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 in 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')) { + return $this->getAttribute('value'); + } + return false; + } + } + + /** + * A group of tags with the same name within a form. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleCheckboxGroup { + protected $_widgets; + + /** + * Starts empty. + * @access public + */ + function SimpleCheckboxGroup() { + $this->_widgets = array(); + } + + /** + * Accessor for an attribute. + * @param string $label Attribute name. + * @return boolean Always false. + * @access public + */ + function getAttribute($label) { + return false; + } + + /** + * Scans the checkboxes for one with the appropriate + * ID field. + * @param string $id ID value to try. + * @return boolean True if matched. + * @access public + */ + function isId($id) { + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($this->_widgets[$i]->isId($id)) { + return true; + } + } + return false; + } + + /** + * Adds a tag to the group. + * @param SimpleWidget $widget + * @access public + */ + function addWidget($widget) { + $this->_widgets[] = $widget; + } + + /** + * Fetches the name for the widget from the first + * member. + * @return string Name of widget. + * @access public + */ + function getName() { + if (count($this->_widgets) > 0) { + return $this->_widgets[0]->getName(); + } + } + + /** + * Accessor for current selected widget or false + * if none. + * @return string/array Widget values or false if none. + * @access public + */ + function getValue() { + $values = array(); + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($this->_widgets[$i]->getValue()) { + $values[] = $this->_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(); + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($this->_widgets[$i]->getDefault()) { + $values[] = $this->_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; + } + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + $possible = $this->_widgets[$i]->getAttribute('value'); + if (in_array($this->_widgets[$i]->getAttribute('value'), $values)) { + $this->_widgets[$i]->setValue($possible); + } else { + $this->_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(); + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + $possible = $this->_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 { + protected $_widgets; + + /** + * Starts empty. + * @access public + */ + function SimpleRadioGroup() { + $this->_widgets = array(); + } + + /** + * Accessor for an attribute. + * @param string $label Attribute name. + * @return boolean Always false. + * @access public + */ + function getAttribute($label) { + return false; + } + + /** + * Scans the checkboxes for one with the appropriate + * ID field. + * @param string $id ID value to try. + * @return boolean True if matched. + * @access public + */ + function isId($id) { + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($this->_widgets[$i]->isId($id)) { + return true; + } + } + return false; + } + + /** + * Adds a tag to the group. + * @param SimpleWidget $widget + * @access public + */ + function addWidget($widget) { + $this->_widgets[] = $widget; + } + + /** + * Fetches the name for the widget from the first + * member. + * @return string Name of widget. + * @access public + */ + function getName() { + if (count($this->_widgets) > 0) { + return $this->_widgets[0]->getName(); + } + } + + /** + * 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; + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if (! $this->_widgets[$i]->setValue($value)) { + $this->_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) { + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($this->_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() { + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($this->_widgets[$i]->getValue()) { + return $this->_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() { + for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { + if ($this->_widgets[$i]->getDefault()) { + return $this->_widgets[$i]->getDefault(); + } + } + return false; + } + } + + /** + * 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/UnitTests/simpletest/test/acceptance_test.php b/tests/UnitTests/simpletest/test/acceptance_test.php new file mode 100644 index 00000000..7cb73afb --- /dev/null +++ b/tests/UnitTests/simpletest/test/acceptance_test.php @@ -0,0 +1,1106 @@ +addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion()); + + $this->assertTrue($browser->get('http://www.lastcraft.com/test/network_confirm.php')); + $this->assertWantedPattern('/target for the SimpleTest/', $browser->getContent()); + $this->assertWantedPattern('/Request method.*?
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 ' . SimpleTestOptions::getVersion()); + $this->assertTrue($browser->post('http://www.lastcraft.com/test/network_confirm.php')); + $this->assertWantedPattern('/target for the SimpleTest/', $browser->getContent()); + $this->assertWantedPattern('/Request method.*?
POST<\/dd>/', $browser->getContent()); + } + + function testAbsoluteLinkFollowing() { + $browser = &new SimpleBrowser(); + $browser->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion()); + $browser->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($browser->clickLink('Absolute')); + $this->assertWantedPattern('/target for the SimpleTest/', $browser->getContent()); + } + + function testRelativeLinkFollowing() { + $browser = &new SimpleBrowser(); + $browser->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion()); + $browser->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($browser->clickLink('Relative')); + $this->assertWantedPattern('/target for the SimpleTest/', $browser->getContent()); + } + + function testIdLinkFollowing() { + $browser = &new SimpleBrowser(); + $browser->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion()); + $browser->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($browser->clickLinkById(1)); + $this->assertWantedPattern('/target for the SimpleTest/', $browser->getContent()); + } + + function testCookieReading() { + $browser = &new SimpleBrowser(); + $browser->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::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 ' . SimpleTestOptions::getVersion()); + $browser->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($browser->clickSubmit('Go!')); + $this->assertWantedPattern('/Request method.*?
POST<\/dd>/', $browser->getContent()); + $this->assertWantedPattern('/go=\[Go!\]/', $browser->getContent()); + } + } + + class TestOfLiveFetching extends WebTestCase { + + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion()); + } + + function testGet() { + $this->assertTrue($this->get('http://www.lastcraft.com/test/network_confirm.php')); + $this->assertTrue($this->getUrl() == 'http://www.lastcraft.com/test/network_confirm.php'); + $this->assertWantedPattern('/target for the SimpleTest/'); + $this->assertWantedPattern('/Request method.*?
GET<\/dd>/'); + $this->assertTitle('Simple test target file'); + $this->assertResponse(200); + $this->assertMime('text/html'); + } + + function testSlowGet() { + $this->assertTrue($this->get('http://www.lastcraft.com/test/slow_page.php')); + } + + function testTimedOutGet() { + $this->setConnectionTimeout(1); + $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->assertWantedText('target for the SimpleTest'); + $this->assertWantedPattern('/Request method.*?
POST<\/dd>/'); + } + + function testGetWithData() { + $this->get('http://www.lastcraft.com/test/network_confirm.php', array("a" => "aaa")); + $this->assertWantedPattern('/Request method.*?
GET<\/dd>/'); + $this->assertWantedText('a=[aaa]'); + } + + function testPostWithData() { + $this->post('http://www.lastcraft.com/test/network_confirm.php', array("a" => "aaa")); + $this->assertWantedPattern('/Request method.*?
POST<\/dd>/'); + $this->assertWantedText('a=[aaa]'); + } + + function testRelativeGet() { + $this->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($this->get('network_confirm.php')); + $this->assertWantedText('target for the SimpleTest'); + } + + function testRelativePost() { + $this->post('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($this->post('network_confirm.php')); + $this->assertWantedText('target for the SimpleTest'); + } + + function testAbsoluteLinkFollowing() { + $this->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertLink('Absolute'); + $this->assertTrue($this->clickLink('Absolute')); + $this->assertWantedText('target for the SimpleTest'); + } + + function testRelativeLinkFollowing() { + $this->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->assertTrue($this->clickLink('Relative')); + $this->assertWantedText('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->assertWantedText('target for the SimpleTest'); + } + + function testAbsoluteUrlBehavesAbsolutely() { + $this->get('http://www.lastcraft.com/test/link_confirm.php'); + $this->get('http://www.lastcraft.com'); + $this->assertWantedText('No guarantee of quality is given or even intended'); + } + } + + class TestOfLivePageLinkingWithMinimalLinks extends WebTestCase { + + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion()); + } + + function testClickToExplicitelyNamedSelfReturns() { + $this->get('http://www.lastcraft.com/test/front_controller_style/a_page.php'); + $this->assertTrue($this->getUrl() == 'http://www.lastcraft.com/test/front_controller_style/a_page.php'); + $this->assertTitle('Simple test page with links'); + $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->assertWantedText('[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->assertWantedText('[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->assertWantedText('Index of /test'); + } + } + + class TestOfLiveFrontControllerEmulation extends WebTestCase { + + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion()); + } + + function testJumpToNamedPage() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->assertWantedText('Simple test front controller'); + $this->clickLink('Index'); + $this->assertResponse(200); + $this->assertWantedText('[action=index]'); + } + + function testJumpToUnnamedPage() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickLink('No page'); + $this->assertResponse(200); + $this->assertWantedText('Simple test front controller'); + $this->assertWantedText('[action=no_page]'); + } + + function testJumpToUnnamedPageWithBareParameter() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickLink('Bare action'); + $this->assertResponse(200); + $this->assertWantedText('Simple test front controller'); + $this->assertWantedText('[action=]'); + } + + function testJumpToUnnamedPageWithEmptyQuery() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickLink('Empty query'); + $this->assertResponse(200); + $this->assertWantedPattern('/Simple test front controller/'); + $this->assertWantedPattern('/raw get data.*?\[\].*?get data/si'); + } + + function testJumpToUnnamedPageWithEmptyLink() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickLink('Empty link'); + $this->assertResponse(200); + $this->assertWantedPattern('/Simple test front controller/'); + $this->assertWantedPattern('/raw get data.*?\[\].*?get data/si'); + } + + function testJumpBackADirectoryLevel() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickLink('Down one'); + $this->assertWantedText('Index of /test'); + } + + function testSubmitToNamedPage() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->assertWantedText('Simple test front controller'); + $this->clickSubmit('Index'); + $this->assertResponse(200); + $this->assertWantedText('[action=Index]'); + } + + function testSubmitToSameDirectory() { + $this->get('http://www.lastcraft.com/test/front_controller_style/index.php'); + $this->clickSubmit('Same directory'); + $this->assertResponse(200); + $this->assertWantedText('[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->assertWantedText('[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->assertWantedText('[action=No+action]'); + } + + function testSubmitBackADirectoryLevel() { + $this->get('http://www.lastcraft.com/test/front_controller_style/'); + $this->clickSubmit('Down one'); + $this->assertWantedText('Index of /test'); + } + } + + class TestOfLiveHeaders extends WebTestCase { + + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::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->assertNoUnwantedHeader('WWW-Authenticate'); + } + } + + class TestOfLiveRedirects extends WebTestCase { + + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::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->assertNoUnwantedText('a=[aaa]'); + } + + function testRedirectKeepsExtraRequestDataOfItsOwn() { + $this->get('http://www.lastcraft.com/test/redirect.php'); + $this->assertWantedText('r=[rrr]'); + } + + function testRedirectLosesPostData() { + $this->post('http://www.lastcraft.com/test/redirect.php', array('a' => 'aaa')); + $this->assertTitle('Simple test target file'); + $this->assertNoUnwantedText('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 ' . SimpleTestOptions::getVersion()); + } + + function testCookieSetting() { + $this->setCookie('a', 'Test cookie a', 'www.lastcraft.com'); + $this->setCookie('b', 'Test cookie b', 'www.lastcraft.com', 'test'); + $this->get('http://www.lastcraft.com/test/network_confirm.php'); + $this->assertWantedPattern('/Test cookie a/'); + $this->assertWantedPattern('/Test cookie b/'); + $this->assertCookie('a'); + $this->assertCookie('b', 'Test cookie b'); + $this->assertTrue($this->getCookie('a') == 'Test cookie a'); + $this->assertTrue($this->getCookie('b') == 'Test cookie b'); + } + + 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 testTemporaryCookieExpiry() { + $this->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->restart(); + $this->assertNoCookie('session_cookie'); + $this->assertCookie('day_cookie', 'C'); + } + + function testTimedCookieExpiry() { + $this->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->ageCookies(3600); + $this->restart(time() + 60); // Includes a 60 sec. clock drift margin. + $this->assertNoCookie('session_cookie'); + $this->assertNoCookie('hour_cookie'); + $this->assertCookie('day_cookie', 'C'); + } + + function testOfClockOverDrift() { + $this->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->restart(time() + 160); // Allows sixty second drift. + $this->assertNoCookie( + 'short_cookie', + '%s->Please check your computer clock setting if you are not using NTP'); + } + + function testOfClockUnderDrift() { + $this->get('http://www.lastcraft.com/test/set_cookies.php'); + $this->restart(time() + 40); // Allows sixty second drift. + $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->assertWantedPattern('/path_cookie/'); + $this->assertCookie("path_cookie", "D"); + } + } + + class TestOfLiveForms extends WebTestCase { + + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion()); + } + + function testSimpleSubmit() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertWantedPattern('/Request method.*?
POST<\/dd>/'); + $this->assertWantedText('go=[Go!]'); + } + + function testDefaultFormValues() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertField('a', ''); + $this->assertField('b', 'Default text'); + $this->assertField('c', ''); + $this->assertField('d', 'd1'); + $this->assertField('e', false); + $this->assertField('f', 'on'); + $this->assertField('g', 'g3'); + $this->assertField('h', 2); + $this->assertField('go', 'Go!'); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertWantedText('go=[Go!]'); + $this->assertWantedText('a=[]'); + $this->assertWantedText('b=[Default text]'); + $this->assertWantedText('c=[]'); + $this->assertWantedText('d=[d1]'); + $this->assertNoUnwantedText('e=['); + $this->assertWantedText('f=[on]'); + $this->assertWantedText('g=[g3]'); + } + + function testFormSubmissionByLabel() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->setField('a', 'aaa'); + $this->setField('b', 'bbb'); + $this->setField('c', 'ccc'); + $this->setField('d', 'D2'); + $this->setField('e', 'on'); + $this->setField('f', false); + $this->setField('g', 'g2'); + $this->setField('h', 1); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertWantedText('a=[aaa]'); + $this->assertWantedText('b=[bbb]'); + $this->assertWantedText('c=[ccc]'); + $this->assertWantedText('d=[d2]'); + $this->assertWantedText('e=[on]'); + $this->assertNoUnwantedText('f=['); + $this->assertWantedText('g=[g2]'); + } + + function testAdditionalFormValues() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickSubmit('Go!', array('add' => 'A'))); + $this->assertWantedText('go=[Go!]'); + $this->assertWantedText('add=[A]'); + } + + function testFormSubmissionByName() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickSubmitByName('go')); + $this->assertWantedText('go=[Go!]'); + } + + function testFormSubmissionByNameAndadditionalParameters() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickSubmitByName('go', array('add' => 'A'))); + $this->assertWantedText('go=[Go!]'); + $this->assertWantedText('add=[A]'); + } + + function testFormSubmissionBySubmitButtonLabeledSubmit() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickSubmitByName('test')); + $this->assertWantedText('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->setFieldById(1, 'aaa'); + $this->setFieldById(2, 'bbb'); + $this->setFieldById(3, 'ccc'); + $this->setFieldById(4, 'D2'); + $this->setFieldById(5, 'on'); + $this->assertTrue($this->clickSubmitById(99)); + $this->assertWantedText('a=[aaa]'); + $this->assertWantedText('b=[bbb]'); + $this->assertWantedText('c=[ccc]'); + $this->assertWantedText('d=[d2]'); + $this->assertWantedText('e=[on]'); + $this->assertWantedText('go=[Go!]'); + } + + function testImageSubmissionByLabel() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickImage('Image go!', 10, 12)); + $this->assertWantedText('go_x=[10]'); + $this->assertWantedText('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->assertWantedText('add=[A]'); + } + + function testImageSubmissionByName() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickImageByName('go', 10, 12)); + $this->assertWantedText('go_x=[10]'); + $this->assertWantedText('go_y=[12]'); + } + + function testImageSubmissionById() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickImageById(97, 10, 12)); + $this->assertWantedText('go_x=[10]'); + $this->assertWantedText('go_y=[12]'); + } + + function testButtonSubmissionByLabel() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->clickSubmit('Button go!', 10, 12)); + $this->assertWantedPattern('/go=\[ButtonGo\]/s'); + } + + function testSelfSubmit() { + $this->get('http://www.lastcraft.com/test/self_form.php'); + $this->assertNoUnwantedPattern('/

submitted<\/p>/i'); + $this->assertNoUnwantedPattern('/

wrong form<\/p>/i'); + $this->assertTitle('Test of form self submission'); + $this->assertTrue($this->clickSubmit()); + $this->assertWantedPattern('/

submitted<\/p>/i'); + $this->assertNoUnwantedPattern('/

wrong form<\/p>/i'); + $this->assertTitle('Test of form self submission'); + } + + function testSettingOfBlankOption() { + $this->get('http://www.lastcraft.com/test/form.html'); + $this->assertTrue($this->setField('d', '')); + $this->clickSubmit('Go!'); + $this->assertWantedText('d=[]'); + } + } + + class TestOfLiveMultiValueWidgets extends WebTestCase { + + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion()); + } + + function testDefaultFormValueSubmission() { + $this->get('http://www.lastcraft.com/test/multiple_widget_form.html'); + $this->assertField('a', array('a2', 'a3')); + $this->assertField('b', array('b2', 'b3')); + $this->assertField('c[]', array('c2', 'c3')); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertWantedText('a=[a2, a3]'); + $this->assertWantedText('b=[b2, b3]'); + $this->assertWantedText('c=[c2, c3]'); + } + + function testSubmittingMultipleValues() { + $this->get('http://www.lastcraft.com/test/multiple_widget_form.html'); + $this->setField('a', array('a1', 'a4')); + $this->assertField('a', array('a1', 'a4')); + $this->assertField('a', array('a4', 'a1')); + $this->setField('b', array('b1', 'b4')); + $this->assertField('b', array('b1', 'b4')); + $this->setField('c[]', array('c1', 'c4')); + $this->assertField('c[]', array('c1', 'c4')); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertWantedText('a=[a1, a4]'); + $this->assertWantedText('b=[b1, b4]'); + $this->assertWantedText('c=[c1, c4]'); + } + + function testSavantStyleHiddenFieldDefaults() { + $this->get('http://www.lastcraft.com/test/savant_style_form.html'); + $this->assertField('a', array('a0')); + $this->assertField('b', array('b0')); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertWantedText('a=[a0]'); + $this->assertWantedText('b=[b0]'); + } + + function testSavantStyleHiddenDefaultsAreOverridden() { + $this->get('http://www.lastcraft.com/test/savant_style_form.html'); + $this->assertTrue($this->setField('a', array('a1'))); + $this->assertTrue($this->setField('b', 'b1')); + $this->assertTrue($this->clickSubmit('Go!')); + $this->assertWantedText('a=[a1]'); + $this->assertWantedText('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->assertWantedText('a=[a1]'); + $this->assertWantedText('b=[b1]'); + } + } + + class TestOfLiveHistoryNavigation extends WebTestCase { + + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion()); + } + + function testRetry() { + $this->get('http://www.lastcraft.com/test/cookie_based_counter.php'); + $this->assertWantedPattern('/count: 1/i'); + $this->retry(); + $this->assertWantedPattern('/count: 2/i'); + $this->retry(); + $this->assertWantedPattern('/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->assertWantedPattern('/Request method.*?

GET<\/dd>/'); + $this->assertWantedText('a=[aaa]'); + $this->retry(); + $this->assertWantedPattern('/Request method.*?
GET<\/dd>/'); + $this->assertWantedText('a=[aaa]'); + } + + function testGetRetryResubmitsExtraData() { + $this->assertTrue($this->get( + 'http://www.lastcraft.com/test/network_confirm.php', + array('a' => 'aaa'))); + $this->assertWantedPattern('/Request method.*?
GET<\/dd>/'); + $this->assertWantedText('a=[aaa]'); + $this->retry(); + $this->assertWantedPattern('/Request method.*?
GET<\/dd>/'); + $this->assertWantedText('a=[aaa]'); + } + + function testPostRetryResubmitsData() { + $this->assertTrue($this->post( + 'http://www.lastcraft.com/test/network_confirm.php', + array('a' => 'aaa'))); + $this->assertWantedPattern('/Request method.*?
POST<\/dd>/'); + $this->assertWantedText('a=[aaa]'); + $this->retry(); + $this->assertWantedPattern('/Request method.*?
POST<\/dd>/'); + $this->assertWantedText('a=[aaa]'); + } + + function testGetRetryResubmitsRepeatedData() { + $this->assertTrue($this->get( + 'http://www.lastcraft.com/test/network_confirm.php?a=1&a=2')); + $this->assertWantedPattern('/Request method.*?
GET<\/dd>/'); + $this->assertWantedText('a=[1, 2]'); + $this->retry(); + $this->assertWantedPattern('/Request method.*?
GET<\/dd>/'); + $this->assertWantedText('a=[1, 2]'); + } + } + + class TestOfLiveAuthentication extends WebTestCase { + + function setUp() { + $this->addHeader('User-Agent: SimpleTest ' . SimpleTestOptions::getVersion()); + } + + function testChallengeFromProtectedPage() { + $this->get('http://www.lastcraft.com/test/protected/'); + $this->assertResponse(401); + $this->assertAuthentication('Basic'); + $this->assertRealm('SimpleTest basic authentication'); + $this->authenticate('test', 'secret'); + $this->assertResponse(200); + $this->retry(); + $this->assertResponse(200); + } + + function testEncodedAuthenticationFetchesPage() { + $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 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 ' . SimpleTestOptions::getVersion()); + } + + function testNoFramesContentWhenFramesDisabled() { + $this->ignoreFrames(); + $this->get('http://www.lastcraft.com/test/one_page_frameset.html'); + $this->assertTitle('Frameset for testing of SimpleTest'); + $this->assertWantedText('This content is for no frames only'); + } + + function testPatternMatchCanReadTheOnlyFrame() { + $this->get('http://www.lastcraft.com/test/one_page_frameset.html'); + $this->assertWantedText('A target for the SimpleTest test suite'); + $this->assertNoUnwantedText('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->assertWantedText('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->assertWantedText('Count: 1'); + + $this->assertTrue($this->setFrameFocus('Redirected')); + $this->assertResponse(200); + $this->assertWantedText('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->assertWantedText('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->assertWantedTExt('Count: 1'); + + $this->assertTrue($this->setFrameFocusByIndex(5)); + $this->assertResponse(200); + $this->assertWantedText('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->assertWantedText('Count: 1'); + $this->retry(); + $this->assertWantedText('Count: 2'); + $this->retry(); + $this->assertWantedText('Count: 3'); + } + + function testReloadingSingleFrameWithCookieCounter() { + $this->get('http://www.lastcraft.com/test/counting_frameset.html'); + $this->setFrameFocus('a'); + $this->assertWantedText('Count: 1'); + $this->setFrameFocus('b'); + $this->assertWantedText('Count: 2'); + + $this->setFrameFocus('a'); + $this->retry(); + $this->assertWantedText('Count: 3'); + $this->retry(); + $this->assertWantedText('Count: 4'); + $this->setFrameFocus('b'); + $this->assertWantedText('Count: 2'); + } + + function testReloadingFrameWhenUnfocusedReloadsWholeFrameset() { + $this->get('http://www.lastcraft.com/test/counting_frameset.html'); + $this->setFrameFocus('a'); + $this->assertWantedText('Count: 1'); + $this->setFrameFocus('b'); + $this->assertWantedText('Count: 2'); + + $this->clearFrameFocus('a'); + $this->retry(); + + $this->assertTitle('Frameset for testing of SimpleTest'); + $this->setFrameFocus('a'); + $this->assertWantedText('Count: 3'); + $this->setFrameFocus('b'); + $this->assertWantedText('Count: 4'); + } + + function testClickingNormalLinkReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('2'); + $this->assertLink('3'); + $this->assertWantedText('Simple test front controller'); + } + + function testJumpToNamedPageReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->assertWantedPattern('/Simple test front controller/'); + $this->clickLink('Index'); + $this->assertResponse(200); + $this->assertWantedText('[action=index]'); + $this->assertWantedText('Count: 1'); + } + + function testJumpToUnnamedPageReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('No page'); + $this->assertResponse(200); + $this->assertWantedText('Simple test front controller'); + $this->assertWantedText('[action=no_page]'); + $this->assertWantedText('Count: 1'); + } + + function testJumpToUnnamedPageWithBareParameterReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('Bare action'); + $this->assertResponse(200); + $this->assertWantedText('Simple test front controller'); + $this->assertWantedText('[action=]'); + $this->assertWantedText('Count: 1'); + } + + function testJumpToUnnamedPageWithEmptyQueryReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('Empty query'); + $this->assertResponse(200); + $this->assertWantedPattern('/Simple test front controller/'); + $this->assertWantedPattern('/raw get data.*?\[\].*?get data/si'); + $this->assertWantedPattern('/Count: 1/'); + } + + function testJumpToUnnamedPageWithEmptyLinkReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('Empty link'); + $this->assertResponse(200); + $this->assertWantedPattern('/Simple test front controller/'); + $this->assertWantedPattern('/raw get data.*?\[\].*?get data/si'); + $this->assertWantedPattern('/Count: 1/'); + } + + function testJumpBackADirectoryLevelReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickLink('Down one'); + $this->assertWantedPattern('/index of \/test/i'); + $this->assertWantedPattern('/Count: 1/'); + } + + function testSubmitToNamedPageReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->assertWantedPattern('/Simple test front controller/'); + $this->clickSubmit('Index'); + $this->assertResponse(200); + $this->assertWantedText('[action=Index]'); + $this->assertWantedText('Count: 1'); + } + + function testSubmitToSameDirectoryReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickSubmit('Same directory'); + $this->assertResponse(200); + $this->assertWantedText('[action=Same+directory]'); + $this->assertWantedText('Count: 1'); + } + + function testSubmitToEmptyActionReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickSubmit('Empty action'); + $this->assertResponse(200); + $this->assertWantedText('[action=Empty+action]'); + $this->assertWantedText('Count: 1'); + } + + function testSubmitToNoActionReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickSubmit('No action'); + $this->assertResponse(200); + $this->assertWantedText('[action=No+action]'); + $this->assertWantedText('Count: 1'); + } + + function testSubmitBackADirectoryLevelReplacesJustThatFrame() { + $this->get('http://www.lastcraft.com/test/messy_frameset.html'); + $this->clickSubmit('Down one'); + $this->assertWantedPattern('/index of \/test/i'); + $this->assertWantedPattern('/Count: 1/'); + } + + 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 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->assertWantedText('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->assertWantedText('A target for the SimpleTest test suite'); + $this->clearFrameFocus(); + $this->assertWantedText('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->assertWantedText('A target for the SimpleTest test suite'); + $this->clearFrameFocus(); + $this->assertWantedText('Count: 1'); + } + } + + class TestOfNestedFrames extends WebTestCase { + + function testCanNavigateToSpecificContent() { + $this->get('http://www.lastcraft.com/test/nested_frameset.html'); + $this->assertTitle('Nested frameset for testing of SimpleTest'); + + $this->assertWantedPattern('/This is frame A/'); + $this->assertWantedPattern('/This is frame B/'); + $this->assertWantedPattern('/Simple test front controller/'); + $this->assertLink('2'); + $this->assertLink('Set one to 2'); + $this->assertWantedPattern('/Count: 1/'); + $this->assertWantedPattern('/r=rrr/'); + + $this->setFrameFocus('pair'); + $this->assertWantedPattern('/This is frame A/'); + $this->assertWantedPattern('/This is frame B/'); + $this->assertNoUnwantedPattern('/Simple test front controller/'); + $this->assertNoLink('2'); + + $this->setFrameFocus('aaa'); + $this->assertWantedPattern('/This is frame A/'); + $this->assertNoUnwantedPattern('/This is frame B/'); + + $this->clearFrameFocus(); + $this->assertResponse(200); + $this->setFrameFocus('messy'); + $this->assertResponse(200); + $this->setFrameFocus('Front controller'); + $this->assertResponse(200); + $this->assertWantedPattern('/Simple test front controller/'); + $this->assertNoLink('2'); + } + + function testReloadingFramesetPage() { + $this->get('http://www.lastcraft.com/test/nested_frameset.html'); + $this->assertWantedPattern('/Count: 1/'); + $this->retry(); + $this->assertWantedPattern('/Count: 2/'); + $this->retry(); + $this->assertWantedPattern('/Count: 3/'); + } + + function testRetryingNestedPageOnlyRetriesThatSet() { + $this->get('http://www.lastcraft.com/test/nested_frameset.html'); + $this->assertWantedPattern('/Count: 1/'); + $this->setFrameFocus('messy'); + $this->retry(); + $this->assertWantedPattern('/Count: 2/'); + $this->setFrameFocus('Counter'); + $this->retry(); + $this->assertWantedPattern('/Count: 3/'); + + $this->clearFrameFocus(); + $this->setFrameFocus('messy'); + $this->setFrameFocus('Front controller'); + $this->retry(); + + $this->clearFrameFocus(); + $this->assertWantedPattern('/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->assertWantedPattern('/A target for the SimpleTest test suite/'); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/adapter_test.php b/tests/UnitTests/simpletest/test/adapter_test.php new file mode 100644 index 00000000..d7f67caf --- /dev/null +++ b/tests/UnitTests/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->assertTrue($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", "PEAR regex"); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/all_tests.php b/tests/UnitTests/simpletest/test/all_tests.php new file mode 100644 index 00000000..d5e8a9de --- /dev/null +++ b/tests/UnitTests/simpletest/test/all_tests.php @@ -0,0 +1,31 @@ +GroupTest('All tests for SimpleTest ' . SimpleTestOptions::getVersion()); + $this->addTestCase(new UnitTests()); + $this->addTestFile('shell_test.php'); + $this->addTestFile('live_test.php'); + $this->addTestFile('acceptance_test.php'); + $this->addTestFile('real_sites_test.php'); + } + } + + $test = new AllTests(); + if (SimpleReporter::inCli()) { + exit ($test->run(new TextReporter()) ? 0 : 1); + } + $test->run(new HtmlReporter()); +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/authentication_test.php b/tests/UnitTests/simpletest/test/authentication_test.php new file mode 100644 index 00000000..3a12a2ff --- /dev/null +++ b/tests/UnitTests/simpletest/test/authentication_test.php @@ -0,0 +1,141 @@ +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 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($this); + $request->expectNever('addHeaderLine'); + $authenticator = &new SimpleAuthenticator(); + $authenticator->addHeaders($request, new SimpleUrl('http://here.com/')); + $request->tally(); + } + + 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($this); + $request->expectNever('addHeaderLine'); + $authenticator = &$this->createSingleRealm(); + $authenticator->addHeaders( + $request, + new SimpleUrl('http://www.here.com/hello.html')); + $request->tally(); + } + + function testWithinRealm() { + $request = &new MockSimpleHttpRequest($this); + $request->expectOnce('addHeaderLine'); + $authenticator = &$this->createSingleRealm(); + $authenticator->addHeaders( + $request, + new SimpleUrl('http://www.here.com/path/more/hello.html')); + $request->tally(); + } + + function testRestartingClearsRealm() { + $request = &new MockSimpleHttpRequest($this); + $request->expectNever('addHeaderLine'); + $authenticator = &$this->createSingleRealm(); + $authenticator->restartSession(); + $authenticator->addHeaders( + $request, + new SimpleUrl('http://www.here.com/hello.html')); + $request->tally(); + } + + function testDifferentHostIsOutsideRealm() { + $request = &new MockSimpleHttpRequest($this); + $request->expectNever('addHeaderLine'); + $authenticator = &$this->createSingleRealm(); + $authenticator->addHeaders( + $request, + new SimpleUrl('http://here.com/path/hello.html')); + $request->tally(); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/browser_test.php b/tests/UnitTests/simpletest/test/browser_test.php new file mode 100644 index 00000000..b7d23fc4 --- /dev/null +++ b/tests/UnitTests/simpletest/test/browser_test.php @@ -0,0 +1,870 @@ +assertIdentical($history->getMethod(), false); + $this->assertIdentical($history->getUrl(), false); + $this->assertIdentical($history->getParameters(), false); + } + + function testCannotMoveInEmptyHistory() { + $history = &new SimpleBrowserHistory(); + $this->assertFalse($history->back()); + $this->assertFalse($history->forward()); + } + + function testCurrentTargetAccessors() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + 'GET', + new SimpleUrl('http://www.here.com/'), + new SimpleFormEncoding()); + $this->assertIdentical($history->getMethod(), 'GET'); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.here.com/')); + $this->assertIdentical($history->getParameters(), new SimpleFormEncoding()); + } + + function testSecondEntryAccessors() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + 'GET', + new SimpleUrl('http://www.first.com/'), + new SimpleFormEncoding()); + $history->recordEntry( + 'POST', + new SimpleUrl('http://www.second.com/'), + new SimpleFormEncoding(array('a' => 1))); + $this->assertIdentical($history->getMethod(), 'POST'); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); + $this->assertIdentical( + $history->getParameters(), + new SimpleFormEncoding(array('a' => 1))); + } + + function testGoingBackwards() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + 'GET', + new SimpleUrl('http://www.first.com/'), + new SimpleFormEncoding()); + $history->recordEntry( + 'POST', + new SimpleUrl('http://www.second.com/'), + new SimpleFormEncoding(array('a' => 1))); + $this->assertTrue($history->back()); + $this->assertIdentical($history->getMethod(), 'GET'); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); + $this->assertIdentical($history->getParameters(), new SimpleFormEncoding()); + } + + function testGoingBackwardsOffBeginning() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + 'GET', + new SimpleUrl('http://www.first.com/'), + new SimpleFormEncoding()); + $this->assertFalse($history->back()); + $this->assertIdentical($history->getMethod(), 'GET'); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); + $this->assertIdentical($history->getParameters(), new SimpleFormEncoding()); + } + + function testGoingForwardsOffEnd() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + 'GET', + new SimpleUrl('http://www.first.com/'), + new SimpleFormEncoding()); + $this->assertFalse($history->forward()); + $this->assertIdentical($history->getMethod(), 'GET'); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); + $this->assertIdentical($history->getParameters(), new SimpleFormEncoding()); + } + + function testGoingBackwardsAndForwards() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + 'GET', + new SimpleUrl('http://www.first.com/'), + new SimpleFormEncoding()); + $history->recordEntry( + 'POST', + new SimpleUrl('http://www.second.com/'), + new SimpleFormEncoding(array('a' => 1))); + $this->assertTrue($history->back()); + $this->assertTrue($history->forward()); + $this->assertIdentical($history->getMethod(), 'POST'); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); + $this->assertIdentical( + $history->getParameters(), + new SimpleFormEncoding(array('a' => 1))); + } + + function testNewEntryReplacesNextOne() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + 'GET', + new SimpleUrl('http://www.first.com/'), + new SimpleFormEncoding()); + $history->recordEntry( + 'POST', + new SimpleUrl('http://www.second.com/'), + new SimpleFormEncoding(array('a' => 1))); + $history->back(); + $history->recordEntry( + 'GET', + new SimpleUrl('http://www.third.com/'), + new SimpleFormEncoding()); + $this->assertIdentical($history->getMethod(), 'GET'); + $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.third.com/')); + $this->assertIdentical($history->getParameters(), new SimpleFormEncoding()); + } + + function testNewEntryDropsFutureEntries() { + $history = &new SimpleBrowserHistory(); + $history->recordEntry( + 'GET', + new SimpleUrl('http://www.first.com/'), + new SimpleFormEncoding()); + $history->recordEntry( + 'GET', + new SimpleUrl('http://www.second.com/'), + new SimpleFormEncoding()); + $history->recordEntry( + 'GET', + new SimpleUrl('http://www.third.com/'), + new SimpleFormEncoding()); + $history->back(); + $history->back(); + $history->recordEntry( + 'GET', + new SimpleUrl('http://www.fourth.com/'), + new SimpleFormEncoding()); + $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($this); + $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($this); + $page->setReturnValue('getUrlsByLabel', array('http://www.nowhere.com')); + $page->expectOnce('getUrlsByLabel', array('a link label')); + + $browser = &$this->loadPage($page); + $this->assertTrue($browser->isLink('a link label')); + + $page->tally(); + } + + function testLinkAffirmationByIdWhenPresent() { + $page = &new MockSimplePage($this); + $page->setReturnValue('getUrlById', true, array(99)); + $page->setReturnValue('getUrlById', false, array('*')); + + $browser = &$this->loadPage($page); + $this->assertTrue($browser->isLinkById(99)); + $this->assertFalse($browser->isLinkById(98)); + + $page->tally(); + } + + function testFormHandling() { + $page = &new MockSimplePage($this); + $page->setReturnValue('getField', 'Value'); + $page->expectOnce('getField', array('key')); + $page->expectOnce('setField', array('key', 'Value')); + $page->setReturnValue('getFieldById', 'Id value'); + $page->expectOnce('getFieldById', array(99)); + $page->expectOnce('setFieldById', array(99, 'Id value')); + + $browser = &$this->loadPage($page); + $this->assertEqual($browser->getField('key'), 'Value'); + $this->assertEqual($browser->getFieldById(99), 'Id value'); + $browser->setField('key', 'Value'); + $browser->setFieldById(99, 'Id value'); + + $page->tally(); + } + } + + class TestOfBrowserNavigation extends UnitTestCase { + + function &createBrowser(&$agent, &$page) { + $browser = &new MockParseSimpleBrowser($this); + $browser->setReturnReference('_createUserAgent', $agent); + $browser->setReturnReference('_parse', $page); + $browser->SimpleBrowser(); + return $browser; + } + + function testClickLinkRequestsPage() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + $agent->expectArgumentsAt( + 0, + 'fetchResponse', + array('GET', new SimpleUrl('http://this.com/page.html'), false)); + $agent->expectArgumentsAt( + 1, + 'fetchResponse', + array('GET', new SimpleUrl('http://this.com/new.html'), false)); + $agent->expectCallCount('fetchResponse', 2); + + $page = &new MockSimplePage($this); + $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')); + + $agent->tally(); + $page->tally(); + } + + function testClickLinkWithUnknownFrameStillRequestsWholePage() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + $agent->expectArgumentsAt( + 0, + 'fetchResponse', + array('GET', new SimpleUrl('http://this.com/page.html'), false)); + $target = new SimpleUrl('http://this.com/new.html'); + $target->setTarget('missing'); + $agent->expectArgumentsAt( + 1, + 'fetchResponse', + array('GET', $target, false)); + $agent->expectCallCount('fetchResponse', 2); + + $parsed_url = new SimpleUrl('http://this.com/new.html'); + $parsed_url->setTarget('missing'); + + $page = &new MockSimplePage($this); + $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')); + + $agent->tally(); + $page->tally(); + } + + function testClickingMissingLinkFails() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + + $page = &new MockSimplePage($this); + $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($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + $agent->expectArgumentsAt( + 1, + 'fetchResponse', + array('GET', new SimpleUrl('1.html'), false)); + $agent->expectCallCount('fetchResponse', 2); + + $page = &new MockSimplePage($this); + $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)); + + $agent->tally(); + } + + function testClinkLinkById() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + $agent->expectArgumentsAt(1, 'fetchResponse', array( + 'GET', + new SimpleUrl('http://this.com/link.html'), + false)); + $agent->expectCallCount('fetchResponse', 2); + + $page = &new MockSimplePage($this); + $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)); + + $agent->tally(); + $page->tally(); + } + + function testClickingMissingLinkIdFails() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + + $page = &new MockSimplePage($this); + $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($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + $agent->expectArgumentsAt(1, 'fetchResponse', array( + 'POST', + new SimpleUrl('http://this.com/handler.html'), + new SimpleFormEncoding(array('a' => 'A')))); + $agent->expectCallCount('fetchResponse', 2); + + $form = &new MockSimpleForm($this); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submitButtonByLabel', new SimpleFormEncoding(array('a' => 'A'))); + $form->expectOnce('submitButtonByLabel', array('Go', false)); + + $page = &new MockSimplePage($this); + $page->setReturnReference('getFormBySubmitLabel', $form); + $page->expectOnce('getFormBySubmitLabel', array('Go')); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickSubmit('Go')); + + $agent->tally(); + $page->tally(); + $form->tally(); + } + + function testDefaultSubmitFormByLabel() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + $agent->expectArgumentsAt(1, 'fetchResponse', array( + 'GET', + new SimpleUrl('http://this.com/page.html'), + new SimpleFormEncoding(array('a' => 'A')))); + $agent->expectCallCount('fetchResponse', 2); + + $form = &new MockSimpleForm($this); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/page.html')); + $form->setReturnValue('getMethod', 'get'); + $form->setReturnValue('submitButtonByLabel', new SimpleFormEncoding(array('a' => 'A'))); + + $page = &new MockSimplePage($this); + $page->setReturnReference('getFormBySubmitLabel', $form); + $page->expectOnce('getFormBySubmitLabel', array('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()); + + $agent->tally(); + $page->tally(); + $form->tally(); + } + + function testSubmitFormByName() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + + $form = &new MockSimpleForm($this); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submitButtonByName', new SimpleFormEncoding(array('a' => 'A'))); + + $page = &new MockSimplePage($this); + $page->setReturnReference('getFormBySubmitName', $form); + $page->expectOnce('getFormBySubmitName', array('me')); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickSubmitByName('me')); + + $page->tally(); + } + + function testSubmitFormById() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + + $form = &new MockSimpleForm($this); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submitButtonById', new SimpleFormEncoding(array('a' => 'A'))); + $form->expectOnce('submitButtonById', array(99, false)); + + $page = &new MockSimplePage($this); + $page->setReturnReference('getFormBySubmitId', $form); + $page->expectOnce('getFormBySubmitId', array(99)); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickSubmitById(99)); + + $page->tally(); + $form->tally(); + } + + function testSubmitFormByImageLabel() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + + $form = &new MockSimpleForm($this); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submitImageByLabel', new SimpleFormEncoding(array('a' => 'A'))); + $form->expectOnce('submitImageByLabel', array('Go!', 10, 11, false)); + + $page = &new MockSimplePage($this); + $page->setReturnReference('getFormByImageLabel', $form); + $page->expectOnce('getFormByImageLabel', array('Go!')); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickImage('Go!', 10, 11)); + + $page->tally(); + $form->tally(); + } + + function testSubmitFormByImageName() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + + $form = &new MockSimpleForm($this); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submitImageByName', new SimpleFormEncoding(array('a' => 'A'))); + $form->expectOnce('submitImageByName', array('a', 10, 11, false)); + + $page = &new MockSimplePage($this); + $page->setReturnReference('getFormByImageName', $form); + $page->expectOnce('getFormByImageName', array('a')); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickImageByName('a', 10, 11)); + + $page->tally(); + $form->tally(); + } + + function testSubmitFormByImageId() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + + $form = &new MockSimpleForm($this); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submitImageById', new SimpleFormEncoding(array('a' => 'A'))); + $form->expectOnce('submitImageById', array(99, 10, 11, false)); + + $page = &new MockSimplePage($this); + $page->setReturnReference('getFormByImageId', $form); + $page->expectOnce('getFormByImageId', array(99)); + $page->setReturnValue('getRaw', 'stuff'); + + $browser = &$this->createBrowser($agent, $page); + $browser->get('http://this.com/page.html'); + $this->assertTrue($browser->clickImageById(99, 10, 11)); + + $page->tally(); + $form->tally(); + } + + function testSubmitFormByFormId() { + $agent = &new MockSimpleUserAgent($this); + $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); + $agent->expectArgumentsAt(1, 'fetchResponse', array( + 'POST', + new SimpleUrl('http://this.com/handler.html'), + new SimpleFormEncoding(array('a' => 'A')))); + $agent->expectCallCount('fetchResponse', 2); + + $form = &new MockSimpleForm($this); + $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); + $form->setReturnValue('getMethod', 'post'); + $form->setReturnValue('submit', new SimpleFormEncoding(array('a' => 'A'))); + + $page = &new MockSimplePage($this); + $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)); + + $agent->tally(); + $page->tally(); + } + } + + class TestOfBrowserFrames extends UnitTestCase { + + function &createBrowser(&$agent) { + $browser = &new MockUserAgentSimpleBrowser($this); + $browser->setReturnReference('_createUserAgent', $agent); + $browser->SimpleBrowser(); + return $browser; + } + + function &createUserAgent($pages) { + $agent = &new MockSimpleUserAgent($this); + foreach ($pages as $url => $raw) { + $url = new SimpleUrl($url); + $response = &new MockSimpleHttpResponse($this); + $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/UnitTests/simpletest/test/dumper_test.php b/tests/UnitTests/simpletest/test/dumper_test.php new file mode 100644 index 00000000..f0169247 --- /dev/null +++ b/tests/UnitTests/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->assertWantedPattern('/null/i', $dumper->describeValue(null)); + } + + function testDescribeBoolean() { + $dumper = new SimpleDumper(); + $this->assertWantedPattern('/boolean/i', $dumper->describeValue(true)); + $this->assertWantedPattern('/true/i', $dumper->describeValue(true)); + $this->assertWantedPattern('/false/i', $dumper->describeValue(false)); + } + + function testDescribeString() { + $dumper = new SimpleDumper(); + $this->assertWantedPattern('/string/i', $dumper->describeValue('Hello')); + $this->assertWantedPattern('/Hello/', $dumper->describeValue('Hello')); + } + + function testDescribeInteger() { + $dumper = new SimpleDumper(); + $this->assertWantedPattern('/integer/i', $dumper->describeValue(35)); + $this->assertWantedPattern('/35/', $dumper->describeValue(35)); + } + + function testDescribeFloat() { + $dumper = new SimpleDumper(); + $this->assertWantedPattern('/float/i', $dumper->describeValue(0.99)); + $this->assertWantedPattern('/0\.99/', $dumper->describeValue(0.99)); + } + + function testDescribeArray() { + $dumper = new SimpleDumper(); + $this->assertWantedPattern('/array/i', $dumper->describeValue(array(1, 4))); + $this->assertWantedPattern('/2/i', $dumper->describeValue(array(1, 4))); + } + + function testDescribeObject() { + $dumper = new SimpleDumper(); + $this->assertWantedPattern( + '/object/i', + $dumper->describeValue(new DumperDummy())); + $this->assertWantedPattern( + '/DumperDummy/i', + $dumper->describeValue(new DumperDummy())); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/encoding_test.php b/tests/UnitTests/simpletest/test/encoding_test.php new file mode 100644 index 00000000..409283d5 --- /dev/null +++ b/tests/UnitTests/simpletest/test/encoding_test.php @@ -0,0 +1,134 @@ +assertIdentical($encoding->getValue('a'), false); + $this->assertIdentical($encoding->getKeys(), array()); + $this->assertIdentical($encoding->asString(), ''); + } + + function testPrefilled() { + $encoding = &new SimpleFormEncoding(array('a' => 'aaa')); + $this->assertIdentical($encoding->getValue('a'), 'aaa'); + $this->assertIdentical($encoding->getKeys(), array('a')); + $this->assertIdentical($encoding->asString(), 'a=aaa'); + } + + function testPrefilledWithObject() { + $encoding = &new SimpleFormEncoding(new SimpleFormEncoding(array('a' => 'aaa'))); + $this->assertIdentical($encoding->getValue('a'), 'aaa'); + $this->assertIdentical($encoding->getKeys(), array('a')); + $this->assertIdentical($encoding->asString(), 'a=aaa'); + } + + function testMultiplePrefilled() { + $encoding = &new SimpleFormEncoding(array('a' => array('a1', 'a2'))); + $this->assertIdentical($encoding->getValue('a'), array('a1', 'a2')); + $this->assertIdentical($encoding->asString(), 'a=a1&a=a2'); + } + + function testSingleParameter() { + $encoding = &new SimpleFormEncoding(); + $encoding->add('a', 'Hello'); + $this->assertEqual($encoding->getValue('a'), 'Hello'); + $this->assertIdentical($encoding->asString(), 'a=Hello'); + } + + function testFalseParameter() { + $encoding = &new SimpleFormEncoding(); + $encoding->add('a', false); + $this->assertEqual($encoding->getValue('a'), false); + $this->assertIdentical($encoding->asString(), ''); + } + + function testUrlEncoding() { + $encoding = &new SimpleFormEncoding(); + $encoding->add('a', 'Hello there!'); + $this->assertIdentical($encoding->asString(), 'a=Hello+there%21'); + } + + function testMultipleParameter() { + $encoding = &new SimpleFormEncoding(); + $encoding->add('a', 'Hello'); + $encoding->add('b', 'Goodbye'); + $this->assertIdentical($encoding->asString(), 'a=Hello&b=Goodbye'); + } + + function testEmptyParameters() { + $encoding = &new SimpleFormEncoding(); + $encoding->add('a', ''); + $encoding->add('b', ''); + $this->assertIdentical($encoding->asString(), 'a=&b='); + } + + function testRepeatedParameter() { + $encoding = &new SimpleFormEncoding(); + $encoding->add('a', 'Hello'); + $encoding->add('a', 'Goodbye'); + $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); + $this->assertIdentical($encoding->asString(), 'a=Hello&a=Goodbye'); + } + + function testDefaultCoordinatesAreUnset() { + $encoding = &new SimpleFormEncoding(); + $this->assertIdentical($encoding->getX(), false); + $this->assertIdentical($encoding->getY(), false); + } + + function testSettingCoordinates() { + $encoding = &new SimpleFormEncoding(); + $encoding->setCoordinates('32', '45'); + $this->assertIdentical($encoding->getX(), 32); + $this->assertIdentical($encoding->getY(), 45); + $this->assertIdentical($encoding->asString(), '?32,45'); + } + + function testClearingCordinates() { + $encoding = &new SimpleFormEncoding(); + $encoding->setCoordinates('32', '45'); + $encoding->setCoordinates(); + $this->assertIdentical($encoding->getX(), false); + $this->assertIdentical($encoding->getY(), false); + } + + function testAddingLists() { + $encoding = &new SimpleFormEncoding(); + $encoding->add('a', array('Hello', 'Goodbye')); + $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); + $this->assertIdentical($encoding->asString(), 'a=Hello&a=Goodbye'); + } + + function testMergeInHash() { + $encoding = &new SimpleFormEncoding(array('a' => 'A1', 'b' => 'B')); + $encoding->merge(array('a' => 'A2')); + $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); + $this->assertIdentical($encoding->getValue('b'), 'B'); + } + + function testMergeInObject() { + $encoding = &new SimpleFormEncoding(array('a' => 'A1', 'b' => 'B')); + $encoding->merge(new SimpleFormEncoding(array('a' => 'A2'))); + $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); + $this->assertIdentical($encoding->getValue('b'), 'B'); + } + + function testMergeInObjectWithCordinates() { + $incoming = new SimpleFormEncoding(array('a' => 'A2')); + $incoming->setCoordinates(25, 24); + + $encoding = &new SimpleFormEncoding(array('a' => 'A1')); + $encoding->setCoordinates(1, 2); + $encoding->merge($incoming); + + $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); + $this->assertIdentical($encoding->getX(), 25); + $this->assertIdentical($encoding->getY(), 24); + $this->assertIdentical($encoding->asString(), 'a=A1&a=A2?25,24'); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/errors_test.php b/tests/UnitTests/simpletest/test/errors_test.php new file mode 100644 index 00000000..57aff612 --- /dev/null +++ b/tests/UnitTests/simpletest/test/errors_test.php @@ -0,0 +1,139 @@ +clear(); + } + + function tearDown() { + $queue = &SimpleErrorQueue::instance(); + $queue->clear(); + } + + function testSingleton() { + $this->assertReference( + SimpleErrorQueue::instance(), + SimpleErrorQueue::instance()); + $this->assertIsA(SimpleErrorQueue::instance(), 'SimpleErrorQueue'); + } + + function testEmpty() { + $queue = &SimpleErrorQueue::instance(); + $this->assertTrue($queue->isEmpty()); + $this->assertFalse($queue->extract()); + } + + function testOrder() { + $queue = &SimpleErrorQueue::instance(); + $queue->add(1024, 'Ouch', 'here.php', 100, array()); + $this->assertFalse($queue->isEmpty()); + $queue->add(512, 'Yuk', 'there.php', 101, array()); + $this->assertEqual( + $queue->extract(), + array(1024, 'Ouch', 'here.php', 100, array())); + $this->assertEqual( + $queue->extract(), + array(512, 'Yuk', 'there.php', 101, array())); + $this->assertFalse($queue->extract()); + } + } + + 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 testTrappedErrorPlacedInQueue() { + $queue = &SimpleErrorQueue::instance(); + $this->assertFalse($queue->extract()); + trigger_error('Ouch!'); + list($severity, $message, $file, $line, $globals) = $queue->extract(); + $this->assertEqual($message, 'Ouch!'); + $this->assertEqual($file, __FILE__); + $this->assertFalse($queue->extract()); + } + } + + 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); + $this->assertNoErrors(); + } + + function testNoWarningWhenNotReported() { + error_reporting(0); + trigger_error('Ouch!', E_USER_WARNING); + $this->assertNoErrors(); + } + + function testNoErrorWhenNotReported() { + error_reporting(0); + trigger_error('Ouch!', E_USER_ERROR); + $this->assertNoErrors(); + } + + function testNoticeSuppressedWhenReported() { + error_reporting(E_ALL); + @trigger_error('Ouch!', E_USER_NOTICE); + $this->assertNoErrors(); + } + + function testWarningSuppressedWhenReported() { + error_reporting(E_ALL); + @trigger_error('Ouch!', E_USER_WARNING); + $this->assertNoErrors(); + } + + function testErrorSuppressedWhenReported() { + error_reporting(E_ALL); + @trigger_error('Ouch!', E_USER_ERROR); + $this->assertNoErrors(); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/expectation_test.php b/tests/UnitTests/simpletest/test/expectation_test.php new file mode 100644 index 00000000..f16db28a --- /dev/null +++ b/tests/UnitTests/simpletest/test/expectation_test.php @@ -0,0 +1,282 @@ +assertTrue($is_true->test(true)); + $this->assertFalse($is_true->test(false)); + $this->assertWantedPattern( + '/equal expectation.*?boolean: true/i', + $is_true->testMessage(true)); + $this->assertWantedPattern( + '/fails.*?boolean.*?boolean/i', + $is_true->testMessage(false)); + } + + function testStringMatch() { + $hello = &new EqualExpectation("Hello"); + $this->assertTrue($hello->test("Hello")); + $this->assertFalse($hello->test("Goodbye")); + $this->assertWantedPattern('/Equal expectation.*?Hello/', $hello->testMessage("Hello")); + $this->assertWantedPattern('/fails/', $hello->testMessage("Goodbye")); + $this->assertWantedPattern('/fails.*?goodbye/i', $hello->testMessage("Goodbye")); + } + + function testStringPosition() { + $comparisons = array( + "ab" => 2, + "a" => 1, + "abcz" => 3, + "abz" => 2, + "az" => 1, + "z" => 0); + $str = &new EqualExpectation("abc"); + foreach ($comparisons as $compare => $position) { + $this->assertWantedPattern( + "/at character $position/", + $str->testMessage($compare)); + } + $str = &new EqualExpectation("abcd"); + foreach ($comparisons as $compare => $position) { + $this->assertWantedPattern( + "/at character $position/", + $str->testMessage($compare)); + } + } + + function testInteger() { + $fifteen = &new EqualExpectation(15); + $this->assertTrue($fifteen->test(15)); + $this->assertFalse($fifteen->test(14)); + $this->assertWantedPattern( + '/equal expectation.*?15/i', + $fifteen->testMessage(15)); + $this->assertWantedPattern( + '/fails.*?15.*?14/i', + $fifteen->testMessage(14)); + } + + function testFloat() { + $pi = &new EqualExpectation(3.14); + $this->assertTrue($pi->test(3.14)); + $this->assertFalse($pi->test(3.15)); + $this->assertWantedPattern( + '/float.*?3\.14/i', + $pi->testMessage(3.14)); + $this->assertWantedPattern( + '/fails.*?3\.14.*?3\.15/i', + $pi->testMessage(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"))); + $this->assertEqual( + $colours->testMessage(array("r", "g", "b")), + "Equal expectation [Array: 3 items]"); + $this->assertWantedPattern('/fails/', $colours->testMessage(array("r", "g", "z"))); + $this->assertWantedPattern( + '/\[2\] at character 0/', + $colours->testMessage(array("r", "g", "z"))); + $this->assertWantedPattern( + '/key.*? does not match/', + $colours->testMessage(array("r", "g"))); + $this->assertWantedPattern( + '/key.*? does not match/', + $colours->testMessage(array("r", "g", "b", "z"))); + } + + 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))); + $this->assertWantedPattern( + '/array.*?3 items/i', + $is_blue->testMessage(array("r" => 0, "g" => 0, "b" => 255))); + $this->assertWantedPattern( + '/fails.*?\[b\]/', + $is_blue->testMessage(array("r" => 0, "g" => 0, "b" => 254))); + } + + function testNestedHash() { + $tree = &new EqualExpectation(array( + "a" => 1, + "b" => array( + "c" => 2, + "d" => "Three"))); + $this->assertWantedPattern( + '/member.*?\[b\].*?\[d\].*?at character 5/', + $tree->testMessage(array( + "a" => 1, + "b" => array( + "c" => 2, + "d" => "Threeish")))); + } + + function testHashWithOutOfOrderKeysShouldStillMatch() { + $any_order = &new EqualExpectation(array('a' => 1, 'b' => 2)); + $this->assertTrue($any_order->test(array('b' => 2, 'a' => 1))); + } + } + + class TestOfInequality extends UnitTestCase { + + function testStringMismatch() { + $not_hello = &new NotEqualExpectation("Hello"); + $this->assertTrue($not_hello->test("Goodbye")); + $this->assertFalse($not_hello->test("Hello")); + $this->assertWantedPattern( + '/at character 0/', + $not_hello->testMessage("Goodbye")); + $this->assertWantedPattern( + '/matches/', + $not_hello->testMessage("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")); + $this->assertWantedPattern( + '/identical.*?string.*?37/i', + $string->testMessage("37")); + $this->assertWantedPattern( + '/fails.*?37/', + $string->testMessage(37)); + $this->assertWantedPattern( + '/at character 1/', + $string->testMessage("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")); + $this->assertWantedPattern( + '/at character 1/', + $string->testMessage("38")); + $this->assertWantedPattern( + '/passes.*?type/', + $string->testMessage(37)); + } + } + + class TestOfPatterns extends UnitTestCase { + + function testWanted() { + $pattern = &new WantedPatternExpectation('/hello/i'); + $this->assertTrue($pattern->test("Hello world")); + $this->assertFalse($pattern->test("Goodbye world")); + } + + function testUnwanted() { + $pattern = &new UnwantedPatternExpectation('/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/UnitTests/simpletest/test/form_test.php b/tests/UnitTests/simpletest/test/form_test.php new file mode 100644 index 00000000..b24eab2c --- /dev/null +++ b/tests/UnitTests/simpletest/test/form_test.php @@ -0,0 +1,326 @@ + '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('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('me'), 'Myself'); + $this->assertTrue($form->setField('me', 'Not me')); + $this->assertFalse($form->setField('not_present', 'Not me')); + $this->assertIdentical($form->getValue('me'), 'Not me'); + $this->assertNull($form->getValue('not_present')); + } + + 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->getValueById(50), 'Myself'); + $this->assertTrue($form->setFieldById(50, 'Not me')); + $this->assertIdentical($form->getValueById(50), 'Not me'); + } + + function testSubmitEmpty() { + $form = new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('htp://host')); + $this->assertIdentical($form->submit(), new SimpleFormEncoding()); + } + + 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->hasSubmitName('go')); + $this->assertEqual($form->getValue('go'), 'Go!'); + $this->assertEqual($form->getValueById(9), 'Go!'); + $this->assertEqual( + $form->submitButtonByName('go'), + new SimpleFormEncoding(array('go' => 'Go!'))); + $this->assertEqual( + $form->submitButtonByLabel('Go!'), + new SimpleFormEncoding(array('go' => 'Go!'))); + $this->assertEqual( + $form->submitButtonById(9), + new SimpleFormEncoding(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!', 'id' => '9'))); + $this->assertEqual( + $form->submitButtonByName('go', array('a' => 'A')), + new SimpleFormEncoding(array('go' => 'Go!', 'a' => 'A'))); + $this->assertEqual( + $form->submitButtonByLabel('Go!', array('a' => 'A')), + new SimpleFormEncoding(array('go' => 'Go!', 'a' => 'A'))); + $this->assertEqual( + $form->submitButtonById(9, array('a' => 'A')), + new SimpleFormEncoding(array('go' => 'Go!', 'a' => 'A'))); + } + + function testSubmitButtonWithLabelOfSubmit() { + $form = new SimpleForm( + new SimpleFormTag(array()), + new SimpleUrl('http://host')); + $form->addWidget(new SimpleSubmitTag( + array('type' => 'submit', 'name' => 'test', 'value' => 'Submit', 'id' => '9'))); + $this->assertTrue($form->hasSubmitName('test')); + $this->assertEqual($form->getValue('test'), 'Submit'); + $this->assertEqual($form->getValueById(9), 'Submit'); + $this->assertEqual( + $form->submitButtonByName('test'), + new SimpleFormEncoding(array('test' => 'Submit'))); + $this->assertEqual( + $form->submitButtonByLabel('Submit'), + new SimpleFormEncoding(array('test' => 'Submit'))); + $this->assertEqual( + $form->submitButtonById(9), + new SimpleFormEncoding(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 ', 'id' => '9'))); + $this->assertEqual($form->getValue('test'), ' Submit '); + $this->assertEqual($form->getValueById(9), ' Submit '); + $this->assertEqual( + $form->submitButtonByLabel('Submit'), + new SimpleFormEncoding(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->hasImageLabel('Go!')); + $this->assertEqual( + $form->submitImageByLabel('Go!', 100, 101), + new SimpleFormEncoding(array('go.x' => 100, 'go.y' => 101))); + $this->assertTrue($form->hasImageName('go')); + $this->assertEqual( + $form->submitImageByName('go', 100, 101), + new SimpleFormEncoding(array('go.x' => 100, 'go.y' => 101))); + $this->assertTrue($form->hasImageId(9)); + $this->assertEqual( + $form->submitImageById(9, 100, 101), + new SimpleFormEncoding(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!', + 'id' => '9'))); + $this->assertEqual( + $form->submitImageByLabel('Go!', 100, 101, array('a' => 'A')), + new SimpleFormEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A'))); + $this->assertTrue($form->hasImageName('go')); + $this->assertEqual( + $form->submitImageByName('go', 100, 101, array('a' => 'A')), + new SimpleFormEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A'))); + $this->assertTrue($form->hasImageId(9)); + $this->assertEqual( + $form->submitImageById(9, 100, 101, array('a' => 'A')), + new SimpleFormEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A'))); + } + + 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->hasSubmitName('go')); + $this->assertTrue($form->hasSubmitLabel('Go!')); + $this->assertEqual( + $form->submitButtonByName('go'), + new SimpleFormEncoding(array('go' => 'Go'))); + $this->assertEqual( + $form->submitButtonByLabel('Go!'), + new SimpleFormEncoding(array('go' => 'Go'))); + $this->assertEqual( + $form->submitButtonById(9), + new SimpleFormEncoding(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 SimpleFormEncoding(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('me'), false); + $this->assertTrue($form->setField('me', 'on')); + $this->assertEqual($form->getValue('me'), 'on'); + $this->assertFalse($form->setField('me', 'other')); + $this->assertEqual($form->getValue('me'), 'on'); + } + + 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('me'), 'a'); + $this->assertFalse($form->setField('me', 'on')); + $this->assertEqual($form->getValue('me'), 'a'); + $this->assertTrue($form->setField('me', false)); + $this->assertEqual($form->getValue('me'), false); + } + + 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('me'), false); + $this->assertTrue($form->setField('me', 'a')); + $this->assertIdentical($form->getValue('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('me'), 'a'); + $this->assertFalse($form->setField('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('me'), false); + $this->assertTrue($form->setField('me', 'a')); + $this->assertIdentical($form->getValue('me'), 'a'); + $this->assertTrue($form->setField('me', 'b')); + $this->assertIdentical($form->getValue('me'), 'b'); + $this->assertFalse($form->setField('me', 'c')); + $this->assertIdentical($form->getValue('me'), 'b'); + } + + 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('me'), 'b'); + $this->assertTrue($form->setField('me', 'a')); + $this->assertIdentical($form->getValue('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('a'), false); + $this->assertTrue($form->setField('a', 'me')); + $this->assertIdentical($form->getValue('a'), 'me'); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/frames_test.php b/tests/UnitTests/simpletest/test/frames_test.php new file mode 100644 index 00000000..5226d070 --- /dev/null +++ b/tests/UnitTests/simpletest/test/frames_test.php @@ -0,0 +1,569 @@ +setReturnValue('getTitle', 'This page'); + $frameset = &new SimpleFrameset($page); + $this->assertEqual($frameset->getTitle(), 'This page'); + } + + function TestHeadersReadFromFramesetByDefault() { + $page = &new MockSimplePage($this); + $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($this); + $page->setReturnValue('getRaw', 'This content'); + $frameset = &new SimpleFrameset($page); + $this->assertEqual($frameset->getRaw(), ''); + } + + function testRawContentIsFromOnlyFrame() { + $page = &new MockSimplePage($this); + $page->expectNever('getRaw'); + + $frame = &new MockSimplePage($this); + $frame->setReturnValue('getRaw', 'Stuff'); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame); + $this->assertEqual($frameset->getRaw(), 'Stuff'); + } + + function testRawContentIsFromAllFrames() { + $page = &new MockSimplePage($this); + $page->expectNever('getRaw'); + + $frame1 = &new MockSimplePage($this); + $frame1->setReturnValue('getRaw', 'Stuff1'); + + $frame2 = &new MockSimplePage($this); + $frame2->setReturnValue('getRaw', 'Stuff2'); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame1); + $frameset->addFrame($frame2); + $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); + } + + function testTextContentIsFromOnlyFrame() { + $page = &new MockSimplePage($this); + $page->expectNever('getText'); + + $frame = &new MockSimplePage($this); + $frame->setReturnValue('getText', 'Stuff'); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame); + $this->assertEqual($frameset->getText(), 'Stuff'); + } + + function testTextContentIsFromAllFrames() { + $page = &new MockSimplePage($this); + $page->expectNever('getText'); + + $frame1 = &new MockSimplePage($this); + $frame1->setReturnValue('getText', 'Stuff1'); + + $frame2 = &new MockSimplePage($this); + $frame2->setReturnValue('getText', 'Stuff2'); + + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame1); + $frameset->addFrame($frame2); + $this->assertEqual($frameset->getText(), 'Stuff1 Stuff2'); + } + + function testFieldIsFirstInFramelist() { + $frame1 = &new MockSimplePage($this); + $frame1->setReturnValue('getField', null); + $frame1->expectOnce('getField', array('a')); + + $frame2 = &new MockSimplePage($this); + $frame2->setReturnValue('getField', 'A'); + $frame2->expectOnce('getField', array('a')); + + $frame3 = &new MockSimplePage($this); + $frame3->expectNever('getField'); + + $page = &new MockSimplePage($this); + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame1); + $frameset->addFrame($frame2); + $frameset->addFrame($frame3); + + $this->assertIdentical($frameset->getField('a'), 'A'); + $frame1->tally(); + $frame2->tally(); + } + + function testFrameReplacementByIndex() { + $page = &new MockSimplePage($this); + $page->expectNever('getRaw'); + + $frame1 = &new MockSimplePage($this); + $frame1->setReturnValue('getRaw', 'Stuff1'); + + $frame2 = &new MockSimplePage($this); + $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($this); + $page->expectNever('getRaw'); + + $frame1 = &new MockSimplePage($this); + $frame1->setReturnValue('getRaw', 'Stuff1'); + + $frame2 = &new MockSimplePage($this); + $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($this); + $frameset = &new SimpleFrameset($page); + $frameset->addFrame($frame); + $this->assertFalse($frameset->getFrameFocus()); + } + + function testCanFocusOnSingleFrame() { + $page = &new MockSimplePage($this); + $page->expectNever('getRaw'); + + $frame = &new MockSimplePage($this); + $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($this); + + $frame1 = &new MockSimplePage($this); + $frame1->setReturnValue('getRaw', 'Stuff1'); + $frame1->setReturnValue('getFrameFocus', array()); + + $frame2 = &new MockSimplePage($this); + $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($this); + + $frame1 = &new MockSimplePage($this); + $frame1->setReturnValue('getRaw', 'Stuff1'); + $frame1->setReturnValue('getFrameFocus', array()); + + $frame2 = &new MockSimplePage($this); + $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($this); + $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($this)); + $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($this); + $page->expectNever('getAbsoluteUrls'); + + $frame1 = &new MockSimplePage($this); + $frame1->setReturnValue( + 'getAbsoluteUrls', + array('http://www.lastcraft.com/', 'http://myserver/')); + + $frame2 = &new MockSimplePage($this); + $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($this); + $frame1->setReturnValue( + 'getRelativeUrls', + array('/', '.', '/test/', 'goodbye.php')); + + $frame2 = &new MockSimplePage($this); + $frame2->setReturnValue( + 'getRelativeUrls', + array('/', '..', '/test/', 'hello.php')); + + $page = &new MockSimplePage($this); + $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($this); + $frame1->setReturnValue( + 'getUrlsByLabel', + array(new SimpleUrl('goodbye.php')), + array('a')); + + $frame2 = &new MockSimplePage($this); + $frame2->setReturnValue( + 'getUrlsByLabel', + array(new SimpleUrl('hello.php')), + array('a')); + + $frameset = &new SimpleFrameset(new MockSimplePage($this)); + $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($this); + $frame1->setReturnValue('getUrlById', new SimpleUrl('four.php'), array(4)); + $frame1->setReturnValue('getUrlById', false, array(5)); + + $frame2 = &new MockSimplePage($this); + $frame2->setReturnValue('getUrlById', false, array(4)); + $frame2->setReturnValue('getUrlById', new SimpleUrl('five.php'), array(5)); + + $frameset = &new SimpleFrameset(new MockSimplePage($this)); + $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($this); + $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($this); + $frame2->expectNever('getAbsoluteUrls'); + $frame2->expectNever('getRelativeUrls'); + $frame2->expectNever('getUrlsByLabel'); + $frame2->expectNever('getUrlById'); + + $frameset = &new SimpleFrameset(new MockSimplePage($this)); + $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($this); + + $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($this)); + $frameset->addFrame($frame, 'A'); + $frameset->setFrameFocus('A'); + + $this->assertIdentical($frameset->getUrlsByLabel('label'), array($by_label)); + $this->assertIdentical($frameset->getUrlById(99), $by_id); + } + + function testFindingFormsByAllFinders() { + $finders = array( + 'getFormBySubmitLabel', 'getFormBySubmitName', + 'getFormBySubmitId', 'getFormByImageLabel', + 'getFormByImageName', 'getFormByImageId', 'getFormById'); + $forms = array(); + + $frame = &new MockSimplePage($this); + for ($i = 0; $i < count($finders); $i++) { + $forms[$i] = &new MockSimpleForm($this); + $frame->setReturnReference($finders[$i], $forms[$i], array('a')); + } + + $frameset = &new SimpleFrameset(new MockSimplePage($this)); + $frameset->addFrame(new MockSimplePage($this), 'A'); + $frameset->addFrame($frame, 'B'); + for ($i = 0; $i < count($finders); $i++) { + $method = $finders[$i]; + $this->assertReference($frameset->$method('a'), $forms[$i]); + } + + $frameset->setFrameFocus('A'); + for ($i = 0; $i < count($finders); $i++) { + $method = $finders[$i]; + $this->assertNull($frameset->$method('a')); + } + + $frameset->setFrameFocus('B'); + for ($i = 0; $i < count($finders); $i++) { + $method = $finders[$i]; + $this->assertReference($frameset->$method('a'), $forms[$i]); + } + } + + function testSettingAllFrameFieldsWhenNoFrameFocus() { + $frame1 = &new MockSimplePage($this); + $frame1->expectOnce('setField', array('a', 'A')); + $frame1->expectOnce('setFieldById', array(22, 'A')); + + $frame2 = &new MockSimplePage($this); + $frame2->expectOnce('setField', array('a', 'A')); + $frame2->expectOnce('setFieldById', array(22, 'A')); + + $frameset = &new SimpleFrameset(new MockSimplePage($this)); + $frameset->addFrame($frame1, 'A'); + $frameset->addFrame($frame2, 'B'); + + $frameset->setField('a', 'A'); + $frameset->setFieldById(22, 'A'); + $frame1->tally(); + $frame2->tally(); + } + + function testOnlySettingFieldFromFocusedFrame() { + $frame1 = &new MockSimplePage($this); + $frame1->expectOnce('setField', array('a', 'A')); + $frame1->expectOnce('setFieldById', array(22, 'A')); + + $frame2 = &new MockSimplePage($this); + $frame2->expectNever('setField'); + $frame2->expectNever('setFieldById'); + + $frameset = &new SimpleFrameset(new MockSimplePage($this)); + $frameset->addFrame($frame1, 'A'); + $frameset->addFrame($frame2, 'B'); + $frameset->setFrameFocus('A'); + + $frameset->setField('a', 'A'); + $frameset->setFieldById(22, 'A'); + $frame1->tally(); + } + + function testOnlyGettingFieldFromFocusedFrame() { + $frame1 = &new MockSimplePage($this); + $frame1->setReturnValue('getField', 'f', array('a')); + $frame1->setReturnValue('getFieldById', 'i', array(7)); + + $frame2 = &new MockSimplePage($this); + $frame2->expectNever('getField'); + $frame2->expectNever('getFieldById'); + + $frameset = &new SimpleFrameset(new MockSimplePage($this)); + $frameset->addFrame($frame1, 'A'); + $frameset->addFrame($frame2, 'B'); + $frameset->setFrameFocus('A'); + + $this->assertIdentical($frameset->getField('a'), 'f'); + $this->assertIdentical($frameset->getFieldById(7), 'i'); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/http_test.php b/tests/UnitTests/simpletest/test/http_test.php new file mode 100644 index 00000000..ca201be0 --- /dev/null +++ b/tests/UnitTests/simpletest/test/http_test.php @@ -0,0 +1,567 @@ +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 TestOfDirectRoute extends UnitTestCase { + + function testDefaultGetRequest() { + $socket = &new MockSimpleSocket($this); + $socket->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($this); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleRoute(new SimpleUrl('http://a.valid.host/here.html')); + + $this->assertReference($route->createConnection('GET', 15), $socket); + $socket->tally(); + } + + function testDefaultPostRequest() { + $socket = &new MockSimpleSocket($this); + $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($this); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleRoute(new SimpleUrl('http://a.valid.host/here.html')); + + $route->createConnection('POST', 15); + $socket->tally(); + } + + function testGetWithPort() { + $socket = &new MockSimpleSocket($this); + $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($this); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleRoute(new SimpleUrl('http://a.valid.host:81/here.html')); + + $route->createConnection('GET', 15); + $socket->tally(); + } + + function testGetWithParameters() { + $socket = &new MockSimpleSocket($this); + $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($this); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleRoute(new SimpleUrl('http://a.valid.host/here.html?a=1&b=2')); + + $route->createConnection('GET', 15); + $socket->tally(); + } + } + + class TestOfProxyRoute extends UnitTestCase { + + function testDefaultGet() { + $socket = &new MockSimpleSocket($this); + $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($this); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleProxyRoute( + new SimpleUrl('http://a.valid.host/here.html'), + new SimpleUrl('http://my-proxy')); + + $route->createConnection('GET', 15); + $socket->tally(); + } + + function testDefaultPost() { + $socket = &new MockSimpleSocket($this); + $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($this); + $route->setReturnReference('_createSocket', $socket); + $route->SimpleProxyRoute( + new SimpleUrl('http://a.valid.host/here.html'), + new SimpleUrl('http://my-proxy')); + + $route->createConnection('POST', 15); + $socket->tally(); + } + + function testGetWithPort() { + $socket = &new MockSimpleSocket($this); + $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($this); + $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); + $socket->tally(); + } + + function testGetWithParameters() { + $socket = &new MockSimpleSocket($this); + $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($this); + $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); + $socket->tally(); + } + + function testGetWithAuthentication() { + $encoded = base64_encode('Me:Secret'); + + $socket = &new MockSimpleSocket($this); + $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($this); + $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); + $socket->tally(); + } + } + + class TestOfHttpRequest extends UnitTestCase { + + function testReadingBadConnection() { + $socket = &new MockSimpleSocket($this); + + $route = &new MockSimpleRoute($this); + $route->setReturnReference('createConnection', $socket); + + $request = &new SimpleHttpRequest($route, 'GET'); + + $reponse = &$request->fetch(15); + $this->assertTrue($reponse->isError()); + } + + function testReadingGoodConnection() { + $socket = &new MockSimpleSocket($this); + $socket->expectOnce('write', array("\r\n")); + + $route = &new MockSimpleRoute($this); + $route->setReturnReference('createConnection', $socket); + $route->expectArguments('createConnection', array('GET', 15)); + + $request = &new SimpleHttpRequest($route, 'GET'); + + $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); + $socket->tally(); + $route->tally(); + } + + function testWritingAdditionalHeaders() { + $socket = &new MockSimpleSocket($this); + $socket->expectArgumentsAt(0, 'write', array("My: stuff\r\n")); + $socket->expectArgumentsAt(1, 'write', array("\r\n")); + $socket->expectCallCount('write', 2); + + $route = &new MockSimpleRoute($this); + $route->setReturnReference('createConnection', $socket); + + $request = &new SimpleHttpRequest($route, 'GET'); + $request->addHeaderLine('My: stuff'); + $request->fetch(15); + + $socket->tally(); + } + + function testCookieWriting() { + $socket = &new MockSimpleSocket($this); + $socket->expectArgumentsAt(0, 'write', array("Cookie: a=A\r\n")); + $socket->expectArgumentsAt(1, 'write', array("\r\n")); + $socket->expectCallCount('write', 2); + + $route = &new MockSimpleRoute($this); + $route->setReturnReference('createConnection', $socket); + + $request = &new SimpleHttpRequest($route, 'GET'); + $request->setCookie(new SimpleCookie('a', 'A')); + + $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); + $socket->tally(); + } + + function testMultipleCookieWriting() { + $socket = &new MockSimpleSocket($this); + $socket->expectArgumentsAt(0, 'write', array("Cookie: a=A;b=B\r\n")); + + $route = &new MockSimpleRoute($this); + $route->setReturnReference('createConnection', $socket); + + $request = &new SimpleHttpRequest($route, 'GET'); + $request->setCookie(new SimpleCookie('a', 'A')); + $request->setCookie(new SimpleCookie('b', 'B')); + + $request->fetch(15); + $socket->tally(); + } + } + + class TestOfHttpPostRequest extends UnitTestCase { + + function testReadingBadConnection() { + $socket = &new MockSimpleSocket($this); + + $route = &new MockSimpleRoute($this); + $route->setReturnReference('createConnection', $socket); + + $request = &new SimpleHttpRequest($route, 'POST', ''); + + $reponse = &$request->fetch(15); + $this->assertTrue($reponse->isError()); + } + + function testReadingGoodConnection() { + $socket = &new MockSimpleSocket($this); + $socket->expectArgumentsAt(0, 'write', array("Content-Length: 0\r\n")); + $socket->expectArgumentsAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); + $socket->expectArgumentsAt(2, 'write', array("\r\n")); + $socket->expectArgumentsAt(3, 'write', array("")); + + $route = &new MockSimpleRoute($this); + $route->setReturnReference('createConnection', $socket); + $route->expectArguments('createConnection', array('POST', 15)); + + $request = &new SimpleHttpRequest($route, 'POST', new SimpleFormEncoding()); + + $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); + $socket->tally(); + $route->tally(); + } + + function testContentHeadersCalculated() { + $socket = &new MockSimpleSocket($this); + $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($this); + $route->setReturnReference('createConnection', $socket); + $route->expectArguments('createConnection', array('POST', 15)); + + $request = &new SimpleHttpRequest( + $route, + 'POST', + new SimpleFormEncoding(array('a' => 'A'))); + + $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); + $socket->tally(); + $route->tally(); + } + } + + 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 testParseOfCookies() { + $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"); + $cookies = $headers->getNewCookies(); + $this->assertEqual(count($cookies), 2); + $this->assertEqual($cookies[0]->getName(), "a"); + $this->assertEqual($cookies[0]->getValue(), "aaa"); + $this->assertEqual($cookies[0]->getPath(), "/here/"); + $this->assertEqual($cookies[0]->getExpiry(), "Wed, 25 Dec 2002 04:24:20 GMT"); + $this->assertEqual($cookies[1]->getName(), "b"); + $this->assertEqual($cookies[1]->getValue(), "bbb"); + $this->assertEqual($cookies[1]->getPath(), "/"); + $this->assertEqual($cookies[1]->getExpiry(), ""); + } + + function testRedirect() { + $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 testParseChallenge() { + $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($this); + $socket->setReturnValue('getSent', ''); + + $response = &new SimpleHttpResponse($socket, 'GET', new SimpleUrl('here')); + $this->assertTrue($response->isError()); + $this->assertWantedPattern('/Nothing fetched/', $response->getError()); + $this->assertIdentical($response->getContent(), false); + $this->assertIdentical($response->getSent(), ''); + } + + function testBadSocketDuringResponse() { + $socket = &new MockSimpleSocket($this); + $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, 'GET', new SimpleUrl('here')); + $this->assertTrue($response->isError()); + $this->assertEqual($response->getContent(), ''); + $this->assertEqual($response->getSent(), 'HTTP/1.1 ...'); + } + + function testIncompleteHeader() { + $socket = &new MockSimpleSocket($this); + $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, 'GET', new SimpleUrl('here')); + $this->assertTrue($response->isError()); + $this->assertEqual($response->getContent(), ""); + } + + function testParseOfResponseHeaders() { + $socket = &new MockSimpleSocket($this); + $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, 'GET', new SimpleUrl('here')); + $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 testParseOfCookies() { + $socket = &new MockSimpleSocket($this); + $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->setReturnValueAt(3, "read", "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n"); + $socket->setReturnValueAt(4, "read", "Set-Cookie: a=aaa; expires=Wed, 25-Dec-02 04:24:20 GMT; path=/here/\r\n"); + $socket->setReturnValueAt(5, "read", "Connection: close\r\n"); + $socket->setReturnValueAt(6, "read", "\r\n"); + $socket->setReturnValue("read", ""); + + $response = &new SimpleHttpResponse($socket, 'GET', new SimpleUrl('here')); + $this->assertFalse($response->isError()); + $headers = $response->getHeaders(); + $cookies = $headers->getNewCookies(); + $this->assertEqual($cookies[0]->getName(), "a"); + $this->assertEqual($cookies[0]->getValue(), "aaa"); + $this->assertEqual($cookies[0]->getPath(), "/here/"); + $this->assertEqual($cookies[0]->getExpiry(), "Wed, 25 Dec 2002 04:24:20 GMT"); + } + + function testRedirect() { + $socket = &new MockSimpleSocket($this); + $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, 'GET', new SimpleUrl('here')); + $headers = $response->getHeaders(); + $this->assertTrue($headers->isRedirect()); + $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/"); + } + + function testRedirectWithPort() { + $socket = &new MockSimpleSocket($this); + $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, 'GET', new SimpleUrl('here')); + $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/UnitTests/simpletest/test/live_test.php b/tests/UnitTests/simpletest/test/live_test.php new file mode 100644 index 00000000..193284e7 --- /dev/null +++ b/tests/UnitTests/simpletest/test/live_test.php @@ -0,0 +1,47 @@ +assertTrue($socket->isError()); + $this->assertWantedPattern( + '/Cannot open \\[bad_url:111\\] with \\[.*?\\] within \\[5\\] seconds/', + $socket->getError()); + $this->assertFalse($socket->isOpen()); + $this->assertFalse($socket->write('A message')); + } + + function testSocketClosure() { + $socket = &new SimpleSocket('www.lastcraft.com', 80, 15); + $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(8), "HTTP/1.1"); + $socket->close(); + $this->assertIdentical($socket->read(8), 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/UnitTests/simpletest/test/options_test.php b/tests/UnitTests/simpletest/test/options_test.php new file mode 100644 index 00000000..8535f739 --- /dev/null +++ b/tests/UnitTests/simpletest/test/options_test.php @@ -0,0 +1,95 @@ +assertEqual(SimpleTestOptions::getMockBaseClass(), 'Fred'); + SimpleTestOptions::setMockBaseClass($old_class); + } + + function testStubBase() { + $old_class = SimpleTestOptions::getStubBaseClass(); + SimpleTestOptions::setStubBaseClass('Fred'); + $this->assertEqual(SimpleTestOptions::getStubBaseClass(), 'Fred'); + SimpleTestOptions::setStubBaseClass($old_class); + } + + function testIgnoreList() { + $this->assertFalse(SimpleTestOptions::isIgnored('ImaginaryTestCase')); + SimpleTestOptions::ignore('ImaginaryTestCase'); + $this->assertTrue(SimpleTestOptions::isIgnored('ImaginaryTestCase')); + } + } + + class ComparisonClass { + } + + class ComparisonSubclass extends ComparisonClass { + } + + 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 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)); + } + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/page_test.php b/tests/UnitTests/simpletest/test/page_test.php new file mode 100644 index 00000000..d9e87d12 --- /dev/null +++ b/tests/UnitTests/simpletest/test/page_test.php @@ -0,0 +1,792 @@ + 'http://somewhere')); + $tag->addContent('Label'); + + $page = &new MockSimplePage($this); + $page->expectArguments('acceptTag', array($tag)); + $page->expectCallCount('acceptTag', 1); + + $builder = &new PartialSimplePageBuilder($this); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', new MockSimpleSaxParser($this)); + $builder->SimplePageBuilder(); + + $builder->parse(new MockSimpleHttpResponse($this)); + $this->assertTrue($builder->startElement( + 'a', + array('href' => 'http://somewhere'))); + $this->assertTrue($builder->addContent('Label')); + $this->assertTrue($builder->endElement('a')); + + $page->tally(); + } + + function testLinkWithId() { + $tag = &new SimpleAnchorTag(array("href" => "http://somewhere", "id" => "44")); + $tag->addContent("Label"); + + $page = &new MockSimplePage($this); + $page->expectArguments("acceptTag", array($tag)); + $page->expectCallCount("acceptTag", 1); + + $builder = &new PartialSimplePageBuilder($this); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', new MockSimpleSaxParser($this)); + $builder->SimplePageBuilder(); + + $builder->parse(new MockSimpleHttpResponse($this)); + $this->assertTrue($builder->startElement( + "a", + array("href" => "http://somewhere", "id" => "44"))); + $this->assertTrue($builder->addContent("Label")); + $this->assertTrue($builder->endElement("a")); + + $page->tally(); + } + + function testLinkExtraction() { + $tag = &new SimpleAnchorTag(array("href" => "http://somewhere")); + $tag->addContent("Label"); + + $page = &new MockSimplePage($this); + $page->expectArguments("acceptTag", array($tag)); + $page->expectCallCount("acceptTag", 1); + + $builder = &new PartialSimplePageBuilder($this); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', new MockSimpleSaxParser($this)); + $builder->SimplePageBuilder(); + + $builder->parse(new MockSimpleHttpResponse($this)); + $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")); + + $page->tally(); + } + + 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($this); + $page->expectArgumentsAt(0, "acceptTag", array($a1)); + $page->expectArgumentsAt(1, "acceptTag", array($a2)); + $page->expectCallCount("acceptTag", 2); + + $builder = &new PartialSimplePageBuilder($this); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', new MockSimpleSaxParser($this)); + $builder->SimplePageBuilder(); + + $builder->parse(new MockSimpleHttpResponse($this)); + $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"); + + $page->tally(); + } + + function testTitle() { + $tag = &new SimpleTitleTag(array()); + $tag->addContent("HereThere"); + + $page = &new MockSimplePage($this); + $page->expectArguments("acceptTag", array($tag)); + $page->expectCallCount("acceptTag", 1); + + $builder = &new PartialSimplePageBuilder($this); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', new MockSimpleSaxParser($this)); + $builder->SimplePageBuilder(); + + $builder->parse(new MockSimpleHttpResponse($this)); + $builder->startElement("title", array()); + $builder->addContent("Here"); + $builder->addContent("There"); + $builder->endElement("title"); + + $page->tally(); + } + + function testForm() { + $page = &new MockSimplePage($this); + $page->expectOnce("acceptFormStart", array(new SimpleFormTag(array()))); + $page->expectOnce("acceptFormEnd", array()); + + $builder = &new PartialSimplePageBuilder($this); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', new MockSimpleSaxParser($this)); + $builder->SimplePageBuilder(); + + $builder->parse(new MockSimpleHttpResponse($this)); + $builder->startElement("form", array()); + $builder->addContent("Stuff"); + $builder->endElement("form"); + $page->tally(); + } + } + + class TestOfPageParsing extends UnitTestCase { + + function testParseMechanics() { + $parser = &new MockSimpleSaxParser($this); + $parser->expectOnce('parse', array('stuff')); + + $page = &new MockSimplePage($this); + $page->expectOnce('acceptPageEnd'); + + $builder = &new PartialSimplePageBuilder($this); + $builder->setReturnReference('_createPage', $page); + $builder->setReturnReference('_createParser', $parser); + $builder->SimplePageBuilder(); + + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', 'stuff'); + + $builder->parse($response); + $parser->tally(); + $page->tally(); + } + } + + 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($this); + + $response = &new MockSimpleHttpResponse($this); + $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($this); + $response->setReturnValue('getError', 'Ouch'); + + $page = &new SimplePage($response); + $this->assertEqual($page->getTransportError(), 'Ouch'); + } + + function testHeadersAccessor() { + $headers = &new MockSimpleHttpHeaders($this); + $headers->setReturnValue('getRaw', 'My: Headers'); + + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getHeaders', $headers); + + $page = &new SimplePage($response); + $this->assertEqual($page->getHeaders(), 'My: Headers'); + } + + function testMimeAccessor() { + $headers = &new MockSimpleHttpHeaders($this); + $headers->setReturnValue('getMimeType', 'text/html'); + + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getHeaders', $headers); + + $page = &new SimplePage($response); + $this->assertEqual($page->getMimeType(), 'text/html'); + } + + function testResponseAccessor() { + $headers = &new MockSimpleHttpHeaders($this); + $headers->setReturnValue('getResponseCode', 301); + + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getHeaders', $headers); + + $page = &new SimplePage($response); + $this->assertIdentical($page->getResponseCode(), 301); + } + + function testAuthenticationAccessors() { + $headers = &new MockSimpleHttpHeaders($this); + $headers->setReturnValue('getAuthentication', 'Basic'); + $headers->setReturnValue('getRealm', 'Secret stuff'); + + $response = &new MockSimpleHttpResponse($this); + $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($this); + $response->setReturnValue('getContent', 'Raw HTML'); + + $page = &new SimplePage($response); + $this->assertEqual($page->getRaw(), 'Raw HTML'); + } + + function testTextAccessor() { + $response = &new MockSimpleHttpResponse($this); + $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)); + $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($this)); + $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($this); + $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($this); + $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($this); + $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($this); + $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($this); + $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($this)); + $page->AcceptTag($title); + $this->assertEqual($page->getTitle(), 'Title'); + } + + function testFramesetAbsence() { + $url = new SimpleUrl('here'); + $response = new MockSimpleHttpResponse($this); + $response->setReturnValue('getUrl', $url); + $page = &new SimplePage($response); + $this->assertFalse($page->hasFrames()); + $this->assertIdentical($page->getFrameset(), false); + } + + function testHasEmptyFrameset() { + $page = &new SimplePage(new MockSimpleHttpResponse($this)); + $page->acceptFramesetStart(new SimpleTag('frameset', array())); + $page->acceptFramesetEnd(); + $this->assertTrue($page->hasFrames()); + $this->assertIdentical($page->getFrameset(), array()); + } + + function testFramesInPage() { + $response = &new MockSimpleHttpResponse($this); + $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($this); + $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 TestOfForms extends UnitTestCase { + + function testButtons() { + $page = &new SimplePage(new MockSimpleHttpResponse($this)); + $page->acceptFormStart( + new SimpleFormTag(array("method" => "GET", "action" => "here.php"))); + $page->AcceptTag( + new SimpleSubmitTag(array("type" => "submit", "name" => "s"))); + $page->acceptFormEnd(); + $form = &$page->getFormBySubmitLabel("Submit"); + $this->assertEqual( + $form->submitButtonByLabel("Submit"), + new SimpleFormEncoding(array("s" => "Submit"))); + } + } + + class TestOfPageScraping extends UnitTestCase { + + function &parse($response) { + $builder = &new SimplePageBuilder(); + return $builder->parse($response); + } + + function testEmptyPage() { + $page = &new SimplePage(new MockSimpleHttpResponse($this)); + $this->assertIdentical($page->getAbsoluteUrls(), array()); + $this->assertIdentical($page->getRelativeUrls(), array()); + $this->assertIdentical($page->getTitle(), false); + } + + function testUninterestingPage() { + $response = &new MockSimpleHttpResponse($this); + $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($this); + $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($this); + $response->setReturnValue('getContent', 'Me'); + + $page = &$this->parse($response); + $this->assertEqual($page->getTitle(), 'Me'); + } + + function testNastyTitle() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue( + 'getContent', + ' <b>Me&Me '); + + $page = &$this->parse($response); + $this->assertEqual($page->getTitle(), "Me&Me"); + } + + function testCompleteForm() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', + '
' . + '' . + '
'); + + $page = &$this->parse($response); + $this->assertEqual($page->getField('here'), "Hello"); + } + + function testUnclosedForm() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', + '
' . + '' . + ''); + + $page = &$this->parse($response); + $this->assertEqual($page->getField('here'), "Hello"); + } + + function testEmptyFrameset() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue( + 'getContent', + ''); + + $page = &$this->parse($response); + $this->assertTrue($page->hasFrames()); + $this->assertIdentical($page->getFrameset(), array()); + } + + function testSingleFrame() { + $response = &new MockSimpleHttpResponse($this); + $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($this); + $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($this); + $response->setReturnValue( + 'getContent', + ''); + + $page = &$this->parse($response); + $this->assertTrue($page->hasFrames()); + $this->assertIdentical($page->getFrameset(), array()); + } + + function testFramesCollectedWithNestedFramesetTags() { + $response = &new MockSimpleHttpResponse($this); + $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($this); + $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($this); + $response->setReturnValue( + 'getContent', + '
'); + + $page = &$this->parse($response); + $this->assertNull($page->getFormBySubmitLabel('submit')); + $this->assertIsA($page->getFormBySubmitName('submit'), 'SimpleForm'); + $this->assertIsA($page->getFormBySubmitLabel('Submit'), 'SimpleForm'); + } + + function testConfirmSubmitAttributesAreCaseInsensitive() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue( + 'getContent', + '
'); + + $page = &$this->parse($response); + $this->assertIsA($page->getFormBySubmitName('submit'), 'SimpleForm'); + $this->assertIsA($page->getFormBySubmitLabel('Submit'), 'SimpleForm'); + } + + function testFindFormByImage() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', '
' . + '' . + '
'); + + $page = &$this->parse($response); + $this->assertIsA($page->getFormByImageLabel('Label'), 'SimpleForm'); + $this->assertIsA($page->getFormByImageName('me'), 'SimpleForm'); + $this->assertIsA($page->getFormByImageId(100), 'SimpleForm'); + } + + function testFindFormByButtonTag() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', '
' . + '' . + '
'); + + $page = &$this->parse($response); + $this->assertNull($page->getFormBySubmitLabel('b')); + $this->assertNull($page->getFormBySubmitLabel('B')); + $this->assertIsA($page->getFormBySubmitName('b'), 'SimpleForm'); + $this->assertIsA($page->getFormBySubmitLabel('BBB'), 'SimpleForm'); + } + + function testFindFormById() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue( + 'getContent', + '
'); + + $page = &$this->parse($response); + $this->assertNull($page->getFormById(54)); + $this->assertIsA($page->getFormById(55), 'SimpleForm'); + } + + function testReadingTextField() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', '
' . + '' . + '' . + '
'); + + $page = &$this->parse($response); + $this->assertNull($page->getField('missing')); + $this->assertIdentical($page->getField('a'), ''); + $this->assertIdentical($page->getField('b'), 'bbb'); + } + + function testReadingTextFieldIsCaseInsensitive() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', '
' . + '' . + '' . + '
'); + + $page = &$this->parse($response); + $this->assertNull($page->getField('missing')); + $this->assertIdentical($page->getField('a'), ''); + $this->assertIdentical($page->getField('b'), 'bbb'); + } + + function testSettingTextField() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', '
' . + '' . + '' . + '' . + '
'); + + $page = &$this->parse($response); + $this->assertTrue($page->setField('a', 'aaa')); + $this->assertEqual($page->getField('a'), 'aaa'); + $this->assertTrue($page->setFieldById(3, 'bbb')); + $this->assertEqual($page->getFieldById(3), 'bbb'); + $this->assertFalse($page->setField('z', 'zzz')); + $this->assertNull($page->getField('z')); + } + + function testReadingTextArea() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', '
' . + '' . + '' . + '
'); + + $page = &$this->parse($response); + $this->assertEqual($page->getField('a'), 'aaa'); + } + + function testSettingTextArea() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', '
' . + '' . + '' . + '
'); + + $page = &$this->parse($response); + $this->assertTrue($page->setField('a', 'AAA')); + $this->assertEqual($page->getField('a'), 'AAA'); + } + + function testSettingSelectionField() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', '
' . + '' . + '' . + '
'); + + $page = &$this->parse($response); + $this->assertEqual($page->getField('a'), 'bbb'); + $this->assertFalse($page->setField('a', 'ccc')); + $this->assertTrue($page->setField('a', 'aaa')); + $this->assertEqual($page->getField('a'), 'aaa'); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/parse_error_test.php b/tests/UnitTests/simpletest/test/parse_error_test.php new file mode 100644 index 00000000..dd0f4eae --- /dev/null +++ b/tests/UnitTests/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/UnitTests/simpletest/test/parser_test.php b/tests/UnitTests/simpletest/test/parser_test.php new file mode 100644 index 00000000..6356c343 --- /dev/null +++ b/tests/UnitTests/simpletest/test/parser_test.php @@ -0,0 +1,648 @@ +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($this); + $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($this); + $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")); + $handler->tally(); + } + + function testMultiplePattern() { + $handler = &new MockTestParser($this); + $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")); + $handler->tally(); + } + } + + class TestOfLexerModes extends UnitTestCase { + + function testIsolatedPattern() { + $handler = &new MockTestParser($this); + $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")); + $handler->tally(); + } + + function testModeChange() { + $handler = &new MockTestParser($this); + $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")); + $handler->tally(); + } + + function testNesting() { + $handler = &new MockTestParser($this); + $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")); + $handler->tally(); + } + + function testSingular() { + $handler = &new MockTestParser($this); + $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")); + $handler->tally(); + } + + function testUnwindTooFar() { + $handler = &new MockTestParser($this); + $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")); + $handler->tally(); + } + } + + class TestOfLexerHandlers extends UnitTestCase { + + function testModeMapping() { + $handler = &new MockTestParser($this); + $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")); + $handler->tally(); + } + } + + Mock::generate("HtmlSaxParser"); + + class TestOfHtmlLexer extends UnitTestCase { + var $_handler; + var $_lexer; + + function setUp() { + $this->_handler = &new MockSimpleSaxParser($this); + $this->_handler->setReturnValue("acceptStartToken", true); + $this->_handler->setReturnValue("acceptEndToken", true); + $this->_handler->setReturnValue("acceptAttributeToken", true); + $this->_handler->setReturnValue("acceptEntityToken", true); + $this->_handler->setReturnValue("acceptTextToken", true); + $this->_handler->setReturnValue("ignore", true); + $this->_lexer = &SimpleSaxParser::createLexer($this->_handler); + } + + function tearDown() { + $this->_handler->tally(); + } + + function testUninteresting() { + $this->_handler->expectOnce("acceptTextToken", array("", "*")); + $this->assertTrue($this->_lexer->parse("")); + } + + function testSkipCss() { + $this->_handler->expectMaximumCallCount("acceptTextToken", 0); + $this->_handler->expectAtLeastOnce("ignore"); + $this->assertTrue($this->_lexer->parse("")); + } + + function testSkipJavaScript() { + $this->_handler->expectMaximumCallCount("acceptTextToken", 0); + $this->_handler->expectAtLeastOnce("ignore"); + $this->assertTrue($this->_lexer->parse("")); + } + + function testSkipComments() { + $this->_handler->expectMaximumCallCount("acceptTextToken", 0); + $this->_handler->expectAtLeastOnce("ignore"); + $this->assertTrue($this->_lexer->parse("")); + } + + function testTitleTag() { + $this->_handler->expectArgumentsAt(0, "acceptStartToken", array("_handler->expectArgumentsAt(1, "acceptStartToken", array(">", "*")); + $this->_handler->expectCallCount("acceptStartToken", 2); + $this->_handler->expectOnce("acceptTextToken", array("Hello", "*")); + $this->_handler->expectOnce("acceptEndToken", array("", "*")); + $this->assertTrue($this->_lexer->parse("Hello")); + } + + function testFramesetTag() { + $this->_handler->expectArgumentsAt(0, "acceptStartToken", array("_handler->expectArgumentsAt(1, "acceptStartToken", array(">", "*")); + $this->_handler->expectCallCount("acceptStartToken", 2); + $this->_handler->expectOnce("acceptTextToken", array("Frames", "*")); + $this->_handler->expectOnce("acceptEndToken", array("", "*")); + $this->assertTrue($this->_lexer->parse("Frames")); + } + + function testInputTag() { + $this->_handler->expectArgumentsAt(0, "acceptStartToken", array("_handler->expectArgumentsAt(1, "acceptStartToken", array("name", "*")); + $this->_handler->expectArgumentsAt(2, "acceptStartToken", array("value", "*")); + $this->_handler->expectArgumentsAt(3, "acceptStartToken", array(">", "*")); + $this->_handler->expectArgumentsAt(0, "acceptAttributeToken", array("=a.b.c", "*")); + $this->_handler->expectArgumentsAt(1, "acceptAttributeToken", array("= d", "*")); + $this->assertTrue($this->_lexer->parse("")); + } + + function testEmptyLink() { + $this->_handler->expectArgumentsAt(0, "acceptStartToken", array("_handler->expectArgumentsAt(1, "acceptStartToken", array(">", "*")); + $this->_handler->expectCallCount("acceptStartToken", 2); + $this->_handler->expectOnce("acceptEndToken", array("", "*")); + $this->assertTrue($this->_lexer->parse("")); + } + + function testLabelledLink() { + $this->_handler->expectArgumentsAt(0, "acceptStartToken", array("_handler->expectArgumentsAt(1, "acceptStartToken", array(">", "*")); + $this->_handler->expectCallCount("acceptStartToken", 2); + $this->_handler->expectOnce("acceptEndToken", array("", "*")); + $this->_handler->expectArgumentsAt(0, "acceptTextToken", array("", "*")); + $this->_handler->expectArgumentsAt(1, "acceptTextToken", array("label", "*")); + $this->_handler->expectArgumentsAt(2, "acceptTextToken", array("", "*")); + $this->_handler->expectCallCount("acceptTextToken", 3); + $this->assertTrue($this->_lexer->parse("label")); + } + + function testLinkAddress() { + $this->_handler->expectArgumentsAt(0, "acceptTextToken", array("", "*")); + $this->_handler->expectArgumentsAt(1, "acceptTextToken", array("label", "*")); + $this->_handler->expectArgumentsAt(2, "acceptTextToken", array("", "*")); + $this->_handler->expectCallCount("acceptTextToken", 3); + $this->_handler->expectArgumentsAt(0, "acceptStartToken", array("_handler->expectArgumentsAt(1, "acceptStartToken", array("href", "*")); + $this->_handler->expectArgumentsAt(2, "acceptStartToken", array(">", "*")); + $this->_handler->expectCallCount("acceptStartToken", 3); + $this->_handler->expectArgumentsAt(0, "acceptAttributeToken", array("= '", "*")); + $this->_handler->expectArgumentsAt(1, "acceptAttributeToken", array("here.html", "*")); + $this->_handler->expectArgumentsAt(2, "acceptAttributeToken", array("'", "*")); + $this->_handler->expectCallCount("acceptAttributeToken", 3); + $this->assertTrue($this->_lexer->parse("label")); + } + + function testEncodedLinkAddress() { + $this->_handler->expectArgumentsAt(0, "acceptTextToken", array("", "*")); + $this->_handler->expectArgumentsAt(1, "acceptTextToken", array("label", "*")); + $this->_handler->expectArgumentsAt(2, "acceptTextToken", array("", "*")); + $this->_handler->expectCallCount("acceptTextToken", 3); + $this->_handler->expectArgumentsAt(0, "acceptStartToken", array("_handler->expectArgumentsAt(1, "acceptStartToken", array("href", "*")); + $this->_handler->expectArgumentsAt(2, "acceptStartToken", array(">", "*")); + $this->_handler->expectCallCount("acceptStartToken", 3); + $this->_handler->expectArgumentsAt(0, "acceptAttributeToken", array("= '", "*")); + $this->_handler->expectArgumentsAt(1, "acceptAttributeToken", array("here&there.html", "*")); + $this->_handler->expectArgumentsAt(2, "acceptAttributeToken", array("'", "*")); + $this->_handler->expectCallCount("acceptAttributeToken", 3); + $this->assertTrue($this->_lexer->parse("label")); + } + + function testEmptyLinkWithId() { + $this->_handler->expectArgumentsAt(0, "acceptTextToken", array("", "*")); + $this->_handler->expectArgumentsAt(1, "acceptTextToken", array("label", "*")); + $this->_handler->expectArgumentsAt(2, "acceptTextToken", array("", "*")); + $this->_handler->expectCallCount("acceptTextToken", 3); + $this->_handler->expectArgumentsAt(0, "acceptStartToken", array("_handler->expectArgumentsAt(1, "acceptStartToken", array("id", "*")); + $this->_handler->expectArgumentsAt(2, "acceptStartToken", array(">", "*")); + $this->_handler->expectCallCount("acceptStartToken", 3); + $this->_handler->expectArgumentsAt(0, "acceptAttributeToken", array("=\"", "*")); + $this->_handler->expectArgumentsAt(1, "acceptAttributeToken", array("0", "*")); + $this->_handler->expectArgumentsAt(2, "acceptAttributeToken", array("\"", "*")); + $this->_handler->expectCallCount("acceptAttributeToken", 3); + $this->assertTrue($this->_lexer->parse("label")); + } + + function testComplexLink() { + $this->_handler->expectArgumentsAt(0, "acceptStartToken", array("_handler->expectArgumentsAt(1, "acceptStartToken", array("HREF", "*")); + $this->_handler->expectArgumentsAt(2, "acceptStartToken", array("bool", "*")); + $this->_handler->expectArgumentsAt(3, "acceptStartToken", array("Style", "*")); + $this->_handler->expectArgumentsAt(4, "acceptStartToken", array(">", LEXER_EXIT)); + $this->_handler->expectCallCount("acceptStartToken", 5); + $this->_handler->expectArgumentsAt(0, "acceptAttributeToken", array("= '", "*")); + $this->_handler->expectArgumentsAt(1, "acceptAttributeToken", array("here.html", LEXER_UNMATCHED)); + $this->_handler->expectArgumentsAt(2, "acceptAttributeToken", array("'", "*")); + $this->_handler->expectArgumentsAt(3, "acceptAttributeToken", array("=\"", "*")); + $this->_handler->expectArgumentsAt(4, "acceptAttributeToken", array("'coo", "*")); + $this->_handler->expectArgumentsAt(5, "acceptAttributeToken", array('\"', "*")); + $this->_handler->expectArgumentsAt(6, "acceptAttributeToken", array("l'", "*")); + $this->_handler->expectArgumentsAt(7, "acceptAttributeToken", array("\"", "*")); + $this->_handler->expectCallCount("acceptAttributeToken", 8); + $this->assertTrue($this->_lexer->parse("label")); + } + + function testSubmit() { + $this->_handler->expectArgumentsAt(0, "acceptStartToken", array("_handler->expectArgumentsAt(1, "acceptStartToken", array("type", "*")); + $this->_handler->expectArgumentsAt(2, "acceptStartToken", array("name", "*")); + $this->_handler->expectArgumentsAt(3, "acceptStartToken", array("value", "*")); + $this->_handler->expectArgumentsAt(4, "acceptStartToken", array("/", "*")); + $this->_handler->expectArgumentsAt(5, "acceptStartToken", array(">", LEXER_EXIT)); + $this->_handler->expectCallCount("acceptStartToken", 6); + $this->assertTrue($this->_lexer->parse('')); + } + + function testFramesParsedWithoutError() { + $this->assertTrue($this->_lexer->parse( + '')); + $this->assertTrue($this->_lexer->parse( + 'Hello')); + } + } + + class TestOfTextExtraction extends UnitTestCase { + + function testSpaceNormalisation() { + $this->assertEqual( + SimpleSaxParser::normalise("\nOne\tTwo \nThree\t"), + 'One Two Three'); + } + + function testTagSuppression() { + $this->assertEqual( + SimpleSaxParser::normalise('Hello'), + 'Hello'); + } + + function testAdjoiningTagSuppression() { + $this->assertEqual( + SimpleSaxParser::normalise('HelloGoodbye'), + 'HelloGoodbye'); + } + + function testExtractImageAltTextWithDifferentQuotes() { + $this->assertEqual( + SimpleSaxParser::normalise('One\'Two\'Three'), + 'One Two Three'); + } + + function testExtractImageAltTextMultipleTimes() { + $this->assertEqual( + SimpleSaxParser::normalise('OneTwoThree'), + 'One Two Three'); + } + + function testHtmlEntityTranslation() { + $this->assertEqual( + SimpleSaxParser::normalise('<>"&'), + '<>"&'); + } + } + + class TestSimpleSaxParser extends SimpleSaxParser { + var $_lexer; + + function TestSimpleSaxParser(&$listener, &$lexer) { + $this->_lexer = &$lexer; + $this->SimpleSaxParser($listener); + } + + function &createLexer() { + return $this->_lexer; + } + } + + Mock::generate("SimpleSaxListener"); + Mock::generate("SimpleLexer"); + + class TestOfSaxGeneration extends UnitTestCase { + var $_listener; + var $_lexer; + + function setUp() { + $this->_listener = &new MockSimpleSaxListener($this); + $this->_lexer = &new MockSimpleLexer($this); + $this->_parser = &new TestSimpleSaxParser($this->_listener, $this->_lexer); + } + + function tearDown() { + $this->_listener->tally(); + $this->_lexer->tally(); + } + + function testLexerFailure() { + $this->_lexer->setReturnValue("parse", false); + $this->assertFalse($this->_parser->parse("")); + } + + function testLexerSuccess() { + $this->_lexer->setReturnValue("parse", true); + $this->assertTrue($this->_parser->parse("")); + } + + function testSimpleLinkStart() { + $this->_parser->parse(""); + $this->_listener->expectOnce("startElement", array("a", array())); + $this->_listener->setReturnValue("startElement", true); + $this->assertTrue($this->_parser->acceptStartToken("assertTrue($this->_parser->acceptStartToken(">", LEXER_EXIT)); + } + + function testSimpleTitleStart() { + $this->_parser->parse(""); + $this->_listener->expectOnce("startElement", array("title", array())); + $this->_listener->setReturnValue("startElement", true); + $this->assertTrue($this->_parser->acceptStartToken("assertTrue($this->_parser->acceptStartToken(">", LEXER_EXIT)); + } + + function testLinkStart() { + $this->_parser->parse(""); + $this->_listener->expectOnce("startElement", array("a", array("href" => "here.html"))); + $this->_listener->setReturnValue("startElement", true); + $this->assertTrue($this->_parser->acceptStartToken("assertTrue($this->_parser->acceptStartToken("href", LEXER_MATCHED)); + $this->assertTrue($this->_parser->acceptAttributeToken("=\"", LEXER_ENTER)); + $this->assertTrue($this->_parser->acceptAttributeToken("here.html", LEXER_UNMATCHED)); + $this->assertTrue($this->_parser->acceptAttributeToken("\"", LEXER_EXIT)); + $this->assertTrue($this->_parser->acceptStartToken(">", LEXER_EXIT)); + } + + function testLinkStartWithEncodedUrl() { + $this->_parser->parse(""); + $this->_listener->expectOnce( + "startElement", + array("a", array("href" => "here&there.html"))); + $this->_listener->setReturnValue("startElement", true); + $this->assertTrue($this->_parser->acceptStartToken("assertTrue($this->_parser->acceptStartToken("href", LEXER_MATCHED)); + $this->assertTrue($this->_parser->acceptAttributeToken("=\"", LEXER_ENTER)); + $this->assertTrue($this->_parser->acceptAttributeToken("here&there.html", LEXER_UNMATCHED)); + $this->assertTrue($this->_parser->acceptAttributeToken("\"", LEXER_EXIT)); + $this->assertTrue($this->_parser->acceptStartToken(">", LEXER_EXIT)); + } + + function testLinkStartWithId() { + $this->_parser->parse(""); + $this->_listener->expectOnce( + "startElement", + array("a", array("id" => "0"))); + $this->_listener->setReturnValue("startElement", true); + $this->assertTrue($this->_parser->acceptStartToken("assertTrue($this->_parser->acceptStartToken("id", LEXER_MATCHED)); + $this->assertTrue($this->_parser->acceptAttributeToken("= \"", LEXER_ENTER)); + $this->assertTrue($this->_parser->acceptAttributeToken("0", LEXER_UNMATCHED)); + $this->assertTrue($this->_parser->acceptAttributeToken("\"", LEXER_EXIT)); + $this->assertTrue($this->_parser->acceptStartToken(">", LEXER_EXIT)); + } + + function testLinkEnd() { + $this->_parser->parse(""); + $this->_listener->expectOnce("endElement", array("a")); + $this->_listener->setReturnValue("endElement", true); + $this->assertTrue($this->_parser->acceptEndToken("", LEXER_SPECIAL)); + } + + function testInput() { + $this->_parser->parse(""); + $this->_listener->expectOnce( + "startElement", + array("input", array("name" => "a"))); + $this->_listener->setReturnValue("startElement", true); + $this->assertTrue($this->_parser->acceptStartToken("assertTrue($this->_parser->acceptStartToken("name", LEXER_MATCHED)); + $this->assertTrue($this->_parser->acceptAttributeToken("= a", LEXER_SPECIAL)); + $this->assertTrue($this->_parser->acceptStartToken(">", LEXER_EXIT)); + } + + function testButton() { + $this->_parser->parse(""); + $this->_listener->expectOnce( + "startElement", + array("button", array("name" => "a"))); + $this->_listener->setReturnValue("startElement", true); + $this->assertTrue($this->_parser->acceptStartToken("assertTrue($this->_parser->acceptStartToken("name", LEXER_MATCHED)); + $this->assertTrue($this->_parser->acceptAttributeToken("= a", LEXER_SPECIAL)); + $this->assertTrue($this->_parser->acceptStartToken(">", LEXER_EXIT)); + } + + function testContent() { + $this->_parser->parse(""); + $this->_listener->expectOnce("addContent", array("stuff")); + $this->_listener->setReturnValue("addContent", true); + $this->assertTrue($this->_parser->acceptTextToken("stuff", LEXER_UNMATCHED)); + } + + function testIgnore() { + $this->_parser->parse(""); + $this->_listener->expectNever("addContent"); + $this->assertTrue($this->_parser->ignore("stuff", LEXER_UNMATCHED)); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/real_sites_test.php b/tests/UnitTests/simpletest/test/real_sites_test.php new file mode 100644 index 00000000..728b6e95 --- /dev/null +++ b/tests/UnitTests/simpletest/test/real_sites_test.php @@ -0,0 +1,29 @@ +assertTrue($this->get('http://www.lastcraft.com')); + $this->assertResponse(array(200)); + $this->assertMime(array('text/html')); + $this->clickLink('About'); + $this->assertTitle('About Last Craft'); + } + + function testSourceforge() { + $this->assertTrue($this->get('http://sourceforge.net/')); + $this->setField('words', 'simpletest'); + $this->assertTrue($this->clickImageByName('imageField')); + $this->assertTitle('SourceForge.net: Search'); + $this->assertTrue($this->clickLink('SimpleTest')); + $this->clickLink('statistics'); + $this->assertWantedPattern('/Statistics for the past 7 days/'); + $this->assertTrue($this->setField('report', 'Monthly')); + $this->clickSubmit('Change Stats View'); + $this->assertWantedPattern('/Statistics for the past \d+ months/'); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/remote_test.php b/tests/UnitTests/simpletest/test/remote_test.php new file mode 100644 index 00000000..16c82b31 --- /dev/null +++ b/tests/UnitTests/simpletest/test/remote_test.php @@ -0,0 +1,17 @@ +addTestCase(new RemoteTestCase( + $base_url . 'test/visual_test.php?xml=yes', + $base_url . 'test/visual_test.php?xml=yes&dry=yes')); + if (SimpleReporter::inCli()) { + exit ($test->run(new XmlReporter()) ? 0 : 1); + } + $test->run(new HtmlReporter()); +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/shell_test.php b/tests/UnitTests/simpletest/test/shell_test.php new file mode 100644 index 00000000..7d5631a3 --- /dev/null +++ b/tests/UnitTests/simpletest/test/shell_test.php @@ -0,0 +1,38 @@ +assertIdentical($shell->execute('echo Hello'), 0); + $this->assertWantedPattern('/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/UnitTests/simpletest/test/shell_tester_test.php b/tests/UnitTests/simpletest/test/shell_tester_test.php new file mode 100644 index 00000000..5a8f5b59 --- /dev/null +++ b/tests/UnitTests/simpletest/test/shell_tester_test.php @@ -0,0 +1,37 @@ +_mock_shell; + } + + function testExitCode() { + $this->_mock_shell = &new MockSimpleShell($this); + $this->_mock_shell->setReturnValue('execute', 0); + $this->_mock_shell->expectOnce('execute', array('ls')); + $this->assertTrue($this->execute('ls')); + $this->assertExitCode(0); + $this->_mock_shell->tally(); + } + + function testOutput() { + $this->_mock_shell = &new MockSimpleShell($this); + $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); + $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/UnitTests/simpletest/test/simple_mock_test.php b/tests/UnitTests/simpletest/test/simple_mock_test.php new file mode 100644 index 00000000..cdae14f9 --- /dev/null +++ b/tests/UnitTests/simpletest/test/simple_mock_test.php @@ -0,0 +1,648 @@ +assertTrue($expectation->test(33)); + $this->assertWantedPattern( + '/matches.*33/i', + $expectation->testMessage(33)); + } + } + + 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 testWildcardExpectations() { + $expectation = new ParametersExpectation(array(new WildcardExpectation())); + $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 WantedPatternExpectation('/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 WildcardExpectation(), 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 WildcardExpectation(), 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 WildcardExpectation()), "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($parameter) { + return $parameter; + } + + function anotherMethod() { + return true; + } + } + + Stub::generate("Dummy"); + Stub::generate("Dummy", "AnotherStubDummy"); + Stub::generate("Dummy", "StubDummyWithExtraMethods", array("extraMethod")); + + class SpecialSimpleStub extends SimpleStub { + function SpecialSimpleStub($wildcard) { + $this->SimpleStub($wildcard); + } + } + SimpleTestOptions::setStubBaseClass("SpecialSimpleStub"); + Stub::generate("Dummy", "SpecialStubDummy"); + SimpleTestOptions::setStubBaseClass("SimpleStub"); + + class TestOfStubGeneration extends UnitTestCase { + + function testCloning() { + $stub = &new StubDummy(); + $this->assertTrue(method_exists($stub, "aMethod")); + $this->assertNull($stub->aMethod()); + } + + 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->assertIsA($stub, "SpecialSimpleStub"); + $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($stub->aMethod(1, 2, 3), $object); + } + + function testWildcardReturn() { + $stub = &new StubDummy("wild"); + $stub->setReturnValue("aMethod", "aaa", array(1, "wild", 3)); + $this->assertIdentical($stub->aMethod(1, "something", 3), "aaa"); + $this->assertIdentical($stub->aMethod(1, "anything", 3), "aaa"); + } + + function testAllWildcardReturn() { + $stub = &new StubDummy("wild"); + $stub->setReturnValue("aMethod", "aaa"); + $this->assertIdentical($stub->aMethod(1, 2, 3), "aaa"); + $this->assertIdentical($stub->aMethod(), "aaa"); + } + + function testCallCount() { + $stub = &new StubDummy(); + $this->assertEqual($stub->getCallCount("aMethod"), 0); + $stub->aMethod(); + $this->assertEqual($stub->getCallCount("aMethod"), 1); + $stub->aMethod(); + $this->assertEqual($stub->getCallCount("aMethod"), 2); + } + + 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($stub->aMethod(), $object); + $this->assertNull($stub->aMethod()); + } + + function testComplicatedReturnSequence() { + $stub = &new StubDummy("wild"); + $object = new Dummy(); + $stub->setReturnValueAt(1, "aMethod", "aaa", array("a")); + $stub->setReturnValueAt(1, "aMethod", "bbb"); + $stub->setReturnReferenceAt(2, "aMethod", $object, array("wild", 2)); + $stub->setReturnValueAt(2, "aMethod", "value", array("wild", 3)); + $stub->setReturnValue("aMethod", 3, array(3)); + $this->assertNull($stub->aMethod()); + $this->assertEqual($stub->aMethod("a"), "aaa"); + $this->assertReference($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::generate("Dummy"); + Mock::generate("Dummy", "AnotherMockDummy"); + Mock::generate("Dummy", "MockDummyWithExtraMethods", array("extraMethod")); + + class SpecialSimpleMock extends SimpleMock { + function SpecialSimpleMock(&$test, $wildcard) { + $this->SimpleMock($test, $wildcard); + } + } + SimpleTestOptions::setMockBaseClass("SpecialSimpleMock"); + Mock::generate("Dummy", "SpecialMockDummy"); + SimpleTestOptions::setMockBaseClass("SimpleMock"); + + class TestOfMockGeneration extends UnitTestCase { + + function testCloning() { + $mock = &new MockDummy($this); + $this->assertTrue(method_exists($mock, "aMethod")); + $this->assertNull($mock->aMethod()); + } + + function testCloningWithExtraMethod() { + $mock = &new MockDummyWithExtraMethods($this); + $this->assertTrue(method_exists($mock, "extraMethod")); + } + + function testCloningWithChosenClassName() { + $mock = &new AnotherMockDummy($this); + $this->assertTrue(method_exists($mock, "aMethod")); + } + + function testCloningWithDifferentBaseClass() { + $mock = &new SpecialMockDummy($this); + $this->assertIsA($mock, "SpecialSimpleMock"); + $this->assertTrue(method_exists($mock, "aMethod")); + } + } + + class TestOfMockReturns extends UnitTestCase { + + function testNoUnitTesterSetThrowsError() { + $mock = &new MockDummy(); + $this->assertErrorPattern('/missing argument/i'); + $this->assertErrorPattern('/no unit tester/i'); + } + + function testParameteredReturn() { + $mock = &new MockDummy($this); + $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($this); + $object = new Dummy(); + $mock->setReturnReference("aMethod", $object, array(1, 2, 3)); + $this->assertReference($mock->aMethod(1, 2, 3), $object); + } + + function testWildcardReturn() { + $mock = &new MockDummy($this, "wild"); + $mock->setReturnValue("aMethod", "aaa", array(1, "wild", 3)); + $this->assertIdentical($mock->aMethod(1, "something", 3), "aaa"); + $this->assertIdentical($mock->aMethod(1, "anything", 3), "aaa"); + } + + function testPatternMatchReturn() { + $mock = &new MockDummy($this); + $mock->setReturnValue( + "aMethod", + "aaa", + array(new wantedPatternExpectation('/hello/i'))); + $this->assertIdentical($mock->aMethod('Hello'), "aaa"); + $this->assertNull($mock->aMethod('Goodbye')); + } + + function testCallCount() { + $mock = &new MockDummy($this); + $this->assertEqual($mock->getCallCount("aMethod"), 0); + $mock->aMethod(); + $this->assertEqual($mock->getCallCount("aMethod"), 1); + $mock->aMethod(); + $this->assertEqual($mock->getCallCount("aMethod"), 2); + } + + function testReturnReferenceSequence() { + $mock = &new MockDummy($this); + $object = new Dummy(); + $mock->setReturnReferenceAt(1, "aMethod", $object); + $this->assertNull($mock->aMethod()); + $this->assertReference($mock->aMethod(), $object); + $this->assertNull($mock->aMethod()); + $this->swallowErrors(); + } + } + + Mock::generate("SimpleTestCase"); + + class TestOfMockTally extends UnitTestCase { + + function testZeroCallCount() { + $mock = &new MockDummy($this); + $mock->expectCallCount("aMethod", 0); + $mock->tally(); + } + + function testExpectedCallCount() { + $mock = &new MockDummy($this); + $mock->expectCallCount("aMethod", 2); + $mock->aMethod(); + $mock->aMethod(); + $mock->tally(); + } + } + + class TestOfMockExpectations extends UnitTestCase { + var $_test; + + function TestOfMockExpectations() { + $this->UnitTestCase(); + } + + function setUp() { + $this->_test = &new MockSimpleTestCase($this); + } + + function tearDown() { + $this->_test->tally(); + } + + function testSettingExpectationOnNonMethodThrowsError() { + $mock = &new MockDummy($this); + $mock->expectMaximumCallCount("aMissingMethod", 2); + $this->assertError(); + } + + function testMaxCallsDetectsOverrun() { + $this->_test->expectOnce("assertTrue", array(false, '*')); + $mock = &new MockDummy($this->_test); + $mock->expectMaximumCallCount("aMethod", 2); + $mock->aMethod(); + $mock->aMethod(); + $mock->aMethod(); + } + + function testTallyOnMaxCallsSendsPassOnUnderrun() { + $this->_test->expectOnce("assertTrue", array(true, '*')); + $mock = &new MockDummy($this->_test); + $mock->expectMaximumCallCount("aMethod", 2); + $mock->aMethod(); + $mock->aMethod(); + $mock->tally(); + } + + function testExpectNeverDetectsOverrun() { + $this->_test->expectOnce("assertTrue", array(false, '*')); + $mock = &new MockDummy($this->_test); + $mock->expectNever("aMethod"); + $mock->aMethod(); + } + + function testTallyOnExpectNeverSendsPassOnUnderrun() { + $this->_test->expectOnce("assertTrue", array(true, '*')); + $mock = &new MockDummy($this->_test); + $mock->expectNever("aMethod"); + $mock->tally(); + } + + function testMinCalls() { + $this->_test->expectOnce("assertTrue", array(true, '*')); + $mock = &new MockDummy($this->_test); + $mock->expectMinimumCallCount("aMethod", 2); + $mock->aMethod(); + $mock->aMethod(); + $mock->tally(); + } + + function testFailedNever() { + $this->_test->expectOnce("assertTrue", array(false, '*')); + $mock = &new MockDummy($this->_test); + $mock->expectNever("aMethod"); + $mock->aMethod(); + } + + function testUnderOnce() { + $this->_test->expectOnce("assertTrue", array(false, '*')); + $mock = &new MockDummy($this->_test); + $mock->expectOnce("aMethod"); + $mock->tally(); + } + + function testOverOnce() { + $this->_test->expectOnce("assertTrue", array(false, '*')); + $mock = &new MockDummy($this->_test); + $mock->expectOnce("aMethod"); + $mock->aMethod(); + $mock->aMethod(); + $mock->tally(); + $this->swallowErrors(); + } + + function testUnderAtLeastOnce() { + $this->_test->expectOnce("assertTrue", array(false, '*')); + $mock = &new MockDummy($this->_test); + $mock->expectAtLeastOnce("aMethod"); + $mock->tally(); + } + + function testZeroArguments() { + $mock = &new MockDummy($this); + $mock->expectArguments("aMethod", array()); + $mock->aMethod(); + } + + function testExpectedArguments() { + $mock = &new MockDummy($this); + $mock->expectArguments("aMethod", array(1, 2, 3)); + $mock->aMethod(1, 2, 3); + } + + function testFailedArguments() { + $this->_test->expectOnce("assertTrue", array(false, "*")); + $mock = &new MockDummy($this->_test); + $mock->expectArguments("aMethod", array("this")); + $mock->aMethod("that"); + } + + function testWildcardArguments() { + $mock = &new MockDummy($this, "wild"); + $mock->expectArguments("aMethod", array("wild", 123, "wild")); + $mock->aMethod(100, 123, 101); + } + + function testSpecificSequence() { + $mock = &new MockDummy($this); + $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(); + } + + function testFailedSequence() { + $this->_test->expectArguments("assertTrue", array(false, "*")); + $this->_test->expectCallCount("assertTrue", 2); + $mock = &new MockDummy($this->_test); + $mock->expectArgumentsAt(0, "aMethod", array(1, 2, 3)); + $mock->expectArgumentsAt(1, "aMethod", array("Hello")); + $mock->aMethod(1, 2); + $mock->aMethod("Goodbye"); + } + + function testBadArgParameter() { + $mock = &new MockDummy($this); + $mock->expectArguments("aMethod", "foo"); + $this->assertErrorPattern('/\$args.*not an array/i'); + $mock->aMethod(); + $mock->tally(); + } + } + + class TestOfMockComparisons extends UnitTestCase { + + function testTestCaseRegistry() { + $test = &new MockSimpleTestCase($this); + $class = SimpleMock::registerTest($test); + $this->assertReference($test, SimpleMock::injectTest($class)); + } + + function testEqualComparisonOfMocksDoesNotCrash() { + $expectation = &new EqualExpectation(new MockDummy($this)); + $this->assertTrue($expectation->test(new MockDummy($this), true)); + } + + function testIdenticalComparisonOfMocksDoesNotCrash() { + $expectation = &new IdenticalExpectation(new MockDummy($this)); + $this->assertTrue($expectation->test(new MockDummy($this))); + } + } + + SimpleTestOptions::addPartialMockCode('function sayHello() { return "Hello"; }'); + Mock::generatePartial("Dummy", "TestDummy", array("anotherMethod")); + SimpleTestOptions::addPartialMockCode(); + + class TestOfPartialMocks extends UnitTestCase { + + function testMethodReplacement() { + $mock = &new TestDummy($this); + $this->assertEqual($mock->aMethod(99), 99); + $this->assertNull($mock->anotherMethod()); + } + + function testSettingReturns() { + $mock = &new TestDummy($this); + $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($this); + $object = new Dummy(); + $mock->setReturnReferenceAt(0, "anotherMethod", $object, array(3)); + $this->assertReference($mock->anotherMethod(3), $object); + } + + function testExpectations() { + $mock = &new TestDummy($this); + $mock->expectCallCount("anotherMethod", 2); + $mock->expectArguments("anotherMethod", array(77)); + $mock->expectArgumentsAt(1, "anotherMethod", array(66)); + $mock->anotherMethod(77); + $mock->anotherMethod(66); + $mock->tally(); + } + + function testAdditionalPartialMockCode() { + $dummy = &new TestDummy($this); + $this->assertEqual($dummy->sayHello(), 'Hello'); + } + + function testSettingExpectationOnMissingMethodThrowsError() { + $mock = &new TestDummy($this); + $mock->expectCallCount("aMissingMethod", 2); + $this->assertError(); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/socket_test.php b/tests/UnitTests/simpletest/test/socket_test.php new file mode 100644 index 00000000..a872d8c5 --- /dev/null +++ b/tests/UnitTests/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/UnitTests/simpletest/test/tag_test.php b/tests/UnitTests/simpletest/test/tag_test.php new file mode 100644 index 00000000..c18788af --- /dev/null +++ b/tests/UnitTests/simpletest/test/tag_test.php @@ -0,0 +1,462 @@ + '1', 'b' => '')); + $this->assertEqual($tag->getTagName(), 'title'); + $this->assertIdentical($tag->getAttribute('a'), '1'); + $this->assertIdentical($tag->getAttribute('b'), true); + $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'), true); + $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('' => 'text')); + $this->assertIdentical($tag->getDefault(), ''); + $this->assertIdentical($tag->getValue(), ''); + } + + 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->assertEqual($tag->getName(), 'submit'); + $this->assertEqual($tag->getValue(), 'Submit'); + $this->assertFalse($tag->setValue('Cannot set this')); + $this->assertEqual($tag->getValue(), 'Submit'); + $this->assertEqual($tag->getLabel(), 'Submit'); + $this->assertEqual($tag->getSubmitValues(), array('submit' => 'Submit')); + } + + 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!'); + $this->assertEqual($tag->getSubmitValues(), array('s' => 'Ok!')); + } + + function testImageSubmit() { + $tag = &new SimpleImageSubmitTag( + array('type' => 'image', 'name' => 's', 'alt' => 'Label')); + $this->assertEqual($tag->getName(), 's'); + $this->assertEqual($tag->getLabel(), 'Label'); + $this->assertEqual( + $tag->getSubmitValues(20, 30), + array('s.x' => 20, 's.y' => 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'); + $this->assertEqual($tag->getSubmitValues(), array('s' => 'do')); + } + } + + 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\ntext that\nshould be\nwrapped"); + $tag->setValue("New long text\nwith two lines"); + $this->assertEqual( + $tag->getValue(), + "New long\ntext\nwith two\nlines"); + } + } + + 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'); + } + + 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' => '')); + $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')); + } + } + + 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)); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/test_with_parse_error.php b/tests/UnitTests/simpletest/test/test_with_parse_error.php new file mode 100644 index 00000000..affdb751 --- /dev/null +++ b/tests/UnitTests/simpletest/test/test_with_parse_error.php @@ -0,0 +1,8 @@ + \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/unit_tester_test.php b/tests/UnitTests/simpletest/test/unit_tester_test.php new file mode 100644 index 00000000..a6a61f8d --- /dev/null +++ b/tests/UnitTests/simpletest/test/unit_tester_test.php @@ -0,0 +1,52 @@ +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'); + } + } + + class JBehaveStyleRunner extends SimpleRunner { + function JBehaveStyleRunner(&$test_case, &$scorer) { + $this->SimpleRunner($test_case, $scorer); + } + + function _isTest($method) { + return strtolower(substr($method, 0, 6)) == 'should'; + } + } + + class TestOfJBehaveStyleRunner extends UnitTestCase { + + function &_createRunner(&$reporter) { + return new JBehaveStyleRunner($this, $reporter); + } + + function testFail() { + $this->fail('This should not be run'); + } + + function shouldBeRun() { + $this->pass('This should be run'); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/unit_tests.php b/tests/UnitTests/simpletest/test/unit_tests.php new file mode 100644 index 00000000..ebc38ffe --- /dev/null +++ b/tests/UnitTests/simpletest/test/unit_tests.php @@ -0,0 +1,49 @@ +GroupTest('Unit tests'); + $this->addTestFile('errors_test.php'); + $this->addTestFile('options_test.php'); + $this->addTestFile('dumper_test.php'); + $this->addTestFile('expectation_test.php'); + $this->addTestFile('unit_tester_test.php'); + $this->addTestFile('simple_mock_test.php'); + $this->addTestFile('adapter_test.php'); + $this->addTestFile('socket_test.php'); + $this->addTestFile('encoding_test.php'); + $this->addTestFile('url_test.php'); + $this->addTestFile('http_test.php'); + $this->addTestFile('authentication_test.php'); + $this->addTestFile('user_agent_test.php'); + $this->addTestFile('parser_test.php'); + $this->addTestFile('tag_test.php'); + $this->addTestFile('form_test.php'); + $this->addTestFile('page_test.php'); + $this->addTestFile('frames_test.php'); + $this->addTestFile('browser_test.php'); + $this->addTestFile('web_tester_test.php'); + $this->addTestFile('shell_tester_test.php'); + $this->addTestFile('xml_test.php'); + } + } + + if (TEST == __FILE__) { + $test = &new UnitTests(); + if (SimpleReporter::inCli()) { + exit ($test->run(new TextReporter()) ? 0 : 1); + } + $test->run(new HtmlReporter()); + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/url_test.php b/tests/UnitTests/simpletest/test/url_test.php new file mode 100644 index 00000000..5ca01260 --- /dev/null +++ b/tests/UnitTests/simpletest/test/url_test.php @@ -0,0 +1,369 @@ +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='); + } + + function testParseEmptyParameter() { + $url = new SimpleUrl('?a='); + $this->assertEqual($url->getPath(), ''); + $this->assertEqual($url->getEncodedRequest(), '?a='); + } + + function testParseParameterPair() { + $url = new SimpleUrl('?a=A'); + $this->assertEqual($url->getPath(), ''); + $this->assertEqual($url->getEncodedRequest(), '?a=A'); + } + + function testParseMultipleParameters() { + $url = new SimpleUrl('?a=A&b=B'); + $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); + } + + function testParsingParameterMixture() { + $url = new SimpleUrl('?a=A&b=&c'); + $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c='); + } + + function testAddParameters() { + $url = new SimpleUrl(''); + $url->addRequestParameter('a', 'A'); + $this->assertEqual($url->getEncodedRequest(), '?a=A'); + $url->addRequestParameter('b', 'B'); + $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); + $url->addRequestParameter('a', 'aaa'); + $this->assertEqual($url->getEncodedRequest(), '?a=A&a=aaa&b=B'); + } + + 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(), '?32,45'); + } + + function testParseCordinates() { + $url = new SimpleUrl('?32,45'); + $this->assertIdentical($url->getX(), 32); + $this->assertIdentical($url->getY(), 45); + $this->assertEqual($url->getEncodedRequest(), '?32,45'); + } + + function testClearingCordinates() { + $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=?32,45'); + } + + 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'); + } + + 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", "?1,2", 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?3,4", 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'); + } + + function assertUrl($raw, $parts, $params = false, $coords = false) { + if (! is_array($params)) { + $params = array(); + } + $url = new SimpleUrl($raw); + $this->assertIdentical($url->getScheme(), $parts[0], "[$raw] scheme -> %s"); + $this->assertIdentical($url->getUsername(), $parts[1], "[$raw] username -> %s"); + $this->assertIdentical($url->getPassword(), $parts[2], "[$raw] password -> %s"); + $this->assertIdentical($url->getHost(), $parts[3], "[$raw] host -> %s"); + $this->assertIdentical($url->getPort(), $parts[4], "[$raw] port -> %s"); + $this->assertIdentical($url->getPath(), $parts[5], "[$raw] path -> %s"); + $this->assertIdentical($url->getTld(), $parts[6], "[$raw] tld -> %s"); + $this->assertIdentical($url->getEncodedRequest(), $parts[7], "[$raw] encoded -> %s"); + $this->assertIdentical($url->getFragment(), $parts[8], "[$raw] fragment -> %s"); + if ($coords) { + $this->assertIdentical($url->getX(), $coords[0], "[$raw] x -> %s"); + $this->assertIdentical($url->getY(), $coords[1], "[$raw] y -> %s"); + } + } + + function assertPreserved($string) { + $url = new SimpleUrl($string); + $this->assertEqual($url->asString(), $string); + } + } + + class TestOfAbsoluteUrls extends UnitTestCase { + + function 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 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 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/UnitTests/simpletest/test/user_agent_test.php b/tests/UnitTests/simpletest/test/user_agent_test.php new file mode 100644 index 00000000..578327c6 --- /dev/null +++ b/tests/UnitTests/simpletest/test/user_agent_test.php @@ -0,0 +1,546 @@ +setCookie(new SimpleCookie("a", "A")); + $cookies = $jar->getValidCookies(); + $this->assertEqual(count($cookies), 1); + $this->assertEqual($cookies[0]->getValue(), "A"); + } + + function testHostFilter() { + $jar = new SimpleCookieJar(); + $cookie = new SimpleCookie('a', 'A'); + $cookie->setHost('my-host.com'); + $jar->setCookie($cookie); + $cookie = new SimpleCookie('b', 'B'); + $cookie->setHost('another-host.com'); + $jar->setCookie($cookie); + $cookie = new SimpleCookie('c', 'C'); + $jar->setCookie($cookie); + $cookies = $jar->getValidCookies('my-host.com'); + $this->assertEqual(count($cookies), 2); + $this->assertEqual($cookies[0]->getValue(), 'A'); + $this->assertEqual($cookies[1]->getValue(), 'C'); + $this->assertEqual(count($jar->getValidCookies('another-host.com')), 2); + $this->assertEqual(count($jar->getValidCookies('www.another-host.com')), 2); + $this->assertEqual(count($jar->getValidCookies('new-host.org')), 1); + $this->assertEqual(count($jar->getValidCookies()), 3); + } + + function testPathFilter() { + $jar = new SimpleCookieJar(); + $jar->setCookie(new SimpleCookie("a", "A", "/path/")); + $this->assertEqual(count($jar->getValidCookies(false, "/")), 0); + $this->assertEqual(count($jar->getValidCookies(false, "/elsewhere")), 0); + $this->assertEqual(count($jar->getValidCookies(false, "/path/")), 1); + $this->assertEqual(count($jar->getValidCookies(false, "/path")), 1); + $this->assertEqual(count($jar->getValidCookies(false, "/pa")), 0); + $this->assertEqual(count($jar->getValidCookies(false, "/path/here/")), 1); + } + + function testPathFilterDeeply() { + $jar = new SimpleCookieJar(); + $jar->setCookie(new SimpleCookie("a", "A", "/path/more_path/")); + $this->assertEqual(count($jar->getValidCookies(false, "/path/")), 0); + $this->assertEqual(count($jar->getValidCookies(false, "/path")), 0); + $this->assertEqual(count($jar->getValidCookies(false, "/pa")), 0); + $this->assertEqual(count($jar->getValidCookies(false, "/path/more_path/")), 1); + $this->assertEqual(count($jar->getValidCookies(false, "/path/more_path/and_more")), 1); + $this->assertEqual(count($jar->getValidCookies(false, "/path/not_here/")), 0); + } + + function testMultipleCookieWithDifferentPaths() { + $jar = new SimpleCookieJar(); + $jar->setCookie(new SimpleCookie("a", "abc", "/")); + $jar->setCookie(new SimpleCookie("a", "123", "/path/here/")); + $cookies = $jar->getValidCookies("my-host.com", "/"); + $this->assertEqual($cookies[0]->getPath(), "/"); + $cookies = $jar->getValidCookies("my-host.com", "/path/"); + $this->assertEqual($cookies[0]->getPath(), "/"); + $cookies = $jar->getValidCookies("my-host.com", "/path/here"); + $this->assertEqual($cookies[0]->getPath(), "/"); + $this->assertEqual($cookies[1]->getPath(), "/path/here/"); + $cookies = $jar->getValidCookies("my-host.com", "/path/here/there"); + $this->assertEqual($cookies[0]->getPath(), "/"); + $this->assertEqual($cookies[1]->getPath(), "/path/here/"); + } + + function testOverwrite() { + $jar = new SimpleCookieJar(); + $jar->setCookie(new SimpleCookie("a", "abc", "/")); + $jar->setCookie(new SimpleCookie("a", "cde", "/")); + $cookies = $jar->getValidCookies(); + $this->assertIdentical($cookies[0]->getValue(), "cde"); + } + + function testClearSessionCookies() { + $jar = new SimpleCookieJar(); + $jar->setCookie(new SimpleCookie("a", "A", "/")); + $jar->restartSession(); + $this->assertEqual(count($jar->getValidCookies(false, "/")), 0); + } + + function testExpiryFilterByDate() { + $cookie = new SimpleCookie("a", "A", "/", "Wed, 25-Dec-02 04:24:20 GMT"); + $jar = new SimpleCookieJar(); + $jar->setCookie($cookie); + $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); + $this->assertIdentical($list = $jar->getValidCookies(false, "/"), array($cookie)); + $jar->restartSession("Wed, 25-Dec-02 04:24:21 GMT"); + $this->assertIdentical($list = $jar->getValidCookies(false, "/"), array()); + } + + function testExpiryFilterByAgeing() { + $cookie = new SimpleCookie("a", "A", "/", "Wed, 25-Dec-02 04:24:20 GMT"); + $jar = new SimpleCookieJar(); + $jar->setCookie($cookie); + $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); + $this->assertIdentical($list = $jar->getValidCookies(false, "/"), array($cookie)); + $jar->agePrematurely(2); + $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); + $this->assertIdentical($list = $jar->getValidCookies(false, "/"), array()); + } + + function testCookieClearing() { + $jar = new SimpleCookieJar(); + $jar->setCookie(new SimpleCookie("a", "abc", "/")); + $jar->setCookie(new SimpleCookie("a", "", "/")); + $this->assertEqual(count($cookies = $jar->getValidCookies(false, "/")), 1); + $this->assertIdentical($cookies[0]->getValue(), ""); + } + + function testCookieClearByDate() { + $jar = new SimpleCookieJar(); + $jar->setCookie(new SimpleCookie("a", "abc", "/", "Wed, 25-Dec-02 04:24:21 GMT")); + $jar->setCookie(new SimpleCookie("a", "def", "/", "Wed, 25-Dec-02 04:24:19 GMT")); + $cookies = $jar->getValidCookies(false, "/"); + $this->assertIdentical($cookies[0]->getValue(), "def"); + $jar->restartSession("Wed, 25-Dec-02 04:24:20 GMT"); + $this->assertEqual(count($jar->getValidCookies(false, "/")), 0); + } + } + + class TestOfFetchingUrlParameters extends UnitTestCase { + + function testGet() { + $headers = &new MockSimpleHttpHeaders($this); + $headers->setReturnValue('getMimeType', 'text/html'); + $headers->setReturnValue('getResponseCode', 200); + $headers->setReturnValue('getNewCookies', array()); + + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', 'stuff'); + $response->setReturnReference('getHeaders', $headers); + + $request = &new MockSimpleHttpRequest($this); + $request->setReturnReference('fetch', $response); + + $agent = &new MockRequestUserAgent($this); + $agent->setReturnReference('_createHttpRequest', $request); + $agent->expectOnce('_createHttpRequest', array( + 'GET', + new SimpleUrl('http://test:secret@this.com/page.html?a=A&b=B'), + new SimpleFormEncoding())); + $agent->SimpleUserAgent(); + + $agent->fetchResponse( + 'GET', + new SimpleUrl('http://test:secret@this.com/page.html'), + new SimpleFormEncoding(array('a' => 'A', 'b' => 'B'))); + $agent->tally(); + } + + function testHead() { + $headers = &new MockSimpleHttpHeaders($this); + $headers->setReturnValue('getMimeType', 'text/html'); + $headers->setReturnValue('getResponseCode', 200); + $headers->setReturnValue('getNewCookies', array()); + + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', 'stuff'); + $response->setReturnReference('getHeaders', $headers); + + $request = &new MockSimpleHttpRequest($this); + $request->setReturnReference('fetch', $response); + + $url = new SimpleUrl('http://this.com/page.html'); + $url->addRequestParameters(array('a' => 'A', 'b' => 'B')); + + $agent = &new MockRequestUserAgent($this); + $agent->setReturnReference('_createHttpRequest', $request); + $agent->expectOnce('_createHttpRequest', array( + 'HEAD', + new SimpleUrl('http://test:secret@this.com/page.html?a=A&b=B'), + new SimpleFormEncoding())); + $agent->SimpleUserAgent(); + + $agent->fetchResponse( + 'HEAD', + new SimpleUrl('http://test:secret@this.com/page.html'), + new SimpleFormEncoding(array('a' => 'A', 'b' => 'B'))); + $agent->tally(); + } + + function testPost() { + $headers = &new MockSimpleHttpHeaders($this); + $headers->setReturnValue('getMimeType', 'text/html'); + $headers->setReturnValue('getResponseCode', 200); + $headers->setReturnValue('getNewCookies', array()); + + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', 'stuff'); + $response->setReturnReference('getHeaders', $headers); + + $request = &new MockSimpleHttpRequest($this); + $request->setReturnReference('fetch', $response); + + $agent = &new MockRequestUserAgent($this); + $agent->setReturnReference('_createHttpRequest', $request); + $agent->expectOnce('_createHttpRequest', array( + 'POST', + new SimpleUrl('http://test:secret@this.com/page.html'), + new SimpleFormEncoding(array('a' => 'A', 'b' => 'B')))); + $agent->SimpleUserAgent(); + + $agent->fetchResponse( + 'POST', + new SimpleUrl('http://test:secret@this.com/page.html'), + new SimpleFormEncoding(array('a' => 'A', 'b' => 'B'))); + $agent->tally(); + } + } + + class TestOfAdditionalHeaders extends UnitTestCase { + + function testAdditionalHeaderAddedToRequest() { + $headers = &new MockSimpleHttpHeaders($this); + $headers->setReturnValue('getNewCookies', array()); + + $response = &new MockSimpleHttpResponse($this); + $response->setReturnReference('getHeaders', $headers); + + $request = &new MockSimpleHttpRequest($this); + $request->setReturnReference('fetch', $response); + $request->expectOnce( + 'addHeaderLine', + array('User-Agent: SimpleTest')); + + $agent = &new MockRequestUserAgent($this); + $agent->setReturnReference('_createHttpRequest', $request); + $agent->SimpleUserAgent(); + + $agent->addHeader('User-Agent: SimpleTest'); + $response = &$agent->fetchResponse('GET', new SimpleUrl('http://this.host/')); + $request->tally(); + } + } + + class TestOfBrowserCookies extends UnitTestCase { + + function &_createStandardResponse() { + $headers = &new MockSimpleHttpHeaders($this); + $headers->setReturnValue("getNewCookies", array()); + + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue("isError", false); + $response->setReturnValue("getContent", "stuff"); + $response->setReturnReference("getHeaders", $headers); + return $response; + } + + function &_createCookieSite($cookies) { + $headers = &new MockSimpleHttpHeaders($this); + $headers->setReturnValue("getNewCookies", $cookies); + + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue("isError", false); + $response->setReturnReference("getHeaders", $headers); + $response->setReturnValue("getContent", "stuff"); + + $request = &new MockSimpleHttpRequest($this); + $request->setReturnReference("fetch", $response); + return $request; + } + + function &_createPartialFetcher(&$request) { + $agent = &new MockRequestUserAgent($this); + $agent->setReturnReference('_createHttpRequest', $request); + $agent->SimpleUserAgent(); + return $agent; + } + + function testSendingExistingCookie() { + $request = &new MockSimpleHttpRequest($this); + $request->setReturnReference('fetch', $this->_createStandardResponse()); + $request->expectOnce('setCookie', array(new SimpleCookie('a', 'A'))); + + $agent = &$this->_createPartialFetcher($request); + $agent->setCookie('a', 'A'); + $response = $agent->fetchResponse( + 'GET', + new SimpleUrl('http://this.com/this/path/page.html'), + array()); + $this->assertEqual($response->getContent(), "stuff"); + $request->tally(); + } + + function testOverwriteCookieThatAlreadyExists() { + $request = &$this->_createCookieSite(array(new SimpleCookie("a", "AAAA", "this/path/"))); + $agent = &$this->_createPartialFetcher($request); + + $agent->setCookie("a", "A"); + $agent->fetchResponse( + "GET", + new SimpleUrl('http://this.com/this/path/page.html'), + array()); + $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); + } + + function testClearCookieBySettingExpiry() { + $request = &$this->_createCookieSite(array( + new SimpleCookie("a", "b", "this/path/", "Wed, 25-Dec-02 04:24:19 GMT"))); + $agent = &$this->_createPartialFetcher($request); + + $agent->setCookie("a", "A", "this/path/", "Wed, 25-Dec-02 04:24:21 GMT"); + $agent->fetchResponse( + 'GET', + new SimpleUrl('http://this.com/this/path/page.html'), + array()); + $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(array( + new SimpleCookie("a", "A", "this/path/", "Wed, 25-Dec-02 04:24:21 GMT"))); + $agent = &$this->_createPartialFetcher($request); + + $agent->fetchResponse( + 'GET', + new SimpleUrl('http://this.com/this/path/page.html'), + array()); + $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 testReadingIncomingAndSetCookies() { + $request = &$this->_createCookieSite(array( + new SimpleCookie("a", "AAA", "this/path/"))); + $agent = &$this->_createPartialFetcher($request); + + $this->assertNull($agent->getBaseCookieValue("a", false)); + $agent->fetchResponse( + 'GET', + new SimpleUrl('http://this.com/this/path/page.html'), + array()); + $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($this); + $headers->setReturnValue('getNewCookies', array()); + $headers->setReturnValue('isRedirect', (boolean)$redirect); + $headers->setReturnValue('getLocation', $redirect); + $headers->setReturnValue('getNewCookies', array()); + + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('getContent', $content); + $response->setReturnReference('getHeaders', $headers); + + $request = &new MockSimpleHttpRequest($this); + $request->setReturnReference('fetch', $response); + return $request; + } + + function testDisabledRedirects() { + $agent = &new MockRequestUserAgent($this); + $agent->setReturnReference( + '_createHttpRequest', + $this->createRedirect('stuff', 'there.html')); + $agent->expectOnce('_createHttpRequest'); + $agent->SimpleUserAgent(); + + $agent->setMaximumRedirects(0); + $response = &$agent->fetchResponse('GET', new SimpleUrl('here.html')); + + $this->assertEqual($response->getContent(), 'stuff'); + $agent->tally(); + } + + function testSingleRedirect() { + $agent = &new MockRequestUserAgent($this); + $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('GET', new SimpleUrl('one.html')); + + $this->assertEqual($response->getContent(), 'second'); + $agent->tally(); + } + + function testDoubleRedirect() { + $agent = &new MockRequestUserAgent($this); + $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('GET', new SimpleUrl('one.html')); + + $this->assertEqual($response->getContent(), 'third'); + $agent->tally(); + } + + function testSuccessAfterRedirect() { + $agent = &new MockRequestUserAgent($this); + $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('GET', new SimpleUrl('one.html')); + + $this->assertEqual($response->getContent(), 'second'); + $agent->tally(); + } + + function testRedirectChangesPostToGet() { + $agent = &new MockRequestUserAgent($this); + $agent->setReturnReferenceAt( + 0, + '_createHttpRequest', + $this->createRedirect('first', 'two.html')); + $agent->expectArgumentsAt(0, '_createHttpRequest', array('POST', '*', '*')); + $agent->setReturnReferenceAt( + 1, + '_createHttpRequest', + $this->createRedirect('second', 'three.html')); + $agent->expectArgumentsAt(1, '_createHttpRequest', array('GET', '*', '*')); + $agent->expectCallCount('_createHttpRequest', 2); + $agent->SimpleUserAgent(); + + $agent->setMaximumRedirects(1); + $response = &$agent->fetchResponse('POST', new SimpleUrl('one.html')); + + $agent->tally(); + } + } + + class TestOfBadHosts extends UnitTestCase { + + function &_createSimulatedBadHost() { + $response = &new MockSimpleHttpResponse($this); + $response->setReturnValue('isError', true); + $response->setReturnValue('getError', 'Bad socket'); + $response->setReturnValue('getContent', false); + + $request = &new MockSimpleHttpRequest($this); + $request->setReturnReference('fetch', $response); + return $request; + } + + function testUntestedHost() { + $request = &$this->_createSimulatedBadHost(); + + $agent = &new MockRequestUserAgent($this); + $agent->setReturnReference('_createHttpRequest', $request); + $agent->SimpleUserAgent(); + + $response = &$agent->fetchResponse( + 'GET', + new SimpleUrl('http://this.host/this/path/page.html')); + $this->assertTrue($response->isError()); + } + } + + class TestOfAuthorisation extends UnitTestCase { + + function testAuthenticateHeaderAdded() { + $headers = &new MockSimpleHttpHeaders($this); + $headers->setReturnValue('getNewCookies', array()); + + $response = &new MockSimpleHttpResponse($this); + $response->setReturnReference('getHeaders', $headers); + + $request = &new MockSimpleHttpRequest($this); + $request->setReturnReference('fetch', $response); + $request->expectOnce( + 'addHeaderLine', + array('Authorization: Basic ' . base64_encode('test:secret'))); + + $agent = &new MockRequestUserAgent($this); + $agent->setReturnReference('_createHttpRequest', $request); + $agent->SimpleUserAgent(); + + $response = &$agent->fetchResponse( + 'GET', + new SimpleUrl('http://test:secret@this.host')); + $request->tally(); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/visual_test.php b/tests/UnitTests/simpletest/test/visual_test.php new file mode 100644 index 00000000..975ef050 --- /dev/null +++ b/tests/UnitTests/simpletest/test/visual_test.php @@ -0,0 +1,386 @@ +_a = $a; + } + } + + class TestOfUnitTestCaseOutput extends UnitTestCase { + + function testOfResults() { + $this->pass('Pass'); + $this->fail('Fail'); // Fail. + } + + function testTrue() { + $this->assertTrue(true); + $this->assertTrue(false); // Fail. + } + + function testFalse() { + $this->assertFalse(true); // Fail. + $this->assertFalse(false); + } + + function testExpectation() { + $expectation = &new EqualExpectation(25, 'My expectation message: %s'); + $this->assertExpectation($expectation, 25, 'My assert message : %s'); + $this->assertExpectation($expectation, 24, 'My assert message : %s'); // Fail. + } + + function testNull() { + $this->assertNull(null, "%s -> Pass"); + $this->assertNull(false, "%s -> Fail"); // Fail. + $this->assertNotNull(null, "%s -> Fail"); // Fail. + $this->assertNotNull(false, "%s -> Pass"); + } + + function testType() { + $this->assertIsA("hello", "string", "%s -> Pass"); + $this->assertIsA(14, "string", "%s -> Fail"); // Fail. + $this->assertIsA($this, "TestOfUnitTestCaseOutput", "%s -> Pass"); + $this->assertIsA($this, "UnitTestCase", "%s -> Pass"); + $this->assertIsA(14, "TestOfUnitTestCaseOutput", "%s -> Fail"); // Fail. + $this->assertIsA($this, "TestReporter", "%s -> Fail"); // Fail. + } + + function testTypeEquality() { + $this->assertEqual("0", 0, "%s -> Pass"); + $this->assertNotEqual("0", 0, "%s -> Fail"); // Fail. + } + + function testNullEquality() { + $this->assertEqual(null, 1, "%s -> Fail"); // Fail. + $this->assertNotEqual(null, 1, "%s -> Pass"); + $this->assertEqual(1, null, "%s -> Fail"); // Fail. + $this->assertNotEqual(1, null, "%s -> Pass"); + } + + function testIntegerEquality() { + $this->assertEqual(1, 2, "%s -> Fail"); // Fail. + $this->assertNotEqual(1, 2, "%s -> Pass"); + } + + function testStringEquality() { + $this->assertEqual("a", "a", "%s -> Pass"); + $this->assertNotEqual("a", "a", "%s -> Fail"); // Fail. + $this->assertEqual("aa", "ab", "%s -> Fail"); // Fail. + $this->assertNotEqual("aa", "ab", "%s -> Pass"); + } + + function testHashEquality() { + $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> Pass"); + $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "Z"), "%s -> Pass"); + } + + function testStringIdentity() { + $a = "fred"; + $b = $a; + $this->assertIdentical($a, $b, "%s -> Pass"); + $this->assertNotIdentical($a, $b, "%s -> Fail"); // Fail. + } + + function testTypeIdentity() { + $a = "0"; + $b = 0; + $this->assertIdentical($a, $b, "%s -> Fail"); // Fail. + $this->assertNotIdentical($a, $b, "%s -> Pass"); + } + + function testNullIdentity() { + $this->assertIdentical(null, 1, "%s -> Fail"); // Fail. + $this->assertNotIdentical(null, 1, "%s -> Pass"); + $this->assertIdentical(1, null, "%s -> Fail"); // Fail. + $this->assertNotIdentical(1, null, "%s -> Pass"); + } + + function testHashIdentity() { + $this->assertIdentical(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> fail"); // Fail. + } + + function testObjectEquality() { + $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Pass"); + $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Fail"); // Fail. + $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Fail"); // Fail. + $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(false), "%s -> Fail"); // Fail. + $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Fail"); // Fail. + $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Pass"); + } + + function testReference() { + $a = "fred"; + $b = &$a; + $this->assertReference($a, $b, "%s -> Pass"); + $this->assertCopy($a, $b, "%s -> Fail"); // Fail. + $c = "Hello"; + $this->assertReference($a, $c, "%s -> Fail"); // Fail. + $this->assertCopy($a, $c, "%s -> Pass"); + } + + function testPatterns() { + $this->assertWantedPattern('/hello/i', "Hello there", "%s -> Pass"); + $this->assertNoUnwantedPattern('/hello/', "Hello there", "%s -> Pass"); + $this->assertWantedPattern('/hello/', "Hello there", "%s -> Fail"); // Fail. + $this->assertNoUnwantedPattern('/hello/i', "Hello there", "%s -> Fail"); // Fail. + } + + function testLongStrings() { + $text = ""; + for ($i = 0; $i < 10; $i++) { + $text .= "0123456789"; + } + $this->assertEqual($text, $text); + $this->assertEqual($text . $text, $text . "a" . $text); // Fail. + } + + 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->assertNoErrors("%s -> Pass"); + $this->assertError(); // Fail. + trigger_error('Error 1'); + $this->assertNoErrors("%s -> Fail"); // Fail. + $this->assertError(); + $this->assertNoErrors("%s -> Pass at end"); + } + + function testErrorText() { + trigger_error('Error 2'); + $this->assertError('Error 2', "%s -> Pass"); + trigger_error('Error 3'); + $this->assertError('Error 2', "%s -> Fail"); // Fail. + } + + function testErrorPatterns() { + trigger_error('Error 2'); + $this->assertErrorPattern('/Error 2/', "%s -> Pass"); + trigger_error('Error 3'); + $this->assertErrorPattern('/Error 2/', "%s -> Fail"); // Fail. + } + + function testDumping() { + $this->dump(array("Hello"), "Displaying a variable"); + } + + 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($this); + $dummy->expectCallCount('a', 1, 'My message: %s'); + $dummy->a(); + $dummy->tally(); + $dummy->a(); + $dummy->tally(); + } + + function testMinimumCallCounts() { + $dummy = &new MockDummy($this); + $dummy->expectMinimumCallCount('a', 2, 'My message: %s'); + $dummy->a(); + $dummy->tally(); + $dummy->a(); + $dummy->tally(); + } + + function testEmptyMatching() { + $dummy = &new MockDummy($this); + $dummy->expectArguments('a', array()); + $dummy->a(); + $dummy->a(null); // Fail. + } + + function testEmptyMatchingWithCustomMessage() { + $dummy = &new MockDummy($this); + $dummy->expectArguments('a', array(), 'My expectation message: %s'); + $dummy->a(); + $dummy->a(null); // Fail. + } + + function testNullMatching() { + $dummy = &new MockDummy($this); + $dummy->expectArguments('a', array(null)); + $dummy->a(null); + $dummy->a(); // Fail. + } + + function testBooleanMatching() { + $dummy = &new MockDummy($this); + $dummy->expectArguments('a', array(true, false)); + $dummy->a(true, false); + $dummy->a(true, true); // Fail. + } + + function testIntegerMatching() { + $dummy = &new MockDummy($this); + $dummy->expectArguments('a', array(32, 33)); + $dummy->a(32, 33); + $dummy->a(32, 34); // Fail. + } + + function testFloatMatching() { + $dummy = &new MockDummy($this); + $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($this); + $dummy->expectArguments('a', array('32', '33')); + $dummy->a('32', '33'); + $dummy->a('32', '34'); // Fail. + } + + function testEmptyMatchingWithCustomExpectationMessage() { + $dummy = &new MockDummy($this); + $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($this); + $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($this); + $dummy->expectArguments('a', array($a, $b)); + $dummy->a($a, $b); + $dummy->a($a, $a); // Fail. + } + + function testBigList() { + $dummy = &new MockDummy($this); + $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($this); + $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 AllOutputReporter 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"; + } + } + + $test = &new GroupTest("Visual test with 49 passes, 49 fails and 4 exceptions"); + $test->addTestCase(new TestOfUnitTestCaseOutput()); + $test->addTestCase(new TestOfMockObjectsOutput()); + $test->addTestCase(new TestOfPastBugs()); + $test->addTestCase(new TestOfVisualShell()); + + if (isset($_GET['xml']) || in_array('xml', (isset($argv) ? $argv : array()))) { + $reporter = &new XmlReporter(); + } elseif(SimpleReporter::inCli()) { + $reporter = &new TextReporter(); + } else { + $reporter = &new AllOutputReporter(); + } + 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/UnitTests/simpletest/test/web_tester_test.php b/tests/UnitTests/simpletest/test/web_tester_test.php new file mode 100644 index 00000000..6d3219c5 --- /dev/null +++ b/tests/UnitTests/simpletest/test/web_tester_test.php @@ -0,0 +1,133 @@ +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 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 HttpHeaderPatternExpectation('a', '/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 HttpHeaderPatternExpectation('a', '/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 HttpUnwantedHeaderExpectation('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 HttpUnwantedHeaderExpectation('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); + } + } + + class TestOfTextExpectations extends UnitTestCase { + + function testMatchingSubString() { + $expectation = new WantedTextExpectation('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 UnwantedTextExpectation('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); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/test/xml_test.php b/tests/UnitTests/simpletest/test/xml_test.php new file mode 100644 index 00000000..afb3faf9 --- /dev/null +++ b/tests/UnitTests/simpletest/test/xml_test.php @@ -0,0 +1,189 @@ + 2)); + $this->assertEqual($nesting->getSize(), 2); + } + } + + class TestOfXmlStructureParsing extends UnitTestCase { + + function testValidXml() { + $listener = &new MockSimpleScorer($this); + $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($this); + $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"); + $listener->tally(); + } + + function testEmptyCase() { + $listener = &new MockSimpleScorer($this); + $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"); + $listener->tally(); + } + + function testEmptyMethod() { + $listener = &new MockSimpleScorer($this); + $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"); + $listener->tally(); + } + + function testNestedGroup() { + $listener = &new MockSimpleScorer($this); + $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"); + $listener->tally(); + } + } + + 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($this); + $listener->expectOnce('paintPass', array('a_message')); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse("a_message\n")); + $this->sendValidEnd($parser); + $listener->tally(); + } + + function testFail() { + $listener = &new MockSimpleScorer($this); + $listener->expectOnce('paintFail', array('a_message')); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse("a_message\n")); + $this->sendValidEnd($parser); + $listener->tally(); + } + + function testException() { + $listener = &new MockSimpleScorer($this); + $listener->expectOnce('paintException', array('a_message')); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse("a_message\n")); + $this->sendValidEnd($parser); + $listener->tally(); + } + + function testSignal() { + $signal = new AnyOldSignal(); + $signal->stuff = "Hello"; + $listener = &new MockSimpleScorer($this); + $listener->expectOnce('paintSignal', array('a_signal', $signal)); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse( + "\n")); + $this->sendValidEnd($parser); + $listener->tally(); + } + + function testMessage() { + $listener = &new MockSimpleScorer($this); + $listener->expectOnce('paintMessage', array('a_message')); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse("a_message\n")); + $this->sendValidEnd($parser); + $listener->tally(); + } + + function testFormattedMessage() { + $listener = &new MockSimpleScorer($this); + $listener->expectOnce('paintFormattedMessage', array("\na\tmessage\n")); + $parser = &new SimpleTestXmlParser($listener); + $this->sendValidStart($parser); + $this->assertTrue($parser->parse("\n")); + $this->sendValidEnd($parser); + $listener->tally(); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/unit_tester.php b/tests/UnitTests/simpletest/unit_tester.php new file mode 100644 index 00000000..a8d4e9db --- /dev/null +++ b/tests/UnitTests/simpletest/unit_tester.php @@ -0,0 +1,303 @@ +SimpleTestCase($label); + } + + /** + * Will be true if the value is null. + * @param null $value Supposedly null value. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + 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->assertExpectation( + 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->assertExpectation( + 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->assertExpectation( + 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->assertExpectation( + new NotEqualExpectation($first), + $second, + $message); + } + + /** + * Will trigger a pass if the two parameters have + * the same value and same type. Otherwise a fail. + * @param mixed $first Value to compare. + * @param mixed $second Value to compare. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertIdentical($first, $second, $message = "%s") { + return $this->assertExpectation( + 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->assertExpectation( + 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. + * @param mixed $first Object reference to check. + * @param mixed $second Hopefully not the same object. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertCopy($first, $second, $message = "%s") { + $dumper = new SimpleDumper(); + $message = sprintf( + $message, + "[" . $dumper->describeValue($first) . + "] and [" . $dumper->describeValue($second) . + "] should not be the same object"); + return $this->assertFalse( + SimpleTestCompatibility::isReference($first, $second), + $message); + } + + /** + * Will trigger a pass if the Perl regex pattern + * is found in the subject. Fail otherwise. + * @param string $pattern Perl regex to look for including + * the regex delimiters. + * @param string $subject String to search in. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertWantedPattern($pattern, $subject, $message = "%s") { + return $this->assertExpectation( + new WantedPatternExpectation($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 assertNoUnwantedPattern($pattern, $subject, $message = "%s") { + return $this->assertExpectation( + new UnwantedPatternExpectation($pattern), + $subject, + $message); + } + + /** + * Confirms that no errors have occoured so + * far in the test method. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertNoErrors($message = "%s") { + $queue =SimpleErrorQueue::instance(); + return $this->assertTrue( + $queue->isEmpty(), + sprintf($message, "Should be no errors")); + } + + /** + * Confirms that an error has occoured and + * optionally that the error text matches exactly. + * @param string $expected Expected error text or + * false for no check. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertError($expected = false, $message = "%s") { + $queue =SimpleErrorQueue::instance(); + if ($queue->isEmpty()) { + $this->fail(sprintf($message, "Expected error not found")); + return; + } + list($severity, $content, $file, $line, $globals) = $queue->extract(); + $severity = SimpleErrorQueue::getSeverityAsString($severity); + return $this->assertTrue( + ! $expected || ($expected == $content), + "Expected [$expected] in PHP error [$content] severity [$severity] in [$file] line [$line]"); + } + + /** + * Confirms that an error has occoured and + * that the error text matches a Perl regular + * expression. + * @param string $pattern Perl regular expresion to + * match against. + * @param string $message Message to display. + * @return boolean True on pass + * @access public + */ + function assertErrorPattern($pattern, $message = "%s") { + $queue =SimpleErrorQueue::instance(); + if ($queue->isEmpty()) { + $this->fail(sprintf($message, "Expected error not found")); + return; + } + list($severity, $content, $file, $line, $globals) = $queue->extract(); + $severity = SimpleErrorQueue::getSeverityAsString($severity); + return $this->assertTrue( + (boolean)preg_match($pattern, $content), + "Expected pattern match [$pattern] in PHP error [$content] severity [$severity] in [$file] line [$line]"); + } + } +?> diff --git a/tests/UnitTests/simpletest/url.php b/tests/UnitTests/simpletest/url.php new file mode 100644 index 00000000..50a0b1aa --- /dev/null +++ b/tests/UnitTests/simpletest/url.php @@ -0,0 +1,508 @@ +_chompCoordinates($url); + $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->_request->setCoordinates($x, $y); + $this->_fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false); + $this->_target = false; + } + + /** + * Extracts the X, Y coordinate pair from an image map. + * @param string $url URL so far. The coordinates will be + * removed. + * @return array X, Y as a pair of integers. + * @access private + */ + 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) { + $request = new SimpleFormEncoding(); + 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; + } + + /** + * Accessor for horizontal image coordinate. + * @return integer X value. + * @access public + */ + function getX() { + return $this->_request->getX(); + } + + /** + * Accessor for vertical image coordinate. + * @return integer Y value. + * @access public + */ + function getY() { + return $this->_request->getY(); + } + + /** + * Accessor for current request parameters + * in URL string form + * @return string Form is string "?a=1&b=2", etc. + * @access public + */ + function getEncodedRequest() { + $encoded = $this->_request->asString(); + 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->_request->add($key, $value); + } + + /** + * Adds additional parameters to the request. + * @param hash/SimpleFormEncoding $parameters Additional + * parameters. + * @access public + */ + function addRequestParameters($parameters) { + $this->_request->merge($parameters); + } + + /** + * Clears down all parameters. + * @access public + */ + function clearRequest() { + $this->_request = new SimpleFormEncoding(); + } + + /** + * Sets image coordinates. Set to flase to clear + * them. + * @param integer $x Horizontal position. + * @param integer $y Vertical position. + * @access public + */ + function setCoordinates($x = false, $y = false) { + $this->_request->setCoordinates($x, $y); + } + + /** + * 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->_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() : ''; + return "$scheme://$identity$host$path$encoded$fragment"; + } + + /** + * Replaces unknown sections to turn a relative + * URL into an absolute one. The base URL can + * be either a string or a SimpleUrl object. + * @param string/SimpleUrl $base Base URL. + * @access public + */ + function makeAbsolute($base) { + if (! is_object($base)) { + $base = new SimpleUrl($base); + } + $scheme = $this->getScheme() ? $this->getScheme() : $base->getScheme(); + $host = $this->getHost() ? $this->getHost() : $base->getHost(); + $port = $this->_extractAbsolutePort($base); + $path = $this->normalisePath($this->_extractAbsolutePath($base)); + $identity = $this->_getIdentity() ? $this->_getIdentity() . '@' : ''; + $encoded = $this->getEncodedRequest(); + $fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; + return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment"); + } + + /** + * Extracts the port from the base URL if it's needed, but + * not present, in the current URL. + * @param string/SimpleUrl $base Base URL. + * @param string Absolute port number. + * @access private + */ + function _extractAbsolutePort($base) { + if ($this->getHost()) { + return ($this->getPort() ? ':' . $this->getPort() : ''); + } + return ($base->getPort() ? ':' . $base->getPort() : ''); + } + + /** + * 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 private + */ + 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/UnitTests/simpletest/user_agent.php b/tests/UnitTests/simpletest/user_agent.php new file mode 100644 index 00000000..f3cacfea --- /dev/null +++ b/tests/UnitTests/simpletest/user_agent.php @@ -0,0 +1,490 @@ +_cookies = array(); + } + + /** + * Removes expired and temporary cookies as if + * the browser was closed and re-opened. + * @param string/integer $now Time to test expiry against. + * @access public + */ + function restartSession($date = false) { + $surviving_cookies = array(); + for ($i = 0; $i < count($this->_cookies); $i++) { + if (! $this->_cookies[$i]->getValue()) { + continue; + } + if (! $this->_cookies[$i]->getExpiry()) { + continue; + } + if ($date && $this->_cookies[$i]->isExpired($date)) { + continue; + } + $surviving_cookies[] = $this->_cookies[$i]; + } + $this->_cookies = $surviving_cookies; + } + + /** + * Ages all cookies in the cookie jar. + * @param integer $interval The old session is moved + * into the past by this number + * of seconds. Cookies now over + * age will be removed. + * @access public + */ + function agePrematurely($interval) { + for ($i = 0; $i < count($this->_cookies); $i++) { + $this->_cookies[$i]->agePrematurely($interval); + } + } + + /** + * Adds a cookie to the jar. This will overwrite + * cookies with matching host, paths and keys. + * @param SimpleCookie $cookie New cookie. + * @access public + */ + function setCookie($cookie) { + for ($i = 0; $i < count($this->_cookies); $i++) { + $is_match = $this->_isMatch( + $cookie, + $this->_cookies[$i]->getHost(), + $this->_cookies[$i]->getPath(), + $this->_cookies[$i]->getName()); + if ($is_match) { + $this->_cookies[$i] = $cookie; + return; + } + } + $this->_cookies[] = $cookie; + } + + /** + * Fetches a hash of all valid cookies filtered + * by host, path and keyed by name + * Any cookies with missing categories will not + * be filtered out by that category. Expired + * cookies must be cleared by restarting the session. + * @param string $host Host name requirement. + * @param string $path Path encompassing cookies. + * @return hash Valid cookie objects keyed + * on the cookie name. + * @access public + */ + function getValidCookies($host = false, $path = "/") { + $valid_cookies = array(); + foreach ($this->_cookies as $cookie) { + if ($this->_isMatch($cookie, $host, $path, $cookie->getName())) { + $valid_cookies[] = $cookie; + } + } + return $valid_cookies; + } + + /** + * Tests cookie for matching against search + * criteria. + * @param SimpleTest $cookie Cookie to test. + * @param string $host Host must match. + * @param string $path Cookie path must be shorter than + * this path. + * @param string $name Name must match. + * @return boolean True if matched. + * @access private + */ + function _isMatch($cookie, $host, $path, $name) { + if ($cookie->getName() != $name) { + return false; + } + if ($host && $cookie->getHost() && !$cookie->isValidHost($host)) { + return false; + } + if (! $cookie->isValidPath($path)) { + return false; + } + return true; + } + + /** + * Adds the current cookies to a request. + * @param SimpleHttpRequest $request Request to modify. + * @param SimpleUrl $url Cookie selector. + * @access private + */ + function addHeaders($request, $url) { + $cookies = $this->getValidCookies($url->getHost(), $url->getPath()); + foreach ($cookies as $cookie) { + $request->setCookie($cookie); + } + } + } + + /** + * Fetches web pages whilst keeping track of + * cookies and authentication. + * @package SimpleTest + * @subpackage WebTester + */ + class SimpleUserAgent { + protected $_cookie_jar; + protected $_authenticator; + protected $_max_redirects; + protected $_proxy; + protected $_proxy_username; + protected $_proxy_password; + protected $_connection_timeout; + protected $_additional_headers; + + /** + * Starts with no cookies, realms or proxies. + * @access public + */ + function SimpleUserAgent() { + $this->_cookie_jar = new SimpleCookieJar(); + $this->_authenticator = new SimpleAuthenticator(); + $this->setMaximumRedirects(DEFAULT_MAX_REDIRECTS); + $this->_proxy = false; + $this->_proxy_username = false; + $this->_proxy_password = false; + $this->setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT); + $this->_additional_headers = array(); + } + + /** + * 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) { + $cookie = new SimpleCookie($name, $value, $path, $expiry); + if ($host) { + $cookie->setHost($host); + } + $this->_cookie_jar->setCookie($cookie); + } + + /** + * Reads the most specific cookie value from the + * browser cookies. + * @param string $host Host to search. + * @param string $path Applicable path. + * @param string $name Name of cookie to read. + * @return string False if not present, else the + * value as a string. + * @access public + */ + function getCookieValue($host, $path, $name) { + $longest_path = ''; + foreach ($this->_cookie_jar->getValidCookies($host, $path) as $cookie) { + if ($name == $cookie->getName()) { + if (strlen($cookie->getPath()) > strlen($longest_path)) { + $value = $cookie->getValue(); + $longest_path = $cookie->getPath(); + } + } + } + return (isset($value) ? $value : false); + } + + /** + * Reads the current cookies within the base URL. + * @param string $name Key of cookie to find. + * @param SimpleUrl $base Base URL to search from. + * @return string Null if there is no base URL, false + * if the cookie is not set. + * @access public + */ + function getBaseCookieValue($name, $base) { + if (! $base) { + return null; + } + return $this->getCookieValue($base->getHost(), $base->getPath(), $name); + } + + /** + * Sets the socket timeout for opening a connection. + * @param integer $timeout Maximum time in seconds. + * @access public + */ + 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) { + $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 $method GET, POST, etc. + * @param string/SimpleUrl $url Target to fetch. + * @param SimpleFormEncoding $parameters Additional parameters for request. + * @return SimpleHttpResponse Hopefully the target page. + * @access public + */ + function fetchResponse($method, $url, $parameters = false) { + if ($method != 'POST') { + $url->addRequestParameters($parameters); + $parameters = false; + } + $response = $this->_fetchWhileRedirected($method, $url, $parameters); + 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 string $method GET, POST, etc. + * @param SimpleUrl $url Target to fetch. + * @param SimpelFormEncoding $parameters Additional parameters for request. + * @return SimpleHttpResponse Hopefully the target page. + * @access private + */ + function _fetchWhileRedirected($method, $url, $parameters) { + $redirects = 0; + do { + $response = $this->_fetch($method, $url, $parameters); + if ($response->isError()) { + return $response; + } + $headers = $response->getHeaders(); + $location = new SimpleUrl($headers->getLocation()); + $url = $location->makeAbsolute($url); + $this->_addCookiesToJar($url, $headers->getNewCookies()); + if (! $headers->isRedirect()) { + break; + } + $method = 'GET'; + $parameters = false; + } while (! $this->_isTooManyRedirects(++$redirects)); + return $response; + } + + /** + * Actually make the web request. + * @param string $method GET, POST, etc. + * @param SimpleUrl $url Target to fetch. + * @param SimpleFormEncoding $parameters Additional parameters for request. + * @return SimpleHttpResponse Headers and hopefully content. + * @access protected + */ + function _fetch($method, $url, $parameters) { + if (! $parameters) { + $parameters = new SimpleFormEncoding(); + } + $request = $this->_createRequest($method, $url, $parameters); + return $request->fetch($this->_connection_timeout); + } + + /** + * Creates a full page request. + * @param string $method Fetching method. + * @param SimpleUrl $url Target to fetch as url object. + * @param SimpleFormEncoding $parameters POST/GET parameters. + * @return SimpleHttpRequest New request. + * @access private + */ + function _createRequest($method, $url, $parameters) { + $request = $this->_createHttpRequest($method, $url, $parameters); + $this->_addAdditionalHeaders($request); + $this->_cookie_jar->addHeaders($request, $url); + $this->_authenticator->addHeaders($request, $url); + return $request; + } + + /** + * Builds the appropriate HTTP request object. + * @param string $method Fetching method. + * @param SimpleUrl $url Target to fetch as url object. + * @param SimpleFormEncoding $parameters POST/GET parameters. + * @return SimpleHttpRequest New request object. + * @access protected + */ + function _createHttpRequest($method, $url, $parameters) { + if ($method == 'POST') { + $request = new SimpleHttpRequest( + $this->_createRoute($url), + 'POST', + $parameters); + return $request; + } + if ($parameters) { + $url->addRequestParameters($parameters); + } + return new SimpleHttpRequest($this->_createRoute($url), $method); + } + + /** + * Sets up either a direct route or via a proxy. + * @param SimpleUrl $url Target to fetch as url object. + * @return SimpleRoute Route to take to fetch URL. + * @access protected + */ + function _createRoute($url) { + if ($this->_proxy) { + return new SimpleProxyRoute( + $url, + $this->_proxy, + $this->_proxy_username, + $this->_proxy_password); + } + return new SimpleRoute($url); + } + + /** + * Adds additional manual headers. + * @param SimpleHttpRequest $request Outgoing request. + * @access private + */ + function _addAdditionalHeaders($request) { + foreach ($this->_additional_headers as $header) { + $request->addHeaderLine($header); + } + } + + /** + * Extracts new cookies into the cookie jar. + * @param SimpleUrl $url Target to fetch as url object. + * @param array $cookies New cookies. + * @access private + */ + function _addCookiesToJar($url, $cookies) { + foreach ($cookies as $cookie) { + if ($url->getHost()) { + $cookie->setHost($url->getHost()); + } + $this->_cookie_jar->setCookie($cookie); + } + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/web_tester.php b/tests/UnitTests/simpletest/web_tester.php new file mode 100644 index 00000000..315da35a --- /dev/null +++ b/tests/UnitTests/simpletest/web_tester.php @@ -0,0 +1,1330 @@ +SimpleExpectation(); + 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 [" . + $this->_dumper->describeValue($compare) . "] " . + $this->_dumper->describeDifference($this->_value, $compare); + } + } + } + + /** + * Test for a specific HTTP header within a header block. + * @package SimpleTest + * @subpackage WebTester + */ + class HttpHeaderExpectation extends SimpleExpectation { + protected $_expected_header; + protected $_expected_value; + + /** + * Sets the field and value to compare against. + * @param string $header Case insenstive trimmed header name. + * @param string $value Optional value to compare. If not + * given then any value will match. + */ + function HttpHeaderExpectation($header, $value = false) { + $this->_expected_header = $this->_normaliseHeader($header); + $this->_expected_value = $value; + } + + /** + * Accessor for subclases. + * @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) { + 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; + } + 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) { + $expectation = $this->_expected_header; + if ($this->_expected_value) { + $expectation .= ': ' . $this->_expected_header; + } + if (is_string($line = $this->_findHeader($compare))) { + return "Searching for header [$expectation] found [$line]"; + } else { + return "Failed to find header [$expectation]"; + } + } + } + + /** + * Test for a specific HTTP header within a header block that + * should not be found. + * @package SimpleTest + * @subpackage WebTester + */ + class HttpUnwantedHeaderExpectation extends HttpHeaderExpectation { + protected $_expected_header; + protected $_expected_value; + + /** + * Sets the field and value to compare against. + * @param string $unwanted Case insenstive trimmed header name. + */ + function HttpUnwantedHeaderExpectation($unwanted) { + $this->HttpHeaderExpectation($unwanted); + } + + /** + * 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 specific HTTP header within a header block. + * @package SimpleTest + * @subpackage WebTester + */ + class HttpHeaderPatternExpectation extends HttpHeaderExpectation { + + /** + * Sets the field and value to compare against. + * @param string $header Case insenstive header name. + * @param string $pattern Pattern to compare value against. + * @access public + */ + function HttpHeaderPatternExpectation($header, $pattern) { + $this->HttpHeaderExpectation($header, $pattern); + } + + /** + * Tests the value part of the header. + * @param string $value Value to test. + * @param mixed $pattern Pattern to test against. + * @return boolean True if matched. + * @access protected + */ + function _testHeaderValue($value, $expected) { + return (boolean)preg_match($expected, trim($value)); + } + } + + /** + * Test for a text substring. + * @package SimpleTest + * @subpackage UnitTester + */ + class WantedTextExpectation extends SimpleExpectation { + protected $_substring; + + /** + * Sets the value to compare against. + * @param string $substring Text to search for. + * @param string $message Customised message on failure. + * @access public + */ + function WantedTextExpectation($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 UnwantedTextExpectation extends WantedTextExpectation { + + /** + * Sets the reject pattern + * @param string $substring Text to search for. + * @param string $message Customised message on failure. + * @access public + */ + function UnwantedTextExpectation($substring, $message = '%s') { + $this->WantedTextExpectation($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); + } + } + } + + /** + * Extension that builds a web browser at the start of each + * test. + * @package SimpleTest + * @subpackage WebTester + */ + class WebTestCaseInvoker extends SimpleInvokerDecorator { + + /** + * Takes in the test case and reporter to mediate between. + * @param SimpleTestCase $test_case Test case to run. + * @param SimpleScorer $scorer Reporter to receive events. + */ + function WebTestCaseInvoker($invoker) { + $this->SimpleInvokerDecorator($invoker); + } + + /** + * Builds the browser and runs the test. + * @param string $method Test method to call. + * @access public + */ + function invoke($method) { + $test = $this->getTestCase(); + $test->setBrowser($test->createBrowser()); + parent::invoke($method); + $test->unsetBrowser(); + } + } + + /** + * Test case for testing of web pages. Allows + * fetching of pages, parsing of HTML and + * submitting forms. + * @package SimpleTest + * @subpackage WebTester + */ + class WebTestCase extends SimpleTestCase { + protected $_browser; + + /** + * 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); + } + + /** + * Sets the invoker to one that restarts the browser on + * each request. + * @return SimpleInvoker Invoker for each method. + * @access public + */ + function createInvoker() { + return new WebTestCaseInvoker(parent::createInvoker()); + } + + /** + * 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() { + return new SimpleBrowser(); + } + + /** + * Gets the last response error. + * @return string Last low level HTTP error. + * @access public + */ + function getTransportError() { + return $this->_browser->getTransportError(); + } + + /** + * Accessor for the currently selected URL. + * @return string Current location or false if + * no page yet fetched. + * @access public + */ + function getUrl() { + return $this->_browser->getUrl(); + } + + /** + * Dumps the current request for debugging. + * @access public + */ + function showRequest() { + $this->dump($this->_browser->getRequest()); + } + + /** + * Dumps the current HTTP headers for debugging. + * @access public + */ + function showHeaders() { + $this->dump($this->_browser->getHeaders()); + } + + /** + * Dumps the current HTML source for debugging. + * @access public + */ + function showSource() { + $this->dump($this->_browser->getContent()); + } + + /** + * 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(); + } + + /** + * 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 True on success. + * @access public + */ + function get($url, $parameters = false) { + $content = $this->_browser->get($url, $parameters); + if ($content === false) { + return false; + } + return true; + } + + /** + * 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 True on success. + * @access public + */ + function post($url, $parameters = false) { + $content = $this->_browser->post($url, $parameters); + if ($content === false) { + return false; + } + return true; + } + + /** + * 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->_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->_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->_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->_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 True if successful fetch. Note + * that authentication may still have + * failed. + * @access public + */ + function authenticate($username, $password) { + return $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 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. + * @access public + */ + function clickSubmit($label = 'Submit', $additional = false) { + return $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->_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->_browser->clickSubmitById($id, $additional); + } + + /** + * 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->_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->_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->_browser->clickImageById($id, $x, $y, $additional); + } + + /** + * 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->_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->_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->_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 string $message Message to display. Default + * can be embedded with %s. + * @return boolean True if link present. + * @access public + */ + function assertLink($label, $message = "%s") { + return $this->assertTrue( + $this->_browser->isLink($label), + sprintf($message, "Link [$label] should exist")); + } + + /** + * 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->assertFalse( + $this->_browser->isLink($label), + sprintf($message, "Link [$label] should not exist")); + } + + /** + * Tests for the presence of a link id attribute. + * @param string $id Id attribute value. + * @param string $message Message to display. Default + * can be embedded with %s. + * @return boolean True if link present. + * @access public + */ + function assertLinkById($id, $message = "%s") { + return $this->assertTrue( + $this->_browser->isLinkById($id), + sprintf($message, "Link ID [$id] should exist")); + } + + /** + * 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->assertFalse( + $this->_browser->isLinkById($id), + sprintf($message, "Link ID [$id] should not exist")); + } + + /** + * Sets all form fields with that name. + * @param string $name Name of field in forms. + * @param string $value New value of field. + * @return boolean True if field exists, otherwise false. + * @access public + */ + function setField($name, $value) { + return $this->_browser->setField($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($name, $expected = true, $message = "%s") { + $value = $this->_browser->getField($name); + if ($expected === true) { + return $this->assertTrue( + isset($value), + sprintf($message, "Field [$name] should exist")); + } else { + return $this->assertExpectation( + new FieldExpectation($expected), + $value, + sprintf($message, "Field [$name] should match with [%s]")); + } + } + + /** + * 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); + if ($expected === true) { + return $this->assertTrue( + isset($value), + sprintf($message, "Field of ID [$id] should exist")); + } else { + return $this->assertExpectation( + new FieldExpectation($expected), + $value, + sprintf($message, "Field of ID [$id] should match with [%s]")); + } + } + + /** + * 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') { + $message = sprintf($message, "Expected realm [$realm] got [" . + $this->_browser->getRealm() . "]"); + return $this->assertTrue( + strtolower($this->_browser->getRealm()) == strtolower($realm), + $message); + } + + /** + * Checks each header line for the required value. If no + * value is given then only an existence check is made. + * @param string $header Case insensitive header name. + * @param string $value Case sensitive trimmed string to + * match against. + * @return boolean True if pass. + * @access public + */ + function assertHeader($header, $value = false, $message = '%s') { + return $this->assertExpectation( + new HttpHeaderExpectation($header, $value), + $this->_browser->getHeaders(), + $message); + } + + /** + * Checks each header line for the required pattern. + * @param string $header Case insensitive header name. + * @param string $pattern Pattern to match value against. + * @return boolean True if pass. + * @access public + */ + function assertHeaderPattern($header, $pattern, $message = '%s') { + return $this->assertExpectation( + new HttpHeaderPatternExpectation($header, $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 assertNoUnwantedHeader($header, $message = '%s') { + return $this->assertExpectation( + new HttpUnwantedHeaderExpectation($header), + $this->_browser->getHeaders(), + $message); + } + + /** + * Tests the text between the title tags. + * @param string $title Expected title or empty + * if expecting no title. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertTitle($title = false, $message = '%s') { + return $this->assertTrue( + $title === $this->_browser->getTitle(), + sprintf($message, "Expecting title [$title] got [" . + $this->_browser->getTitle() . "]")); + } + + /** + * 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 assertWantedText($text, $message = '%s') { + return $this->assertExpectation( + new WantedTextExpectation($text), + $this->_browser->getContentAsText(), + $message); + } + + /** + * Will trigger a pass if the text is not found in the plain + * text form of the page. + * @param string $text Text to look for. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertNoUnwantedText($text, $message = '%s') { + return $this->assertExpectation( + new UnwantedTextExpectation($text), + $this->_browser->getContentAsText(), + $message); + } + + /** + * Will trigger a pass if the Perl regex pattern + * is found in the raw content. + * @param string $pattern Perl regex to look for including + * the regex delimiters. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertWantedPattern($pattern, $message = '%s') { + return $this->assertExpectation( + new WantedPatternExpectation($pattern), + $this->_browser->getContent(), + $message); + } + + /** + * Will trigger a pass if the perl regex pattern + * is not present in raw content. + * @param string $pattern Perl regex to look for including + * the regex delimiters. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertNoUnwantedPattern($pattern, $message = '%s') { + return $this->assertExpectation( + new UnwantedPatternExpectation($pattern), + $this->_browser->getContent(), + $message); + } + + /** + * Checks that a cookie is set for the current page + * and optionally checks the value. + * @param string $name Name of cookie to test. + * @param string $expected Expected value as a string or + * false if any value will do. + * @param string $message Message to display. + * @return boolean True if pass. + * @access public + */ + function assertCookie($name, $expected = false, $message = '%s') { + $value = $this->getCookie($name); + if ($expected) { + return $this->assertTrue($value === $expected, sprintf( + $message, + "Expecting cookie [$name] value [$expected], got [$value]")); + } else { + return $this->assertTrue( + $value, + sprintf($message, "Expecting cookie [$name]")); + } + } + + /** + * 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]")); + } + } +?> \ No newline at end of file diff --git a/tests/UnitTests/simpletest/xml.php b/tests/UnitTests/simpletest/xml.php new file mode 100644 index 00000000..a842860c --- /dev/null +++ b/tests/UnitTests/simpletest/xml.php @@ -0,0 +1,615 @@ +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); + } + + /** + * Increments the pass count. + * @param string $message Message is ignored. + * @access public + */ + function paintPass($message) { + parent::paintPass($message); + print $this->_getIndent(1); + print "<" . $this->_namespace . "pass>"; + print $this->toParsedXml($message); + print "_namespace . "pass>\n"; + } + + /** + * Increments the fail count. + * @param string $message Message is ignored. + * @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 a PHP error or exception. + * @param string $message Message is ignored. + * @access public + * @abstract + */ + function paintException($message) { + parent::paintException($message); + print $this->_getIndent(1); + print "<" . $this->_namespace . "exception>"; + print $this->toParsedXml($message); + print "_namespace . "exception>\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 { + protected $_name; + protected $_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 { + protected $_listener; + protected $_expat; + protected $_tag_stack; + protected $_in_content_tag; + protected $_content; + protected $_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', '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->paintException($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) { + } + } +?> -- cgit v1.2.3