summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorxue <>2006-07-16 01:50:23 +0000
committerxue <>2006-07-16 01:50:23 +0000
commitaf68030fcf0c266300feb2c100149ecadef7d364 (patch)
tree76b7c8ad5d8227870b9ef10c3e7b92a36336b320
parent4b78404c20490a615459267426ce9e6737bf4485 (diff)
Merge from 3.0 branch till 1264.
-rw-r--r--.gitattributes19
-rw-r--r--HISTORY372
-rw-r--r--buildscripts/texbuilder/Page2Tex.php286
-rw-r--r--demos/blog/protected/Pages/SearchPost.php2
-rw-r--r--demos/quickstart/protected/controls/TopicList.tpl2
-rw-r--r--demos/quickstart/protected/pages/Advanced/Assets.page2
-rw-r--r--demos/quickstart/protected/pages/Advanced/Collections.page2
-rw-r--r--demos/quickstart/protected/pages/Advanced/Error.page4
-rw-r--r--demos/quickstart/protected/pages/Advanced/I18N.page52
-rw-r--r--demos/quickstart/protected/pages/Advanced/Logging.page4
-rw-r--r--demos/quickstart/protected/pages/Advanced/Scripts.page178
-rw-r--r--demos/quickstart/protected/pages/Advanced/Scripts1.page156
-rw-r--r--demos/quickstart/protected/pages/Advanced/Scripts2.page144
-rw-r--r--demos/quickstart/protected/pages/Advanced/Scripts3.page22
-rw-r--r--demos/quickstart/protected/pages/Advanced/Security.page8
-rw-r--r--demos/quickstart/protected/pages/Advanced/State.page2
-rw-r--r--demos/quickstart/protected/pages/Advanced/Themes.page8
-rw-r--r--demos/quickstart/protected/pages/Comments.page46
-rw-r--r--demos/quickstart/protected/pages/Comments.php76
-rw-r--r--demos/quickstart/protected/pages/Controls/ClientScript.page36
-rw-r--r--demos/quickstart/protected/pages/Controls/DataGrid.page10
-rw-r--r--demos/quickstart/protected/pages/Controls/DataList.page2
-rw-r--r--demos/quickstart/protected/pages/Controls/DatePicker.page34
-rw-r--r--demos/quickstart/protected/pages/Controls/HtmlArea.page4
-rw-r--r--demos/quickstart/protected/pages/Controls/JavascriptLogger.page4
-rw-r--r--demos/quickstart/protected/pages/Controls/NewControl.page6
-rw-r--r--demos/quickstart/protected/pages/Controls/Panel.page2
-rw-r--r--demos/quickstart/protected/pages/Controls/Repeater.page2
-rw-r--r--demos/quickstart/protected/pages/Controls/Validation.page4
-rw-r--r--demos/quickstart/protected/pages/Controls/Wizard.page6
-rw-r--r--demos/quickstart/protected/pages/GettingStarted/Introduction.page4
-rw-r--r--demos/quickstart/protected/pages/Search.page6
-rw-r--r--framework/Web/UI/TControl.php22
-rw-r--r--framework/Web/UI/TPage.php1
-rw-r--r--framework/Web/UI/WebControls/TCheckBox.php2
-rw-r--r--framework/Web/UI/WebControls/TClientScript.php42
-rw-r--r--framework/Web/UI/WebControls/TCustomValidator.php10
-rw-r--r--framework/Web/UI/WebControls/TRadioButton.php66
-rw-r--r--framework/Web/UI/WebControls/TTextHighlighter.php2
-rw-r--r--tests/FunctionalTests/tickets/protected/pages/Ticket284.page14
-rw-r--r--tests/FunctionalTests/tickets/protected/pages/Ticket284.php11
-rw-r--r--tests/FunctionalTests/tickets/protected/pages/Ticket284Component.php94
-rw-r--r--tests/FunctionalTests/tickets/protected/pages/Ticket284Component.tpl94
-rw-r--r--tests/FunctionalTests/tickets/tests/Ticket284TestCase.php14
-rwxr-xr-xtests/test_tools/simpletest/CHANGELOG2
-rwxr-xr-xtests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE119
-rwxr-xr-xtests/test_tools/simpletest/LICENSE507
-rwxr-xr-xtests/test_tools/simpletest/README22
-rwxr-xr-xtests/test_tools/simpletest/VERSION2
-rw-r--r--tests/test_tools/simpletest/authentication.php23
-rw-r--r--tests/test_tools/simpletest/browser.php397
-rw-r--r--tests/test_tools/simpletest/collector.php115
-rw-r--r--tests/test_tools/simpletest/compatibility.php184
-rw-r--r--tests/test_tools/simpletest/cookies.php380
-rw-r--r--tests/test_tools/simpletest/detached.php96
-rwxr-xr-xtests/test_tools/simpletest/docs/en/authentication_documentation.html48
-rwxr-xr-xtests/test_tools/simpletest/docs/en/browser_documentation.html27
-rwxr-xr-xtests/test_tools/simpletest/docs/en/expectation_documentation.html40
-rwxr-xr-xtests/test_tools/simpletest/docs/en/form_testing_documentation.html13
-rwxr-xr-xtests/test_tools/simpletest/docs/en/group_test_documentation.html5
-rwxr-xr-xtests/test_tools/simpletest/docs/en/index.html48
-rwxr-xr-xtests/test_tools/simpletest/docs/en/mock_objects_documentation.html272
-rwxr-xr-xtests/test_tools/simpletest/docs/en/overview.html154
-rwxr-xr-xtests/test_tools/simpletest/docs/en/partial_mocks_documentation.html3
-rwxr-xr-xtests/test_tools/simpletest/docs/en/reporter_documentation.html3
-rwxr-xr-xtests/test_tools/simpletest/docs/en/unit_test_documentation.html19
-rwxr-xr-xtests/test_tools/simpletest/docs/en/web_tester_documentation.html31
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/authentication_documentation.html264
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/browser_documentation.html329
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/docs.css84
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/expectation_documentation.html263
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/form_testing_documentation.html235
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/group_test_documentation.html288
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/index.html343
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/mock_objects_documentation.html492
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/overview.html294
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/partial_mocks_documentation.html333
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/reporter_documentation.html386
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/server_stubs_documentation.html279
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/unit_test_documentation.html306
-rwxr-xr-xtests/test_tools/simpletest/docs/fr/web_tester_documentation.html397
-rw-r--r--tests/test_tools/simpletest/dumper.php54
-rw-r--r--tests/test_tools/simpletest/encoding.php493
-rw-r--r--tests/test_tools/simpletest/errors.php63
-rw-r--r--tests/test_tools/simpletest/exceptions.php46
-rw-r--r--tests/test_tools/simpletest/expectation.php234
-rwxr-xr-xtests/test_tools/simpletest/extensions/pear_test_case.php199
-rwxr-xr-xtests/test_tools/simpletest/extensions/phpunit_test_case.php108
-rw-r--r--tests/test_tools/simpletest/form.php395
-rw-r--r--tests/test_tools/simpletest/frames.php241
-rw-r--r--tests/test_tools/simpletest/http.php365
-rw-r--r--tests/test_tools/simpletest/invoker.php139
-rw-r--r--tests/test_tools/simpletest/mock_objects.php832
-rw-r--r--tests/test_tools/simpletest/page.php584
-rw-r--r--tests/test_tools/simpletest/parser.php213
-rw-r--r--tests/test_tools/simpletest/reflection_php4.php115
-rw-r--r--tests/test_tools/simpletest/reflection_php5.php275
-rw-r--r--tests/test_tools/simpletest/remote.php8
-rw-r--r--tests/test_tools/simpletest/reporter.php178
-rw-r--r--tests/test_tools/simpletest/scorer.php507
-rw-r--r--tests/test_tools/simpletest/selector.php133
-rw-r--r--tests/test_tools/simpletest/shell_tester.php63
-rw-r--r--tests/test_tools/simpletest/simpletest.php282
-rw-r--r--tests/test_tools/simpletest/socket.php28
-rw-r--r--tests/test_tools/simpletest/tag.php553
-rw-r--r--tests/test_tools/simpletest/test_case.php684
-rw-r--r--tests/test_tools/simpletest/unit_tester.php182
-rw-r--r--tests/test_tools/simpletest/url.php105
-rw-r--r--tests/test_tools/simpletest/user_agent.php297
-rw-r--r--tests/test_tools/simpletest/web_tester.php491
-rw-r--r--tests/test_tools/simpletest/xml.php107
111 files changed, 8130 insertions, 8524 deletions
diff --git a/.gitattributes b/.gitattributes
index 993b0cba..3127d88f 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -587,6 +587,7 @@ buildscripts/phing/tasks/XmlLintTask.php -text
buildscripts/phing/tasks/ZendCodeAnalyzerTask.php -text
buildscripts/phpbuilder/build.php -text
buildscripts/setup.php -text
+buildscripts/texbuilder/Page2Tex.php -text
buildscripts/texbuilder/quickstart/build.php -text
buildscripts/texbuilder/quickstart/pages.php -text
buildscripts/texbuilder/quickstart/quickstart.tex -text
@@ -803,8 +804,6 @@ demos/quickstart/protected/pages/Advanced/mastercontent.gif -text
demos/quickstart/protected/pages/Advanced/mastercontent.vsd -text
demos/quickstart/protected/pages/Advanced/pcrelation.gif -text
demos/quickstart/protected/pages/Advanced/pcrelation.vsd -text
-demos/quickstart/protected/pages/Comments.page -text
-demos/quickstart/protected/pages/Comments.php -text
demos/quickstart/protected/pages/Configurations/AppConfig.page -text
demos/quickstart/protected/pages/Configurations/Overview.page -text
demos/quickstart/protected/pages/Configurations/PageConfig.page -text
@@ -1863,6 +1862,10 @@ tests/FunctionalTests/tickets/protected/pages/Ticket239.php -text
tests/FunctionalTests/tickets/protected/pages/Ticket27.page -text
tests/FunctionalTests/tickets/protected/pages/Ticket28.page -text
tests/FunctionalTests/tickets/protected/pages/Ticket28.php -text
+tests/FunctionalTests/tickets/protected/pages/Ticket284.page -text
+tests/FunctionalTests/tickets/protected/pages/Ticket284.php -text
+tests/FunctionalTests/tickets/protected/pages/Ticket284Component.php -text
+tests/FunctionalTests/tickets/protected/pages/Ticket284Component.tpl -text
tests/FunctionalTests/tickets/protected/pages/Ticket54.page -text
tests/FunctionalTests/tickets/protected/pages/Ticket54Master.php -text
tests/FunctionalTests/tickets/protected/pages/Ticket54Master.tpl -text
@@ -1880,6 +1883,7 @@ tests/FunctionalTests/tickets/tests/Ticket191TestCase.php -text
tests/FunctionalTests/tickets/tests/Ticket21TestCase.php -text
tests/FunctionalTests/tickets/tests/Ticket239TestCase.php -text
tests/FunctionalTests/tickets/tests/Ticket27TestCase.php -text
+tests/FunctionalTests/tickets/tests/Ticket284TestCase.php -text
tests/FunctionalTests/tickets/tests/Ticket28TestCase.php -text
tests/FunctionalTests/tickets/tests/Ticket54TestCase.php -text
tests/FunctionalTests/tickets/tests/Ticket72TestCase.php -text
@@ -1926,6 +1930,17 @@ tests/FunctionalTests/validators/tests/RegExpValidatorTestCase.php -text
tests/FunctionalTests/validators/tests/RequiredFieldTestCase.php -text
tests/FunctionalTests/validators/tests/RequiredListTestCase.php -text
tests/FunctionalTests/validators/tests/ValidationSummaryTestCase.php -text
+tests/test_tools/simpletest/collector.php -text
+tests/test_tools/simpletest/compatibility.php -text
+tests/test_tools/simpletest/cookies.php -text
+tests/test_tools/simpletest/detached.php -text
+tests/test_tools/simpletest/exceptions.php -text
+tests/test_tools/simpletest/invoker.php -text
+tests/test_tools/simpletest/reflection_php4.php -text
+tests/test_tools/simpletest/reflection_php5.php -text
+tests/test_tools/simpletest/selector.php -text
+tests/test_tools/simpletest/simpletest.php -text
+tests/test_tools/simpletest/test_case.php -text
tests/unit/Collections/TListTest.php -text
tests/unit/Collections/TMapTest.php -text
tests/unit/I18N/core/CultureInfoTest.php -text
diff --git a/HISTORY b/HISTORY
index fe92f7fd..93038b23 100644
--- a/HISTORY
+++ b/HISTORY
@@ -1,185 +1,187 @@
-Version 3.1.0 To be released
-============================
-BUG: Ticket#188 - Postback js caused controls not inheritable (Qiang)
-ENH: Ticket#180, #222 - Prado js files are not rendered at the beginning of the form (Qiang)
-ENH: Ticket#99 - TXmlTransform control (Knut)
-ENH: Ticket#117 - added support to configure subproperties in a group. (Qiang)
-NEW: TOutputCache (Qiang)
-NEW: TQueue (Qiang)
-NEW: TSessionPageStatePersister (Qiang)
-NEW: SQLMap (Wei)
-NEW: TFeedService, TRssFeedDocument (Knut, Qiang)
-
-Version 3.0.3 August 6, 2006
-============================
-BUG: Ticket#264 - Typos in some exception throw statements (Knut)
-BUG: Ticket#268 - THttpResponse.redirect() may fail for some browsers (Qiang)
-BUG: TDataGrid may complain getting ItemType on a non-object if the grid is not data-bound (Qiang)
-ENH: Ticket#220 - TClientScripts method to import custom javascript files (Wei)
-ENH: Ticket#225 - TRadioButton::getRadioButtonsInGroup() added (Wei)
-ENH: Ticket#223 - Use TRequiredFieldValidator for TRadioButtons with GroupName property (Wei)
-NEW: Added TStyleSheet (Wei)
-
-Version 3.0.2 July 2, 2006
-==========================
-BUG: Ticket#182 - List and validator controls cause problem in child classes (Qiang)
-BUG: Ticket#191 - Duplicated postbacks occur when using TButton with validators (Qiang)
-BUG: Ticket#207 - Validators ClientSide.OnError triggered twice (Wei)
-BUG: Ticket#213 - PRADO Requirements Checker charset error (Qiang)
-BUG: Ticket#227 - Enabled property doesn't works with THtmlArea (Wei)
-BUG: Ticket#234 - Postback target could be out of date (Qiang)
-BUG: Ticket#239 - Ondeactivate handler for the first View of MultiView is always fired (Qiang)
-BUG: Ticket#244 - redirect() needs absolute URL (Qiang)
-BUG: Ticket#245 - getIsSecureConnection() is not working correctly (Qiang)
-BUG: Ticket#246 - TDatePicker wrong popup position in scrolled div (Wei)
-BUG: Ticket#260 - Wrong value of a configuration option in setUseTransparentSessionID (Qiang)
-CHG: ensureChildControls() is now invoked in TControl::initRecursive (Qiang)
-CHG: Postback enabled control will always disable default client-side browser action. (Qiang)
-CHG: CSS and JS files in a theme are now included in page in alphabetic order (Qiang)
-ENH: Ticket#206 - Added OnValidate, OnError, OnSuccess events to validators (Qiang)
-ENH: Ticket#230 - Added TDataList.EmptyTemplate property (Qiang)
-ENH: Ticket#231 - Added TButton.ButtonType property to allow reset button (Qiang)
-ENH: Ticket#232 - Allow <%# %> and <%= %> embedded within property values (Qiang)
-ENH: Ticket#256 - Datagrid columns can now be accessed via IDs (Qiang)
-ENH: Ticket#257 - OnSelectedIndexChanged event of TDataList and TDataGrid now passes the original command parameter (Qiang)
-ENH: Ticket#262 - Added TCheckBox.Value property (Qiang)
-ENH: TRepeater, TDataList and TDataGrid will store data indices in DataKeys if DataKeyField is not set. (Qiang)
-ENH: Added TPageService.BasePageClass property (Qiang)
-ENH: Added TDataGrid.EmptyTemplate property (Qiang)
-ENH: Added paging feature to all TDataBoundControl-derived controls (Qiang)
-ENH: ClientSide.ObserveChanges="false" to only revalidate client side validator when control changes (Wei)
-NEW: Added TPager (Qiang)
-NEW: Added Dreamweaver taglib extension (Stanislav, Qiang)
-NEW: Prado Command line script to create a new project, see framework/prado-cli.php (Wei)
-
-Version 3.0.1 June 4, 2006
-==========================
-BUG: Ticket#28 - OnClick does not work with Safari/KHTML (Wei)
-BUG: Ticket#37 - Changes of config files do not trigger cache update (Qiang)
-BUG: Ticket#44 - THtmlArea (tiny_mce) not working on some systems (Qiang)
-BUG: Ticket#162 - Missing currency sign in TNumberFormat if Value is 0 (Wei)
-BUG: Ticket#167 - TSecurityManager issues warning when trying to encrypt/decrypt strings (Qiang)
-BUG: Ticket#169 - Validation of subclass of THtmlArea/TDatePicker fails (Wei)
-BUG: Ticket#179 - CGI incompatibility causing clientscripts.php failure (Qiang)
-BUG: Ticket#181 - Unable to change Content-Type in response header if charset is not set (Qiang)
-BUG: Ticket#200 - onClick javascript event triggered twice on CheckBox label (Qiang)
-BUG: newly created controls during postbacks might get their initial states reset during loadStateRecursive. (Qiang)
-ENH: Ticket#150 - TDataGrid and TDataList now render table section tags (Qiang)
-ENH: Ticket#152 - constituent parts of TWizard are exposed (Qiang)
-ENH: Ticket#184 - added TUserManager.Users and Roles properties (Qiang)
-ENH: Ticket#197 - sanity check for datagrid header and footer (Qiang)
-ENH: added sanity check to calling event handlers (Qiang)
-ENH: added search for quickstart tutorials (Wei)
-ENH: added support to property tags for template owner control (Qiang)
-ENH: added Bulgarian requirement checker messages (StanProg)
-ENH: added TTheme.BaseUrl and TTheme.BasePath property (Qiang)
-ENH: added TListControl.SelectedValues property (Qiang)
-ENH: added TThemeManager.AvailableThemes property (Qiang)
-ENH: refactored TUserManager and TAuthManager so that they are easier to be extended (Qiang)
-ENH: template syntax now supports setting event handler via subproperties (Qiang)
-CHG: Ticket#151 - URL format is modified to handle empty GET values (Qiang)
-CHG: Ticket#153 - TAssetManager now ignores .svn directories (Qiang)
-CHG: Changed TControl::onBubbleEvent() to TControl::bubbleEvent() (Qiang)
-NEW: TTableHeaderRow, TTableFooterRow and table section support (Qiang)
-NEW: TCompositeControl (Qiang)
-NEW: TTextProcessor (Qiang)
-NEW: TMarkdown (Wei)
-NEW: Blog demo (Qiang)
-
-Version 3.0.0 May 1, 2006
-=========================
-BUG: Ticket#68 - 2 TButtons with THtmlArea causes second button to fail to function (Wei)
-BUG: Ticket#70 - Javascript for TDataTypeValidator added (Wei)
-BUG: Ticket#131 - TImageMap and TLinkButton continue to postback even client validator fails (Wei)
-BUG: Ticket#135 - TBrowserLogRoute reports wrong timings (Qiang)
-BUG: Ticket#137 - The JavasciptLogger does not work (Qiang)
-BUG: Ticket#138 - missing file in TDataGrid (Qiang)
-BUG: Ticket#139 - TThemeManager::setBasePath() should understand an alias path (Qiang)
-BUG: Non-control components can now use expressions in their properties (Qiang)
-BUG: TControl.Visible did not make use of overriden getVisible() (Qiang)
-BUG: TWizard did not stop navigation upon a validation failure (Qiang)
-BUG: NumberFormat will now zero-fill numbers base on the pattern. (Wei)
-ENH: TButton, TImageButton and TLinkButton now implement IButtonControl interface (Qiang)
-ENH: TResponse::writeFile takes three additional parameters to allow sending memory data (Qiang)
-ENH: TButtonColumn can now be a column of image buttons (Qiang)
-ENH: TLiteral will display body content if Text is empty (Qiang)
-ENH: Format string in classes extending TDataGridColumn can now evaluate an expression (Qiang)
-ENH: Format string in classes extending TListControl can now evaluate an expression (Qiang)
-ENH: Added THttpResponse::reload() (Qiang)
-ENH: Custom visual effects can be added to client-side validators via ClientSide property in validators. (Wei)
-ENH: TJavascript::encode() allows raw javascript code when string begins with "javascript:" (Wei)
-ENH: Update TinyMCE to 2.0.5.1
-CHG: Rewrote client-side javascript validators, check your client-side validation behaviour (Wei)
-CHG: Updated the javascript Prototype library, a few utilties functions REMOVED, may break your existing javascript code. (Wei)
-CHG: Build javascript without compression, only comments are removed. (Wei)
-CHG: TDatePicker's date can be set using Date property, it value must be in same format as DateFormat, TimeStamp must be set as integer (wei)
-CHG: TSimpleDateFormatter::parse() now return an integer or null on parse error (Wei)
-CHG: TControl::createControls() is changed to public. (Qiang)
-CHG: Template comment tag is changed from <! ... !> to <!-- ... --!> (Qiang)
-NEW: TListControlValidator (Wei)
-NEW: TClientScript (Wei)
-
-
-Version 3.0RC2 April 16, 2006
-=============================
-BUG: Ticket#54 - recursive reverse() definition (Wei)
-BUG: Ticket#93 - ValidationGroup not working in TImageMap for js validator (Wei)
-BUG: Ticket#97 - Invalid return type value for TSimpleDateFormatter::parse (Wei)
-BUG: Ticket#118 - Variables that may not have been initialized (Qiang)
-BUG: Ticket#121 - OnClick don't fire with TImageButton and TRequiredFieldValidator (Wei)
-BUG: Ticket#129 - TRadioButtonList in TWizard step does not postback correctly (Qiang)
-CHG: Moved localize() into PradoBase (Qiang)
-CHG: List controls now use array keys as list item values even if the array is integer-indexed (Qiang)
-CHG: THttpUtility::htmlEncode and htmlDecode now do not deal with & (Qiang)
-CHG: Expressions appeared in a template are evaluated in PreRender stage (Qiang)
-CHG: The context of expressions appeared in a template is changed to the template control (Qiang)
-ENH: Optimized the representation and evaluation of template expressions (Qiang)
-ENH: Added Raw layout to TDataList (Qiang)
-ENH: Added TRepeater.DataKeys and TRepeater.DataKeyField (Qiang)
-
-Version 3.0RC1 April 5, 2006
-============================
-BUG: Ticket#85 - Undefined TDataGrid::setSelectedIndex (Qiang)
-BUG: Ticket#87 - Typo in IDbConnection (Qiang)
-BUG: Ticket#88 - Unclosed HTML tag in TDatePicker and TColorPicker (Qiang)
-BUG: Ticket#89 - TInlineFrame::ScrollBars wrong behaviour expected (Qiang)
-BUG: Ticket#95 - Typo in TTemplateControl::registerContentPlaceHolder (Qiang)
-BUG: Ticket#103 - Typo in TStyle::setVerticalAlign (Qiang)
-BUG: Ticket#107 - ListControls not respect parent disabling (Qiang)
-BUG: SF#1432624 - Incorrect documentation about caching expiry (Qiang)
-BUG: SF#1446846 - Typo in THead (Qiang)
-BUG: THttpSession fails when user storage module is used (Qiang)
-CHG: TTextHighlighter.EnableCopyCode defaults to false (Qiang)
-CHG: Reorganized quickstart tutorial demo, added new sections (Qiang)
-CHG: Reorganized folders under framework (Qiang)
-CHG: Modified THtmlArea default toolbar and size. (Qiang)
-CHG: Pagers in TDataGrid are now enclosed within panels (Qiang)
-ENH: Ticket#92 - Support for user exception message file (Qiang)
-ENH: Ticket#106 - Support for validation on THiddenField (Qiang)
-ENH: Ticket#110 - Support for TVarDump with syntax highlight (Qiang)
-ENH: TDataFieldAccessor can access public class variables (Qiang)
-ENH: TPhpErrorException now shows the actual error lines (Qiang)
-ENH: Refactored cache classes with support for cache dependency (Qiang)
-NEW: TStack component (Qiang)
-NEW: TImageMap control (Qiang)
-NEW: TWizard control (Qiang)
-NEW: TVarDumper and PradoBase::varDump() (Qiang)
-NEW: TComponentReflection (Qiang)
-NEW: TParameterModule (Qiang)
-NEW: TPropelLogRoute (Jason)
-
-Version 3.0b March 6, 2006
-==========================
-BUG: fixed many
-CHG: event names must be prefixed with 'On' (Qiang)
-CHG: values of properties whose name ends with 'Template' are parsed directly by template parser (Qiang)
-ENH: template parser reports exact error location (Qiang)
-ENH: cookie HMAC check (Qiang)
-NEW: TInlineFrame (Jason)
-NEW: TAPCCache (Alban)
-NEW: TColorPicker, TDatePicker, TRatingList, TAdodbProvider, TCreoleProvider (Wei)
-NEW: TMultiView, TView, TControlAdapter, TWebControlAdapter, TPagedList, TAttributeCollection (Qiang)
-
-Version 3.0a January 18, 2006
-=============================
-Starting, main feaures ready (Qiang)
+Version 3.1.0 To be released
+============================
+BUG: Ticket#188 - Postback js caused controls not inheritable (Qiang)
+ENH: Ticket#180, #222 - Prado js files are not rendered at the beginning of the form (Qiang)
+ENH: Ticket#99 - TXmlTransform control (Knut)
+ENH: Ticket#117 - added support to configure subproperties in a group. (Qiang)
+NEW: TOutputCache (Qiang)
+NEW: TQueue (Qiang)
+NEW: TSessionPageStatePersister (Qiang)
+NEW: SQLMap (Wei)
+NEW: TFeedService, TRssFeedDocument (Knut, Qiang)
+
+Version 3.0.3 August 6, 2006
+============================
+BUG: Ticket#264 - Typos in some exception throw statements (Knut)
+BUG: Ticket#268 - THttpResponse.redirect() may fail for some browsers (Qiang)
+BUG: TDataGrid may complain getting ItemType on a non-object if the grid is not data-bound (Qiang)
+BUG: TCheckBox.Value should be converted to string (Qiang)
+ENH: Ticket#220 - TClientScripts method to import custom javascript files (Wei)
+ENH: Ticket#225 - TRadioButton::getRadioButtonsInGroup() added (Wei)
+ENH: Ticket#223 - Use TRequiredFieldValidator for TRadioButtons with GroupName property (Wei)
+ENH: Ticket#277 - Added TControl.CustomData property (Qiang)
+NEW: Added TStyleSheet (Wei)
+
+Version 3.0.2 July 2, 2006
+==========================
+BUG: Ticket#182 - List and validator controls cause problem in child classes (Qiang)
+BUG: Ticket#191 - Duplicated postbacks occur when using TButton with validators (Qiang)
+BUG: Ticket#207 - Validators ClientSide.OnError triggered twice (Wei)
+BUG: Ticket#213 - PRADO Requirements Checker charset error (Qiang)
+BUG: Ticket#227 - Enabled property doesn't works with THtmlArea (Wei)
+BUG: Ticket#234 - Postback target could be out of date (Qiang)
+BUG: Ticket#239 - Ondeactivate handler for the first View of MultiView is always fired (Qiang)
+BUG: Ticket#244 - redirect() needs absolute URL (Qiang)
+BUG: Ticket#245 - getIsSecureConnection() is not working correctly (Qiang)
+BUG: Ticket#246 - TDatePicker wrong popup position in scrolled div (Wei)
+BUG: Ticket#260 - Wrong value of a configuration option in setUseTransparentSessionID (Qiang)
+CHG: ensureChildControls() is now invoked in TControl::initRecursive (Qiang)
+CHG: Postback enabled control will always disable default client-side browser action. (Qiang)
+CHG: CSS and JS files in a theme are now included in page in alphabetic order (Qiang)
+ENH: Ticket#206 - Added OnValidate, OnError, OnSuccess events to validators (Qiang)
+ENH: Ticket#230 - Added TDataList.EmptyTemplate property (Qiang)
+ENH: Ticket#231 - Added TButton.ButtonType property to allow reset button (Qiang)
+ENH: Ticket#232 - Allow <%# %> and <%= %> embedded within property values (Qiang)
+ENH: Ticket#256 - Datagrid columns can now be accessed via IDs (Qiang)
+ENH: Ticket#257 - OnSelectedIndexChanged event of TDataList and TDataGrid now passes the original command parameter (Qiang)
+ENH: Ticket#262 - Added TCheckBox.Value property (Qiang)
+ENH: TRepeater, TDataList and TDataGrid will store data indices in DataKeys if DataKeyField is not set. (Qiang)
+ENH: Added TPageService.BasePageClass property (Qiang)
+ENH: Added TDataGrid.EmptyTemplate property (Qiang)
+ENH: Added paging feature to all TDataBoundControl-derived controls (Qiang)
+ENH: ClientSide.ObserveChanges="false" to only revalidate client side validator when control changes (Wei)
+NEW: Added TPager (Qiang)
+NEW: Added Dreamweaver taglib extension (Stanislav, Qiang)
+NEW: Prado Command line script to create a new project, see framework/prado-cli.php (Wei)
+
+Version 3.0.1 June 4, 2006
+==========================
+BUG: Ticket#28 - OnClick does not work with Safari/KHTML (Wei)
+BUG: Ticket#37 - Changes of config files do not trigger cache update (Qiang)
+BUG: Ticket#44 - THtmlArea (tiny_mce) not working on some systems (Qiang)
+BUG: Ticket#162 - Missing currency sign in TNumberFormat if Value is 0 (Wei)
+BUG: Ticket#167 - TSecurityManager issues warning when trying to encrypt/decrypt strings (Qiang)
+BUG: Ticket#169 - Validation of subclass of THtmlArea/TDatePicker fails (Wei)
+BUG: Ticket#179 - CGI incompatibility causing clientscripts.php failure (Qiang)
+BUG: Ticket#181 - Unable to change Content-Type in response header if charset is not set (Qiang)
+BUG: Ticket#200 - onClick javascript event triggered twice on CheckBox label (Qiang)
+BUG: newly created controls during postbacks might get their initial states reset during loadStateRecursive. (Qiang)
+ENH: Ticket#150 - TDataGrid and TDataList now render table section tags (Qiang)
+ENH: Ticket#152 - constituent parts of TWizard are exposed (Qiang)
+ENH: Ticket#184 - added TUserManager.Users and Roles properties (Qiang)
+ENH: Ticket#197 - sanity check for datagrid header and footer (Qiang)
+ENH: added sanity check to calling event handlers (Qiang)
+ENH: added search for quickstart tutorials (Wei)
+ENH: added support to property tags for template owner control (Qiang)
+ENH: added Bulgarian requirement checker messages (StanProg)
+ENH: added TTheme.BaseUrl and TTheme.BasePath property (Qiang)
+ENH: added TListControl.SelectedValues property (Qiang)
+ENH: added TThemeManager.AvailableThemes property (Qiang)
+ENH: refactored TUserManager and TAuthManager so that they are easier to be extended (Qiang)
+ENH: template syntax now supports setting event handler via subproperties (Qiang)
+CHG: Ticket#151 - URL format is modified to handle empty GET values (Qiang)
+CHG: Ticket#153 - TAssetManager now ignores .svn directories (Qiang)
+CHG: Changed TControl::onBubbleEvent() to TControl::bubbleEvent() (Qiang)
+NEW: TTableHeaderRow, TTableFooterRow and table section support (Qiang)
+NEW: TCompositeControl (Qiang)
+NEW: TTextProcessor (Qiang)
+NEW: TMarkdown (Wei)
+NEW: Blog demo (Qiang)
+
+Version 3.0.0 May 1, 2006
+=========================
+BUG: Ticket#68 - 2 TButtons with THtmlArea causes second button to fail to function (Wei)
+BUG: Ticket#70 - Javascript for TDataTypeValidator added (Wei)
+BUG: Ticket#131 - TImageMap and TLinkButton continue to postback even client validator fails (Wei)
+BUG: Ticket#135 - TBrowserLogRoute reports wrong timings (Qiang)
+BUG: Ticket#137 - The JavasciptLogger does not work (Qiang)
+BUG: Ticket#138 - missing file in TDataGrid (Qiang)
+BUG: Ticket#139 - TThemeManager::setBasePath() should understand an alias path (Qiang)
+BUG: Non-control components can now use expressions in their properties (Qiang)
+BUG: TControl.Visible did not make use of overriden getVisible() (Qiang)
+BUG: TWizard did not stop navigation upon a validation failure (Qiang)
+BUG: NumberFormat will now zero-fill numbers base on the pattern. (Wei)
+ENH: TButton, TImageButton and TLinkButton now implement IButtonControl interface (Qiang)
+ENH: TResponse::writeFile takes three additional parameters to allow sending memory data (Qiang)
+ENH: TButtonColumn can now be a column of image buttons (Qiang)
+ENH: TLiteral will display body content if Text is empty (Qiang)
+ENH: Format string in classes extending TDataGridColumn can now evaluate an expression (Qiang)
+ENH: Format string in classes extending TListControl can now evaluate an expression (Qiang)
+ENH: Added THttpResponse::reload() (Qiang)
+ENH: Custom visual effects can be added to client-side validators via ClientSide property in validators. (Wei)
+ENH: TJavascript::encode() allows raw javascript code when string begins with "javascript:" (Wei)
+ENH: Update TinyMCE to 2.0.5.1
+CHG: Rewrote client-side javascript validators, check your client-side validation behaviour (Wei)
+CHG: Updated the javascript Prototype library, a few utilties functions REMOVED, may break your existing javascript code. (Wei)
+CHG: Build javascript without compression, only comments are removed. (Wei)
+CHG: TDatePicker's date can be set using Date property, it value must be in same format as DateFormat, TimeStamp must be set as integer (wei)
+CHG: TSimpleDateFormatter::parse() now return an integer or null on parse error (Wei)
+CHG: TControl::createControls() is changed to public. (Qiang)
+CHG: Template comment tag is changed from <! ... !> to <!-- ... --!> (Qiang)
+NEW: TListControlValidator (Wei)
+NEW: TClientScript (Wei)
+
+
+Version 3.0RC2 April 16, 2006
+=============================
+BUG: Ticket#54 - recursive reverse() definition (Wei)
+BUG: Ticket#93 - ValidationGroup not working in TImageMap for js validator (Wei)
+BUG: Ticket#97 - Invalid return type value for TSimpleDateFormatter::parse (Wei)
+BUG: Ticket#118 - Variables that may not have been initialized (Qiang)
+BUG: Ticket#121 - OnClick don't fire with TImageButton and TRequiredFieldValidator (Wei)
+BUG: Ticket#129 - TRadioButtonList in TWizard step does not postback correctly (Qiang)
+CHG: Moved localize() into PradoBase (Qiang)
+CHG: List controls now use array keys as list item values even if the array is integer-indexed (Qiang)
+CHG: THttpUtility::htmlEncode and htmlDecode now do not deal with & (Qiang)
+CHG: Expressions appeared in a template are evaluated in PreRender stage (Qiang)
+CHG: The context of expressions appeared in a template is changed to the template control (Qiang)
+ENH: Optimized the representation and evaluation of template expressions (Qiang)
+ENH: Added Raw layout to TDataList (Qiang)
+ENH: Added TRepeater.DataKeys and TRepeater.DataKeyField (Qiang)
+
+Version 3.0RC1 April 5, 2006
+============================
+BUG: Ticket#85 - Undefined TDataGrid::setSelectedIndex (Qiang)
+BUG: Ticket#87 - Typo in IDbConnection (Qiang)
+BUG: Ticket#88 - Unclosed HTML tag in TDatePicker and TColorPicker (Qiang)
+BUG: Ticket#89 - TInlineFrame::ScrollBars wrong behaviour expected (Qiang)
+BUG: Ticket#95 - Typo in TTemplateControl::registerContentPlaceHolder (Qiang)
+BUG: Ticket#103 - Typo in TStyle::setVerticalAlign (Qiang)
+BUG: Ticket#107 - ListControls not respect parent disabling (Qiang)
+BUG: SF#1432624 - Incorrect documentation about caching expiry (Qiang)
+BUG: SF#1446846 - Typo in THead (Qiang)
+BUG: THttpSession fails when user storage module is used (Qiang)
+CHG: TTextHighlighter.EnableCopyCode defaults to false (Qiang)
+CHG: Reorganized quickstart tutorial demo, added new sections (Qiang)
+CHG: Reorganized folders under framework (Qiang)
+CHG: Modified THtmlArea default toolbar and size. (Qiang)
+CHG: Pagers in TDataGrid are now enclosed within panels (Qiang)
+ENH: Ticket#92 - Support for user exception message file (Qiang)
+ENH: Ticket#106 - Support for validation on THiddenField (Qiang)
+ENH: Ticket#110 - Support for TVarDump with syntax highlight (Qiang)
+ENH: TDataFieldAccessor can access public class variables (Qiang)
+ENH: TPhpErrorException now shows the actual error lines (Qiang)
+ENH: Refactored cache classes with support for cache dependency (Qiang)
+NEW: TStack component (Qiang)
+NEW: TImageMap control (Qiang)
+NEW: TWizard control (Qiang)
+NEW: TVarDumper and PradoBase::varDump() (Qiang)
+NEW: TComponentReflection (Qiang)
+NEW: TParameterModule (Qiang)
+NEW: TPropelLogRoute (Jason)
+
+Version 3.0b March 6, 2006
+==========================
+BUG: fixed many
+CHG: event names must be prefixed with 'On' (Qiang)
+CHG: values of properties whose name ends with 'Template' are parsed directly by template parser (Qiang)
+ENH: template parser reports exact error location (Qiang)
+ENH: cookie HMAC check (Qiang)
+NEW: TInlineFrame (Jason)
+NEW: TAPCCache (Alban)
+NEW: TColorPicker, TDatePicker, TRatingList, TAdodbProvider, TCreoleProvider (Wei)
+NEW: TMultiView, TView, TControlAdapter, TWebControlAdapter, TPagedList, TAttributeCollection (Qiang)
+
+Version 3.0a January 18, 2006
+=============================
+Starting, main feaures ready (Qiang)
diff --git a/buildscripts/texbuilder/Page2Tex.php b/buildscripts/texbuilder/Page2Tex.php
new file mode 100644
index 00000000..c8cad6c9
--- /dev/null
+++ b/buildscripts/texbuilder/Page2Tex.php
@@ -0,0 +1,286 @@
+<?php
+
+class Page2Tex
+{
+ private $_current_page;
+ private static $header_count = 0;
+ private $_base;
+ private $_dir;
+
+ private $_verb_find = array('\$','\%', '\{', '\}', "\t",'``');
+ private $_verb_replace = array('$', '%', '{','}', " ",'"');
+
+ function __construct($base, $dir, $current='')
+ {
+ $this->_base = $base;
+ $this->_current_page = $current;
+ $this->_dir = $dir;
+ }
+
+ function setCurrentPage($current)
+ {
+ $this->_current_page = $current;
+ }
+
+ function escape_verbatim($matches)
+ {
+ return "\begin{verbatim}".str_replace($this->_verb_find, $this->_verb_replace, $matches[1])."\end{verbatim}\n";
+ }
+
+ function escape_verb($matches)
+ {
+ $text = str_replace($this->_verb_find, $this->_verb_replace, $matches[1]);
+ return '\verb<'.$text.'<';
+ }
+
+ function include_image($matches)
+ {
+
+ $current_path = $this->_current_page;
+
+ $image = dirname($current_path).'/'.trim($matches[1]);
+
+ $file = realpath($image);
+ $info = getimagesize($file);
+ switch($info[2])
+ {
+ case 1:
+ $im = imagecreatefromgif($file);
+ break;
+ case 2: $im = imagecreatefromjpeg($file); break;
+ case 3: $im = imagecreatefrompng($file); break;
+ }
+ $base = $this->_base;
+
+ if(isset($im))
+ {
+ $prefix = strtolower(str_replace(realpath($base), '', $file));
+ $filename = preg_replace('/\\\|\//', '_', substr($prefix,1));
+ $filename = substr($filename, 0, strrpos($filename,'.')).'.png';
+ $newfile = $this->_dir.'/'.$filename;
+ imagepng($im,$newfile);
+ imagedestroy($im);
+
+ return $this->include_figure($info, $filename);
+ }
+ }
+
+ function include_figure($info, $filename)
+ {
+ $width = sprintf('%0.2f', $info[0]/(135/2.54));
+ return '
+ \begin{figure}[!ht]
+ \centering
+ \includegraphics[width='.$width.'cm]{'.$filename.'}
+ \label{fig:'.$filename.'}
+ \end{figure}
+ ';
+ }
+
+ function anchor($matches)
+ {
+ $page = $this->get_current_path();
+ return '\hypertarget{'.$page.'/'.strtolower($matches[1]).'}{}';
+ }
+
+ function texttt($matches)
+ {
+ return '\texttt{'.str_replace(array('#','_'),array('\#','\_'), $matches[1]).'}';
+ }
+
+ function get_current_path()
+ {
+ $current_path = $this->_current_page;
+ $base = $this->_base;
+ $page = strtolower(substr(str_replace($base, '', $current_path),1));
+ return $page;
+ }
+
+ function make_link($matches)
+ {
+ if(is_int(strpos($matches[1], '#')))
+ {
+ if(strpos($matches[1],'?') ===false)
+ {
+ $target = $this->get_current_path().'/'.substr($matches[1],1);
+ return '\hyperlink{'.$target.'}{'.$matches[2].'}';
+ }
+ else
+ {
+ $page = strtolower(str_replace('?page=', '', $matches[1]));
+ $page = str_replace('.','/',$page);
+ $page = str_replace('#','.page/',$page);
+ return '\hyperlink{'.$page.'}{'.$matches[2].'}';
+ }
+ }
+ else if(is_int(strpos($matches[1],'?')))
+ {
+ $page = str_replace('?page=','',$matches[1]);
+ return '\hyperlink{'.$page.'}{'.$matches[2].'}';
+ }
+ return '\href{'.$matches[1].'}{'.$matches[2].'}';
+ }
+
+ function parse_html($page,$html)
+ {
+
+
+ $html = preg_replace('/<\/?com:TContent[^>]*>/', '', $html);
+ $html = preg_replace('/<\/?p [^>]*>/', '', $html);
+ $html = preg_replace('/<\/?p>/', '', $html);
+
+ $html = preg_replace('/(\s+|\(+|\[+)"/', '$1``', $html);
+
+ //escape { and }
+ $html = preg_replace('/([^\s]+){([^}]*)}([^\s]+)/', '$1\\\{$2\\\}$3', $html);
+
+ $html = preg_replace_callback('/<img\s+src="?<%~([^"]*)%>"?[^>]*\/>/', array($this, 'include_image'), $html);
+
+ //escape %
+ $html = str_replace('%', '\%', $html);
+
+ //codes
+ $html = str_replace('$', '\$', $html);
+
+ $html = preg_replace_callback('/<com:TTextHighlighter[^>]*>((.|\n)*?)<\/com:TTextHighlighter>/', array($this,'escape_verbatim'), $html);
+// $html = preg_replace('/<\/com:TTextHighlighter>/', '`2`', $html);
+// $html = preg_replace_callback('/(`1`)([^`]*)(`2`)/m', array($this,'escape_verbatim'), $html);
+ $html = preg_replace_callback('/(<div class="source">)((.|\n)*?)(<\/div>)/', array($this,'escape_verbatim'), $html);
+ $html = preg_replace_callback('/(<pre>)([^<]*)(<\/pre>)/', array($this,'escape_verbatim'), $html);
+
+ //<code>
+ $html = preg_replace_callback('/<code>([^<]*)<\/code>/', array($this,'escape_verb'), $html);
+
+ //runbar
+ $html = preg_replace('/<com:RunBar\s+PagePath="([^"]*)"\s+\/>/',
+ '\href{http://www.pradosoft.com/demos/quickstart/index.php?page=$1}{$1 Demo}', $html);
+
+ //DocLink
+ $html = preg_replace('/<com:DocLink\s+ClassPath="([^"]*)[.]([^.]*)"\s+\/>/',
+ '\href{http://www.pradosoft.com/docs/manual/$1/$2.html}{$1.$2 API Reference}', $html);
+
+ //text modifiers
+ $html = preg_replace('/<b[^>]*>([^<]*)<\/b>/', '\textbf{$1}', $html);
+ $html = preg_replace('/<i[^>]*>([^<]*)<\/i>/', '\emph{$1}', $html);
+ $html = preg_replace_callback('/<tt>([^<]*)<\/tt>/', array($this,'texttt'), $html);
+
+ //links
+ $html = preg_replace_callback('/<a[^>]+href="([^"]*)"[^>]*>([^<]*)<\/a>/',
+ array($this,'make_link'), $html);
+ //anchor
+ $html = preg_replace_callback('/<a[^>]+name="([^"]*)"[^>]*><\/a>/', array($this,'anchor'), $html);
+
+ //description <dl>
+ $html = preg_replace('/<dt>([^<]*)<\/dt>/', '\item[$1]', $html);
+ $html = preg_replace('/<\/?dd>/', '', $html);
+ $html = preg_replace('/<dl>/', '\begin{description}', $html);
+ $html = preg_replace('/<\/dl>/', '\end{description}', $html);
+
+ //item lists
+ $html = preg_replace('/<ul[^>]*>/', '\begin{itemize}', $html);
+ $html = preg_replace('/<\/ul>/', '\end{itemize}', $html);
+ $html = preg_replace('/<ol[^>]*>/', '\begin{enumerate}', $html);
+ $html = preg_replace('/<\/ol>/', '\end{enumerate}', $html);
+ $html = preg_replace('/<li[^>]*>/', '\item ', $html);
+ $html = preg_replace('/<\/li>/', '', $html);
+
+ //headings
+ $html = preg_replace('/<h1(\s+id="[^"]+")?>([^<]+)<\/h1>/', '\section{$2}', $html);
+ $html = preg_replace('/<h2(\s+id="[^"]+")?>([^<]+)<\/h2>/', '\subsection{$2}', $html);
+ $html = preg_replace('/<h3(\s+id="[^"]+")?>([^<]+)<\/h3>/', '\subsubsection{$2}', $html);
+
+ //div box
+ $html = preg_replace_callback('/<div class="[tipnofe]*?">((.|\n)*?)<\/div>/',
+ array($this, 'mbox'), $html);
+
+ //tabular
+ $html = preg_replace_callback('/<!--\s*tabular:([^-]*)-->\s*<table[^>]*>((.|\n)*?)<\/table>/',
+ array($this, 'tabular'), $html);
+
+ $html = html_entity_decode($html);
+
+ return $html;
+ }
+
+ function tabular($matches)
+ {
+ $options = array();
+ foreach(explode(',', $matches[1]) as $string)
+ {
+ $sub = explode('=', trim($string));
+ $options[trim($sub[0])] = trim($sub[1]);
+ }
+
+ $widths = explode(' ',preg_replace('/\(|\)/', '', $options['width']));
+ $this->_tabular_widths = $widths;
+
+ $this->_tabular_total = count($widths);
+ $this->_tabular_col = 0;
+
+ $begin = "\begin{table}[!hpt]\centering \n \begin{tabular}{".$options['align']."}\\hline";
+ $end = "\end{tabular} \n \end{table}\n";
+ $table = preg_replace('/<\/tr>/', '\\\\\\\\ \hline', $matches[2]);
+ $table = preg_replace('/<tr>/', '', $table);
+ $table = preg_replace('/<th>([^<]+)<\/th>/', '\textbf{$1} &', $table);
+ $table = preg_replace_callback('/<td>((.|\n)*?)<\/td>/', array($this, 'table_column'), $table);
+ $table = preg_replace('/<br \/>/', ' \\\\\\\\', $table);
+
+ $table = preg_replace('/&\s*\\\\\\\\/', '\\\\\\\\', $table);
+ return $begin.$table.$end;
+ }
+
+ function table_column($matches)
+ {
+ $width = $this->_tabular_widths[$this->_tabular_col];
+ if($this->_tabular_col >= $this->_tabular_total-1)
+ $this->_tabular_col = 0;
+ else
+ $this->_tabular_col++;
+ return '\begin{minipage}{'.$width.'\textwidth}\vspace{3mm}'.
+ $matches[1].'\vspace{3mm}\end{minipage} & ';
+ }
+
+ function mbox($matches)
+ {
+ return "\n\begin{mybox}\n".$matches[1]."\n\end{mybox}\n";
+ }
+
+ function get_chapter_label($chapter)
+ {
+ return '\hypertarget{'.str_replace(' ', '', $chapter).'}{}';
+ }
+
+ function get_section_label($section)
+ {
+ $section = str_replace('.page', '', $section);
+ return '\hypertarget{'.str_replace('/', '.', $section).'}{}';
+ }
+
+
+ function set_header_id($content, $count)
+ {
+ self::$header_count = $count*100;
+ $content = preg_replace_callback('/<h1>/', array($this,"h1"), $content);
+ $content = preg_replace_callback('/<h2>/', array($this,"h2"), $content);
+ $content = preg_replace_callback('/<h3>/', array($this,"h3"), $content);
+ return $content;
+ }
+
+ function h1($matches)
+ {
+ return "<h1 id=\"".(++self::$header_count)."\">";
+ }
+
+ function h2($matches)
+ {
+ return "<h2 id=\"".(++self::$header_count)."\">";
+ }
+
+ function h3($matches)
+ {
+ return "<h3 id=\"".(++self::$header_count)."\">";
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/demos/blog/protected/Pages/SearchPost.php b/demos/blog/protected/Pages/SearchPost.php
index 53e8401c..a824d257 100644
--- a/demos/blog/protected/Pages/SearchPost.php
+++ b/demos/blog/protected/Pages/SearchPost.php
@@ -21,7 +21,7 @@ class SearchPost extends BlogPage
foreach($keywords as $keyword)
{
if(($keyword=$this->DataAccess->escapeString(trim($keyword)))!=='')
- $filter.=" AND content LIKE '%$keyword%'";
+ $filter.=" AND (content LIKE '%$keyword%' OR title LIKE '%$keyword%')";
}
return $filter;
}
diff --git a/demos/quickstart/protected/controls/TopicList.tpl b/demos/quickstart/protected/controls/TopicList.tpl
index f26b75a6..1302338d 100644
--- a/demos/quickstart/protected/controls/TopicList.tpl
+++ b/demos/quickstart/protected/controls/TopicList.tpl
@@ -62,7 +62,7 @@
</div>
<div class="topic">
-<div>Avanced Topics</div>
+<div>Advanced Topics</div>
<ul>
<li><a href="?page=Advanced.Collections">Collections</a></li>
<li><a href="?page=Advanced.Auth">Authentication and Authorization</a></li>
diff --git a/demos/quickstart/protected/pages/Advanced/Assets.page b/demos/quickstart/protected/pages/Advanced/Assets.page
index e79f4ecf..8c7980a6 100644
--- a/demos/quickstart/protected/pages/Advanced/Assets.page
+++ b/demos/quickstart/protected/pages/Advanced/Assets.page
@@ -36,7 +36,7 @@ Asset publishing is managed by the <tt>System.Web.TAssetManager</tt> module. By
<h2 id="5704">Performance</h2>
<p>
-PRADO uses caching techniques to ensure the efficiency of asset publishing. Publishing an asset essentially requires file copy operation, which is expensive. To save unnecessary file copy operations, <tt>System.Web.TAssetManager</tt> only publishes an asset when it has a newer file modification time than the published file. When an application runs under the <tt>Performance</tt> mode, such timestamp checkings are also omitted.
+PRADO uses caching techniques to ensure the efficiency of asset publishing. Publishing an asset essentially requires file copy operation, which is expensive. To save unnecessary file copy operations, <tt>System.Web.TAssetManager</tt> only publishes an asset when it has a newer file modification time than the published file. When an application runs under the <tt>Performance</tt> mode, such timestamp checking is also omitted.
</p>
<p>
ADVISORY: Do not overuse asset publishing. The asset concept is mainly used to help better reuse and redistribute component classes. Normally, you should not use asset publishing for resources that are not bound to any component in an application. For example, you should not use asset publishing for images that are mainly used as design elements (e.g. logos, background images, etc.) Let Web server to directly serve these images will help improve the performance of your application.
diff --git a/demos/quickstart/protected/pages/Advanced/Collections.page b/demos/quickstart/protected/pages/Advanced/Collections.page
index 7fc3443d..84883be4 100644
--- a/demos/quickstart/protected/pages/Advanced/Collections.page
+++ b/demos/quickstart/protected/pages/Advanced/Collections.page
@@ -2,7 +2,7 @@
<h1 id="5501">Collections</h1>
<p>
-Collection is a basic data structure in programming. In traditional PHP programming, array is used widely to represent collection data structure. A PHP array is a mix of cardinal-indxed array and hash table.
+Collection is a basic data structure in programming. In traditional PHP programming, array is used widely to represent collection data structure. A PHP array is a mix of cardinal-indexed array and hash table.
</p>
<p>
To enable object-oriented manipulation of collections, PRADO provides a set of powerful collection classes. Among them, the <tt>TList</tt> and <tt>TMap</tt> are the most fundamental and usually serve as the base classes for other collection classes. Since many PRADO components have properties that are of collection type, it is very important for developers to master the usage of PRADO collection classes.
diff --git a/demos/quickstart/protected/pages/Advanced/Error.page b/demos/quickstart/protected/pages/Advanced/Error.page
index 9d5e3037..a0765c10 100644
--- a/demos/quickstart/protected/pages/Advanced/Error.page
+++ b/demos/quickstart/protected/pages/Advanced/Error.page
@@ -7,7 +7,7 @@ PRADO provides a complete error handling and reporting framework based on the PH
<h2 id="6302">Exception Classes</h2>
<p>
-Errors occur in a PRADO application may be classified into three categories: those caused by PHP script parsing, those caused by wrong code (such as calling an undefined function, setting an unknown property), and those caused by improper use of the Web application by client users (such as attempting to access restricted pages). PRADO is unable to deal with the first category of errors because they cannot be caughted in PHP code. PRADO provides an exception hierarchy to deal with the second and third categories.
+Errors occur in a PRADO application may be classified into three categories: those caused by PHP script parsing, those caused by wrong code (such as calling an undefined function, setting an unknown property), and those caused by improper use of the Web application by client users (such as attempting to access restricted pages). PRADO is unable to deal with the first category of errors because they cannot be caught in PHP code. PRADO provides an exception hierarchy to deal with the second and third categories.
</p>
<p>
All errors in PRADO applications are represented as exceptions. The base class for all PRADO exceptions is <tt>TException</tt>. It provides the message internationalization functionality to all system exceptions. An error message may be translated into different languages according to the user browser's language preference.
@@ -21,7 +21,7 @@ Exceptions raised due to improper usage of the PRADO framework inherit from <tt>
<li><tt>TInvalidDataTypeException</tt> - data type is incorrect or unexpected.</li>
<li><tt>TInvalidDataFormatException</tt> - format of data is incorrect.</li>
<li><tt>TInvalidOperationException</tt> - invalid operation request.</li>
-<li><tt>TPhpErrorException</tt> - caughtable PHP errors, warnings, notices, etc.</li>
+<li><tt>TPhpErrorException</tt> - catchable PHP errors, warnings, notices, etc.</li>
<li><tt>TSecurityException</tt> - errors related with security.</li>
<li><tt>TIOException</tt> - IO operation error, such as file open failure.</li>
<li><tt>TDBException</tt> - errors related with database operations.</li>
diff --git a/demos/quickstart/protected/pages/Advanced/I18N.page b/demos/quickstart/protected/pages/Advanced/I18N.page
index 6c86a6c9..1330091f 100644
--- a/demos/quickstart/protected/pages/Advanced/I18N.page
+++ b/demos/quickstart/protected/pages/Advanced/I18N.page
@@ -18,7 +18,7 @@
<li> Dates, Times.</li>
<li> Numbers, Currency, Measurements.</li>
<li> Phone numbers.</li>
- <li> Honorifics and personal titles.</li>
+ <li> Honorific and personal titles.</li>
<li> Postal address.</li>
<li> Page layout.</li>
</ul>
@@ -26,7 +26,7 @@
<p>If possible all manner of text should be isolated and store in a persistence format. These text include, application error messages, hard coded strings in PHP files, emails, static HTML text, and text on form elements (e.g. buttons).</p>
<h2 id="6204">Configuration</h2>
-<p>To enable the localization features in Prado, you need to add a few configuration options in your <a href="?page=Configurations.AppConfig">application configuration</a>.
+<p>To enable the localization features in PRADO, you need to add a few configuration options in your <a href="?page=Configurations.AppConfig">application configuration</a>.
First you need to include the <tt>System.I18N.*</tt> namespace to your paths.
</p>
<com:TTextHighlighter Language="xml" CssClass="source">
@@ -98,7 +98,7 @@ Lastly, you can change the globalization settings on page by page basis using <a
&lt;%@ Application.Globalization.Culture="zh" %&gt;
</com:TTextHighlighter>
-<h2 id="6207">Localizing your Prado application</h2>
+<h2 id="6207">Localizing your PRADO application</h2>
There are two areas in your application that may need message or string localization, in PHP code and in the templates. To localize strings within PHP, use the <tt>localize</tt> function detailed below. To localize text in the template, use the <a href="#ttranslate">TTranslate</a> component.
<h2 id="6208">Using <tt>localize</tt> function to translate text within PHP</h2>
@@ -134,7 +134,7 @@ $message = Prado::localize("There are {num_users} users online.", array('num_use
<p>Where the second parameter in <tt>localize</tt> takes an associative array with the key as the substitution to find in the text and replaced it with the associated value.
The <tt>localize</tt> function does not solve the problem of localizing languages that have plural forms, the solution is to use <a href="#choice-format">TChoiceFormat</a>.</p>
-<p>The following sample demonstrates the basics of localization in Prado.</p>
+<p>The following sample demonstrates the basics of localization in PRADO.</p>
<com:RunBar PagePath="Advanced.Samples.I18N.Home" />
<h1 id="6202">I18N Components</h1>
@@ -148,9 +148,9 @@ To translate a message or string in the template, use <tt>TTranslate</tt>.</p>
&lt;com:TTranslate Text="Goodbye" /&gt;
</com:TTextHighlighter>
-<p><tt>TTranslate</tt> can also perform string substitution.
+<p><tt>TTranslate</tt> can also perform string substitution.
The <tt>Parameters</tt> property can be use to add name values pairs for substitution. Substrings in the translation enclosed with "{" and "}" are consider as the
- parameter names during substitution lookup. The following example will substitute the substring "{time}" with the value of the parameter attribute "<tt>Parameters.time=&lt;%= time() %&gt;</tt>".
+ parameter names during substitution lookup. The following example will substitute the substring "{time}" with the value of the parameter attribute "<tt>Parameters.time=&lt;%= time() %&gt;</tt>".
<com:TTextHighlighter Language="prado" CssClass="source">
&lt;com:TTranslate Parameters.time=&lt;%= time() %&gt; &gt;
The time is {time}.
@@ -183,17 +183,17 @@ The time is {time}.
<li><tt>mediumtime</tt></li>
<li><tt>shorttime</tt></li>
</ul>
-The predefined can be used in any combination. If using a combined predefined pattern,
-the first pattern must be the date, followed by a space, and lastly the time pattern.
-For example, full date pattern with short time pattern. The actual ordering of the
-date-time and the actual pattern will be determine automatically from locale data specified
+The predefined can be used in any combination. If using a combined predefined pattern,
+the first pattern must be the date, followed by a space, and lastly the time pattern.
+For example, full date pattern with short time pattern. The actual ordering of the
+date-time and the actual pattern will be determine automatically from locale data specified
by the <tt>Culture</tt> property.</p>
<com:TTextHighlighter Language="prado" CssClass="source">
&lt;com:TDateFormat Pattern="fulldate shorttime" /&gt;
</com:TTextHighlighter>
-<p>You can also specify a custom pattern using the following sub-patterns.
+<p>You can also specify a custom pattern using the following sub-patterns.
The date/time format is specified by means of a string time pattern. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following:
<com:TTextHighlighter Language="text" CssClass="source">
Symbol Meaning Presentation Example
@@ -222,22 +222,22 @@ The date/time format is specified by means of a string time pattern. In this pat
<p>The count of pattern letters determine the format.</p>
-<p>(Text): 4 letters uses full form, less than 4, use short or abbreviated form
+<p>(Text): 4 letters uses full form, less than 4, use short or abbreviated form
if it exists. (e.g., "EEEE" produces "Monday", "EEE" produces "Mon")</p>
<p>(Number): the minimum number of digits. Shorter numbers are zero-padded
- to this amount (e.g. if "m" produces "6", "mm" produces "06"). Year is
- handled specially; that is, if the count of 'y' is 2, the Year will be
- truncated to 2 digits. (e.g., if "yyyy" produces "1997", "yy" produces "97".)
+ to this amount (e.g. if "m" produces "6", "mm" produces "06"). Year is
+ handled specially; that is, if the count of 'y' is 2, the Year will be
+ truncated to 2 digits. (e.g., if "yyyy" produces "1997", "yy" produces "97".)
Unlike other fields, fractional seconds are padded on the right with zero.</p>
-<p>(Text and Number): 3 or over, use text, otherwise use number. (e.g.,
-"M" produces "1", "MM" produces "01", "MMM" produces "Jan", and "MMMM"
+<p>(Text and Number): 3 or over, use text, otherwise use number. (e.g.,
+"M" produces "1", "MM" produces "01", "MMM" produces "Jan", and "MMMM"
produces "January".)</p>
-<p>Any characters in the pattern that are not in the ranges of ['a'..'z']
-and ['A'..'Z'] will be treated as quoted text. For instance, characters
-like ':', '.', ' ', and '@' will appear in the resulting time text
+<p>Any characters in the pattern that are not in the ranges of ['a'..'z']
+and ['A'..'Z'] will be treated as quoted text. For instance, characters
+like ':', '.', ' ', and '@' will appear in the resulting time text
even they are not embraced within single quotes.</p>
<p>Examples using the US locale:
@@ -259,7 +259,7 @@ Format Pattern Result
<h2 id="6212">TNumberFormat</h2>
<p>PRADO's Internationalization framework provide localized currency formatting and number formatting. Please note that the <tt>TNumberFormat</tt> component provides formatting only, it does not perform current conversion or exchange.</p>
-<p>Numbers can be formatted as currency, percentage, decimal or scientific
+<p>Numbers can be formatted as currency, percentage, decimal or scientific
numbers by specifying the <tt>Type</tt> attribute. The valid types are:
<ul>
<li><tt>currency</tt></li>
@@ -268,7 +268,7 @@ numbers by specifying the <tt>Type</tt> attribute. The valid types are:
<li><tt>scientific</tt></li>
</ul>
</p>
-
+
<com:TTextHighlighter Language="prado" CssClass="source">
&lt;com:TNumberFormat Type="currency" Value="100" /&gt;
</com:TTextHighlighter>
@@ -283,13 +283,13 @@ then also from the <tt>de_DE</tt> locale. This may lead to some confusion becaus
people from US uses the "," (comma) as thousand separator. Therefore a <tt>Currency</tt>
attribute is available, so that the output from the following example results in $100.00
<com:TTextHighlighter Language="prado" CssClass="source">
-&lt;com:TNumberFormat Type="currency"
+&lt;com:TNumberFormat Type="currency"
Culture="en_US" Currency="EUR" Value="100" /&gt;
</com:TTextHighlighter>
</p>
-<p>The <tt>Pattern</tt> property determines the number of digits, thousand grouping
-positions, the number of decimal points and the decimal position. The actual characters that
+<p>The <tt>Pattern</tt> property determines the number of digits, thousand grouping
+positions, the number of decimal points and the decimal position. The actual characters that
are used to represent the decimal points and thousand points are culture specific
and will change automatically according to the <tt>Culture</tt> property. The valid
<tt>Pattern</tt> characters are:
@@ -299,7 +299,7 @@ and will change automatically according to the <tt>Culture</tt> property. The va
<li><tt>. (full stop)</tt> - the position of the decimal point (only 1 decimal point is allowed)</li>
<li><tt>, (comma)</tt> - thousand point separation (up to 2 commas are allowed)</li>
</ul>
-For example, consider the <tt>Value="1234567.12345"</tt> and
+For example, consider the <tt>Value="1234567.12345"</tt> and
with <tt>Culture="en_US"</tt> (which uses "," for thousand point separator and "." for decimal separators).
<com:TTextHighlighter Language="text" CssClass="source">
Pattern Output
diff --git a/demos/quickstart/protected/pages/Advanced/Logging.page b/demos/quickstart/protected/pages/Advanced/Logging.page
index 5270a00d..9c7ec15e 100644
--- a/demos/quickstart/protected/pages/Advanced/Logging.page
+++ b/demos/quickstart/protected/pages/Advanced/Logging.page
@@ -52,10 +52,10 @@ Messages can be filtered according to their log levels and categories. Each log
Log levels defined in <tt>System.Util.TLogger</tt> include : <tt>DEBUG</tt>, <tt>INFO</tt>, <tt>NOTICE</tt>, <tt>WARNING</tt>, <tt>ERROR</tt>, <tt>ALERT</tt>, <tt>FATAL</tt>. Messages can be filtered according log level criteria. For example, if a filter specifies <tt>WARNING</tt> and <tt>ERROR</tt> levels, then only those messages that are of <tt>WARNING</tt> and <tt>ERROR</tt> will be returned.
</p>
<p>
-Message categories are hierarchical. A category whose name is the prefix of another is said to be the ancestor category of the other category. For example, <tt>System.Web</tt> category is the ancestor of <tt>System.Web.UI</tt> and <tt>System.Web.UI.WebControls</tt> categories. Messages can be selectively retrieved using such hierarchical category filters. For example, if the category filter is <tt>System.Web</tt>, then all messages in the <tt>System.Web</tt> are returned. In addition, messages in the childd categories, such as <tt>System.Web.UI.WebControls</tt>, are also returned.
+Message categories are hierarchical. A category whose name is the prefix of another is said to be the ancestor category of the other category. For example, <tt>System.Web</tt> category is the ancestor of <tt>System.Web.UI</tt> and <tt>System.Web.UI.WebControls</tt> categories. Messages can be selectively retrieved using such hierarchical category filters. For example, if the category filter is <tt>System.Web</tt>, then all messages in the <tt>System.Web</tt> are returned. In addition, messages in the child categories, such as <tt>System.Web.UI.WebControls</tt>, are also returned.
</p>
<p>
-By convention, the messages logged in the core code of PRADO are categorized according to the namespace of the corresponding classes. For example, messsages logged in <tt>TPage</tt> will be of category <tt>System.Web.UI.TPage</tt>.
+By convention, the messages logged in the core code of PRADO are categorized according to the namespace of the corresponding classes. For example, messages logged in <tt>TPage</tt> will be of category <tt>System.Web.UI.TPage</tt>.
</p>
</com:TContent> \ No newline at end of file
diff --git a/demos/quickstart/protected/pages/Advanced/Scripts.page b/demos/quickstart/protected/pages/Advanced/Scripts.page
index 5921e865..8fa1e27e 100644
--- a/demos/quickstart/protected/pages/Advanced/Scripts.page
+++ b/demos/quickstart/protected/pages/Advanced/Scripts.page
@@ -5,46 +5,46 @@ Quick guide to somewhat advanced JavaScript tour of some OO features</a> by Serg
<h2 id="6502">Hey, I didn't know you could do that</h2>
<p>
- If you are a web developer and come from the same place I do, you have probably
- used quite a bit of Javascript in your web pages, mostly as UI glue.
+ If you are a web developer and come from the same place I do, you have probably
+ used quite a bit of Javascript in your web pages, mostly as UI glue.
</p>
<p>
Until recently, I knew that Javascript had more OO capabilities than I was employing,
- but I did not feel like I needed to use it. As the browsers started to support a more
- standardized featureset of Javascript and the DOM, it became viable to write more
- complex and functional code to run on the client. That helped giving birth to the
+ but I did not feel like I needed to use it. As the browsers started to support a more
+ standardized featureset of Javascript and the DOM, it became viable to write more
+ complex and functional code to run on the client. That helped giving birth to the
AJAX phenomena.
</p>
<p>
- As we all start to learn what it takes to write our cool, AJAXy applications, we begin
- to notice that the Javascript we used to know was really just the tip of the iceberg.
- We now see Javascript being used beyond simple UI chores like input validation and frivolous
- tasks. The client code now is far more advanced and layered, much like a real desktop
- application or a client-server thick client. We see class libraries, object models,
- hierarchies, patterns, and many other things we got used to seeing only in our server
+ As we all start to learn what it takes to write our cool, AJAX applications, we begin
+ to notice that the Javascript we used to know was really just the tip of the iceberg.
+ We now see Javascript being used beyond simple UI chores like input validation and frivolous
+ tasks. The client code now is far more advanced and layered, much like a real desktop
+ application or a client-server thick client. We see class libraries, object models,
+ hierarchies, patterns, and many other things we got used to seeing only in our server
side code.
</p>
<p>
- In many ways we can say that suddenly the bar was put much higher than before. It takes
- a heck lot more proficiency to write applications for the new Web and we need to improve
+ In many ways we can say that suddenly the bar was put much higher than before. It takes
+ a heck lot more proficiency to write applications for the new Web and we need to improve
our Javascript skills to get there.
- If you try to use many of the existing javascript libraries out there, like
- <a href="http://prototype.conio.net/">Prototype.js</a>,
- <a href="http://script.aculo.us/">Scriptaculous</a>,
- <a href="http://moofx.mad4milk.net/">moo.fx</a>,
- <a href="http://bennolan.com/behaviour/">Behaviour</a>,
- <a href="http://developer.yahoo.net/yui/">YUI</a>,
- etc you'll eventually find yourself reading the JS code. Maybe because you want
- to learn how they do it, or because you're curious, or more often because that's the
- only way to figure out how to use it, since documentation does not seem to be highly
- regarded with most of these libraries. Whatever the case may be, you'll face some
- kung-fu techniques that will be foreign and scary if you haven't seen anything like
+ If you try to use many of the existing javascript libraries out there, like
+ <a href="http://prototype.conio.net/">Prototype.js</a>,
+ <a href="http://script.aculo.us/">Scriptaculous</a>,
+ <a href="http://moofx.mad4milk.net/">moo.fx</a>,
+ <a href="http://bennolan.com/behaviour/">Behaviour</a>,
+ <a href="http://developer.yahoo.net/yui/">YUI</a>,
+ etc you'll eventually find yourself reading the JS code. Maybe because you want
+ to learn how they do it, or because you're curious, or more often because that's the
+ only way to figure out how to use it, since documentation does not seem to be highly
+ regarded with most of these libraries. Whatever the case may be, you'll face some
+ kung-fu techniques that will be foreign and scary if you haven't seen anything like
that before.
</p>
<p>
- The purpose of this article is precisely explaining the types of constructs that
+ The purpose of this article is precisely explaining the types of constructs that
many of us are not familiar with yet.
</p>
@@ -52,12 +52,12 @@ Quick guide to somewhat advanced JavaScript tour of some OO features</a> by Serg
<h2 id="6503">JSON (JavaScript Object Notation)</h2>
<p>
JavaScript Object Notation (<a href="http://www.json.org/">JSON</a>,) is one of the new
- buzzwords popping up around the AJAX theme. JSON, simply put, is a way of
- declaring an object in javascript. Let's see an example right away and note
+ buzzwords popping up around the AJAX theme. JSON, simply put, is a way of
+ declaring an object in Javascript. Let's see an example right away and note
how simple it is.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-var myPet = { color: 'black', leg_count: 4, communicate: function(repeatCount){
+var myPet = { color: 'black', leg_count: 4, communicate: function(repeatCount){
for(i=0;i&lt;repeatCount;i++) alert('Woof!');} };
</com:TTextHighlighter>
@@ -65,10 +65,10 @@ for(i=0;i&lt;repeatCount;i++) alert('Woof!');} };
Let's just add little bit of formatting so it looks more like how we usually find out there:
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-var myPet =
+var myPet =
{
- color: 'black',
- legCount: 4,
+ color: 'black',
+ legCount: 4,
communicate: function(repeatCount)
{
for(i=0;i&lt;repeatCount;i++)
@@ -77,14 +77,14 @@ var myPet =
};
</com:TTextHighlighter>
<p>
- Here we created a reference to an object with two properties (<tt>color</tt>
- and <tt>legCount</tt>) and a method (<tt>communicate</tt>.)
+ Here we created a reference to an object with two properties (<tt>color</tt>
+ and <tt>legCount</tt>) and a method (<tt>communicate</tt>.)
It's not hard to figure out that the object's properties and methods
- are defined as a comma delimited list. Each of the members is introduced by name, followed
- by a colon and then the definition. In the case of the properties it is easy, just the value
- of the property. The methods are created by assigning an anonymous function, which we will
+ are defined as a comma delimited list. Each of the members is introduced by name, followed
+ by a colon and then the definition. In the case of the properties it is easy, just the value
+ of the property. The methods are created by assigning an anonymous function, which we will
explain better down the line.
- After the object is created and assigned to the variable <tt>myPet</tt>,
+ After the object is created and assigned to the variable <tt>myPet</tt>,
we can use it like this:
</p>
@@ -95,13 +95,13 @@ alert('my pet has ' + myPet.legCount + ' legs');
myPet.communicate(3);
</com:TTextHighlighter>
<p>
- You'll see JSON used pretty much everywhere in JS these days, as arguments to functions,
+ You'll see JSON used pretty much everywhere in JS these days, as arguments to functions,
as return values, as server responses (in strings,) etc.
</p>
<h2 id="6504">What do you mean? A function is an object too?</h2>
<p>
- This might be unusual to developers that never thought about that, but in JS a function is
+ This might be unusual to developers that never thought about that, but in JS a function is
also an object. You can pass a function around as an argument to another function just like
you can pass a string, for example. This is extensively used and very handy.
</p>
@@ -110,7 +110,7 @@ myPet.communicate(3);
Take a look at this example. We will pass functions to another function that will use them.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-var myDog =
+var myDog =
{
bark: function()
{
@@ -118,7 +118,7 @@ var myDog =
}
};
-var myCat =
+var myCat =
{
meow: function()
{
@@ -138,9 +138,9 @@ annoyThePet(myDog.bark);
annoyThePet(myCat.meow);
</com:TTextHighlighter>
<p>
- Note that we pass myDog.bark and myCat.meow without appending parenthesis
- <tt>"()"</tt> to them. If we did that we would not be passing
- the function, rather we would be calling the method and passing the return value,
+ Note that we pass myDog.bark and myCat.meow without appending parenthesis
+ <tt>"()"</tt> to them. If we did that we would not be passing
+ the function, rather we would be calling the method and passing the return value,
<tt>undefined</tt> in both cases here.
</p>
@@ -162,7 +162,7 @@ var a = new Array();
var b = [];
</com:TTextHighlighter>
<p>
- As I'm sure you already know, you can access individual items in an array
+ As I'm sure you already know, you can access individual items in an array
by using the square brackets:
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
@@ -173,8 +173,8 @@ var v3 = a[2];
</com:TTextHighlighter>
<p>
- But you are not limited to numeric indices. You can access any member of a JS
- object by using its name, in a string. The following example creates an empty
+ But you are not limited to numeric indices. You can access any member of a JS
+ object by using its name, in a string. The following example creates an empty
object, and adds some members by name.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
@@ -187,7 +187,7 @@ obj['some_function'] = function(){ /* do something */};
The above code has identical effect as the following:
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-var obj =
+var obj =
{
member_1:'this is the member value',
flag_2: false,
@@ -196,7 +196,7 @@ var obj =
</com:TTextHighlighter>
<p>
- In many ways, the idea of objects and associative arrays (hashes) in JS are not
+ In many ways, the idea of objects and associative arrays (hashes) in JS are not
distiguishable. The following two lines do the same thing too.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
@@ -208,8 +208,8 @@ obj['some_function']();
<h2 id="6506">Enough about objects, may I have a class now?</h2>
<p>
- The great power of object oriented programming languages derive from the use
- of classes. I don't think I would have guessed how classes are defined in JS
+ The great power of object oriented programming languages derive from the use
+ of classes. I don't think I would have guessed how classes are defined in JS
using only my previous experience with other languages. Judge for yourself.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
@@ -225,27 +225,27 @@ var famousDog = new Pet('Santa\'s Little Helper', 15);
alert('This pet is called ' + famousDog.name);
</com:TTextHighlighter>
<p>
- Let's see how we add a method to our <tt>Pet</tt> class. We will be using the
- <tt>prototype</tt> property that all classes have. The <tt>prototype</tt>
- property is an object that contains all the members that any object of the class will have.
- Even the default JS classes, like <tt>String</tt>, <tt>Number</tt>,
- and <tt>Date</tt> have a <tt>prototype</tt> object that we
+ Let's see how we add a method to our <tt>Pet</tt> class. We will be using the
+ <tt>prototype</tt> property that all classes have. The <tt>prototype</tt>
+ property is an object that contains all the members that any object of the class will have.
+ Even the default JS classes, like <tt>String</tt>, <tt>Number</tt>,
+ and <tt>Date</tt> have a <tt>prototype</tt> object that we
can add methods and properties to and make any object of that class automatically gain this new member.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
Pet.prototype.communicate = function()
-{
+{
alert('I do not know what I should say, but my name is ' + this.name);
};
</com:TTextHighlighter>
<p>
- That's when a library like <a href="http://www.sergiopereira.com/articles/prototype.js.html">prototype.js</a> comes in
+ That's when a library like <a href="http://www.sergiopereira.com/articles/prototype.js.html">prototype.js</a> comes in
handy. If we are using prototype.js, we can make our code look cleaner (at least in my opinion.)
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
var Pet = Class.create();
-Pet.prototype =
+Pet.prototype =
{
//our 'constructor'
initialize: function(petName, age)
@@ -258,7 +258,7 @@ Pet.prototype =
{
alert('I do not know what I should say, but my name is ' + this.name);
}
-};
+};
</com:TTextHighlighter>
<h2 id="6507">Functions as arguments, an interesting pattern</h2>
@@ -275,15 +275,15 @@ myArray.each( function(item, index)
</com:TTextHighlighter>
<p>
- Whoa! Let's explain what is going on here before you decide I've gone too
+ Whoa! Let's explain what is going on here before you decide I've gone too
far and navigate to a better article than this one.
</p>
<p>
- First of all, in the above example we are using the prototype.js library, which
- adds the each function to the Array class. The each function accepts one
- argument that is a function object. This function, in turn, will be called once
- for each item in the array, passing two arguments when called, the item and the index
- for the current item. Let's call this function our iterator function.
+ First of all, in the above example we are using the prototype.js library, which
+ adds the each function to the Array class. The each function accepts one
+ argument that is a function object. This function, in turn, will be called once
+ for each item in the array, passing two arguments when called, the item and the index
+ for the current item. Let's call this function our iterator function.
We could have also written the code like this.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
@@ -296,24 +296,24 @@ var myArray = ['first', 'second', 'third'];
myArray.each( myIterator );
</com:TTextHighlighter>
<p>
- But then we would not be doing like all the cool kids in school, right?
- More seriously, though, this last format is simpler to understand but causes
- us to jump around in the code looking for the myIterator function. It's nice
- to have the logic of the iterator function right there in the same place
- it's called. Also, in this case, we will not need the iterator function anywhere
- else in our code, so we can transform it into an anonymous function without penalty.
+ But then we would not be doing like all the cool kids in school, right?
+ More seriously, though, this last format is simpler to understand but causes
+ us to jump around in the code looking for the myIterator function. It's nice
+ to have the logic of the iterator function right there in the same place
+ it's called. Also, in this case, we will not need the iterator function anywhere
+ else in our code, so we can transform it into an anonymous function without penalty.
</p>
<h2 id="6508">This is <tt>this</tt> but sometimes <tt>this</tt> is also that</h2>
<p>
- One of the most common troubles we have with JS when we start writing our code
- it the use of the <tt>this</tt> keyword. It could be a real
+ One of the most common troubles we have with JS when we start writing our code
+ it the use of the <tt>this</tt> keyword. It could be a real
tripwire.
</p>
<p>
- As we mentioned before, a function is also an object in JS, and sometimes we
- do not notice that we are passing a function around.
+ As we mentioned before, a function is also an object in JS, and sometimes we
+ do not notice that we are passing a function around.
</p>
<p>
Take this code snippet as an example.
@@ -331,15 +331,15 @@ myButton2.onclick = buttonClicked;
</com:TTextHighlighter>
<p>
Because the buttonClicked function is defined outside any object we may tend to
- think the <tt>this</tt> keyword will contain a reference to
- the <tt>window</tt> or <tt>document</tt>
+ think the <tt>this</tt> keyword will contain a reference to
+ the <tt>window</tt> or <tt>document</tt>
object (assuming this code is in the middle of an HTML page viewed in a browser.)
</p>
<p>
But when we run this code we see that it works as intended and displays the <tt>id</tt> of
- the clicked button. What happened here is that we made the onclick method of each button contain the
- <tt>buttonClicked</tt> object reference, replacing whatever was there before. Now
+ the clicked button. What happened here is that we made the onclick method of each button contain the
+ <tt>buttonClicked</tt> object reference, replacing whatever was there before. Now
whenever the button is clicked, the browser will execute something similar to the following line.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
@@ -347,11 +347,11 @@ myButton.onclick();
</com:TTextHighlighter>
<p>
- That isn't so confusing afterall, is it? But see what happens you start having other
+ That isn't so confusing afterall, is it? But see what happens you start having other
objects to deal with and you want to act on these object upon events like the button's click.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-var myHelper =
+var myHelper =
{
formFields: [ ],
emptyAllFields: function()
@@ -377,18 +377,18 @@ var clearButton = document.getElementById('btnClear');
clearButton.onclick = myHelper.emptyAllFields;
</com:TTextHighlighter>
<p>
- So you think, nice, now I can click the Clear button on my page and those three text boxes
- will be emptied. Then you try clicking the button only to get a runtime error. The error
- will be related to (guess what?) the <tt>this</tt> keyword.
- The problem is that <tt>this.formFields</tt> is not defined if
- <tt>this</tt> containz a referece to the button, which is
+ So you think, nice, now I can click the Clear button on my page and those three text boxes
+ will be emptied. Then you try clicking the button only to get a runtime error. The error
+ will be related to (guess what?) the <tt>this</tt> keyword.
+ The problem is that <tt>this.formFields</tt> is not defined if
+ <tt>this</tt> contains a referece to the button, which is
precisely what's happening. One quick solution would be to rewrite our last line of code.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
clearButton.onclick = function()
-{
- myHelper.emptyAllFields();
+{
+ myHelper.emptyAllFields();
};
</com:TTextHighlighter>
<p>
diff --git a/demos/quickstart/protected/pages/Advanced/Scripts1.page b/demos/quickstart/protected/pages/Advanced/Scripts1.page
index f11a2f9d..ef0b6317 100644
--- a/demos/quickstart/protected/pages/Advanced/Scripts1.page
+++ b/demos/quickstart/protected/pages/Advanced/Scripts1.page
@@ -6,8 +6,8 @@ Developer Notes for prototype.js</a> by Sergio Pereira.
<h2 id="6603">What is that?</h2>
<p>
-In case you haven't already used it, <a href="http://prototype.conio.net">prototype.js</a> is a
- JavaScript library written by <a href="http://www.conio.net">Sam Stephenson</a>.
+In case you haven't already used it, <a href="http://prototype.conio.net">prototype.js</a> is a
+ JavaScript library written by <a href="http://www.conio.net">Sam Stephenson</a>.
This amazingly well thought and well written piece of <b>standards-compliant</b> code takes a lot of
the burden associated with creating rich, highly interactive web pages that characterize the Web 2.0 off your back.
</p>
@@ -20,7 +20,7 @@ In case you haven't already used it, <a href="http://prototype.conio.net">protot
</p>
<p>
As you read the examples and the reference, developers familiar with the Ruby
- programming language will notice an intentional similarity between Ruby's
+ programming language will notice an intentional similarity between Ruby's
built-in classes and many of the extensions implemented by this library.
</p>
@@ -32,7 +32,7 @@ In case you haven't already used it, <a href="http://prototype.conio.net">protot
</p>
<p>
- Unlike the DOM function, though, this one goes further. You can pass more than one id and
+ Unlike the DOM function, though, this one goes further. You can pass more than one id and
<tt>$()</tt> will return an <tt>Array</tt> object with
all the requested elements. The example below should illustrate this.
</p>
@@ -76,7 +76,7 @@ function test2()
<h2 id="6605">Using the <tt>$F()</tt> function</h2>
<p>
- The <tt>$F()</tt> function is a another welcome shortcut. It returns the value of any field input control,
+ The <tt>$F()</tt> function is a another welcome shortcut. It returns the value of any field input control,
like text boxes or drop-down lists. The function can take as argument either the element <tt>id</tt> or the element object itself.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
@@ -100,9 +100,9 @@ function test3()
into an <tt>Array</tt> object.
</p>
<p>
- This function, combined with the extensions for the Array class,
- makes it easier to convert or copy any enumerable list into an
- <tt>Array</tt> object. One suggested use is to convert DOM
+ This function, combined with the extensions for the Array class,
+ makes it easier to convert or copy any enumerable list into an
+ <tt>Array</tt> object. One suggested use is to convert DOM
<tt>NodeLists</tt> into regular arrays, which can be traversed
more efficiently. See example below.
</p>
@@ -113,8 +113,8 @@ function test3()
<option value="8">Callahan, Laura</option>
<option value="1">Davolio, Nancy</option>
</select>
-
-<input type="button" value="Show the options" onclick="showOptions();" />
+
+<input type="button" value="Show the options" onclick="showOptions();" />
<script type="text/javascript">
/*<![CDATA[*/
@@ -134,15 +134,15 @@ function showOptions()
<h2 id="6607">Using the <tt>$H()</tt> function</h2>
<p>
- The <tt>$H()</tt> function converts
- objects into enumerable Hash objects that
+ The <tt>$H()</tt> function converts
+ objects into enumerable Hash objects that
resemble associative arrays.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
function testHash()
{
//let's create the object
- var a =
+ var a =
{
first: 10,
second: 20,
@@ -151,22 +151,22 @@ function testHash()
//now transform it into a hash
var h = $H(a);
- alert(h.toQueryString());
-
+ alert(h.toQueryString());
+
//displays: first=10&amp;second=20&amp;third=30
}
</com:TTextHighlighter>
<h2 id="6608">Enumerating... Wow! Damn! Wahoo!</h2>
<p>
- We are all familar with for loops. You know, create yourself an array, populate it with
+ We are all familiar with for-loops. You know, create yourself an array, populate it with
elements of the same kind, create a loop control structure (for, foreach, while, repeat, etc,)
access each element sequentially, by its numeric index, and do something with the element.
</p>
<p>
When you come to think about it, almost every time you have an array in your code it
means that you'll be using that array in a loop sooner or later. Wouldn't it be nice
- if the array objects had more functionality to deal with these iterations? Yes, it would,
+ if the array objects had more functionality to deal with these iterations? Yes, it would,
and many programming languages provide such functionality in their arrays or equivalent
structures (like collections and lists.)
</p>
@@ -174,7 +174,7 @@ function testHash()
<p>
Well, it turns out that prototype.js gives us the Enumerable
object, which implements a plethora of tricks for us to use when dealing with iterable data.
- The prototype.js library goes one step further and extends the
+ The prototype.js library goes one step further and extends the
<tt>Array</tt> class with all the methods of <tt>Enumerable</tt>.
</p>
@@ -206,7 +206,7 @@ function showList()
<com:TTextHighlighter Language="javascript" CssClass="source">
function showList()
-{
+{
var simpsons = ['Homer', 'Marge', 'Lisa', 'Bart', 'Meg'];
simpsons.each( function(familyMember)
{
@@ -216,13 +216,13 @@ function showList()
</com:TTextHighlighter>
<p>
You are probably thinking "big freaking deal...just a weird syntax for the same old thing."
- Well, in the above example, yes, there's nothing too earth shattering going on. Afterall,
- there's not much to be changed in such a drop-dead-simple example. But
+ Well, in the above example, yes, there's nothing too earth shattering going on. After all,
+ there's not much to be changed in such a drop-dead-simple example. But
keep reading, nonetheless.
</p>
<p>
Before we move on. Do you see this function that is being passed as an argument
- to the <tt>each</tt> method? Let's start referring to it as an
+ to the <tt>each</tt> method? Let's start referring to it as an
<b>iterator</b> function.
</p>
@@ -247,7 +247,7 @@ function findEmployeeById(emp_id)
{
return (employee.value == emp_id);
});
-
+
alert(opt.innerHTML); //displays the employee name
}
/*]]>*/
@@ -259,7 +259,7 @@ function findEmployeeById(emp_id)
<option value="1">Davolio, Nancy</option>
</select>
-<input type="button" value="Find Laura" onclick="findEmployeeById(8);" />
+<input type="button" value="Find Laura" onclick="findEmployeeById(8);" />
</com:TTextHighlighter>
<p>
@@ -274,7 +274,7 @@ function showLocalLinks(paragraph)
{
paragraph = $(paragraph);
var links = $A(paragraph.getElementsByTagName('a'));
-
+
//find links that do not start with 'http'
var localLinks = links.findAll( function(link)
{
@@ -284,7 +284,7 @@ function showLocalLinks(paragraph)
//now the link texts
var texts = localLinks.pluck('innerHTML');
-
+
//get them in a single string
var result = texts.inspect();
alert(result);
@@ -293,13 +293,13 @@ function showLocalLinks(paragraph)
</script>
<p id="someText">
- This &lt;a href="http://othersite.com/page.html"&gt;text&lt;/a&gt; has
- a &lt;a href="#localAnchor"&gt;lot&lt;/a&gt; of
- &lt;a href="#otherAnchor"&gt;links&lt;/a&gt;. Some are
+ This &lt;a href="http://othersite.com/page.html"&gt;text&lt;/a&gt; has
+ a &lt;a href="#localAnchor"&gt;lot&lt;/a&gt; of
+ &lt;a href="#otherAnchor"&gt;links&lt;/a&gt;. Some are
&lt;a href="http://wherever.com/page.html"&gt;external&lt;/a&gt;
and some are &lt;a href="#someAnchor"&gt;local&lt;/a&gt;
</p>
-<input type=button value="Find Local Links"
+<input type=button value="Find Local Links"
onclick="showLocalLinks('someText')" />
</com:TTextHighlighter>
<p>
@@ -309,21 +309,21 @@ function showLocalLinks(paragraph)
<h1 id="6602">Enumerable Functions</h1>
The sample data for the following examples.
<com:TTextHighlighter Language="javascript" CssClass="source">
-var Fixtures =
+var Fixtures =
{
- Products:
+ Products:
[
{name: 'Basecamp', company: '37signals', type: 'Project Management'},
{name: 'Shopify', company: 'JadedPixel', type: 'E-Commerce'},
{name: 'Mint', company: 'Shaun Inman',type: 'Statistics'}
],
- Artist:
+ Artist:
[
- 'As I Lay Dying',
- '36 Crazyfist',
- 'Shadows Fall',
- 'Trivium',
+ 'As I Lay Dying',
+ '36 Crazyfist',
+ 'Shadows Fall',
+ 'Trivium',
'In Flames'
],
@@ -334,11 +334,11 @@ var F = Fixtures;
</com:TTextHighlighter>
<h2 id="6609"><tt>Enumerable.each</tt> function</h2>
-<p>I used to find myself writing a lot of for loops. Although,
-Prototype doesn’t by any means eliminate the need to do for loops,
+<p>I used to find myself writing a lot of for loops. Although,
+Prototype does not by any means eliminate the need to do for-loops,
it does give you access to what I consider to be a cleaner, easier to read method in each.
<com:TTextHighlighter Language="javascript" CssClass="source">
-for(var i = 0; i < F.Numbers.length; i++)
+for(var i = 0; i < F.Numbers.length; i++)
{
Logger.info(F.Numbers[i]);
}
@@ -347,7 +347,7 @@ for(var i = 0; i < F.Numbers.length; i++)
The <tt>each</tt> function allows us to iterate over these objects Ruby style.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-F.Numbers.each(function(num)
+F.Numbers.each(function(num)
{
Logger.info(num);
});
@@ -363,14 +363,14 @@ F.Numbers.each(function(num)
9
</com:TTextHighlighter>
-<p>The <tt>each</tt> function takes one argument, an <b>iterator</b> function.
-This iterator is invoked once for every item in the array, and that item
-along with the optional index is passed to the iterator. So if
+<p>The <tt>each</tt> function takes one argument, an <b>iterator</b> function.
+This iterator is invoked once for every item in the array, and that item
+along with the optional index is passed to the iterator. So if
we also needed the index we could do something like the code below.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-F.Numbers.each(function(num, index)
+F.Numbers.each(function(num, index)
{
Logger.info(index + ": " + num);
});
@@ -387,11 +387,11 @@ F.Numbers.each(function(num, index)
</com:TTextHighlighter>
<h2 id="6610">Hash key/value pairs</h2>
-<p>Hashes can be created by wrapping an Object (associative array) in
+<p>Hashes can be created by wrapping an Object (associative array) in
<tt>$H()</tt> and can have their key/value pairs exposed.</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-$H(F.Products[0]).each(function(product)
+$H(F.Products[0]).each(function(product)
{
Logger.info(product.key + ": " + product.value);
});
@@ -406,19 +406,19 @@ We can also directly access the keys and values of a Hash without iterating over
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
$H(F.Products[1]).keys();
-//Outputs name,company,type
+//Outputs name,company,type
$H(F.Products[1]).values();
-//Outputs Shopify,JadedPixel,E-Commerce
+//Outputs Shopify,JadedPixel,E-Commerce
</com:TTextHighlighter>
<h2 id="6611"><tt>Enumerable.collect</tt> function</h2>
-<p>The <tt>collect</tt> function allows you to iterate over an <tt>Array</tt> and return the
-results as a new array. Each item returned as a result of the iteration will be
+<p>The <tt>collect</tt> function allows you to iterate over an <tt>Array</tt> and return the
+results as a new array. Each item returned as a result of the iteration will be
pushed onto the end of the new array.</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-var companies = F.Products.collect(function(product)
+var companies = F.Products.collect(function(product)
{
return product.company;
});
@@ -431,7 +431,7 @@ Logger.info(companies.join(', '));
<p>You can even join on the end of the block.</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-return F.Products.collect(function(product)
+return F.Products.collect(function(product)
{
return product.company;
}).join(', ');
@@ -439,9 +439,9 @@ return F.Products.collect(function(product)
<h2 id="6612"><tt>Enumerable.include</tt> function</h2>
-<p>The <tt>include</tt> function allows you to check if a value is included in an array
-and returns true or false depending on if a match was made. Assuming I put
-up a form asking the user to name some artist in my iTunes playlist,
+<p>The <tt>include</tt> function allows you to check if a value is included in an array
+and returns true or false depending on if a match was made. Assuming I put
+up a form asking the user to name some artist in my iTunes playlist,
we could do something like the code below. Prime candidate for some conditional madness.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
@@ -450,11 +450,11 @@ return F.Artists.include('Britney Spears'); // returns false
<h2 id="6613"><tt>Enumerable.inject</tt> function</h2>
-<p>The <tt>inject</tt> function is good for getting a collective sum from an array of
+<p>The <tt>inject</tt> function is good for getting a collective sum from an array of
values. For instance, to add up all the numbers.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-var score = F.Numbers.inject(0, function(sum, value)
+var score = F.Numbers.inject(0, function(sum, value)
{
return sum + value;
});
@@ -463,19 +463,19 @@ Logger.info(score);
//Output 161
</com:TTextHighlighter>
-<p>The first argument to <tt>inject</tt> is just an initial value that
+<p>The first argument to <tt>inject</tt> is just an initial value that
would be added to the sum, so if we added 1 instead of 0, the output would be 162.</p>
<h2 id="6614"><tt>Enumerable.findAll</tt> function</h2>
<p>
-When given an Array, the <tt>findAll</tt> function will return an array of
-items for which the iterator evaluated to true. Basically, it allows you to
-build a new array of values based on some search criteria.
-If we wanted to find all products whose type was “E-Commerce”
+When given an Array, the <tt>findAll</tt> function will return an array of
+items for which the iterator evaluated to true. Basically, it allows you to
+build a new array of values based on some search criteria.
+If we wanted to find all products whose type was “E-Commerce”
we could do something like the code below.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-var ecom = F.Products.findAll(function(product)
+var ecom = F.Products.findAll(function(product)
{
return product.type == 'E-Commerce';
});
@@ -486,18 +486,18 @@ Logger.info(ecom[0].company + " produces " + ecom[0].name);
JadedPixel produces Shopify
</com:TTextHighlighter>
-<p>Note that even if only one match is made, just as in this case,
-the result is still returned as an array. In that case,
+<p>Note that even if only one match is made, just as in this case,
+the result is still returned as an array. In that case,
<tt>ecom.company</tt> would return <tt>undefined</tt>.</p>
<h2 id="6615"><tt>Enumerable.detect</tt> function</h2>
-<p>Unlike the <tt>findAll</tt> function, the <tt>detect</tt> function will only
-return the first item for which the expression inside
-the iterator is true. So, if we wanted to find the first number that
+<p>Unlike the <tt>findAll</tt> function, the <tt>detect</tt> function will only
+return the first item for which the expression inside
+the iterator is true. So, if we wanted to find the first number that
was greater than 5 we’d do something like the code below.
</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-var low = F.Numbers.detect(function(num)
+var low = F.Numbers.detect(function(num)
{
return num > 5
});
@@ -506,13 +506,13 @@ Logger.info(low);
//Outputs 98
</com:TTextHighlighter>
-<p>Even though, there are other numbers above 5 in our array, detect
+<p>Even though, there are other numbers above 5 in our array, detect
only gives us the first match back.</p>
<h2 id="6616"><tt>Enumerable.invoke</tt> function</h2>
-<p>The <tt>invoke</tt> function allows us to pass a method as a string and
-have that method invoked. For instance, if we wanted to sort
+<p>The <tt>invoke</tt> function allows us to pass a method as a string and
+have that method invoked. For instance, if we wanted to sort
our array of artists we’d do something like this:</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
@@ -520,7 +520,7 @@ our array of artists we’d do something like this:</p>
//Outputs 36 Crazyfist,As I Lay Dying,In Flames,Shadows Fall,Trivium
</com:TTextHighlighter>
-<p>Why not just use <tt>F.Artists.sort</tt>? Well, for the example above
+<p>Why not just use <tt>F.Artists.sort</tt>? Well, for the example above
we could do just that, but here is where <tt>invoke</tt> shines.</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
@@ -533,8 +533,8 @@ we could do just that, but here is where <tt>invoke</tt> shines.</p>
F.Artists.invoke('sort');
</com:TTextHighlighter>
-<p>The reason this will not work is because it is taking each item
-in that array and trying to apply sort to it, thus if we wrote it outright,
+<p>The reason this will not work is because it is taking each item
+in that array and trying to apply sort to it, thus if we wrote it outright,
it would look something like this:</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
@@ -548,8 +548,8 @@ F.Artists.invoke('toLowerCase');
</com:TTextHighlighter>
<p>
-Now, what about passing arguments to the <tt>invoke</tt> function?
-The first argument passed to <tt>invoke</tt> is the method to be invoked,
+Now, what about passing arguments to the <tt>invoke</tt> function?
+The first argument passed to <tt>invoke</tt> is the method to be invoked,
and any other arguments beyond that will be passed as arguments to the invoked method.</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
diff --git a/demos/quickstart/protected/pages/Advanced/Scripts2.page b/demos/quickstart/protected/pages/Advanced/Scripts2.page
index 6ee6a5d8..2c9ce220 100644
--- a/demos/quickstart/protected/pages/Advanced/Scripts2.page
+++ b/demos/quickstart/protected/pages/Advanced/Scripts2.page
@@ -9,13 +9,13 @@
Event.observe(element, name, observer, [useCapture]);
</com:TTextHighlighter>
-<p>Assuming for a moment that we want to observe when a link was clicked,
+<p>Assuming for a moment that we want to observe when a link was clicked,
we could do the following:</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
// &lt;a id="clicker" href="http://foo.com"&gt;Click me&lt;/a&gt;
Event.observe('clicker', 'click', function(event)
-{
+{
alert('clicked!');
});
</com:TTextHighlighter>
@@ -24,7 +24,7 @@ Event.observe('clicker', 'click', function(event)
<com:TTextHighlighter Language="javascript" CssClass="source">
Event.observe('clicker', 'click', function(event)
-{
+{
alert(Event.element(event));
});
</com:TTextHighlighter>
@@ -35,8 +35,8 @@ Event.observe('clicker', 'click', function(event)
<com:TTextHighlighter Language="javascript" CssClass="source">
Event.observe(document, 'keypress', function(event)
-{
- if(Event.keyCode(event) == Event.KEY_TAB)
+{
+ if(Event.keyCode(event) == Event.KEY_TAB)
alert('Tab Pressed');
});
</com:TTextHighlighter>
@@ -44,37 +44,37 @@ Event.observe(document, 'keypress', function(event)
<p>And lets say we wanted to keep track of what has been typed :</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-Event.observe('search', 'keypress', function(event)
-{
+Event.observe('search', 'keypress', function(event)
+{
Element.update('search-results', $F(Event.element(event)));
});
</com:TTextHighlighter>
-<p>Prototype defines properties inside the event object for some
-of the more common keys, so feel free to dig around in Prototype to
+<p>Prototype defines properties inside the event object for some
+of the more common keys, so feel free to dig around in Prototype to
see which ones those are.</p>
-<p>A final note on keypress events; If you'd like to detect a
+<p>A final note on keypress events; If you'd like to detect a
left click you can use <tt>Event.isLeftClick(event)</tt>.</p>
<h2 id="6704">Getting the coordinates of the mouse pointer</h2>
-<p>Drag and drop, dynamic element resizing, games, and
-much more all require the ability to track the X and Y location of
-the mouse. Prototype makes this fairly simple. The code below tracks
-the X and Y position of the mouse and spits out those values into
+<p>Drag and drop, dynamic element resizing, games, and
+much more all require the ability to track the X and Y location of
+the mouse. Prototype makes this fairly simple. The code below tracks
+the X and Y position of the mouse and spits out those values into
an input box named mouse.</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
Event.observe(document, 'mousemove', function(event)
{
- $('mouse').value = "X: " + Event.pointerX(event) +
+ $('mouse').value = "X: " + Event.pointerX(event) +
"px Y: " + Event.pointerY(event) + "px";
});
</com:TTextHighlighter>
-<p>If we wanted to observe the mouse location when it was
-hovering over a certain element, we'd just change the document argument to
+<p>If we wanted to observe the mouse location when it was
+hovering over a certain element, we'd just change the document argument to
the id or element that was relevant.</p>
<h2 id="6705">Stopping Propagation</h2>
@@ -83,33 +83,33 @@ the id or element that was relevant.</p>
<h2 id="6706">Events, Binding, and Objects</h2>
-<p>Everything has been fairly straight forward so far, but things
-start getting a little tricker when you need to work with events in
-and object-oriented environment. You have to deal with binding and funky
+<p>Everything has been fairly straight forward so far, but things
+start getting a little trickier when you need to work with events in
+and object-oriented environment. You have to deal with binding and funky
looking syntax that might take a moment to get your head around.</p>
<p>Lets look at some code so you can get a better understanding of what I'm talking about.</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
EventDispenser = Class.create();
-EventDispenser.prototype =
+EventDispenser.prototype =
{
- initialize: function(list)
+ initialize: function(list)
{
this.list = list;
- // Observe clicks on our list items
- $$(this.list + " li").each(function(item)
+ // Observe clicks on our list items
+ $$(this.list + " li").each(function(item)
{
Event.observe(item, 'click', this.showTagName.bindEvent(this));
}.bind(this));
- // Observe when a key on the keyboard is pressed.
- // In the observer, we check for
+ // Observe when a key on the keyboard is pressed.
+ // In the observer, we check for
// the tab key and alert a message if it is pressed.
Event.observe(document, 'keypress', this.onKeyPress.bindEvent(this));
- // Observe our fake live search box. When a user types
- // something into the box, the observer will take that
+ // Observe our fake live search box. When a user types
+ // something into the box, the observer will take that
// value(-1) and update our search-results div with it.
Event.observe('search', 'keypress', this.onSearch.bindEvent(this));
@@ -117,65 +117,65 @@ EventDispenser.prototype =
},
// Arbitrary functions to respond to events
- showTagName: function(event)
+ showTagName: function(event)
{
alert(Event.element(event).tagName);
},
- onKeyPress: function(event)
+ onKeyPress: function(event)
{
var code = event.keyCode;
- if(code == Event.KEY_TAB)
+ if(code == Event.KEY_TAB)
alert('Tab key was pressed');
},
- onSearch: function(event)
+ onSearch: function(event)
{
Element.update('search-results', $F(Event.element(event)));
},
- onMouseMove: function(event)
+ onMouseMove: function(event)
{
- $('mouse').value = "X: " + Event.pointerX(event) +
+ $('mouse').value = "X: " + Event.pointerX(event) +
"px Y: " + Event.pointerY(event) + "px";
}
}
</com:TTextHighlighter>
-<p>Whoa! What's going on here? Well, we've defined our a
-custom class <tt>EventDispenser</tt>. We're going to be using this class
-to setup events for our document. Most of this code is a
-rewrite of the code we looked at earlier except this time, we
+<p>Whoa! What's going on here? Well, we've defined our a
+custom class <tt>EventDispenser</tt>. We're going to be using this class
+to setup events for our document. Most of this code is a
+rewrite of the code we looked at earlier except this time, we
are working from inside an object.</p>
-<p>Looking at the <tt>initialize</tt> method, we can really see how
+<p>Looking at the <tt>initialize</tt> method, we can really see how
things are different now. Take a look at the code below:</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-// Observe clicks on our list items
-$$(this.list + " li").each(function(item)
+// Observe clicks on our list items
+$$(this.list + " li").each(function(item)
{
Event.observe(item, 'click', this.showTagName.bindEvent(this));
}.bind(this));
</com:TTextHighlighter>
-<p>We've got iterators, binding and all sorts of stuff going on.
+<p>We've got iterators, binding and all sorts of stuff going on.
Lets break down what this chunk of code is doing.</p>
-<p>First we are hunting for a collection of elements based on
-it's Css selector. This uses the Prototype selector function <tt>$$()</tt>.
-After we've found the list items we are dealing with we send
+<p>First we are hunting for a collection of elements based on
+it's CSS selector. This uses the Prototype selector function <tt>$$()</tt>.
+After we've found the list items we are dealing with we send
those into an each iteration where we will add our observers.</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
Event.observe(item, 'click', this.showTagName.bindEvent(this));
</com:TTextHighlighter>
-<p>Now looking at the code above, you'll notice the <tt>bindEvent</tt> function.
-This takes the method before it <tt>showTagName</tt> and treats it as the
-method that will be triggered when, in this case,
+<p>Now looking at the code above, you'll notice the <tt>bindEvent</tt> function.
+This takes the method before it <tt>showTagName</tt> and treats it as the
+method that will be triggered when, in this case,
someone clicks one of our list items.</p>
-<p>You'll also notice we pass this as an argument to the <tt>bindEvent</tt> function.
-This simply allows us to reference the object in context <tt>EventDispenser</tt>
+<p>You'll also notice we pass this as an argument to the <tt>bindEvent</tt> function.
+This simply allows us to reference the object in context <tt>EventDispenser</tt>
inside our function <tt>showTagName(event)</tt>. If the <tt>showTagName</tt> function
requires additional parameters, you can attach them to the later parameters of <tt>bindEvent</tt>. For example</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
@@ -185,58 +185,58 @@ this.showTagName.bindEvent(this, param1, param2);
showTime : function (event, param1, param2) { ... }
</com:TTextHighlighter>
-<p>Moving on, you'll see <tt>bind(this)</tt> attached to our iterator function.
-This really has nothing to do with events, it is only here to allow me to
-use <tt>this</tt> inside the iterator. If we didn't use <tt>bind(this)</tt>, I couldn't
+<p>Moving on, you'll see <tt>bind(this)</tt> attached to our iterator function.
+This really has nothing to do with events, it is only here to allow me to
+use <tt>this</tt> inside the iterator. If we did not use <tt>bind(this)</tt>, I could not
reference the method <tt>showTagName</tt> inside the iterator.</p>
-<p>Ok, so we'll move on to looking at our methods that actually get
+<p>Ok, so we'll move on to looking at our methods that actually get
called when an event occurs. Since we've been dealing with <tt>showTagName</tt>, lets look at it.</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-showTagName: function(event)
+showTagName: function(event)
{
alert(Event.element(event).tagName);
}
</com:TTextHighlighter>
-<p>As you can see, this function accepts one argument--the event.
-In order for us to get the element which fired the event we need to
+<p>As you can see, this function accepts one argument--the event.
+In order for us to get the element which fired the event we need to
pass that argument to <tt>Event.element</tt>. Now we can manipulate it at will.</p>
-<p>This covers the most confusing parts of our code. The text above is also
-relevant to the remaining parts of our code. If there is anything about
+<p>This covers the most confusing parts of our code. The text above is also
+relevant to the remaining parts of our code. If there is anything about
this you don't understand, feel free to ask questions in the forum.</p>
<h2 id="6707">Removing Event Listeners</h2>
-<p>This one threw me for a loop the first time I tried to use it.
-I tried something similar to what I did in the <tt>Event.observe</tt>
-call with the exception of using <tt>stopObserving</tt>, but nothing seemed
+<p>This one threw me for a loop the first time I tried to use it.
+I tried something similar to what I did in the <tt>Event.observe</tt>
+call with the exception of using <tt>stopObserving</tt>, but nothing seemed
to change. In other words, the code below does <b>NOT</b> work.</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-$$(this.list + " li").each(function(item)
+$$(this.list + " li").each(function(item)
{
Event.stopObserving(item, 'click', this.showTagName);
}.bind(this));
</com:TTextHighlighter>
-<p>What's the deal here? The reason this doesn't work is because there
+<p>What's the deal here? The reason this does not work is because there
is no pointer to the observer. This means that when we passed <tt>this.showTagName</tt>
-in the <tt>Event.observe</tt> method before hand, we passed it as an
-anonymous function. We can't reference an anonymous function
-because it simply doesn't have a pointer.</p>
+in the <tt>Event.observe</tt> method before hand, we passed it as an
+anonymous function. We can't reference an anonymous function
+because it simply does not have a pointer.</p>
-<p>So how do we get the job done? All we need to do is give the
-observing function a pointer, or the jargon free version: Set a variable
+<p>So how do we get the job done? All we need to do is give the
+observing function a pointer, or the jargon free version: Set a variable
that points to <tt>this.showTagName</tt>. Ok, lets change our code a bit.</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
this.showTagObserver = this.showTagName.bindEvent(this);
-// Observe clicks on our list items
-$$(this.list + " li").each(function(item)
+// Observe clicks on our list items
+$$(this.list + " li").each(function(item)
{
Event.observe(item, 'click', this.showTagObserver);
}.bind(this));
@@ -244,7 +244,7 @@ $$(this.list + " li").each(function(item)
<p>Now we can remove the event listeners from our list like this:</p>
<com:TTextHighlighter Language="javascript" CssClass="source">
-$$(this.list + " li").each(function(item)
+$$(this.list + " li").each(function(item)
{
Event.stopObserving(item, 'click', this.showTagObserver);
}.bind(this));
diff --git a/demos/quickstart/protected/pages/Advanced/Scripts3.page b/demos/quickstart/protected/pages/Advanced/Scripts3.page
index 123caa3a..8ba6d5c8 100644
--- a/demos/quickstart/protected/pages/Advanced/Scripts3.page
+++ b/demos/quickstart/protected/pages/Advanced/Scripts3.page
@@ -1,20 +1,20 @@
<com:TContent ID="body" >
-<h1 id="6801">Javascript in Prado, Questions and Answers</h1>
-<h2 id="6802">How do I include the predefined javascript libraries?</h2>
+<h1 id="6801">Javascript in PRADO, Questions and Answers</h1>
+<h2 id="6802">How do I include the predefined Javascript libraries?</h2>
<ul><li>Adding libraries in the template
<com:TTextHighlighter Language="prado" CssClass="source">
&lt;com:TClientScript UsingPradoScripts="effects" /&gt;
-</com:TTextHighlighter>
- </li>
+</com:TTextHighlighter>
+ </li>
<li>Adding libraries in PHP code
<com:TTextHighlighter Language="php" CssClass="source">
-$this->getPage()->getClientScript()->registerPradoScript("effects");
+$this->getPage()->getClientScript()->registerPradoScript("effects");
</com:TTextHighlighter>
</li>
-</ul>
-The available packaged libraries included in Prado are
+</ul>
+The available packaged libraries included in Prado are
<ul>
- <li><tt>prado</tt> : basic prado javascript framework based on Prototype</li>
+ <li><tt>prado</tt> : basic PRADO javascript framework based on Prototype</li>
<li><tt>effects</tt> : visual effects from script.aculo.us</li>
<li><tt>ajax</tt> : ajax and callback related based on Prototype</li>
<li><tt>validator</tt> : validation</li>
@@ -24,12 +24,12 @@ The available packaged libraries included in Prado are
<li><tt>colorpicker</tt> : colorpicker</li>
</ul>
-<p>The dependencies for each library are automatically resolved. Components
+<p>The dependencies for each library are automatically resolved. Components
that require a particular library will also automatically load the necessary libraries.
-For example, if you add a TDatePicker component on the page, the <tt>datapicker</tt>
+For example, if you add a TDatePicker component on the page, the <tt>datepicker</tt>
and its dependencies will be automatically included on the page.</p>
<p>See <a href="?page=Controls.ClientScript">TClientScript</a> for options of adding
- your custom javascript code to the page.</p>
+ your custom Javascript code to the page.</p>
</com:TContent> \ No newline at end of file
diff --git a/demos/quickstart/protected/pages/Advanced/Security.page b/demos/quickstart/protected/pages/Advanced/Security.page
index 9be7946a..3dbfe0ab 100644
--- a/demos/quickstart/protected/pages/Advanced/Security.page
+++ b/demos/quickstart/protected/pages/Advanced/Security.page
@@ -10,7 +10,7 @@ Viewstate lies at the heart of PRADO. Viewstate represents data that can be used
It is extremely important to ensure that viewstate is not tampered by end users. Without protection, malicious users may inject harmful code into viewstate and unwanted instructions may be performed when page state is being restored on server side.
</p>
<p>
-To prevent viewstate from being tampered, PRADO enforces viewstate HMAC (Keyed-Hashing for Message Authentication) check before restoring viewstate. Such a check can detect if the viewstate has been tampered or not by end users. Should the viewstate is modified, PRADO will stop restoring the viewstate and return an error message.
+To prevent viewstate from being tampered, PRADO enforces viewstate HMAC (Keyed-Hashing for Message Authentication) check before restoring viewstate. Such a check can detect if the viewstate has been tampered or not by end users. Should the viewstate is modified, PRADO will stop restoring the viewstate and return an error message.
</p>
<p>
HMAC check requires a private key that should be secret to end users. Developers can either manually specify a key or let PRADO automatically generate a key. Manually specified key is useful when the application runs on a server farm. To do so, configure <tt>TSecurityManager</tt> in application configuration,
@@ -31,7 +31,7 @@ HMAC check does not prevent end users from reading the viewstate content. An add
Cross site scripting (also known as XSS) occurs when a web application gathers malicious data from a user. Often attackers will inject JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable application to fool other application users and gather data from them. For example, a poorly design forum system may display user input in forum posts without any checking. An attacker can then inject a piece of malicious JavaScript code into a post so that when other users read this post, the JavaScript runs unexpectedly on their computers.
</p>
<p>
-One of the most important measures to prevent XSS attacks is to check user input before displaying them. One can do HTML-encoding with the user input to achieve this goal. However, in some situations, HTML-encoding may not be preferrable because it disables all HTML tags.
+One of the most important measures to prevent XSS attacks is to check user input before displaying them. One can do HTML-encoding with the user input to achieve this goal. However, in some situations, HTML-encoding may not be preferable because it disables all HTML tags.
</p>
<p>
PRADO incorporates the work of <a href="http://pixel-apes.com/safehtml/">SafeHTML</a> and provides developers with a useful component called <tt>TSafeHtml</tt>. By enclosing content within a <tt>TSafeHtml</tt> component tag, the enclosed content are ensured to be safe to end users. In addition, the commonly used <tt>TTextBox</tt> has a <tt>SafeText</tt> property which contains user input that are ensured to be safe if displayed directly to end users.
@@ -51,7 +51,7 @@ There are several countermeasures to prevent cookies from being attacked.
<li>Validate cookie data and detect if they are altered.</li>
</ul>
<p>
-Prado implements a cookie validation scheme that prevents cookies from being modified. In particular, it does HMAC check for the cookie values if cookie validation is enable.
+PRADO implements a cookie validation scheme that prevents cookies from being modified. In particular, it does HMAC check for the cookie values if cookie validation is enable.
</p>
<p>
Cookie validation is disabled by default. To enable it, configure the <tt>THttpRequest</tt> module as follows,
@@ -62,7 +62,7 @@ Cookie validation is disabled by default. To enable it, configure the <tt>THttpR
</modules>
</com:TTextHighlighter>
<p>
-To make use of cookie validation scheme provided by Prado, you also need to retrieve cookies through the <tt>Cookies</tt> collection of <tt>THttpRequest</tt> by using the following PHP statements,
+To make use of cookie validation scheme provided by PRADO, you also need to retrieve cookies through the <tt>Cookies</tt> collection of <tt>THttpRequest</tt> by using the following PHP statements,
</p>
<com:TTextHighlighter CssClass="source">
foreach($this->Request->Cookies as $cookie)
diff --git a/demos/quickstart/protected/pages/Advanced/State.page b/demos/quickstart/protected/pages/Advanced/State.page
index 051090e9..6e7e7f99 100644
--- a/demos/quickstart/protected/pages/Advanced/State.page
+++ b/demos/quickstart/protected/pages/Advanced/State.page
@@ -7,7 +7,7 @@ Web applications often need to remember what an end user has done in previous pa
<h2 id="6002">View State</h2>
<p>
-View state lies at the heart of PRADO. With view state, Web pages become stateful and are capable of restoring pages to the state that end users interacted with before the current page request. Web programming thus resembles to Windows GUI programming, and developers can think continuously without worrying about the roundtrips between end users and the Web server. For example, with view state, a textbox control is able to detect if the user input changes the content in the textbox.
+View state lies at the heart of PRADO. With view state, Web pages become stateful and are capable of restoring pages to the state that end users interacted with before the current page request. Web programming thus resembles to Windows GUI programming, and developers can think continuously without worrying about the round trips between end users and the Web server. For example, with view state, a textbox control is able to detect if the user input changes the content in the textbox.
</p>
<p>
View state is only available to controls. View state of a control can be disabled by setting its <tt>EnableViewState</tt> property to false. To store a variable in view state, call the following,
diff --git a/demos/quickstart/protected/pages/Advanced/Themes.page b/demos/quickstart/protected/pages/Advanced/Themes.page
index ef593c65..5ba0a121 100644
--- a/demos/quickstart/protected/pages/Advanced/Themes.page
+++ b/demos/quickstart/protected/pages/Advanced/Themes.page
@@ -4,12 +4,12 @@
<h2 id="5902">Introduction</h2>
<p>
-Themes in Prado provide a way for developers to provide a consistent look-and-feel across an entire web application. A theme contains a list of initial values for properties of various control types. When applying a theme to a page, all controls on that page will receive the corresponding initial property values from the theme. This allows themes to interact with the rich property sets of the various PRADO controls, meaning that themes can be used to specify a large range of presentational properties that other theming methods (e.g. CSS) cannot. For example, themes could be used to specify the default page size of all data grids across an application by specifying a default value for the <tt>PageSize</tt> property of the <tt>TDataGrid</tt> control.
+Themes in PRADO provide a way for developers to provide a consistent look-and-feel across an entire web application. A theme contains a list of initial values for properties of various control types. When applying a theme to a page, all controls on that page will receive the corresponding initial property values from the theme. This allows themes to interact with the rich property sets of the various PRADO controls, meaning that themes can be used to specify a large range of presentational properties that other theming methods (e.g. CSS) cannot. For example, themes could be used to specify the default page size of all data grids across an application by specifying a default value for the <tt>PageSize</tt> property of the <tt>TDataGrid</tt> control.
</p>
<h2 id="5903">Understanding Themes</h2>
<p>
-A theme is a directory consists of skin files, javascript files and CSS files. Any javascript or CSS files contained in a theme will be registered with the page that the theme is applied to. A skin is a set of initial property values for a particular control type. A control type may have one or several skins, each identified by a unqiue <tt>SkinID</tt>. When applying a theme to a page, a skin is applied to a control if the control type and the <tt>SkinID</tt> value both match to those of the skin. Note, if a skin has an empty <tt>SkinID</tt> value, it will apply to all controls of the particular type whose <tt>SkinID</tt> is not set or empty. A skin file consists of one or several skins, for one or several control types. A theme is the union of skins defined in all skin files.
+A theme is a directory consists of skin files, javascript files and CSS files. Any javascript or CSS files contained in a theme will be registered with the page that the theme is applied to. A skin is a set of initial property values for a particular control type. A control type may have one or several skins, each identified by a unique <tt>SkinID</tt>. When applying a theme to a page, a skin is applied to a control if the control type and the <tt>SkinID</tt> value both match to those of the skin. Note, if a skin has an empty <tt>SkinID</tt> value, it will apply to all controls of the particular type whose <tt>SkinID</tt> is not set or empty. A skin file consists of one or several skins, for one or several control types. A theme is the union of skins defined in all skin files.
</p>
<h2 id="5904">Using Themes</h2>
@@ -26,7 +26,7 @@ To use a particular skin in the theme for a control, set <tt>SkinID</tt> propert
This will apply the 'Blue' skin to the button. Note, the initial property values specified by the 'Blue' skin will overwrite any existing property values of the button. Use stylesheet theme if you do not want them to be overwritten. To use stylesheet theme, set the <tt>StyleSheetTheme</tt> property of the page instead of <tt>Theme</tt> (you can have both <tt>StyleSheetTheme</tt> and <tt>Theme</tt>).
</p>
<p>
-To use the javascript files and CSS files contained in a theme, a <tt>THead</tt> control must be placed on the page template. This is because the theme will register those files with the page and <tt>THead</tt> is the right place to load those files.
+To use the Javascript files and CSS files contained in a theme, a <tt>THead</tt> control must be placed on the page template. This is because the theme will register those files with the page and <tt>THead</tt> is the right place to load those files.
</p>
<h2 id="5905">Theme Storage</h2>
@@ -46,7 +46,7 @@ All themes by default must be placed under the <tt>[AppEntryPath]/themes</tt> di
<h2 id="5906">Creating Themes</h2>
<p>
-Creating a theme involves creating the theme directory and writing skin files (and possibly javascript and CSS files). The name of skin files must be terminated with <tt>.skin</tt>. The format of skin files are the same as that of control template files. Since skin files do not define parent-child presentational relationship among controls, you cannot place a component tag within another. And any static texts between component tags are discarded. To define the aforementioned 'Blue' skin for <tt>TButton</tt>, write the following in a skin file,
+Creating a theme involves creating the theme directory and writing skin files (and possibly Javascript and CSS files). The name of skin files must be terminated with <tt>.skin</tt>. The format of skin files are the same as that of control template files. Since skin files do not define parent-child presentational relationship among controls, you cannot place a component tag within another. And any static texts between component tags are discarded. To define the aforementioned 'Blue' skin for <tt>TButton</tt>, write the following in a skin file,
</p>
<com:TTextHighlighter Language="prado" CssClass="source">
&lt;com:TButton SkinID="Blue" BackColor="blue" /&gt;
diff --git a/demos/quickstart/protected/pages/Comments.page b/demos/quickstart/protected/pages/Comments.page
deleted file mode 100644
index 32c7bcae..00000000
--- a/demos/quickstart/protected/pages/Comments.page
+++ /dev/null
@@ -1,46 +0,0 @@
-<com:TContent ID="body">
- <com:TDataList
- ID="comments"
- DataKeyField="id"
- OnEditCommand="editComment"
- OnCancelCommand="cancelEdit"
- OnUpdateCommand="updateComment"
- OnDeleteCommand="deleteComment"
- OnSelectedIndexChanged="approveComment"
- ItemStyle.BackColor="#BFCFFF"
- AlternatingItemStyle.BackColor="#E6ECFF"
- EditItemStyle.BackColor="lightgreen">
-
- <prop:HeaderTemplate>
- Comments awaiting approval
- </prop:HeaderTemplate>
-
- <prop:ItemTemplate>
- <span class="page"><%# $this->DataItem['page'] %></span>
- <span class="date">
- <com:TDateFormat Value=<%# intval($this->DataItem['date_added']) %> />
- </span>
- <span class="email">
- <%# $this->DataItem['email'] %>
- </span>
- <div class="comment">
- <com:TSafeHtml>
- <%# $this->DataItem['comment']%>
- </com:TSafeHtml>
- </div>
- <com:TLinkButton Text="Edit" CommandName="edit" />
- <com:TLinkButton Text="Delete" CommandName="delete"
- Attributes.onclick="if(!confirm('Are you sure?')) return false;" />
- <com:TLinkButton Text="Approve" CommandName="select" />
- </prop:ItemTemplate>
-
- <prop:EditItemTemplate>
- <com:TTextBox ID="email" Text=<%# $this->DataItem['email'] %> />
- <com:TTextBox ID="page" Text=<%# $this->DataItem['page'] %> />
- <com:TTextBox ID="content" Text=<%# $this->DataItem['comment'] %> TextMode="MultiLine"/>
- <com:TLinkButton Text="Save" CommandName="update" />
- <com:TLinkButton Text="Cancel" CommandName="cancel" />
- </prop:EditItemTemplate>
-
- </com:TDataList>
-</com:TContent> \ No newline at end of file
diff --git a/demos/quickstart/protected/pages/Comments.php b/demos/quickstart/protected/pages/Comments.php
deleted file mode 100644
index 7af70ece..00000000
--- a/demos/quickstart/protected/pages/Comments.php
+++ /dev/null
@@ -1,76 +0,0 @@
-<?php
-
-Prado::using('System.I18N.*');
-
-/**
- * Comments class.
- *
- * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
- * @version : $ Sat May 27 20:23:00 AZOST 2006 $
- * @package Demo.Quickstart
- * @since 3.0
- */
-class Comments extends TPage
-{
- private $_quickstart;
-
- public function onLoad($param)
- {
- parent::onLoad($param);
- $this->_quickstart = new QuickStartComments;
- if(!$this->getIsPostBack())
- $this->refreshData();
- }
-
- protected function refreshData()
- {
- $this->comments->setDataSource($this->_quickstart->getQuequedComments());
- $this->comments->dataBind();
- }
-
- public function approveComment($sender, $param)
- {
- $ID = $this->comments->DataKeys[$this->comments->SelectedItemIndex];
- $this->_quickstart->approveComment($ID);
- $this->refreshData();
- $this->comments->SelectedItemIndex=-1;
- }
-
- public function editComment($sender, $param)
- {
- $this->comments->SelectedItemIndex=-1;
- $this->comments->EditItemIndex=$param->Item->ItemIndex;
- $this->refreshData();
- }
-
- public function cancelEdit($sender, $param)
- {
- $this->comments->SelectedItemIndex=-1;
- $this->comments->EditItemIndex=-1;
- $this->refreshData();
- }
-
- public function deleteComment($sender, $param)
- {
- $ID = $this->comments->DataKeys[$param->Item->ItemIndex];
- $this->_quickstart->deleteComment($ID);
- $this->comments->SelectedItemIndex=-1;
- $this->comments->EditItemIndex=-1;
- $this->refreshData();
- }
-
- public function updateComment($sender, $param)
- {
- $item=$param->Item;
- $this->_quickstart->updateComment(
- $this->comments->DataKeys[$item->ItemIndex],
- $item->page->Text,
- $item->email->Text,
- $item->content->Text);
-
- $this->comments->EditItemIndex=-1;
- $this->refreshData();
- }
-}
-
-?> \ No newline at end of file
diff --git a/demos/quickstart/protected/pages/Controls/ClientScript.page b/demos/quickstart/protected/pages/Controls/ClientScript.page
index 5dab41d5..d5687fb1 100644
--- a/demos/quickstart/protected/pages/Controls/ClientScript.page
+++ b/demos/quickstart/protected/pages/Controls/ClientScript.page
@@ -1,23 +1,23 @@
<com:TContent ID="body" >
-<h1>TClientScript</h1>
+<h1 id="2201">TClientScript</h1>
<com:DocLink ClassPath="System.Web.UI.WebControls.TClientScript" />
-<h2>Including Bundled Javascript Libraries in Prado</h2>
+<h2 id="2202">Including Bundled Javascript Libraries in Prado</h2>
<p>
-<tt>TClientScript</tt> allows javascript code to be insert or linked to the
-page template. Prado is bundled with a large library of javascript functionality
-including effects, AJAX, basic event handlers, and many others. The bundled
-javascript libraries can be linked to the current page template using the
-<tt>UsingPradoScripts</tt> property. Multiple bundled javascript libraries
-can be specified using comma delimited string of the name of javascript library
+<tt>TClientScript</tt> allows Javascript code to be insert or linked to the
+page template. PRADO is bundled with a large library of Javascript functionality
+including effects, AJAX, basic event handlers, and many others. The bundled
+Javascript libraries can be linked to the current page template using the
+<tt>PradoScripts</tt> property. Multiple bundled Javascript libraries
+can be specified using comma delimited string of the name of Javascript library
to include on the page. For following example will include the "ajax" and "effects" library.
</p>
<com:TTextHighlighter Language="prado" CssClass="source">
-&lt;com:TClientScript UsingPradoScripts="ajax, effects" /&gt;
+&lt;com:TClientScript PradoScripts="ajax, effects" /&gt;
</com:TTextHighlighter>
<p>
- The available bundled libraries included in Prado are
+ The available bundled libraries included in Prado are
<ul>
<li><tt>prado</tt> : basic prado javascript framework based on Prototype</li>
<li><tt>effects</tt> : visual effects from script.aculo.us</li>
@@ -29,12 +29,12 @@ to include on the page. For following example will include the "ajax" and "effec
<li><tt>colorpicker</tt> : colorpicker</li>
</ul>
</p>
-<p>The dependencies for each library are automatically resolved. That is,
+<p>The dependencies for each library are automatically resolved. That is,
specifying, say the "ajax", will also include the "prado" library.</p>
-
-<h2>Including Custom Javascript Files</h2>
-<p>Custom javascript files can be register using the <tt>ScriptUrl</tt> property.
-The following example includes the javascript file "test.js" to the page. In this case, the file
+
+<h2 id="2203">Including Custom Javascript Files</h2>
+<p>Custom Javascript files can be register using the <tt>ScriptUrl</tt> property.
+The following example includes the Javascript file "test.js" to the page. In this case, the file
"test.js" is relative the current template you are using. Since the property value is
<a href="?page=Configurations.Templates3">dynamic asset tag</a>, the file "test.js" will be published
automatically, that is, the file will be copied to the assets directory if necessary.
@@ -42,11 +42,11 @@ automatically, that is, the file will be copied to the assets directory if neces
<com:TTextHighlighter Language="prado" CssClass="source">
&lt;com:TClientScript ScriptUrl=&lt;%~ test.js %&gt; /&gt;
</com:TTextHighlighter>
-<p>You can include javascript files from other servers by specifying the full URL string in
+<p>You can include Javascript files from other servers by specifying the full URL string in
the <tt>ScriptUrl</tt> property.</p>
-<h2>Including Custom Javascript Code Blocks</h2>
+<h2 id="2204">Including Custom Javascript Code Blocks</h2>
<p> Any content within the <tt>TClientScript</tt> control tag will be considered as
- javascript code and will be rendered where it is declared.</p>
+ Javascript code and will be rendered where it is declared.</p>
</com:TContent> \ No newline at end of file
diff --git a/demos/quickstart/protected/pages/Controls/DataGrid.page b/demos/quickstart/protected/pages/Controls/DataGrid.page
index ed1ad32b..392b78ab 100644
--- a/demos/quickstart/protected/pages/Controls/DataGrid.page
+++ b/demos/quickstart/protected/pages/Controls/DataGrid.page
@@ -6,15 +6,15 @@
TDatagrid is an important control in building complex Web applications. It displays data in a tabular format with rows (also called items) and columns. A row is composed by cells, while columns govern how cells should be displayed according to their association with the columns. Data specified via <tt>DataSource</tt> or <tt>DataSourceID</tt> are bound to the rows and feed contents to cells.
</p>
<p>
-TDataGrid is highly interactive. Users can sort the data along specified columns, navigate through different pages of the data, and perform actions, such as editting and deleting, on rows of the data.
+TDataGrid is highly interactive. Users can sort the data along specified columns, navigate through different pages of the data, and perform actions, such as editing and deleting, on rows of the data.
</p>
<p>
-Rows of TDataGrid can be accessed via its <tt>Items</tt> property. A row (item) can be in one of several modes: browsing, editting and selecting, which affects how cells in the row are displayed. To change an item's mode, modify <tt>EditItemIndex</tt> or <tt>SelectedItemIndex</tt>. Note, if an item is in edit mode, then selecting this item will have no effect.
+Rows of TDataGrid can be accessed via its <tt>Items</tt> property. A row (item) can be in one of several modes: browsing, editing and selecting, which affects how cells in the row are displayed. To change an item's mode, modify <tt>EditItemIndex</tt> or <tt>SelectedItemIndex</tt>. Note, if an item is in edit mode, then selecting this item will have no effect.
</p>
<h2 id="5202">Columns</h2>
<p>
-Columns of a data grid determine how the associated cells are displayed. For example, cells associated with a <tt>TBoundColumn</tt> are displayed differently according to their modes. A cell is displayed as a static text if the cell is in browsing mode, a text box if it is in editting mode, and so on.
+Columns of a data grid determine how the associated cells are displayed. For example, cells associated with a <tt>TBoundColumn</tt> are displayed differently according to their modes. A cell is displayed as a static text if the cell is in browsing mode, a text box if it is in editing mode, and so on.
</p>
<p>
PRADO provides five types of columns:
@@ -103,7 +103,7 @@ The following example uses manually specified columns to show a list of book inf
<li>Publisher - displayed as a piece of text using <tt>TBoundColumn</tt>.</li>
<li>Price - displayed as a piece of text using <tt>TBoundColumn</tt> with output formatting string and customized styles.</li>
<li>In-stock or not - displayed as a checkbox using <tt>TCheckBoxColumn</tt>.</li>
- <li>Rating - displayed as an image using <tt>TTemplateColumn</tt> which allows maximum freedom in specifiying cell contents.</li>
+ <li>Rating - displayed as an image using <tt>TTemplateColumn</tt> which allows maximum freedom in specifying cell contents.</li>
</ul>
<p>Pay attention to how item (row) styles and column styles cooperate together to affect the appearance of the cells in the datagrid.</p>
<com:RunBar PagePath="Controls.Samples.TDataGrid.Sample2" />
@@ -111,7 +111,7 @@ The following example uses manually specified columns to show a list of book inf
<h2 id="5206">Interacting with TDataGrid</h2>
<p>
-Besides the rich data presentation functionalities as demonstrated in previous section, TDataGrid is also highly user interactive. An import usage of TDataGrid is editting or deleting rows of data. The <tt>TBoundColumn</tt> can adjust the associated cell presentation according to the mode of datagrid items. When an item is in browsing mode, the cell is displayed with a static text; when the item is in editting mode, a textbox is displayed to collect user inputs. TDataGrid provides <tt>TEditCommandColumn</tt> for switching item modes. In addition, <tt>TButtonColumn</tt> offers developers the flexibility of creating arbitrary buttons for various user interactions.
+Besides the rich data presentation functionalities as demonstrated in previous section, TDataGrid is also highly user interactive. An import usage of TDataGrid is editing or deleting rows of data. The <tt>TBoundColumn</tt> can adjust the associated cell presentation according to the mode of datagrid items. When an item is in browsing mode, the cell is displayed with a static text; when the item is in editing mode, a textbox is displayed to collect user inputs. TDataGrid provides <tt>TEditCommandColumn</tt> for switching item modes. In addition, <tt>TButtonColumn</tt> offers developers the flexibility of creating arbitrary buttons for various user interactions.
</p>
<p>
The following example shows how to make the previous book information table an interactive one. It allows users to edit and delete book items from the table. Two additional columns are used in the example to allow users interact with the datagrid: <tt>TEditCommandColumn</tt> and <tt>TButtonColumn</tt>.
diff --git a/demos/quickstart/protected/pages/Controls/DataList.page b/demos/quickstart/protected/pages/Controls/DataList.page
index c1ff1147..75541564 100644
--- a/demos/quickstart/protected/pages/Controls/DataList.page
+++ b/demos/quickstart/protected/pages/Controls/DataList.page
@@ -50,7 +50,7 @@ The following example shows how to use TDataList to display tabular data, with d
</p>
<com:RunBar PagePath="Controls.Samples.TDataList.Sample1" />
<p>
-A common use of TDataList is for maintaining tabular data, including browsing, editting, deleting data items. This is enabled by the command events and various item templates of TDataList.
+A common use of TDataList is for maintaining tabular data, including browsing, editing, deleting data items. This is enabled by the command events and various item templates of TDataList.
</p>
<p>
The following example displays a computer product information. Users can add new products, modify or delete existing ones. In order to locate the data item for updating or deleting, <tt>DataKeys</tt> property is used.
diff --git a/demos/quickstart/protected/pages/Controls/DatePicker.page b/demos/quickstart/protected/pages/Controls/DatePicker.page
index a37ff048..36d2f435 100644
--- a/demos/quickstart/protected/pages/Controls/DatePicker.page
+++ b/demos/quickstart/protected/pages/Controls/DatePicker.page
@@ -3,14 +3,14 @@
<h1 id="2301">TDatePicker</h1>
<com:DocLink ClassPath="System.Web.UI.WebControls.TDatePicker" />
-<p><tt>TDatePicker</tt> displays a text box for date input purpose.
+<p><tt>TDatePicker</tt> displays a text box for date input purpose.
When the text box receives focus, a calendar will pop up and users can
pick up from it a date that will be automatically entered into the text box.
The format of the date string displayed in the text box is determined by
the <tt>DateFormat</tt> property. Valid formats are the combination of the
following tokens:
-
-<com:TTextHighlighter Language="text" CssClass="source">
+
+<com:TTextHighlighter Language="text" CssClass="source">
Character Format Pattern (en-US)
---------------------------------------------------------------------
d day digit
@@ -32,7 +32,7 @@ only accepts integers such as the Unix timestamp.
</p>
<p>
-TDatePicker has three <tt>Mode</tt> to show the date picker popup.
+TDatePicker has three <tt>Mode</tt> to show the date picker popup.
<ul>
<li><tt>Basic</tt> - Only shows a text input, focusing on the input shows the date picker.</li>
<li><tt>Button</tt> - Shows a button next to the text input, clicking on the button shows the date, button text can be by the <tt>ButtonText</tt> property.</li>
@@ -40,8 +40,8 @@ TDatePicker has three <tt>Mode</tt> to show the date picker popup.
</ul>
</p>
-<p>The <tt>CssClass</tt> property can be used to override the css class name
-for the date picker panel. The <tt>CalendarStyle</tt> property changes the overall calendar style.
+<p>The <tt>CssClass</tt> property can be used to override the CSS class name
+for the date picker panel. The <tt>CalendarStyle</tt> property changes the overall calendar style.
The following <tt>CalendarStyle</tt> values are available:
<ul>
<li><tt>default</tt> - The default calendar style.</li>
@@ -50,9 +50,9 @@ The following <tt>CalendarStyle</tt> values are available:
<p>The <tt>InputMode</tt> property can be set to "TextBox" or "DropDownList" with
default as "TextBox". In <tt>DropDownList</tt> mode, in addition to the popup date picker, three
-drop down list (day, month and year) are presented to select the date .
+drop down list (day, month and year) are presented to select the date .
When <tt>InputMode</tt> equals "DropDownList", the order and appearance of the date, month, and year
-will depend on the pattern specified in <tt>DateFormat</tt> property.
+will depend on the pattern specified in <tt>DateFormat</tt> property.
</p>
<p>The popup date picker can be hidden by specifying <tt>ShowCalendar</tt> as false. Much of the
@@ -64,20 +64,20 @@ where <tt>FromYear</tt> is the starting year and <tt>UpToYear</tt> is the last y
The starting day of the week can be changed by the <tt>FirstDayOfWeek</tt> property, with 0 as Sunday, 1 as Monday, etc.
</p>
-<p><b>Note 1:</b> If the <tt>InputMode</tt> is "TextBox", the <tt>DateFormat</tt> should
-only <b>NOT</b> contain <code>MMM</code> or <code>MMMM</code> patterns. The
+<p><b>Note 1:</b> If the <tt>InputMode</tt> is "TextBox", the <tt>DateFormat</tt> should
+only <b>NOT</b> contain <code>MMM</code> or <code>MMMM</code> patterns. The
server side date parser will not be able to determine the correct date if <code>MMM</code> or
<code>MMMM</code> are used. When <tt>InputMode</tt> equals "DropDownList", all patterns can be used.</p>
-
+
<p><b>Note 2:</b> When the <tt>TDatePicker</tt> is used together
-with a validator, the <tt>DateFormat</tt> property of the validator must be equal to
-the <tt>DateFormat</tt> of the <tt>TDatePicker</tt> <b>AND</b> must set <tt>DataType</tt>="Date"
-on the validator to ensure correct validation. See
+with a validator, the <tt>DateFormat</tt> property of the validator must be equal to
+the <tt>DateFormat</tt> of the <tt>TDatePicker</tt> <b>AND</b> must set <tt>DataType</tt>="Date"
+on the validator to ensure correct validation. See
<a href="?page=Controls.Validation#TCompareValidator">TCompareValidator</a>,
-<a href="?page=Controls.Validation#TDataTypeValidator">TDataTypeValidator</a> and
-<a href="?page=Controls.Validation#TRangeValidator">TRangeValidator</a>
+<a href="?page=Controls.Validation#TDataTypeValidator">TDataTypeValidator</a> and
+<a href="?page=Controls.Validation#TRangeValidator">TRangeValidator</a>
for details.</p>
-
+
<com:RunBar PagePath="Controls.Samples.TDatePicker.Home" />
</com:TContent> \ No newline at end of file
diff --git a/demos/quickstart/protected/pages/Controls/HtmlArea.page b/demos/quickstart/protected/pages/Controls/HtmlArea.page
index 00a65573..e40a4444 100644
--- a/demos/quickstart/protected/pages/Controls/HtmlArea.page
+++ b/demos/quickstart/protected/pages/Controls/HtmlArea.page
@@ -24,7 +24,7 @@ The default editor gives only the basic tool bar. To change or add additional to
</com:TTextHighlighter>
<p>
-The client-side visual editting capability is supported by Internet Explorer 5.0+ for Windows and Gecko-based browser. If the browser does not support the visual editting, a traditional textarea will be displayed.
+The client-side visual editing capability is supported by Internet Explorer 5.0+ for Windows and Gecko-based browser. If the browser does not support the visual editing, a traditional textarea will be displayed.
</p>
<pre>
@@ -39,7 +39,7 @@ Firefox 1.5b2 OK OK
Safari 2.0 (412) OK(1)
Opera 9 Preview 1 OK(1) OK(1)
----------------------------------------------------
-(1) - Partialy working
+(1) - Partially working
----------------------------------------------------
</pre>
diff --git a/demos/quickstart/protected/pages/Controls/JavascriptLogger.page b/demos/quickstart/protected/pages/Controls/JavascriptLogger.page
index ccb4a27b..2c0032f8 100644
--- a/demos/quickstart/protected/pages/Controls/JavascriptLogger.page
+++ b/demos/quickstart/protected/pages/Controls/JavascriptLogger.page
@@ -4,7 +4,7 @@
<com:DocLink ClassPath="System.Web.UI.WebControls.TJavascriptLogger" />
<p>
-<tt>TJavascriptLogger</tt> provides logging for client-side javascript. It is mainly a wrapper of the javascript developed at <a href="http://gleepglop.com/javascripts/logger/">http://gleepglop.com/javascripts/logger/</a>.
+<tt>TJavascriptLogger</tt> provides logging for client-side javascript. It is mainly a wrapper of the Javascript developed at <a href="http://gleepglop.com/javascripts/logger/">http://gleepglop.com/javascripts/logger/</a>.
</p>
<p>
@@ -15,7 +15,7 @@ To use <tt>TJavascriptLogger</tt>, simply place the following component tag in a
</com:TTextHighlighter>
<p>
-Then, the client-side javascript may contain the following statements. When they are executed, they will appear in the logger window.
+Then, the client-side Javascript may contain the following statements. When they are executed, they will appear in the logger window.
</p>
<com:TTextHighlighter Language="js" CssClass="source">
Logger.info('something happend');
diff --git a/demos/quickstart/protected/pages/Controls/NewControl.page b/demos/quickstart/protected/pages/Controls/NewControl.page
index 54465ff7..5662f848 100644
--- a/demos/quickstart/protected/pages/Controls/NewControl.page
+++ b/demos/quickstart/protected/pages/Controls/NewControl.page
@@ -13,7 +13,7 @@ In general, there are two ways of writing new controls: composition of existing
Composition is the easiest way of creating new controls. It mainly involves instantiating existing controls, configuring them and making them the constituent components. The properties of the constituent components are exposed through <a href="?page=Fundamentals.Components">subproperties</a>.
</p>
<p>
-One can compose a new control in two ways. One is to extend <tt>TCompositeControl</tt> and override the <tt>TControl::createChildControls()</tt> method. The other is to extend <tt>TTemplateControl</tt> (or its child classes) and write a control template. The latter is easier to use and can organize the layout constituent compoents more intuitively, while the former is more efficient because it does not require parsing of the template.
+One can compose a new control in two ways. One is to extend <tt>TCompositeControl</tt> and override the <tt>TControl::createChildControls()</tt> method. The other is to extend <tt>TTemplateControl</tt> (or its child classes) and write a control template. The latter is easier to use and can organize the layout constituent components more intuitively, while the former is more efficient because it does not require parsing of the template.
</p>
<p>
As an example, we show how to create a labeled textbox called <tt>LabeledTextBox</tt> using the above two approaches. A labeled textbox displays a label besides a textbox. We want reuse the PRADO provided <tt>TLabel</tt> and <tt>TTextBox</tt> to accomplish this task.
@@ -130,8 +130,8 @@ Other important properties and methods include:
<tt>TWebControl</tt> is mainly used as a base class for controls representing HTML elements. It provides a set of properties that are common among HTML elements. It breaks the <tt>TControl::render()</tt> into the following methods that are more suitable for rendering an HTML element:
</p>
<ul>
- <li><tt>addAttributesToRender()</tt> - adds attributes for the HTML element to be rendered. This method is often overriden by derived classes as they usually have different attributes to be rendered.</li>
- <li><tt>renderBeginTag()</tt> - renders the openning HTML tag.</li>
+ <li><tt>addAttributesToRender()</tt> - adds attributes for the HTML element to be rendered. This method is often overridden by derived classes as they usually have different attributes to be rendered.</li>
+ <li><tt>renderBeginTag()</tt> - renders the opening HTML tag.</li>
<li><tt>renderContents()</tt> - renders the content enclosed within the HTML element. By default, it displays the items in the <tt>Controls</tt> collection of the control. Derived classes may override this method to render customized contents.</li>
<li><tt>renderEndTag()</tt> - renders the closing HTML tag.</li>
</ul>
diff --git a/demos/quickstart/protected/pages/Controls/Panel.page b/demos/quickstart/protected/pages/Controls/Panel.page
index d507da36..be36095b 100644
--- a/demos/quickstart/protected/pages/Controls/Panel.page
+++ b/demos/quickstart/protected/pages/Controls/Panel.page
@@ -4,7 +4,7 @@
<com:DocLink ClassPath="System.Web.UI.WebControls.TPanel" />
<p>
-<tt>TPanel</tt> acts as a presentational container for other control. It displays a &lt;div&gt; element on a page. The property <tt>Wrap</tt> specifies whether the panel's body content should wrap or not, while <tt>HorizontalAlign</tt> governs how the content is aligned horizontally and <tt>Direction</tt> indicates the content direction (left to right or right to left). You can set <tt>BackImageUrl</tt> to give a background image to the panel, and you can ste <tt>GroupingText</tt> so that the panel is displayed as a field set with a legend text. Finally, you can specify a default button to be fired when users press 'return' key within the panel by setting the <tt>DefaultButton</tt> property.
+<tt>TPanel</tt> acts as a presentational container for other control. It displays a &lt;div&gt; element on a page. The property <tt>Wrap</tt> specifies whether the panel's body content should wrap or not, while <tt>HorizontalAlign</tt> governs how the content is aligned horizontally and <tt>Direction</tt> indicates the content direction (left to right or right to left). You can set <tt>BackImageUrl</tt> to give a background image to the panel, and you can set <tt>GroupingText</tt> so that the panel is displayed as a field set with a legend text. Finally, you can specify a default button to be fired when users press 'return' key within the panel by setting the <tt>DefaultButton</tt> property.
</p>
<com:RunBar PagePath="Controls.Samples.TPanel.Home" />
diff --git a/demos/quickstart/protected/pages/Controls/Repeater.page b/demos/quickstart/protected/pages/Controls/Repeater.page
index 795e27aa..d8f3fd0a 100644
--- a/demos/quickstart/protected/pages/Controls/Repeater.page
+++ b/demos/quickstart/protected/pages/Controls/Repeater.page
@@ -5,7 +5,7 @@
TRepeater displays its content defined in templates repeatedly based on the given data specified by the <tt>DataSource</tt> or <tt>DataSourceID</tt> property. The repeated contents can be retrieved from the <tt>Items</tt> property. Each item is created by instantiating a template and each is a child control of the repeater.
</p>
<p>
-Like normal control templates, the repeater templates can contain static text, controls and special tags, which after instantiation, become child contents of the corresponding item. TRepeater defiens five templates for different purposes,
+Like normal control templates, the repeater templates can contain static text, controls and special tags, which after instantiation, become child contents of the corresponding item. TRepeater defines five templates for different purposes,
</p>
<ul>
<li><tt>HeaderTemplate</tt> - the template used for displaying content at the beginning of a repeater;</li>
diff --git a/demos/quickstart/protected/pages/Controls/Validation.page b/demos/quickstart/protected/pages/Controls/Validation.page
index a28c8faf..12836b8c 100644
--- a/demos/quickstart/protected/pages/Controls/Validation.page
+++ b/demos/quickstart/protected/pages/Controls/Validation.page
@@ -26,7 +26,7 @@ Validators share a common set of properties, which are defined in the base class
<li><tt>Dynamic</tt> - the space for displaying the error message is NOT reserved. Therefore, showing up the error message will shift the layout of your page around (usually down).</li>
</ul>
</li>
-<li><tt>ControlCssClass</tt> - the Css class that is applied to the control being validated in case the validation fails.</li>
+<li><tt>ControlCssClass</tt> - the CSS class that is applied to the control being validated in case the validation fails.</li>
<li><tt>FocusOnError</tt> - set focus at the validating place if the validation fails. Defaults to false.</li>
<li><tt>FocusElementID</tt> - the ID of the HTML element that will receive focus if validation fails and <tt>FocusOnError</tt> is true.</li>
</ul>
@@ -71,7 +71,7 @@ TEmailAddressValidator verifies that the user input is a valid email address. Th
Note, if the input being validated is empty, TEmailAddressValidator will not do validation. Use a TRequiredFieldValidator to ensure the value is not empty.
</p>
<com:RunBar PagePath="Controls.Samples.TEmailAddressValidator.Home" />
-
+
<a name="TCompareValidator"></a>
<h2 id="4904">TCompareValidator</h2>
<p>
diff --git a/demos/quickstart/protected/pages/Controls/Wizard.page b/demos/quickstart/protected/pages/Controls/Wizard.page
index ce8bc774..fe910aa7 100644
--- a/demos/quickstart/protected/pages/Controls/Wizard.page
+++ b/demos/quickstart/protected/pages/Controls/Wizard.page
@@ -74,15 +74,15 @@ In this sample, we use wizard to collect user's preference of color. In the firs
Given a set of wizard steps, <tt>TWizard</tt> supports three different ways of navigation among them:
</p>
<ul>
- <li>Bidirectional - Users can navigate forward and backward along a sequence of wizard steps. User input data is usally collected at the last step. This is also known as commit-at-the-end model. It is the default navigation way that <tt>TWizard</tt> supports.</li>
- <li>Unidirectional - Users can navigate forward along a sequence of wizard steps. Backward move is not allowed. User input data is usally collected step by step. This is also known as command-as-you-go model. To disallow backward move to a specific step, set its <tt>AllowReturn</tt> property to false.</li>
+ <li>Bidirectional - Users can navigate forward and backward along a sequence of wizard steps. User input data is usually collected at the last step. This is also known as commit-at-the-end model. It is the default navigation way that <tt>TWizard</tt> supports.</li>
+ <li>Unidirectional - Users can navigate forward along a sequence of wizard steps. Backward move is not allowed. User input data is usually collected step by step. This is also known as command-as-you-go model. To disallow backward move to a specific step, set its <tt>AllowReturn</tt> property to false.</li>
<li>Nonlinear - User input in a step determines which step to go next. To do so, set <tt>ActiveStepIndex</tt> to the step that you want the user to go to. In this case, when a user clicks on the previous button in the navigation panel, the previous step that they visited (not the previous step in the sequential order) will become visible.</li>
</ul>
<com:RunBar PagePath="Controls.Samples.TWizard.Sample3" />
<h3 id="4707">Using Templates in Wizard</h3>
<p>
-<tt>TWizard</tt> supports more concrete control of its outlook through templating. In particular, it provides the following template properties that allow complete customization of the wizard's header, navigation and side bar.
+<tt>TWizard</tt> supports more concrete control of its outlook through templates. In particular, it provides the following template properties that allow complete customization of the wizard's header, navigation and side bar.
</p>
<ul>
<li>Header - <tt>HeaderTemplate</tt>.</li>
diff --git a/demos/quickstart/protected/pages/GettingStarted/Introduction.page b/demos/quickstart/protected/pages/GettingStarted/Introduction.page
index 42ee0dad..e52f4acf 100644
--- a/demos/quickstart/protected/pages/GettingStarted/Introduction.page
+++ b/demos/quickstart/protected/pages/GettingStarted/Introduction.page
@@ -1,7 +1,7 @@
<com:TContent ID="body" >
-<h1 id="101">Welcome to the PRADO QuickStart Tutorial</h1>
+<h1 id="101">Welcome to the PRADO Quickstart Tutorial</h1>
<p>
-This QuickStart tutorial is provided to help you quickly start building your own Web applications based on PRADO version 3.0.
+This Quickstart tutorial is provided to help you quickly start building your own Web applications based on PRADO version 3.0.
</p>
<p>
You may refer to the following resources if you find this tutorial does not fulfill all your needs.
diff --git a/demos/quickstart/protected/pages/Search.page b/demos/quickstart/protected/pages/Search.page
index ae7f07bc..43c0cce4 100644
--- a/demos/quickstart/protected/pages/Search.page
+++ b/demos/quickstart/protected/pages/Search.page
@@ -7,11 +7,11 @@
<com:TRepeater id="quickstart_results">
<prop:HeaderTemplate>
<div class="searchHeader">
- Found <%# $this->Parent->Data->Count %> results in quickstart tutorial.
+ Found <%# $this->Parent->Data->Count %> results in the Quickstart Tutorial.
</div>
</prop:HeaderTemplate>
<prop:ItemTemplate>
- <div class="searchItem">
+ <div class="searchItem">
<div class="searchItemLink">
<%# $this->ItemIndex + 1 %>.
<a href="<%# $this->DataItem->link %>">
@@ -25,5 +25,5 @@
<com:TPanel id="emptyResult" CssClass="empty_search_result" Visible="false">
No results available for "<%= htmlentities($this->Page->search->Text) %>".
</com:TPanel>
-</div>
+</div>
</com:TContent> \ No newline at end of file
diff --git a/framework/Web/UI/TControl.php b/framework/Web/UI/TControl.php
index 34aeb85e..aa8ea2a3 100644
--- a/framework/Web/UI/TControl.php
+++ b/framework/Web/UI/TControl.php
@@ -453,6 +453,28 @@ class TControl extends TApplicationComponent implements IRenderable, IBindable
}
/**
+ * Returns custom data associated with this control.
+ * A control may be associated with some custom data for various purposes.
+ * For example, a button may be associated with a string to identify itself
+ * in a generic OnClick event handler.
+ * @return mixed custom data associated with this control. Defaults to null.
+ */
+ public function getCustomData()
+ {
+ return $this->getViewState('CustomData',null);
+ }
+
+ /**
+ * Associates custom data with this control.
+ * Note, the custom data must be serializable and unserializable.
+ * @param mixed custom data
+ */
+ public function setCustomData($value)
+ {
+ $this->getViewState('CustomData',$value,null);
+ }
+
+ /**
* @return boolean whether the control has child controls
*/
public function getHasControls()
diff --git a/framework/Web/UI/TPage.php b/framework/Web/UI/TPage.php
index 8839e6a2..22aee89f 100644
--- a/framework/Web/UI/TPage.php
+++ b/framework/Web/UI/TPage.php
@@ -157,6 +157,7 @@ class TPage extends TTemplateControl
/**
* Constructor.
* Sets the page object to itself.
+ * Derived classes must call parent implementation.
*/
public function __construct()
{
diff --git a/framework/Web/UI/WebControls/TCheckBox.php b/framework/Web/UI/WebControls/TCheckBox.php
index 04733f95..c938950d 100644
--- a/framework/Web/UI/WebControls/TCheckBox.php
+++ b/framework/Web/UI/WebControls/TCheckBox.php
@@ -143,7 +143,7 @@ class TCheckBox extends TWebControl implements IPostBackDataHandler, IValidatabl
*/
public function setValue($value)
{
- $this->setViewState('Value',$value,'');
+ $this->setViewState('Value',TPropertyValue::ensureString($value),'');
}
/**
diff --git a/framework/Web/UI/WebControls/TClientScript.php b/framework/Web/UI/WebControls/TClientScript.php
index 88f7f7d4..ff236c42 100644
--- a/framework/Web/UI/WebControls/TClientScript.php
+++ b/framework/Web/UI/WebControls/TClientScript.php
@@ -31,11 +31,6 @@
* Contents within TClientScript will be treated as javascript code and will be
* rendered in place.
*
- * The {@link setPreRenderControlTypes PreRenderControlTypes} property can
- * be used to specify that controls type/class names that should pre-render itself
- * even though they may not be rendered on the page. This is useful to publish
- * controls that require assets and is only visible after a callback response.
- *
* @author Wei Zhuo <weizhuo[at]gmail[dot]com>
* @version $Revision: $ $Date: $
* @package System.Web.UI.WebControls
@@ -82,23 +77,6 @@ class TClientScript extends TControl
}
/**
- * @param string comma delimited list of controls that wish to be prerendered
- * so as to publish its assets.
- */
- public function setPreRenderControlTypes($value)
- {
- $this->setViewState('PreRenderControls', $value);
- }
-
- /**
- * @return string comma delimited list of controls types that require prerendering.
- */
- public function getPreRenderControlTypes()
- {
- return $this->getViewState('PreRenderControls', '');
- }
-
- /**
* Calls the client script manager to add each of the requested client
* script libraries.
* @param mixed event parameter
@@ -113,7 +91,6 @@ class TClientScript extends TControl
if(($script = trim($script))!=='')
$cs->registerPradoScript($script);
}
- $this->preRenderControls($param);
}
/**
@@ -151,25 +128,6 @@ class TClientScript extends TControl
$writer->write("\n/*]]>*/\n</script>\n");
}
}
-
- /**
- * PreRender other controls to allow them to publish their assets. Useful
- * when callback response components that require assets to be present on the page.
- * @param mixed event paramater
- */
- protected function preRenderControls($param)
- {
- $types = preg_split('/,|\s+/', $this->getPreRenderControlTypes());
- foreach($types as $type)
- {
- if(strlen($type))
- {
- $control = Prado::createComponent(trim($type));
- $control->setPage($this->getPage());
- $control->onPreRender($param);
- }
- }
- }
}
?>
diff --git a/framework/Web/UI/WebControls/TCustomValidator.php b/framework/Web/UI/WebControls/TCustomValidator.php
index 32510f89..2afa48dc 100644
--- a/framework/Web/UI/WebControls/TCustomValidator.php
+++ b/framework/Web/UI/WebControls/TCustomValidator.php
@@ -120,6 +120,16 @@ class TCustomValidator extends TBaseValidator
$options['ClientValidationFunction']=$clientJs;
return $options;
}
+
+ /**
+ * Only register the client-side validator if
+ * {@link setClientValidationFunction ClientValidationFunction} is set.
+ */
+ protected function registerClientScriptValidator()
+ {
+ if($this->getClientValidationFunction()!=='')
+ parent::registerClientScriptValidator();
+ }
}
/**
diff --git a/framework/Web/UI/WebControls/TRadioButton.php b/framework/Web/UI/WebControls/TRadioButton.php
index 974a431c..244244cb 100644
--- a/framework/Web/UI/WebControls/TRadioButton.php
+++ b/framework/Web/UI/WebControls/TRadioButton.php
@@ -56,39 +56,44 @@ Prado::using('System.Web.UI.WebControls.TRadioButtonList');
class TRadioButton extends TCheckBox
{
/**
- * @param array list of radio buttons registered.
+ * @param array list of radio buttons that are on the current page hierarchy
*/
- private static $_radiobuttons=array();
+ private static $_activeButtons=array();
/**
- * @var string the name used to fetch radiobutton post data
+ * @var integer number of radio buttons created
*/
- private $_uniqueGroupName=null;
+ private static $_buttonCount=0;
/**
- * @var int number radio buttons created
+ * @var integer global ID of this radiobutton
*/
- private static $_counter=0;
+ private $_globalID;
/**
- * @var int unique unmutable radio button id
+ * @var string the name used to fetch radiobutton post data
*/
- private $_radioUid;
+ private $_uniqueGroupName=null;
+ /**
+ * Constructor.
+ * Registers the radiobutton in a global radiobutton collection.
+ * If overridden, the parent implementation must be invoked first.
+ */
public function __construct()
{
parent::__construct();
- $this->_radioUid = self::$_counter++;
+ $this->_globalID = self::$_buttonCount++;
}
-
+
/**
- * Registers the radio button groupings. If overriding onInit method,
+ * Registers the radio button groupings. If overriding onInit method,
* ensure to call parent implemenation.
* @param TEventParameter event parameter to be passed to the event handlers
*/
public function onInit($param)
{
parent::onInit($param);
- $this->registerRadioButton($this);
+ self::$_activeButtons[$this->_globalID]=$this;
}
-
+
/**
* Unregisters the radio button groupings. If overriding onInit method,
* ensure to call parent implemenation.
@@ -96,10 +101,10 @@ class TRadioButton extends TCheckBox
*/
public function onUnLoad($param)
{
+ unset(self::$_activeButtons[$this->_globalID]);
parent::onUnLoad($param);
- $this->unregisterRadioButton($this);
}
-
+
/**
* Loads user input data.
* This method is primarly used by framework developers.
@@ -142,42 +147,23 @@ class TRadioButton extends TCheckBox
{
$this->setViewState('GroupName',$value,'');
}
-
- /**
- * Register radio button control grouping.
- * @param TRadioButton control to add
- */
- protected function registerRadioButton(TRadioButton $control)
- {
- if(!isset(self::$_radiobuttons[$control->_radioUid]))
- self::$_radiobuttons[$control->_radioUid] = $control;
- }
-
+
/**
- * Unregister radio button control for grouping
- * @param TRadioButton control to unregister.
- */
- protected function unregisterRadioButton(TRadioButton $control)
- {
- if(isset(self::$_radiobuttons[$control->_radioUid]))
- unset(self::$_radiobuttons[$control->_radioUid]);
- }
-
- /**
- * Gets an array of RadioButtons with same group name. This method will
- * always return at least the current radio button in the array.
+ * Gets an array of radiobuttons whose group name is the same as this radiobutton's.
+ * Note, only those radiobuttons that are on the current page hierarchy may be
+ * returned in the result.
* @return array list of TRadioButton with the same group
*/
public function getRadioButtonsInGroup()
{
$group = $this->getUniqueGroupName();
$buttons = array();
- foreach(self::$_radiobuttons as $control)
+ foreach(self::$_activeButtons as $control)
{
if($control->getUniqueGroupName() === $group)
$buttons[] = $control;
}
- return count($buttons) > 0 ? $buttons : array($this);
+ return $buttons;
}
/**
diff --git a/framework/Web/UI/WebControls/TTextHighlighter.php b/framework/Web/UI/WebControls/TTextHighlighter.php
index a9ccf5bb..f4e72895 100644
--- a/framework/Web/UI/WebControls/TTextHighlighter.php
+++ b/framework/Web/UI/WebControls/TTextHighlighter.php
@@ -136,7 +136,7 @@ class TTextHighlighter extends TTextProcessor
$geshi->enable_classes();
if($this->getEnableCopyCode())
$geshi->set_header_content($this->getHeaderTemplate());
-
+
return $geshi->parse_code();
}
diff --git a/tests/FunctionalTests/tickets/protected/pages/Ticket284.page b/tests/FunctionalTests/tickets/protected/pages/Ticket284.page
new file mode 100644
index 00000000..ff25e3fb
--- /dev/null
+++ b/tests/FunctionalTests/tickets/protected/pages/Ticket284.page
@@ -0,0 +1,14 @@
+<com:TContent ID="Content">
+
+
+<com:Application.pages.Ticket284Component ID="fooBar" ShowHours="true" ShowMinutes="true" />
+<com:TCustomValidator
+ ControlToValidate="fooBar"
+ OnServerValidate="checkUserAvailability"
+ Display="Dynamic"
+ Text="Unavailable."
+ CssClass="inlineError" />
+<com:TButton Text="POST it!" />
+
+</com:TContent>
+
diff --git a/tests/FunctionalTests/tickets/protected/pages/Ticket284.php b/tests/FunctionalTests/tickets/protected/pages/Ticket284.php
new file mode 100644
index 00000000..332789ff
--- /dev/null
+++ b/tests/FunctionalTests/tickets/protected/pages/Ticket284.php
@@ -0,0 +1,11 @@
+<?php
+
+class Ticket284 extends TPage
+{
+ function checkUserAvailability()
+ {
+
+ }
+}
+
+?> \ No newline at end of file
diff --git a/tests/FunctionalTests/tickets/protected/pages/Ticket284Component.php b/tests/FunctionalTests/tickets/protected/pages/Ticket284Component.php
new file mode 100644
index 00000000..892bdc87
--- /dev/null
+++ b/tests/FunctionalTests/tickets/protected/pages/Ticket284Component.php
@@ -0,0 +1,94 @@
+<?php
+
+class Ticket284Component extends TTemplateControl implements IValidatable
+{
+ public function onPreRender($param)
+ {
+ if (!$this->ShowHours && $this->ShowMinutes)
+ {
+ throw new TConfigurationException(
+ 'Invalid OPSDatePicker Config: You cannot specify ShowMinutes="true" while ShowHours="false"'
+ );
+ }
+ }
+
+ public function getDatePicker()
+ {
+ $this->ensureChildControls();
+ return $this->getRegisteredObject('datePicker');
+ }
+
+ public function getHourPicker()
+ {
+ $this->ensureChildControls();
+ return $this->getRegisteredObject('hourPicker');
+ }
+
+ public function getMinutePicker()
+ {
+ $this->ensureChildControls();
+ return $this->getRegisteredObject('minutePicker');
+ }
+
+ public function getShowHours()
+ {
+ return $this->HourPicker->Visible;
+ }
+
+ public function setShowHours($value)
+ {
+ $this->HourPicker->Visible = TPropertyValue::ensureBoolean($value);
+ }
+
+ public function getShowMinutes()
+ {
+ return $this->MinutePicker->Visible;
+ }
+
+ public function setShowMinutes($value)
+ {
+ $this->MinutePicker->Visible = TPropertyValue::ensureBoolean($value);
+ }
+
+ public function getTimeStamp()
+ {
+ return strtotime($this->Date);
+ }
+
+ public function setTimeStamp($value)
+ {
+ $ts = TPropertyValue::ensureInteger($value);
+ $this->DatePicker->TimeStamp = $ts;
+ $this->HourPicker->SelectedValue = date('H', $ts);
+ $this->MinutePicker->SelectedValue = date('i', $ts);
+ }
+
+ public function getDate()
+ {
+ $dateStr = $this->DatePicker->Date;
+ if ($this->ShowHours){
+ $dateStr .= ' '.$this->HourPicker->SelectedValue;
+ }
+ if ($this->ShowMinutes){
+ $dateStr .= ':'.$this->MinutePicker->SelectedValue;
+ }
+ return $dateStr;
+ }
+
+ public function setDate($value)
+ {
+ $dateStr = TPropertyValue::ensureString($value);
+ $this->TimeStamp = strtotime($dateStr);
+ }
+
+ public function getValidationPropertyValue()
+ {
+ if ($this->DatePicker->Date === ''){
+ return '';
+ }
+ else{
+ return $this->TimeStamp;
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/tests/FunctionalTests/tickets/protected/pages/Ticket284Component.tpl b/tests/FunctionalTests/tickets/protected/pages/Ticket284Component.tpl
new file mode 100644
index 00000000..ed787287
--- /dev/null
+++ b/tests/FunctionalTests/tickets/protected/pages/Ticket284Component.tpl
@@ -0,0 +1,94 @@
+<com:TDatePicker ID="datePicker"
+ Style.width="68px"
+ Mode="ImageButton"
+ DateFormat="MM/dd/yyyy" />
+
+<com:TDropDownList ID="hourPicker" Style.width="40px" Visible="false">
+ <com:TListItem Text="00" Value="00" />
+ <com:TListItem Text="01" Value="01" />
+ <com:TListItem Text="02" Value="02" />
+ <com:TListItem Text="03" Value="03" />
+ <com:TListItem Text="04" Value="04" />
+ <com:TListItem Text="05" Value="05" />
+ <com:TListItem Text="06" Value="06" />
+ <com:TListItem Text="07" Value="07" />
+ <com:TListItem Text="08" Value="08" />
+ <com:TListItem Text="09" Value="09" />
+ <com:TListItem Text="10" Value="10" />
+ <com:TListItem Text="11" Value="11" />
+ <com:TListItem Text="12" Value="12" />
+ <com:TListItem Text="13" Value="13" />
+ <com:TListItem Text="14" Value="14" />
+ <com:TListItem Text="15" Value="15" />
+ <com:TListItem Text="16" Value="16" />
+ <com:TListItem Text="17" Value="17" />
+ <com:TListItem Text="18" Value="18" />
+ <com:TListItem Text="19" Value="19" />
+ <com:TListItem Text="20" Value="20" />
+ <com:TListItem Text="21" Value="21" />
+ <com:TListItem Text="22" Value="22" />
+ <com:TListItem Text="23" Value="23" />
+</com:TDropDownList>
+
+<com:TDropDownList ID="minutePicker" Style.width="40px" Visible="false">
+ <com:TListItem Text="00" Value="00" />
+ <com:TListItem Text="01" Value="01" />
+ <com:TListItem Text="02" Value="02" />
+ <com:TListItem Text="03" Value="03" />
+ <com:TListItem Text="04" Value="04" />
+ <com:TListItem Text="05" Value="05" />
+ <com:TListItem Text="06" Value="06" />
+ <com:TListItem Text="07" Value="07" />
+ <com:TListItem Text="08" Value="08" />
+ <com:TListItem Text="09" Value="09" />
+ <com:TListItem Text="10" Value="10" />
+ <com:TListItem Text="11" Value="11" />
+ <com:TListItem Text="12" Value="12" />
+ <com:TListItem Text="13" Value="13" />
+ <com:TListItem Text="14" Value="14" />
+ <com:TListItem Text="15" Value="15" />
+ <com:TListItem Text="16" Value="16" />
+ <com:TListItem Text="17" Value="17" />
+ <com:TListItem Text="18" Value="18" />
+ <com:TListItem Text="19" Value="19" />
+ <com:TListItem Text="20" Value="20" />
+ <com:TListItem Text="21" Value="21" />
+ <com:TListItem Text="22" Value="22" />
+ <com:TListItem Text="23" Value="23" />
+ <com:TListItem Text="24" Value="24" />
+ <com:TListItem Text="25" Value="25" />
+ <com:TListItem Text="26" Value="26" />
+ <com:TListItem Text="27" Value="27" />
+ <com:TListItem Text="28" Value="28" />
+ <com:TListItem Text="29" Value="29" />
+ <com:TListItem Text="30" Value="30" />
+ <com:TListItem Text="31" Value="31" />
+ <com:TListItem Text="32" Value="32" />
+ <com:TListItem Text="33" Value="33" />
+ <com:TListItem Text="34" Value="34" />
+ <com:TListItem Text="35" Value="35" />
+ <com:TListItem Text="36" Value="36" />
+ <com:TListItem Text="37" Value="37" />
+ <com:TListItem Text="38" Value="38" />
+ <com:TListItem Text="39" Value="39" />
+ <com:TListItem Text="40" Value="40" />
+ <com:TListItem Text="41" Value="41" />
+ <com:TListItem Text="42" Value="42" />
+ <com:TListItem Text="43" Value="43" />
+ <com:TListItem Text="44" Value="44" />
+ <com:TListItem Text="45" Value="45" />
+ <com:TListItem Text="46" Value="46" />
+ <com:TListItem Text="47" Value="47" />
+ <com:TListItem Text="48" Value="48" />
+ <com:TListItem Text="49" Value="49" />
+ <com:TListItem Text="50" Value="50" />
+ <com:TListItem Text="51" Value="51" />
+ <com:TListItem Text="52" Value="52" />
+ <com:TListItem Text="53" Value="53" />
+ <com:TListItem Text="54" Value="54" />
+ <com:TListItem Text="55" Value="55" />
+ <com:TListItem Text="56" Value="56" />
+ <com:TListItem Text="57" Value="57" />
+ <com:TListItem Text="58" Value="58" />
+ <com:TListItem Text="59" Value="59" />
+</com:TDropDownList> \ No newline at end of file
diff --git a/tests/FunctionalTests/tickets/tests/Ticket284TestCase.php b/tests/FunctionalTests/tickets/tests/Ticket284TestCase.php
new file mode 100644
index 00000000..9a6fa7c3
--- /dev/null
+++ b/tests/FunctionalTests/tickets/tests/Ticket284TestCase.php
@@ -0,0 +1,14 @@
+<?php
+
+class Ticket284TestCase extends SeleniumTestCase
+{
+ function test()
+ {
+ $this->open('tickets/index.php?page=Ticket284');
+ $this->assertTextPresent('Verifying Ticket 284');
+ $this->click('ctl0_Content_ctl1');
+
+ }
+}
+
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/CHANGELOG b/tests/test_tools/simpletest/CHANGELOG
index 961ce208..a7f890c5 100755
--- a/tests/test_tools/simpletest/CHANGELOG
+++ b/tests/test_tools/simpletest/CHANGELOG
@@ -2,5 +2,5 @@ June 7, 2005, by Qiang Xue (qiang.xue@gmail.com)
------------------------------------------------
- changed all class memeber declarations from 'var $varname' to 'private $varname'.
- removed all reference usages, including creating new objects, returning and passing objects.
-- modified expectation.php line 106 from 'function test($compare, &$nasty=false) {' to 'function test($compare) {'.
+- modified expectation.php line 106 from 'function test($compare, $nasty=false) {' to 'function test($compare) {'.
- added HtmlReporterWithCoverage.php \ No newline at end of file
diff --git a/tests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE b/tests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE
index 99c3be2d..4be59649 100755
--- a/tests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE
+++ b/tests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE
@@ -3,7 +3,116 @@ Simple Test interface changes
Because the SimpleTest tool set is still evolving it is likely that tests
written with earlier versions will fail with the newest ones. The most
dramatic changes are in the alpha releases. Here is a list of possible
-problems...
+problems and their fixes...
+
+Failure to connect now emits failures
+-------------------------------------
+It used to be that you would have to use the
+getTransferError() call on the web tester to see if
+there was a socket level error in a fetch. This check
+is now always carried out by the WebTestCase unless
+the fetch is prefaced with WebTestCase::ignoreErrors().
+The ignore directive only lasts for test case fetching
+action such as get() and click().
+
+No method SimpleTestOptions::ignore()
+-------------------------------------
+This is deprecated in version 1.0.1beta and has been moved
+to SimpleTest::ignore() as that is more readable. In
+addition, parent classes are also ignored automatically.
+If you are using PHP5 you can skip this directive simply
+by marking your test case as abstract.
+
+No method assertCopy()
+----------------------
+This is deprecated in 1.0.1 in favour of assertClone().
+The assertClone() method is slightly different in that
+the objects must be identical, but without being a
+reference. It is thus not a strict inversion of
+assertReference().
+
+Constructor wildcard override has no effect in mocks
+----------------------------------------------------
+As of 1.0.1beta this is now set with setWildcard() instead
+of in the constructor.
+
+No methods setStubBaseClass()/getStubBaseClass()
+------------------------------------------------
+As mocks are now used instead of stubs, these methods
+stopped working and are now removed as of the 1.0.1beta
+release. The mock objects may be freely used instead.
+
+No method addPartialMockCode()
+------------------------------
+The ability to insert arbitrary partial mock code
+has been removed. This was a low value feature
+causing needless complications.It was removed
+in the 1.0.1beta release.
+
+No method setMockBaseClass()
+----------------------------
+The ability to change the mock base class has been
+scheduled for removal and is deprecated since the
+1.0.1beta version. This was a rarely used feature
+except as a workaround for PHP5 limitations. As
+these limitations are being resolved it's hoped
+that the bundled mocks can be used directly.
+
+No class Stub
+-------------
+Server stubs are deprecated from 1.0.1 as the mocks now
+have exactly the same interface. Just use mock objects
+instead.
+
+No class SimpleTestOptions
+--------------------------
+This was replced by the shorter SimpleTest in 1.0.1beta1
+and is since deprecated.
+
+No file simple_test.php
+-----------------------
+This was renamed test_case.php in 1.0.1beta to more accurately
+reflect it's purpose. This file should never be directly
+included in test suites though, as it's part of the
+underlying mechanics and has a tendency to be refactored.
+
+No class WantedPatternExpectation
+---------------------------------
+This was deprecated in 1.0.1alpha in favour of the simpler
+name PatternExpectation.
+
+No class NoUnwantedPatternExpectation
+-------------------------------------
+This was deprecated in 1.0.1alpha in favour of the simpler
+name NoPatternExpectation.
+
+No method assertNoUnwantedPattern()
+-----------------------------------
+This has been renamed to assertNoPattern() in 1.0.1alpha and
+the old form is deprecated.
+
+No method assertWantedPattern()
+-------------------------------
+This has been renamed to assertPattern() in 1.0.1alpha and
+the old form is deprecated.
+
+No method assertExpectation()
+-----------------------------
+This was renamed as assert() in 1.0.1alpha and the old form
+has been deprecated.
+
+No class WildcardExpectation
+----------------------------
+This was a mostly internal class for the mock objects. It was
+renamed AnythingExpectation to bring it closer to JMock and
+NMock in version 1.0.1alpha.
+
+Missing UnitTestCase::assertErrorPattern()
+------------------------------------------
+This method is deprecated for version 1.0.1 onwards.
+This method has been subsumed by assertError() that can now
+take an expectation. Simply pass a PatternExpectation
+into assertError() to simulate the old behaviour.
No HTML when matching page elements
-----------------------------------
@@ -29,7 +138,9 @@ My custom test case ignored by tally()
--------------------------------------
The _assertTrue method has had it's signature changed due to a bug
in the PHP 5.0.1 release. You must now use getTest() from within
-that method to get the test case.
+that method to get the test case. Mock compatibility with other
+unit testers is now deprecated as of 1.0.1alpha as PEAR::PHUnit2
+should soon have mock support of it's own.
Broken code extending SimpleRunner
----------------------------------
@@ -142,13 +253,13 @@ test case expansion against the ease of writing user interfaces.
Code such as...
-$test = &new MyTestCase();
+$test = new MyTestCase();
$test->attachObserver(new TestHtmlDisplay());
$test->run();
...should be rewritten as...
-$test = &new MyTestCase();
+$test = new MyTestCase();
$test->run(new HtmlReporter());
If you previously attached multiple observers then the workaround
diff --git a/tests/test_tools/simpletest/LICENSE b/tests/test_tools/simpletest/LICENSE
index 93acab79..4a1f7201 100755
--- a/tests/test_tools/simpletest/LICENSE
+++ b/tests/test_tools/simpletest/LICENSE
@@ -1,49 +1,502 @@
-The Open Group Test Suite License
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
-Preamble
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
-The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications.
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
-Testing is essential for proper development and maintenance of standards-based products.
+ Preamble
-For buyers: adequate conformance testing leads to reduced integration costs and protection of investments in applications, software and people.
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
-For software developers: conformance testing of platforms and middleware greatly reduces the cost of developing and maintaining multi-platform application software.
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
-For suppliers: In-depth testing increases customer satisfaction and keeps development and support costs in check. API conformance is highly measurable and suppliers who claim it must be able to substantiate that claim.
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
-As such, since these are benchmark measures of conformance, we feel the integrity of test tools is of importance. In order to preserve the integrity of the existing conformance modes of this test package and to permit recipients of modified versions of this package to run the original test modes, this license requires that the original test modes be preserved.
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
-If you find a bug in one of the standards mode test cases, please let us know so we can feed this back into the original, and also raise any specification issues with the appropriate bodies (for example the POSIX committees).
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
-Definitions:
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
- * "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification.
- * "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder.
- * "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package.
- * "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.)
-* "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it.
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
-1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers.
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
-2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version.
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
-3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least the following:
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
-rename any non-standard executables and testcases so the names do not conflict with standard executables and testcases, which must also be provided, and provide a separate manual page for each non-standard executable and testcase that clearly documents how it differs from the Standard Version.
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
-4. You may distribute the programs of this Package in object code or executable form, provided that you do at least the following:
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
-accompany any non-standard executables and testcases with their corresponding Standard Version executables and testcases, giving the non-standard executables and testcases non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version.
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
-5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own.
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
-6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package.
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
-7.Subroutines supplied by you and linked into this Package shall not be considered part of this Package.
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission.
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
-9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
-The End
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/tests/test_tools/simpletest/README b/tests/test_tools/simpletest/README
index 50fa4aaa..c2ff9b75 100755
--- a/tests/test_tools/simpletest/README
+++ b/tests/test_tools/simpletest/README
@@ -21,12 +21,6 @@ A web tester similar in concept to JWebUnit is also included. There is no
JavaScript or tables support, but forms, authentication, cookies and
frames are handled.
-You are not tied to just using SimpleTest, though. The mocks and stubs
-will work with other test frameworks and SimpleTest can use other
-framework's (PHPUnit, PEAR::PhpUnit) test cases as it's own. The
-web browser part of the web tester can also be used independently either
-in other testers or as part of a scripting solution.
-
You can see a release schedule at http://www.lastcraft.com/overview.php
which is also copied to the documentation folder with this release.
A full PHPDocumenter API documentation exists at
@@ -61,7 +55,7 @@ The full tests read some test data from the LastCraft site. If the site
is down or has been modified for a later version then you will get
spurious errors. A unit_tests.php failure on the other hand would be
very serious. As far as we know we haven't yet managed to check in any
-test failures so please correct us if you find one.
+unit test failures so please correct us if you find one.
Even if all of the tests run please verify that your existing test suites
also function as expected. If they don't see the file...
@@ -74,14 +68,18 @@ your current tests appear to run.
There is a documentation folder which contains the core reference information
in English and French, although this information is fairly basic.
-You can find a tutorial on http://www.lastcraft.com/first_test_tutorial.php
-to get you started and this material will eventually become included
-with the project documentation. A French translation exists at
+You can find a tutorial on...
+
+http://www.lastcraft.com/first_test_tutorial.php
+
+...to get you started and this material will eventually become included
+with the project documentation. A French translation exists at...
+
http://www.onpk.net/index.php/2005/01/12/254-tutoriel-simpletest-decouvrir-les-tests-unitaires.
If you download and use and possibly even extend this tool, please let us
know. Any feedback, even bad, is always welcome and we will work to get
-your suggestions into the version one release. Ideally please send your
+your suggestions into the next release. Ideally please send your
comments to...
simpletest-support@lists.sourceforge.net
@@ -105,6 +103,6 @@ really are invaluable, but sadly you are too many to mention in full.
Thanks to all on the advanced PHP forum on SitePoint, especially Harry
Feucks. Early adopters are always an inspiration.
-yours Marcus Baker, Jason Sweat and Perrick Penet.
+yours Marcus Baker, Jason Sweat, Travis Swicegood and Perrick Penet.
--
marcus@lastcraft.com
diff --git a/tests/test_tools/simpletest/VERSION b/tests/test_tools/simpletest/VERSION
index d3827e75..9980c7df 100755
--- a/tests/test_tools/simpletest/VERSION
+++ b/tests/test_tools/simpletest/VERSION
@@ -1 +1 @@
-1.0
+1.0.1alpha3 \ No newline at end of file
diff --git a/tests/test_tools/simpletest/authentication.php b/tests/test_tools/simpletest/authentication.php
index 7b6ed4ba..bc413b2c 100644
--- a/tests/test_tools/simpletest/authentication.php
+++ b/tests/test_tools/simpletest/authentication.php
@@ -3,7 +3,7 @@
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
- * @version $Id: authentication.php,v 1.9 2004/09/19 17:24:11 lastcraft Exp $
+ * @version $Id: authentication.php,v 1.10 2005/07/26 01:27:18 lastcraft Exp $
*/
/**
* include http class
@@ -100,7 +100,26 @@
* @access public
*/
function isWithin($url) {
- return (strpos($url->getBasePath(), $this->_root) === 0);
+ if ($this->_isIn($this->_root, $url->getBasePath())) {
+ return true;
+ }
+ if ($this->_isIn($this->_root, $url->getBasePath() . $url->getPage() . '/')) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Tests to see if one string is a substring of
+ * another.
+ * @param string $part Small bit.
+ * @param string $whole Big bit.
+ * @return boolean True if the small bit is
+ * in the big bit.
+ * @access private
+ */
+ function _isIn($part, $whole) {
+ return strpos($whole, $part) === 0;
}
}
diff --git a/tests/test_tools/simpletest/browser.php b/tests/test_tools/simpletest/browser.php
index 06e1b8d7..8e843b18 100644
--- a/tests/test_tools/simpletest/browser.php
+++ b/tests/test_tools/simpletest/browser.php
@@ -3,22 +3,25 @@
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
- * @version $Id: browser.php,v 1.141 2005/02/22 02:39:21 lastcraft Exp $
+ * @version $Id: browser.php,v 1.162 2006/02/05 01:07:49 lastcraft Exp $
*/
-
+
/**#@+
* include other SimpleTest class files
*/
- require_once(dirname(__FILE__) . '/options.php');
+ require_once(dirname(__FILE__) . '/simpletest.php');
require_once(dirname(__FILE__) . '/http.php');
require_once(dirname(__FILE__) . '/encoding.php');
require_once(dirname(__FILE__) . '/page.php');
+ require_once(dirname(__FILE__) . '/selector.php');
require_once(dirname(__FILE__) . '/frames.php');
require_once(dirname(__FILE__) . '/user_agent.php');
/**#@-*/
-
- define('DEFAULT_MAX_NESTED_FRAMES', 3);
-
+
+ if (!defined('DEFAULT_MAX_NESTED_FRAMES')) {
+ define('DEFAULT_MAX_NESTED_FRAMES', 3);
+ }
+
/**
* Browser history list.
* @package SimpleTest
@@ -27,7 +30,7 @@
class SimpleBrowserHistory {
protected $_sequence;
protected $_position;
-
+
/**
* Starts empty.
* @access public
@@ -36,7 +39,7 @@
$this->_sequence = array();
$this->_position = -1;
}
-
+
/**
* Test for no entries yet.
* @return boolean True if empty.
@@ -45,7 +48,7 @@
function _isEmpty() {
return ($this->_position == -1);
}
-
+
/**
* Test for being at the beginning.
* @return boolean True if first.
@@ -54,7 +57,7 @@
function _atBeginning() {
return ($this->_position == 0) && ! $this->_isEmpty();
}
-
+
/**
* Test for being at the last entry.
* @return boolean True if last.
@@ -63,36 +66,21 @@
function _atEnd() {
return ($this->_position + 1 >= count($this->_sequence)) && ! $this->_isEmpty();
}
-
+
/**
* Adds a successfully fetched page to the history.
- * @param string $method GET or POST.
* @param SimpleUrl $url URL of fetch.
- * @param SimpleFormEncoding $parameters Any post data with the fetch.
+ * @param SimpleEncoding $parameters Any post data with the fetch.
* @access public
*/
- function recordEntry($method, $url, $parameters) {
+ function recordEntry($url, $parameters) {
$this->_dropFuture();
array_push(
$this->_sequence,
- array('method' => $method, 'url' => $url, 'parameters' => $parameters));
+ array('url' => $url, 'parameters' => $parameters));
$this->_position++;
}
-
- /**
- * Last fetching method for current history
- * position.
- * @return string GET or POST for this point in
- * the history.
- * @access public
- */
- function getMethod() {
- if ($this->_isEmpty()) {
- return false;
- }
- return $this->_sequence[$this->_position]['method'];
- }
-
+
/**
* Last fully qualified URL for current history
* position.
@@ -105,7 +93,7 @@
}
return $this->_sequence[$this->_position]['url'];
}
-
+
/**
* Parameters of last fetch from current history
* position.
@@ -118,7 +106,7 @@
}
return $this->_sequence[$this->_position]['parameters'];
}
-
+
/**
* Step back one place in the history. Stops at
* the first page.
@@ -132,7 +120,7 @@
$this->_position--;
return true;
}
-
+
/**
* Step forward one place. If already at the
* latest entry then nothing will happen.
@@ -146,7 +134,7 @@
$this->_position++;
return true;
}
-
+
/**
* Ditches all future entries beyond the current
* point.
@@ -161,7 +149,7 @@
}
}
}
-
+
/**
* Simulated web browser. This is an aggregate of
* the user agent, the HTML parsing, request history
@@ -175,7 +163,7 @@
protected $_history;
protected $_ignore_frames;
protected $_maximum_nested_frames;
-
+
/**
* Starts with a fresh browser with no
* cookie or any other state information. The
@@ -186,33 +174,35 @@
function SimpleBrowser() {
$this->_user_agent = $this->_createUserAgent();
$this->_user_agent->useProxy(
- SimpleTestOptions::getDefaultProxy(),
- SimpleTestOptions::getDefaultProxyUsername(),
- SimpleTestOptions::getDefaultProxyPassword());
+ SimpleTest::getDefaultProxy(),
+ SimpleTest::getDefaultProxyUsername(),
+ SimpleTest::getDefaultProxyPassword());
$this->_page = new SimplePage();
$this->_history = $this->_createHistory();
$this->_ignore_frames = false;
$this->_maximum_nested_frames = DEFAULT_MAX_NESTED_FRAMES;
}
-
+
/**
* Creates the underlying user agent.
* @return SimpleFetcher Content fetcher.
* @access protected
*/
- function _createUserAgent() {
- return new SimpleUserAgent();
+ function &_createUserAgent() {
+ $user_agent = new SimpleUserAgent();
+ return $user_agent;
}
-
+
/**
* Creates a new empty history list.
* @return SimpleBrowserHistory New list.
* @access protected
*/
- function _createHistory() {
- return new SimpleBrowserHistory();
+ function &_createHistory() {
+ $history = new SimpleBrowserHistory();
+ return $history;
}
-
+
/**
* Disables frames support. Frames will not be fetched
* and the frameset page will be used instead.
@@ -221,7 +211,7 @@
function ignoreFrames() {
$this->_ignore_frames = true;
}
-
+
/**
* Enables frames support. Frames will be fetched from
* now on.
@@ -232,93 +222,122 @@
}
/**
+ * Switches off cookie sending and recieving.
+ * @access public
+ */
+ function ignoreCookies() {
+ $this->_user_agent->ignoreCookies();
+ }
+
+ /**
+ * Switches back on the cookie sending and recieving.
+ * @access public
+ */
+ function useCookies() {
+ $this->_user_agent->useCookies();
+ }
+
+ /**
* Parses the raw content into a page. Will load further
* frame pages unless frames are disabled.
* @param SimpleHttpResponse $response Response from fetch.
* @param integer $depth Nested frameset depth.
* @return SimplePage Parsed HTML.
- * @access protected
+ * @access private
*/
- function _parse($response, $depth = 0) {
- $builder = new SimplePageBuilder();
- $page = $builder->parse($response);
+ function &_parse($response, $depth = 0) {
+ $page = $this->_buildPage($response);
if ($this->_ignore_frames || ! $page->hasFrames() || ($depth > $this->_maximum_nested_frames)) {
return $page;
}
$frameset = new SimpleFrameset($page);
foreach ($page->getFrameset() as $key => $url) {
- $frame = $this->_fetch('GET', $url, array(), $depth + 1);
+ $frame = $this->_fetch($url, new SimpleGetEncoding(), $depth + 1);
$frameset->addFrame($frame, $key);
}
return $frameset;
}
/**
- * Fetches a page.
- * @param string $method GET or POST.
- * @param string/SimpleUrl $url Target to fetch as string.
- * @param SimpleFormEncoding $parameters POST parameters.
- * @param integer $depth Nested frameset depth protection.
- * @return SimplePage Parsed page.
+ * Assembles the parsing machinery and actually parses
+ * a single page. Frees all of the builder memory and so
+ * unjams the PHP memory management.
+ * @param SimpleHttpResponse $response Response from fetch.
+ * @return SimplePage Parsed top level page.
+ * @access protected
+ */
+ function &_buildPage($response) {
+ $builder = new SimplePageBuilder();
+ $page = $builder->parse($response);
+ $builder->free();
+ unset($builder);
+ return $page;
+ }
+
+ /**
+ * Fetches a page. Jointly recursive with the _parse()
+ * method as it descends a frameset.
+ * @param string/SimpleUrl $url Target to fetch.
+ * @param SimpleEncoding $encoding GET/POST parameters.
+ * @param integer $depth Nested frameset depth protection.
+ * @return SimplePage Parsed page.
* @access private
*/
- function _fetch($method, $url, $parameters, $depth = 0) {
- $response = $this->_user_agent->fetchResponse($method, $url, $parameters);
+ function &_fetch($url, $encoding, $depth = 0) {
+ $response = $this->_user_agent->fetchResponse($url, $encoding);
if ($response->isError()) {
- return new SimplePage($response);
+ $page = new SimplePage($response);
+ } else {
+ $page = $this->_parse($response, $depth);
}
- return $this->_parse($response, $depth);
+ return $page;
}
-
+
/**
* Fetches a page or a single frame if that is the current
* focus.
- * @param string $method GET or POST.
- * @param string/SimpleUrl $url Target to fetch as string.
- * @param SimpleFormEncoding $parameters POST parameters.
+ * @param SimpleUrl $url Target to fetch.
+ * @param SimpleEncoding $parameters GET/POST parameters.
* @return string Raw content of page.
* @access private
*/
- function _load($method, $url, $parameters = false) {
+ function _load($url, $parameters) {
$frame = $url->getTarget();
if (! $frame || ! $this->_page->hasFrames() || (strtolower($frame) == '_top')) {
- return $this->_loadPage($method, $url, $parameters);
+ return $this->_loadPage($url, $parameters);
}
- return $this->_loadFrame(array($frame), $method, $url, $parameters);
+ return $this->_loadFrame(array($frame), $url, $parameters);
}
-
+
/**
* Fetches a page and makes it the current page/frame.
- * @param string $method GET or POST.
* @param string/SimpleUrl $url Target to fetch as string.
- * @param SimpleFormEncoding $parameters POST parameters.
+ * @param SimplePostEncoding $parameters POST parameters.
* @return string Raw content of page.
* @access private
*/
- function _loadPage($method, $url, $parameters = false) {
- $this->_page = $this->_fetch(strtoupper($method), $url, $parameters);
+ function _loadPage($url, $parameters) {
+ $this->_page = $this->_fetch($url, $parameters);
$this->_history->recordEntry(
- $this->_page->getMethod(),
$this->_page->getUrl(),
$this->_page->getRequestData());
return $this->_page->getRaw();
}
-
+
/**
* Fetches a frame into the existing frameset replacing the
* original.
* @param array $frames List of names to drill down.
- * @param string $method GET or POST.
* @param string/SimpleUrl $url Target to fetch as string.
* @param SimpleFormEncoding $parameters POST parameters.
* @return string Raw content of page.
* @access private
*/
- function _loadFrame($frames, $method, $url, $parameters = false) {
- $page = $this->_fetch(strtoupper($method), $url, $parameters);
+ function _loadFrame($frames, $url, $parameters) {
+ $page = $this->_fetch($url, $parameters);
$this->_page->setFrame($frames, $page);
}
-
+
/**
* Removes expired and temporary cookies as if
* the browser was closed and re-opened.
@@ -330,7 +349,7 @@
function restart($date = false) {
$this->_user_agent->restart($date);
}
-
+
/**
* Adds a header to every fetch.
* @param string $header Header line to add to every
@@ -340,7 +359,7 @@
function addHeader($header) {
$this->_user_agent->addHeader($header);
}
-
+
/**
* Ages the cookies by the specified time.
* @param integer $interval Amount in seconds.
@@ -349,7 +368,7 @@
function ageCookies($interval) {
$this->_user_agent->ageCookies($interval);
}
-
+
/**
* Sets an additional cookie. If a cookie has
* the same name and path it is replaced.
@@ -363,7 +382,7 @@
function setCookie($name, $value, $host = false, $path = '/', $expiry = false) {
$this->_user_agent->setCookie($name, $value, $host, $path, $expiry);
}
-
+
/**
* Reads the most specific cookie value from the
* browser cookies.
@@ -377,7 +396,7 @@
function getCookieValue($host, $path, $name) {
return $this->_user_agent->getCookieValue($host, $path, $name);
}
-
+
/**
* Reads the current cookies for the current URL.
* @param string $name Key of cookie to find.
@@ -388,7 +407,7 @@
function getCurrentCookieValue($name) {
return $this->_user_agent->getBaseCookieValue($name, $this->_page->getUrl());
}
-
+
/**
* Sets the maximum number of redirects before
* a page will be loaded anyway.
@@ -398,7 +417,7 @@
function setMaximumRedirects($max) {
$this->_user_agent->setMaximumRedirects($max);
}
-
+
/**
* Sets the maximum number of nesting of framed pages
* within a framed page to prevent loops.
@@ -408,7 +427,7 @@
function setMaximumNestedFrames($max) {
$this->_maximum_nested_frames = $max;
}
-
+
/**
* Sets the socket timeout for opening a connection.
* @param integer $timeout Maximum time in seconds.
@@ -417,7 +436,7 @@
function setConnectionTimeout($timeout) {
$this->_user_agent->setConnectionTimeout($timeout);
}
-
+
/**
* Sets proxy to use on all requests for when
* testing from behind a firewall. Set URL
@@ -430,12 +449,12 @@
function useProxy($proxy, $username = false, $password = false) {
$this->_user_agent->useProxy($proxy, $username, $password);
}
-
+
/**
* Fetches the page content with a HEAD request.
* Will affect cookies, but will not change the base URL.
* @param string/SimpleUrl $url Target to fetch as string.
- * @param hash/SimpleFormEncoding $parameters Additional parameters for
+ * @param hash/SimpleHeadEncoding $parameters Additional parameters for
* HEAD request.
* @return boolean True if successful.
* @access public
@@ -444,19 +463,13 @@
if (! is_object($url)) {
$url = new SimpleUrl($url);
}
- if (is_array($parameters)) {
- $parameters = new SimpleFormEncoding($parameters);
- }
if ($this->getUrl()) {
$url = $url->makeAbsolute($this->getUrl());
}
- $response = $this->_user_agent->fetchResponse(
- 'HEAD',
- $url,
- $parameters);
+ $response = $this->_user_agent->fetchResponse($url, new SimpleHeadEncoding($parameters));
return ! $response->isError();
}
-
+
/**
* Fetches the page content with a simple GET request.
* @param string/SimpleUrl $url Target to fetch.
@@ -469,15 +482,12 @@
if (! is_object($url)) {
$url = new SimpleUrl($url);
}
- if (is_array($parameters)) {
- $parameters = new SimpleFormEncoding($parameters);
- }
if ($this->getUrl()) {
$url = $url->makeAbsolute($this->getUrl());
}
- return $this->_load('GET', $url, $parameters);
+ return $this->_load($url, new SimpleGetEncoding($parameters));
}
-
+
/**
* Fetches the page content with a POST request.
* @param string/SimpleUrl $url Target to fetch as string.
@@ -489,15 +499,12 @@
if (! is_object($url)) {
$url = new SimpleUrl($url);
}
- if (is_array($parameters)) {
- $parameters = new SimpleFormEncoding($parameters);
- }
if ($this->getUrl()) {
$url = $url->makeAbsolute($this->getUrl());
}
- return $this->_load('POST', $url, $parameters);
+ return $this->_load($url, new SimplePostEncoding($parameters));
}
-
+
/**
* Equivalent to hitting the retry button on the
* browser. Will attempt to repeat the page fetch. If
@@ -511,25 +518,22 @@
if (count($frames) > 0) {
$this->_loadFrame(
$frames,
- $this->_page->getMethod(),
$this->_page->getUrl(),
$this->_page->getRequestData());
return $this->_page->getRaw();
}
- if ($method = $this->_history->getMethod()) {
- $this->_page = $this->_fetch(
- $method,
- $this->_history->getUrl(),
- $this->_history->getParameters());
+ if ($url = $this->_history->getUrl()) {
+ $this->_page = $this->_fetch($url, $this->_history->getParameters());
return $this->_page->getRaw();
}
return false;
}
-
+
/**
* Equivalent to hitting the back button on the
* browser. The browser history is unchanged on
- * failure.
+ * failure. The page content is refetched as there
+ * is no concept of content caching in SimpleTest.
* @return boolean True if history entry and
* fetch succeeded
* @access public
@@ -544,11 +548,12 @@
}
return $content;
}
-
+
/**
* Equivalent to hitting the forward button on the
* browser. The browser history is unchanged on
- * failure.
+ * failure. The page content is refetched as there
+ * is no concept of content caching in SimpleTest.
* @return boolean True if history entry and
* fetch succeeded
* @access public
@@ -563,7 +568,7 @@
}
return $content;
}
-
+
/**
* Retries a request after setting the authentication
* for the current realm.
@@ -589,7 +594,7 @@
$password);
return $this->retry();
}
-
+
/**
* Accessor for a breakdown of the frameset.
* @return array Hash tree of frames by name
@@ -599,7 +604,7 @@
function getFrames() {
return $this->_page->getFrames();
}
-
+
/**
* Accessor for current frame focus. Will be
* false if no frame has focus.
@@ -611,7 +616,7 @@
function getFrameFocus() {
return $this->_page->getFrameFocus();
}
-
+
/**
* Sets the focus by index. The integer index starts from 1.
* @param integer $choice Chosen frame.
@@ -621,7 +626,7 @@
function setFrameFocusByIndex($choice) {
return $this->_page->setFrameFocusByIndex($choice);
}
-
+
/**
* Sets the focus by name.
* @param string $name Chosen frame.
@@ -631,7 +636,7 @@
function setFrameFocus($name) {
return $this->_page->setFrameFocus($name);
}
-
+
/**
* Clears the frame focus. All frames will be searched
* for content.
@@ -640,7 +645,7 @@
function clearFrameFocus() {
return $this->_page->clearFrameFocus();
}
-
+
/**
* Accessor for last error.
* @return string Error from last response.
@@ -649,7 +654,7 @@
function getTransportError() {
return $this->_page->getTransportError();
}
-
+
/**
* Accessor for current MIME type.
* @return string MIME type as string; e.g. 'text/html'
@@ -658,7 +663,7 @@
function getMimeType() {
return $this->_page->getMimeType();
}
-
+
/**
* Accessor for last response code.
* @return integer Last HTTP response code received.
@@ -667,7 +672,7 @@
function getResponseCode() {
return $this->_page->getResponseCode();
}
-
+
/**
* Accessor for last Authentication type. Only valid
* straight after a challenge (401).
@@ -677,7 +682,7 @@
function getAuthentication() {
return $this->_page->getAuthentication();
}
-
+
/**
* Accessor for last Authentication realm. Only valid
* straight after a challenge (401).
@@ -687,7 +692,7 @@
function getRealm() {
return $this->_page->getRealm();
}
-
+
/**
* Accessor for current URL of page or frame if
* focused.
@@ -698,7 +703,7 @@
$url = $this->_page->getUrl();
return $url ? $url->asString() : false;
}
-
+
/**
* Accessor for raw bytes sent down the wire.
* @return string Original text sent.
@@ -725,7 +730,7 @@
function getContent() {
return $this->_page->getRaw();
}
-
+
/**
* Accessor for plain text version of the page.
* @return string Normalised text representation.
@@ -734,7 +739,7 @@
function getContentAsText() {
return $this->_page->getText();
}
-
+
/**
* Accessor for parsed title.
* @return string Title or false if no title is present.
@@ -743,7 +748,7 @@
function getTitle() {
return $this->_page->getTitle();
}
-
+
/**
* Accessor for a list of all fixed links in current page.
* @return array List of urls with scheme of
@@ -753,7 +758,7 @@
function getAbsoluteUrls() {
return $this->_page->getAbsoluteUrls();
}
-
+
/**
* Accessor for a list of all relative links.
* @return array List of urls without hostname.
@@ -762,18 +767,30 @@
function getRelativeUrls() {
return $this->_page->getRelativeUrls();
}
-
+
/**
* Sets all form fields with that name.
+ * @param string $label Name or label of field in forms.
+ * @param string $value New value of field.
+ * @return boolean True if field exists, otherwise false.
+ * @access public
+ */
+ function setField($label, $value) {
+ return $this->_page->setField(new SimpleByLabelOrName($label), $value);
+ }
+
+ /**
+ * Sets all form fields with that name. Will use label if
+ * one is available (not yet implemented).
* @param string $name Name of field in forms.
* @param string $value New value of field.
* @return boolean True if field exists, otherwise false.
* @access public
*/
- function setField($name, $value) {
- return $this->_page->setField($name, $value);
+ function setFieldByName($name, $value) {
+ return $this->_page->setField(new SimpleByName($name), $value);
}
-
+
/**
* Sets all form fields with that id attribute.
* @param string/integer $id Id of field in forms.
@@ -782,9 +799,22 @@
* @access public
*/
function setFieldById($id, $value) {
- return $this->_page->setFieldById($id, $value);
+ return $this->_page->setField(new SimpleById($id), $value);
}
-
+
+ /**
+ * Accessor for a form element value within the page.
+ * Finds the first match.
+ * @param string $label Field label.
+ * @return string/boolean A value if the field is
+ * present, false if unchecked
+ * and null if missing.
+ * @access public
+ */
+ function getField($label) {
+ return $this->_page->getField(new SimpleByLabelOrName($label));
+ }
+
/**
* Accessor for a form element value within the page.
* Finds the first match.
@@ -794,10 +824,10 @@
* and null if missing.
* @access public
*/
- function getField($name) {
- return $this->_page->getField($name);
+ function getFieldByName($name) {
+ return $this->_page->getField(new SimpleByName($name));
}
-
+
/**
* Accessor for a form element value within the page.
* @param string/integer $id Id of field in forms.
@@ -807,9 +837,9 @@
* @access public
*/
function getFieldById($id) {
- return $this->_page->getFieldById($id);
+ return $this->_page->getField(new SimpleById($id));
}
-
+
/**
* Clicks the submit button by label. The owning
* form will be submitted by this.
@@ -820,16 +850,15 @@
* @access public
*/
function clickSubmit($label = 'Submit', $additional = false) {
- if (! ($form = $this->_page->getFormBySubmitLabel($label))) {
+ if (! ($form = $this->_page->getFormBySubmit(new SimpleByLabel($label)))) {
return false;
}
$success = $this->_load(
- $form->getMethod(),
$form->getAction(),
- $form->submitButtonByLabel($label, $additional));
+ $form->submitButton(new SimpleByLabel($label), $additional));
return ($success ? $this->getContent() : $success);
}
-
+
/**
* Clicks the submit button by name attribute. The owning
* form will be submitted by this.
@@ -839,16 +868,15 @@
* @access public
*/
function clickSubmitByName($name, $additional = false) {
- if (! ($form = $this->_page->getFormBySubmitName($name))) {
+ if (! ($form = $this->_page->getFormBySubmit(new SimpleByName($name)))) {
return false;
}
$success = $this->_load(
- $form->getMethod(),
$form->getAction(),
- $form->submitButtonByName($name, $additional));
+ $form->submitButton(new SimpleByName($name), $additional));
return ($success ? $this->getContent() : $success);
}
-
+
/**
* Clicks the submit button by ID attribute of the button
* itself. The owning form will be submitted by this.
@@ -858,16 +886,15 @@
* @access public
*/
function clickSubmitById($id, $additional = false) {
- if (! ($form = $this->_page->getFormBySubmitId($id))) {
+ if (! ($form = $this->_page->getFormBySubmit(new SimpleById($id)))) {
return false;
}
$success = $this->_load(
- $form->getMethod(),
$form->getAction(),
- $form->submitButtonById($id, $additional));
+ $form->submitButton(new SimpleById($id), $additional));
return ($success ? $this->getContent() : $success);
}
-
+
/**
* Clicks the submit image by some kind of label. Usually
* the alt tag or the nearest equivalent. The owning
@@ -882,16 +909,15 @@
* @access public
*/
function clickImage($label, $x = 1, $y = 1, $additional = false) {
- if (! ($form = $this->_page->getFormByImageLabel($label))) {
+ if (! ($form = $this->_page->getFormByImage(new SimpleByLabel($label)))) {
return false;
}
$success = $this->_load(
- $form->getMethod(),
$form->getAction(),
- $form->submitImageByLabel($label, $x, $y, $additional));
+ $form->submitImage(new SimpleByLabel($label), $x, $y, $additional));
return ($success ? $this->getContent() : $success);
}
-
+
/**
* Clicks the submit image by the name. Usually
* the alt tag or the nearest equivalent. The owning
@@ -906,16 +932,15 @@
* @access public
*/
function clickImageByName($name, $x = 1, $y = 1, $additional = false) {
- if (! ($form = $this->_page->getFormByImageName($name))) {
+ if (! ($form = $this->_page->getFormByImage(new SimpleByName($name)))) {
return false;
}
$success = $this->_load(
- $form->getMethod(),
$form->getAction(),
- $form->submitImageByName($name, $x, $y, $additional));
+ $form->submitImage(new SimpleByName($name), $x, $y, $additional));
return ($success ? $this->getContent() : $success);
}
-
+
/**
* Clicks the submit image by ID attribute. The owning
* form will be submitted by this. Clicking outside of
@@ -929,16 +954,15 @@
* @access public
*/
function clickImageById($id, $x = 1, $y = 1, $additional = false) {
- if (! ($form = $this->_page->getFormByImageId($id))) {
+ if (! ($form = $this->_page->getFormByImage(new SimpleById($id)))) {
return false;
}
$success = $this->_load(
- $form->getMethod(),
$form->getAction(),
- $form->submitImageById($id, $x, $y, $additional));
+ $form->submitImage(new SimpleById($id), $x, $y, $additional));
return ($success ? $this->getContent() : $success);
}
-
+
/**
* Submits a form by the ID.
* @param string $id The form ID. No submit button value
@@ -951,12 +975,11 @@
return false;
}
$success = $this->_load(
- $form->getMethod(),
$form->getAction(),
$form->submit());
return ($success ? $this->getContent() : $success);
}
-
+
/**
* Follows a link by label. Will click the first link
* found with this link text by default, or a later
@@ -975,10 +998,10 @@
if (count($urls) < $index + 1) {
return false;
}
- $this->_load('GET', $urls[$index]);
+ $this->_load($urls[$index], new SimpleGetEncoding());
return $this->getContent();
}
-
+
/**
* Tests to see if a link is present by label.
* @param string $label Text of value attribute.
@@ -988,7 +1011,7 @@
function isLink($label) {
return (count($this->_page->getUrlsByLabel($label)) > 0);
}
-
+
/**
* Follows a link by id attribute.
* @param string $id ID attribute value.
@@ -999,10 +1022,10 @@
if (! ($url = $this->_page->getUrlById($id))) {
return false;
}
- $this->_load('GET', $url);
+ $this->_load($url, new SimpleGetEncoding());
return $this->getContent();
}
-
+
/**
* Tests to see if a link is present by ID attribute.
* @param string $id Text of id attribute.
@@ -1012,5 +1035,23 @@
function isLinkById($id) {
return (boolean)$this->_page->getUrlById($id);
}
+
+ /**
+ * Clicks a visible text item. Will first try buttons,
+ * then links and then images.
+ * @param string $label Visible text or alt text.
+ * @return string/boolean Raw page or false.
+ * @access public
+ */
+ function click($label) {
+ $raw = $this->clickSubmit($label);
+ if (! $raw) {
+ $raw = $this->clickLink($label);
+ }
+ if (! $raw) {
+ $raw = $this->clickImage($label);
+ }
+ return $raw;
+ }
}
?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/collector.php b/tests/test_tools/simpletest/collector.php
new file mode 100644
index 00000000..f73193c7
--- /dev/null
+++ b/tests/test_tools/simpletest/collector.php
@@ -0,0 +1,115 @@
+<?php
+/**
+ * This file contains the following classes: {@link SimpleCollector},
+ * {@link SimplePatternCollector}.
+ *
+ * @author Travis Swicegood <development@domain51.com>
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: collector.php,v 1.7 2005/09/10 21:09:34 tswicegood Exp $
+ */
+
+/**
+ * The basic collector for {@link GroupTest}
+ *
+ * @see collect(), GroupTest::collect()
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+class SimpleCollector {
+
+ /**
+ * Strips off any kind of slash at the end so as to normalise the path
+ *
+ * @param string $path Path to normalise.
+ */
+ function _removeTrailingSlash($path) {
+ return preg_replace('|[\\/]$|', '', $path);
+
+ /**
+ * @internal
+ * Try benchmarking the following. It's more code, but by not using the
+ * regex, it may be faster? Also, shouldn't be looking for
+ * DIRECTORY_SEPERATOR instead of a manual "/"?
+ */
+ if (substr($path, -1) == DIRECTORY_SEPERATOR) {
+ return substr($path, 0, -1);
+ } else {
+ return $path;
+ }
+ }
+
+ /**
+ * Scans the directory and adds what it can.
+ * @param object $test Group test with {@link GroupTest::addTestFile()} method.
+ * @param string $path Directory to scan.
+ * @see _attemptToAdd()
+ */
+ function collect($test, $path) {
+ $path = $this->_removeTrailingSlash($path);
+ if ($handle = opendir($path)) {
+ while (($entry = readdir($handle)) !== false) {
+ $this->_handle($test, $path . DIRECTORY_SEPARATOR . $entry);
+ }
+ closedir($handle);
+ }
+ }
+
+ /**
+ * This method determines what should be done with a given file and adds
+ * it via {@link GroupTest::addTestFile()} if necessary.
+ *
+ * This method should be overriden to provide custom matching criteria,
+ * such as pattern matching, recursive matching, etc. For an example, see
+ * {@link SimplePatternCollector::_handle()}.
+ *
+ * @param object $test Group test with {@link GroupTest::addTestFile()} method.
+ * @param string $filename A filename as generated by {@link collect()}
+ * @see collect()
+ * @access protected
+ */
+ function _handle($test, $file) {
+ if (!is_dir($file)) {
+ $test->addTestFile($file);
+ }
+ }
+}
+
+/**
+ * An extension to {@link SimpleCollector} that only adds files matching a
+ * given pattern.
+ *
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @see SimpleCollector
+ */
+class SimplePatternCollector extends SimpleCollector {
+ protected $_pattern;
+
+
+ /**
+ *
+ * @param string $pattern Perl compatible regex to test name against
+ * See {@link http://us4.php.net/manual/en/reference.pcre.pattern.syntax.php PHP's PCRE}
+ * for full documentation of valid pattern.s
+ */
+ function SimplePatternCollector($pattern = '/php$/i') {
+ $this->_pattern = $pattern;
+ }
+
+
+ /**
+ * Attempts to add files that match a given pattern.
+ *
+ * @see SimpleCollector::_handle()
+ * @param object $test Group test with {@link GroupTest::addTestFile()} method.
+ * @param string $path Directory to scan.
+ * @access protected
+ */
+ function _handle($test, $filename) {
+ if (preg_match($this->_pattern, $filename)) {
+ parent::_handle($test, $filename);
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/compatibility.php b/tests/test_tools/simpletest/compatibility.php
new file mode 100644
index 00000000..36775194
--- /dev/null
+++ b/tests/test_tools/simpletest/compatibility.php
@@ -0,0 +1,184 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @version $Id: compatibility.php,v 1.6 2006/01/02 22:39:23 lastcraft Exp $
+ */
+
+ /**
+ * Static methods for compatibility between different
+ * PHP versions.
+ * @package SimpleTest
+ */
+ class SimpleTestCompatibility {
+
+ /**
+ * Creates a copy whether in PHP5 or PHP4.
+ * @param object $object Thing to copy.
+ * @return object A copy.
+ * @access public
+ * @static
+ */
+ function copy($object) {
+ if (version_compare(phpversion(), '5') >= 0) {
+ eval('$copy = clone $object;');
+ return $copy;
+ }
+ return $object;
+ }
+
+ /**
+ * Identity test. Drops back to equality + types for PHP5
+ * objects as the === operator counts as the
+ * stronger reference constraint.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @return boolean True if identical.
+ * @access public
+ * @static
+ */
+ function isIdentical($first, $second) {
+ if ($first != $second) {
+ return false;
+ }
+ if (version_compare(phpversion(), '5') >= 0) {
+ return SimpleTestCompatibility::_isIdenticalType($first, $second);
+ }
+ return ($first === $second);
+ }
+
+ /**
+ * Recursive type test.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @return boolean True if same type.
+ * @access private
+ * @static
+ */
+ function _isIdenticalType($first, $second) {
+ if (gettype($first) != gettype($second)) {
+ return false;
+ }
+ if (is_object($first) && is_object($second)) {
+ if (get_class($first) != get_class($second)) {
+ return false;
+ }
+ return SimpleTestCompatibility::_isArrayOfIdenticalTypes(
+ get_object_vars($first),
+ get_object_vars($second));
+ }
+ if (is_array($first) && is_array($second)) {
+ return SimpleTestCompatibility::_isArrayOfIdenticalTypes($first, $second);
+ }
+ return true;
+ }
+
+ /**
+ * Recursive type test for each element of an array.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @return boolean True if identical.
+ * @access private
+ * @static
+ */
+ function _isArrayOfIdenticalTypes($first, $second) {
+ if (array_keys($first) != array_keys($second)) {
+ return false;
+ }
+ foreach (array_keys($first) as $key) {
+ $is_identical = SimpleTestCompatibility::_isIdenticalType(
+ $first[$key],
+ $second[$key]);
+ if (! $is_identical) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Test for two variables being aliases.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @return boolean True if same.
+ * @access public
+ * @static
+ */
+ function isReference($first, $second) {
+ if (version_compare(phpversion(), '5', '>=')
+ && is_object($first)) {
+ return ($first === $second);
+ }
+ if (is_object($first) && is_object($second)) {
+ $id = uniqid("test");
+ $first->$id = true;
+ $is_ref = isset($second->$id);
+ unset($first->$id);
+ return $is_ref;
+ }
+ $temp = $first;
+ $first = uniqid("test");
+ $is_ref = ($first === $second);
+ $first = $temp;
+ return $is_ref;
+ }
+
+ /**
+ * Test to see if an object is a member of a
+ * class hiearchy.
+ * @param object $object Object to test.
+ * @param string $class Root name of hiearchy.
+ * @return boolean True if class in hiearchy.
+ * @access public
+ * @static
+ */
+ function isA($object, $class) {
+ if (version_compare(phpversion(), '5') >= 0) {
+ if (! class_exists($class, false)) {
+ if (function_exists('interface_exists')) {
+ if (! interface_exists($class, false)) {
+ return false;
+ }
+ }
+ }
+ eval("\$is_a = \$object instanceof $class;");
+ return $is_a;
+ }
+ if (function_exists('is_a')) {
+ return is_a($object, $class);
+ }
+ return ((strtolower($class) == get_class($object))
+ or (is_subclass_of($object, $class)));
+ }
+
+ /**
+ * Sets a socket timeout for each chunk.
+ * @param resource $handle Socket handle.
+ * @param integer $timeout Limit in seconds.
+ * @access public
+ * @static
+ */
+ function setTimeout($handle, $timeout) {
+ if (function_exists('stream_set_timeout')) {
+ stream_set_timeout($handle, $timeout, 0);
+ } elseif (function_exists('socket_set_timeout')) {
+ socket_set_timeout($handle, $timeout, 0);
+ } elseif (function_exists('set_socket_timeout')) {
+ set_socket_timeout($handle, $timeout, 0);
+ }
+ }
+
+ /**
+ * Gets the current stack trace topmost first.
+ * @return array List of stack frames.
+ * @access public
+ * @static
+ */
+ function getStackTrace() {
+ if (function_exists('debug_backtrace')) {
+ return array_reverse(debug_backtrace());
+ }
+ return array();
+ }
+ }
+?>
diff --git a/tests/test_tools/simpletest/cookies.php b/tests/test_tools/simpletest/cookies.php
new file mode 100644
index 00000000..ecd2893c
--- /dev/null
+++ b/tests/test_tools/simpletest/cookies.php
@@ -0,0 +1,380 @@
+<?php
+ /**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: cookies.php,v 1.4 2005/12/05 04:47:03 lastcraft Exp $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/url.php');
+ /**#@-*/
+
+ /**
+ * Cookie data holder. Cookie rules are full of pretty
+ * arbitary stuff. I have used...
+ * http://wp.netscape.com/newsref/std/cookie_spec.html
+ * http://www.cookiecentral.com/faq/
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleCookie {
+ protected $_host;
+ protected $_name;
+ protected $_value;
+ protected $_path;
+ protected $_expiry;
+ protected $_is_secure;
+
+ /**
+ * Constructor. Sets the stored values.
+ * @param string $name Cookie key.
+ * @param string $value Value of cookie.
+ * @param string $path Cookie path if not host wide.
+ * @param string $expiry Expiry date as string.
+ * @param boolean $is_secure Currently ignored.
+ */
+ function SimpleCookie($name, $value = false, $path = false, $expiry = false, $is_secure = false) {
+ $this->_host = false;
+ $this->_name = $name;
+ $this->_value = $value;
+ $this->_path = ($path ? $this->_fixPath($path) : "/");
+ $this->_expiry = false;
+ if (is_string($expiry)) {
+ $this->_expiry = strtotime($expiry);
+ } elseif (is_integer($expiry)) {
+ $this->_expiry = $expiry;
+ }
+ $this->_is_secure = $is_secure;
+ }
+
+ /**
+ * Sets the host. The cookie rules determine
+ * that the first two parts are taken for
+ * certain TLDs and three for others. If the
+ * new host does not match these rules then the
+ * call will fail.
+ * @param string $host New hostname.
+ * @return boolean True if hostname is valid.
+ * @access public
+ */
+ function setHost($host) {
+ if ($host = $this->_truncateHost($host)) {
+ $this->_host = $host;
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for the truncated host to which this
+ * cookie applies.
+ * @return string Truncated hostname.
+ * @access public
+ */
+ function getHost() {
+ return $this->_host;
+ }
+
+ /**
+ * Test for a cookie being valid for a host name.
+ * @param string $host Host to test against.
+ * @return boolean True if the cookie would be valid
+ * here.
+ */
+ function isValidHost($host) {
+ return ($this->_truncateHost($host) === $this->getHost());
+ }
+
+ /**
+ * Extracts just the domain part that determines a
+ * cookie's host validity.
+ * @param string $host Host name to truncate.
+ * @return string Domain or false on a bad host.
+ * @access private
+ */
+ function _truncateHost($host) {
+ $tlds = SimpleUrl::getAllTopLevelDomains();
+ if (preg_match('/[a-z\-]+\.(' . $tlds . ')$/i', $host, $matches)) {
+ return $matches[0];
+ } elseif (preg_match('/[a-z\-]+\.[a-z\-]+\.[a-z\-]+$/i', $host, $matches)) {
+ return $matches[0];
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for name.
+ * @return string Cookie key.
+ * @access public
+ */
+ function getName() {
+ return $this->_name;
+ }
+
+ /**
+ * Accessor for value. A deleted cookie will
+ * have an empty string for this.
+ * @return string Cookie value.
+ * @access public
+ */
+ function getValue() {
+ return $this->_value;
+ }
+
+ /**
+ * Accessor for path.
+ * @return string Valid cookie path.
+ * @access public
+ */
+ function getPath() {
+ return $this->_path;
+ }
+
+ /**
+ * Tests a path to see if the cookie applies
+ * there. The test path must be longer or
+ * equal to the cookie path.
+ * @param string $path Path to test against.
+ * @return boolean True if cookie valid here.
+ * @access public
+ */
+ function isValidPath($path) {
+ return (strncmp(
+ $this->_fixPath($path),
+ $this->getPath(),
+ strlen($this->getPath())) == 0);
+ }
+
+ /**
+ * Accessor for expiry.
+ * @return string Expiry string.
+ * @access public
+ */
+ function getExpiry() {
+ if (! $this->_expiry) {
+ return false;
+ }
+ return gmdate("D, d M Y H:i:s", $this->_expiry) . " GMT";
+ }
+
+ /**
+ * Test to see if cookie is expired against
+ * the cookie format time or timestamp.
+ * Will give true for a session cookie.
+ * @param integer/string $now Time to test against. Result
+ * will be false if this time
+ * is later than the cookie expiry.
+ * Can be either a timestamp integer
+ * or a cookie format date.
+ * @access public
+ */
+ function isExpired($now) {
+ if (! $this->_expiry) {
+ return true;
+ }
+ if (is_string($now)) {
+ $now = strtotime($now);
+ }
+ return ($this->_expiry < $now);
+ }
+
+ /**
+ * Ages the cookie by the specified number of
+ * seconds.
+ * @param integer $interval In seconds.
+ * @public
+ */
+ function agePrematurely($interval) {
+ if ($this->_expiry) {
+ $this->_expiry -= $interval;
+ }
+ }
+
+ /**
+ * Accessor for the secure flag.
+ * @return boolean True if cookie needs SSL.
+ * @access public
+ */
+ function isSecure() {
+ return $this->_is_secure;
+ }
+
+ /**
+ * Adds a trailing and leading slash to the path
+ * if missing.
+ * @param string $path Path to fix.
+ * @access private
+ */
+ function _fixPath($path) {
+ if (substr($path, 0, 1) != '/') {
+ $path = '/' . $path;
+ }
+ if (substr($path, -1, 1) != '/') {
+ $path .= '/';
+ }
+ return $path;
+ }
+ }
+
+ /**
+ * Repository for cookies. This stuff is a
+ * tiny bit browser dependent.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleCookieJar {
+ protected $_cookies;
+
+ /**
+ * Constructor. Jar starts empty.
+ * @access public
+ */
+ function SimpleCookieJar() {
+ $this->_cookies = array();
+ }
+
+ /**
+ * Removes expired and temporary cookies as if
+ * the browser was closed and re-opened.
+ * @param string/integer $now Time to test expiry against.
+ * @access public
+ */
+ function restartSession($date = false) {
+ $surviving_cookies = array();
+ for ($i = 0; $i < count($this->_cookies); $i++) {
+ if (! $this->_cookies[$i]->getValue()) {
+ continue;
+ }
+ if (! $this->_cookies[$i]->getExpiry()) {
+ continue;
+ }
+ if ($date && $this->_cookies[$i]->isExpired($date)) {
+ continue;
+ }
+ $surviving_cookies[] = $this->_cookies[$i];
+ }
+ $this->_cookies = $surviving_cookies;
+ }
+
+ /**
+ * Ages all cookies in the cookie jar.
+ * @param integer $interval The old session is moved
+ * into the past by this number
+ * of seconds. Cookies now over
+ * age will be removed.
+ * @access public
+ */
+ function agePrematurely($interval) {
+ for ($i = 0; $i < count($this->_cookies); $i++) {
+ $this->_cookies[$i]->agePrematurely($interval);
+ }
+ }
+
+ /**
+ * Sets an additional cookie. If a cookie has
+ * the same name and path it is replaced.
+ * @param string $name Cookie key.
+ * @param string $value Value of cookie.
+ * @param string $host Host upon which the cookie is valid.
+ * @param string $path Cookie path if not host wide.
+ * @param string $expiry Expiry date.
+ * @access public
+ */
+ function setCookie($name, $value, $host = false, $path = '/', $expiry = false) {
+ $cookie = new SimpleCookie($name, $value, $path, $expiry);
+ if ($host) {
+ $cookie->setHost($host);
+ }
+ $this->_cookies[$this->_findFirstMatch($cookie)] = $cookie;
+ }
+
+ /**
+ * Finds a matching cookie to write over or the
+ * first empty slot if none.
+ * @param SimpleCookie $cookie Cookie to write into jar.
+ * @return integer Available slot.
+ * @access private
+ */
+ function _findFirstMatch($cookie) {
+ for ($i = 0; $i < count($this->_cookies); $i++) {
+ $is_match = $this->_isMatch(
+ $cookie,
+ $this->_cookies[$i]->getHost(),
+ $this->_cookies[$i]->getPath(),
+ $this->_cookies[$i]->getName());
+ if ($is_match) {
+ return $i;
+ }
+ }
+ return count($this->_cookies);
+ }
+
+ /**
+ * Reads the most specific cookie value from the
+ * browser cookies. Looks for the longest path that
+ * matches.
+ * @param string $host Host to search.
+ * @param string $path Applicable path.
+ * @param string $name Name of cookie to read.
+ * @return string False if not present, else the
+ * value as a string.
+ * @access public
+ */
+ function getCookieValue($host, $path, $name) {
+ $longest_path = '';
+ foreach ($this->_cookies as $cookie) {
+ if ($this->_isMatch($cookie, $host, $path, $name)) {
+ if (strlen($cookie->getPath()) > strlen($longest_path)) {
+ $value = $cookie->getValue();
+ $longest_path = $cookie->getPath();
+ }
+ }
+ }
+ return (isset($value) ? $value : false);
+ }
+
+ /**
+ * Tests cookie for matching against search
+ * criteria.
+ * @param SimpleTest $cookie Cookie to test.
+ * @param string $host Host must match.
+ * @param string $path Cookie path must be shorter than
+ * this path.
+ * @param string $name Name must match.
+ * @return boolean True if matched.
+ * @access private
+ */
+ function _isMatch($cookie, $host, $path, $name) {
+ if ($cookie->getName() != $name) {
+ return false;
+ }
+ if ($host && $cookie->getHost() && ! $cookie->isValidHost($host)) {
+ return false;
+ }
+ if (! $cookie->isValidPath($path)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Uses a URL to sift relevant cookies by host and
+ * path. Results are list of strings of form "name=value".
+ * @param SimpleUrl $url Url to select by.
+ * @return array Valid name and value pairs.
+ * @access public
+ */
+ function selectAsPairs($url) {
+ $pairs = array();
+ foreach ($this->_cookies as $cookie) {
+ if ($this->_isMatch($cookie, $url->getHost(), $url->getPath(), $cookie->getName())) {
+ $pairs[] = $cookie->getName() . '=' . $cookie->getValue();
+ }
+ }
+ return $pairs;
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/detached.php b/tests/test_tools/simpletest/detached.php
new file mode 100644
index 00000000..00f08880
--- /dev/null
+++ b/tests/test_tools/simpletest/detached.php
@@ -0,0 +1,96 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: detached.php,v 1.1 2005/12/08 19:35:06 lastcraft Exp $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/xml.php');
+ require_once(dirname(__FILE__) . '/shell_tester.php');
+ /**#@-*/
+
+ /**
+ * Runs an XML formated test in a separate process.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class DetachedTestCase {
+ protected $_command;
+ protected $_dry_command;
+ protected $_size;
+
+ /**
+ * Sets the location of the remote test.
+ * @param string $command Test script.
+ * @param string $dry_command Script for dry run.
+ * @access public
+ */
+ function DetachedTestCase($command, $dry_command = false) {
+ $this->_command = $command;
+ $this->_dry_command = $dry_command ? $dry_command : $command;
+ $this->_size = false;
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->_command;
+ }
+
+ /**
+ * Runs the top level test for this class. Currently
+ * reads the data as a single chunk. I'll fix this
+ * once I have added iteration to the browser.
+ * @param SimpleReporter $reporter Target of test results.
+ * @returns boolean True if no failures.
+ * @access public
+ */
+ function run($reporter) {
+ $shell = new SimpleShell();
+ $shell->execute($this->_command);
+ $parser = $this->_createParser($reporter);
+ if (! $parser->parse($shell->getOutput())) {
+ trigger_error('Cannot parse incoming XML from [' . $this->_command . ']');
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Accessor for the number of subtests.
+ * @return integer Number of test cases.
+ * @access public
+ */
+ function getSize() {
+ if ($this->_size === false) {
+ $shell = new SimpleShell();
+ $shell->execute($this->_dry_command);
+ $reporter = new SimpleReporter();
+ $parser = $this->_createParser($reporter);
+ if (! $parser->parse($shell->getOutput())) {
+ trigger_error('Cannot parse incoming XML from [' . $this->_dry_command . ']');
+ return false;
+ }
+ $this->_size = $reporter->getTestCaseCount();
+ }
+ return $this->_size;
+ }
+
+ /**
+ * Creates the XML parser.
+ * @param SimpleReporter $reporter Target of test results.
+ * @return SimpleTestXmlListener XML reader.
+ * @access protected
+ */
+ function &_createParser($reporter) {
+ return new SimpleTestXmlParser($reporter);
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/docs/en/authentication_documentation.html b/tests/test_tools/simpletest/docs/en/authentication_documentation.html
index 0623023c..c90d61e5 100755
--- a/tests/test_tools/simpletest/docs/en/authentication_documentation.html
+++ b/tests/test_tools/simpletest/docs/en/authentication_documentation.html
@@ -21,9 +21,6 @@
<a href="group_test_documentation.html">Group tests</a>
</li>
<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
<a href="mock_objects_documentation.html">Mock objects</a>
</li>
<li>
@@ -109,6 +106,19 @@ class AuthenticationTest extends WebTestCase {
on the amount of detail you want to see.
</p>
<p>
+ One theme that runs through SimpleTest is the ability to use
+ <span class="new_code">SimpleExpectation</span> objects wherever a simple
+ match is not enough.
+ If you want only an approximate match to the realm for
+ example, you can do this...
+<pre>
+class AuthenticationTest extends WebTestCase {
+ function test401Header() {
+ $this-&gt;get('http://www.lastcraft.com/protected/');
+ $this-&gt;assertRealm(<strong>new PatternExpectation('/simpletest/i')</strong>);
+ }
+}
+</pre>
Most of the time we are not interested in testing the
authentication itself, but want to get past it to test
the pages underneath.
@@ -116,7 +126,7 @@ class AuthenticationTest extends WebTestCase {
an authentication response...
<pre>
class AuthenticationTest extends WebTestCase {
- function testAuthentication() {
+ function testCanAuthenticate() {
$this-&gt;get('http://www.lastcraft.com/protected/');<strong>
$this-&gt;authenticate('Me', 'Secret');</strong>
$this-&gt;assertTitle(...);
@@ -208,9 +218,15 @@ class LogInTest extends WebTestCase {
</pre>
All we are doing is confirming that the cookie is set.
As the value is likely to be rather cryptic it's not
- really worth testing this.
- </p>
- <p>
+ really worth testing this with...
+<pre>
+class LogInTest extends WebTestCase {
+ function testSessionCookieIsCorrectPattern() {
+ $this-&gt;get('http://www.my-site.com/login.php');
+ $this-&gt;assertCookie('SID', <strong>new PatternExpectation('/[a-f0-9]{32}/i')</strong>);
+ }
+}
+</pre>
The rest of the test would be the same as any other form,
but we might want to confirm that we still have the same
cookie after log-in as before we entered.
@@ -224,8 +240,8 @@ class LogInTest extends WebTestCase {
$session = $this-&gt;getCookie('SID');
$this-&gt;setField('u', 'Me');
$this-&gt;setField('p', 'Secret');
- $this-&gt;clickSubmit('Log in');
- $this-&gt;assertWantedPattern('/Welcome Me/');
+ $this-&gt;click('Log in');
+ $this-&gt;assertText('Welcome Me');
$this-&gt;assertCookie('SID', $session);</strong>
}
}
@@ -243,7 +259,7 @@ class LogInTest extends WebTestCase {
$this-&gt;get('http://www.my-site.com/login.php');<strong>
$this-&gt;setCookie('SID', 'Some other session');
$this-&gt;get('http://www.my-site.com/restricted.php');</strong>
- $this-&gt;assertWantedPattern('/Access denied/');
+ $this-&gt;assertText('Access denied');
}
}
</pre>
@@ -266,12 +282,12 @@ class LogInTest extends WebTestCase {
$this-&gt;get('http://www.my-site.com/login.php');
$this-&gt;setField('u', 'Me');
$this-&gt;setField('p', 'Secret');
- $this-&gt;clickSubmit('Log in');
- $this-&gt;assertWantedPattern('/Welcome Me/');<strong>
+ $this-&gt;click('Log in');
+ $this-&gt;assertText('Welcome Me');<strong>
$this-&gt;restart();
$this-&gt;get('http://www.my-site.com/restricted.php');
- $this-&gt;assertWantedPattern('/Access denied/');</strong>
+ $this-&gt;assertText('Access denied');</strong>
}
}
</pre>
@@ -297,13 +313,13 @@ class LogInTest extends WebTestCase {
$this-&gt;get('http://www.my-site.com/login.php');
$this-&gt;setField('u', 'Me');
$this-&gt;setField('p', 'Secret');
- $this-&gt;clickSubmit('Log in');
- $this-&gt;assertWantedPattern('/Welcome Me/');
+ $this-&gt;click('Log in');
+ $this-&gt;assertText('Welcome Me');
<strong>
$this-&gt;ageCookies(3600);</strong>
$this-&gt;restart();
$this-&gt;get('http://www.my-site.com/restricted.php');
- $this-&gt;assertWantedPattern('/Access denied/');
+ $this-&gt;assertText('Access denied');
}
}
</pre>
diff --git a/tests/test_tools/simpletest/docs/en/browser_documentation.html b/tests/test_tools/simpletest/docs/en/browser_documentation.html
index ef54aaea..f6046a9d 100755
--- a/tests/test_tools/simpletest/docs/en/browser_documentation.html
+++ b/tests/test_tools/simpletest/docs/en/browser_documentation.html
@@ -21,9 +21,6 @@
<a href="group_test_documentation.html">Group tests</a>
</li>
<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
<a href="mock_objects_documentation.html">Mock objects</a>
</li>
<li>
@@ -76,9 +73,9 @@
$browser = &amp;new SimpleBrowser();
$browser-&gt;get('http://php.net/');
- $browser-&gt;clickLink('reporting bugs');
- $browser-&gt;clickLink('statistics');
- $page = $browser-&gt;clickLink('PHP 5 bugs only');
+ $browser-&gt;click('reporting bugs');
+ $browser-&gt;click('statistics');
+ $page = $browser-&gt;click('PHP 5 bugs only');
preg_match('/status=Open.*?by=Any.*?(\d+)&lt;\/a&gt;/', $page, $matches);
print $matches[1];
?&gt;</strong>
@@ -298,13 +295,21 @@
<tr>
<td><span class="new_code">useFrames()</span></td><td>Enables frames support</td>
</tr>
+ <tr>
+<td><span class="new_code">ignoreCookies()</span></td><td>Disables sending and receiving of cookies</td>
+</tr>
+ <tr>
+<td><span class="new_code">useCookies()</span></td><td>Enables cookie support</td>
+</tr>
</tbody>
</table>
The methods <span class="new_code">SimpleBrowser::setConnectionTimeout()</span>
<span class="new_code">SimpleBrowser::setMaximumRedirects()</span>,
<span class="new_code">SimpleBrowser::setMaximumNestedFrames()</span>,
- <span class="new_code">SimpleBrowser::ignoreFrames()</span> and
- <span class="new_code">SimpleBrowser::useFrames()</span> continue to apply
+ <span class="new_code">SimpleBrowser::ignoreFrames()</span>,
+ <span class="new_code">SimpleBrowser::useFrames()</span>,
+ <span class="new_code">SimpleBrowser::ignoreCookies()</span> and
+ <span class="new_code">SimpleBrowser::useCokies()</span> continue to apply
to every subsequent request.
The other methods are frames aware.
This means that if you have an individual frame that is not
@@ -332,7 +337,7 @@ class TestOfRegistration extends UnitTestCase {
$browser-&gt;get('http://my-site.com/register.php');
$browser-&gt;setField('email', 'me@here');
$browser-&gt;setField('password', 'Secret');
- $browser-&gt;clickSubmit('Register');
+ $browser-&gt;click('Register');
<strong>
$authenticator = &amp;new Authenticator();
$member = &amp;$authenticator-&gt;findByEmail('me@here');
@@ -361,14 +366,14 @@ class TestOfSecurity extends UnitTestCase {
$first-&gt;get('http://my-site.com/login.php');
$first-&gt;setField('name', 'Me');
$first-&gt;setField('password', 'Secret');
- $first-&gt;clickSubmit('Enter');
+ $first-&gt;click('Enter');
$this-&gt;assertEqual($first-&gt;getTitle(), 'Welcome');
$second = &amp;new SimpleBrowser();
$second-&gt;get('http://my-site.com/login.php');
$second-&gt;setField('name', 'Me');
$second-&gt;setField('password', 'Secret');
- $second-&gt;clickSubmit('Enter');
+ $second-&gt;click('Enter');
$this-&gt;assertEqual($second-&gt;getTitle(), 'Access Denied');</strong>
}
}
diff --git a/tests/test_tools/simpletest/docs/en/expectation_documentation.html b/tests/test_tools/simpletest/docs/en/expectation_documentation.html
index 0165988c..bd189b94 100755
--- a/tests/test_tools/simpletest/docs/en/expectation_documentation.html
+++ b/tests/test_tools/simpletest/docs/en/expectation_documentation.html
@@ -23,9 +23,6 @@
<a href="group_test_documentation.html">Group tests</a>
</li>
<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
<a href="mock_objects_documentation.html">Mock objects</a>
</li>
<li>
@@ -101,8 +98,8 @@
<pre>
class TestOfNewsService extends UnitTestCase {
...
- function testConnectionFailure() {<strong>
- $writer = &amp;new MockWriter($this);
+ function testConnectionFailure() {&lt;strong&gt;
+ $writer = &amp;new MockWriter();
$writer-&gt;expectOnce('write', array(
'Cannot connect to news service ' .
'"BBC News" at this time. ' .
@@ -110,8 +107,6 @@ class TestOfNewsService extends UnitTestCase {
$service = &amp;new NewsService('BBC News');
$service-&gt;publish($writer);
-
- $writer-&gt;tally();</strong>
}
}
</pre>
@@ -129,15 +124,13 @@ class TestOfNewsService extends UnitTestCase {
class TestOfNewsService extends UnitTestCase {
...
function testConnectionFailure() {
- $writer = &amp;new MockWriter($this);<strong>
+ $writer = &amp;new MockWriter();<strong>
$writer-&gt;expectOnce(
'write',
- array(new WantedPatternExpectation('/cannot connect/i')));</strong>
+ array(new PatternExpectation('/cannot connect/i')));</strong>
$service = &amp;new NewsService('BBC News');
$service-&gt;publish($writer);
-
- $writer-&gt;tally();
}
}
</pre>
@@ -179,10 +172,10 @@ class TestOfNewsService extends UnitTestCase {
<td><span class="new_code">NotIndenticalExpectation</span></td><td>Inverts the mock object logic</td>
</tr>
<tr>
-<td><span class="new_code">WantedPatternExpectation</span></td><td>Uses a Perl Regex to match a string</td>
+<td><span class="new_code">PatternExpectation</span></td><td>Uses a Perl Regex to match a string</td>
</tr>
<tr>
-<td><span class="new_code">NoUnwantedPatternExpectation</span></td><td>Passes only if failing a Perl Regex</td>
+<td><span class="new_code">NoPatternExpectation</span></td><td>Passes only if failing a Perl Regex</td>
</tr>
<tr>
<td><span class="new_code">IsAExpectation</span></td><td>Checks the type or class name only</td>
@@ -208,29 +201,26 @@ class TestOfNewsService extends UnitTestCase {
</p>
<p>
The expectation classes can be used not just for sending assertions
- from mock objects, but also for selecting behaviour for either
- the
- <a href="mock_objects_documentation.html">mock objects</a>
- or the
- <a href="server_stubs_documentation.html">server stubs</a>.
+ from mock objects, but also for selecting behaviour for the
+ <a href="mock_objects_documentation.html">mock objects</a>.
Anywhere a list of arguments is given, a list of expectation objects
can be inserted instead.
</p>
<p>
- Suppose we want an authorisation server stub to simulate a successful login
+ Suppose we want an authorisation server mock to simulate a successful login
only if it receives a valid session object.
We can do this as follows...
<pre>
-Stub::generate('Authorisation');
+Mock::generate('Authorisation');
<strong>
-$authorisation = new StubAuthorisation();
+$authorisation = new MockAuthorisation();
$authorisation-&gt;setReturnValue(
'isAllowed',
true,
array(new IsAExpectation('Session', 'Must be a session')));
$authorisation-&gt;setReturnValue('isAllowed', false);</strong>
</pre>
- We have set the default stub behaviour to return false when
+ We have set the default mock behaviour to return false when
<span class="new_code">isAllowed</span> is called.
When we call the method with a single parameter that
is a <span class="new_code">Session</span> object, it will return true.
@@ -299,14 +289,14 @@ $authorisation-&gt;setReturnValue('isAllowed', false);</strong>
</p>
<p>
The most crude way of doing this is to use the
- <span class="new_code">SimpleTest::assertExpectation()</span> method to
+ <span class="new_code">SimpleTest::assert()</span> method to
test against it directly...
<pre>
<strong>class TestOfNetworking extends UnitTestCase {
...
function testGetValidIp() {
$server = &amp;new Server();
- $this-&gt;assertExpectation(
+ $this-&gt;assert(
new ValidIp(),
$server-&gt;getIp(),
'Server IP address-&gt;%s');
@@ -327,7 +317,7 @@ $authorisation-&gt;setReturnValue('isAllowed', false);</strong>
class TestOfNetworking extends UnitTestCase {
...<strong>
function assertValidIp($ip, $message = '%s') {
- $this-&gt;assertExpectation(new ValidIp(), $ip, $message);
+ $this-&gt;assert(new ValidIp(), $ip, $message);
}</strong>
function testGetValidIp() {
diff --git a/tests/test_tools/simpletest/docs/en/form_testing_documentation.html b/tests/test_tools/simpletest/docs/en/form_testing_documentation.html
index b1e15b3d..50b634c0 100755
--- a/tests/test_tools/simpletest/docs/en/form_testing_documentation.html
+++ b/tests/test_tools/simpletest/docs/en/form_testing_documentation.html
@@ -21,9 +21,6 @@
<a href="group_test_documentation.html">Group tests</a>
</li>
<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
<a href="mock_objects_documentation.html">Mock objects</a>
</li>
<li>
@@ -96,7 +93,9 @@ class SimpleFormTests extends WebTestCase {
their default values just as they would appear in the web browser.
The assertion tests that a HTML widget exists in the page with the
name "a" and that it is currently set to the value
- "A default"
+ "A default".
+ As usual, we could use a pattern expectation instead if a fixed
+ string.
</p>
<p>
We could submit the form straight away, but first we'll change
@@ -108,7 +107,7 @@ class SimpleFormTests extends WebTestCase {
$this-&gt;get('http://www.my-site.com/');
$this-&gt;assertField('a', 'A default');<strong>
$this-&gt;setField('a', 'New value');
- $this-&gt;clickSubmit('Go');</strong>
+ $this-&gt;click('Go');</strong>
}
}
</pre>
@@ -235,7 +234,7 @@ class SimpleFormTests extends WebTestCase {
$this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
$this-&gt;assertField('crud', array('c', 'r', 'u', 'd'));
$this-&gt;setField('crud', array('r'));
- $this-&gt;clickSubmit('Enable Privileges');
+ $this-&gt;click('Enable Privileges');
}</strong>
}
</pre>
@@ -261,7 +260,7 @@ class SimpleFormTests extends WebTestCase {
$this-&gt;post(
'http://www.my-site.com/add_user.php',
array('type' =&gt; 'superuser'));
- $this-&gt;assertNoUnwantedPattern('/user created/i');
+ $this-&gt;assertNoText('user created');
}</strong>
}
</pre>
diff --git a/tests/test_tools/simpletest/docs/en/group_test_documentation.html b/tests/test_tools/simpletest/docs/en/group_test_documentation.html
index adbc66ef..1e14d31e 100755
--- a/tests/test_tools/simpletest/docs/en/group_test_documentation.html
+++ b/tests/test_tools/simpletest/docs/en/group_test_documentation.html
@@ -21,9 +21,6 @@
<span class="chosen">Group tests</span>
</li>
<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
<a href="mock_objects_documentation.html">Mock objects</a>
</li>
<li>
@@ -87,7 +84,7 @@
class MyFileTestCase extends UnitTestCase {
...
}
- SimpleTestOptions::ignore('MyFileTestCase');</strong>
+ SimpleTest::ignore('MyFileTestCase');</strong>
class FileTester extends MyFileTestCase {
...
diff --git a/tests/test_tools/simpletest/docs/en/index.html b/tests/test_tools/simpletest/docs/en/index.html
index 04797272..c7183c49 100755
--- a/tests/test_tools/simpletest/docs/en/index.html
+++ b/tests/test_tools/simpletest/docs/en/index.html
@@ -24,9 +24,6 @@
<a href="group_test_documentation.html">Group tests</a>
</li>
<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
<a href="mock_objects_documentation.html">Mock objects</a>
</li>
<li>
@@ -101,26 +98,22 @@
We start by creating a test script which we will call
<em>tests/log_test.php</em> and populate it as follows...
<pre>
-<strong>&lt;?php
-require_once('simpletest/unit_tester.php');
-require_once('simpletest/reporter.php');
-require_once('../classes/log.php');
-?&gt;</strong>
-</pre>
- Here the <em>simpletest</em> folder is either local or in the path.
- You would have to edit these locations depending on where you
- placed the toolset.
- Next we create a test case...
-<pre>
-&lt;?php
+&lt;?php<strong>
require_once('simpletest/unit_tester.php');
require_once('simpletest/reporter.php');
require_once('../classes/log.php');
-<strong>
+
class TestOfLogging extends UnitTestCase {
}</strong>
?&gt;
</pre>
+ Here the <em>simpletest</em> folder is either local or in the path.
+ You would have to edit these locations depending on where you
+ placed the toolset.
+ The <span class="new_code">TestOfLogging</span> is our frst test case and it's
+ currently empty.
+ </p>
+ <p>
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 <span class="new_code">Log</span> class
@@ -376,21 +369,15 @@ Mock::generate('Log');</strong>
class TestOfSessionLogging extends UnitTestCase {
function testLogInIsLogged() {<strong>
- $log = &amp;new MockLog($this);
+ $log = &amp;new MockLog();
$log-&gt;expectOnce('message', array('User fred logged in.'));</strong>
$session_pool = &amp;new SessionPool($log);
- $session_pool-&gt;logIn('fred');<strong>
- $log-&gt;tally();</strong>
+ $session_pool-&gt;logIn('fred');
}
}
?&gt;
</pre>
- The <span class="new_code">tally()</span> call is needed to
- tell the mock object that time is up for the expected call
- count.
- Without it the mock would wait forever for the method
- call to come in without ever actually notifying the test case.
- The other test will be triggered when the call to
+ The test will be triggered when the call to
<span class="new_code">message()</span> is invoked on the
<span class="new_code">MockLog</span> object.
The mock call will trigger a parameter comparison and then send the
@@ -399,6 +386,13 @@ class TestOfSessionLogging extends UnitTestCase {
becoming too specific.
</p>
<p>
+ If the mock reaches the end of the test case without the
+ method being called, the <span class="new_code">expectOnce()</span>
+ expectation will trigger a test failure.
+ In other words the mocks can detect the absence of
+ behaviour as well as the presence.
+ </p>
+ <p>
The mock objects in the SimpleTest suite can have arbitrary
return values set, sequences of returns, return values
selected according to the incoming arguments, sequences of
@@ -439,12 +433,12 @@ class TestOfAbout extends WebTestCase {
function setUp() {
$this-&gt;get('http://test-server/index.php');
- $this-&gt;clickLink('About');
+ $this-&gt;click('About');
}
function testSearchEngineOptimisations() {
$this-&gt;assertTitle('A long title about us for search engines');
- $this-&gt;assertWantedPattern('/a popular keyphrase/i');
+ $this-&gt;assertPattern('/a popular keyphrase/i');
}
}</strong>
$test = &amp;new TestOfAbout();
diff --git a/tests/test_tools/simpletest/docs/en/mock_objects_documentation.html b/tests/test_tools/simpletest/docs/en/mock_objects_documentation.html
index 2f8a1f90..eb32c619 100755
--- a/tests/test_tools/simpletest/docs/en/mock_objects_documentation.html
+++ b/tests/test_tools/simpletest/docs/en/mock_objects_documentation.html
@@ -21,9 +21,6 @@
<a href="group_test_documentation.html">Group tests</a>
</li>
<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
<span class="chosen">Mock objects</span>
</li>
<li>
@@ -76,7 +73,17 @@
</p>
<p>
If mock objects only behaved as actors they would simply be
- known as <a href="server_stubs_documentation.html">server stubs</a>.
+ known as server stubs.
+ This was originally a pattern named by Robert Binder (Testing
+ object-oriented systems: models, patterns, and tools,
+ Addison-Wesley) in 1999.
+ </p>
+ <p>
+ A server stub is a simulation of an object or component.
+ It should exactly replace a component in a system for test
+ or prototyping purposes, but remain lightweight.
+ This allows tests to run more quickly, or if the simulated
+ class has not been written, to run at all.
</p>
<p>
However, the mock objects not only play a part (by supplying chosen
@@ -87,6 +94,8 @@
If expectations are not met they save us the effort of
writing a failed test assertion by performing that duty on our
behalf.
+ </p>
+ <p>
In the case of an imaginary database connection they can
test that the query, say SQL, was correctly formed by
the object that is using the connection.
@@ -138,7 +147,7 @@ Mock::generate('DatabaseConnection');
class MyTestCase extends UnitTestCase {
function testSomething() {
- $connection = &amp;new MockDatabaseConnection($this);
+ $connection = &amp;new MockDatabaseConnection();
}
}</strong>
</pre>
@@ -155,19 +164,27 @@ class MyTestCase extends UnitTestCase {
</a>
</p>
<p>
- The mock version of a class has all the methods of the original
+ The mock version of a class has all the methods of the original,
so that operations like
<span class="new_code">$connection-&gt;query()</span> are still
legal.
- As with stubs we can replace the default null return values...
+ The return value will be <span class="new_code">null</span>,
+ but we can change that with...
<pre>
-<strong>$connection-&gt;setReturnValue('query', 37);</strong>
+<strong>$connection-&gt;setReturnValue('query', 37)</strong>
</pre>
Now every time we call
<span class="new_code">$connection-&gt;query()</span> we get
the result of 37.
- As with the stubs we can set wildcards and we can overload the
- wildcard parameter.
+ We can set the return value to anything, say a hash of
+ imaginary database results or a list of persistent objects.
+ Parameters are irrelevant here, we always get the same
+ values back each time once they have been set up this way.
+ That may not sound like a convincing replica of a
+ database connection, but for the half a dozen lines of
+ a test method it is usually all you need.
+ </p>
+ <p>
We can also add extra methods to the mock when generating it
and choose our own class name...
<pre>
@@ -180,8 +197,12 @@ class MyTestCase extends UnitTestCase {
You can create a special mock to simulate this situation.
</p>
<p>
- All of the patterns available with server stubs are available
- to mock objects...
+ Things aren't always that simple though.
+ One common problem is iterators, where constantly returning
+ the same value could cause an endless loop in the object
+ being tested.
+ For these we need to set up sequences of values.
+ Let's say we have a simple iterator that looks like this...
<pre>
class Iterator {
function Iterator() {
@@ -191,7 +212,8 @@ class Iterator {
}
}
</pre>
- Again, assuming that this iterator only returns text until it
+ This is about the simplest iterator you could have.
+ Assuming that this iterator only returns text until it
reaches the end, when it returns false, we can simulate it
with...
<pre>
@@ -200,7 +222,7 @@ Mock::generate('Iterator');
class IteratorTest extends UnitTestCase() {
function testASequence() {<strong>
- $iterator = &amp;new MockIterator($this);
+ $iterator = &amp;new MockIterator();
$iterator-&gt;setReturnValue('next', false);
$iterator-&gt;setReturnValueAt(0, 'next', 'First string');
$iterator-&gt;setReturnValueAt(1, 'next', 'Second string');</strong>
@@ -218,7 +240,10 @@ class IteratorTest extends UnitTestCase() {
The constant one is a kind of default if you like.
</p>
<p>
- A repeat of the stubbed information holder with name/value pairs...
+ Another tricky situation is an overloaded
+ <span class="new_code">get()</span> operation.
+ An example of this is an information holder with name/value pairs.
+ Say we have a configuration class like...
<pre>
class Configuration {
function Configuration() {
@@ -237,7 +262,7 @@ class Configuration {
we want different results for different keys.
Luckily the mocks have a filter system...
<pre>
-<strong>$config = &amp;new MockConfiguration($this);
+<strong>$config = &amp;new MockConfiguration();
$config-&gt;setReturnValue('getValue', 'primary', array('db_host'));
$config-&gt;setReturnValue('getValue', 'admin', array('db_user'));
$config-&gt;setReturnValue('getValue', 'secret', array('db_password'));</strong>
@@ -258,9 +283,35 @@ $config-&gt;getValue('db_user')
a complete match is found.
</p>
<p>
+ You can set a default argument argument like so...
+<pre>
+<strong>
+$config-&gt;setReturnValue('getValue', false, array('*'));</strong>
+</pre>
+ This is not the same as setting the return value without
+ any argument requirements like this...
+<pre>
+<strong>
+$config-&gt;setReturnValue('getValue', false);</strong>
+</pre>
+ In the first case it will accept any single argument,
+ but exactly one is required.
+ In the second case any number of arguments will do and
+ it acts as a catchall after all other matches.
+ Note that if we add further single parameter options after
+ the wildcard in the first case, they will be ignored as the wildcard
+ will match first.
+ With complex parameter lists the ordering could be important
+ or else desired matches could be masked by earlier wildcard
+ ones.
+ Declare the most specific matches first if you are not sure.
+ </p>
+ <p>
There are times when you want a specific object to be
dished out by the mock rather than a copy.
- Again this is identical to the server stubs mechanism...
+ The PHP4 copy semantics force us to use a different method
+ for this.
+ You might be simulating a container for example...
<pre>
class Thing {
}
@@ -276,14 +327,79 @@ class Vector {
In this case you can set a reference into the mock's
return list...
<pre>
-$thing = new Thing();<strong>
-$vector = &amp;new MockVector($this);
+$thing = &amp;new Thing();<strong>
+$vector = &amp;new MockVector();
$vector-&gt;setReturnReference('get', $thing, array(12));</strong>
</pre>
With this arrangement you know that every time
<span class="new_code">$vector-&gt;get(12)</span> is
called it will return the same
<span class="new_code">$thing</span> each time.
+ This is compatible with PHP5 as well.
+ </p>
+ <p>
+ These three factors, timing, parameters and whether to copy,
+ can be combined orthogonally.
+ For example...
+<pre>
+$complex = &amp;new MockComplexThing();
+$stuff = &amp;new Stuff();<strong>
+$complex-&gt;setReturnReferenceAt(3, 'get', $stuff, array('*', 1));</strong>
+</pre>
+ This will return the <span class="new_code">$stuff</span> 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.
+ </p>
+ <p>
+ A final tricky case is one object creating another, known
+ as a factory pattern.
+ Suppose that on a successful query to our imaginary
+ database, a result set is returned as an iterator with
+ each call to <span class="new_code">next()</span> giving
+ one row until false.
+ This sounds like a simulation nightmare, but in fact it can all
+ be mocked using the mechanics above.
+ </p>
+ <p>
+ Here's how...
+<pre>
+Mock::generate('DatabaseConnection');
+Mock::generate('ResultIterator');
+
+class DatabaseTest extends UnitTestCase {
+
+ function testUserFinder() {<strong>
+ $result = &amp;new MockResultIterator();
+ $result-&gt;setReturnValue('next', false);
+ $result-&gt;setReturnValueAt(0, 'next', array(1, 'tom'));
+ $result-&gt;setReturnValueAt(1, 'next', array(3, 'dick'));
+ $result-&gt;setReturnValueAt(2, 'next', array(6, 'harry'));
+
+ $connection = &amp;new MockDatabaseConnection();
+ $connection-&gt;setReturnValue('query', false);
+ $connection-&gt;setReturnReference(
+ 'query',
+ $result,
+ array('select id, name from users'));</strong>
+
+ $finder = &amp;new UserFinder($connection);
+ $this-&gt;assertIdentical(
+ $finder-&gt;findNames(),
+ array('tom', 'dick', 'harry'));
+ }
+}
+</pre>
+ Now only if our
+ <span class="new_code">$connection</span> is called with the correct
+ <span class="new_code">query()</span> will the
+ <span class="new_code">$result</span> be returned that is
+ itself exhausted after the third call to <span class="new_code">next()</span>.
+ This should be enough
+ information for our <span class="new_code">UserFinder</span> class,
+ the class actually
+ being tested here, to come up with goods.
+ A very precise test and not a real database in sight.
</p>
<p>
@@ -388,18 +504,16 @@ Mock::generate('Log');
class LoggingSessionPoolTest extends UnitTestCase {
...
function testFindSessionLogging() {<strong>
- $session = &amp;new MockSession($this);
- $pool = &amp;new MockSessionPool($this);
+ $session = &amp;new MockSession();
+ $pool = &amp;new MockSessionPool();
$pool-&gt;setReturnReference('findSession', $session);
$pool-&gt;expectOnce('findSession', array('abc'));
- $log = &amp;new MockLog($this);
+ $log = &amp;new MockLog();
$log-&gt;expectOnce('message', array('Starting session abc'));
$logging_pool = &amp;new LoggingSessionPool($pool, $log);
- $this-&gt;assertReference($logging_pool-&gt;findSession('abc'), $session);
- $pool-&gt;tally();
- $log-&gt;tally();</strong>
+ $this-&gt;assertReference($logging_pool-&gt;findSession('abc'), $session);</strong>
}
}
</pre>
@@ -427,15 +541,6 @@ class LoggingSessionPoolTest extends UnitTestCase {
evaluation is the same.
</p>
<p>
- 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
- <span class="new_code">tally()</span> call at the end of
- the test.
- </p>
- <p>
We use the same pattern to set up the mock logger.
We tell it that it should have
<span class="new_code">message()</span> invoked
@@ -448,11 +553,6 @@ class LoggingSessionPoolTest extends UnitTestCase {
<span class="new_code">LoggingSessionPool</span> and feed
it our preset mock objects.
Everything is now under our control.
- Finally we confirm that the
- <span class="new_code">$session</span> we gave our decorator
- is the one that we get back and tell the mocks to run their
- internal call count tests with the
- <span class="new_code">tally()</span> calls.
</p>
<p>
This is still quite a bit of test code, but the code is very
@@ -477,11 +577,11 @@ class LoggingSessionPoolTest extends UnitTestCase {
</thead>
<tbody>
<tr>
- <td><span class="new_code">expectArguments($method, $args)</span></td>
+ <td><span class="new_code">expect($method, $args)</span></td>
<td style="text-align: center">No</td>
</tr>
<tr>
- <td><span class="new_code">expectArgumentsAt($timing, $method, $args)</span></td>
+ <td><span class="new_code">expectAt($timing, $method, $args)</span></td>
<td style="text-align: center">No</td>
</tr>
<tr>
@@ -589,8 +689,8 @@ class LoggingSessionPoolTest extends UnitTestCase {
<strong>
Mock::generate('Connection', 'BasicMockConnection');
class MockConnection extends BasicMockConnection {
- function MockConnection(&amp;$test, $wildcard = '*') {
- $this-&gt;BasicMockConnection($test, $wildcard);
+ function MockConnection() {
+ $this-&gt;BasicMockConnection();
$this-&gt;setReturn('query', false);
}
}</strong>
@@ -619,92 +719,6 @@ class LoggingSessionPoolTest extends UnitTestCase {
stages of testing.
</p>
- <p>
-<a class="target" name="other_testers">
-<h2>I think SimpleTest stinks!</h2>
-</a>
-</p>
- <p>
- But at the time of writing it is the only one with mock objects,
- so are you stuck with it?
- </p>
- <p>
- No, not at all.
- <a href="simple_test.html">SimpleTest</a> 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...
-<pre>
-class PHPUnit {
- function PHPUnit() {
- }
-
- function assertion($message, $assertion) {
- }
- ...
-}
-</pre>
- All the <span class="new_code">assertion()</span> 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...
-<pre>
-$unit_test = new PHPUnit();
-$unit_test&gt;assertion('I hope this file exists', file_exists('my_file'));
-</pre>
- How do you use mocks with this?
- </p>
- <p>
- There is a protected method on the base mock class
- <span class="new_code">SimpleMock</span> called
- <span class="new_code">_assertTrue()</span> and
- by overriding this method we can use our own assertion format.
- We start with a subclass, in say <em>my_mock.php</em>...
-<pre>
-<strong>&lt;?php
- require_once('simpletest/mock_objects.php');
-
- class MyMock extends SimpleMock() {
- function MyMock(&amp;$test, $wildcard) {
- $this-&gt;SimpleMock($test, $wildcard);
- }
-
- function _assertTrue($assertion, $message) {
- $test = &amp;$this-&gt;getTest();
- $test-&gt;assertion($message, $assertion);
- }
- }
-?&gt;</strong>
-</pre>
- Now instantiating <span class="new_code">MyMock</span> 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...
-<pre>
-&lt;?php
- require_once('simpletst/mock_objects.php');
-
- class MyMock extends SimpleMock() {
- function MyMock($test, $wildcard) {
- $this-&gt;SimpleMock(&amp;$test, $wildcard);
- }
-
- function _assertTrue($assertion, $message , &amp;$test) {
- $test-&gt;assertion($message, $assertion);
- }
- }<strong>
- SimpleTestOptions::setMockBaseClass('MyMock');</strong>
-?&gt;
-</pre>
- From now on you just include <em>my_mock.php</em> instead of the
- default <em>mock_objects.php</em> version and you can introduce
- mock objects into your existing test suite.
- </p>
-
</div>
<div class="copyright">
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
diff --git a/tests/test_tools/simpletest/docs/en/overview.html b/tests/test_tools/simpletest/docs/en/overview.html
index d4965de3..5d4e80e2 100755
--- a/tests/test_tools/simpletest/docs/en/overview.html
+++ b/tests/test_tools/simpletest/docs/en/overview.html
@@ -23,9 +23,6 @@
<a href="group_test_documentation.html">Group tests</a>
</li>
<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
<a href="mock_objects_documentation.html">Mock objects</a>
</li>
<li>
@@ -151,8 +148,7 @@ class <strong>MySiteTest</strong> extends WebTestCase {
milestones rather depends on time available.
Green stuff has been coded, but not necessarily released yet.
If you have a pressing need for a green but unreleased feature
- then you should check-out the code from sourceforge CVS directly.
- A released feature is marked as "Done".
+ then you should check-out the code from Sourceforge CVS directly.
<table>
<thead>
<tr>
@@ -163,12 +159,12 @@ class <strong>MySiteTest</strong> extends WebTestCase {
<tr>
<td>Unit test case</td>
<td>Core test case class and assertions</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>Html display</td>
<td>Simplest possible display</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>Autoloading of test cases</td>
@@ -176,41 +172,20 @@ class <strong>MySiteTest</strong> extends WebTestCase {
Reading a file with test cases and loading them into a
group test automatically
</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
- <td>Mock objects code generator</td>
+ <td>Mock objects</td>
<td>
Objects capable of simulating other objects removing
test dependencies
</td>
- <td style="color: green;">Done</td>
- </tr>
- <tr>
- <td>Server stubs</td>
- <td>
- Mocks without expectations to be used outside of test cases,
- e.g. for prototyping
- </td>
- <td style="color: green;">Done</td>
- </tr>
- <tr>
- <td>Integration of other unit testers</td>
- <td>
- The ability to read and simulate test cases from PHPUnit
- and PEAR::PhpUnit
- </td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>Web test case</td>
- <td>Basic pattern matching of fetched pages</td>
- <td style="color: green;">Done</td>
- </tr>
- <tr>
- <td>HTML parsing of pages</td>
<td>Allows link following and title tag matching</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>Partial mocks</td>
@@ -218,32 +193,32 @@ class <strong>MySiteTest</strong> extends WebTestCase {
Mocking parts of a class for testing less than a class
or for complex simulations
</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>Web cookie handling</td>
<td>Correct handling of cookies when fetching pages</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>Following redirects</td>
<td>Page fetching automatically follows 300 redirects</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>Form parsing</td>
<td>Ability to submit simple forms and read default form values</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>Command line interface</td>
<td>Test display without the need of a web browser</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>Exposure of expectation classes</td>
<td>Can create precise tests with mocks as well as test cases</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>XML output and parsing</td>
@@ -251,25 +226,15 @@ class <strong>MySiteTest</strong> extends WebTestCase {
Allows multi host testing and the integration of acceptance
testing extensions
</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
- <td>Command line test case</td>
- <td>Allows testing of utilities and file handling</td>
- <td style="color: green;">Done</td>
- </tr>
- <tr>
- <td>PHP Documentor compatibility</td>
- <td>Fully generated class level documentation</td>
- <td style="color: green;">Done</td>
- </tr>
- <tr>
- <td>Browser interface</td>
+ <td>Browser component</td>
<td>
Exposure of lower level web browser interface for more
detailed test cases
</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>HTTP authentication</td>
@@ -277,31 +242,39 @@ class <strong>MySiteTest</strong> extends WebTestCase {
Fetching protected web pages with basic authentication
only
</td>
- <td style="color: green;">Done</td>
- </tr>
- <tr>
- <td>Browser navigation buttons</td>
- <td>Back, forward and retry</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>SSL support</td>
<td>Can connect to https: pages</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>Proxy support</td>
<td>Can connect via. common proxies</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
</tr>
<tr>
<td>Frames support</td>
<td>Handling of frames in web test cases</td>
- <td style="color: green;">Done</td>
+ <td style="color: green;">1.0</td>
+ </tr>
+ <tr>
+ <td>File upload testing</td>
+ <td>Can simulate the input type file tag</td>
+ <td style="color: green;">1.0.1</td>
+ </tr>
+ <tr>
+ <td>Mocking interfaces</td>
+ <td>
+ Can generate mock objects to interfaces as well as classes
+ and class interfaces are carried for type hints
+ </td>
+ <td style="color: green;">1.0.1</td>
</tr>
<tr>
- <td>Improved display</td>
- <td>Better web GUI with tree display of test cases</td>
+ <td>Reporting machinery enhancements</td>
+ <td>Improved message passing for better cooperation with IDEs</td>
<td style="color: red;">1.1</td>
</tr>
<tr>
@@ -310,28 +283,43 @@ class <strong>MySiteTest</strong> extends WebTestCase {
<td style="color: red;">1.1</td>
</tr>
<tr>
- <td>File upload testing</td>
- <td>Can simulate the input type file tag</td>
+ <td>Testing exceptions</td>
+ <td>Similar to testing PHP errors</td>
<td style="color: red;">1.1</td>
</tr>
<tr>
- <td>Mocking interfaces</td>
- <td>Can generate mock objects to interfaces as well as classes</td>
+ <td>IFrame support</td>
+ <td>Reads IFrame content that can be refreshed</td>
+ <td style="color: red;">1.1</td>
+ </tr>
+ <tr>
+ <td>Improved mock interface</td>
+ <td>More compact way of expressing mocks</td>
<td style="color: red;">2.0</td>
</tr>
<tr>
- <td>Testing exceptions</td>
- <td>Similar to testing PHP errors</td>
+ <td>HTML table assertions</td>
+ <td>Can match table elements to numerical assertions</td>
+ <td style="color: red;">2.0</td>
+ </tr>
+ <tr>
+ <td>XPath searching of HTML elements</td>
+ <td>More flexible content matching</td>
<td style="color: red;">2.0</td>
</tr>
<tr>
- <td>XPath searching of elements</td>
- <td>Can make use of HTML tidy for faster and more flexible content matching</td>
+ <td>Alternate HTML parsers</td>
+ <td>Can detect compiled parsers for performance improvements</td>
<td style="color: red;">2.0</td>
</tr>
+ <tr>
+ <td>Javascript suport</td>
+ <td>Use of PECL module to add Javascript</td>
+ <td style="color: red;">3.0</td>
+ </tr>
</tbody>
</table>
- PHP5 migraton will start straight after the version 1.1 series,
+ PHP5 migraton will start straight after the version 1.0.1 series,
whereupon PHP4 will no longer be supported.
SimpleTest is currently compatible with PHP5, but will not
make use of all of the new features until version 2.
@@ -375,18 +363,6 @@ class <strong>MySiteTest</strong> extends WebTestCase {
existing <a href="http://www.junit.org/">JUnit</a> test cases.
</p>
<p>
- 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
- <a href="http://wact.sourceforge.net/">WACT</a> and
- <a href="http://sourceforge.net/projects/htmlsax">PEAR::XML_HTMLSax</a>.
- </p>
- <p>
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 <a href="http://www.sidewize.com/company/mockobjects.pdf">original mock objects paper</a>
@@ -394,14 +370,15 @@ class <strong>MySiteTest</strong> extends WebTestCase {
As a new technology there are plenty of discussions and debate on how to use mocks,
often on Wikis such as
<a href="http://xpdeveloper.com/cgi-bin/oldwiki.cgi?MockObjects">Extreme Tuesday</a>
- or <a href="http://www.mockobjects.com/wiki/MocksObjectsPaper">www.mockobjects.com</a>
+ or <a href="http://www.mockobjects.com/MocksObjectsPaper.html">www.mockobjects.com</a>
or <a href="http://c2.com/cgi/wiki?MockObject">the original C2 Wiki</a>.
Injecting mocks into a class is the main area of debate for which this
<a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html">paper on IBM</a>
makes a good starting point.
</p>
<p>
- There are plenty of web testing tools, but most are written in Java and
+ There are plenty of web testing tools, but the scriptable ones
+ are mostly are written in Java and
tutorials and advice are rather thin on the ground.
The only hope is to look at the documentation for
<a href="http://httpunit.sourceforge.net/">HTTPUnit</a>,
@@ -409,6 +386,13 @@ class <strong>MySiteTest</strong> extends WebTestCase {
or <a href="http://jwebunit.sourceforge.net/">JWebUnit</a> and hope for clues.
There are some XML driven test frameworks, but again most
require Java to run.
+ </p>
+ <p>
+ A new generation of tools that run directly in the web browser
+ are now available.
+ These include
+ <a href="http://www.openqa.org/selenium/">Selenium</a> and
+ <a href="http://wtr.rubyforge.org/">Watir</a>.
As SimpleTest does not support JavaScript you would probably
have to look at these tools anyway if you have highly dynamic
pages.
diff --git a/tests/test_tools/simpletest/docs/en/partial_mocks_documentation.html b/tests/test_tools/simpletest/docs/en/partial_mocks_documentation.html
index 20749415..6d7b6243 100755
--- a/tests/test_tools/simpletest/docs/en/partial_mocks_documentation.html
+++ b/tests/test_tools/simpletest/docs/en/partial_mocks_documentation.html
@@ -21,9 +21,6 @@
<a href="group_test_documentation.html">Group tests</a>
</li>
<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
<a href="mock_objects_documentation.html">Mock objects</a>
</li>
<li>
diff --git a/tests/test_tools/simpletest/docs/en/reporter_documentation.html b/tests/test_tools/simpletest/docs/en/reporter_documentation.html
index 44be8b1e..ead61175 100755
--- a/tests/test_tools/simpletest/docs/en/reporter_documentation.html
+++ b/tests/test_tools/simpletest/docs/en/reporter_documentation.html
@@ -21,9 +21,6 @@
<a href="group_test_documentation.html">Group tests</a>
</li>
<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
<a href="mock_objects_documentation.html">Mock objects</a>
</li>
<li>
diff --git a/tests/test_tools/simpletest/docs/en/unit_test_documentation.html b/tests/test_tools/simpletest/docs/en/unit_test_documentation.html
index 6aa8d8a7..47b61eca 100755
--- a/tests/test_tools/simpletest/docs/en/unit_test_documentation.html
+++ b/tests/test_tools/simpletest/docs/en/unit_test_documentation.html
@@ -21,9 +21,6 @@
<a href="group_test_documentation.html">Group tests</a>
</li>
<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
<a href="mock_objects_documentation.html">Mock objects</a>
</li>
<li>
@@ -164,6 +161,12 @@ class FileTestCase extends UnitTestCase {
<td><span class="new_code">assertNotEqual($x, $y)</span></td><td>Fail if $x == $y is true</td>
</tr>
<tr>
+<td><span class="new_code">assertWithinMargin($x, $y, $m)</span></td><td>Fail if abs($x - $y) &lt; $m is false</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertOutsideMargin($x, $y, $m)</span></td><td>Fail if abs($x - $y) &lt; $m is true</td>
+</tr>
+ <tr>
<td><span class="new_code">assertIdentical($x, $y)</span></td><td>Fail if $x == $y is false or a type mismatch</td>
</tr>
<tr>
@@ -176,19 +179,19 @@ class FileTestCase extends UnitTestCase {
<td><span class="new_code">assertCopy($x, $y)</span></td><td>Fail if $x and $y are the same variable</td>
</tr>
<tr>
-<td><span class="new_code">assertWantedPattern($p, $x)</span></td><td>Fail unless the regex $p matches $x</td>
+<td><span class="new_code">assertPattern($p, $x)</span></td><td>Fail unless the regex $p matches $x</td>
</tr>
<tr>
-<td><span class="new_code">assertNoUnwantedPattern($p, $x)</span></td><td>Fail if the regex $p matches $x</td>
+<td><span class="new_code">assertNoPattern($p, $x)</span></td><td>Fail if the regex $p matches $x</td>
</tr>
<tr>
<td><span class="new_code">assertNoErrors()</span></td><td>Fail if any PHP error occoured</td>
</tr>
<tr>
-<td><span class="new_code">assertError($x)</span></td><td>Fail if no PHP error or incorrect message</td>
+<td><span class="new_code">assertError($x)</span></td><td>Fail if no PHP error or incorrect message/expectation</td>
</tr>
<tr>
-<td><span class="new_code">assertErrorPattern($p)</span></td><td>Fail unless the error matches the regex $p</td>
+<td><span class="new_code">assertExpectation($e)</span></td><td>Fail on failed expectation object</td>
</tr>
</tbody>
</table>
@@ -226,7 +229,7 @@ $this-&gt;assertReference($a, $b);</strong>
</pre>
Will fail as the variable <span class="new_code">$a</span> is a copy of <span class="new_code">$b</span>.
<pre>
-<strong>$this-&gt;assertWantedPattern('/hello/i', 'Hello world');</strong>
+<strong>$this-&gt;assertPattern('/hello/i', 'Hello world');</strong>
</pre>
This will pass as using a case insensitive match the string
<span class="new_code">hello</span> is contained in <span class="new_code">Hello world</span>.
diff --git a/tests/test_tools/simpletest/docs/en/web_tester_documentation.html b/tests/test_tools/simpletest/docs/en/web_tester_documentation.html
index 51f604be..99dacacc 100755
--- a/tests/test_tools/simpletest/docs/en/web_tester_documentation.html
+++ b/tests/test_tools/simpletest/docs/en/web_tester_documentation.html
@@ -21,9 +21,6 @@
<a href="group_test_documentation.html">Group tests</a>
</li>
<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
<a href="mock_objects_documentation.html">Mock objects</a>
</li>
<li>
@@ -153,7 +150,7 @@ class TestOfLastcraft extends WebTestCase {
function testHomepage() {<strong>
$this-&gt;get('http://www.lastcraft.com/');
- $this-&gt;assertWantedPattern('/why the last craft/i');</strong>
+ $this-&gt;assertTest('Why the last craft');</strong>
}
}
</pre>
@@ -169,16 +166,16 @@ class TestOfLastcraft extends WebTestCase {
<td><span class="new_code">assertTitle($title)</span></td><td>Pass if title is an exact match</td>
</tr>
<tr>
-<td><span class="new_code">assertWantedPattern($pattern)</span></td><td>A Perl pattern match against the page content</td>
+<td><span class="new_code">assertPattern($pattern)</span></td><td>A Perl pattern match against the page content</td>
</tr>
<tr>
-<td><span class="new_code">assertNoUnwantedPattern($pattern)</span></td><td>A Perl pattern match to not find content</td>
+<td><span class="new_code">assertNoPattern($pattern)</span></td><td>A Perl pattern match to not find content</td>
</tr>
<tr>
-<td><span class="new_code">assertWantedText($text)</span></td><td>Pass if matches visible and "alt" text</td>
+<td><span class="new_code">assertText($text)</span></td><td>Pass if matches visible and "alt" text</td>
</tr>
<tr>
-<td><span class="new_code">assertNoUnwantedText($text)</span></td><td>Pass if doesn't match visible and "alt" text</td>
+<td><span class="new_code">assertNoText($text)</span></td><td>Pass if doesn't match visible and "alt" text</td>
</tr>
<tr>
<td><span class="new_code">assertLink($label)</span></td><td>Pass if a link with this text is present</td>
@@ -217,10 +214,7 @@ class TestOfLastcraft extends WebTestCase {
<td><span class="new_code">assertHeader($header, $content)</span></td><td>Pass if a header was fetched matching this value</td>
</tr>
<tr>
-<td><span class="new_code">assertNoUnwantedHeader($header)</span></td><td>Pass if a header was not fetched</td>
-</tr>
- <tr>
-<td><span class="new_code">assertHeaderPattern($header, $pattern)</span></td><td>Pass if a header was fetched matching this Perl regex</td>
+<td><span class="new_code">assertNoHeader($header)</span></td><td>Pass if a header was not fetched</td>
</tr>
<tr>
<td><span class="new_code">assertCookie($name, $value)</span></td><td>Pass if there is currently a matching cookie</td>
@@ -241,6 +235,10 @@ class TestOfLastcraft extends WebTestCase {
<pre>
<strong>$this-&gt;assertTitle('The Last Craft? Web developer tutorials on PHP, Extreme programming and Object Oriented development');</strong>
</pre>
+ ...or, if that is too long and fragile...
+<pre>
+<strong>$this-&gt;assertTitle(new PatternExpectation('/The Last Craft/'));</strong>
+</pre>
As well as the simple HTML content checks we can check
that the MIME type is in a list of allowed types with...
<pre>
@@ -319,7 +317,7 @@ class TestOfLastcraft extends WebTestCase {
function testContact() {
$this-&gt;get('http://www.lastcraft.com/');<strong>
$this-&gt;clickLink('About');
- $this-&gt;assertTitle('About Last Craft');</strong>
+ $this-&gt;assertTitle(new PatternExpectation('/About Last Craft/'));</strong>
}
}
</pre>
@@ -327,11 +325,16 @@ class TestOfLastcraft extends WebTestCase {
</p>
<p>
If the target is a button rather than an anchor tag, then
- <span class="new_code">clickSubmit()</span> should be used
+ <span class="new_code">clickSubmit()</span> can be used
with the button title...
<pre>
<strong>$this-&gt;clickSubmit('Go!');</strong>
</pre>
+ If you are not sure or don't care, the usual case, then just
+ use the <span class="new_code">click()</span> method...
+<pre>
+<strong>$this-&gt;click('Go!');</strong>
+</pre>
</p>
<p>
The list of navigation methods is...
diff --git a/tests/test_tools/simpletest/docs/fr/authentication_documentation.html b/tests/test_tools/simpletest/docs/fr/authentication_documentation.html
deleted file mode 100755
index 08cc2349..00000000
--- a/tests/test_tools/simpletest/docs/fr/authentication_documentation.html
+++ /dev/null
@@ -1,264 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>Documentation Simple Test : tester l'authentification</title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<a href="index.html">SimpleTest</a>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Documentation sur l'authentification</h1>
-<div class="content">
-
- <p>
- Un des secteurs &agrave; la fois d&eacute;licat et important lors d'un test de site web reste la s&eacute;curit&eacute;. Tester ces sch&eacute;mas est au coeur des objectifs du testeur web de SimpleTest.
- </p>
-
- <p>
-<a class="target" name="basique">
-<h2>Authentification HTTP basique</h2>
-</a>
-</p>
- <p>
- Si vous allez chercher une page web prot&eacute;g&eacute;e par une authentification basique, vous h&eacute;riterez d'une ent&ecirc;te 401. Nous pouvons repr&eacute;senter ceci par ce test...
-<pre>
-class AuthenticationTest extends WebTestCase {<strong>
- function test401Header() {
- $this-&gt;get('http://www.lastcraft.com/protected/');
- $this-&gt;showHeaders();
- }</strong>
-}
-</pre>
- Ce qui nous permet de voir les ent&ecirc;tes re&ccedil;ues...
- <div class="demo">
- <h1>File test</h1>
-<pre style="background-color: lightgray; color: black">
-HTTP/1.1 401 Authorization Required
-Date: Sat, 18 Sep 2004 19:25:18 GMT
-Server: Apache/1.3.29 (Unix) PHP/4.3.4
-WWW-Authenticate: Basic realm="SimpleTest basic authentication"
-Connection: close
-Content-Type: text/html; charset=iso-8859-1
-</pre>
- <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
- <strong>0</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
- </div>
- Sauf que nous voulons &eacute;viter l'inspection visuelle, on souhaite que SimpleTest puisse nous dire si oui ou non la page est prot&eacute;g&eacute;e. Voici un test en profondeur sur nos ent&ecirc;tes...
-<pre>
-class AuthenticationTest extends WebTestCase {
- function test401Header() {
- $this-&gt;get('http://www.lastcraft.com/protected/');<strong>
- $this-&gt;assertAuthentication('Basic');
- $this-&gt;assertResponse(401);
- $this-&gt;assertRealm('SimpleTest basic authentication');</strong>
- }
-}
-</pre>
- N'importe laquelle de ces assertions suffirait, tout d&eacute;pend de la masse de d&eacute;tails que vous souhaitez voir.
- </p>
- <p>
- La plupart du temps, nous ne souhaitons pas tester l'authentification en elle-m&ecirc;me, mais plut&ocirc;t les pages prot&eacute;g&eacute;es par cette authentification. D&egrave;s que la tentative d'authentification est re&ccedil;ue, nous pouvons y r&eacute;pondre &agrave; l'aide d'une r&eacute;ponse d'authentification :
-<pre>
-class AuthenticationTest extends WebTestCase {
- function testAuthentication() {
- $this-&gt;get('http://www.lastcraft.com/protected/');<strong>
- $this-&gt;authenticate('Me', 'Secret');</strong>
- $this-&gt;assertTitle(...);
- }
-}
-</pre>
- Le nom d'utilisateur et le mot de passe seront d&eacute;sormais envoy&eacute;s &agrave; chaque requ&ecirc;te vers ce r&eacute;pertoire et ses sous r&eacute;pertoires. En revanche vous devrez vous authentifier &agrave; nouveau si vous sortez de ce r&eacute;pertoire.
- </p>
- <p>
- Vous pouvez gagner une ligne en d&eacute;finissant l'authentification au niveau de l'URL...
-<pre>
-class AuthenticationTest extends WebTestCase {
- function testCanReadAuthenticatedPages() {
- $this-&gt;get('http://<strong>Me:Secret@</strong>www.lastcraft.com/protected/');
- $this-&gt;assertTitle(...);
- }
-}
-</pre>
- Si votre nom d'utilisateur ou mot de passe comporte des caract&egrave;res sp&eacute;ciaux, alors n'oubliez pas de les encoder, sinon la requ&ecirc;te ne sera pas analys&eacute;e correctement. De plus cette ent&ecirc;te ne sera pas envoy&eacute;e aux sous requ&ecirc;tes si vous la d&eacute;finissez avec une URL absolue. Par contre si vous naviguez avec des URL relatives, l'information d'authentification sera pr&eacute;serv&eacute;e.
- </p>
- <p>
- Pour l'instant, seule l'authentification de base est impl&eacute;ment&eacute;e et elle n'est r&eacute;ellement fiable qu'en tandem avec une connexion HTTPS. C'est g&eacute;n&eacute;ralement suffisant pour prot&eacute;ger le serveur test&eacute; des regards malveillants. Les authentifications Digest et NTLM pourraient &ecirc;tre ajout&eacute;es prochainement.
- </p>
-
- <p>
-<a class="target" name="cookies">
-<h2>Cookies</h2>
-</a>
-</p>
- <p>
- L'authentification de base ne donne pas assez de contr&ocirc;le au d&eacute;veloppeur Web sur l'interface utilisateur. Il y a de forte chance pour que cette fonctionnalit&eacute; soit cod&eacute;e directement dans l'architecture web &agrave; grand renfort de cookies et de timeouts compliqu&eacute;s.
- </p>
- <p>
- Commen&ccedil;ons par un simple formulaire de connexion...
-<pre>
-&lt;form&gt;
- Username:
- &lt;input type="text" name="u" value="" /&gt;&lt;br /&gt;
- Password:
- &lt;input type="password" name="p" value="" /&gt;&lt;br /&gt;
- &lt;input type="submit" value="Log in" /&gt;
-&lt;/form&gt;
-</pre>
- Lequel doit ressembler &agrave;...
- </p>
- <p>
- <form class="demo">
- Username:
- <input type="text" name="u" value="">
-<br>
- Password:
- <input type="password" name="p" value="">
-<br>
- <input type="submit" value="Log in">
- </form>
- </p>
- <p>
- Supposons que, durant le chargement de la page, un cookie ait &eacute;t&eacute; inscrit avec un num&eacute;ro d'identifiant de session. Nous n'allons pas encore remplir le formulaire, juste tester que nous pistons bien l'utilisateur. Voici le test...
-<pre>
-class LogInTest extends WebTestCase {
- function testSessionCookieSetBeforeForm() {
- $this-&gt;get('http://www.my-site.com/login.php');<strong>
- $this-&gt;assertCookie('SID');</strong>
- }
-}
-</pre>
- Nous nous contentons ici de v&eacute;rifier que le cookie a bien &eacute;t&eacute; d&eacute;fini. Etant donn&eacute; que sa valeur est plut&ocirc;t &eacute;nigmatique, elle ne vaut pas la peine d'&ecirc;tre test&eacute;e.
- </p>
- <p>
- Le reste du test est le m&ecirc;me que dans n'importe quel autre formulaire, mais nous pourrions souhaiter nous assurer que le cookie n'a pas &eacute;t&eacute; modifi&eacute; depuis la phase de connexion. Voici comment cela pourrait &ecirc;tre test&eacute; :
-<pre>
-class LogInTest extends WebTestCase {
- ...
- function testSessionCookieSameAfterLogIn() {
- $this-&gt;get('http://www.my-site.com/login.php');<strong>
- $session = $this-&gt;getCookie('SID');
- $this-&gt;setField('u', 'Me');
- $this-&gt;setField('p', 'Secret');
- $this-&gt;clickSubmit('Log in');
- $this-&gt;assertWantedPattern('/Welcome Me/');
- $this-&gt;assertCookie('SID', $session);</strong>
- }
-}
-</pre>
- Ceci confirme que l'identifiant de session est identique avant et apr&egrave;s la connexion.
- </p>
- <p>
- Nous pouvons m&ecirc;me essayer de duper notre propre syst&egrave;me en cr&eacute;ant un cookie arbitraire pour se connecter...
-<pre>
-class LogInTest extends WebTestCase {
- ...
- function testSessionCookieSameAfterLogIn() {
- $this-&gt;get('http://www.my-site.com/login.php');<strong>
- $this-&gt;setCookie('SID', 'Some other session');
- $this-&gt;get('http://www.my-site.com/restricted.php');</strong>
- $this-&gt;assertWantedPattern('/Access denied/');
- }
-}
-</pre>
- Votre site est-il prot&eacute;g&eacute; contre ce type d'attaque ?
- </p>
-
- <p>
-<a class="target" name="session">
-<h2>Sessions de navigateur</h2>
-</a>
-</p>
- <p>
- Si vous testez un syst&egrave;me d'authentification, la reconnexion par un utilisateur est un point sensible. Essayons de simuler ce qui se passe dans ce cas :
-<pre>
-class LogInTest extends WebTestCase {
- ...
- function testLoseAuthenticationAfterBrowserClose() {
- $this-&gt;get('http://www.my-site.com/login.php');
- $this-&gt;setField('u', 'Me');
- $this-&gt;setField('p', 'Secret');
- $this-&gt;clickSubmit('Log in');
- $this-&gt;assertWantedPattern('/Welcome Me/');<strong>
-
- $this-&gt;restart();
- $this-&gt;get('http://www.my-site.com/restricted.php');
- $this-&gt;assertWantedPattern('/Access denied/');</strong>
- }
-}
-</pre>
- La m&eacute;thode <span class="new_code">WebTestCase::restart()</span> pr&eacute;serve les cookies dont le timeout a expir&eacute;, mais conserve les cookies temporaires ou expir&eacute;s. Vous pouvez sp&eacute;cifier l'heure et la date de leur r&eacute;activation.
- </p>
- <p>
- L'expiration des cookies peut &ecirc;tre un probl&egrave;me. Si vous avez un cookie qui doit expirer au bout d'une heure, nous n'allons pas mettre le test en veille en attendant que le cookie expire...
- </p>
- <p>
- Afin de provoquer leur expiration, vous pouvez dater manuellement les cookies, avant le d&eacute;but de la session.
-<pre>
-class LogInTest extends WebTestCase {
- ...
- function testLoseAuthenticationAfterOneHour() {
- $this-&gt;get('http://www.my-site.com/login.php');
- $this-&gt;setField('u', 'Me');
- $this-&gt;setField('p', 'Secret');
- $this-&gt;clickSubmit('Log in');
- $this-&gt;assertWantedPattern('/Welcome Me/');
- <strong>
- $this-&gt;ageCookies(3600);</strong>
- $this-&gt;restart();
- $this-&gt;get('http://www.my-site.com/restricted.php');
- $this-&gt;assertWantedPattern('/Access denied/');
- }
-}
-</pre>
- Apr&egrave;s le red&eacute;marrage, les cookies seront plus vieux d'une heure et que tous ceux dont la date d'expiration sera pass&eacute;e auront disparus.
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/docs/fr/browser_documentation.html b/tests/test_tools/simpletest/docs/fr/browser_documentation.html
deleted file mode 100755
index fa8ad1b6..00000000
--- a/tests/test_tools/simpletest/docs/fr/browser_documentation.html
+++ /dev/null
@@ -1,329 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>Documentation SimpleTest : le composant de navigation web scriptable</title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<a href="index.html">SimpleTest</a>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Documentation sur le navigateur scriptable</h1>
-<div class="content">
-
- <p>
- Le composant de navigation web de SimpleTest peut &ecirc;tre utilis&eacute; non seulement &agrave; l'ext&eacute;rieur de la classe <span class="new_code">WebTestCase</span>, mais aussi ind&eacute;pendamment du frameword SimpleTest lui-m&ecirc;me.
- </p>
-
- <p>
-<a class="target" name="script">
-<h2>Le navigateur scriptable</h2>
-</a>
-</p>
- <p>
- Vous pouvez utiliser le navigateur web dans des scripts PHP pour confirmer que des services marchent bien comme il faut ou pour extraire des informations &agrave; partir de ceux-ci de fa&ccedil;on r&eacute;guli&egrave;re.
- Par exemple, voici un petit script pour extraire le nombre de bogues ouverts dans PHP 5 &agrave; partir du <a href="http://www.php.net/">site web PHP</a>...
-<pre>
-&lt;?php
- require_once('simpletest/browser.php');
-
- $browser = &amp;new SimpleBrowser();
- $browser-&gt;get('http://php.net/');
- $browser-&gt;clickLink('reporting bugs');
- $browser-&gt;clickLink('statistics');
- $browser-&gt;clickLink('PHP 5 bugs only');
- $page = $browser-&gt;getContent();
- preg_match('/status=Open.*?by=Any.*?(\d+)&lt;\/a&gt;/', $page, $matches);
- print $matches[1];
-?&gt;
-</pre>
- Bien s&ucirc;r Il y a des m&eacute;thodes plus simple pour r&eacute;aliser cet exemple en PHP. Par exemple, vous pourriez juste utiliser la commande PHP <span class="new_code">file()</span> sur ce qui est ici une page fixe. Cependant, en utilisant des scripts avec le navigateur web vous vous autorisez l'authentification, la gestion des cookies, le chargement automatique des fen&ecirc;tres, les redirections, la transmission de formulaire et la capacit&eacute; d'examiner les ent&ecirc;tes. De telles m&eacute;thodes sont fragiles dans un site en constante &eacute;volution et vous voudrez employer une m&eacute;thode plus directe pour acc&eacute;der aux donn&eacute;es de fa&ccedil;on permanente, mais pour des t&acirc;ches simples cette technique peut s'av&eacute;rer une solution tr&egrave;s rapide.
- </p>
- <p>
- Toutes les m&eacute;thode de navigation utilis&eacute;es dans <a href="web_tester_documentation.html">WebTestCase</a> sont pr&eacute;sente dans la classe <span class="new_code">SimpleBrowser</span>, mais les assertions sont remplac&eacute;es par de simples accesseurs. Voici une liste compl&egrave;te des m&eacute;thodes de navigation de page &agrave; page...
- <table>
-<tbody>
- <tr>
-<td><span class="new_code">addHeader($header)</span></td><td>Ajouter une ent&ecirc;te &agrave; chaque t&eacute;l&eacute;chargement</td>
-</tr>
- <tr>
-<td><span class="new_code">useProxy($proxy, $username, $password)</span></td><td>Utilise ce proxy &agrave; partir de maintenant</td>
-</tr>
- <tr>
-<td><span class="new_code">head($url, $parameters)</span></td><td>Effectue une requ&ecirc;te HEAD</td>
-</tr>
- <tr>
-<td><span class="new_code">get($url, $parameters)</span></td><td>T&eacute;l&eacute;charge une page avec un GET</td>
-</tr>
- <tr>
-<td><span class="new_code">post($url, $parameters)</span></td><td>T&eacute;l&eacute;charge une page avec un POST</td>
-</tr>
- <tr>
-<td><span class="new_code">clickLink($label)</span></td><td>Suit un lien par son &eacute;tiquette</td>
-</tr>
- <tr>
-<td><span class="new_code">isLink($label)</span></td><td>V&eacute;rifie si un lien avec cette &eacute;tiquette existe</td>
-</tr>
- <tr>
-<td><span class="new_code">clickLinkById($id)</span></td><td>Suit un lien par son attribut d'identification</td>
-</tr>
- <tr>
-<td><span class="new_code">isLinkById($id)</span></td><td>V&eacute;rifie si un lien avec cet attribut d'identification existe</td>
-</tr>
- <tr>
-<td><span class="new_code">getUrl()</span></td><td>La page ou la fen&ecirc;tre URL en cours</td>
-</tr>
- <tr>
-<td><span class="new_code">getTitle()</span></td><td>Le titre de la page</td>
-</tr>
- <tr>
-<td><span class="new_code">getContent()</span></td><td>Le page ou la fen&ecirc;tre brute</td>
-</tr>
- <tr>
-<td><span class="new_code">getContentAsText()</span></td><td>Sans code HTML &agrave; l'exception du text "alt"</td>
-</tr>
- <tr>
-<td><span class="new_code">retry()</span></td><td>R&eacute;p&egrave;te la derni&egrave;re requ&ecirc;te</td>
-</tr>
- <tr>
-<td><span class="new_code">back()</span></td><td>Utilise le bouton "pr&eacute;c&eacute;dent" du navigateur</td>
-</tr>
- <tr>
-<td><span class="new_code">forward()</span></td><td>Utilise le bouton "suivant" du navigateur</td>
-</tr>
- <tr>
-<td><span class="new_code">authenticate($username, $password)</span></td><td>Retente la page ou la fen&ecirc;tre apr&egrave;s une r&eacute;ponse 401</td>
-</tr>
- <tr>
-<td><span class="new_code">restart($date)</span></td><td>Relance le navigateur pour une nouvelle session</td>
-</tr>
- <tr>
-<td><span class="new_code">ageCookies($interval)</span></td><td>Change la date des cookies</td>
-</tr>
- <tr>
-<td><span class="new_code">setCookie($name, $value)</span></td><td>Lance un nouveau cookie</td>
-</tr>
- <tr>
-<td><span class="new_code">getCookieValue($host, $path, $name)</span></td><td>Lit le cookie le plus sp&eacute;cifique</td>
-</tr>
- <tr>
-<td><span class="new_code">getCurrentCookieValue($name)</span></td><td>Lit le contenue du cookie en cours</td>
-</tr>
- </tbody>
-</table>
- Les m&eacute;thode <span class="new_code">SimpleBrowser::useProxy()</span> et <span class="new_code">SimpleBrowser::addHeader()</span> sont sp&eacute;ciales. Une fois appell&eacute;es, elles continuent &agrave; s'appliquer sur les t&eacute;l&eacute;chargements suivants.
- </p>
- <p>
- Naviguer dans les formulaires est similaire &agrave; la <a href="form_testing_documentation.html">navigation des formulaires via WebTestCase</a>...
- <table>
-<tbody>
- <tr>
-<td><span class="new_code">setField($name, $value)</span></td><td>Modifie tous les champs avec ce nom</td>
-</tr>
- <tr>
-<td><span class="new_code">setFieldById($id, $value)</span></td><td>Modifie tous les champs avec cet identifiant</td>
-</tr>
- <tr>
-<td><span class="new_code">getField($name)</span></td><td>Accesseur de la valeur d'un &eacute;l&eacute;ment de formulaire</td>
-</tr>
- <tr>
-<td><span class="new_code">getFieldById($id)</span></td><td>Accesseur de la valeur de l'&eacute;l&eacute;ment de formulaire avec cet identifiant</td>
-</tr>
- <tr>
-<td><span class="new_code">clickSubmit($label)</span></td><td>Transmet le formulaire avec l'&eacute;tiquette de son bouton</td>
-</tr>
- <tr>
-<td><span class="new_code">clickSubmitByName($name)</span></td><td>Transmet le formulaire avec l'attribut de son bouton</td>
-</tr>
- <tr>
-<td><span class="new_code">clickSubmitById($id)</span></td><td>Transmet le formulaire avec l'identifiant de son bouton</td>
-</tr>
- <tr>
-<td><span class="new_code">clickImage($label, $x, $y)</span></td><td>Clique sur l'image par son texte alternatif</td>
-</tr>
- <tr>
-<td><span class="new_code">clickImageByName($name, $x, $y)</span></td><td>Clique sur l'image par son attribut</td>
-</tr>
- <tr>
-<td><span class="new_code">clickImageById($id, $x, $y)</span></td><td>Clique sur l'image par son identifiant</td>
-</tr>
- <tr>
-<td><span class="new_code">submitFormById($id)</span></td><td>Transmet le formulaire par son identifiant propre</td>
-</tr>
- </tbody>
-</table>
- A aujourd'hui il n'existe aucune m&eacute;thode pour lister les formulaires et les champs disponibles : ce sera probablement ajout&eacute; dans des versions successives de SimpleTest.
- </p>
- <p>
- A l'int&eacute;rieur d'une page, les fen&ecirc;tres individuelles peuvent &ecirc;tre s&eacute;lectionn&eacute;es. Si aucune s&eacute;lection n'est r&eacute;alis&eacute;e alors toutes les fen&ecirc;tres sont fusionn&eacute;es ensemble dans un unique et grande page. Le contenu de la page en cours sera une concat&eacute;nation des toutes les fen&ecirc;tres dans l'ordre sp&eacute;cifi&eacute; par les balises "frameset".
- <table>
-<tbody>
- <tr>
-<td><span class="new_code">getFrames()</span></td><td>Un d&eacute;chargement de la structure de la fen&ecirc;tre courante</td>
-</tr>
- <tr>
-<td><span class="new_code">getFrameFocus()</span></td><td>L'index ou l'&eacute;tiquette de la fen&ecirc;tre en courante</td>
-</tr>
- <tr>
-<td><span class="new_code">setFrameFocusByIndex($choice)</span></td><td>S&eacute;lectionne la fen&ecirc;tre num&eacute;rot&eacute;e &agrave; partir de 1</td>
-</tr>
- <tr>
-<td><span class="new_code">setFrameFocus($name)</span></td><td>S&eacute;lectionne une fen&ecirc;tre par son &eacute;tiquette</td>
-</tr>
- <tr>
-<td><span class="new_code">clearFrameFocus()</span></td><td>Traite toutes les fen&ecirc;tres comme une seule page</td>
-</tr>
- </tbody>
-</table>
- Lorsqu'on est focalis&eacute; sur une fen&ecirc;tre unique, le contenu viendra de celle-ci uniquement. Cela comprend les liens &agrave; cliquer et les formulaires &agrave; transmettre.
- </p>
-
- <p>
-<a class="target" name="deboguer">
-<h2>O&ugrave; sont les erreurs ?</h2>
-</a>
-</p>
- <p>
- Toute cette masse de fonctionnalit&eacute;s est g&eacute;niale lorsqu'on arrive &agrave; bien t&eacute;l&eacute;charger les pages, mais ce n'est pas toujours &eacute;vident. Pour aider &agrave; d&eacute;couvrir les erreurs, le navigateur a aussi des m&eacute;thodes pour aider au d&eacute;bogage.
- <table>
-<tbody>
- <tr>
-<td><span class="new_code">setConnectionTimeout($timeout)</span></td><td>Ferme la socket avec un d&eacute;lai trop long</td>
-</tr>
- <tr>
-<td><span class="new_code">getRequest()</span></td><td>L'ent&ecirc;te de la requ&ecirc;te brute de la page ou de la fen&ecirc;tre</td>
-</tr>
- <tr>
-<td><span class="new_code">getHeaders()</span></td><td>L'ent&ecirc;te de r&eacute;ponse de la page ou de la fen&ecirc;tre</td>
-</tr>
- <tr>
-<td><span class="new_code">getTransportError()</span></td><td>N'importe quel erreur au niveau de la socket dans le dernier t&eacute;l&eacute;chargement</td>
-</tr>
- <tr>
-<td><span class="new_code">getResponseCode()</span></td><td>La r&eacute;ponse HTTP de la page ou de la fen&ecirc;tre</td>
-</tr>
- <tr>
-<td><span class="new_code">getMimeType()</span></td><td>Le type Mime de la page our de la fen&ecirc;tre</td>
-</tr>
- <tr>
-<td><span class="new_code">getAuthentication()</span></td><td>Le type d'authenficiation dans l'ent&ecirc;te d'une provocation 401</td>
-</tr>
- <tr>
-<td><span class="new_code">getRealm()</span></td><td>Le realm d'authentification dans l'ent&ecirc;te d'une provocation 401</td>
-</tr>
- <tr>
-<td><span class="new_code">setMaximumRedirects($max)</span></td><td>Nombre de redirection avant que la page ne soit charg&eacute;e automatiquement</td>
-</tr>
- <tr>
-<td><span class="new_code">setMaximumNestedFrames($max)</span></td><td>Protection contre des framesets r&eacute;cursifs</td>
-</tr>
- <tr>
-<td><span class="new_code">ignoreFrames()</span></td><td>Neutralise le support des fen&ecirc;tres</td>
-</tr>
- <tr>
-<td><span class="new_code">useFrames()</span></td><td>Autorise le support des fen&ecirc;tres</td>
-</tr>
- </tbody>
-</table>
- Les m&eacute;thodes <span class="new_code">SimpleBrowser::setConnectionTimeout()</span>, <span class="new_code">SimpleBrowser::setMaximumRedirects()</span>,<span class="new_code">SimpleBrowser::setMaximumNestedFrames()</span>, <span class="new_code">SimpleBrowser::ignoreFrames()</span> et <span class="new_code">SimpleBrowser::useFrames()</span> continuent &agrave; s'appliquer sur toutes les requ&ecirc;tes suivantes. Les autres m&eacute;thodes tiennent compte des fen&ecirc;tres. Cela veut dire que si une fen&ecirc;tre individuel ne se charge pas, il suffit de se diriger vers elle avec <span class="new_code">SimpleBrowser::setFrameFocus()</span> : ensuite on utilisera <span class="new_code">SimpleBrowser::getRequest()</span>, etc. pour voir ce qui se passe.
- </p>
-
- <p>
-<a class="target" name="unit">
-<h2>Tests unitaires complexes avec des navigateurs multiples</h2>
-</a>
-</p>
- <p>
- Tout ce qui peut &ecirc;tre fait dans <a href="web_tester_documentation.html">WebTestCase</a> peut maintenant &ecirc;tre fait dans un <a href="unit_tester_documentation.html">UnitTestCase</a>. Ce qui revient &agrave; dire que nous pouvons librement m&eacute;langer des tests sur des objets de domaine avec l'interface web...
-<pre>
-class TestOfRegistration extends UnitTestCase {
- function testNewUserAddedToAuthenticator() {
- $browser = &amp;new SimpleBrowser();
- $browser-&gt;get('http://my-site.com/register.php');
- $browser-&gt;setField('email', 'me@here');
- $browser-&gt;setField('password', 'Secret');
- $browser-&gt;clickSubmit('Register');
-
- $authenticator = &amp;new Authenticator();
- $member = &amp;$authenticator-&gt;findByEmail('me@here');
- $this-&gt;assertEqual($member-&gt;getPassword(), 'Secret');
- }
-}
-</pre>
- Bien que &ccedil;a puisse &ecirc;tre utile par convenance temporaire, je ne suis pas fan de ce genre de test. Ce test s'applique &agrave; sur plusieurs couches de l'application, &ccedil;a implique qu'il est plus que probable qu'il faudra le remanier lorsque le code change.
- </p>
- <p>
- Un cas plus utile d'utilisation directe du navigateur est le moment o&ugrave; le <span class="new_code">WebTestCase</span> ne peut plus suivre. Un exemple ? Quand deux navigateurs doivent &ecirc;tre utilis&eacute;s en m&ecirc;me temps.
- </p>
- <p>
- Par exemple, supposons que nous voulions interdire des usages simultan&eacute;s d'un site avec le m&ecirc;me login d'identification. Ce sc&eacute;nario de test le v&eacute;rifie...
-<pre>
-class TestOfSecurity extends UnitTestCase {
- function testNoMultipleLoginsFromSameUser() {
- $first = &amp;new SimpleBrowser();
- $first-&gt;get('http://my-site.com/login.php');
- $first-&gt;setField('name', 'Me');
- $first-&gt;setField('password', 'Secret');
- $first-&gt;clickSubmit('Enter');
- $this-&gt;assertEqual($first-&gt;getTitle(), 'Welcome');
-
- $second = &amp;new SimpleBrowser();
- $second-&gt;get('http://my-site.com/login.php');
- $second-&gt;setField('name', 'Me');
- $second-&gt;setField('password', 'Secret');
- $second-&gt;clickSubmit('Enter');
- $this-&gt;assertEqual($second-&gt;getTitle(), 'Access Denied');
- }
-}
-</pre>
- Vous pouvez aussi utiliser la classe <span class="new_code">SimpleBrowser</span> quand vous souhaitez &eacute;crire des sc&eacute;narios de test en utilisant un autre outil que SimpleTest.
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/docs/fr/docs.css b/tests/test_tools/simpletest/docs/fr/docs.css
deleted file mode 100755
index 93226cd7..00000000
--- a/tests/test_tools/simpletest/docs/fr/docs.css
+++ /dev/null
@@ -1,84 +0,0 @@
-body {
- padding-left: 3%;
- padding-right: 3%;
-}
-pre {
- font-family: courier;
- font-size: 80%;
- border: 1px solid;
- background-color: #cccccc;
- padding: 5px;
- margin-left: 5%;
- margin-right: 8%;
-}
-.code, .new_code, pre.new_code {
- font-weight: bold;
-}
-div.copyright {
- font-size: 80%;
- color: gray;
-}
-div.copyright a {
- color: gray;
-}
-ul.api {
- padding-left: 0em;
- padding-right: 25%;
-}
-ul.api li {
- margin-top: 0.2em;
- margin-bottom: 0.2em;
- list-style: none;
- text-indent: -3em;
- padding-left: 3em;
-}
-div.demo {
- border: 4px ridge;
- border-color: gray;
- padding: 10px;
- margin: 5px;
- margin-left: 20px;
- margin-right: 40px;
- background-color: white;
-}
-div.demo span.fail {
- color: red;
-}
-div.demo span.pass {
- color: green;
-}
-div.demo h1 {
- font-size: 12pt;
- text-align: left;
- font-weight: bold;
-}
-table {
- border: 2px outset;
- border-color: gray;
- background-color: white;
- margin: 5px;
- margin-left: 5%;
- margin-right: 5%;
-}
-td {
- font-size: 80%;
-}
-.shell {
- color: white;
-}
-pre.shell {
- border: 4px ridge;
- border-color: gray;
- padding: 10px;
- margin: 5px;
- margin-left: 20px;
- margin-right: 40px;
- background-color: black;
-}
-form.demo {
- background-color: lightgray;
- border: 4px outset;
- border-color: lightgray;
- padding: 10px;
- margin-right: 40%;
-}
diff --git a/tests/test_tools/simpletest/docs/fr/expectation_documentation.html b/tests/test_tools/simpletest/docs/fr/expectation_documentation.html
deleted file mode 100755
index ab9ef606..00000000
--- a/tests/test_tools/simpletest/docs/fr/expectation_documentation.html
+++ /dev/null
@@ -1,263 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>Documentation SimpleTest : &eacute;tendre le testeur unitaire avec des classes d'attentes suppl&eacute;mentaires</title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<a href="index.html">SimpleTest</a>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Documentation sur les attentes</h1>
-<div class="content">
- <p>
-<a class="target" name="fantaisie">
-<h2>Plus de contr&ocirc;le sur les objets fantaisie</h2>
-</a>
-</p>
- <p>
- Le comportement par d&eacute;faut des <a href="mock_objects_documentation.html">objets fantaisie</a> dans <a href="http://sourceforge.net/projects/simpletest/">SimpleTest</a> est soit une correspondance identique sur l'argument, soit l'acceptation de n'importe quel argument. Pour la plupart des tests, c'est suffisant. Cependant il est parfois n&eacute;cessaire de ramollir un sc&eacute;nario de test.
- </p>
- <p>
- Un des endroits o&ugrave; un test peut &ecirc;tre trop serr&eacute; 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&eacute;e, mais le texte proprement dit risque d'&ecirc;tre plut&ocirc;t long. Si vous testez le texte dans son ensemble alors &agrave; chaque modification de ce m&ecirc;me message -- m&ecirc;me un point ou une virgule -- vous aurez &agrave; revenir sur la suite de test pour la modifier.
- </p>
- <p>
- Voici un cas concret, nous avons un service d'actualit&eacute;s qui a &eacute;chou&eacute; dans sa tentative de connexion &agrave; sa source distante.
-<pre>
-<strong>class NewsService {
- ...
- function publish(&amp;$writer) {
- if (! $this-&gt;isConnected()) {
- $writer-&gt;write('Cannot connect to news service "' .
- $this-&gt;_name . '" at this time. ' .
- 'Please try again later.');
- }
- ...
- }
-}</strong>
-</pre>
- L&agrave; il envoie son contenu vers un classe <span class="new_code">Writer</span>. Nous pourrions tester ce comportement avec un <span class="new_code">MockWriter</span>...
-<pre>
-class TestOfNewsService extends UnitTestCase {
- ...
- function testConnectionFailure() {<strong>
- $writer = &amp;new MockWriter($this);
- $writer-&gt;expectOnce('write', array(
- 'Cannot connect to news service ' .
- '"BBC News" at this time. ' .
- 'Please try again later.'));
-
- $service = &amp;new NewsService('BBC News');
- $service-&gt;publish($writer);
-
- $writer-&gt;tally();</strong>
- }
-}
-</pre>
- C'est un bon exemple d'un test fragile. Si nous d&eacute;cidons d'ajouter des instructions compl&eacute;mentaires, par exemple proposer une source d'actualit&eacute;s alternative, nous casserons nos tests par la m&ecirc;me occasion sans pourtant avoir modifi&eacute; une seule fonctionnalit&eacute;.
- </p>
- <p>
- Pour contourner ce probl&egrave;me, nous voudrions utiliser un test avec une expression rationnelle plut&ocirc;t qu'une correspondance exacte. Nous pouvons y parvenir avec...
-<pre>
-class TestOfNewsService extends UnitTestCase {
- ...
- function testConnectionFailure() {
- $writer = &amp;new MockWriter($this);<strong>
- $writer-&gt;expectOnce(
- 'write',
- array(new WantedPatternExpectation('/cannot connect/i')));</strong>
-
- $service = &amp;new NewsService('BBC News');
- $service-&gt;publish($writer);
-
- $writer-&gt;tally();
- }
-}
-</pre>
- Plut&ocirc;t que de transmettre le param&egrave;tre attendu au <span class="new_code">MockWriter</span>, nous envoyons une classe d'attente appel&eacute;e <span class="new_code">WantedPatternExpectation</span>. L'objet fantaisie est suffisamment &eacute;l&eacute;gant pour reconna&icirc;tre qu'il s'agit d'un truc sp&eacute;cial et pour le traiter diff&eacute;remment. Plut&ocirc;t que de comparer l'argument entrant &agrave; cet objet, il utilise l'objet attente lui-m&ecirc;me pour ex&eacute;cuter le test.
- </p>
- <p>
- <span class="new_code">WantedPatternExpectation</span> utilise l'expression rationnelle pour la comparaison avec son constructeur. A chaque fois q'une comparaison est fait &agrave; travers <span class="new_code">MockWriter</span> par rapport &agrave; cette classe attente, elle fera un <span class="new_code">preg_match()</span> avec ce motif. Dans notre sc&eacute;nario de test ci-dessus, aussi longtemps que la cha&icirc;ne "cannot connect" appara&icirc;t dans le texte, la fantaisie transmettra un succ&egrave;s au testeur unitaire. Peu importe le reste du texte.
- </p>
- <p>
- Les classes attente possibles sont...
- <table>
-<tbody>
- <tr>
-<td><span class="new_code">EqualExpectation</span></td><td>Une &eacute;galit&eacute;, plut&ocirc;t que la plus forte comparaison &agrave; l'identique</td>
-</tr>
- <tr>
-<td><span class="new_code">NotEqualExpectation</span></td><td>Une comparaison sur la non-&eacute;galit&eacute;</td>
-</tr>
- <tr>
-<td><span class="new_code">IndenticalExpectation</span></td><td>La v&eacute;rification par d&eacute;faut de l'objet fantaisie qui doit correspondre exactement</td>
-</tr>
- <tr>
-<td><span class="new_code">NotIndenticalExpectation</span></td><td>Inverse la logique de l'objet fantaisie</td>
-</tr>
- <tr>
-<td><span class="new_code">WantedPatternExpectation</span></td><td>Utilise une expression rationnelle Perl pour comparer une cha&icirc;ne</td>
-</tr>
- <tr>
-<td><span class="new_code">NoUnwantedPatternExpectation</span></td><td>Passe seulement si l'expression rationnelle Perl &eacute;choue</td>
-</tr>
- <tr>
-<td><span class="new_code">IsAExpectation</span></td><td>V&eacute;rifie le type ou le nom de la classe uniquement</td>
-</tr>
- <tr>
-<td><span class="new_code">NotAExpectation</span></td><td>L'oppos&eacute; de <span class="new_code">IsAExpectation</span></td>
-</tr>
- <tr>
-<td><span class="new_code">MethodExistsExpectation</span></td><td>V&eacute;rifie si la m&eacute;thode est disponible sur un objet</td>
-</tr>
- </tbody>
-</table>
- La plupart utilisent la valeur attendue dans le constructeur. Les exceptions sont les v&eacute;rifications sur motif, qui utilisent une expression rationnelle, ainsi que <span class="new_code">IsAExpectation</span> et <span class="new_code">NotAExpectation</span>, qui prennent un type ou un nom de classe comme cha&icirc;ne.
- </p>
-
- <p>
-<a class="target" name="comportement">
-<h2>Utiliser les attentes pour contr&ocirc;ler les bouchons serveur</h2>
-</a>
-</p>
- <p>
- Les classes attente peuvent servir &agrave; autre chose que l'envoi d'assertions depuis les objets fantaisie, afin de choisir le comportement d'un <a href="mock_objects_documentation.html">objet fantaisie</a> our celui d'un <a href="server_stubs_documentation.html">bouchon serveur</a>. A chaque fois qu'une liste d'arguments est donn&eacute;e, une liste d'objets attente peut &ecirc;tre ins&eacute;r&eacute;e &agrave; la place.
- </p>
- <p>
- Mettons que nous voulons qu'un bouchon serveur d'autorisation simule une connexion r&eacute;ussie seulement si il re&ccedil;oit un objet de session valide. Nous pouvons y arriver avec ce qui suit...
-<pre>
-Stub::generate('Authorisation');
-<strong>
-$authorisation = new StubAuthorisation();
-$authorisation-&gt;setReturnValue(
- 'isAllowed',
- true,
- array(new IsAExpectation('Session', 'Must be a session')));
-$authorisation-&gt;setReturnValue('isAllowed', false);</strong>
-</pre>
- Le comportement par d&eacute;faut du bouchon serveur est d&eacute;fini pour renvoyer <span class="new_code">false</span> quand <span class="new_code">isAllowed</span> est appel&eacute;. Lorsque nous appelons cette m&eacute;thode avec un unique param&egrave;tre qui est un objet <span class="new_code">Session</span>, il renverra <span class="new_code">true</span>. Nous avons aussi ajout&eacute; un deuxi&egrave;me param&egrave;tre comme message. Il sera affich&eacute; dans le message d'erreur de l'objet fantaisie si l'attente est la cause de l'&eacute;chec.
- </p>
- <p>
- Ce niveau de sophistication est rarement utile : il n'est inclut que pour &ecirc;tre complet.
- </p>
-
- <p>
-<a class="target" name="etendre">
-<h2>Cr&eacute;er vos propres attentes</h2>
-</a>
-</p>
- <p>
- Les classes d'attentes ont une structure tr&egrave;s simple. Tellement simple qu'il devient tr&egrave;s simple de cr&eacute;er vos propres version de logique pour des tests utilis&eacute;s couramment.
- </p>
- <p>
- Par exemple voici la cr&eacute;ation d'une classe pour tester la validit&eacute; d'adresses IP. Pour fonctionner correctement avec les bouchons serveurs et les objets fantaisie, cette nouvelle classe d'attente devrait &eacute;tendre <span class="new_code">SimpleExpectation</span>...
-<pre>
-<strong>class ValidIp extends SimpleExpectation {
-
- function test($ip) {
- return (ip2long($ip) != -1);
- }
-
- function testMessage($ip) {
- return "Address [$ip] should be a valid IP address";
- }
-}</strong>
-</pre>
- Il n'y a v&eacute;ritablement que deux m&eacute;thodes &agrave; mettre en place. La m&eacute;thode <span class="new_code">test()</span> devrait renvoyer un <span class="new_code">true</span> si l'attente doit passer, et une erreur <span class="new_code">false</span> dans le cas contraire. La m&eacute;thode <span class="new_code">testMessage()</span> ne devrait renvoyer que du texte utile &agrave; la compr&eacute;hension du test en lui-m&ecirc;me.
- </p>
- <p>
- Cette classe peut d&eacute;sormais &ecirc;tre employ&eacute;e &agrave; la place des classes d'attente pr&eacute;c&eacute;dentes.
- </p>
-
- <p>
-<a class="target" name="unitaire">
-<h2>Sous le capot du testeur unitaire</h2>
-</a>
-</p>
- <p>
- Le <a href="http://sourceforge.net/projects/simpletest/">frameworkd de test unitaire SimpleTest</a> utilise aussi dans son coeur des classes d'attente pour la <a href="unit_test_documentation.html">classe UnitTestCase</a>. Nous pouvons aussi tirer parti de ces m&eacute;canismes pour r&eacute;utiliser nos propres classes attente &agrave; l'int&eacute;rieur m&ecirc;me des suites de test.
- </p>
- <p>
- La m&eacute;thode la plus directe est d'utiliser la m&eacute;thode <span class="new_code">SimpleTest::assertExpectation()</span> pour effectuer le test...
-<pre>
-<strong>class TestOfNetworking extends UnitTestCase {
- ...
- function testGetValidIp() {
- $server = &amp;new Server();
- $this-&gt;assertExpectation(
- new ValidIp(),
- $server-&gt;getIp(),
- 'Server IP address-&gt;%s');
- }
-}</strong>
-</pre>
- C'est plut&ocirc;t sale par rapport &agrave; notre syntaxe habituelle du type <span class="new_code">assert...()</span>.
- </p>
- <p>
- Pour un cas aussi simple, nous cr&eacute;ons d'ordinaire une m&eacute;thode d'assertion distincte en utilisant la classe d'attente. Supposons un instant que notre attente soit un peu plus compliqu&eacute;e et que par cons&eacute;quent nous souhaitions la r&eacute;utiliser, nous obtenons...
-<pre>
-class TestOfNetworking extends UnitTestCase {
- ...<strong>
- function assertValidIp($ip, $message = '%s') {
- $this-&gt;assertExpectation(new ValidIp(), $ip, $message);
- }</strong>
-
- function testGetValidIp() {
- $server = &amp;new Server();<strong>
- $this-&gt;assertValidIp(
- $server-&gt;getIp(),
- 'Server IP address-&gt;%s');</strong>
- }
-}
-</pre>
- Il est peu probable que nous ayons besoin de ce niveau de contr&ocirc;le sur la machinerie de test. Il est assez rare que le besoin d'une attente d&eacute;passe le stade de la reconnaissance d'un motif. De plus, les classes d'attente complexes peuvent rendre les tests difficiles &agrave; lire et &agrave; d&eacute;boguer. Ces m&eacute;canismes sont v&eacute;ritablement l&agrave; pour les auteurs de syst&egrave;me qui &eacute;tendront le framework de test pour leurs propres outils de test.
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/docs/fr/form_testing_documentation.html b/tests/test_tools/simpletest/docs/fr/form_testing_documentation.html
deleted file mode 100755
index f9f5d0df..00000000
--- a/tests/test_tools/simpletest/docs/fr/form_testing_documentation.html
+++ /dev/null
@@ -1,235 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>Documentation SimpleTest : tester des formulaires HTML</title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<a href="index.html">SimpleTest</a>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Documentation sur les tests de formulaire</h1>
-<div class="content">
- <p>
-<a class="target" name="submit">
-<h2>Valider un formulaire simple</h2>
-</a>
-</p>
- <p>
- Lorsqu'une page est t&eacute;l&eacute;charg&eacute;e par <span class="new_code">WebTestCase</span> en utilisant <span class="new_code">get()</span> ou <span class="new_code">post()</span> le contenu de la page est automatiquement analys&eacute;. De cette analyse d&eacute;coule le fait que toutes les commandes &agrave; l'int&eacute;rieur de la balise &lt;form&gt; sont disponibles depuis l'int&eacute;rieur du sc&eacute;nario de test. Prenons pas exemple cet extrait de code HTML...
-<pre>
-&lt;form&gt;
- &lt;input type="text" name="a" value="A default" /&gt;
- &lt;input type="submit" value="Go" /&gt;
-&lt;/form&gt;
-</pre>
- Il ressemble &agrave;...
- </p>
- <p>
- <form class="demo">
- <input type="text" name="a" value="A default">
- <input type="submit" value="Go">
- </form>
- </p>
- <p>
- Nous pouvons naviguer vers ce code, via le site <a href="http://www.lastcraft.com/form_testing_documentation.php">LastCraft</a>, avec le test suivant...
-<pre>
-class SimpleFormTests extends WebTestCase {
- <strong>
- function testDefaultValue() {
- $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
- $this-&gt;assertField('a', 'A default');
- }</strong>
-}
-</pre>
- Directement apr&egrave;s le chargement de la page toutes les commandes HTML sont initi&eacute;es avec leur valeur par d&eacute;faut, comme elles appara&icirc;traient dans un navigateur web. L'assertion teste qu'un objet HTML avec le nom "a" existe dans la page et qu'il contient la valeur "A default".
- </p>
- <p>
- Nous pourrions retourner le formulaire tout de suite, mais d'abord nous allons changer la valeur du champ texte. Ce n'est qu'apr&egrave;s que nous le transmettre...
-<pre>
-class SimpleFormTests extends WebTestCase {
-
- function testDefaultValue() {
- $this-&gt;get('http://www.my-site.com/');
- $this-&gt;assertField('a', 'A default');<strong>
- $this-&gt;setField('a', 'New value');
- $this-&gt;clickSubmit('Go');</strong>
- }
-}
-</pre>
- Parce que nous n'avons sp&eacute;cifi&eacute; ni attribut "method" sur la balise form, ni attribut "action", le sc&eacute;nario de test suivra le comportement classique d'un navigateur : transmission des donn&eacute;es avec une requ&ecirc;te <em>GET</em> vers la m&ecirc;me page. SimpleTest essaie d'&eacute;muler le comportement typique d'un navigateur autant que possible, plut&ocirc;t que d'essayer d'attraper des attributs manquants sur les balises. La raison est simple : la cible d'un framework de test est la logique d'une application PHP, pas les erreurs -- de syntaxe ou autres -- du code HTML. Pour les erreurs HTML, d'autres outils tel <a href="http://www.w3.org/People/Raggett/tidy/">HTMLTidy</a> devraient &ecirc;tre employ&eacute;s.
- </p>
- <p>
- Si un champ manque dans n'importe que formulaire ou si une option est indisponible alors <span class="new_code">WebTestCase::setField()</span> renverra <span class="new_code">false</span>. Par exemple, supposons que nous souhaitons v&eacute;rifier qu'une option "Superuser" n'est pas pr&eacute;sente dans ce formulaire...
-<pre>
-&lt;strong&gt;Select type of user to add:&lt;/strong&gt;
-&lt;select name="type"&gt;
- &lt;option&gt;Subscriber&lt;/option&gt;
- &lt;option&gt;Author&lt;/option&gt;
- &lt;option&gt;Administrator&lt;/option&gt;
-&lt;/select&gt;
-</pre>
- Qui ressemble &agrave;...
- </p>
- <p>
- <form class="demo">
- <strong>Select type of user to add:</strong>
- <select name="type">
- <option>Subscriber</option>
- <option>Author</option>
- <option>Administrator</option>
- </select>
- </form>
- </p>
- <p>
- Le test suivant le confirmera...
-<pre>
-class SimpleFormTests extends WebTestCase {
- ...
- function testNoSuperuserChoiceAvailable() {<strong>
- $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
- $this-&gt;assertFalse($this-&gt;setField('type', 'Superuser'));</strong>
- }
-}
-</pre>
- La s&eacute;lection ne sera pas chang&eacute;e suite &agrave; un &eacute;chec d'initialisation d'une valeur sur un objet.
- </p>
- <p>
- Voici la liste compl&egrave;te des objets support&eacute;s &agrave; aujourd'hui...
- <ul>
- <li>Champs texte, y compris les champs masqu&eacute;s (hidden) ou crypt&eacute;s (password).</li>
- <li>Boutons submit, en incluant aussi la balise button, mais pas encore les boutons reset</li>
- <li>Aires texte (textarea) avec leur gestion des retours &agrave; la ligne (wrap).</li>
- <li>Cases &agrave; cocher, y compris les cases &agrave; cocher multiples dans un m&ecirc;me formulaire.</li>
- <li>Listes &agrave; menu d&eacute;roulant, y compris celles &agrave; s&eacute;lections multiples.</li>
- <li>Boutons radio.</li>
- <li>Images.</li>
- </ul>
- </p>
- <p>
- Bien que la plupart des objets HTML standards soient couvert par le parseur de <em>SimpleTest</em>, il est peu probable que JavaScript soit impl&eacute;ment&eacute; dans un futur proche.
- </p>
-
- <p>
-<a class="target" name="multiple">
-<h2>Champs &agrave; valeurs multiples</h2>
-</a>
-</p>
- <p>
- SimpleTest peut g&eacute;rer deux types de commandes &agrave; valeur multiple : les menus d&eacute;roulants &agrave; s&eacute;lection multiple et les cases &agrave; cocher avec le m&ecirc;me nom &agrave; l'int&eacute;rieur m&ecirc;me d'un formulaire. La nature de ceux-ci implique que leur initialisation et leur test sont l&eacute;g&egrave;rement diff&eacute;rents. Voici un exemple avec des cases &agrave; cocher...
-<pre>
-&lt;form class="demo"&gt;
- &lt;strong&gt;Create privileges allowed:&lt;/strong&gt;
- &lt;input type="checkbox" name="crud" value="c" checked&gt;&lt;br&gt;
- &lt;strong&gt;Retrieve privileges allowed:&lt;/strong&gt;
- &lt;input type="checkbox" name="crud" value="r" checked&gt;&lt;br&gt;
- &lt;strong&gt;Update privileges allowed:&lt;/strong&gt;
- &lt;input type="checkbox" name="crud" value="u" checked&gt;&lt;br&gt;
- &lt;strong&gt;Destroy privileges allowed:&lt;/strong&gt;
- &lt;input type="checkbox" name="crud" value="d" checked&gt;&lt;br&gt;
- &lt;input type="submit" value="Enable Privileges"&gt;
-&lt;/form&gt;
-</pre>
- Qui se traduit par...
- </p>
- <p>
- <form class="demo">
- <strong>Create privileges allowed:</strong>
- <input type="checkbox" name="crud" value="c" checked>
-<br>
- <strong>Retrieve privileges allowed:</strong>
- <input type="checkbox" name="crud" value="r" checked>
-<br>
- <strong>Update privileges allowed:</strong>
- <input type="checkbox" name="crud" value="u" checked>
-<br>
- <strong>Destroy privileges allowed:</strong>
- <input type="checkbox" name="crud" value="d" checked>
-<br>
- <input type="submit" value="Enable Privileges">
- </form>
- </p>
- <p>
- Si nous souhaitons d&eacute;sactiver tous les privil&egrave;ges sauf ceux de t&eacute;l&eacute;chargement (Retrieve) et transmettre cette information, nous pouvons y arriver par...
-<pre>
-class SimpleFormTests extends WebTestCase {
- ...<strong>
- function testDisableNastyPrivileges() {
- $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
- $this-&gt;assertField('crud', array('c', 'r', 'u', 'd'));
- $this-&gt;setField('crud', array('r'));
- $this-&gt;clickSubmit('Enable Privileges');
- }</strong>
-}
-</pre>
- Plut&ocirc;t que d'initier le champ &agrave; une valeur unique, nous lui donnons une liste de valeurs. Nous faisons la m&ecirc;me chose pour tester les valeurs attendues. Nous pouvons &eacute;crire d'autre code de test pour confirmer cet effet, peut-&ecirc;tre en nous connectant comme utilisateur et en essayant d'effectuer une mise &agrave; jour.
- </p>
- <p>
- <a class="target" name="brut">
-<h2>Envoi brut</h2>
-</a>
- </p>
- <p>
- Si vous souhaitez tester un gestionnaire de formulaire mais que vous ne l'avez pas &eacute;crit ou que vous n'y avez pas encore acc&egrave;s, vous pouvez cr&eacute;er un envoi de formulaire &agrave; la main.
-<pre>
-class SimpleFormTests extends WebTestCase {
- ...<strong>
- function testAttemptedHack() {
- $this-&gt;post(
- 'http://www.my-site.com/add_user.php',
- array('type' =&gt; 'superuser'));
- $this-&gt;assertNoUnwantedPattern('/user created/i');
- }</strong>
-}
-</pre>
- En ajoutant des donn&eacute;es &agrave; la m&eacute;thode <span class="new_code">WebTestCase::post()</span>, nous essayons de t&eacute;l&eacute;charger la page via la transmission d'un formulaire.
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/docs/fr/group_test_documentation.html b/tests/test_tools/simpletest/docs/fr/group_test_documentation.html
deleted file mode 100755
index 662f868e..00000000
--- a/tests/test_tools/simpletest/docs/fr/group_test_documentation.html
+++ /dev/null
@@ -1,288 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>Documentation SimpleTest : Grouper des tests</title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<a href="index.html">SimpleTest</a>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Documentation sur le groupement des tests</h1>
-<div class="content">
- <p>
-<a class="target" name="grouper">
-<h2>Grouper des tests</h2>
-</a>
-</p>
- <p>
- Pour lancer les sc&eacute;narios de tests en tant que groupe, ils devraient &ecirc;tre plac&eacute;s dans des fichiers sans le code du lanceur...
-<pre>
-<strong>&lt;?php
- require_once('../classes/io.php');
-
- class FileTester extends UnitTestCase {
- ...
- }
-
- class SocketTester extends UnitTestCase {
- ...
- }
-?&gt;</strong>
-</pre>
- Autant de sc&eacute;narios que n&eacute;cessaires peuvent &ecirc;tre mis dans un fichier unique. Ils doivent contenir tout le code n&eacute;cessaire, entre autres la biblioth&egrave;que test&eacute;e, mais aucune des biblioth&egrave;ques de SimpleTest.
- </p>
- <p>
- Si vous avez &eacute;tendu l'un ou l'autre des sc&eacute;narios de test, vous pouvez aussi les inclure.
-<pre>
-&lt;?php
- require_once('../classes/io.php');
-<strong>
- class MyFileTestCase extends UnitTestCase {
- ...
- }
- SimpleTestOptions::ignore('MyFileTestCase');</strong>
-
- class FileTester extends MyFileTestCase {
- ...
- }
-
- class SocketTester extends UnitTestCase {
- ...
- }
-?&gt;
-</pre>
- La classe <span class="new_code">FileTester</span> ne contient aucun test v&eacute;ritable, il s'agit d'une classe de base pour d'autres sc&eacute;narios de test. Pour cette raison nous utilisons la directive <span class="new_code">SimpleTestOptions::ignore()</span> pour indiquer au prochain groupe de test de l'ignorer. Cette directive peut se placer n'importe o&ugrave; dans le fichier et fonctionne quand un fichier complet des sc&eacute;narios de test est charg&eacute; (cf. ci-dessous). Nous l'appelons <em>file_test.php</em>.
- </p>
- <p>
- Ensuite nous cr&eacute;ons un fichier de groupe de test, disons <em>group_test.php</em>. Vous penserez &agrave; un nom plus convaincant, j'en suis s&ucirc;r. Nous lui ajoutons le fichier de test avec une m&eacute;thode sans risque...
-<pre>
-&lt;?php
- require_once('simpletest/unit_tester.php');
- require_once('simpletest/reporter.php');<strong>
- require_once('file_test.php');
-
- $test = &amp;new GroupTest('All file tests');
- $test-&gt;addTestCase(new FileTestCase());
- $test-&gt;run(new HtmlReporter());</strong>
-?&gt;
-</pre>
- Ceci instancie le sc&eacute;nario de test avant que la suite de test ne soit lanc&eacute;e. &Ccedil;a pourrait devenir assez on&eacute;reux avec un grand nombre de sc&eacute;narios de test : il existe donc une autre m&eacute;thode qui instancie la classe uniquement quand elle devient n&eacute;cessaire...
-<pre>
-&lt;?php
- require_once('simpletest/unit_tester.php');
- require_once('simpletest/reporter.php');
- require_once('file_test.php');
-
- $test = &amp;new GroupTest('All file tests');<strong>
- $test-&gt;addTestClass('FileTestCase');</strong>
- $test-&gt;run(new HtmlReporter());
-?&gt;
-</pre>
- Le probl&egrave;me de cette technique est que pour chaque sc&eacute;nario de test suppl&eacute;mentaire nous aurons &agrave; <span class="new_code">require_once()</span> le fichier de code de test et &agrave; manuellement instancier chaque sc&eacute;nario de test. Nous pouvons nous &eacute;pargner beaucoup de dactylographie avec...
-<pre>
-&lt;?php
- require_once('simpletest/unit_tester.php');
- require_once('simpletest/reporter.php');
-
- $test = &amp;new GroupTest('All file tests');<strong>
- $test-&gt;addTestFile('file_test.php');</strong>
- $test-&gt;run(new HtmlReporter());
-?&amp;gt;
-</pre>
- Voici ce qui vient de se passer : la classe <span class="new_code">GroupTest</span> a r&eacute;alis&eacute; le <span class="new_code">require_once()</span> pour nous. Ensuite elle v&eacute;rifie si de nouvelles classes de sc&eacute;nario de test ont &eacute;t&eacute; cr&eacute;&eacute;es par ce nouveau fichier et les ajoute automatiquement au groupe de test. D&eacute;sormais tout ce qu'il nous reste &agrave; faire, c'est d'ajouter chaque nouveau fichier.
- </p>
- <p>
- Il y a deux choses qui peuvent planter et qui demandent un minimum d'attention...
- <ol>
- <li>
- Le fichier peut d&eacute;j&agrave; avoir &eacute;t&eacute; analys&eacute; par PHP et dans ce cas aucune classe ne sera ajout&eacute;e. Pensez &agrave; bien v&eacute;rifier que les sc&eacute;narios de test ne sont inclus que dans ce fichier et dans aucun autre.
- </li>
- <li>
- Les nouvelles classes d'extension de sc&eacute;nario de test qui sont incluses seront plac&eacute;es dans le groupe de test et ex&eacute;cut&eacute;es par la m&ecirc;me occasion. Vous aurez &agrave; ajouter une directive <span class="new_code">SimpleTestOptions::ignore()</span> pour ces classes ou alors pensez &agrave; les ajouter avant la ligne <span class="new_code">GroupTest::addTestFile()</span>.
- </li>
- </ol>
- </p>
-
- <p>
-<a class="target" name="plus-haut">
-<h2>Groupements de plus haut niveau</h2>
-</a>
-</p>
- <p>
- La technique ci-dessus place tous les sc&eacute;narios de test dans un unique et grand groupe. Sauf que pour des projets plus cons&eacute;quents, ce n'est probablement pas assez souple ; vous voudriez peut-&ecirc;tre grouper les tests tout &agrave; fait diff&eacute;remment.
- </p>
- <p>
- Pour obtenir un groupe de test plus souple nous pouvons sous classer <span class="new_code">GroupTest</span> et ensuite l'instancier au cas par cas...
-<pre>
-&lt;?php
- require_once('simpletest/unit_tester.php');
- require_once('simpletest/reporter.php');
- <strong>
- class FileGroupTest extends GroupTest {
- function FileGroupTest() {
- $this-&gt;GroupTest('All file tests');
- $this-&gt;addTestFile('file_test.php');
- }
- }</strong>
-?&gt;
-</pre>
- Ceci nomme le test dans le constructeur et ensuite ajoute &agrave; la fois nos sc&eacute;narios de test et un unique groupe en dessous. Bien s&ucirc;r nous pouvons ajouter plus d'un groupe &agrave; cet instant. Nous pouvons maintenant invoquer les tests &agrave; partir d'un autre fichier d'ex&eacute;cution...
-<pre>
-&lt;?php
- require_once('file_group_test.php');
- <strong>
- $test = &amp;new FileGroupTest();
- $test-&gt;run(new HtmlReporter());</strong>
-?&gt;
-</pre>
- ...ou alors nous pouvons les grouper dans un groupe de tests encore plus grand...
-<pre>
-&lt;?php
- require_once('file_group_test.php');
- <strong>
- $test = &amp;new BigGroupTest('Big group');
- $test-&gt;addTestCase(new FileGroupTest());
- $test-&gt;addTestCase(...);
- $test-&gt;run(new HtmlReporter());</strong>
-?&gt;
-</pre>
- Si nous souhaitons lancer le groupe de test original sans utiliser ses petits fichiers d'ex&eacute;cution, nous pouvons mettre le code du lanceur de test derri&egrave;re des barreaux quand nous cr&eacute;ons chaque groupe.
-<pre>
-&lt;?php
- class FileGroupTest extends GroupTest {
- function FileGroupTest() {
- $this-&gt;GroupTest('All file tests');
- $test-&gt;addTestFile('file_test.php');
- }
- }
- <strong>
- if (! defined('RUNNER')) {
- define('RUNNER', true);</strong>
- $test = &amp;new FileGroupTest();
- $test-&gt;run(new HtmlReporter());
- }
-?&gt;
-</pre>
- Cette approche exige aux barri&egrave;res d'&ecirc;tre activ&eacute;es &agrave; l'inclusion du fichier de groupe de test, mais c'est quand m&ecirc;me moins de tracas que beaucoup de fichiers de lancement &eacute;parpill&eacute;s. Reste &agrave; inclure des barreaux identiques au niveau sup&eacute;rieur afin de s'assurer que le <span class="new_code">run()</span> ne sera lanc&eacute; qu'une seule fois &agrave; partir du script de haut niveau qui l'a invoqu&eacute;.
-<pre>
-&lt;?php
- define('RUNNER', true);
-
- require_once('file_group_test.php');
- $test = &amp;new BigGroupTest('Big group');
- $test-&gt;addTestCase(new FileGroupTest());
- $test-&gt;addTestCase(...);
- $test-&gt;run(new HtmlReporter());
-?&gt;
-</pre>
- Comme les sc&eacute;narios de test normaux, un <span class="new_code">GroupTest</span> peut &ecirc;tre charg&eacute; avec la m&eacute;thode <span class="new_code">GroupTest::addTestFile()</span>.
-<pre>
-&lt;?php
- define('RUNNER', true);
-
- $test = &amp;new BigGroupTest('Big group');<strong>
- $test-&gt;addTestFile('file_group_test.php');
- $test-&gt;addTestFile(...);</strong>
- $test-&gt;run(new HtmlReporter());
-?&gt;
-</pre>
- </p>
-
- <p>
-<a class="target" name="heritage">
-<h2>Int&eacute;grer des sc&eacute;narios de test h&eacute;rit&eacute;s</h2>
-</a>
-</p>
- <p>
- Si vous avez d&eacute;j&agrave; des tests unitaires pour votre code ou alors si vous &eacute;tendez des classes externes qui ont d&eacute;j&agrave; leurs propres tests, il y a peu de chances pour que ceux-ci soient d&eacute;j&agrave; au format SimpleTest. Heureusement il est possible d'incorporer ces sc&eacute;narios de test en provenance d'autres testeurs unitaires directement dans des groupes de test SimpleTest.
- </p>
- <p>
- Par exemple, supposons que nous ayons ce sc&eacute;nario de test pr&eacute;vu pour <a href="http://sourceforge.net/projects/phpunit">PhpUnit</a>dans le fichier <em>config_test.php</em>...
-<pre>
-<strong>class ConfigFileTest extends TestCase {
- function ConfigFileTest() {
- $this-&gt;TestCase('Config file test');
- }
-
- function testContents() {
- $config = new ConfigFile('test.conf');
- $this-&gt;assertRegexp('/me/', $config-&gt;getValue('username'));
- }
-}</strong>
-</pre>
- Le groupe de test peut le reconna&icirc;tre &agrave; partir du moment o&ugrave; nous mettons l'adaptateur appropri&eacute; avant d'ajouter le fichier de test...
-<pre>
-&lt;?php
- require_once('simpletest/unit_tester.php');
- require_once('simpletest/reporter.php');<strong>
- require_once('simpletest/adapters/phpunit_test_case.php');</strong>
-
- $test = &amp;new GroupTest('All file tests');<strong>
- $test-&gt;addTestFile('config_test.php');</strong>
- $test-&gt;run(new HtmlReporter());
-?&gt;
-</pre>
- Il n'y a que deux adaptateurs, l'autre est pour le paquet testeur unitaire de <a href="http://pear.php.net/manual/en/package.php.phpunit.php">PEAR</a>...
-<pre>
-&lt;?php
- require_once('simpletest/unit_tester.php');
- require_once('simpletest/reporter.php');<strong>
- require_once('simpletest/adapters/pear_test_case.php');</strong>
-
- $test = &amp;new GroupTest('All file tests');<strong>
- $test-&gt;addTestFile('some_pear_test_cases.php');</strong>
- $test-&gt;run(new HtmlReporter());
-?&gt;
-</pre>
- Les sc&eacute;narios de test de PEAR peuvent &ecirc;tre librement m&eacute;lang&eacute;s avec ceux de SimpleTest mais vous ne pouvez pas utiliser les assertions de SimpleTest au sein des versions h&eacute;rit&eacute;es des sc&eacute;narios de test. La raison ? Une simple v&eacute;rification que vous ne rendez pas par accident vos sc&eacute;narios de test compl&egrave;tement d&eacute;pendants de SimpleTest. Peut-&ecirc;tre que vous souhaitez publier votre biblioth&egrave;que sur PEAR par exemple : &ccedil;a voudrait dire la livrer avec des sc&eacute;narios de test compatibles avec PEAR::PhpUnit.
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/docs/fr/index.html b/tests/test_tools/simpletest/docs/fr/index.html
deleted file mode 100755
index f4b2ad93..00000000
--- a/tests/test_tools/simpletest/docs/fr/index.html
+++ /dev/null
@@ -1,343 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>
- T&eacute;l&eacute;charger le framework de tests Simple Test - Tests unitaire et objets fantaisie pour PHP
- </title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<span class="chosen">SimpleTest</span>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Simple Test pour PHP</h1>
-<div class="content">
-
- <p>
- Le pr&eacute;sent article pr&eacute;suppose que vous soyez familier avec le concept de tests unitaires ainsi que celui de d&eacute;veloppement web avec le langage PHP. Il s'agit d'un guide pour le nouvel et impatient utilisateur de <a href="https://sourceforge.net/project/showfiles.php?group_id=76550">SimpleTest</a>. Pour une documentation plus compl&egrave;te, particuli&egrave;rement si vous d&eacute;couvrez les tests unitaires, consultez la <a href="http://www.lastcraft.com/unit_test_documentation.php">documentation en cours</a>, et pour des exemples de sc&eacute;narios de test, consultez le <a href="http://www.lastcraft.com/first_test_tutorial.php">tutorial sur les tests unitaires</a>.
- </p>
-
- <p>
-<a class="target" name="unit">
-<h2>Utiliser le testeur rapidement</h2>
-</a>
-</p>
- <p>
- Parmi les outils de test pour logiciel, le testeur unitaire est le plus proche du d&eacute;veloppeur. Dans un contexte de d&eacute;veloppement agile, le code de test se place juste &agrave; c&ocirc;t&eacute; du code source &eacute;tant donn&eacute; que tous les deux sont &eacute;crits simultan&eacute;ment. Dans ce contexte, SimpleTest aspire &agrave; &ecirc;tre une solution compl&egrave;te de test pour un d&eacute;veloppeur PHP et s'appelle "Simple" parce qu'elle devrait &ecirc;tre simple &agrave; utiliser et &agrave; &eacute;tendre. Ce nom n'&eacute;tait pas vraiment un bon choix. Non seulement cette solution inclut toutes les fonctions classiques qu'on est en droit d'attendre de la part des portages de <a href="http://www.junit.org/">JUnit</a> et des <a href="http://sourceforge.net/projects/phpunit/">PHPUnit</a>, mais elle inclut aussi les <a href="http://www.mockobjects.com/">objets fantaisie ou "mock objects"</a>. Sans compter quelques fonctionnalit&eacute;s de <a href="http://sourceforge.net/projects/jwebunit/">JWebUnit</a> : parmi celles-ci la navigation sur des pages web, les tests sur les cookies et l'envoi de formulaire.
- </p>
- <p>
- La d&eacute;monstration la plus rapide : l'exemple
- </p>
- <p>
- Supposons que nous sommes en train de tester une simple classe de log dans un fichier : elle s'appelle <span class="new_code">Log</span> dans <em>classes/Log.php</em>. Commen&ccedil;ons par cr&eacute;er un script de test, appel&eacute; <em>tests/log_test.php</em>. Son contenu est le suivant...
-<pre>
-<strong>&lt;?php
-require_once('simpletest/unit_tester.php');
-require_once('simpletest/reporter.php');
-require_once('../classes/log.php');
-?&gt;</strong>
-</pre>
- Ici le r&eacute;pertoire <em>simpletest</em> est soit dans le dossier courant, soit dans les dossiers pour fichiers inclus. Vous auriez &agrave; &eacute;diter ces arborescences suivant l'endroit o&ugrave; vous avez install&eacute; SimpleTest. Ensuite cr&eacute;ons un sc&eacute;nario de test...
-<pre>
-&lt;?php
-require_once('simpletest/unit_tester.php');
-require_once('simpletest/reporter.php');
-require_once('../classes/log.php');
-<strong>
-class TestOfLogging extends UnitTestCase {
-}</strong>
-?&gt;
-</pre>
- A pr&eacute;sent il y a 5 lignes de code d'&eacute;chafaudage et toujours pas de test. Cependant &agrave; partir de cet instant le retour sur investissement arrive tr&egrave;s rapidement. Supposons que la classe <span class="new_code">Log</span> prenne le nom du fichier &agrave; &eacute;crire dans le constructeur et que nous ayons un r&eacute;pertoire temporaire dans lequel placer ce fichier...
-<pre>
-&lt;?php
-require_once('simpletest/unit_tester.php');
-require_once('simpletest/reporter.php');
-require_once('../classes/log.php');
-
-class TestOfLogging extends UnitTestCase {
- <strong>
- function testCreatingNewFile() {
- @unlink('/temp/test.log');
- $log = new Log('/temp/test.log');
- $this-&gt;assertFalse(file_exists('/temp/test.log'));
- $log-&gt;message('Should write this to a file');
- $this-&gt;assertTrue(file_exists('/temp/test.log'));
- }</strong>
-}
-?&gt;
-</pre>
- Au lancement du sc&eacute;nario de test, toutes les m&eacute;thodes qui commencent avec la cha&icirc;ne <span class="new_code">test</span> sont identifi&eacute;es puis ex&eacute;cut&eacute;es. D'ordinaire nous avons bien plusieurs m&eacute;thodes de tests. Les assertions dans les m&eacute;thodes de test envoient des messages vers le framework de test qui affiche imm&eacute;diatement le r&eacute;sultat. Cette r&eacute;ponse imm&eacute;diate est importante, non seulement lors d'un crash caus&eacute; par le code, mais aussi de mani&egrave;re &agrave; rapprocher l'affichage de l'erreur au plus pr&egrave;s du sc&eacute;nario de test concern&eacute;.
- </p>
- <p>
- Pour voir ces r&eacute;sultats lan&ccedil;ons effectivement les tests. S'il s'agit de l'unique sc&eacute;nario de test &agrave; lancer, on peut y arriver avec...
-<pre>
-&lt;?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-&gt;assertFalse(file_exists('/temp/test.log'));
- $log-&gt;message('Should write this to a file');
- $this-&gt;assertTrue(file_exists('/temp/test.log'));
- }
-}
-<strong>
-$test = &amp;new TestOfLogging();
-$test-&gt;run(new HtmlReporter());</strong>
-?&gt;
-</pre>
- </p>
- <p>
- En cas &eacute;chec, l'affichage ressemble &agrave;...
- <div class="demo">
- <h1>testoflogging</h1>
- <span class="fail">Fail</span>: testcreatingnewfile-&gt;True assertion failed.<br>
- <div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
- <strong>1</strong> passes and <strong>1</strong> fails.</div>
- </div>
- ...et si &ccedil;a passe, on obtient...
- <div class="demo">
- <h1>testoflogging</h1>
- <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
- <strong>2</strong> passes and <strong>0</strong> fails.</div>
- </div>
- Et si vous obtenez &ccedil;a...
- <div class="demo">
- <b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b>
- </div>
- c'est qu'il vous manque le fichier <em>classes/Log.php</em> qui pourrait ressembler &agrave; :
-<pre>
-&lt;?php
-class Log {
-
- function Log($file_path) {
- }
-}
-?&gt;;
-</pre>
- </p>
-
- <p>
-<a class="target" name="group">
-<h2>Construire des groupes de tests</h2>
-</a>
-</p>
- <p>
- Il est peu probable que dans une v&eacute;ritable application on ait uniquement besoin de passer un seul sc&eacute;nario de test. Cela veut dire que nous avons besoin de grouper les sc&eacute;narios dans un script de test qui peut, si n&eacute;cessaire, lancer tous les tests de l'application.
- </p>
- <p>
- Notre premi&egrave;re &eacute;tape est de supprimer les includes et de d&eacute;faire notre hack pr&eacute;c&eacute;dent...
-<pre>
-&lt;?php<strong>
-require_once('../classes/log.php');</strong>
-
-class TestOfLogging extends UnitTestCase {
-
- function testCreatingNewFile() {
- @unlink('/temp/test.log');
- $log = new Log('/temp/test.log');
- $this-&gt;assertFalse(file_exists('/temp/test.log'));
- $log-&gt;message('Should write this to a file');
- $this-&gt;assertTrue(file_exists('/temp/test.log'));<strong>
- }
-}
-?&gt;</strong>
-</pre>
- Ensuite nous cr&eacute;ons un nouveau fichier appel&eacute; <em>tests/all_tests.php</em>. On y insert le code suivant...
-<pre>
-<strong>&lt;?php
-require_once('simpletest/unit_tester.php');
-require_once('simpletest/reporter.php');
-
-$test = &amp;new GroupTest('All tests');
-$test-&gt;addTestFile('log_test.php');
-$test-&gt;run(new HtmlReporter());
-?&gt;</strong>
-</pre>
- Cette m&eacute;thode <span class="new_code">GroupTest::addTestFile()</span> va inclure le fichier de sc&eacute;narios de test et lire parmi toutes les nouvelles classes cr&eacute;&eacute;es celles qui sont issues de <span class="new_code">TestCase</span>. Dans un premier temps, seuls les noms sont stock&eacute;s, de la sorte le lanceur de test peut instancier la classe au fur et &agrave; mesure qu'il ex&eacute;cute votre suite de tests.
- </p>
- <p>
- Pour que &ccedil;a puisse marcher proprement le fichier de suite de tests ne devrait pas inclure aveuglement d'autres extensions de sc&eacute;narios de test qui n'ex&eacute;cuteraient pas effectivement de test. Le r&eacute;sultat pourrait &ecirc;tre que des tests suppl&eacute;mentaires soient alors &ecirc;tre comptabilis&eacute;s pendant l'ex&eacute;cution des tests. Ce n'est pas un probl&egrave;me grave mais pour &eacute;viter ce d&eacute;sagr&eacute;ment, il suffit d'ajouter la commande <span class="new_code">SimpleTestOptions::ignore()</span> quelque part dans le fichier de sc&eacute;nario de test. Par ailleurs le sc&eacute;nario de test ne devrait pas avoir &eacute;t&eacute; inclus ailleurs ou alors aucun sc&eacute;nario ne sera ajout&eacute; aux groupes de test. Il s'agirait l&agrave; d'une erreur autrement s&eacute;rieuse : si tous les classes de sc&eacute;nario de test sont charg&eacute;es par PHP, alors la m&eacute;thode <span class="new_code">GroupTest::addTestFile()</span> ne pourra pas les d&eacute;tecter.
- </p>
- <p>
- Pour afficher les r&eacute;sultats, il est seulement n&eacute;cessaire d'invoquer <em>tests/all_tests.php</em> &agrave; partir du serveur web.
- </p>
-
- <p>
-<a class="target" name="mock">
-<h2>Utiliser les objets fantaisie</h2>
-</a>
-</p>
- <p>
- Avan&ccedil;ons un peu plus dans le futur.
- </p>
- <p>
- Supposons que notre class logging soit test&eacute;e et termin&eacute;e. Supposons aussi que nous testons une autre classe qui ait besoin d'&eacute;crire des messages de log, disons <span class="new_code">SessionPool</span>. Nous voulons tester une m&eacute;thode qui ressemblera probablement &agrave; quelque chose comme...
-<pre>
-<strong>
-class SessionPool {
- ...
- function logIn($username) {
- ...
- $this-&gt;_log-&gt;message('User $username logged in.');
- ...
- }
- ...
-}
-</strong>
-</pre>
- Avec le concept de "r&eacute;utilisation de code" comme fil conducteur, nous utilisons notre class <span class="new_code">Log</span>. Un sc&eacute;nario de test classique ressemblera peut-&ecirc;tre &agrave;...
-<pre>
-<strong>
-&lt;?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 = &amp;new SessionPool($log);
- $session_pool-&gt;logIn('fred');
- $messages = file('/temp/test.log');
- $this-&gt;assertEqual($messages[0], "User fred logged in.\n");
- }
-}
-?&gt;</strong>
-</pre>
- Le design de ce sc&eacute;nario de test n'est pas compl&egrave;tement mauvais, mais on peut l'am&eacute;liorer. Nous passons du temps &agrave; tripoter les fichiers de log qui ne font pas partie de notre test. Pire, nous avons cr&eacute;&eacute; des liens de proximit&eacute; entre la classe <span class="new_code">Log</span> et ce test. Que se passerait-il si nous n'utilisions plus de fichiers, mais la biblioth&egrave;que <em>syslog</em> &agrave; la place ? Avez-vous remarqu&eacute; le retour chariot suppl&eacute;mentaire &agrave; la fin du message ? A-t-il &eacute;t&eacute; ajout&eacute; par le loggueur ? Et si il ajoutait aussi un timestamp ou d'autres donn&eacute;es ?
- </p>
- <p>
- L'unique partie &agrave; tester r&eacute;ellement est l'envoi d'un message pr&eacute;cis au loggueur. Nous r&eacute;duisons le couplage en cr&eacute;ant une fausse classe de logging : elle ne fait qu'enregistrer le message pour le test, mais ne produit aucun r&eacute;sultat. Sauf qu'elle doit ressembler exactement &agrave; l'original.
- </p>
- <p>
- Si l'objet fantaisie n'&eacute;crit pas dans un fichier alors nous nous &eacute;pargnons la suppression du fichier avant et apr&egrave;s le test. Nous pourrions m&ecirc;me nous &eacute;pargner quelques lignes de code suppl&eacute;mentaires si l'objet fantaisie pouvait ex&eacute;cuter l'assertion.
- <p>
- </p>
- Trop beau pour &ecirc;tre vrai ? Par chance on peut cr&eacute;er un tel objet tr&egrave;s facilement...
-<pre>
-&lt;?php
-require_once('../classes/log.php');
-require_once('../classes/session_pool.php');<strong>
-Mock::generate('Log');</strong>
-
-class TestOfSessionLogging extends UnitTestCase {
-
- function testLogInIsLogged() {<strong>
- $log = &amp;new MockLog($this);
- $log-&gt;expectOnce('message', array('User fred logged in.'));</strong>
- $session_pool = &amp;new SessionPool($log);
- $session_pool-&gt;logIn('fred');<strong>
- $log-&gt;tally();</strong>
- }
-}
-?&gt;
-</pre>
- L'appel <span class="new_code">tally()</span> est n&eacute;cessaire pour annoncer &agrave; l'objet fantaisie qu'il n'y aura plus d'appels ult&eacute;rieurs. Sans &ccedil;a l'objet fantaisie pourrait attendre pendant une &eacute;ternit&eacute; l'appel de la m&eacute;thode sans jamais pr&eacute;venir le sc&eacute;nario de test. Les autres tests sont d&eacute;clench&eacute;s automatiquement quand l'appel &agrave; <span class="new_code">message()</span> est invoqu&eacute; sur l'objet <span class="new_code">MockLog</span>. L'appel <span class="new_code">mock</span> va d&eacute;clencher une comparaison des param&egrave;tres et ensuite envoyer le message "pass" ou "fail" au test pour l'affichage. Des jokers peuvent &ecirc;tre inclus ici aussi afin d'emp&ecirc;cher que les tests ne deviennent trop sp&eacute;cifiques.
- </p>
- <p>
- Les objets fantaisie dans la suite SimpleTest peuvent avoir un ensemble de valeurs de sortie arbitraires, des s&eacute;quences de sorties, des valeurs de sortie s&eacute;lectionn&eacute;es &agrave; partir des arguments d'entr&eacute;e, des s&eacute;quences de param&egrave;tres attendus et des limites sur le nombre de fois qu'une m&eacute;thode peut &ecirc;tre invoqu&eacute;e.
- </p>
- <p>
- Pour que ce test fonctionne la librairie avec les objets fantaisie doit &ecirc;tre incluse dans la suite de tests, par exemple dans <em>all_tests.php</em>.
- </p>
-
- <p>
-<a class="target" name="web">
-<h2>Tester une page web</h2>
-</a>
-</p>
- <p>
- Une des exigences des sites web, c'est qu'ils produisent des pages web. Si vous construisez un projet de A &agrave; Z et que vous voulez int&eacute;grer des tests au fur et &agrave; mesure alors vous voulez un outil qui puisse effectuer une navigation automatique et en examiner le r&eacute;sultat. C'est le boulot d'un testeur web.
- </p>
- <p>
- Effectuer un test web via SimpleTest reste assez primitif : il n'y a pas de javascript par exemple. Pour vous donner une id&eacute;e, voici un exemple assez trivial : aller chercher une page web, &agrave; partir de l&agrave; naviguer vers la page "about" et finalement tester un contenu d&eacute;termin&eacute; par le client.
-<pre>
-&lt;?php<strong>
-require_once('simpletest/web_tester.php');</strong>
-require_once('simpletest/reporter.php');
-<strong>
-class TestOfAbout extends WebTestCase {
-
- function setUp() {
- $this-&gt;get('http://test-server/index.php');
- $this-&gt;clickLink('About');
- }
-
- function testSearchEngineOptimisations() {
- $this-&gt;assertTitle('A long title about us for search engines');
- $this-&gt;assertWantedPattern('/a popular keyphrase/i');
- }
-}</strong>
-$test = &amp;new TestOfAbout();
-$test-&gt;run(new HtmlReporter());
-?&gt;
-</pre>
- Avec ce code comme test de recette, vous pouvez vous assurer que le contenu corresponde toujours aux sp&eacute;cifications &agrave; la fois des d&eacute;veloppeurs et des autres parties prenantes au projet.
- </p>
- <p>
- <a href="http://sourceforge.net/projects/simpletest/"><img src="http://sourceforge.net/sflogo.php?group_id=76550&amp;type=5" width="210" height="62" border="0" alt="SourceForge.net Logo"></a>
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/docs/fr/mock_objects_documentation.html b/tests/test_tools/simpletest/docs/fr/mock_objects_documentation.html
deleted file mode 100755
index 0ce48bc9..00000000
--- a/tests/test_tools/simpletest/docs/fr/mock_objects_documentation.html
+++ /dev/null
@@ -1,492 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>Documentation SimpleTest : les objets fantaise</title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<a href="index.html">SimpleTest</a>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Documentation sur les objets fantaisie</h1>
-<div class="content">
- <p>
-<a class="target" name="quoi">
-<h2>Que sont les objets fantaisie ?</h2>
-</a>
-</p>
- <p>
- Les objets fantaisie - ou "mock objects" en anglais - ont deux r&ocirc;les pendant un sc&eacute;nario de test : acteur et critique.
- </p>
- <p>
- Le comportement d'acteur est celui de simuler des objets difficiles &agrave; initialiser ou trop consommateurs en temps pendant un test. Le cas classique est celui de la connexion &agrave; une base de donn&eacute;es. Mettre sur pied une base de donn&eacute;es de test au lancement de chaque test ralentirait consid&eacute;rablement les tests et en plus exigerait l'installation d'un moteur de base de donn&eacute;es ainsi que des donn&eacute;es sur la machine de test. Si nous pouvons simuler la connexion et renvoyer des donn&eacute;es &agrave; notre guise alors non seulement nous gagnons en pragmatisme sur les tests mais en sus nous pouvons nourrir notre base avec des donn&eacute;es falsifi&eacute;es et voir comment il r&eacute;pond. Nous pouvons simuler une base de donn&eacute;es en suspens ou d'autres cas extr&ecirc;mes sans avoir &agrave; cr&eacute;er une v&eacute;ritable panne de base de donn&eacute;es. En d'autres termes nous pouvons gagner en contr&ocirc;le sur l'environnement de test.
- </p>
- <p>
- Si les objets fantaisie ne se comportaient que comme des acteurs alors on les conna&icirc;trait sous le nom de <a href="server_stubs_documentation.html">bouchons serveur</a>.
- </p>
- <p>
- Cependant non seulement les objets fantaisie jouent un r&ocirc;le (en fournissant &agrave; la demande les valeurs requises) mais en plus ils sont aussi sensibles aux messages qui leur sont envoy&eacute;s (par le biais d'attentes). En posant les param&egrave;tres attendus d'une m&eacute;thode ils agissent comme des gardiens : un appel sur eux doit &ecirc;tre r&eacute;alis&eacute; correctement. Si les attentes ne sont pas atteintes ils nous &eacute;pargnent l'effort de l'&eacute;criture d'une assertion de test avec &eacute;chec en r&eacute;alisant cette t&acirc;che &agrave; notre place. Dans le cas d'une connexion &agrave; une base de donn&eacute;es imaginaire ils peuvent tester si la requ&ecirc;te, disons SQL, a bien &eacute;t&eacute; form&eacute; par l'objet qui utilise cette connexion. Mettez-les sur pied avec des attentes assez pr&eacute;cises et vous verrez que vous n'aurez presque plus d'assertion &agrave; &eacute;crire manuellement.
- </p>
-
- <p>
-<a class="target" name="creation">
-<h2>Cr&eacute;er des objets fantaisie</h2>
-</a>
-</p>
- <p>
- Comme pour la cr&eacute;ation des bouchons serveur, tout ce dont nous avons besoin c'est d'un classe existante. La fameuse connexion &agrave; une base de donn&eacute;es qui ressemblerait &agrave;...
-<pre>
-<strong>class DatabaseConnection {
- function DatabaseConnection() {
- }
-
- function query() {
- }
-
- function selectQuery() {
- }
-}</strong>
-</pre>
- Cette classe n'a pas encore besoin d'&ecirc;tre impl&eacute;ment&eacute;e. Pour en cr&eacute;er sa version fantaisie nous devons juste inclure la librairie d'objet fantaisie puis lancer le g&eacute;n&eacute;rateur...
-<pre>
-<strong>require_once('simpletest/unit_tester.php');
-require_once('simpletest/mock_objects.php');
-require_once('database_connection.php');
-
-Mock::generate('DatabaseConnection');</strong>
-</pre>
- Ceci g&eacute;n&egrave;re une classe clone appel&eacute;e <span class="new_code">MockDatabaseConnection</span>. Nous pouvons d&eacute;sormais cr&eacute;er des instances de cette nouvelle classe &agrave; l'int&eacute;rieur m&ecirc;me de notre sc&eacute;nario de test...
-<pre>
-require_once('simpletest/unit_tester.php');
-require_once('simpletest/mock_objects.php');
-require_once('database_connection.php');
-
-Mock::generate('DatabaseConnection');
-<strong>
-class MyTestCase extends UnitTestCase {
-
- function testSomething() {
- $connection = &amp;new MockDatabaseConnection($this);
- }
-}</strong>
-</pre>
- Contrairement aux bouchons, le constructeur d'une classe fantaisie a besoin d'une r&eacute;f&eacute;rence au sc&eacute;nario de test pour pouvoir transmettre les succ&egrave;s et les &eacute;checs pendant qu'il v&eacute;rifie les attentes. Concr&egrave;tement &ccedil;a veut dire que les objets fantaisie ne peuvent &ecirc;tre utilis&eacute;s qu'au sein d'un sc&eacute;nario de test. Malgr&eacute; tout, cette puissance suppl&eacute;mentaire implique que les bouchons ne sont que rarement utilis&eacute;s si des objets fantaisie sont disponibles.
- </p>
- <p>
- <a class="target" name="bouchon">
-<h2>Objets fantaisie en action</h2>
-</a>
- </p>
- <p>
- La version fantaisie d'une classe contient toutes les m&eacute;thodes de l'originale. De la sorte une op&eacute;ration comme <span class="new_code">$connection-&gt;query()</span> est encore possible. Tout comme avec les bouchons, nous pouvons remplacer la valeur nulle renvoy&eacute;e par d&eacute;faut...
-<pre>
-<strong>$connection-&gt;setReturnValue('query', 37);</strong>
-</pre>
- D&eacute;sormais &agrave; chaque appel de <span class="new_code">$connection-&gt;query()</span> nous recevons comme r&eacute;sultat 37. Tout comme avec les bouchons nous pouvons utiliser des jokers et surcharger le param&egrave;tre joker. Nous pouvons aussi ajouter des m&eacute;thodes suppl&eacute;mentaires &agrave; l'objet fantaisie lors de sa g&eacute;n&eacute;ration et lui choisir un nom de classe qui lui soit propre...
-<pre>
-<strong>Mock::generate('DatabaseConnection', 'MyMockDatabaseConnection', array('setOptions'));</strong>
-</pre>
- Ici l'objet fantaisie se comportera comme si <span class="new_code">setOptions()</span> existait dans la classe originale. C'est pratique si une classe a utilis&eacute; le m&eacute;canisme <span class="new_code">overload()</span> de PHP pour ajouter des m&eacute;thodes dynamiques. Vous pouvez cr&eacute;er des fantaisies sp&eacute;ciales pour simuler cette situation.
- </p>
- <p>
- Tous les mod&egrave;les disponibles avec les bouchons serveur le sont &eacute;galement avec les objets fantaisie...
-<pre>
-class Iterator {
- function Iterator() {
- }
-
- function next() {
- }
-}
-</pre>
- Une nouvelle fois, supposons que cet it&eacute;rateur ne retourne que du texte jusqu'au moment o&ugrave; il atteint son terme, quand il renvoie <span class="new_code">false</span>. Nous pouvons le simuler avec...
-<pre>
-Mock::generate('Iterator');
-
-class IteratorTest extends UnitTestCase() {
-
- function testASequence() {<strong>
- $iterator = &amp;new MockIterator($this);
- $iterator-&gt;setReturnValue('next', false);
- $iterator-&gt;setReturnValueAt(0, 'next', 'First string');
- $iterator-&gt;setReturnValueAt(1, 'next', 'Second string');</strong>
- ...
- }
-}
-</pre>
- Au moment du premier appel &agrave; <span class="new_code">next()</span> sur l'it&eacute;rateur fantaisie il renverra tout d'abord "First string", puis ce sera au tour de "Second string" au deuxi&egrave;me appel et ensuite pour tout appel suivant <span class="new_code">false</span> sera renvoy&eacute;. Ces valeurs renvoy&eacute;es successivement sont prioritaires sur la valeur constante retourn&eacute;e. Cette derni&egrave;re est un genre de valeur par d&eacute;faut si vous voulez.
- </p>
- <p>
- Reprenons aussi le conteneur d'information bouchonn&eacute; avec des pairs clef / valeur...
-<pre>
-class Configuration {
- function Configuration() {
- }
-
- function getValue($key) {
- }
-}
-</pre>
- Il s'agit l&agrave; d'une situation classique d'utilisation d'objets fantaisie &eacute;tant donn&eacute; que la configuration peut varier grandement de machine &agrave; machine : &ccedil;a contraint fortement la fiabilit&eacute; de nos tests si nous l'utilisons directement. Le probl&egrave;me est que toutes les donn&eacute;es nous parviennent &agrave; travers la m&eacute;thode <span class="new_code">getValue()</span> et que nous voulons des r&eacute;sultats diff&eacute;rents pour des clefs diff&eacute;rentes. Heureusement les objets fantaisie ont un syst&egrave;me de filtrage...
-<pre>
-<strong>$config = &amp;new MockConfiguration($this);
-$config-&gt;setReturnValue('getValue', 'primary', array('db_host'));
-$config-&gt;setReturnValue('getValue', 'admin', array('db_user'));
-$config-&gt;setReturnValue('getValue', 'secret', array('db_password'));</strong>
-</pre>
- Le param&egrave;tre en plus est une liste d'arguments &agrave; faire correspondre. Dans ce cas nous essayons de faire correspondre un unique argument : en l'occurrence la clef recherch&eacute;e. Maintenant que la m&eacute;thode <span class="new_code">getValue()</span> est invoqu&eacute;e sur l'objet fantaisie...
-<pre>
-$config-&gt;getValue('db_user')
-</pre>
- ...elle renverra "admin". Elle le trouve en essayant de faire correspondre les arguments entrants dans sa liste d'arguments sortants les uns apr&egrave;s les autres jusqu'au moment o&ugrave; une correspondance exacte est atteinte.
- </p>
- <p>
- Il y a des fois o&ugrave; vous souhaitez qu'un objet sp&eacute;cifique soit servi par la fantaisie plut&ocirc;t qu'une copie. De nouveau c'est identique au m&eacute;canisme des bouchons serveur...
-<pre>
-class Thing {
-}
-
-class Vector {
- function Vector() {
- }
-
- function get($index) {
- }
-}
-</pre>
- Dans ce cas vous pouvez placer une r&eacute;f&eacute;rence dans la liste renvoy&eacute;e par l'objet fantaisie...
-<pre>
-$thing = new Thing();<strong>
-$vector = &amp;new MockVector($this);
-$vector-&gt;setReturnReference('get', $thing, array(12));</strong>
-</pre>
- Avec cet arrangement vous savez qu'&agrave; chaque appel de <span class="new_code">$vector-&gt;get(12)</span> le m&ecirc;me <span class="new_code">$thing</span> sera renvoy&eacute;.
- </p>
-
- <p>
-<a class="target" name="attentes">
-<h2>Objets fantaisie en critique</h2>
-</a>
-</p>
- <p>
- M&ecirc;me si les bouchons serveur vous isolent du d&eacute;sordre du monde r&eacute;el, il ne s'agit l&agrave; que de la moiti&eacute; du b&eacute;n&eacute;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.
- </p>
- <p>
- Pour l'exemple, prenons une classe <span class="new_code">SessionPool</span> &agrave; laquelle nous allons ajouter une fonction de log. Plut&ocirc;t que de complexifier la classe originale, nous souhaitons ajouter ce comportement avec un d&eacute;corateur (GOF). Pour l'instant le code de <span class="new_code">SessionPool</span> ressemble &agrave;...
-<pre>
-<strong>class SessionPool {
- function SessionPool() {
- ...
- }
-
- function &amp;findSession($cookie) {
- ...
- }
- ...
-}
-
-class Session {
- ...
-}</strong>
-
-</pre>
- Alors que pour notre code de log, nous avons...
-<pre>
-<strong>
-class Log {
- function Log() {
- ...
- }
-
- function message() {
- ...
- }
-}
-
-class LoggingSessionPool {
- function LoggingSessionPool(&amp;$session_pool, &amp;$log) {
- ...
- }
-
- function &amp;findSession(\$cookie) {
- ...
- }
- ...
-}</strong>
-</pre>
- Dans tout ceci, la seule classe &agrave; tester est <span class="new_code">LoggingSessionPool</span>. En particulier, nous voulons v&eacute;rifier que la m&eacute;thode <span class="new_code">findSession()</span> est appel&eacute;e avec le bon identifiant de session au sein du cookie et qu'elle renvoie bien le message "Starting session $cookie" au loggueur.
- </p>
- <p>
- Bien que nous ne testions que quelques lignes de code de production, voici la liste des choses &agrave; faire dans un sc&eacute;nario de test conventionnel :
- <ol>
- <li>Cr&eacute;er un objet de log.</li>
- <li>Indiquer le r&eacute;pertoire d'&eacute;criture du fichier de log.</li>
- <li>Modifier les droits sur le r&eacute;pertoire pour pouvoir y &eacute;crire le fichier.</li>
- <li>Cr&eacute;er un objet <span class="new_code">SessionPool</span>.</li>
- <li>Lancer une session, ce qui demande probablement pas mal de choses.</li>
- <li>Invoquer <span class="new_code">findSession()</span>.</li>
- <li>Lire le nouvel identifiant de sessions (en esp&eacute;rant qu'il existe un accesseur !).</li>
- <li>Lever une assertion de test pour v&eacute;rifier que cet identifiant correspond bien au cookie.</li>
- <li>Lire la derni&egrave;re ligne du fichier de log.</li>
- <li>Supprimer avec une (ou plusieurs) expression rationnelle les timestamps de log en trop, etc.</li>
- <li>V&eacute;rifier que le message de session est bien dans le texte.</li>
- </ol>
- Pas &eacute;tonnant que les d&eacute;veloppeurs d&eacute;testent &eacute;crire des tests quand ils sont aussi ingrats. Pour rendre les choses encore pire, &agrave; chaque fois que le format de log change ou bien que la m&eacute;thode de cr&eacute;ation des sessions change, nous devons r&eacute;&eacute;crire une partie des tests alors m&ecirc;me qu'ils ne testent pas ces parties du syst&egrave;me. Nous sommes en train de pr&eacute;parer le cauchemar pour les d&eacute;veloppeurs de ces autres classes.
- </p>
- <p>
- A la place, voici la m&eacute;thode compl&egrave;te pour le test avec un peu de magie via les objets fantaisie...
-<pre>
-Mock::generate('Session');
-Mock::generate('SessionPool');
-Mock::generate('Log');
-
-class LoggingSessionPoolTest extends UnitTestCase {
- ...
- function testFindSessionLogging() {<strong>
- $session = &amp;new MockSession($this);
- $pool = &amp;new MockSessionPool($this);
- $pool-&gt;setReturnReference('findSession', $session);
- $pool-&gt;expectOnce('findSession', array('abc'));
-
- $log = &amp;new MockLog($this);
- $log-&gt;expectOnce('message', array('Starting session abc'));
-
- $logging_pool = &amp;new LoggingSessionPool($pool, $log);
- $this-&gt;assertReference($logging_pool-&gt;findSession('abc'), $session);
- $pool-&gt;tally();
- $log-&gt;tally();</strong>
- }
-}
-</pre>
- Commen&ccedil;ons par &eacute;crire une session simulacre. Pas la peine d'&ecirc;tre trop pointilleux avec celle-ci puisque la v&eacute;rification de la session d&eacute;sir&eacute;e est effectu&eacute;e ailleurs. Nous avons juste besoin de v&eacute;rifier qu'il s'agit de la m&ecirc;me que celle qui vient du groupe commun des sessions.
- </p>
- <p>
- <span class="new_code">findSession()</span> est un m&eacute;thode fabrique dont la simulation est d&eacute;crite <a href="#stub">plus haut</a>. Le point de d&eacute;part vient avec le premier appel <span class="new_code">expectOnce()</span>. Cette ligne indique qu'&agrave; chaque fois que <span class="new_code">findSession()</span> est invoqu&eacute; sur l'objet fantaisie, il v&eacute;rifiera les arguments entrant. S'il ne re&ccedil;oit que la cha&icirc;ne "abc" en tant qu'argument alors un succ&egrave;s est envoy&eacute; au testeur unitaire, sinon c'est un &eacute;chec qui est g&eacute;n&eacute;r&eacute;. Il s'agit l&agrave; de la partie qui teste si nous avons bien la bonne session. La liste des arguments suit une format identique &agrave; celui qui pr&eacute;cise les valeurs renvoy&eacute;es. Vous pouvez avoir des jokers et des s&eacute;quences et l'ordre de l'&eacute;valuation restera le m&ecirc;me.
- </p>
- <p>
- Si l'appel n'est jamais effectu&eacute; alors n'est g&eacute;n&eacute;r&eacute; ni le succ&egrave;s, ni l'&eacute;chec. Pour contourner cette limitation, nous devons dire &agrave; l'objet fantaisie que le test est termin&eacute; : il pourra alors d&eacute;cider si les attentes ont &eacute;t&eacute; r&eacute;pondues. L'assertion du testeur unitaire de ceci est d&eacute;clench&eacute;e par l'appel <span class="new_code">tally()</span> &agrave; la fin du test.
- </p>
- <p>
- Nous utilisons le m&ecirc;me mod&egrave;le pour mettre sur pied le loggueur fantaisie. Nous lui indiquons que <span class="new_code">message()</span> devrait &ecirc;tre invoqu&eacute; une fois et une fois seulement avec l'argument "Starting session abc". En testant les arguments d'appel, plut&ocirc;t que ceux de sorite du loggueur, nous isolons le test de tout modification dans le loggueur.
- </p>
- <p>
- Nous commen&ccedil;ons le lancement nos tests &agrave; la cr&eacute;ation du nouveau <span class="new_code">LoggingSessionPool</span> et nous l'alimentons avec nos objets fantaisie juste cr&eacute;&eacute;s. D&eacute;sormais tout est sous contr&ocirc;le. Au final nous confirmons que le <span class="new_code">$session</span> donn&eacute; au d&eacute;corateur est bien celui re&ccedil;u et prions les objets fantaisie de lancer leurs tests de comptage d'appel interne avec les appels <span class="new_code">tally()</span>.
- </p>
- <p>
- Il y a encore pas mal de code de test, mais ce code est tr&egrave;s strict. S'il vous semble encore terrifiant il l'est bien moins que si nous avions essay&eacute; sans les objets fantaisie et ce test en particulier, interactions plut&ocirc;t que r&eacute;sultat, est toujours plus difficile &agrave; mettre en place. Le plus souvent vous aurez besoin de tester des situations plus complexes sans ce niveau ni cette pr&eacute;cision. En outre une partie peut &ecirc;tre remani&eacute;e avec la m&eacute;thode de sc&eacute;nario de test <span class="new_code">setUp()</span>.
- </p>
- <p>
- Voici la liste compl&egrave;te des attentes que vous pouvez placer sur un objet fantaisie avec <a href="http://www.lastcraft.com/simple_test.php">SimpleTest</a>...
- <table>
-<thead>
- <tr>
-<th>Attente</th><th>N&eacute;cessite <span class="new_code">tally()</span></th>
-</tr>
- </thead>
-<tbody>
-<tr>
- <td><span class="new_code">expectArguments($method, $args)</span></td>
- <td style="text-align: center">Non</td>
- </tr>
- <tr>
- <td><span class="new_code">expectArgumentsAt($timing, $method, $args)</span></td>
- <td style="text-align: center">Non</td>
- </tr>
- <tr>
- <td><span class="new_code">expectCallCount($method, $count)</span></td>
- <td style="text-align: center">Oui</td>
- </tr>
- <tr>
- <td><span class="new_code">expectMaximumCallCount($method, $count)</span></td>
- <td style="text-align: center">Non</td>
- </tr>
- <tr>
- <td><span class="new_code">expectMinimumCallCount($method, $count)</span></td>
- <td style="text-align: center">Oui</td>
- </tr>
- <tr>
- <td><span class="new_code">expectNever($method)</span></td>
- <td style="text-align: center">Non</td>
- </tr>
- <tr>
- <td><span class="new_code">expectOnce($method, $args)</span></td>
- <td style="text-align: center">Oui</td>
- </tr>
- <tr>
- <td><span class="new_code">expectAtLeastOnce($method, $args)</span></td>
- <td style="text-align: center">Oui</td>
- </tr>
- </tbody>
-</table>
- O&ugrave; les param&egrave;tres sont...
- <dl>
- <dt class="new_code">$method</dt>
- <dd>Le nom de la m&eacute;thode, sous la forme d'une cha&icirc;ne, &agrave; laquelle la condition doit &ecirc;tre appliqu&eacute;e.</dd>
- <dt class="new_code">$args</dt>
- <dd>
- Les arguments sous la forme d'une liste. Les jokers peuvent &ecirc;tre inclus de la m&ecirc;me mani&egrave;re qu'avec <span class="new_code">setReturn()</span>. Cet argument est optionel pour <span class="new_code">expectOnce()</span> et <span class="new_code">expectAtLeastOnce()</span>.
- </dd>
- <dt class="new_code">$timing</dt>
- <dd>
- Le seul point dans le temps pour tester la condition. Le premier appel commence &agrave; z&eacute;ro.
- </dd>
- <dt class="new_code">$count</dt>
- <dd>Le nombre d'appels attendu.</dd>
- </dl>
- La m&eacute;thode <span class="new_code">expectMaximumCallCount()</span> est l&eacute;g&egrave;rement diff&eacute;rente dans le sens o&ugrave; elle ne pourra g&eacute;n&eacute;rer qu'un &eacute;chec. Elle reste silencieuse si la limite n'est jamais atteinte.
- </p>
- <p>
- Comme avec les assertions dans les sc&eacute;narios de test, toutes ces attentes peuvent accepter une surcharge de message sous la forme d'un param&egrave;tre suppl&eacute;mentaire. Par ailleurs le message d'&eacute;chec original peut &ecirc;tre inclus dans le r&eacute;sultat avec "%s".
- </p>
-
- <p>
-<a class="target" name="approches">
-<h2>D'autres approches</h2>
-</a>
-</p>
- <p>
- Il existe trois approches pour cr&eacute;er des objets fantaisie en comprenant celle utiliser par SimpleTest. Les coder &agrave; la main en utilisant une classe de base, les g&eacute;n&eacute;rer dans un fichier ou les g&eacute;n&eacute;rer dynamiquement &agrave; la vol&eacute;e.
- </p>
- <p>
- Les objets fantaisie g&eacute;n&eacute;r&eacute;s avec <a href="simple_test.html">SimpleTest</a> sont dynamiques. Ils sont cr&eacute;&eacute;s &agrave; l'ex&eacute;cution dans la m&eacute;moire, gr&acirc;ce &agrave; <span class="new_code">eval()</span>, plut&ocirc;t qu'&eacute;crit dans un fichier. Cette op&eacute;ration les rend facile &agrave; cr&eacute;er, en une seule ligne, surtout par rapport &agrave; leur cr&eacute;ation &agrave; la main dans une hi&eacute;rarchie de classe parall&egrave;le. Le probl&egrave;me avec ce comportement tient g&eacute;n&eacute;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&eacute;synchronisation peut subvenir. Cela peut aussi arriver avec l'approche en hi&eacute;rarchie parall&egrave;le, mais c'est d&eacute;tect&eacute; beaucoup plus vite.
- </p>
- <p>
- Bien s&ucirc;r, la solution est d'ajouter de v&eacute;ritables tests d'int&eacute;gration. Vous n'en avez pas besoin de beaucoup et le c&ocirc;t&eacute; pratique des objets fantaisie fait plus que compenser la petite dose de test suppl&eacute;mentaire. Vous ne pouvez pas avoir confiance dans du code qui ne serait test&eacute; que par des objets fantaisie.
- </p>
- <p>
- Si vous restez d&eacute;termin&eacute; de construire des librairies statiques d'objets fantaisie parce que vous souhaitez &eacute;muler un comportement tr&egrave;s sp&eacute;cifique, vous pouvez y parvenir gr&acirc;ce au g&eacute;n&eacute;rateur de classe de SimpleTest. Dans votre fichier librairie, par exemple <em>mocks/connection.php</em> pour une connexion &agrave; une base de donn&eacute;es, cr&eacute;er un objet fantaisie et provoquer m'h&eacute;ritage pour h&eacute;riter pour surcharger des m&eacute;thodes sp&eacute;ciales ou ajouter des pr&eacute;r&eacute;glages...
-<pre>
-&lt;?php
- require_once('simpletest/mock_objects.php');
- require_once('../classes/connection.php');
-<strong>
- Mock::generate('Connection', 'BasicMockConnection');
- class MockConnection extends BasicMockConnection {
- function MockConnection(&amp;$test, $wildcard = '*') {
- $this-&gt;BasicMockConnection($test, $wildcard);
- $this-&gt;setReturn('query', false);
- }
- }</strong>
-?&gt;
-</pre>
- L'appel <span class="new_code">generate</span> dit au g&eacute;n&eacute;rateur de classe d'en cr&eacute;er une appel&eacute;e <span class="new_code">BasicMockConnection</span> plut&ocirc;t que la plus courante <span class="new_code">MockConnection</span>. Ensuite nous h&eacute;ritons &agrave; partir de celle-ci pour obtenir notre version de <span class="new_code">MockConnection</span>. En interceptant de cette mani&egrave;re nous pouvons ajouter un comportement, ici transformer la valeur par d&eacute;faut de <span class="new_code">query()</span> en "false".
- En utilisant le nom par d&eacute;faut nous garantissons que le g&eacute;n&eacute;rateur de classe fantaisie n'en recr&eacute;era pas une autre diff&eacute;rente si il est invoqu&eacute; ailleurs dans les tests. Il ne cr&eacute;era jamais de classe si elle existe d&eacute;j&agrave;. Aussi longtemps que le fichier ci-dessus est inclus avant alors tous les tests qui g&eacute;n&eacute;raient <span class="new_code">MockConnection</span> devraient utiliser notre version &agrave; pr&eacute;sent. Par contre si nous avons une erreur dans l'ordre et que la librairie de fantaisie en cr&eacute;e une d'abord alors la cr&eacute;ation de la classe &eacute;chouera tout simplement.
- </p>
- <p>
- Utiliser cette astuce si vous vous trouvez avec beaucoup de comportement en commun sur les objets fantaisie ou si vous avez de fr&eacute;quents probl&egrave;mes d'int&eacute;gration plus tard dans les &eacute;tapes de test.
- </p>
-
- <p>
-<a class="target" name="autres_testeurs">
-<h2>Je pense que SimpleTest pue !</h2>
-</a>
-</p>
- <p>
- Mais au moment d'&eacute;crire ces lignes c'est le seul &agrave; g&eacute;rer les objets fantaisie, donc vous &ecirc;tes bloqu&eacute; avec lui ?
- </p>
- <p>
- Non, pas du tout.
- <a href="simple_test.html">SimpleTest</a> est une bo&icirc;te &agrave; outils et parmi ceux-ci on trouve les objets fantaisie qui peuvent &ecirc;tre utilis&eacute;s ind&eacute;pendamment. Supposons que vous avez votre propre testeur unitaire favori et que tous vos tests actuels l'utilisent. Pr&eacute;tendez que vous avez appel&eacute; votre tester unitaire PHPUnit (c'est ce que tout le monde a fait) et que la classe principale de test ressemble &agrave;...
-<pre>
-class PHPUnit {
- function PHPUnit() {
- }
-
- function assertion($message, $assertion) {
- }
- ...
-}
-</pre>
- La seule chose que la m&eacute;thode <span class="new_code">assertion()</span> r&eacute;alise, c'est de pr&eacute;parer une sortie embellie alors le param&egrave;tre boolien de l'assertion sert &agrave; d&eacute;terminer s'il s'agit d'une erreur ou d'un succ&egrave;s. Supposons qu'elle est utilis&eacute;e de la mani&egrave;re suivante...
-<pre>
-$unit_test = new PHPUnit();
-$unit_test&gt;assertion('I hope this file exists', file_exists('my_file'));
-</pre>
- Comment utiliser les objets fantaisie avec ceci ?
- </p>
- <p>
- Il y a une m&eacute;thode prot&eacute;g&eacute;e sur la classe de base des objets fantaisie : elle s'appelle <span class="new_code">_assertTrue()</span>. En surchargeant cette m&eacute;thode nous pouvons utiliser notre propre format d'assertion. Nous commen&ccedil;ons avec une sous-classe, dans <em>my_mock.php</em>...
-<pre>
-<strong>&lt;?php
- require_once('simpletest/mock_objects.php');
-
- class MyMock extends SimpleMock() {
- function MyMock(&amp;$test, $wildcard) {
- $this-&gt;SimpleMock($test, $wildcard);
- }
-
- function _assertTrue($assertion, $message) {
- $test = &amp;$this-&gt;getTest();
- $test-&gt;assertion($message, $assertion);
- }
- }
-?&gt;</strong>
-</pre>
- Maintenant une instance de <span class="new_code">MyMock</span> cr&eacute;era un objet qui parle le m&ecirc;me langage que votre testeur. Bien s&ucirc;r le truc c'est que nous cr&eacute;ons jamais un tel objet : le g&eacute;n&eacute;rateur s'en chargera. Nous avons juste besoin d'une ligne de code suppl&eacute;mentaire pour dire au g&eacute;n&eacute;rateur d'utiliser vos nouveaux objets fantaisie...
-<pre>
-&lt;?php
- require_once('simpletst/mock_objects.php');
-
- class MyMock extends SimpleMock() {
- function MyMock($test, $wildcard) {
- $this-&gt;SimpleMock(&amp;$test, $wildcard);
- }
-
- function _assertTrue($assertion, $message , &amp;$test) {
- $test-&gt;assertion($message, $assertion);
- }
- }<strong>
- SimpleTestOptions::setMockBaseClass('MyMock');</strong>
-?&gt;
-</pre>
- A partir de maintenant vous avez juste &agrave; inclure <em>my_mock.php</em> &agrave; la place de la version par d&eacute;faut <em>simple_mock.php</em> et vous pouvez introduire des objets fantaisie dans votre suite de tests existants.
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/docs/fr/overview.html b/tests/test_tools/simpletest/docs/fr/overview.html
deleted file mode 100755
index b6965753..00000000
--- a/tests/test_tools/simpletest/docs/fr/overview.html
+++ /dev/null
@@ -1,294 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>
- Aper&ccedil;u et liste des fonctionnalit&eacute;s des testeurs unitaires PHP et web de SimpleTest PHP
- </title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<a href="index.html">SimpleTest</a>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Apercu de SimpleTest</h1>
-<div class="content">
- <p>
-<a class="target" name="resume">
-<h2>Qu'est-ce que SimpleTest ?</h2>
-</a>
-</p>
- <p>
- Le coeur de SimpleTest est un framework de test construit autour de classes de sc&eacute;narios de test. Celles-ci sont &eacute;crites comme des extensions des classes premi&egrave;res de sc&eacute;narios de test, chacune &eacute;largie avec des m&eacute;thodes qui contiennent le code de test effectif. Les scripts de test de haut niveau invoque la m&eacute;thode <span class="new_code">run()</span> &agrave; chaque sc&eacute;nario de test successivement. Chaque m&eacute;thode de test est &eacute;crite pour appeler des assertions diverses que le d&eacute;veloppeur suppose &ecirc;tre vraies, <span class="new_code">assertEqual()</span> par exemple. Si l'assertion est correcte, alors un succ&egrave;s est exp&eacute;di&eacute; au rapporteur observant le test, mais toute erreur d&eacute;clenche une alerte et une description de la dissension.
- </p>
- <p>
- Un <a href="unit_test_documentation.html">sc&eacute;nario de test</a> ressemble &agrave;...
-<pre>
-class <strong>MyTestCase</strong> extends UnitTestCase {
- <strong>
- function testLog() {
- $log = &amp;new Log('my.log');
- $log-&gt;message('Hello');
- $this-&gt;assertTrue(file_exists('my.log'));
- }</strong>
-}
-</pre>
- </p>
- <p>
- Ces outils sont con&ccedil;us pour le d&eacute;veloppeur. Les tests sont &eacute;crits en PHP directement, plus ou moins simultan&eacute;ment avec la construction de l'application elle-m&ecirc;me. L'avantage d'utiliser PHP lui-m&ecirc;me comme langage de test est qu'il n'y a pas de nouveau langage &agrave; apprendre, les tests peuvent commencer directement et le d&eacute;veloppeur peut tester n'importe quelle partie du code. Plus simplement, toutes les parties qui peuvent &ecirc;tre acc&eacute;d&eacute;es par le code de l'application peuvent aussi &ecirc;tre acc&eacute;d&eacute;es par le code de test si ils sont tous les deux dans le m&ecirc;me langage.
- </p>
- <p>
- Le type de sc&eacute;nario de test le plus simple est le <span class="new_code">UnitTestCase</span>. Cette classe de sc&eacute;nario de test inclut les tests standards pour l'&eacute;galit&eacute;, les r&eacute;f&eacute;rences et l'appariement de motifs (via les expressions rationnelles). Ceux-ci testent ce que vous seriez en droit d'attendre du r&eacute;sultat d'une fonction ou d'une m&eacute;thode. Il s'agit du type de test le plus commun pendant le quotidien du d&eacute;veloppeur, peut-&ecirc;tre 95% des sc&eacute;narios de test.
- </p>
- <p>
- La t&acirc;che ultime d'une application web n'est cependant pas de produire une sortie correcte &agrave; partir de m&eacute;thodes ou d'objets, mais plut&ocirc;t de produire des pages web. La classe <span class="new_code">WebTestCase</span> teste des pages web. Elle simule un navigateur web demandant une page, de fa&ccedil;on exhaustive : cookies, proxies, connexions s&eacute;curis&eacute;es, authentification, formulaires, cadres et la plupart des &eacute;l&eacute;ments de navigation. Avec ce type de sc&eacute;nario de test, le d&eacute;veloppeur peut garantir que telle ou telle information est pr&eacute;sente dans la page et que les formulaires ainsi que les sessions sont g&eacute;r&eacute;s comme il faut.
- </p>
- <p>
- Un <a href="web_tester_documentation.html">sc&eacute;nario de test web</a> ressemble &agrave;...
-<pre>
-class <strong>MySiteTest</strong> extends WebTestCase {
- <strong>
- function testHomePage() {
- $this-&gt;get('http://www.my-site.com/index.php');
- $this-&gt;assertTitle('My Home Page');
- $this-&gt;clickLink('Contact');
- $this-&gt;assertTitle('Contact me');
- $this-&gt;assertWantedPattern('/Email me at/');
- }</strong>
-}
-</pre>
- </p>
-
- <p>
-<a class="target" name="fonctionnalites">
-<h2>Liste des fonctionnalites</h2>
-</a>
-</p>
- <p>
- Ci-dessous vous trouverez un canevas assez brut des fonctionnalit&eacute;s &agrave; aujourd'hui et pour demain, sans oublier leur date approximative de publication. J'ai bien peur qu'il soit modifiable sans pr&eacute;-avis &eacute;tant donn&eacute; que les jalons d&eacute;pendent beaucoup sur le temps disponible. Les trucs en vert ont &eacute;t&eacute; cod&eacute;s, mais pas forc&eacute;ment d&eacute;j&agrave; rendus public. Si vous avez une besoin pressant pour une fonctionnalit&eacute; verte mais pas encore publique alors vous devriez retirer le code directement sur le CVS chez SourceFourge. Une fonctionnalit&eacute;e publi&eacute;e est indiqu&eacute; par "Fini".
- <table>
-<thead>
- <tr>
-<th>Fonctionnalit&eacute;</th><th>Description</th><th>Publication</th>
-</tr>
- </thead>
-<tbody>
-<tr>
- <td>Sc&eacute;nariot de test unitaire</td>
- <td>Les classes de test et assertions de base</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Affichage HTML</td>
- <td>L'affichage le plus simple possible</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Autochargement des sc&eacute;narios de test</td>
- <td>Lire un fichier avec des sc&eacute;narios de test et les charger dans un groupe de test automatiquement</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>G&eacute;n&eacute;rateur de code d'objets fantaisie</td>
- <td>Des objets capable de simuler d'autres objets, supprimant les d&eacute;pendances dans les tests</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Bouchons serveur</td>
- <td>Des objets fantaisie sans r&eacute;sultat attendu &agrave; utiliser &agrave; l'ext&eacute;rieur des sc&eacute;narios de test, pour le prototypage par exemple.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Int&eacute;gration d'autres testeurs unitaires</td>
- <td>
- La capacit&eacute; de lire et simuler d'autres sc&eacute;narios de test en provenance de PHPUnit et de PEAR::Phpunit.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Sc&eacute;nario de test web</td>
- <td>Appariement basique de motifs dans une page t&eacute;l&eacute;charg&eacute;e.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Analyse de page HTML</td>
- <td>Permet de suivre les liens et de trouver la balise de titre</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Simulacre partiel</td>
- <td>Simuler des parties d'une classe pour tester moins qu'une classe ou dans des cas complexes.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Gestion des cookies Web</td>
- <td>Gestion correcte des cookies au t&eacute;l&eacute;chargement d'une page.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Suivi des redirections</td>
- <td>Le t&eacute;l&eacute;chargement d'une page suit automatiquement une redirection 300.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Analyse d'un formulaire</td>
- <td>La capacit&eacute; de valider un formulaire simple et d'en lire les valeurs par d&eacute;faut.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Interface en ligne de commande</td>
- <td>Affiche le r&eacute;sultat des tests sans navigateur web.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Mise &agrave; nu des attentes d'une classe</td>
- <td>Peut cr&eacute;er des tests pr&eacute;cis avec des simulacres ainsi que des sc&eacute;narios de test.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Sortie et analyse XML</td>
- <td>Permet de tester sur plusieurs h&ocirc;tes et d'int&eacute;grer des extensions d'acceptation de test.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Sc&eacute;nario de test en ligne de commande</td>
- <td>Permet de tester des outils ou scripts en ligne de commande et de manier des fichiers.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Compatibilit&eacute; avec PHP Documentor</td>
- <td>G&eacute;n&eacute;ration automatique et compl&egrave;te de la documentation au niveau des classes.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Interface navigateur</td>
- <td>Mise &agrave; nu des niveaux bas de l'interface du navigateur web pour des sc&eacute;narios de test plus pr&eacute;cis.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Authentification HTTP</td>
- <td>T&eacute;l&eacute;chargement des pages web prot&eacute;g&eacute;es avec une authentification basique seulement.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Boutons de navigation d'un navigateur</td>
- <td>Arri&egrave;re, avant et recommencer</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Support de SSL</td>
- <td>Peut se connecter &agrave; des pages de type https.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Support de proxy</td>
- <td>Peut se connecter via des proxys communs</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Support des cadres</td>
- <td>G&egrave;re les cadres dans les sc&eacute;narios de test web.</td>
- <td style="color: green;">Fini</td>
- </tr>
- <tr>
- <td>Am&eacute;lioration de l'affichage des tests</td>
- <td>Une meilleure interface graphique web, avec un arbre des sc&eacute;narios de test.</td>
- <td style="color: red;">1.1</td>
- </tr>
- <tr>
- <td>Localisation</td>
- <td>Abstraction des messages et g&eacute;nration du code &agrave; partir de fichiers XML.</td>
- <td style="color: red;">1.1</td>
- </tr>
- <tr>
- <td>Simulation d'interface</td>
- <td>Peut g&eacute;n&eacute;rer des objets fantaisie tant vers des interfaces que vers des classes.</td>
- <td style="color: red;">2.0</td>
- </tr>
- <tr>
- <td>Test sur es exceptions</td>
- <td>Dans le m&ecirc;me esprit que sur les tests des erreurs PHP.</td>
- <td style="color: red;">2.0</td>
- </tr>
- <tr>
- <td>Rercherche d'&eacute;l&eacute;ments avec XPath</td>
- <td>Peut utiliser Tidy HTML pour un appariement plus rapide et plus souple.</td>
- <td style="color: red;">2.0</td>
- </tr>
- <tr>
- <td>Test de l'upload de fichier</td>
- <td>Peut simuler la balise input de type file</td>
- <td style="color: red;">2.0</td>
- </tr>
- </tbody>
-</table>
- La migration vers PHP5 commencera juste apr&egrave;s la s&eacute;rie des 1.0, &agrave; partir de l&agrave; PHP4 ne sera plus support&eacute;. SimpleTest est actuellement compatible avec PHP5 mais n'utilisera aucune des nouvelles fonctionnalit&eacute;s avant la version 2.
- </p>
-
- <p>
-<a class="target" name="ressources">
-<h2>Ressources sur le web pour les tests</h2>
-</a>
-</p>
- <p>
- Le processus est au moins aussi important que les outils. Le type de proc&eacute;dure que fait un usage le plus intensif des outils de test pour d&eacute;veloppeur est bien s&ucirc;r l'<a href="http://www.extremeprogramming.org/">Extreme Programming</a>. Il s'agit l&agrave; d'une des <a href="http://www.agilealliance.com/articles/index">m&eacute;thodes agiles</a> qui combinent plusieurs pratiques pour "lisser la courbe de co&ucirc;t" du d&eacute;veloppement logiciel. La plus extr&egrave;me reste le <a href="http://www.testdriven.com/modules/news/">d&eacute;veloppement pilot&eacute; par les tests</a>, o&ugrave; vous devez adh&eacute;rer &agrave; la r&egrave;gle du <cite>pas de code avant d'avoir un test</cite>. Si vous &ecirc;tes plut&ocirc;t du genre planninficateur ou que vous estimez que l'exp&eacute;rience compte plus que l'&eacute;volution, vous pr&eacute;f&eacute;rerez peut-&ecirc;tre l'approche <a href="http://www.therationaledge.com/content/dec_01/f_spiritOfTheRUP_pk.html">RUP</a>. Je ne l'ai pas test&eacute; mais je peux voir o&ugrave; vous aurez besoin d'outils de test (cf. illustration 9).
- </p>
- <p>
- La plupart des testeurs unitaires sont dans une certaine mesure un clone de <a href="http://www.junit.org/">JUnit</a>, au moins dans l'interface. Il y a &eacute;norm&eacute;ment d'information sur le site de JUnit, &agrave; commencer par la <a href="http://junit.sourceforge.net/doc/faq/faq.htm">FAQ</a> quie contient pas mal de conseils g&eacute;n&eacute;raux sur les tests. Une fois mordu par le bogue vous appr&eacute;cierez s&ucirc;rement la phrase <a href="http://junit.sourceforge.net/doc/testinfected/testing.htm">infect&eacute; par les tests</a> trouv&eacute;e par Eric Gamma. Si vous &ecirc;tes encore en train de tergiverser sur un testeur unitaire, sachez que les choix principaux sont <a href="http://phpunit.sourceforge.net/">PHPUnit</a> et <a href="http://pear.php.net/manual/en/package.php.phpunit.php">Pear PHP::PHPUnit</a>. De nombreuses fonctionnalit&eacute;s de SimpleTest leurs font d&eacute;faut, mais la version PEAR a d'ores et d&eacute;j&agrave; &eacute;t&eacute; mise &agrave; jour pour PHP5. Elle est aussi recommand&eacute;e si vous portez des sc&eacute;narios de test existant depuis <a href="http://www.junit.org/">JUnit</a>.
- </p>
- <p>
- Les d&eacute;veloppeurs de biblioth&egrave;que n'ont pas l'air de livrer tr&egrave;s souvent des tests avec leur code : c'est bien dommage. Le code d'une biblioth&egrave;que qui inclut des tests peut &ecirc;tre remani&eacute; avec plus de s&eacute;curit&eacute; et le code de test sert de documentation additionnelle dans un format assez standard. Ceci peut &eacute;pargner la p&ecirc;che aux indices dans le code source lorsque qu'un probl&egrave;me survient, en particulier lors de la mise &agrave; jour d'une telle biblioth&egrave;que. Parmi les biblioth&egrave;ques utilisant SimpleTest comme testeur unitaire on retrouve <a href="http://wact.sourceforge.net/">WACT</a> et <a href="http://sourceforge.net/projects/htmlsax">PEAR::XML_HTMLSax</a>.
- </p>
- <p>
- Au jour d'aujourd'hui il manque tristement beaucoup de mati&egrave;re sur les objets fantaisie : dommage, surtout que tester unitairement sans eux repr&eacute;sente pas mal de travail en plus. L'<a href="http://www.sidewize.com/company/mockobjects.pdf">article original sur les objets fantaisie</a> est tr&egrave;s orient&eacute; Java, mais reste int&eacute;ressant &agrave; lire. Etant donn&eacute; qu'il s'agit d'une nouvelle technologie il y a beaucoup de discussions et de d&eacute;bats sur comment les utiliser, souvent sur des wikis comme <a href="http://xpdeveloper.com/cgi-bin/oldwiki.cgi?MockObjects">Extreme Tuesday</a> ou <a href="http://www.mockobjects.com/wiki/MocksObjectsPaper">www.mockobjects.com</a>ou <a href="http://c2.com/cgi/wiki?MockObject">the original C2 Wiki</a>. Injecter des objets fantaisie dans une classe est un des champs principaux du d&eacute;bat : cet <a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html">article chez IBM</a> en est un bon point de d&eacute;part.
- </p>
- <p>
- Il y a &eacute;normement d'outils de test web mais la plupart sont &eacute;crits en Java. De plus les tutoriels et autres conseils sont plut&ocirc;t rares. Votre seul espoir est de regarder directement la documentation pour <a href="http://httpunit.sourceforge.net/">HTTPUnit</a>, <a href="http://htmlunit.sourceforge.net/">HTMLUnit</a> ou <a href="http://jwebunit.sourceforge.net/">JWebUnit</a> et d'esp&eacute;rer y trouver pour des indices. Il y a aussi des frameworks bas&eacute;s sur XML, mais de nouveau la plupart ont besoin de Java pour tourner.
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/docs/fr/partial_mocks_documentation.html b/tests/test_tools/simpletest/docs/fr/partial_mocks_documentation.html
deleted file mode 100755
index 4098ab45..00000000
--- a/tests/test_tools/simpletest/docs/fr/partial_mocks_documentation.html
+++ /dev/null
@@ -1,333 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>Documentation SimpleTest : les objets fantaisie partiels</title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<a href="index.html">SimpleTest</a>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Documentation sur les objets fantaisie partiels</h1>
-<div class="content">
-
- <p>
- Un objet fantaisie partiel n'est ni plus ni moins qu'un mod&egrave;le de conception pour soulager un probl&egrave;me sp&eacute;cifique du test avec des objets fantaisie, celui de placer des objets fantaisie dans des coins serr&eacute;s. Il s'agit d'un outil assez limit&eacute; et peut-&ecirc;tre m&ecirc;me une id&eacute;e pas si bonne que &ccedil;a. Elle est incluse dans SimpleTest pour la simple raison que je l'ai trouv&eacute;e utile &agrave; plus d'une occasion et qu'elle m'a &eacute;pargn&eacute;e pas mal de travail dans ces moments-l&agrave;.
- </p>
-
- <p>
-<a class="target" name="injection">
-<h2>Le probl&egrave;me de l'injection dans un objet fantaisie</h2>
-</a>
-</p>
- <p>
- Quand un objet en utilise un autre il est tr&egrave;s simple d'y faire circuler une version fantaisie d&eacute;j&agrave; pr&ecirc;te avec ses attentes. Les choses deviennent un peu plus d&eacute;licates si un objet en cr&eacute;e un autre et que le cr&eacute;ateur est celui que l'on souhaite tester. Cela revient &agrave; dire que l'objet cr&eacute;&eacute; devrait &ecirc;tre une fantaisie, mais nous pouvons difficilement dire &agrave; notre classe sous test de cr&eacute;er un objet fantaisie plut&ocirc;t qu'un "vrai" objet. La classe test&eacute;e ne sait m&ecirc;me pas qu'elle travaille dans un environnement de test.
- </p>
- <p>
- Par exemple, supposons que nous sommes en train de construire un client telnet et qu'il a besoin de cr&eacute;er une socket r&eacute;seau pour envoyer ses messages. La m&eacute;thode de connexion pourrait ressemble &agrave; quelque chose comme...
-<pre>
-<strong>&lt;?php
- require_once('socket.php');
-
- class Telnet {
- ...
- function &amp;connect($ip, $port, $username, $password) {
- $socket = &amp;new Socket($ip, $port);
- $socket-&gt;read( ... );
- ...
- }
- }
-?&gt;</strong>
-</pre>
- Nous voudrions vraiment avoir une version fantaisie de l'objet socket, que pouvons nous faire ?
- </p>
- <p>
- La premi&egrave;re solution est de passer la socket en tant que param&egrave;tre, ce qui force la cr&eacute;ation au niveau inf&eacute;rieur. Charger le client de cette t&acirc;che est effectivement une bonne approche si c'est possible et devrait conduire &agrave; un remaniement -- de la cr&eacute;ation &agrave; partir de l'action. En fait, c'est l&agrave; une des mani&egrave;res avec lesquels tester en s'appuyant sur des objets fantaisie vous force &agrave; coder des solutions plus resserr&eacute;es sur leur objectif. Ils am&eacute;liorent votre programmation.
- </p>
- <p>
- Voici ce que &ccedil;a devrait &ecirc;tre...
-<pre>
-&lt;?php
- require_once('socket.php');
-
- class Telnet {
- ...
- <strong>function &amp;connect(&amp;$socket, $username, $password) {
- $socket-&gt;read( ... );
- ...
- }</strong>
- }
-?&gt;
-</pre>
- Sous-entendu, votre code de test est typique d'un cas de test avec un objet fantaisie.
-<pre>
-class TelnetTest extends UnitTestCase {
- ...
- function testConnection() {<strong>
- $socket = &amp;new MockSocket($this);
- ...
- $telnet = &amp;new Telnet();
- $telnet-&gt;connect($socket, 'Me', 'Secret');
- ...</strong>
- }
-}
-</pre>
- C'est assez &eacute;vident que vous ne pouvez descendre que d'un niveau. Vous ne voudriez pas que votre application de haut niveau cr&eacute;e tous les fichiers de bas niveau, sockets et autres connexions &agrave; la base de donn&eacute;es dont elle aurait besoin. Elle ne conna&icirc;trait pas les param&egrave;tres du constructeur de toute fa&ccedil;on.
- </p>
- <p>
- La solution suivante est de passer l'objet cr&eacute;&eacute; sous la forme d'un param&egrave;tre optionnel...
-<pre>
-&lt;?php
- require_once('socket.php');
-
- class Telnet {
- ...<strong>
- function &amp;connect($ip, $port, $username, $password, $socket = false) {
- if (!$socket) {
- $socket = &amp;new Socket($ip, $port);
- }
- $socket-&gt;read( ... );</strong>
- ...
- return $socket;
- }
- }
-?&gt;
-</pre>
- Pour une solution rapide, c'est g&eacute;n&eacute;ralement suffisant. Ensuite le test est tr&egrave;s similaire : comme si le param&egrave;tre &eacute;tait transmis formellement...
-<pre>
-class TelnetTest extends UnitTestCase {
- ...
- function testConnection() {<strong>
- $socket = &amp;new MockSocket($this);
- ...
- $telnet = &amp;new Telnet();
- $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret', &amp;$socket);
- ...</strong>
- }
-}
-</pre>
- Le probl&egrave;me de cette approche tient dans son manque de nettet&eacute;. Il y a du code de test dans la classe principale et aussi des param&egrave;tres transmis dans le sc&eacute;nario de test qui ne sont jamais utilis&eacute;s. Il s'agit l&agrave; d'une approche rapide et sale, mais qui ne reste pas moins efficace dans la plupart des situations.
- </p>
- <p>
- Une autre solution encore est de laisser un objet fabrique s'occuper de la cr&eacute;ation...
-<pre>
-&lt;?php
- require_once('socket.php');
-
- class Telnet {<strong>
- function Telnet(&amp;$network) {
- $this-&gt;_network = &amp;$network;
- }</strong>
- ...
- function &amp;connect($ip, $port, $username, $password) {<strong>
- $socket = &amp;$this-&gt;_network-&gt;createSocket($ip, $port);
- $socket-&gt;read( ... );</strong>
- ...
- return $socket;
- }
- }
-?&gt;
-</pre>
- Il s'agit l&agrave; probablement de la r&eacute;ponse la plus travaill&eacute;e &eacute;tant donn&eacute; que la cr&eacute;ation est maintenant situ&eacute;e dans une petite classe sp&eacute;cialis&eacute;e. La fabrique r&eacute;seau peut &ecirc;tre test&eacute;e s&eacute;par&eacute;ment et utilis&eacute;e en tant que fantaisie quand nous testons la classe telnet...
-<pre>
-class TelnetTest extends UnitTestCase {
- ...
- function testConnection() {<strong>
- $socket = &amp;new MockSocket($this);
- ...
- $network = &amp;new MockNetwork($this);
- $network-&gt;setReturnReference('createSocket', $socket);
- $telnet = &amp;new Telnet($network);
- $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');
- ...</strong>
- }
-}
-</pre>
- Le probl&egrave;me reste que nous ajoutons beaucoup de classes &agrave; la biblioth&egrave;que. Et aussi que nous utilisons beaucoup de fabriques ce qui rend notre code un peu moins intuitif. La solution la plus flexible, mais aussi la plus complexe.
- </p>
- <p>
- Peut-on trouver un juste milieu ?
- </p>
-
- <p>
-<a class="target" name="creation">
-<h2>M&eacute;thode fabrique prot&eacute;g&eacute;e</h2>
-</a>
-</p>
- <p>
- Il existe une technique pour palier &agrave; ce probl&egrave;me sans cr&eacute;er de nouvelle classe dans l'application; par contre elle induit la cr&eacute;ation d'une sous-classe au moment du test. Premi&egrave;rement nous d&eacute;pla&ccedil;ons la cr&eacute;ation de la socket dans sa propre m&eacute;thode...
-<pre>
-&lt;?php
- require_once('socket.php');
-
- class Telnet {
- ...
- function &amp;connect($ip, $port, $username, $password) {<strong>
- $socket = &amp;$this-&gt;_createSocket($ip, $port);</strong>
- $socket-&gt;read( ... );
- ...
- }<strong>
-
- function &amp;_createSocket($ip, $port) {
- return new Socket($ip, $port);
- }</strong>
- }
-?&gt;
-</pre>
- Il s'agit l&agrave; de la seule modification dans le code de l'application.
- </p>
- <p>
- Pour le sc&eacute;nario de test, nous devons cr&eacute;er une sous-classe de mani&egrave;re &agrave; intercepter la cr&eacute;ation de la socket...
-<pre>
-<strong>class TelnetTestVersion extends Telnet {
- var $_mock;
-
- function TelnetTestVersion(&amp;$mock) {
- $this-&gt;_mock = &amp;$mock;
- $this-&gt;Telnet();
- }
-
- function &amp;_createSocket() {
- return $this-&gt;_mock;
- }
-}</strong>
-</pre>
- Ici j'ai d&eacute;plac&eacute; la fantaisie dans le constructeur, mais un setter aurait fonctionn&eacute; tout aussi bien. Notez bien que la fantaisie est plac&eacute;e dans une variable d'objet avant que le constructeur ne soit attach&eacute;. C'est n&eacute;cessaire dans le cas o&ugrave; le constructeur appelle <span class="new_code">connect()</span>. Autrement il pourrait donner un valeur nulle &agrave; partir de <span class="new_code">_createSocket()</span>.
- </p>
- <p>
- Apr&egrave;s la r&eacute;alisation de tout ce travail suppl&eacute;mentaire le sc&eacute;nario de test est assez simple. Nous avons juste besoin de tester notre nouvelle classe &agrave; la place...
-<pre>
-class TelnetTest extends UnitTestCase {
- ...
- function testConnection() {<strong>
- $socket = &amp;new MockSocket($this);
- ...
- $telnet = &amp;new TelnetTestVersion($socket);
- $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');
- ...</strong>
- }
-}
-</pre>
- Cette nouvelle classe est tr&egrave;s simple bien s&ucirc;r. Elle ne fait qu'initier une valeur renvoy&eacute;e, &agrave; la mani&egrave;re d'une fantaisie. Ce serait pas mal non plus si elle pouvait v&eacute;rifier les param&egrave;tres entrants. Exactement comme un objet fantaisie. Il se pourrait bien que nous ayons &agrave; r&eacute;aliser cette astuce r&eacute;guli&egrave;rement : serait-il possible d'automatiser la cr&eacute;ation de cette sous-classe ?
- </p>
-
- <p>
-<a class="target" name="partiel">
-<h2>Un objet fantaisie partiel</h2>
-</a>
-</p>
- <p>
- Bien s&ucirc;r la r&eacute;ponse est "oui" ou alors j'aurais arr&ecirc;t&eacute; d'&eacute;crire depuis quelques temps d&eacute;j&agrave; ! Le test pr&eacute;c&eacute;dent a repr&eacute;sent&eacute; beaucoup de travail, mais nous pouvons g&eacute;n&eacute;rer la sous-classe en utilisant une approche &agrave; celle des objets fantaisie.
- </p>
- <p>
- Voici donc une version avec objet fantaisie partiel du test...
-<pre>
-<strong>Mock::generatePartial(
- 'Telnet',
- 'TelnetTestVersion',
- array('_createSocket'));</strong>
-
-class TelnetTest extends UnitTestCase {
- ...
- function testConnection() {<strong>
- $socket = &amp;new MockSocket($this);
- ...
- $telnet = &amp;new TelnetTestVersion($this);
- $telnet-&gt;setReturnReference('_createSocket', $socket);
- $telnet-&gt;Telnet();
- $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');
- ...</strong>
- }
-}
-</pre>
- La fantaisie partielle est une sous-classe de l'original dont on aurait "remplac&eacute;" les m&eacute;thodes s&eacute;lectionn&eacute;es avec des versions de test. L'appel &agrave; <span class="new_code">generatePartial()</span> n&eacute;cessite trois param&egrave;tres : la classe &agrave; sous classer, le nom de la nouvelle classe et une liste des m&eacute;thodes &agrave; simuler.
- </p>
- <p>
- Instancier les objets qui en r&eacute;sultent est plut&ocirc;t d&eacute;licat. L'unique param&egrave;tre du constructeur d'un objet fantaisie partiel est la r&eacute;f&eacute;rence du testeur unitaire. Comme avec les objets fantaisie classiques c'est n&eacute;cessaire pour l'envoi des r&eacute;sultats de test en r&eacute;ponse &agrave; la v&eacute;rification des attentes.
- </p>
- <p>
- Une nouvelle fois le constructeur original n'est pas lanc&eacute;. Indispensable dans le cas o&ugrave; le constructeur aurait besoin des m&eacute;thodes fantaisie : elles n'ont pas encore &eacute;t&eacute; initi&eacute;es ! Nous initions les valeurs retourn&eacute;es &agrave; cet instant et ensuite lan&ccedil;ons le constructeur avec ses param&egrave;tres normaux. Cette construction en trois &eacute;tapes de "new", suivie par la mise en place des m&eacute;thodes et ensuite par la lancement du constructeur proprement dit est ce qui distingue le code d'un objet fantaisie partiel.
- </p>
- <p>
- A part pour leur construction, toutes ces m&eacute;thodes fantaisie ont les m&ecirc;mes fonctionnalit&eacute;s que dans le cas des objets fantaisie et toutes les m&eacute;thodes non fantaisie se comportent comme avant. Nous pouvons mettre en place des attentes tr&egrave;s facilement...
-<pre>
-class TelnetTest extends UnitTestCase {
- ...
- function testConnection() {
- $socket = &amp;new MockSocket($this);
- ...
- $telnet = &amp;new TelnetTestVersion($this);
- $telnet-&gt;setReturnReference('_createSocket', $socket);<strong>
- $telnet-&gt;expectOnce('_createSocket', array('127.0.0.1', 21));</strong>
- $telnet-&gt;Telnet();
- $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');
- ...<strong>
- $telnet-&gt;tally();</strong>
- }
-}
-</pre>
- </p>
-
- <p>
-<a class="target" name="moins">
-<h2>Tester moins qu'une classe</h2>
-</a>
-</p>
- <p>
- Les m&eacute;thodes issues d'un objet fantaisie n'ont pas besoin d'&ecirc;tre des m&eacute;thodes fabrique, Il peut s'agir de n'importe quelle sorte de m&eacute;thode. Ainsi les objets fantaisie partiels nous permettent de prendre le contr&ocirc;le de n'importe quelle partie d'une classe, le constructeur except&eacute;. Nous pourrions m&ecirc;me aller jusqu'&agrave; cr&eacute;er des fantaisies sur toutes les m&eacute;thode &agrave; part celle que nous voulons effectivement tester.
- </p>
- <p>
- Cette situation est assez hypoth&eacute;tique, &eacute;tant donn&eacute; que je ne l'ai jamais essay&eacute;e. Je suis ouvert &agrave; cette possibilit&eacute;, mais je crains qu'en for&ccedil;ant la granularit&eacute; d'un objet on n'obtienne pas forc&eacute;ment un code de meilleur qualit&eacute;. Personnellement j'utilise les objets fantaisie partiels comme moyen de passer outre la cr&eacute;ation ou alors de temps en temps pour tester le mod&egrave;le de conception TemplateMethod.
- </p>
- <p>
- Pour choisir le m&eacute;canisme &agrave; utiliser, on en revient toujours aux standards de code de votre projet.
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/docs/fr/reporter_documentation.html b/tests/test_tools/simpletest/docs/fr/reporter_documentation.html
deleted file mode 100755
index 4f927781..00000000
--- a/tests/test_tools/simpletest/docs/fr/reporter_documentation.html
+++ /dev/null
@@ -1,386 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>Documentation SimpleTest : le rapporteur de test</title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<a href="index.html">SimpleTest</a>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Documentation sur le rapporteur de test</h1>
-<div class="content">
-
- <p>
- SimpleTest suit plut&ocirc;t plus que moins le mod&egrave;le MVC (Mod&egrave;le-Vue-Contr&ocirc;leur). Les classes "reporter" sont les vues et les mod&egrave;les sont vos sc&eacute;narios de test et leur hi&eacute;rarchie. Le contr&ocirc;leur est le plus souvent masqu&eacute; &agrave; l'utilisateur de SimpleTest &agrave; moins de vouloir changer la fa&ccedil;on dont les tests sont effectivement ex&eacute;cut&eacute;s, auquel cas il est possible de surcharger les objets "runner" (ceux de l'ex&eacute;cuteur) depuis l'int&eacute;rieur d'un sc&eacute;nario de test. Comme d'habitude avec MVC, le contr&ocirc;leur est plut&ocirc;t ind&eacute;fini et il existe d'autres endroits pour contr&ocirc;ler l'ex&eacute;cution des tests.
- </p>
-
- <p>
-<a class="target" name="html">
-<h2>Les r&eacute;sultats rapport&eacute;s au format HTML</h2>
-</a>
-</p>
- <p>
- L'affichage par d&eacute;faut est minimal &agrave; l'extr&ecirc;me. Il renvoie le succ&egrave;s ou l'&eacute;chec avec les barres conventionnelles - rouge et verte - et affichent une trace d'arborescence des groupes de test pour chaque assertion erron&eacute;e. Voici un tel &eacute;chec...
- <div class="demo">
- <h1>File test</h1>
- <span class="fail">Fail</span>: createnewfile-&gt;True assertion failed.<br>
- <div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
- <strong>0</strong> passes, <strong>1</strong> fails and <strong>0</strong> exceptions.</div>
- </div>
- Alors qu'ici tous les tests passent...
- <div class="demo">
- <h1>File test</h1>
- <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
- <strong>1</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
- </div>
- La bonne nouvelle, c'est qu'il existe pas mal de points dans la hi&eacute;rarchie de l'affichage pour cr&eacute;er des sous-classes.
- </p>
- <p>
- Pour l'affichage bas&eacute; sur des pages web, il y a la classe <span class="new_code">HtmlReporter</span> avec la signature suivante...
-<pre>
-class HtmlReporter extends SimpleReporter {
- public 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() { ... }
-}
-</pre>
- Voici ce que certaines de ces m&eacute;thodes veulent dire. Premi&egrave;rement les m&eacute;thodes d'affichage que vous voudrez probablement surcharger...
- <ul class="api">
- <li>
- <span class="new_code">HtmlReporter(string $encoding)</span>
-<br>
- est le constructeur. Notez que le test unitaire initie le lien &agrave; l'affichage plut&ocirc;t que l'oppos&eacute;. L'affichage est principalement un receveur passif des &eacute;v&egrave;nements de tests. Cela permet d'adapter facilement l'affichage pour d'autres syst&egrave;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&eacute;bogage quand on utilise le testeur web, il doit correspondre &agrave; l'encodage du site test&eacute;. Les cha&icirc;nes de caract&egrave;res disponibles sont indiqu&eacute;es dans la fonction PHP <a href="http://www.php.net/manual/fr/function.htmlentities.php">html_entities()</a>.
- </li>
- <li>
- <span class="new_code">void paintHeader(string $test_name)</span>
-<br>
- est appel&eacute; une fois, au d&eacute;but du test quand l'&eacute;v&egrave;nement de d&eacute;marrage survient. Le premier &eacute;v&egrave;nement de d&eacute;marrage est souvent d&eacute;livr&eacute; par le groupe de test du niveau le plus haut et donc c'est de l&agrave; que le <span class="new_code">$test_name</span> arrive. Il peint les titres de la page, CSS, la balise "body", etc. Il ne renvoie rien du tout (<span class="new_code">void</span>).
- </li>
- <li>
- <span class="new_code">void paintFooter(string $test_name)</span>
-<br>
- est appel&eacute; &agrave; la toute fin du test pour fermer les balises ouvertes par l'ent&ecirc;te de la page. Par d&eacute;faut il affiche aussi la barre rouge ou verte et le d&eacute;compte final des r&eacute;sultats. En fait la fin des tests arrive quand l'&eacute;v&egrave;nement de fin de test arrive avec le m&ecirc;me nom que celui qui l'a initi&eacute; au m&ecirc;me niveau. Le nid des tests en quelque sorte. Fermer le dernier test finit l'affichage.
- </li>
- <li>
- <span class="new_code">void paintMethodStart(string $test_name)</span>
-<br>
- est appel&eacute; au d&eacute;but de chaque m&eacute;thode de test. Normalement le nom vient de celui de la m&eacute;thode. Les autres &eacute;v&egrave;nements de d&eacute;part de test se comportent de la m&ecirc;me mani&egrave;re sauf que celui du groupe de test indique au rapporteur le nombre de sc&eacute;narios de test qu'il contient. De la sorte le rapporteur peut afficher une barre de progr&egrave;s au fur et &agrave; mesure que l'ex&eacute;cuteur passe en revue les sc&eacute;narios de test.
- </li>
- <li>
- <span class="new_code">void paintMethodEnd(string $test_name)</span>
-<br>
- cl&ocirc;t le test lanc&eacute; avec le m&ecirc;me nom.
- </li>
- <li>
- <span class="new_code">void paintFail(string $message)</span>
-<br>
- peint un &eacute;chec. Par d&eacute;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.
- </li>
- <li>
- <span class="new_code">void paintPass(string $message)</span>
-<br>
- ne fait rien, par d&eacute;faut.
- </li>
- <li>
- <span class="new_code">string _getCss()</span>
-<br>
- renvoie les styles CSS sous la forme d'une cha&icirc;ne &agrave; l'attention de la m&eacute;thode d'ent&ecirc;tes d'une page. Des styles additionnels peuvent &ecirc;tre ajout&eacute;s ici si vous ne surchargez pas les ent&ecirc;tes de la page. Vous ne voudrez pas utiliser cette m&eacute;thode dans des ent&ecirc;tes d'une page surcharg&eacute;e si vous souhaitez inclure le feuille de style CSS d'origine.
- </li>
- </ul>
- Il y a aussi des accesseurs pour aller chercher l'information sur l'&eacute;tat courant de la suite de test. Vous les utiliserez pour enrichir l'affichage...
- <ul class="api">
- <li>
- <span class="new_code">array getTestList()</span>
-<br>
- est la premi&egrave;re m&eacute;thode tr&egrave;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&eacute;thode de test en cours sera la derni&egrave;re.
- </li>
- <li>
- <span class="new_code">integer getPassCount()</span>
-<br>
- renvoie le nombre de succ&egrave;s atteint. Il est n&eacute;cessaire pour l'affichage &agrave; la fin.
- </li>
- <li>
- <span class="new_code">integer getFailCount()</span>
-<br>
- renvoie de la m&ecirc;me mani&egrave;re le nombre d'&eacute;checs.
- </li>
- <li>
- <span class="new_code">integer getExceptionCount()</span>
-<br>
- renvoie quant &agrave; lui le nombre d'erreurs.
- </li>
- <li>
- <span class="new_code">integer getTestCaseCount()</span>
-<br>
- est le nombre total de sc&eacute;narios lors de l'ex&eacute;cution des tests. Il comprend aussi les tests group&eacute;s.
- </li>
- <li>
- <span class="new_code">integer getTestCaseProgress()</span>
-<br>
- est le nombre de sc&eacute;narios r&eacute;alis&eacute;s jusqu'&agrave; pr&eacute;sent.
- </li>
- </ul>
- Une modification simple : demander &agrave; l'HtmlReporter d'afficher aussi bien les succ&egrave;s que les &eacute;checs et les erreurs...
-<pre>
-<strong>class ShowPasses extends HtmlReporter {
-
- function paintPass($message) {
- parent::paintPass($message);
- print "&amp;&lt;span class=\"pass\"&gt;Pass&lt;/span&gt;: ";
- $breadcrumb = $this-&gt;getTestList();
- array_shift($breadcrumb);
- print implode("-&amp;gt;", $breadcrumb);
- print "-&amp;gt;$message&lt;br /&gt;\n";
- }
-
- function _getCss() {
- return parent::_getCss() . ' .pass { color: green; }';
- }
-}</strong>
-</pre>
- </p>
- <p>
- Une m&eacute;thode qui a beaucoup fait jaser reste la m&eacute;thode <span class="new_code">makeDry()</span>. Si vous lancez cette m&eacute;thode, sans param&egrave;tre, sur le rapporteur avant que la suite de test ne soit ex&eacute;cut&eacute;e alors aucune m&eacute;thode de test ne sera appel&eacute;e. Vous continuerez &agrave; avoir les &eacute;v&egrave;nements entrants et sortants des m&eacute;thodes et sc&eacute;narios de test, mais aucun succ&egrave;s ni &eacute;chec ou erreur, parce que le code de test ne sera pas ex&eacute;cut&eacute;.
- </p>
- <p>
- La raison ? Pour permettre un affichage complexe d'une IHM (ou GUI) qui permettrait la s&eacute;lection de sc&eacute;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&eacute; sur une ex&eacute;cution s&egrave;che qui ne renverrait que les &eacute;v&egrave;nements d'affichage, cela devient facilement r&eacute;alisable.
- </p>
-
- <p>
-<a class="target" name="autre">
-<h2>Etendre le rapporteur</h2>
-</a>
-</p>
- <p>
- Plut&ocirc;t que de modifier l'affichage existant, vous voudrez peut-&ecirc;tre produire une pr&eacute;sentation HTML compl&egrave;tement diff&eacute;rente, ou m&ecirc;me g&eacute;n&eacute;rer une version texte ou XML. Plut&ocirc;t que de surcharger chaque m&eacute;thode dans <span class="new_code">HtmlReporter</span> nous pouvons nous rendre une &eacute;tape plus haut dans la hi&eacute;rarchie de classe vers <span class="new_code">SimpleReporter</span> dans le fichier source <em>simple_test.php</em>.
- </p>
- <p>
- Un affichage sans rien, un canvas vierge pour votre propre cr&eacute;ation, serait...
-<pre>
-<strong>require_once('simpletest/simple_test.php');</strong>
-
-class MyDisplay extends SimpleReporter {<strong>
- </strong>
- function paintHeader($test_name) {
- }
-
- function paintFooter($test_name) {
- }
-
- function paintStart($test_name, $size) {<strong>
- parent::paintStart($test_name, $size);</strong>
- }
-
- function paintEnd($test_name, $size) {<strong>
- parent::paintEnd($test_name, $size);</strong>
- }
-
- function paintPass($message) {<strong>
- parent::paintPass($message);</strong>
- }
-
- function paintFail($message) {<strong>
- parent::paintFail($message);</strong>
- }
-}
-</pre>
- Aucune sortie ne viendrait de cette classe jusqu'&agrave; un ajout de votre part.
- </p>
-
- <p>
-<a class="target" name="cli">
-<h2>Le rapporteur en ligne de commande</h2>
-</a>
-</p>
- <p>
- SimpleTest est aussi livr&eacute; 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 &agrave; mesure de leur arriv&eacute;e. Pour utiliser le rapporteur en ligne de commande, il suffit de l'intervertir avec celui de la version HTML...
-<pre>
-&lt;?php
- require_once('simpletest/unit_tester.php');
- require_once('simpletest/reporter.php');
-
- $test = &amp;new GroupTest('File test');
- $test-&gt;addTestFile('tests/file_test.php');
- $test-&gt;run(<strong>new TextReporter()</strong>);
-?&gt;
-</pre>
- Et ensuite d'invoquer la suite de test &agrave; partir d'une ligne de commande...
-<pre class="shell">
-php file_test.php
-</pre>
- Bien s&ucirc;r vous aurez besoin d'installer PHP en ligne de commande. Une suite de test qui passerait toutes ses assertions ressemble &agrave;...
-<pre class="shell">
-File test
-OK
-Test cases run: 1/1, Failures: 0, Exceptions: 0
-</pre>
- Un &eacute;chec d&eacute;clenche un affichage comme...
-<pre class="shell">
-File test
-1) True assertion failed.
- in createnewfile
-FAILURES!!!
-Test cases run: 1/1, Failures: 1, Exceptions: 0
-</pre>
- </p>
- <p>
- Une des principales raisons pour utiliser une suite de test en ligne de commande tient dans l'utilisation possible du testeur avec un processus automatis&eacute;. Pour fonctionner comme il faut dans des scripts shell le script de test devrait renvoyer un code de sortie non-nul suite &agrave; un &eacute;chec. Si une suite de test &eacute;choue la valeur <span class="new_code">false</span> est renvoy&eacute;e par la m&eacute;thode <span class="new_code">SimpleTest::run()</span>. Nous pouvons utiliser ce r&eacute;sultat pour terminer le script avec la bonne valeur renvoy&eacute;e...
-<pre>
-&lt;?php
- require_once('simpletest/unit_tester.php');
- require_once('simpletest/reporter.php');
-
- $test = &amp;new GroupTest('File test');
- $test-&gt;addTestFile('tests/file_test.php');
- <strong>exit ($test-&gt;run(new TextReporter()) ? 0 : 1);</strong>
-?&gt;
-</pre>
- Bien s&ucirc;r l'objectif n'est pas de cr&eacute;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&eacute;thode pour d&eacute;terminer l'environnement d'ex&eacute;cution...
-<pre>
-&lt;?php
- require_once('simpletest/unit_tester.php');
- require_once('simpletest/reporter.php');
-
- $test = &amp;new GroupTest('File test');
- $test-&gt;addTestFile('tests/file_test.php');
- <strong>if (TextReporter::inCli()) {</strong>
- exit ($test-&gt;run(new TextReporter()) ? 0 : 1);
- <strong>}</strong>
- $test-&gt;run(new HtmlReporter());
-?&gt;
-</pre>
- Il s'agit l&agrave; de la forme utilis&eacute;e par SimpleTest lui-m&ecirc;me.
- </p>
-
- <p>
-<a class="target" name="xml">
-<h2>Test distant</h2>
-</a>
-</p>
- <p>
- SimpleTest est livr&eacute; avec une classe <span class="new_code">XmlReporter</span> utilis&eacute;e pour de la communication interne. Lors de son ex&eacute;cution, le r&eacute;sultat ressemble &agrave;...
-<pre class="shell">
-&lt;?xml version="1.0"?&gt;
-&lt;run&gt;
- &lt;group size="4"&gt;
- &lt;name&gt;Remote tests&lt;/name&gt;
- &lt;group size="4"&gt;
- &lt;name&gt;Visual test with 48 passes, 48 fails and 4 exceptions&lt;/name&gt;
- &lt;case&gt;
- &lt;name&gt;testofunittestcaseoutput&lt;/name&gt;
- &lt;test&gt;
- &lt;name&gt;testofresults&lt;/name&gt;
- &lt;pass&gt;This assertion passed&lt;/pass&gt;
- &lt;fail&gt;This assertion failed&lt;/fail&gt;
- &lt;/test&gt;
- &lt;test&gt;
- ...
- &lt;/test&gt;
- &lt;/case&gt;
- &lt;/group&gt;
- &lt;/group&gt;
-&lt;/run&gt;
-</pre>
- Vous pouvez utiliser ce format avec le parseur fourni dans SimpleTest lui-m&ecirc;me. Il s'agit de <span class="new_code">SimpleTestXmlParser</span> et se trouve <em>xml.php</em> &agrave; l'int&eacute;rieur du paquet SimpleTest...
-<pre>
-&lt;?php
- require_once('simpletest/xml.php');
-
- ...
- $parser = &amp;new SimpleTestXmlParser(new HtmlReporter());
- $parser-&gt;parse($test_output);
-?&gt;
-</pre>
- <span class="new_code">$test_output</span> devrait &ecirc;tre au format XML, &agrave; partir du rapporteur XML, et pourrait venir d'une ex&eacute;cution en ligne de commande d'un sc&eacute;nario de test. Le parseur envoie des &eacute;v&egrave;nements au rapporteur exactement comme tout autre ex&eacute;cution de test. Il y a des occasions bizarres dans lesquelles c'est en fait tr&egrave;s utile.
- </p>
- <p>
- Un probl&egrave;me des suites de test tr&egrave;s grandes, c'est qu'elles peuvent venir &agrave; bout de la limite de m&eacute;moire par d&eacute;faut d'un process PHP - 8Mb. En pla&ccedil;ant la sortie des groupes de test dans du XML et leur ex&eacute;cution dans des process diff&eacute;rents, le r&eacute;sultat peut &ecirc;tre parser &agrave; nouveau pour agr&eacute;grer les r&eacute;sultats avec moins d'impact sur le test au premier niveau.
- </p>
- <p>
- Parce que la sortie XML peut venir de n'importe o&ugrave;, &ccedil;a ouvre des possibilit&eacute;s d'agr&eacute;gation d'ex&eacute;cutions de test depuis des serveur distants. Un sc&eacute;nario de test pour le r&eacute;aliser existe d&eacute;j&agrave; &agrave; l'int&eacute;rieur du framework SimpleTest, mais il est encore exp&eacute;rimental...
-<pre>
-&lt;?php
- <strong>require_once('../remote.php');</strong>
- require_once('../reporter.php');
-
- $test_url = ...;
- $dry_url = ...;
-
- $test = &amp;new GroupTest('Remote tests');
- $test-&gt;addTestCase(<strong>new RemoteTestCase($test_url, $dry_url)</strong>);
- $test-&gt;run(new HtmlReporter());
-?&gt;
-</pre>
- <span class="new_code">RemoteTestCase</span> prend la localisation r&eacute;elle du lanceur de test, tout simplement un page web au format XML. Il prend aussi l'URL d'un rapporteur initi&eacute; pour effectuer une ex&eacute;cution s&egrave;che. Cette technique est employ&eacute;e pour que les progr&egrave;s soient correctement rapport&eacute;s vers le haut. <span class="new_code">RemoteTestCase</span> peut &ecirc;tre ajout&eacute; &agrave; une suite de test comme n'importe quel autre groupe de test.
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/docs/fr/server_stubs_documentation.html b/tests/test_tools/simpletest/docs/fr/server_stubs_documentation.html
deleted file mode 100755
index 59085795..00000000
--- a/tests/test_tools/simpletest/docs/fr/server_stubs_documentation.html
+++ /dev/null
@@ -1,279 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>Documentation SimpleTest : les bouchons serveur</title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<a href="index.html">SimpleTest</a>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Documentation sur les bouchons serveur</h1>
-<div class="content">
- <p>
-<a class="target" name="quoi">
-<h2>Que sont les bouchons serveur ?</h2>
-</a>
-</p>
- <p>
- Au d&eacute;part il s'agit d'un mod&egrave;le de conception initi&eacute; 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&egrave;me pour des raisons de testabilit&eacute; ou de prototypage, tout en restant l&eacute;ger. Il permet aux tests de tourner plus rapidement ou alors, si la classe simul&eacute;e n'a pas &eacute;t&eacute; &eacute;crite, juste de fonctionner.
- </p>
-
- <p>
-<a class="target" name="creation">
-<h2>Cr&eacute;er des bouchons serveur</h2>
-</a>
-</p>
- <p>
- Nous avons juste besoin d'une classe pr&eacute;existante, par exemple une connexion vers une base de donn&eacute;es qui ressemblerait &agrave;...
-<pre>
-<strong>class DatabaseConnection {
- function DatabaseConnection() {
- }
-
- function query() {
- }
-
- function selectQuery() {
- }
-}</strong>
-</pre>
- La classe n'a m&ecirc;me pas encore besoin d'avoir &eacute;t&eacute; impl&eacute;ment&eacute;e. Pour cr&eacute;er la version bouchonn&eacute;e de cette classe, nous incluons la librairie de bouchon serveur et ex&eacute;cutons le g&eacute;n&eacute;rateur...
-<pre>
-<strong>require_once('simpletest/mock_objects.php');
-require_once('database_connection.php');
-Stub::generate('DatabaseConnection');</strong>
-</pre>
- Est g&eacute;n&eacute;r&eacute; un clone de la classe appel&eacute; <span class="new_code">StubDatabaseConnection</span>. Nous pouvons alors cr&eacute;er des instances de cette nouvelle classe &agrave; l'int&eacute;rieur de notre prototype de script...
-<pre>
-require_once('simpletest/mock_objects.php');
-require_once('database_connection.php');
-Stub::generate('DatabaseConnection');
-<strong>
-$connection = new StubDatabaseConnection();
-</strong>
-</pre>
- La version bouchonn&eacute;e de la classe contient toutes les m&eacute;thodes de l'original de telle sorte qu'une op&eacute;ration comme <span class="new_code">$connection-&gt;query()</span> soit encore l&eacute;gale. La valeur retourn&eacute;e sera <span class="new_code">null</span>, Mais nous pouvons y rem&eacute;dier avec...
-<pre>
-<strong>$connection-&gt;setReturnValue('query', 37)</strong>
-</pre>
- D&eacute;sormais &agrave; chaque appel de <span class="new_code">$connection-&gt;query()</span> nous obtenons un r&eacute;sultat de 37. Nous pouvons choisir n'importe quelle valeur pour le r&eacute;sultat, par exemple un hash de r&eacute;sultats provenant d'un base de donn&eacute;es imaginaire ou alors une liste d'objets persistants. Peu importe les param&egrave;tres, nous obtenons syst&eacute;matiquement les m&ecirc;me valeurs chaque fois qu'ils ont &eacute;t&eacute; initialis&eacute;s de la sorte : &ccedil;a ne ressemble peut-&ecirc;tre pas &agrave; une r&eacute;ponse convaincante venant d'une connexion vers une base de donn&eacute;es. Mais pour la demi-douzaine de lignes d'une m&eacute;thode de test c'est souvent largement suffisant.
- </p>
-
- <p>
-<a class="target" name="mod%C3%A8les">
-<h2>Mod&egrave;les de simulation</h2>
-</a>
-</p>
- <p>
- Sauf que les choses ne sont que rarement aussi simples. Parmi les probl&egrave;mes les plus courants on trouve les it&eacute;rateurs : le renvoi d'une valeur constante peut causer une boucle infini dans l'objet test&eacute;. Pour ceux-ci nous avons besoin de mettre sur pied une suite de valeurs. Prenons par exemple un it&eacute;rateur simple qui ressemble &agrave;...
-<pre>
-class Iterator {
- function Iterator() {
- }
-
- function next() {
- }
-}
-</pre>
- C'est probablement le plus simple des it&eacute;rateurs possibles. Supposons que cet it&eacute;rateur ne retourne que du texte, jusqu'&agrave; la fin - quand il retourne <span class="new_code">false</span>. Une simulation est possible avec...
-<pre>
-<strong>Stub::generate('Iterator');
-
-$iterator = new StubIterator();
-$iterator-&gt;setReturnValue('next', false);
-$iterator-&gt;setReturnValueAt(0, 'next', 'First string');
-$iterator-&gt;setReturnValueAt(1, 'next', 'Second string');</strong>
-</pre>
- A l'appel de <span class="new_code">next()</span> sur l'it&eacute;rateur bouchonn&eacute; il va d'abord renvoyer "First string", puis au second appel c'est "Second string" qui sera renvoy&eacute;. Finalement pour tous les autres appels, il s'agira d'un <span class="new_code">false</span>. Les valeurs renvoy&eacute;es successivement ont priorit&eacute; sur la valeur constante renvoy&eacute;. Cette derni&egrave;re est un genre de valeur par d&eacute;faut.
- </p>
- <p>
- Une autre situation d&eacute;licate est une op&eacute;ration <span class="new_code">get()</span> surcharg&eacute;e. Un exemple ? Un porteur d'information avec des pairs de clef / valeur. Prenons une classe de configuration...
-<pre>
-class Configuration {
- function Configuration() {
- }
-
- function getValue($key) {
- }
-}
-</pre>
- Il s'agit d'une situation propice &agrave; l'utilisation d'objets bouchon, surtout que la configuration en production d&eacute;pend invariablement de la machine : l'utiliser directement ne va pas nous aider &agrave; maintenir notre confiance dans nos tests. Sauf que le probl&egrave;me tient de ce que toutes les donn&eacute;es proviennent de la m&eacute;thode <span class="new_code">getValue()</span> et que nous voulons des r&eacute;sultats diff&eacute;rents suivant la clef. Par chance les bouchons ont un syst&egrave;me de filtre...
-<pre>
-<strong>Stub::generate('Configuration');
-
-$config = &amp;new StubConfiguration();
-$config-&gt;setReturnValue('getValue', 'primary', array('db_host'));
-$config-&gt;setReturnValue('getValue', 'admin', array('db_user'));
-$config-&gt;setReturnValue('getValue', 'secret', array('db_password'));</strong>
-</pre>
- Ce param&egrave;tre suppl&eacute;mentaire est une liste d'arguments que l'on peut utiliser. Dans ce cas nous essayons d'utiliser un unique argument, &agrave; savoir la clef recherch&eacute;e. Maintenant quand on invoque le bouchon serveur via la m&eacute;thode <span class="new_code">getValue()</span> avec...
-<pre>
-$config-&gt;getValue('db_user');
-</pre>
- ...il renvoie "admin". Il le trouve en essayant d'assortir successivement les arguments d'entr&eacute;e avec sa liste de ceux de sortie jusqu'au moment o&ugrave; une correspondance exacte est trouv&eacute;e.
- </p>
- <p>
- Vous pouvez d&eacute;finir un argument par d&eacute;faut avec...
-<pre>
-<strong>
-$config-&gt;setReturnValue('getValue', false, array('*'));</strong>
-</pre>
- Attention ce n'est pas &eacute;quivalent &agrave; initialiser la valeur retourn&eacute;e sans aucun argument.
-<pre>
-<strong>
-$config-&gt;setReturnValue('getValue', false);</strong>
-</pre>
- Dans le premier cas il acceptera n'importe quel argument, mais exactement un -- pas plus -- est n&eacute;cessaire. Dans le second cas n'importe quel nombre d'arguments fera l'affaire : il agit comme un <cite>catchall</cite> apr&egrave;s tous les correspondances. Prenez garde &agrave; l'ordre : si nous ajoutons un autre param&egrave;tre apr&egrave;s le joker ('*') il sera ignor&eacute; puisque le joker aura &eacute;t&eacute; trouv&eacute; auparavant. Avec des listes de param&egrave;tres complexes l'ordre peut devenir crucial, au risque de perdre des correspondances souhait&eacute;es, masqu&eacute;es par un joker ant&eacute;rieur. Pensez &agrave; mettre d'abord les cas les plus sp&eacute;cifiques si vous n'&ecirc;tes pas s&ucirc;r.
- </p>
- <p>
- Il y a des fois o&ugrave; l'on souhaite qu'un objet sp&eacute;cifique soit servi par le bouchon plut&ocirc;t qu'une simple copie. La s&eacute;mantique de la copie en PHP nous force &agrave; utiliser une autre m&eacute;thode pour cela. Vous &ecirc;tes peut-&ecirc;tre en train de simuler un conteneur par exemple...
-<pre>
-class Thing {
-}
-
-class Vector {
- function Vector() {
- }
-
- function get($index) {
- }
-}
-</pre>
- Dans ce cas vous pouvez mettre une r&eacute;f&eacute;rence dans la liste renvoy&eacute;e par le bouchon...
-<pre>
-Stub::generate('Vector');
-
-$thing = new Thing();<strong>
-$vector = &amp;new StubVector();
-$vector-&gt;setReturnReference('get', $thing, array(12));</strong>
-</pre>
- Avec ce petit arrangement vous vous assurez qu'&agrave; chaque fois que <span class="new_code">$vector-&gt;get(12)</span> est appel&eacute; il renverra le m&ecirc;me <span class="new_code">$thing</span>.
- </p>
- <p>
- Ces trois facteurs, ordre, param&egrave;tres et copie (ou r&eacute;f&eacute;rence), peuvent &ecirc;tre combin&eacute;s orthogonalement. Par exemple...
-<pre>
-$complex = &amp;new StubComplexThing();
-$stuff = new Stuff();<strong>
-$complex-&gt;setReturnReferenceAt(3, 'get', $stuff, array('*', 1));</strong>
-</pre>
- Le <span class="new_code">$stuff</span> ne sera renvoy&eacute; qu'au troisi&egrave;me appel et seulement si deux param&egrave;tres &eacute;taient indiqu&eacute;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 ?
- </p>
- <p>
- Un dernier cas critique reste celle d'un objet en cr&eacute;ant un autre, connu sous le nom du mod&egrave;le factory - fabrique. Supposons qu'apr&egrave;s une requ&ecirc;te r&eacute;ussie &agrave; notre base de donn&eacute;es imaginaire, un ensemble de r&eacute;sultats est retourn&eacute; sous la forme d'un it&eacute;rateur, chaque appel &agrave; <span class="new_code">next()</span> donnant un ligne et &agrave; la fin un <span class="new_code">false</span>.
- Au premier abord, &ccedil;a donne l'impression d'&ecirc;tre cauchemardesque &agrave; simuler. Alors qu'en fait tout peut &ecirc;tre bouchonn&eacute; en utilisant les m&eacute;canismes ci-dessus.
- </p>
- <p>
- Voici comment...
-<pre>
-Stub::generate('DatabaseConnection');
-Stub::generate('ResultIterator');
-
-class DatabaseTest extends UnitTestCase {
-
- function testUserFinder() {<strong>
- $result = &amp;new StubResultIterator();
- $result-&gt;setReturnValue('next', false);
- $result-&gt;setReturnValueAt(0, 'next', array(1, 'tom'));
- $result-&gt;setReturnValueAt(1, 'next', array(3, 'dick'));
- $result-&gt;setReturnValueAt(2, 'next', array(6, 'harry'));
-
- $connection = &amp;new StubDatabaseConnection();
- $connection-&gt;setReturnValue('query', false);
- $connection-&gt;setReturnReference(
- 'query',
- $result,
- array('select id, name from users'));</strong>
-
- $finder = &amp;new UserFinder($connection);
- $this-&gt;assertIdentical(
- $finder-&gt;findNames(),
- array('tom', 'dick', 'harry'));
- }
-}
-</pre>
- D&eacute;sormais ce n'est que si notre <span class="new_code">$connection</span> est appel&eacute; avec la bonne <span class="new_code">query()</span> que le <span class="new_code">$result</span> sera renvoy&eacute; apr&egrave;s le troisi&egrave;me appel &agrave; <span class="new_code">next()</span>. Cela devrait &ecirc;tre suffisant pour que notre classe <span class="new_code">UserFinder</span>, la classe effectivement test&eacute;e &agrave; ce niveau, puisse s'ex&eacute;cuter comme il faut. Un test tr&egrave;s pr&eacute;cis et pas une seule base de donn&eacute;es &agrave; l'horizon.
- </p>
-
- <p>
-<a class="target" name="options">
-<h2>Options de cr&eacute;ation pour les bouchons</h2>
-</a>
-</p>
- <p>
- Il y a d'autres options additionnelles &agrave; la cr&eacute;ation d'un bouchon. Au moment de la g&eacute;n&eacute;ration nous pouvons changer le nom de la classe...
-<pre>
-<strong>Stub::generate('Iterator', 'MyStubIterator');
-$iterator = &amp;new MyStubIterator();
-</strong>
-</pre>
- Pris tout seul ce n'est pas tr&egrave;s utile &eacute;tant donn&eacute; qu'il n'y aurait pas de diff&eacute;rence entre cette classe et celle par d&eacute;faut -- &agrave; part le nom bien entendu. Par contre nous pouvons aussi lui ajouter d'autres m&eacute;thodes qui ne se trouveraient pas dans l'interface originale...
-<pre>
-class Iterator {
-}
-<strong>Stub::generate('Iterator', 'PrototypeIterator', array('next', 'isError'));
-$iterator = &amp;new PrototypeIterator();
-$iterator-&gt;setReturnValue('next', 0);
-</strong>
-</pre>
- Les m&eacute;thodes <span class="new_code">next()</span> et <span class="new_code">isError()</span> peuvent maintenant renvoyer des ensembles de valeurs exactement comme si elles existaient dans la classe originale.
- </p>
- <p>
- Un moyen encore plus &eacute;sot&eacute;rique de modifier les bouchons est de changer le joker utiliser par d&eacute;faut pour la correspondance des param&egrave;tres.
-<pre>
-<strong>Stub::generate('Connection');
-$iterator = &amp;new StubConnection('wild');
-$iterator-&gt;setReturnValue('query', array('id' =&gt; 33), array('wild'));
-</strong>
-</pre>
- L'unique raison valable pour effectuer cette op&eacute;ration, c'est quand vous souhaitez tester la cha&icirc;ne "*" sans pour autant l'interpr&eacute;ter comme un "n'importe lequel".
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/docs/fr/unit_test_documentation.html b/tests/test_tools/simpletest/docs/fr/unit_test_documentation.html
deleted file mode 100755
index 3dcfeca5..00000000
--- a/tests/test_tools/simpletest/docs/fr/unit_test_documentation.html
+++ /dev/null
@@ -1,306 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>Documenation SimpleTest pour les tests de r&eacute;gression en PHP</title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<a href="index.html">SimpleTest</a>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Documentation sur les tests unitaires en PHP</h1>
-<div class="content">
- <p>
-<a class="target" name="unitaire">
-<h2>Sc&eacute;narios de tests unitaires</h2>
-</a>
-</p>
- <p>
- Le coeur du syst&egrave;me est un framework de test de r&eacute;gression construit autour des sc&eacute;narios de test. Un exemple de sc&eacute;nario de test ressemble &agrave;...
-<pre>
-<strong>class FileTestCase extends UnitTestCase {
-}</strong>
-</pre>
- Si aucun nom de test n'est fourni au moment de la liaison avec le constructeur alors le nom de la classe sera utilis&eacute;. Il s'agit du nom qui sera affich&eacute; dans les r&eacute;sultats du test.
- </p>
- <p>
- Les v&eacute;ritables tests sont ajout&eacute;s en tant que m&eacute;thode dans le sc&eacute;nario de test dont le nom par d&eacute;faut commence par la cha&icirc;ne "test" et quand le sc&eacute;nario de test est appel&eacute; toutes les m&eacute;thodes de ce type sont ex&eacute;cut&eacute;es dans l'ordre utilis&eacute; par l'introspection de PHP pour les trouver. Peuvent &ecirc;tre ajout&eacute;es autant de m&eacute;thodes de test que n&eacute;cessaires. Par exemple...
-<pre>
-require_once('../classes/writer.php');
-
-class FileTestCase extends UnitTestCase {
- function FileTestCase() {
- $this-&gt;UnitTestCase('File test');
- }<strong>
-
- function setUp() {
- @unlink('../temp/test.txt');
- }
-
- function tearDown() {
- @unlink('../temp/test.txt');
- }
-
- function testCreation() {
- $writer = &amp;new FileWriter('../temp/test.txt');
- $writer-&gt;write('Hello');
- $this-&gt;assertTrue(file_exists('../temp/test.txt'), 'File created');
- }</strong>
-}
-</pre>
- Le constructeur est optionnel et souvent omis. Sans nom, le nom de la classe est utilis&eacute; comme nom pour le sc&eacute;nario de test.
- </p>
- <p>
- Notre unique m&eacute;thode de test pour le moment est <span class="new_code">testCreation()</span> o&ugrave; nous v&eacute;rifions qu'un fichier a bien &eacute;t&eacute; cr&eacute;&eacute; par notre objet <span class="new_code">Writer</span>. Nous pourrions avoir mis le code <span class="new_code">unlink()</span> dans cette m&eacute;thode, mais en la pla&ccedil;ant dans <span class="new_code">setUp()</span> et <span class="new_code">tearDown()</span> nous pouvons l'utiliser pour nos autres m&eacute;thodes de test que nous ajouterons.
- </p>
- <p>
- La m&eacute;thode <span class="new_code">setUp()</span> est lanc&eacute; juste avant chaque m&eacute;thode de test. <span class="new_code">tearDown()</span> est lanc&eacute; apr&egrave;s chaque m&eacute;thode de test.
- </p>
- <p>
- Vous pouvez placer une initialisation de sc&eacute;nario de test dans le constructeur afin qu'elle soit lanc&eacute;e pour toutes les m&eacute;thodes dans le sc&eacute;nario de test mais dans un tel cas vous vous exposeriez &agrave; des interf&eacute;rences. Cette fa&ccedil;on de faire est l&eacute;g&egrave;rement moins rapide, mais elle est plus s&ucirc;re. Notez que si vous arrivez avec des notions de JUnit, il ne s'agit pas du comportement auquel vous &ecirc;tes habitu&eacute;s. Bizarrement JUnit re-instancie le sc&eacute;nario de test pour chaque m&eacute;thode de test pour se pr&eacute;venir d'une telle interf&eacute;rence. SimpleTest demande &agrave; l'utilisateur final d'utiliser <span class="new_code">setUp()</span>, mais fournit aux codeurs de biblioth&egrave;que d'autres crochets.
- </p>
- <p>
- Pour rapporter les r&eacute;sultats de test, le passage par une classe d'affichage - notifi&eacute;e par les diff&eacute;rentes m&eacute;thodes de type <span class="new_code">assert...()</span> - est utilis&eacute;e. En voici la liste compl&egrave;te pour la classe <span class="new_code">UnitTestCase</span>, celle par d&eacute;faut dans SimpleTest...
- <table>
-<tbody>
- <tr>
-<td><span class="new_code">assertTrue($x)</span></td><td>Echoue si $x est faux</td>
-</tr>
- <tr>
-<td><span class="new_code">assertFalse($x)</span></td><td>Echoue si $x est vrai</td>
-</tr>
- <tr>
-<td><span class="new_code">assertNull($x)</span></td><td>Echoue si $x est initialis&eacute;</td>
-</tr>
- <tr>
-<td><span class="new_code">assertNotNull($x)</span></td><td>Echoue si $x n'est pas initialis&eacute;</td>
-</tr>
- <tr>
-<td><span class="new_code">assertIsA($x, $t)</span></td><td>Echoue si $x n'est pas de la classe ou du type $t</td>
-</tr>
- <tr>
-<td><span class="new_code">assertEqual($x, $y)</span></td><td>Echoue si $x == $y est faux</td>
-</tr>
- <tr>
-<td><span class="new_code">assertNotEqual($x, $y)</span></td><td>Echoue si $x == $y est vrai</td>
-</tr>
- <tr>
-<td><span class="new_code">assertIdentical($x, $y)</span></td><td>Echoue si $x === $y est faux</td>
-</tr>
- <tr>
-<td><span class="new_code">assertNotIdentical($x, $y)</span></td><td>Echoue si $x === $y est vrai</td>
-</tr>
- <tr>
-<td><span class="new_code">assertReference($x, $y)</span></td><td>Echoue sauf si $x et $y sont la m&ecirc;me variable</td>
-</tr>
- <tr>
-<td><span class="new_code">assertCopy($x, $y)</span></td><td>Echoue si $x et $y sont la m&ecirc;me variable</td>
-</tr>
- <tr>
-<td><span class="new_code">assertWantedPattern($p, $x)</span></td><td>Echoue sauf si l'expression rationnelle $p capture $x</td>
-</tr>
- <tr>
-<td><span class="new_code">assertNoUnwantedPattern($p, $x)</span></td><td>Echoue si l'expression rationnelle $p capture $x</td>
-</tr>
- <tr>
-<td><span class="new_code">assertNoErrors()</span></td><td>Echoue si une erreur PHP arrive</td>
-</tr>
- <tr>
-<td><span class="new_code">assertError($x)</span></td><td>Echoue si aucune erreur ou message incorrect de PHP n'arrive</td>
-</tr>
- </tbody>
-</table>
- Toutes les m&eacute;thodes d'assertion peuvent recevoir une description optionnelle : cette description sert pour &eacute;tiqueter le r&eacute;sultat.
- Sans elle, une message par d&eacute;faut est envoy&eacute;e &agrave; la place : il est g&eacute;n&eacute;ralement suffisant. Ce message par d&eacute;faut peut encore &ecirc;tre encadr&eacute; dans votre propre message si vous incluez "%s" dans la cha&icirc;ne. Toutes les assertions renvoient vrai / true en cas de succ&egrave;s et faux / false en cas d'&eacute;chec.
- </p>
- <p>
- D'autres exemples...
-<pre>
-<strong>$variable = null;
-$this-&gt;assertNull($variable, 'Should be cleared');</strong>
-</pre>
- ...passera et normalement n'affichera aucun message. Si vous avez <a href="http://www.lastcraft.com/display_subclass_tutorial.php">configur&eacute; le testeur pour afficher aussi les succ&egrave;s</a> alors le message sera affich&eacute; comme tel.
-<pre>
-<strong>$this-&gt;assertIdentical(0, false, 'Zero is not false [%s]');</strong>
-</pre>
- Ceci &eacute;chouera &eacute;tant donn&eacute; qu'il effectue une v&eacute;rification sur le type en plus d'une comparaison sur les deux valeurs. La partie "%s" est remplac&eacute;e par le message d'erreur par d&eacute;faut qui aurait &eacute;t&eacute; affich&eacute; si nous n'avions pas fourni le n&ocirc;tre. Cela nous permet d'embo&icirc;ter les messages de test.
-<pre>
-<strong>$a = 1;
-$b = $a;
-$this-&gt;assertReference($a, $b);</strong>
-</pre>
- &Eacute;chouera &eacute;tant donn&eacute; que la variable <span class="new_code">$b</span> est une copie de <span class="new_code">$a</span>.
-<pre>
-<strong>$this-&gt;assertWantedPattern('/hello/i', 'Hello world');</strong>
-</pre>
- L&agrave;, &ccedil;a passe puisque la recherche est insensible &agrave; la casse et que donc <span class="new_code">hello</span> est bien rep&eacute;rable dans <span class="new_code">Hello world</span>.
-<pre>
-<strong>trigger_error('Disaster');
-trigger_error('Catastrophe');
-$this-&gt;assertError();
-$this-&gt;assertError('Catastrophe');
-$this-&gt;assertNoErrors();</strong>
-</pre>
- Ici, il y a besoin d'une petite explication : toutes passent !
- </p>
- <p>
- Les erreurs PHP dans SimpleTest sont pi&eacute;g&eacute;es et plac&eacute;es dans une queue. Ici la premi&egrave;re v&eacute;rification d'erreur attrape le message "Disaster" sans v&eacute;rifier le texte et passe. R&eacute;sultat : l'erreur est supprim&eacute;e de la queue. La v&eacute;rification suivante teste non seulement l'existence de l'erreur mais aussi le texte qui correspond : un autre succ&egrave;s. D&eacute;sormais la queue est vide et le dernier test passe aussi. Si une autre erreur non v&eacute;rifi&eacute;e est encore dans la queue &agrave; la fin de notre m&eacute;thode de test alors une exception sera rapport&eacute;e dans le test. Notez que SimpleTest ne peut pas attraper les erreurs PHP &agrave; la compilation.
- </p>
- <p>
- Les sc&eacute;narios de test peuvent utiliser des m&eacute;thodes bien pratiques pour d&eacute;boguer le code ou pour &eacute;tendre la suite...
- <table>
-<tbody>
- <tr>
-<td><span class="new_code">setUp()</span></td><td>Est lanc&eacute;e avant chaque m&eacute;thode de test</td>
-</tr>
- <tr>
-<td><span class="new_code">tearDown()</span></td><td>Est lanc&eacute;e apr&egrave;s chaque m&eacute;thode de test</td>
-</tr>
- <tr>
-<td><span class="new_code">pass()</span></td><td>Envoie un succ&egrave;s</td>
-</tr>
- <tr>
-<td><span class="new_code">fail()</span></td><td>Envoie un &eacute;chec</td>
-</tr>
- <tr>
-<td><span class="new_code">error()</span></td><td>Envoi un &eacute;v&egrave;nement exception</td>
-</tr>
- <tr>
-<td><span class="new_code">sendMessage()</span></td><td>Envoie un message d'&eacute;tat aux syst&egrave;mes d'affichage qui le supporte</td>
-</tr>
- <tr>
-<td><span class="new_code">signal($type, $payload)</span></td><td>Envoie un message d&eacute;fini par l'utilisateur au rapporteur du test</td>
-</tr>
- <tr>
-<td><span class="new_code">dump($var)</span></td><td>Effectue un <span class="new_code">print_r()</span> format&eacute; pour du d&eacute;boguage rapide et grossier</td>
-</tr>
- <tr>
-<td><span class="new_code">swallowErrors()</span></td><td>Vide les erreurs de la queue</td>
-</tr>
- </tbody>
-</table>
- </p>
-
- <p>
-<a class="target" name="extension_unitaire">
-<h2>Etendre les sc&eacute;narios de test</h2>
-</a>
-</p>
- <p>
- Bien s&ucirc;r des m&eacute;thodes suppl&eacute;mentaires de test peuvent &ecirc;tre ajout&eacute;es pour cr&eacute;er d'autres types de sc&eacute;nario de test afin d'&eacute;tendre le framework...
-<pre>
-require_once('simpletest/unit_tester.php');
-<strong>
-class FileTester extends UnitTestCase {
- function FileTester($name = false) {
- $this-&gt;UnitTestCase($name);
- }
-
- function assertFileExists($filename, $message = '%s') {
- $this-&gt;assertTrue(
- file_exists($filename),
- sprintf($message, 'File [$filename] existence check'));
- }</strong>
-}
-</pre>
- Ici la biblioth&egrave;que SimpleTest est localis&eacute;e dans un r&eacute;pertoire local appel&eacute; <em>simpletest</em>. Pensez &agrave; le modifier pour votre propre environnement.
- </p>
- <p>
- Ce nouveau sc&eacute;nario peut &ecirc;tre h&eacute;rit&eacute; exactement comme un sc&eacute;nario de test classique...
-<pre>
-class FileTestCase extends <strong>FileTester</strong> {
-
- function setUp() {
- @unlink('../temp/test.txt');
- }
-
- function tearDown() {
- @unlink('../temp/test.txt');
- }
-
- function testCreation() {
- $writer = &amp;new FileWriter('../temp/test.txt');
- $writer-&gt;write('Hello');<strong>
- $this-&gt;assertFileExists('../temp/test.txt');</strong>
- }
-}
-</pre>
- </p>
- <p>
- Si vous souhaitez un sc&eacute;nario de test sans toutes les assertions de <span class="new_code">UnitTestCase</span> mais uniquement avec les v&ocirc;tres propres, vous aurez besoin d'&eacute;tendre la classe <span class="new_code">SimpleTestCase</span> &agrave; la place. Elle se trouve dans <em>simple_test.php</em> en lieu et place de <em>unit_tester.php</em>. A consulter <a href="group_test_documentation.html">plus tard</a> si vous souhaitez incorporer les sc&eacute;narios d'autres testeurs unitaires dans votre suite de test.
- </p>
-
- <p>
-<a class="target" name="lancement_unitaire">
-<h2>Lancer un unique sc&eacute;nario de test</h2>
-</a>
-</p>
- <p>
- Ce n'est pas souvent qu'il faille lancer des sc&eacute;narios avec un unique test. Sauf lorsqu'il s'agit de s'arracher les cheveux sur un module &agrave; probl&egrave;me sans pour autant d&eacute;sorganiser la suite de test principale. Voici l'&eacute;chafaudage n&eacute;cessaire pour lancer un sc&eacute;nario de test solitaire...
-<pre>
-&lt;?php
- require_once('simpletest/unit_tester.php');<strong>
- require_once('simpletest/reporter.php');</strong>
- require_once('../classes/writer.php');
-
- class FileTestCase extends UnitTestCase {
- function FileTestCase() {
- $this-&gt;UnitTestCase('File test');
- }
- }<strong>
-
- $test = &amp;new FileTestCase();
- $test-&gt;run(new HtmlReporter());</strong>
-?&gt;
-</pre>
- Ce script sera lanc&eacute; tel que mais il n'y aura aucun succ&egrave;s ou &eacute;chec avant que des m&eacute;thodes de test soient ajout&eacute;es.
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/docs/fr/web_tester_documentation.html b/tests/test_tools/simpletest/docs/fr/web_tester_documentation.html
deleted file mode 100755
index 86044e5e..00000000
--- a/tests/test_tools/simpletest/docs/fr/web_tester_documentation.html
+++ /dev/null
@@ -1,397 +0,0 @@
-<html>
-<head>
-<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<title>Documentation SimpleTest : tester des scripts web</title>
-<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
-</head>
-<body>
-<div class="menu_back">
-<div class="menu">
-<h2>
-<a href="index.html">SimpleTest</a>
-</h2>
-<ul>
-<li>
-<a href="overview.html">Overview</a>
-</li>
-<li>
-<a href="unit_test_documentation.html">Unit tester</a>
-</li>
-<li>
-<a href="group_test_documentation.html">Group tests</a>
-</li>
-<li>
-<a href="server_stubs_documentation.html">Server stubs</a>
-</li>
-<li>
-<a href="mock_objects_documentation.html">Mock objects</a>
-</li>
-<li>
-<a href="partial_mocks_documentation.html">Partial mocks</a>
-</li>
-<li>
-<a href="reporter_documentation.html">Reporting</a>
-</li>
-<li>
-<a href="expectation_documentation.html">Expectations</a>
-</li>
-<li>
-<a href="web_tester_documentation.html">Web tester</a>
-</li>
-<li>
-<a href="form_testing_documentation.html">Testing forms</a>
-</li>
-<li>
-<a href="authentication_documentation.html">Authentication</a>
-</li>
-<li>
-<a href="browser_documentation.html">Scriptable browser</a>
-</li>
-</ul>
-</div>
-</div>
-<h1>Documentation sur le testeur web</h1>
-<div class="content">
- <p>
-<a class="target" name="telecharger">
-<h2>T&eacute;l&eacute;charger une page</h2>
-</a>
-</p>
- <p>
- Tester des classes c'es tr&egrave;s bien. Reste que PHP est avant tout un langage pour cr&eacute;er des fonctionnalit&eacute;s &agrave; l'int&eacute;rieur de pages web. Comment pouvons tester la partie de devant -- celle de l'interface -- dans nos applications en PHP ? Etant donn&eacute; qu'une page web n'est constitu&eacute;e que de texte, nous devrions pouvoir les examiner exactement comme n'importe quelle autre donn&eacute;e de test.
- </p>
- <p>
- Cela nous am&egrave;ne &agrave; une situation d&eacute;licate. Si nous testons dans un niveau trop bas, v&eacute;rifier des balises avec un motif ad hoc par exemple, nos tests seront trop fragiles. Le moindre changement dans la pr&eacute;sentation pourrait casser un grand nombre de test. Si nos tests sont situ&eacute;s trop haut, en utilisant une version fantaisie du moteur de template pour donner un cas pr&eacute;cis, alors nous perdons compl&egrave;tement la capacit&eacute; &agrave; automatiser certaines classes de test. Par exemple, l'interaction entre des formulaires et la navigation devra &ecirc;tre test&eacute; manuellement. Ces types de test sont extr&ecirc;mement fastidieux et plut&ocirc;t sensibles aux erreurs.
- </p>
- <p>
- SimpleTest comprend une forme sp&eacute;ciale de sc&eacute;nario de test pour tester les actions d'une page web. <span class="new_code">WebTestCase</span> inclut des facilit&eacute;s pour la navigation, des v&eacute;rifications sur le contenu et les cookies ainsi que la gestion des formulaires. Utiliser ces sc&eacute;narios de test ressemble fortement &agrave; <span class="new_code">UnitTestCase</span>...
-<pre>
-<strong>class TestOfLastcraft extends WebTestCase {
-}</strong>
-</pre>
- Ici nous sommes sur le point de tester le site de <a href="http://www/lastcraft.com/">Last Craft</a>. Si ce sc&eacute;nario de test est situ&eacute; dans un fichier appel&eacute; <em>lastcraft_test.php</em> alors il peut &ecirc;tre charg&eacute; dans un script de lancement tout comme des tests unitaires...
-<pre>
-&lt;?php<strong>
- require_once('simpletest/web_tester.php');</strong>
- require_once('simpletest/reporter.php');
-
- $test = &amp;new GroupTest('Web site tests');<strong>
- $test-&gt;addTestFile('lastcraft_test.php');</strong>
- exit ($test-&gt;run(new TextReporter()) ? 0 : 1);
-?&gt;
-</pre>
- J'utilise ici le rapporteur en mode texte pour mieux distinguer le contenu au format HTML du r&eacute;sultat du test proprement dit.
- </p>
- <p>
- Rien n'est encore test&eacute;. Nous pouvons t&eacute;l&eacute;charger la page d'accueil en utilisant la m&eacute;thode <span class="new_code">get()</span>...
-<pre>
-class TestOfLastcraft extends WebTestCase {
- <strong>
- function testHomepage() {
- $this-&gt;assertTrue($this-&gt;get('http://www.lastcraft.com/'));
- }</strong>
-}
-</pre>
- La m&eacute;thode <span class="new_code">get()</span> renverra "true" uniquement si le contenu de la page a bien &eacute;t&eacute; t&eacute;l&eacute;charg&eacute;. C'est un moyen simple, mais efficace pour v&eacute;rifier qu'une page web a bien &eacute;t&eacute; d&eacute;livr&eacute; par le serveur web. Cependant le contenu peut r&eacute;v&eacute;ler &ecirc;tre une erreur 404 et dans ce cas notre m&eacute;thode <span class="new_code">get()</span> renverrait encore un succ&egrave;s.
- </p>
- <p>
- En supposant que le serveur web pour le site Last Craft soit op&eacute;rationnel (malheureusement ce n'est pas toujours le cas), nous devrions voir...
-<pre class="shell">
-Web site tests
-OK
-Test cases run: 1/1, Failures: 0, Exceptions: 0
-</pre>
- Nous avons v&eacute;rifi&eacute; qu'une page, de n'importe quel type, a bien &eacute;t&eacute; renvoy&eacute;e. Nous ne savons pas encore s'il s'agit de celle que nous souhaitions.
- </p>
-
- <p>
-<a class="target" name="contenu">
-<h2>Tester le contenu d'une page</h2>
-</a>
-</p>
- <p>
- Pour obtenir la confirmation que la page t&eacute;l&eacute;charg&eacute;e est bien celle que nous attendions, nous devons v&eacute;rifier son contenu.
-<pre>
-class TestOfLastcraft extends WebTestCase {
-
- function testHomepage() {<strong>
- $this-&gt;get('http://www.lastcraft.com/');
- $this-&gt;assertWantedPattern('/why the last craft/i');</strong>
- }
-}
-</pre>
- La page obtenue par le dernier t&eacute;l&eacute;chargement est plac&eacute;e dans un buffer au sein m&ecirc;me du sc&eacute;nario de test. Il n'est donc pas n&eacute;cessaire de s'y r&eacute;f&eacute;rer directement. La correspondance du motif est toujours effectu&eacute;e par rapport &agrave; ce buffer.
- </p>
- <p>
- Voici une liste possible d'assertions sur le contenu...
- <table>
-<tbody>
- <tr>
-<td><span class="new_code">assertWantedPattern($pattern)</span></td><td>V&eacute;rifier une correspondance sur le contenu via une expression rationnelle Perl</td>
-</tr>
- <tr>
-<td><span class="new_code">assertNoUnwantedPattern($pattern)</span></td><td>Une expression rationnelle Perl pour v&eacute;rifier une absence</td>
-</tr>
- <tr>
-<td><span class="new_code">assertTitle($title)</span></td><td>Passe si le titre de la page correspond exactement</td>
-</tr>
- <tr>
-<td><span class="new_code">assertLink($label)</span></td><td>Passe si un lien avec ce texte est pr&eacute;sent</td>
-</tr>
- <tr>
-<td><span class="new_code">assertNoLink($label)</span></td><td>Passe si aucun lien avec ce texte est pr&eacute;sent</td>
-</tr>
- <tr>
-<td><span class="new_code">assertLinkById($id)</span></td><td>Passe si un lien avec cet attribut d'identification est pr&eacute;sent</td>
-</tr>
- <tr>
-<td><span class="new_code">assertField($name, $value)</span></td><td>Passe si une balise input avec ce nom contient cette valeur</td>
-</tr>
- <tr>
-<td><span class="new_code">assertFieldById($id, $value)</span></td><td>Passe si une balise input avec cet identifiant contient cette valeur</td>
-</tr>
- <tr>
-<td><span class="new_code">assertResponse($codes)</span></td><td>Passe si la r&eacute;ponse HTTP trouve une correspondance dans la liste</td>
-</tr>
- <tr>
-<td><span class="new_code">assertMime($types)</span></td><td>Passe si le type MIME se retrouve dans cette liste</td>
-</tr>
- <tr>
-<td><span class="new_code">assertAuthentication($protocol)</span></td><td>Passe si l'authentification provoqu&eacute;e est de ce type de protocole</td>
-</tr>
- <tr>
-<td><span class="new_code">assertNoAuthentication()</span></td><td>Passe s'il n'y pas d'authentification provoqu&eacute;e en cours</td>
-</tr>
- <tr>
-<td><span class="new_code">assertRealm($name)</span></td><td>Passe si le domaine provoqu&eacute; correspond</td>
-</tr>
- <tr>
-<td><span class="new_code">assertHeader($header, $content)</span></td><td>Passe si une ent&ecirc;te t&eacute;l&eacute;charg&eacute;e correspond &agrave; cette valeur</td>
-</tr>
- <tr>
-<td><span class="new_code">assertNoUnwantedHeader($header)</span></td><td>Passe si une ent&ecirc;te n'a pas &eacute;t&eacute; t&eacute;l&eacute;charg&eacute;</td>
-</tr>
- <tr>
-<td><span class="new_code">assertHeaderPattern($header, $pattern)</span></td><td>Passe si une ent&ecirc;te t&eacute;l&eacute;charg&eacute;e correspond &agrave; cette expression rationnelle Perl</td>
-</tr>
- <tr>
-<td><span class="new_code">assertCookie($name, $value)</span></td><td>Passe s'il existe un cookie correspondant</td>
-</tr>
- <tr>
-<td><span class="new_code">assertNoCookie($name)</span></td><td>Passe s'il n'y a pas de cookie avec un tel nom</td>
-</tr>
- </tbody>
-</table>
- Comme d'habitude avec les assertions de SimpleTest, elles renvoient toutes "false" en cas d'&eacute;chec et "true" si c'est un succ&egrave;s. Elles renvoient aussi un message de test optionnel : vous pouvez l'ajouter dans votre propre message en utilisant "%s".
- </p>
- <p>
- A pr&eacute;sent nous pourrions effectu&eacute; le test sur le titre uniquement...
-<pre>
-<strong>$this-&gt;assertTitle('The Last Craft?');</strong>
-</pre>
- En plus d'une simple v&eacute;rification sur le contenu HTML, nous pouvons aussi v&eacute;rifier que le type MIME est bien d'un type acceptable...
-<pre>
-<strong>$this-&gt;assertMime(array('text/plain', 'text/html'));</strong>
-</pre>
- Plus int&eacute;ressant encore est la v&eacute;rification sur le code de la r&eacute;ponse HTTP. Pareillement au type MIME, nous pouvons nous assurer que le code renvoy&eacute; se trouve bien dans un liste de valeurs possibles...
-<pre>
-class TestOfLastcraft extends WebTestCase {
-
- function testHomepage() {
- $this-&gt;get('http://simpletest.sourceforge.net/');<strong>
- $this-&gt;assertResponse(200);</strong>
- }
-}
-</pre>
- Ici nous v&eacute;rifions que le t&eacute;l&eacute;chargement s'est bien termin&eacute; en ne permettant qu'une r&eacute;ponse HTTP 200. Ce test passera, mais ce n'est pas la meilleure fa&ccedil;on de proc&eacute;der. Il n'existe aucune page sur <em>http://simpletest.sourceforge.net/</em>, &agrave; la place le serveur renverra une redirection vers <em>http://www.lastcraft.com/simple_test.php</em>. <span class="new_code">WebTestCase</span> suit automatiquement trois de ces redirections. Les tests sont quelque peu plus robustes de la sorte. Surtout qu'on est souvent plus int&eacute;ress&eacute; par l'interaction entre les pages que de leur simple livraison. Si les redirections se r&eacute;v&egrave;lent &ecirc;tre digne d'int&eacute;r&ecirc;t, il reste possible de les supprimer...
-<pre>
-class TestOfLastcraft extends WebTestCase {
-
- function testHomepage() {<strong>
- $this-&gt;setMaximumRedirects(0);</strong>
- $this-&gt;get('http://simpletest.sourceforge.net/');
- $this-&gt;assertResponse(200);
- }
-}
-</pre>
- Alors l'assertion &eacute;choue comme pr&eacute;vue...
-<pre class="shell">
-Web site tests
-1) Expecting response in [200] got [302]
- in testhomepage
- in testoflastcraft
- in lastcraft_test.php
-FAILURES!!!
-Test cases run: 1/1, Failures: 1, Exceptions: 0
-</pre>
- Nous pouvons modifier le test pour accepter les redirections...
-<pre>
-class TestOfLastcraft extends WebTestCase {
-
- function testHomepage() {
- $this-&gt;setMaximumRedirects(0);
- $this-&gt;get('http://simpletest.sourceforge.net/');
- $this-&gt;assertResponse(<strong>array(301, 302, 303, 307)</strong>);
- }
-}
-</pre>
- Maitenant &ccedil;a passe.
- </p>
-
- <p>
-<a class="target" name="navigation">
-<h2>Navigeur dans un site web</h2>
-</a>
-</p>
- <p>
- Les utilisateurs ne naviguent pas souvent en tapant les URLs, mais surtout en cliquant sur des liens et des boutons. Ici nous confirmons que les informations sur le contact peuvent &ecirc;tre atteintes depuis la page d'accueil...
-<pre>
-class TestOfLastcraft extends WebTestCase {
- ...
- function testContact() {
- $this-&gt;get('http://www.lastcraft.com/');<strong>
- $this-&gt;clickLink('About');
- $this-&gt;assertTitle('About Last Craft');</strong>
- }
-}
-</pre>
- Le param&egrave;tre est le texte du lien.
- </p>
- <p>
- Il l'objectif est un bouton plut&ocirc;t qu'une balise ancre, alors <span class="new_code">clickSubmit()</span> doit &ecirc;tre utilis&eacute; avec le titre du bouton...
-<pre>
-<strong>$this-&gt;clickSubmit('Go!');</strong>
-</pre>
- </p>
- <p>
- La liste des m&eacute;thodes de navigation est...
- <table>
-<tbody>
- <tr>
-<td><span class="new_code">get($url, $parameters)</span></td><td>Envoie une requ&ecirc;te GET avec ces param&egrave;tres</td>
-</tr>
- <tr>
-<td><span class="new_code">post($url, $parameters)</span></td><td>Envoie une requ&ecirc;te POST avec ces param&egrave;tres</td>
-</tr>
- <tr>
-<td><span class="new_code">head($url, $parameters)</span></td><td>Envoie une requ&ecirc;te HEAD sans remplacer le contenu de la page</td>
-</tr>
- <tr>
-<td><span class="new_code">retry()</span></td><td>Relance la derni&egrave;re requ&ecirc;te</td>
-</tr>
- <tr>
-<td><span class="new_code">back()</span></td><td>Identique au bouton "Pr&eacute;c&eacute;dent" du navigateur</td>
-</tr>
- <tr>
-<td><span class="new_code">forward()</span></td><td>Identique au bouton "Suivant" du navigateur</td>
-</tr>
- <tr>
-<td><span class="new_code">authenticate($name, $password)</span></td><td>Re-essaye avec une tentative d'authentification</td>
-</tr>
- <tr>
-<td><span class="new_code">getFrameFocus()</span></td><td>Le nom de la fen&ecirc;tre en cours d'utilisation</td>
-</tr>
- <tr>
-<td><span class="new_code">setFrameFocusByIndex($choice)</span></td><td>Change le focus d'une fen&ecirc;tre en commen&ccedil;ant par 1</td>
-</tr>
- <tr>
-<td><span class="new_code">setFrameFocus($name)</span></td><td>Change le focus d'une fen&ecirc;tre en utilisant son nom</td>
-</tr>
- <tr>
-<td><span class="new_code">clearFrameFocus()</span></td><td>Revient &agrave; un traitement de toutes les fen&ecirc;tres comme une seule</td>
-</tr>
- <tr>
-<td><span class="new_code">clickSubmit($label)</span></td><td>Clique sur le premier bouton avec cette &eacute;tiquette</td>
-</tr>
- <tr>
-<td><span class="new_code">clickSubmitByName($name)</span></td><td>Clique sur le bouton avec cet attribut de nom</td>
-</tr>
- <tr>
-<td><span class="new_code">clickSubmitById($id)</span></td><td>Clique sur le bouton avec cet attribut d'identification</td>
-</tr>
- <tr>
-<td><span class="new_code">clickImage($label, $x, $y)</span></td><td>Clique sur une balise input de type image avec ce titre ou ce texte dans l'attribut alt</td>
-</tr>
- <tr>
-<td><span class="new_code">clickImageByName($name, $x, $y)</span></td><td>Clique sur une balise input de type image avec ce nom</td>
-</tr>
- <tr>
-<td><span class="new_code">clickImageById($id, $x, $y)</span></td><td>Clique sur une balise input de type image avec cet attribut d'identification</td>
-</tr>
- <tr>
-<td><span class="new_code">submitFormById($id)</span></td><td>Soumet un formulaire sans valeur de soumission</td>
-</tr>
- <tr>
-<td><span class="new_code">clickLink($label, $index)</span></td><td>Clique sur un ancre avec ce texte d'&eacute;tiquette visible</td>
-</tr>
- <tr>
-<td><span class="new_code">clickLinkById($id)</span></td><td>Clique sur une ancre avec cet attribut d'identification</td>
-</tr>
- </tbody>
-</table>
- </p>
- <p>
- Les param&egrave;tres dans les m&eacute;thodes <span class="new_code">get()</span>, <span class="new_code">post()</span> et <span class="new_code">head()</span> sont optionnels. Le t&eacute;l&eacute;chargement via HTTP HEAD ne modifie pas le contexte du navigateur, il se limite au chargement des cookies. Cela peut &ecirc;tre utilise lorsqu'une image ou une feuille de style initie un cookie pour bloquer un robot trop entreprenant.
- </p>
- <p>
- Les commandes <span class="new_code">retry()</span>, <span class="new_code">back()</span> et <span class="new_code">forward()</span> fonctionnent exactement comme dans un navigateur. Elles utilisent l'historique pour relancer les pages. Une technique bien pratique pour v&eacute;rifier les effets d'un bouton retour sur vos formulaires.
- </p>
- <p>
- Les m&eacute;thodes sur les fen&ecirc;tres m&eacute;ritent une petite explication. Par d&eacute;faut, une page avec des fen&ecirc;tres est trait&eacute;e comme toutes les autres. Le contenu sera v&eacute;rifi&eacute; &agrave; travers l'ensemble de la "frameset", par cons&eacute;quent un lien fonctionnera, peu importe la fen&ecirc;tre qui contient la balise ancre. Vous pouvez outrepass&eacute; ce comportement en exigeant le focus sur une unique fen&ecirc;tre. Si vous r&eacute;alisez cela, toutes les recherches et toutes les actions se limiteront &agrave; cette unique fen&ecirc;tre, y compris les demandes d'authentification. Si un lien ou un bouton n'est pas dans la fen&ecirc;tre en focus alors il ne peut pas &ecirc;tre cliqu&eacute;.
- </p>
- <p>
- Tester la navigation sur des pages fixes ne vous alerte que quand vous avez cass&eacute; un script entier. Pour des pages fortement dynamiques, un forum de discussion par exemple, &ccedil;a peut &ecirc;tre crucial pour v&eacute;rifier l'&eacute;tat de l'application. Pour la plupart des applications cependant, la logique vraiment d&eacute;licate se situe dans la gestion des formulaires et des sessions. Heureusement SimpleTest aussi inclut <a href="form_testing_documentation.html">des outils pour tester des formulaires web</a>.
- </p>
-
- <p>
-<a class="target" name="requete">
-<h2>Modifier la requ&ecirc;te</h2>
-</a>
-</p>
- <p>
- Bien que SimpleTest n'ait pas comme objectif de contr&ocirc;ler des erreurs r&eacute;seau, il contient quand m&ecirc;me des m&eacute;thodes pour modifier et d&eacute;boguer les requ&ecirc;tes qu'il lance. Voici une autre liste de m&eacute;thode...
- <table>
-<tbody>
- <tr>
-<td><span class="new_code">getTransportError()</span></td><td>La derni&egrave;re erreur de socket</td>
-</tr>
- <tr>
-<td><span class="new_code">getUrl()</span></td><td>La localisation courante</td>
-</tr>
- <tr>
-<td><span class="new_code">showRequest()</span></td><td>D&eacute;verse la requ&ecirc;te sortante</td>
-</tr>
- <tr>
-<td><span class="new_code">showHeaders()</span></td><td>D&eacute;verse les ent&ecirc;tes d'entr&eacute;e</td>
-</tr>
- <tr>
-<td><span class="new_code">showSource()</span></td><td>D&eacute;verse le contenu brut de la page HTML</td>
-</tr>
- <tr>
-<td><span class="new_code">ignoreFrames()</span></td><td>Ne recharge pas les framesets</td>
-</tr>
- <tr>
-<td><span class="new_code">setCookie($name, $value)</span></td><td>Initie un cookie &agrave; partir de maintenant</td>
-</tr>
- <tr>
-<td><span class="new_code">addHeader($header)</span></td><td>Ajoute toujours cette ent&ecirc;te &agrave; la requ&ecirc;te</td>
-</tr>
- <tr>
-<td><span class="new_code">setMaximumRedirects($max)</span></td><td>S'arr&ecirc;te apr&egrave;s autant de redirections</td>
-</tr>
- <tr>
-<td><span class="new_code">setConnectionTimeout($timeout)</span></td><td>Termine la connexion apr&egrave;s autant de temps entre les bytes</td>
-</tr>
- <tr>
-<td><span class="new_code">useProxy($proxy, $name, $password)</span></td><td>Effectue les requ&ecirc;tes &agrave; travers ce proxy d'URL</td>
-</tr>
- </tbody>
-</table>
- </p>
-
- </div>
-<div class="copyright">
- Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
- </div>
-</body>
-</html>
diff --git a/tests/test_tools/simpletest/dumper.php b/tests/test_tools/simpletest/dumper.php
index f54140ca..956b8f00 100644
--- a/tests/test_tools/simpletest/dumper.php
+++ b/tests/test_tools/simpletest/dumper.php
@@ -3,12 +3,14 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
- * @version $Id: dumper.php,v 1.22 2005/02/05 04:51:17 lastcraft Exp $
+ * @version $Id: dumper.php,v 1.28 2006/01/03 01:17:07 lastcraft Exp $
*/
/**
* does type matter
*/
- define('TYPE_MATTERS', true);
+ if (! defined('TYPE_MATTERS')) {
+ define('TYPE_MATTERS', true);
+ }
/**
* Displays variables as text and does diffs.
@@ -35,7 +37,7 @@
case "Object":
return "Object: of " . get_class($value);
case "String":
- return "String: " . $this->clipString($value, 100);
+ return "String: " . $this->clipString($value, 200);
default:
return "$type: $value";
}
@@ -184,8 +186,8 @@
$position = $this->_stringDiffersAt($first, $second);
$message = "at character $position";
$message .= " with [" .
- $this->clipString($first, 100, $position) . "] and [" .
- $this->clipString($second, 100, $position) . "]";
+ $this->clipString($first, 200, $position) . "] and [" .
+ $this->clipString($second, 200, $position) . "]";
return $message;
}
@@ -221,9 +223,10 @@
if (is_object($second) || is_array($second)) {
return $this->_describeGenericDifference($first, $second);
}
- return "because " . $this->describeValue($first) .
+ return "because [" . $this->describeValue($first) .
"] differs from [" .
- $this->describeValue($second) . "]";
+ $this->describeValue($second) . "] by " .
+ abs($first - $second);
}
/**
@@ -331,7 +334,7 @@
$position = 0;
$step = strlen($first);
while ($step > 1) {
- $step = (integer)(($step + 1)/2);
+ $step = (integer)(($step + 1) / 2);
if (strncmp($first, $second, $position + $step) == 0) {
$position += $step;
}
@@ -358,23 +361,42 @@
* Extracts the last assertion that was not within
* Simpletest itself. The name must start with "assert".
* @param array $stack List of stack frames.
- * @param string $format String formatting.
- * @param string $prefix Prefix of method to search for.
* @access public
* @static
*/
- function getFormattedAssertionLine($stack, $format = '%d', $prefix = 'assert') {
+ function getFormattedAssertionLine($stack) {
foreach ($stack as $frame) {
- if (isset($frame['file']) && strpos($frame['file'], 'simpletest') !== false) { // dirname() is a bit slow.
- if (substr(dirname($frame['file']), -10) == 'simpletest') {
- continue;
+ if (isset($frame['file'])) {
+ if (strpos($frame['file'], SIMPLE_TEST) !== false) {
+ if (dirname($frame['file']) . '/' == SIMPLE_TEST) {
+ continue;
+ }
}
}
- if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) {
- return sprintf($format, $frame['line']);
+ if (SimpleDumper::_stackFrameIsAnAssertion($frame)) {
+ return ' at [' . $frame['file'] . ' line ' . $frame['line'] . ']';
}
}
return '';
}
+
+ /**
+ * Tries to determine if the method call is an assertion.
+ * @param array $frame PHP stack frame.
+ * @access private
+ * @static
+ */
+ function _stackFrameIsAnAssertion($frame) {
+ if (($frame['function'] == 'fail') || ($frame['function'] == 'pass')) {
+ return true;
+ }
+ if (strncmp($frame['function'], 'assert', 6) == 0) {
+ return true;
+ }
+ if (strncmp($frame['function'], 'expect', 6) == 0) {
+ return true;
+ }
+ return false;
+ }
}
?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/encoding.php b/tests/test_tools/simpletest/encoding.php
index 62ca2a1b..11a94df0 100644
--- a/tests/test_tools/simpletest/encoding.php
+++ b/tests/test_tools/simpletest/encoding.php
@@ -3,8 +3,184 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
- * @version $Id: encoding.php,v 1.6 2005/01/02 23:43:23 lastcraft Exp $
+ * @version $Id: encoding.php,v 1.17 2005/07/20 13:41:40 lastcraft Exp $
*/
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/socket.php');
+ /**#@-*/
+
+ /**
+ * Single post parameter.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleEncodedPair {
+ protected $_key;
+ protected $_value;
+
+ /**
+ * Stashes the data for rendering later.
+ * @param string $key Form element name.
+ * @param string $value Data to send.
+ */
+ function SimpleEncodedPair($key, $value) {
+ $this->_key = $key;
+ $this->_value = $value;
+ }
+
+ /**
+ * The pair as a single string.
+ * @return string Encoded pair.
+ * @access public
+ */
+ function asRequest() {
+ return $this->_key . '=' . urlencode($this->_value);
+ }
+
+ /**
+ * The MIME part as a string.
+ * @return string MIME part encoding.
+ * @access public
+ */
+ function asMime() {
+ $part = 'Content-Disposition: form-data; ';
+ $part .= "name=\"" . $this->_key . "\"\r\n";
+ $part .= "\r\n" . $this->_value;
+ return $part;
+ }
+
+ /**
+ * Is this the value we are looking for?
+ * @param string $key Identifier.
+ * @return boolean True if matched.
+ * @access public
+ */
+ function isKey($key) {
+ return $key == $this->_key;
+ }
+
+ /**
+ * Is this the value we are looking for?
+ * @return string Identifier.
+ * @access public
+ */
+ function getKey() {
+ return $this->_key;
+ }
+
+ /**
+ * Is this the value we are looking for?
+ * @return string Content.
+ * @access public
+ */
+ function getValue() {
+ return $this->_value;
+ }
+ }
+
+ /**
+ * Single post parameter.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleAttachment {
+ protected $_key;
+ protected $_content;
+ protected $_filename;
+
+ /**
+ * Stashes the data for rendering later.
+ * @param string $key Key to add value to.
+ * @param string $content Raw data.
+ * @param hash $filename Original filename.
+ */
+ function SimpleAttachment($key, $content, $filename) {
+ $this->_key = $key;
+ $this->_content = $content;
+ $this->_filename = $filename;
+ }
+
+ /**
+ * The pair as a single string.
+ * @return string Encoded pair.
+ * @access public
+ */
+ function asRequest() {
+ return '';
+ }
+
+ /**
+ * The MIME part as a string.
+ * @return string MIME part encoding.
+ * @access public
+ */
+ function asMime() {
+ $part = 'Content-Disposition: form-data; ';
+ $part .= 'name="' . $this->_key . '"; ';
+ $part .= 'filename="' . $this->_filename . '"';
+ $part .= "\r\nContent-Type: " . $this->_deduceMimeType();
+ $part .= "\r\n\r\n" . $this->_content;
+ return $part;
+ }
+
+ /**
+ * Attempts to figure out the MIME type from the
+ * file extension and the content.
+ * @return string MIME type.
+ * @access private
+ */
+ function _deduceMimeType() {
+ if ($this->_isOnlyAscii($this->_content)) {
+ return 'text/plain';
+ }
+ return 'application/octet-stream';
+ }
+
+ /**
+ * Tests each character is in the range 0-127.
+ * @param string $ascii String to test.
+ * @access private
+ */
+ function _isOnlyAscii($ascii) {
+ for ($i = 0, $length = strlen($ascii); $i < $length; $i++) {
+ if (ord($ascii[$i]) > 127) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Is this the value we are looking for?
+ * @param string $key Identifier.
+ * @return boolean True if matched.
+ * @access public
+ */
+ function isKey($key) {
+ return $key == $this->_key;
+ }
+
+ /**
+ * Is this the value we are looking for?
+ * @return string Identifier.
+ * @access public
+ */
+ function getKey() {
+ return $this->_key;
+ }
+
+ /**
+ * Is this the value we are looking for?
+ * @return string Content.
+ * @access public
+ */
+ function getValue() {
+ return $this->_filename;
+ }
+ }
/**
* Bundle of GET/POST parameters. Can include
@@ -12,28 +188,33 @@
* @package SimpleTest
* @subpackage WebTester
*/
- class SimpleFormEncoding {
+ class SimpleEncoding {
protected $_request;
- protected $_x;
- protected $_y;
/**
* Starts empty.
- * @param array $query/SimpleQueryString Hash of parameters.
- * Multiple values are
- * as lists on a single key.
+ * @param array $query Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
* @access public
*/
- function SimpleFormEncoding($query = false) {
+ function SimpleEncoding($query = false) {
if (! $query) {
$query = array();
}
- $this->_request = array();
- $this->setCoordinates();
+ $this->clear();
$this->merge($query);
}
/**
+ * Empties the request of parameters.
+ * @access public
+ */
+ function clear() {
+ $this->_request = array();
+ }
+
+ /**
* Adds a parameter to the query.
* @param string $key Key to add value to.
* @param string/array $value New data.
@@ -43,19 +224,38 @@
if ($value === false) {
return;
}
- if (! isset($this->_request[$key])) {
- $this->_request[$key] = array();
- }
if (is_array($value)) {
foreach ($value as $item) {
- $this->_request[$key][] = $item;
+ $this->_addPair($key, $item);
}
} else {
- $this->_request[$key][] = $value;
+ $this->_addPair($key, $value);
}
}
/**
+ * Adds a new value into the request.
+ * @param string $key Key to add value to.
+ * @param string/array $value New data.
+ * @access private
+ */
+ function _addPair($key, $value) {
+ $this->_request[] = new SimpleEncodedPair($key, $value);
+ }
+
+ /**
+ * Adds a MIME part to the query. Does nothing for a
+ * form encoded packet.
+ * @param string $key Key to add value to.
+ * @param string $content Raw data.
+ * @param hash $filename Original filename.
+ * @access public
+ */
+ function attach($key, $content, $filename) {
+ $this->_request[] = new SimpleAttachment($key, $content, $filename);
+ }
+
+ /**
* Adds a set of parameters to this query.
* @param array/SimpleQueryString $query Multiple values are
* as lists on a single key.
@@ -63,12 +263,7 @@
*/
function merge($query) {
if (is_object($query)) {
- foreach ($query->getKeys() as $key) {
- $this->add($key, $query->getValue($key));
- }
- if ($query->getX() !== false) {
- $this->setCoordinates($query->getX(), $query->getY());
- }
+ $this->_request = array_merge($this->_request, $query->getAll());
} elseif (is_array($query)) {
foreach ($query as $key => $value) {
$this->add($key, $value);
@@ -77,63 +272,234 @@
}
/**
- * Sets image coordinates. Set to false to clear
- * them.
- * @param integer $x Horizontal position.
- * @param integer $y Vertical position.
+ * Accessor for single value.
+ * @return string/array False if missing, string
+ * if present and array if
+ * multiple entries.
* @access public
*/
- function setCoordinates($x = false, $y = false) {
- if (($x === false) || ($y === false)) {
- $this->_x = $this->_y = false;
- return;
+ function getValue($key) {
+ $values = array();
+ foreach ($this->_request as $pair) {
+ if ($pair->isKey($key)) {
+ $values[] = $pair->getValue();
+ }
+ }
+ if (count($values) == 0) {
+ return false;
+ } elseif (count($values) == 1) {
+ return $values[0];
+ } else {
+ return $values;
}
- $this->_x = (integer)$x;
- $this->_y = (integer)$y;
}
/**
- * Accessor for horizontal image coordinate.
- * @return integer X value.
+ * Accessor for listing of pairs.
+ * @return array All pair objects.
* @access public
*/
- function getX() {
- return $this->_x;
+ function getAll() {
+ return $this->_request;
+ }
+
+ /**
+ * Renders the query string as a URL encoded
+ * request part.
+ * @return string Part of URL.
+ * @access protected
+ */
+ function _encode() {
+ $statements = array();
+ foreach ($this->_request as $pair) {
+ if ($statement = $pair->asRequest()) {
+ $statements[] = $statement;
+ }
+ }
+ return implode('&', $statements);
}
-
+ }
+
+ /**
+ * Bundle of GET parameters. Can include
+ * repeated parameters.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleGetEncoding extends SimpleEncoding {
+
/**
- * Accessor for vertical image coordinate.
- * @return integer Y value.
+ * Starts empty.
+ * @param array $query Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
* @access public
*/
- function getY() {
- return $this->_y;
+ function SimpleGetEncoding($query = false) {
+ $this->SimpleEncoding($query);
}
/**
- * Accessor for single value.
- * @return string/array False if missing, string
- * if present and array if
- * multiple entries.
+ * HTTP request method.
+ * @return string Always GET.
* @access public
*/
- function getValue($key) {
- if (! isset($this->_request[$key])) {
- return false;
- } elseif (count($this->_request[$key]) == 1) {
- return $this->_request[$key][0];
- } else {
- return $this->_request[$key];
- }
+ function getMethod() {
+ return 'GET';
+ }
+
+ /**
+ * Writes no extra headers.
+ * @param SimpleSocket $socket Socket to write to.
+ * @access public
+ */
+ function writeHeadersTo($socket) {
+ }
+
+ /**
+ * No data is sent to the socket as the data is encoded into
+ * the URL.
+ * @param SimpleSocket $socket Socket to write to.
+ * @access public
+ */
+ function writeTo($socket) {
+ }
+
+ /**
+ * Renders the query string as a URL encoded
+ * request part for attaching to a URL.
+ * @return string Part of URL.
+ * @access public
+ */
+ function asUrlRequest() {
+ return $this->_encode();
+ }
+ }
+
+ /**
+ * Bundle of URL parameters for a HEAD request.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleHeadEncoding extends SimpleGetEncoding {
+
+ /**
+ * Starts empty.
+ * @param array $query Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function SimpleHeadEncoding($query = false) {
+ $this->SimpleGetEncoding($query);
+ }
+
+ /**
+ * HTTP request method.
+ * @return string Always HEAD.
+ * @access public
+ */
+ function getMethod() {
+ return 'HEAD';
+ }
+ }
+
+ /**
+ * Bundle of POST parameters. Can include
+ * repeated parameters.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimplePostEncoding extends SimpleEncoding {
+
+ /**
+ * Starts empty.
+ * @param array $query Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function SimplePostEncoding($query = false) {
+ $this->SimpleEncoding($query);
+ }
+
+ /**
+ * HTTP request method.
+ * @return string Always POST.
+ * @access public
+ */
+ function getMethod() {
+ return 'POST';
+ }
+
+ /**
+ * Dispatches the form headers down the socket.
+ * @param SimpleSocket $socket Socket to write to.
+ * @access public
+ */
+ function writeHeadersTo($socket) {
+ $socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n");
+ $socket->write("Content-Type: application/x-www-form-urlencoded\r\n");
+ }
+
+ /**
+ * Dispatches the form data down the socket.
+ * @param SimpleSocket $socket Socket to write to.
+ * @access public
+ */
+ function writeTo($socket) {
+ $socket->write($this->_encode());
+ }
+
+ /**
+ * Renders the query string as a URL encoded
+ * request part for attaching to a URL.
+ * @return string Part of URL.
+ * @access public
+ */
+ function asUrlRequest() {
+ return '';
+ }
+ }
+
+ /**
+ * Bundle of POST parameters in the multipart
+ * format. Can include file uploads.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleMultipartEncoding extends SimplePostEncoding {
+ protected $_boundary;
+
+ /**
+ * Starts empty.
+ * @param array $query Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function SimpleMultipartEncoding($query = false, $boundary = false) {
+ $this->SimplePostEncoding($query);
+ $this->_boundary = ($boundary === false ? uniqid('st') : $boundary);
}
/**
- * Accessor for key list.
- * @return array List of keys present.
+ * Dispatches the form headers down the socket.
+ * @param SimpleSocket $socket Socket to write to.
* @access public
*/
- function getKeys() {
- return array_keys($this->_request);
+ function writeHeadersTo($socket) {
+ $socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n");
+ $socket->write("Content-Type: multipart/form-data, boundary=" . $this->_boundary . "\r\n");
+ }
+
+ /**
+ * Dispatches the form data down the socket.
+ * @param SimpleSocket $socket Socket to write to.
+ * @access public
+ */
+ function writeTo($socket) {
+ $socket->write($this->_encode());
}
/**
@@ -142,15 +508,14 @@
* @return string Part of URL.
* @access public
*/
- function asString() {
- $statements = array();
- foreach ($this->_request as $key => $values) {
- foreach ($values as $value) {
- $statements[] = "$key=" . urlencode($value);
- }
+ function _encode() {
+ $stream = '';
+ foreach ($this->_request as $pair) {
+ $stream .= "--" . $this->_boundary . "\r\n";
+ $stream .= $pair->asMime() . "\r\n";
}
- $coords = ($this->_x !== false) ? '?' . $this->_x . ',' . $this->_y : '';
- return implode('&', $statements) . $coords;
+ $stream .= "--" . $this->_boundary . "--\r\n";
+ return $stream;
}
}
?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/errors.php b/tests/test_tools/simpletest/errors.php
index 70c6c338..b32cd5fe 100644
--- a/tests/test_tools/simpletest/errors.php
+++ b/tests/test_tools/simpletest/errors.php
@@ -3,13 +3,54 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
- * @version $Id: errors.php,v 1.13 2005/01/08 03:48:39 lastcraft Exp $
+ * @version $Id: errors.php,v 1.14 2006/02/06 06:05:18 lastcraft Exp $
*/
+
/** @ignore - PHP5 compatibility fix. */
if (! defined('E_STRICT')) {
define('E_STRICT', 2048);
}
-
+
+ /**#@+
+ * Includes SimpleTest files.
+ */
+ require_once(dirname(__FILE__) . '/invoker.php');
+
+ /**
+ * Extension that traps errors into an error queue.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleErrorTrappingInvoker extends SimpleInvokerDecorator {
+
+ /**
+ * Stores the invoker to wrap.
+ * @param SimpleInvoker $invoker Test method runner.
+ */
+ function SimpleErrorTrappingInvoker($invoker) {
+ $this->SimpleInvokerDecorator($invoker);
+ }
+
+ /**
+ * Invokes a test method and dispatches any
+ * untrapped errors. Called back from
+ * the visiting runner.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function invoke($method) {
+ set_error_handler('simpleTestErrorHandler');
+ parent::invoke($method);
+ $queue = SimpleErrorQueue::instance();
+ while (list($severity, $message, $file, $line, $globals) = $queue->extract()) {
+ $severity = SimpleErrorQueue::getSeverityAsString($severity);
+ $test_case = $this->getTestCase();
+ $test_case->error($severity, $message, $file, $line);
+ }
+ restore_error_handler();
+ }
+ }
+
/**
* Singleton error queue used to record trapped
* errors.
@@ -18,7 +59,7 @@
*/
class SimpleErrorQueue {
protected $_queue;
-
+
/**
* Starts with an empty queue.
* @access public
@@ -26,7 +67,7 @@
function SimpleErrorQueue() {
$this->clear();
}
-
+
/**
* Adds an error to the front of the queue.
* @param $severity PHP error code.
@@ -41,7 +82,7 @@
$this->_queue,
array($severity, $message, $filename, $line, $super_globals));
}
-
+
/**
* Pulls the earliest error from the queue.
* @return False if none, or a list of error
@@ -57,7 +98,7 @@
}
return false;
}
-
+
/**
* Discards the contents of the error queue.
* @access public
@@ -65,7 +106,7 @@
function clear() {
$this->_queue = array();
}
-
+
/**
* Tests to see if the queue is empty.
* @return True if empty.
@@ -73,7 +114,7 @@
function isEmpty() {
return (count($this->_queue) == 0);
}
-
+
/**
* Global access to a single error queue.
* @return Global error queue object.
@@ -87,7 +128,7 @@
}
return $queue;
}
-
+
/**
* Converst an error code into it's string
* representation.
@@ -96,7 +137,7 @@
* @access public
* @static
*/
- static function getSeverityAsString($severity) {
+ static function getSeverityAsString($severity) {
static $map = array(
E_STRICT => 'E_STRICT',
E_ERROR => 'E_ERROR',
@@ -113,7 +154,7 @@
return $map[$severity];
}
}
-
+
/**
* Error handler that simply stashes any errors into the global
* error queue. Simulates the existing behaviour with respect to
diff --git a/tests/test_tools/simpletest/exceptions.php b/tests/test_tools/simpletest/exceptions.php
new file mode 100644
index 00000000..949f2936
--- /dev/null
+++ b/tests/test_tools/simpletest/exceptions.php
@@ -0,0 +1,46 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: exceptions.php,v 1.1 2006/02/06 06:05:18 lastcraft Exp $
+ */
+
+ /**#@+
+ * Includes SimpleTest files and defined the root constant
+ * for dependent libraries.
+ */
+ require_once(dirname(__FILE__) . '/invoker.php');
+
+ /**
+ * Extension that traps exceptions and turns them into
+ * an error message.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleExceptionTrappingInvoker extends SimpleInvokerDecorator {
+
+ /**
+ * Stores the invoker to be wrapped.
+ * @param SimpleInvoker $invoker Test method runner.
+ */
+ function SimpleExceptionTrappingInvoker($invoker) {
+ $this->SimpleInvokerDecorator($invoker);
+ }
+
+ /**
+ * Invokes a test method and dispatches any
+ * untrapped errors.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function invoke($method) {
+ try {
+ parent::invoke($method);
+ } catch (Exception $exception) {
+ $test_case = $this->getTestCase();
+ $test_case->exception($exception);
+ }
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/expectation.php b/tests/test_tools/simpletest/expectation.php
index 355963b4..b2eca0d8 100644
--- a/tests/test_tools/simpletest/expectation.php
+++ b/tests/test_tools/simpletest/expectation.php
@@ -1,23 +1,23 @@
<?php
/**
- * base include file for SimpleTest
- * @package SimpleTest
- * @subpackage UnitTester
- * @version $Id: expectation.php,v 1.35 2005/01/23 22:20:43 lastcraft Exp $
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: expectation.php,v 1.43 2006/02/05 02:04:24 lastcraft Exp $
*/
/**#@+
- * include other SimpleTest class files
+ * include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/dumper.php');
- require_once(dirname(__FILE__) . '/options.php');
+ require_once(dirname(__FILE__) . '/compatibility.php');
/**#@-*/
/**
* Assertion that can display failure information.
* Also includes various helper methods.
- * @package SimpleTest
- * @subpackage UnitTester
+ * @package SimpleTest
+ * @subpackage UnitTester
* @abstract
*/
class SimpleExpectation {
@@ -57,7 +57,7 @@
/**
* Overlays the generated message onto the stored user
- * message.
+ * message. An additional message can be interjected.
* @param mixed $compare Comparison value.
* @return string Description of success
* or failure.
@@ -72,15 +72,30 @@
* @return SimpleDumper Current value dumper.
* @access protected
*/
- function _getDumper() {
+ function &_getDumper() {
return $this->_dumper;
}
+
+ /**
+ * Test to see if a value is an expectation object.
+ * A useful utility method.
+ * @param mixed $expectation Hopefully an Epectation
+ * class.
+ * @return boolean True if descended from
+ * this class.
+ * @access public
+ * @static
+ */
+ function isExpectation($expectation) {
+ return is_object($expectation) &&
+ SimpleTestCompatibility::isA($expectation, 'SimpleExpectation');
+ }
}
/**
* Test for equality.
- * @package SimpleTest
- * @subpackage UnitTester
+ * @package SimpleTest
+ * @subpackage UnitTester
*/
class EqualExpectation extends SimpleExpectation {
protected $_value;
@@ -135,8 +150,8 @@
/**
* Test for inequality.
- * @package SimpleTest
- * @subpackage UnitTester
+ * @package SimpleTest
+ * @subpackage UnitTester
*/
class NotEqualExpectation extends EqualExpectation {
@@ -182,9 +197,130 @@
}
/**
+ * Test for being within a range.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class WithinMarginExpectation extends SimpleExpectation {
+ protected $_upper;
+ protected $_lower;
+
+ /**
+ * Sets the value to compare against and the fuzziness of
+ * the match. Used for comparing floating point values.
+ * @param mixed $value Test value to match.
+ * @param mixed $margin Fuzziness of match.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function WithinMarginExpectation($value, $margin, $message = '%s') {
+ $this->SimpleExpectation($message);
+ $this->_upper = $value + $margin;
+ $this->_lower = $value - $margin;
+ }
+
+ /**
+ * Tests the expectation. True if it matches the
+ * held value.
+ * @param mixed $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return (($compare <= $this->_upper) && ($compare >= $this->_lower));
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ if ($this->test($compare)) {
+ return $this->_withinMessage($compare);
+ } else {
+ return $this->_outsideMessage($compare);
+ }
+ }
+
+ /**
+ * Creates a the message for being within the range.
+ * @param mixed $compare Value being tested.
+ * @access private
+ */
+ function _withinMessage($compare) {
+ return "Within expectation [" . $this->_dumper->describeValue($this->_lower) . "] and [" .
+ $this->_dumper->describeValue($this->_upper) . "]";
+ }
+
+ /**
+ * Creates a the message for being within the range.
+ * @param mixed $compare Value being tested.
+ * @access private
+ */
+ function _outsideMessage($compare) {
+ if ($compare > $this->_upper) {
+ return "Outside expectation " .
+ $this->_dumper->describeDifference($compare, $this->_upper);
+ } else {
+ return "Outside expectation " .
+ $this->_dumper->describeDifference($compare, $this->_lower);
+ }
+ }
+ }
+
+ /**
+ * Test for being outside of a range.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class OutsideMarginExpectation extends WithinMarginExpectation {
+
+ /**
+ * Sets the value to compare against and the fuzziness of
+ * the match. Used for comparing floating point values.
+ * @param mixed $value Test value to not match.
+ * @param mixed $margin Fuzziness of match.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function OutsideMarginExpectation($value, $margin, $message = '%s') {
+ $this->WithinMarginExpectation($value, $margin, $message);
+ }
+
+ /**
+ * Tests the expectation. True if it matches the
+ * held value.
+ * @param mixed $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return ! parent::test($compare);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ if (! $this->test($compare)) {
+ return $this->_withinMessage($compare);
+ } else {
+ return $this->_outsideMessage($compare);
+ }
+ }
+ }
+
+ /**
* Test for identity.
- * @package SimpleTest
- * @subpackage UnitTester
+ * @package SimpleTest
+ * @subpackage UnitTester
*/
class IdenticalExpectation extends EqualExpectation {
@@ -231,8 +367,8 @@
/**
* Test for non-identity.
- * @package SimpleTest
- * @subpackage UnitTester
+ * @package SimpleTest
+ * @subpackage UnitTester
*/
class NotIdenticalExpectation extends IdenticalExpectation {
@@ -277,10 +413,10 @@
/**
* Test for a pattern using Perl regex rules.
- * @package SimpleTest
- * @subpackage UnitTester
+ * @package SimpleTest
+ * @subpackage UnitTester
*/
- class WantedPatternExpectation extends SimpleExpectation {
+ class PatternExpectation extends SimpleExpectation {
protected $_pattern;
/**
@@ -289,7 +425,7 @@
* @param string $message Customised message on failure.
* @access public
*/
- function WantedPatternExpectation($pattern, $message = '%s') {
+ function PatternExpectation($pattern, $message = '%s') {
$this->SimpleExpectation($message);
$this->_pattern = $pattern;
}
@@ -335,6 +471,8 @@
/**
* Describes a pattern match including the string
* found and it's position.
+ * @package SimpleTest
+ * @subpackage UnitTester
* @param string $pattern Regex to match against.
* @param string $subject Subject to search.
* @access protected
@@ -351,12 +489,18 @@
}
/**
+ * @deprecated
+ */
+ class WantedPatternExpectation extends PatternExpectation {
+ }
+
+ /**
* Fail if a pattern is detected within the
* comparison.
- * @package SimpleTest
- * @subpackage UnitTester
+ * @package SimpleTest
+ * @subpackage UnitTester
*/
- class UnwantedPatternExpectation extends WantedPatternExpectation {
+ class NoPatternExpectation extends PatternExpectation {
/**
* Sets the reject pattern
@@ -364,8 +508,8 @@
* @param string $message Customised message on failure.
* @access public
*/
- function UnwantedPatternExpectation($pattern, $message = '%s') {
- $this->WantedPatternExpectation($pattern, $message);
+ function NoPatternExpectation($pattern, $message = '%s') {
+ $this->PatternExpectation($pattern, $message);
}
/**
@@ -399,9 +543,17 @@
}
/**
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @deprecated
+ */
+ class UnwantedPatternExpectation extends NoPatternExpectation {
+ }
+
+ /**
* Tests either type or class name if it's an object.
- * @package SimpleTest
- * @subpackage UnitTester
+ * @package SimpleTest
+ * @subpackage UnitTester
*/
class IsAExpectation extends SimpleExpectation {
protected $_type;
@@ -477,8 +629,8 @@
/**
* Tests either type or class name if it's an object.
* Will succeed if the type does not match.
- * @package SimpleTest
- * @subpackage UnitTester
+ * @package SimpleTest
+ * @subpackage UnitTester
*/
class NotAExpectation extends IsAExpectation {
protected $_type;
@@ -520,8 +672,8 @@
/**
* Tests for existance of a method in an object
- * @package SimpleTest
- * @subpackage UnitTester
+ * @package SimpleTest
+ * @subpackage UnitTester
*/
class MethodExistsExpectation extends SimpleExpectation {
protected $_method;
@@ -556,13 +708,13 @@
* @access public
*/
function testMessage($compare) {
- $dumper = $this->_getDumper();
- if (! is_object($compare)) {
- return 'No method on non-object [' . $dumper->describeValue($compare) . ']';
- }
- $method = $this->_method;
- return "Object [" . $dumper->describeValue($compare) .
- "] should contain method [$method]";
+ $dumper = $this->_getDumper();
+ if (! is_object($compare)) {
+ return 'No method on non-object [' . $dumper->describeValue($compare) . ']';
+ }
+ $method = $this->_method;
+ return "Object [" . $dumper->describeValue($compare) .
+ "] should contain method [$method]";
}
}
-?> \ No newline at end of file
+?>
diff --git a/tests/test_tools/simpletest/extensions/pear_test_case.php b/tests/test_tools/simpletest/extensions/pear_test_case.php
deleted file mode 100755
index 51727345..00000000
--- a/tests/test_tools/simpletest/extensions/pear_test_case.php
+++ /dev/null
@@ -1,199 +0,0 @@
-<?php
- /**
- * adapter for SimpleTest to use PEAR PHPUnit test cases
- * @package SimpleTest
- * @subpackage Extensions
- * @version $Id: pear_test_case.php,v 1.4 2005/01/13 01:31:57 lastcraft Exp $
- */
-
- /**#@+
- * include SimpleTest files
- */
- require_once dirname(__FILE__) . '/../dumper.php';
- require_once dirname(__FILE__) . '/../options.php';
- require_once dirname(__FILE__) . '/../simple_test.php';
- require_once dirname(__FILE__) . '/../expectation.php';
- /**#@-*/
-
- /**
- * Adapter for PEAR PHPUnit test case to allow
- * legacy PEAR test cases to be used with SimpleTest.
- * @package SimpleTest
- * @subpackage Extensions
- */
- class PHPUnit_TestCase extends SimpleTestCase {
- var $_loosely_typed;
-
- /**
- * Constructor. Sets the test name.
- * @param $label Test name to display.
- * @public
- */
- function PHPUnit_TestCase($label = false) {
- $this->SimpleTestCase($label);
- $this->_loosely_typed = false;
- }
-
- /**
- * Will test straight equality if set to loose
- * typing, or identity if not.
- * @param $first First value.
- * @param $second Comparison value.
- * @param $message Message to display.
- * @public
- */
- function assertEquals($first, $second, $message = "%s", $delta = 0) {
- if ($this->_loosely_typed) {
- $expectation = &new EqualExpectation($first);
- } else {
- $expectation = &new IdenticalExpectation($first);
- }
- $this->assertExpectation($expectation, $second, $message);
- }
-
- /**
- * Passes if the value tested is not null.
- * @param $value Value to test against.
- * @param $message Message to display.
- * @public
- */
- function assertNotNull($value, $message = "%s") {
- parent::assertTrue(isset($value), $message);
- }
-
- /**
- * Passes if the value tested is null.
- * @param $value Value to test against.
- * @param $message Message to display.
- * @public
- */
- function assertNull($value, $message = "%s") {
- parent::assertTrue(!isset($value), $message);
- }
-
- /**
- * In PHP5 the identity test tests for the same
- * object. This is a reference test in PHP4.
- * @param $first First object handle.
- * @param $second Hopefully the same handle.
- * @param $message Message to display.
- * @public
- */
- function assertSame(&$first, &$second, $message = "%s") {
- $dumper = &new SimpleDumper();
- $message = sprintf(
- $message,
- "[" . $dumper->describeValue($first) .
- "] and [" . $dumper->describeValue($second) .
- "] should reference the same object");
- return $this->assertTrue(
- SimpleTestCompatibility::isReference($first, $second),
- $message);
- }
-
- /**
- * In PHP5 the identity test tests for the same
- * object. This is a reference test in PHP4.
- * @param $first First object handle.
- * @param $second Hopefully a different handle.
- * @param $message Message to display.
- * @public
- */
- function assertNotSame(&$first, &$second, $message = "%s") {
- $dumper = &new SimpleDumper();
- $message = sprintf(
- $message,
- "[" . $dumper->describeValue($first) .
- "] and [" . $dumper->describeValue($second) .
- "] should not be the same object");
- return $this->assertFalse(
- SimpleTestCompatibility::isReference($first, $second),
- $message);
- }
-
- /**
- * Sends pass if the test condition resolves true,
- * a fail otherwise.
- * @param $condition Condition to test true.
- * @param $message Message to display.
- * @public
- */
- function assertTrue($condition, $message = "%s") {
- parent::assertTrue($condition, $message);
- }
-
- /**
- * Sends pass if the test condition resolves false,
- * a fail otherwise.
- * @param $condition Condition to test false.
- * @param $message Message to display.
- * @public
- */
- function assertFalse($condition, $message = "%s") {
- parent::assertTrue(!$condition, $message);
- }
-
- /**
- * Tests a regex match. Needs refactoring.
- * @param $pattern Regex to match.
- * @param $subject String to search in.
- * @param $message Message to display.
- * @public
- */
- function assertRegExp($pattern, $subject, $message = "%s") {
- $this->assertExpectation(
- new WantedPatternExpectation($pattern),
- $subject,
- $message);
- }
-
- /**
- * Tests the type of a value.
- * @param $value Value to take type of.
- * @param $type Hoped for type.
- * @param $message Message to display.
- * @public
- */
- function assertType($value, $type, $message = "%s") {
- parent::assertTrue(gettype($value) == strtolower($type), $message);
- }
-
- /**
- * Sets equality operation to act as a simple equal
- * comparison only, allowing a broader range of
- * matches.
- * @param $loosely_typed True for broader comparison.
- * @public
- */
- function setLooselyTyped($loosely_typed) {
- $this->_loosely_typed = $loosely_typed;
- }
-
- /**
- * For progress indication during
- * a test amongst other things.
- * @return Usually one.
- * @public
- */
- function countTestCases() {
- return $this->getSize();
- }
-
- /**
- * Accessor for name, normally just the class
- * name.
- * @public
- */
- function getName() {
- return $this->getLabel();
- }
-
- /**
- * Does nothing. For compatibility only.
- * @param $name Dummy
- * @public
- */
- function setName($name) {
- }
- }
-?>
diff --git a/tests/test_tools/simpletest/extensions/phpunit_test_case.php b/tests/test_tools/simpletest/extensions/phpunit_test_case.php
deleted file mode 100755
index a0954d8b..00000000
--- a/tests/test_tools/simpletest/extensions/phpunit_test_case.php
+++ /dev/null
@@ -1,108 +0,0 @@
-<?php
- /**
- * adapter for SimpleTest to use PHPUnit test cases
- * @package SimpleTest
- * @subpackage Extensions
- * @version $Id: phpunit_test_case.php,v 1.3 2004/04/23 03:11:56 jsweat Exp $
- */
-
- /**#@+
- * include SimpleTest files
- */
- require_once dirname(__FILE__).DIRECTORY_SEPARATOR
- .'..'.DIRECTORY_SEPARATOR . 'unit_tester.php';
- require_once dirname(__FILE__).DIRECTORY_SEPARATOR
- .'..'.DIRECTORY_SEPARATOR . 'expectation.php';
- /**#@-*/
-
- /**
- * Adapter for sourceforge PHPUnit test case to allow
- * legacy test cases to be used with SimpleTest.
- * @package SimpleTest
- * @subpackage Extensions
- */
- class TestCase extends SimpleTestCase {
-
- /**
- * Constructor. Sets the test name.
- * @param $label Test name to display.
- * @public
- */
- function TestCase($label) {
- $this->SimpleTestCase($label);
- }
-
- /**
- * Sends pass if the test condition resolves true,
- * a fail otherwise.
- * @param $condition Condition to test true.
- * @param $message Message to display.
- * @public
- */
- function assert($condition, $message = false) {
- parent::assertTrue($condition, $message);
- }
-
- /**
- * Will test straight equality if set to loose
- * typing, or identity if not.
- * @param $first First value.
- * @param $second Comparison value.
- * @param $message Message to display.
- * @public
- */
- function assertEquals($first, $second, $message = false) {
- $this->assertExpectation(
- new EqualExpectation($first),
- $second,
- $message);
- }
-
- /**
- * Will test straight equality if set to loose
- * typing, or identity if not.
- * @param $first First value.
- * @param $second Comparison value.
- * @param $message Message to display.
- * @public
- */
- function assertEqualsMultilineStrings($first, $second, $message = false) {
- $this->assertExpectation(
- new EqualExpectation($first),
- $second,
- $message);
- }
-
- /**
- * Tests a regex match.
- * @param $pattern Regex to match.
- * @param $subject String to search in.
- * @param $message Message to display.
- * @public
- */
- function assertRegexp($pattern, $subject, $message = false) {
- $this->assertExpectation(
- new WantedPatternExpectation($pattern),
- $subject,
- $message);
- }
-
- /**
- * Sends an error which we interpret as a fail
- * with a different message for compatibility.
- * @param $message Message to display.
- * @public
- */
- function error($message) {
- parent::assertTrue(false, "Error triggered [$message]");
- }
-
- /**
- * Accessor for name.
- * @public
- */
- function name() {
- return $this->getLabel();
- }
- }
-?>
diff --git a/tests/test_tools/simpletest/form.php b/tests/test_tools/simpletest/form.php
index 89b4948a..0d071105 100644
--- a/tests/test_tools/simpletest/form.php
+++ b/tests/test_tools/simpletest/form.php
@@ -3,7 +3,7 @@
* Base include file for SimpleTest.
* @package SimpleTest
* @subpackage WebTester
- * @version $Id: form.php,v 1.16 2005/02/22 02:17:04 lastcraft Exp $
+ * @version $Id: form.php,v 1.40 2006/01/24 01:11:55 lastcraft Exp $
*/
/**#@+
@@ -11,91 +11,10 @@
*/
require_once(dirname(__FILE__) . '/tag.php');
require_once(dirname(__FILE__) . '/encoding.php');
+ require_once(dirname(__FILE__) . '/selector.php');
/**#@-*/
/**
- * Used to extract form elements for testing against.
- * Searches by name attribute.
- * @package SimpleTest
- * @subpackage WebTester
- */
- class SimpleNameSelector {
- protected $_name;
-
- /**
- * Stashes the name for later comparison.
- * @param string $name Name attribute to match.
- */
- function SimpleNameSelector($name) {
- $this->_name = $name;
- }
-
- /**
- * Comparison. Compares with name attribute of
- * widget.
- * @param SimpleWidget $widget Control to compare.
- * @access public
- */
- function isMatch($widget) {
- return ($widget->getName() == $this->_name);
- }
- }
-
- /**
- * Used to extract form elements for testing against.
- * Searches by visible label or alt text.
- * @package SimpleTest
- * @subpackage WebTester
- */
- class SimpleLabelSelector {
- protected $_label;
-
- /**
- * Stashes the name for later comparison.
- * @param string $label Visible text to match.
- */
- function SimpleLabelSelector($label) {
- $this->_label = $label;
- }
-
- /**
- * Comparison. Compares visible text of widget.
- * @param SimpleWidget $widget Control to compare.
- * @access public
- */
- function isMatch($widget) {
- return (trim($widget->getLabel()) == trim($this->_label));
- }
- }
-
- /**
- * Used to extract form elements for testing against.
- * Searches dy id attribute.
- * @package SimpleTest
- * @subpackage WebTester
- */
- class SimpleIdSelector {
- protected $_id;
-
- /**
- * Stashes the name for later comparison.
- * @param string $id ID atribute to match.
- */
- function SimpleIdSelector($id) {
- $this->_id = $id;
- }
-
- /**
- * Comparison. Compares id attribute of widget.
- * @param SimpleWidget $widget Control to compare.
- * @access public
- */
- function isMatch($widget) {
- return $widget->isId($this->_id);
- }
- }
-
- /**
* Form tag class to hold widget values.
* @package SimpleTest
* @subpackage WebTester
@@ -103,6 +22,7 @@
class SimpleForm {
protected $_method;
protected $_action;
+ protected $_encoding;
protected $_default_target;
protected $_id;
protected $_buttons;
@@ -119,6 +39,7 @@
function SimpleForm($tag, $url) {
$this->_method = $tag->getAttribute('method');
$this->_action = $this->_createAction($tag->getAttribute('action'), $url);
+ $this->_encoding = $this->_setEncodingClass($tag);
$this->_default_target = false;
$this->_id = $tag->getAttribute('id');
$this->_buttons = array();
@@ -129,6 +50,22 @@
}
/**
+ * Creates the request packet to be sent by the form.
+ * @param SimpleTag $tag Form tag to read.
+ * @return string Packet class.
+ * @access private
+ */
+ function _setEncodingClass($tag) {
+ if (strtolower($tag->getAttribute('method')) == 'post') {
+ if (strtolower($tag->getAttribute('enctype')) == 'multipart/form-data') {
+ return 'SimpleMultipartEncoding';
+ }
+ return 'SimplePostEncoding';
+ }
+ return 'SimpleGetEncoding';
+ }
+
+ /**
* Sets the frame target within a frameset.
* @param string $frame Name of frame.
* @access public
@@ -138,7 +75,7 @@
}
/**
- * Accessor for form action.
+ * Accessor for method of form submission.
* @return string Either get or post.
* @access public
*/
@@ -154,14 +91,10 @@
* @return SimpleUrl Absolute form target.
*/
function _createAction($action, $base) {
- if ($action === false) {
+ if (($action === '') || ($action === false)) {
return $base;
}
- if ($action === true) {
- $url = new SimpleUrl('');
- } else {
- $url = new SimpleUrl($action);
- }
+ $url = new SimpleUrl($action);
return $url->makeAbsolute($base);
}
@@ -177,7 +110,22 @@
}
return $url;
}
-
+
+ /**
+ * Creates the encoding for the current values in the
+ * form.
+ * @return SimpleFormEncoding Request to submit.
+ * @access private
+ */
+ function _encode() {
+ $class = $this->_encoding;
+ $encoding = new $class();
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ $this->_widgets[$i]->write($encoding);
+ }
+ return $encoding;
+ }
+
/**
* ID field of form for unique identification.
* @return string Unique tag ID.
@@ -258,7 +206,7 @@
* if not set.
* @access public
*/
- function _getValueBySelector($selector) {
+ function getValue($selector) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($selector->isMatch($this->_widgets[$i])) {
return $this->_widgets[$i]->getValue();
@@ -273,28 +221,6 @@
}
/**
- * 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.
@@ -303,7 +229,7 @@
* present, nothing will be set.
* @access public
*/
- function _setFieldBySelector($selector, $value) {
+ function setField($selector, $value) {
$success = false;
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
if ($selector->isMatch($this->_widgets[$i])) {
@@ -316,54 +242,29 @@
}
/**
- * Sets a widget value within the form.
- * @param string $name Name of widget tag.
- * @param string $value Value to input into the widget.
- * @return boolean True if value is legal, false
- * otherwise. If the field is not
- * present, nothing will be set.
- * @access public
- */
- function setField($name, $value) {
- return $this->_setFieldBySelector(new SimpleNameSelector($name), $value);
- }
-
- /**
- * Sets a widget value within the form by using the ID.
- * @param string/integer $id Name of widget tag.
- * @param string $value Value to input into the widget.
- * @return boolean True if value is legal, false
- * otherwise. If the field is not
- * present, nothing will be set.
+ * Used by the page object to set widgets labels to
+ * external label tags.
+ * @param SimpleSelector $selector Criteria to apply.
* @access public
*/
- function setFieldById($id, $value) {
- return $this->_setFieldBySelector(new SimpleIdSelector($id), $value);
- }
-
- /**
- * Creates the encoding for the current values in the
- * form.
- * @return SimpleFormEncoding Request to submit.
- * @access private
- */
- function _getEncoding() {
- $encoding = new SimpleFormEncoding();
+ function attachLabelBySelector($selector, $label) {
for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
- $encoding->add(
- $this->_widgets[$i]->getName(),
- $this->_widgets[$i]->getValue());
+ if ($selector->isMatch($this->_widgets[$i])) {
+ if (method_exists($this->_widgets[$i], 'setLabel')) {
+ $this->_widgets[$i]->setLabel($label);
+ return;
+ }
+ }
}
- return $encoding;
}
/**
* Test to see if a form has a submit button.
* @param SimpleSelector $selector Criteria to apply.
* @return boolean True if present.
- * @access private
+ * @access public
*/
- function _hasSubmitBySelector($selector) {
+ function hasSubmit($selector) {
foreach ($this->_buttons as $button) {
if ($selector->isMatch($button)) {
return true;
@@ -373,45 +274,12 @@
}
/**
- * Test to see if a form has a submit button with this
- * name attribute.
- * @param string $name Name to look for.
- * @return boolean True if present.
- * @access public
- */
- function hasSubmitName($name) {
- return $this->_hasSubmitBySelector(new SimpleNameSelector($name));
- }
-
- /**
- * Test to see if a form has a submit button with this
- * value attribute.
- * @param string $label Button label to search for.
- * @return boolean True if present.
- * @access public
- */
- function hasSubmitLabel($label) {
- return $this->_hasSubmitBySelector(new SimpleLabelSelector($label));
- }
-
- /**
- * Test to see if a form has a submit button with this
- * ID attribute.
- * @param string $id Button ID attribute to search for.
- * @return boolean True if present.
- * @access public
- */
- function hasSubmitId($id) {
- return $this->_hasSubmitBySelector(new SimpleIdSelector($id));
- }
-
- /**
* Test to see if a form has an image control.
* @param SimpleSelector $selector Criteria to apply.
* @return boolean True if present.
* @access public
*/
- function _hasImageBySelector($selector) {
+ function hasImage($selector) {
foreach ($this->_images as $image) {
if ($selector->isMatch($image)) {
return true;
@@ -419,40 +287,6 @@
}
return false;
}
-
- /**
- * Test to see if a form has a submit button with this
- * name attribute.
- * @param string $label Button alt attribute to search for
- * or nearest equivalent.
- * @return boolean True if present.
- * @access public
- */
- function hasImageLabel($label) {
- return $this->_hasImageBySelector(new SimpleLabelSelector($label));
- }
-
- /**
- * Test to see if a form has a submittable image with this
- * field name.
- * @param string $name Image name to search for.
- * @return boolean True if present.
- * @access public
- */
- function hasImageName($name) {
- return $this->_hasImageBySelector(new SimpleNameSelector($name));
- }
-
- /**
- * Test to see if a form has a submittable image with this
- * ID attribute.
- * @param string $id Button ID attribute to search for.
- * @return boolean True if present.
- * @access public
- */
- function hasImageId($id) {
- return $this->_hasImageBySelector(new SimpleIdSelector($id));
- }
/**
* Gets the submit values for a selected button.
@@ -463,11 +297,12 @@
* in the form.
* @access public
*/
- function _submitButtonBySelector($selector, $additional) {
+ function submitButton($selector, $additional = false) {
+ $additional = $additional ? $additional : array();
foreach ($this->_buttons as $button) {
if ($selector->isMatch($button)) {
- $encoding = $this->_getEncoding();
- $encoding->merge($button->getSubmitValues());
+ $encoding = $this->_encode();
+ $button->write($encoding);
if ($additional) {
$encoding->merge($additional);
}
@@ -476,51 +311,6 @@
}
return false;
}
-
- /**
- * Gets the submit values for a named button.
- * @param string $name Button label to search for.
- * @param hash $additional Additional data for the form.
- * @return SimpleEncoding Submitted values or false
- * if there is no such button in the
- * form.
- * @access public
- */
- function submitButtonByName($name, $additional = false) {
- return $this->_submitButtonBySelector(
- new SimpleNameSelector($name),
- $additional);
- }
-
- /**
- * Gets the submit values for a named button.
- * @param string $label Button label to search for.
- * @param hash $additional Additional data for the form.
- * @return SimpleEncoding Submitted values or false
- * if there is no such button in the
- * form.
- * @access public
- */
- function submitButtonByLabel($label, $additional = false) {
- return $this->_submitButtonBySelector(
- new SimpleLabelSelector($label),
- $additional);
- }
-
- /**
- * Gets the submit values for a button identified by the ID.
- * @param string $id Button ID attribute to search for.
- * @param hash $additional Additional data for the form.
- * @return SimpleEncoding Submitted values or false
- * if there is no such button in the
- * form.
- * @access public
- */
- function submitButtonById($id, $additional = false) {
- return $this->_submitButtonBySelector(
- new SimpleIdSelector($id),
- $additional);
- }
/**
* Gets the submit values for an image.
@@ -533,11 +323,12 @@
* form.
* @access public
*/
- function _submitImageBySelector($selector, $x, $y, $additional) {
+ function submitImage($selector, $x, $y, $additional = false) {
+ $additional = $additional ? $additional : array();
foreach ($this->_images as $image) {
if ($selector->isMatch($image)) {
- $encoding = $this->_getEncoding();
- $encoding->merge($image->getSubmitValues($x, $y));
+ $encoding = $this->_encode();
+ $image->write($encoding, $x, $y);
if ($additional) {
$encoding->merge($additional);
}
@@ -546,64 +337,6 @@
}
return false;
}
-
- /**
- * Gets the submit values for an image identified by the alt
- * tag or nearest equivalent.
- * @param string $label Button label to search for.
- * @param integer $x X-coordinate of click.
- * @param integer $y Y-coordinate of click.
- * @param hash $additional Additional data for the form.
- * @return SimpleEncoding Submitted values or false
- * if there is no such button in the
- * form.
- * @access public
- */
- function submitImageByLabel($label, $x, $y, $additional = false) {
- return $this->_submitImageBySelector(
- new SimpleLabelSelector($label),
- $x,
- $y,
- $additional);
- }
-
- /**
- * Gets the submit values for an image identified by the ID.
- * @param string $name Image name to search for.
- * @param integer $x X-coordinate of click.
- * @param integer $y Y-coordinate of click.
- * @param hash $additional Additional data for the form.
- * @return SimpleEncoding Submitted values or false
- * if there is no such button in the
- * form.
- * @access public
- */
- function submitImageByName($name, $x, $y, $additional = false) {
- return $this->_submitImageBySelector(
- new SimpleNameSelector($name),
- $x,
- $y,
- $additional);
- }
-
- /**
- * Gets the submit values for an image identified by the ID.
- * @param string/integer $id Button ID attribute to search for.
- * @param integer $x X-coordinate of click.
- * @param integer $y Y-coordinate of click.
- * @param hash $additional Additional data for the form.
- * @return SimpleEncoding Submitted values or false
- * if there is no such button in the
- * form.
- * @access public
- */
- function submitImageById($id, $x, $y, $additional = false) {
- return $this->_submitImageBySelector(
- new SimpleIdSelector($id),
- $x,
- $y,
- $additional);
- }
/**
* Simply submits the form without the submit button
@@ -613,7 +346,7 @@
* @access public
*/
function submit() {
- return $this->_getEncoding();
+ return $this->_encode();
}
}
-?> \ No newline at end of file
+?>
diff --git a/tests/test_tools/simpletest/frames.php b/tests/test_tools/simpletest/frames.php
index 75951476..8eefbe8d 100644
--- a/tests/test_tools/simpletest/frames.php
+++ b/tests/test_tools/simpletest/frames.php
@@ -3,7 +3,7 @@
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
- * @version $Id: frames.php,v 1.29 2004/11/30 05:33:56 lastcraft Exp $
+ * @version $Id: frames.php,v 1.39 2005/09/09 01:42:29 lastcraft Exp $
*/
/**#@+
@@ -12,7 +12,7 @@
require_once(dirname(__FILE__) . '/page.php');
require_once(dirname(__FILE__) . '/user_agent.php');
/**#@-*/
-
+
/**
* A composite page. Wraps a frameset page and
* adds subframes. The original page will be
@@ -26,7 +26,7 @@
protected $_frames;
protected $_focus;
protected $_names;
-
+
/**
* Stashes the frameset page. Will make use of the
* browser to fetch the sub frames recursively.
@@ -38,7 +38,7 @@
$this->_focus = false;
$this->_names = array();
}
-
+
/**
* Adds a parsed page to the frameset.
* @param SimplePage $page Frame page.
@@ -51,7 +51,7 @@
$this->_names[$name] = count($this->_frames) - 1;
}
}
-
+
/**
* Replaces existing frame with another. If the
* frame is nested, then the call is passed down
@@ -73,7 +73,7 @@
}
$this->_frames[$index]->setFrame($path, $page);
}
-
+
/**
* Accessor for current frame focus. Will be
* false if no frame has focus. Will have the nested
@@ -89,7 +89,7 @@
array($this->_getPublicNameFromIndex($this->_focus)),
$this->_frames[$this->_focus]->getFrameFocus());
}
-
+
/**
* Turns an internal array index into the frames list
* into a public name, or if none, then a one offset
@@ -106,7 +106,7 @@
}
return $subject + 1;
}
-
+
/**
* Sets the focus by index. The integer index starts from 1.
* If already focused and the target frame also has frames,
@@ -127,7 +127,7 @@
$this->_focus = $choice - 1;
return true;
}
-
+
/**
* Sets the focus by name. If already focused and the
* target frame also has frames, then the nested frame
@@ -148,7 +148,7 @@
}
return false;
}
-
+
/**
* Clears the frame focus.
* @access public
@@ -157,7 +157,7 @@
$this->_focus = false;
$this->_clearNestedFramesFocus();
}
-
+
/**
* Clears the frame focus for any nested frames.
* @access private
@@ -167,7 +167,7 @@
$this->_frames[$i]->clearFrameFocus();
}
}
-
+
/**
* Test for the presence of a frameset.
* @return boolean Always true.
@@ -176,7 +176,7 @@
function hasFrames() {
return true;
}
-
+
/**
* Accessor for frames information.
* @return array/string Recursive hash of frame URL strings.
@@ -192,7 +192,7 @@
}
return $report;
}
-
+
/**
* Accessor for raw text of either all the pages or
* the frame in focus.
@@ -209,7 +209,7 @@
}
return $raw;
}
-
+
/**
* Accessor for plain text of either all the pages or
* the frame in focus.
@@ -226,7 +226,7 @@
}
return trim($raw);
}
-
+
/**
* Accessor for last error.
* @return string Error from last response.
@@ -238,7 +238,7 @@
}
return $this->_frameset->getTransportError();
}
-
+
/**
* Request method used to fetch this frame.
* @return string GET, POST or HEAD.
@@ -250,7 +250,7 @@
}
return $this->_frameset->getMethod();
}
-
+
/**
* Original resource name.
* @return SimpleUrl Current url.
@@ -265,7 +265,7 @@
}
return $url;
}
-
+
/**
* Original request data.
* @return mixed Sent content.
@@ -277,7 +277,7 @@
}
return $this->_frameset->getRequestData();
}
-
+
/**
* Accessor for current MIME type.
* @return string MIME type as string; e.g. 'text/html'
@@ -289,7 +289,7 @@
}
return $this->_frameset->getMimeType();
}
-
+
/**
* Accessor for last response code.
* @return integer Last HTTP response code received.
@@ -301,7 +301,7 @@
}
return $this->_frameset->getResponseCode();
}
-
+
/**
* Accessor for last Authentication type. Only valid
* straight after a challenge (401).
@@ -314,7 +314,7 @@
}
return $this->_frameset->getAuthentication();
}
-
+
/**
* Accessor for last Authentication realm. Only valid
* straight after a challenge (401).
@@ -327,7 +327,7 @@
}
return $this->_frameset->getRealm();
}
-
+
/**
* Accessor for outgoing header information.
* @return string Header block.
@@ -339,7 +339,7 @@
}
return $this->_frameset->getRequest();
}
-
+
/**
* Accessor for raw header information.
* @return string Header block.
@@ -351,7 +351,7 @@
}
return $this->_frameset->getHeaders();
}
-
+
/**
* Accessor for parsed title.
* @return string Title or false if no title is present.
@@ -360,7 +360,7 @@
function getTitle() {
return $this->_frameset->getTitle();
}
-
+
/**
* Accessor for a list of all fixed links.
* @return array List of urls with scheme of
@@ -377,7 +377,7 @@
}
return array_values(array_unique($urls));
}
-
+
/**
* Accessor for a list of all relative links.
* @return array List of urls without hostname.
@@ -393,7 +393,7 @@
}
return array_values(array_unique($urls));
}
-
+
/**
* Accessor for URLs by the link label. Label will match
* regardess of whitespace issues and case.
@@ -417,7 +417,7 @@
}
return $urls;
}
-
+
/**
* Accessor for a URL by the id attribute. If in a frameset
* then the first link found with that ID attribute is
@@ -438,7 +438,7 @@
}
return false;
}
-
+
/**
* Attaches the intended frame index to a list of URLs.
* @param array $urls List of SimpleUrls.
@@ -456,85 +456,35 @@
}
return $tagged;
}
-
- /**
- * Finds a held form by button label. Will only
- * search correctly built forms. The first form found
- * either within the focused frame, or across frames,
- * will be the one returned.
- * @param string $label Button label, default 'Submit'.
- * @return SimpleForm Form object containing the button.
- * @access public
- */
- function getFormBySubmitLabel($label) {
- return $this->_findForm('getFormBySubmitLabel', $label);
- }
-
+
/**
* Finds a held form by button label. Will only
- * search correctly built forms. The first form found
- * either within the focused frame, or across frames,
- * will be the one returned.
- * @param string $name Button name attribute.
- * @return SimpleForm Form object containing the button.
+ * search correctly built forms.
+ * @param SimpleSelector $selector Button finder.
+ * @return SimpleForm Form object containing
+ * the button.
* @access public
*/
- function getFormBySubmitName($name) {
- return $this->_findForm('getFormBySubmitName', $name);
- }
-
- /**
- * Finds a held form by button id. Will only
- * search correctly built forms. The first form found
- * either within the focused frame, or across frames,
- * will be the one returned.
- * @param string $id Button ID attribute.
- * @return SimpleForm Form object containing the button.
- * @access public
- */
- function getFormBySubmitId($id) {
- return $this->_findForm('getFormBySubmitId', $id);
- }
-
- /**
- * Finds a held form by image label. Will only
- * search correctly built forms. The first form found
- * either within the focused frame, or across frames,
- * will be the one returned.
- * @param string $label Usually the alt attribute.
- * @return SimpleForm Form object containing the image.
- * @access public
- */
- function getFormByImageLabel($label) {
- return $this->_findForm('getFormByImageLabel', $label);
- }
-
- /**
- * Finds a held form by image button id. Will only
- * search correctly built forms. The first form found
- * either within the focused frame, or across frames,
- * will be the one returned.
- * @param string $name Image name.
- * @return SimpleForm Form object containing the image.
- * @access public
- */
- function getFormByImageName($name) {
- return $this->_findForm('getFormByImageName', $name);
+ function &getFormBySubmit($selector) {
+ $form = $this->_findForm('getFormBySubmit', $selector);
+ return $form;
}
-
+
/**
- * Finds a held form by image button id. Will only
- * search correctly built forms. The first form found
- * either within the focused frame, or across frames,
- * will be the one returned.
- * @param string $id Image ID attribute.
- * @return SimpleForm Form object containing the image.
+ * Finds a held form by image using a selector.
+ * Will only search correctly built forms. The first
+ * form found either within the focused frame, or
+ * across frames, will be the one returned.
+ * @param SimpleSelector $selector Image finder.
+ * @return SimpleForm Form object containing
+ * the image.
* @access public
*/
- function getFormByImageId($id) {
- return $this->_findForm('getFormByImageId', $id);
+ function &getFormByImage($selector) {
+ $form = $this->_findForm('getFormByImage', $selector);
+ return $form;
}
-
+
/**
* Finds a held form by the form ID. A way of
* identifying a specific form when we have control
@@ -545,25 +495,27 @@
* @return SimpleForm Form object containing the matching ID.
* @access public
*/
- function getFormById($id) {
- return $this->_findForm('getFormById', $id);
+ function &getFormById($id) {
+ $form = $this->_findForm('getFormById', $id);
+ return $form;
}
-
+
/**
* General form finder. Will search all the frames or
* just the one in focus.
* @param string $method Method to use to find in a page.
* @param string $attribute Label, name or ID.
* @return SimpleForm Form object containing the matching ID.
- * @access protected
+ * @access private
*/
- function _findForm($method, $attribute) {
+ function &_findForm($method, $attribute) {
if (is_integer($this->_focus)) {
- return $this->_findFormInFrame(
+ $form = $this->_findFormInFrame(
$this->_frames[$this->_focus],
$this->_focus,
$method,
$attribute);
+ return $form;
}
for ($i = 0; $i < count($this->_frames); $i++) {
$form = $this->_findFormInFrame(
@@ -575,9 +527,10 @@
return $form;
}
}
- return null;
+ $null = null;
+ return $null;
}
-
+
/**
* Finds a form in a page using a form finding method. Will
* also tag the form with the frame name it belongs in.
@@ -586,83 +539,45 @@
* @param string $method Method to use to find in a page.
* @param string $attribute Label, name or ID.
* @return SimpleForm Form object containing the matching ID.
- * @access protected
+ * @access private
*/
- function _findFormInFrame($page, $index, $method, $attribute) {
+ function &_findFormInFrame($page, $index, $method, $attribute) {
$form = $this->_frames[$index]->$method($attribute);
if (isset($form)) {
$form->setDefaultTarget($this->_getPublicNameFromIndex($index));
}
return $form;
}
-
+
/**
* Sets a field on each form in which the field is
* available.
- * @param string $name Field name.
- * @param string $value Value to set field to.
- * @return boolean True if value is valid.
- * @access public
- */
- function setField($name, $value) {
- if (is_integer($this->_focus)) {
- $this->_frames[$this->_focus]->setField($name, $value);
- } else {
- for ($i = 0; $i < count($this->_frames); $i++) {
- $this->_frames[$i]->setField($name, $value);
- }
- }
- }
-
- /**
- * Sets a field on the form in which the unique field is
- * available.
- * @param string/integer $id Field ID attribute.
- * @param string $value Value to set field to.
- * @return boolean True if value is valid.
+ * @param SimpleSelector $selector Field finder.
+ * @param string $value Value to set field to.
+ * @return boolean True if value is valid.
* @access public
*/
- function setFieldById($id, $value) {
+ function setField($selector, $value) {
if (is_integer($this->_focus)) {
- $this->_frames[$this->_focus]->setFieldById($id, $value);
+ $this->_frames[$this->_focus]->setField($selector, $value);
} else {
for ($i = 0; $i < count($this->_frames); $i++) {
- $this->_frames[$i]->setFieldById($id, $value);
+ $this->_frames[$i]->setField($selector, $value);
}
}
}
-
- /**
- * Accessor for a form element value within a frameset.
- * Finds the first match amongst the frames.
- * @param string $name Field name.
- * @return string/boolean A string if the field is
- * present, false if unchecked
- * and null if missing.
- * @access public
- */
- function getField($name) {
- for ($i = 0; $i < count($this->_frames); $i++) {
- $value = $this->_frames[$i]->getField($name);
- if (isset($value)) {
- return $value;
- }
- }
- return null;
- }
-
+
/**
* Accessor for a form element value within a page.
- * Finds the first match.
- * @param string/integer $id Field ID attribute.
- * @return string/boolean A string if the field is
- * present, false if unchecked
- * and null if missing.
+ * @param SimpleSelector $selector Field finder.
+ * @return string/boolean A string if the field is
+ * present, false if unchecked
+ * and null if missing.
* @access public
*/
- function getFieldById($id) {
+ function getField($selector) {
for ($i = 0; $i < count($this->_frames); $i++) {
- $value = $this->_frames[$i]->getFieldById($id);
+ $value = $this->_frames[$i]->getField($selector);
if (isset($value)) {
return $value;
}
diff --git a/tests/test_tools/simpletest/http.php b/tests/test_tools/simpletest/http.php
index fa27de9c..965fac80 100644
--- a/tests/test_tools/simpletest/http.php
+++ b/tests/test_tools/simpletest/http.php
@@ -3,224 +3,18 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
- * @version $Id: http.php,v 1.98 2005/02/02 23:25:23 lastcraft Exp $
+ * @version $Id: http.php,v 1.112 2005/12/07 18:04:58 lastcraft Exp $
*/
/**#@+
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/socket.php');
+ require_once(dirname(__FILE__) . '/cookies.php');
require_once(dirname(__FILE__) . '/url.php');
/**#@-*/
/**
- * Cookie data holder. Cookie rules are full of pretty
- * arbitary stuff. I have used...
- * http://wp.netscape.com/newsref/std/cookie_spec.html
- * http://www.cookiecentral.com/faq/
- * @package SimpleTest
- * @subpackage WebTester
- */
- class SimpleCookie {
- protected $_host;
- protected $_name;
- protected $_value;
- protected $_path;
- protected $_expiry;
- protected $_is_secure;
-
- /**
- * Constructor. Sets the stored values.
- * @param string $name Cookie key.
- * @param string $value Value of cookie.
- * @param string $path Cookie path if not host wide.
- * @param string $expiry Expiry date as string.
- * @param boolean $is_secure Currently ignored.
- */
- function SimpleCookie($name, $value = false, $path = false, $expiry = false, $is_secure = false) {
- $this->_host = false;
- $this->_name = $name;
- $this->_value = $value;
- $this->_path = ($path ? $this->_fixPath($path) : "/");
- $this->_expiry = false;
- if (is_string($expiry)) {
- $this->_expiry = strtotime($expiry);
- } elseif (is_integer($expiry)) {
- $this->_expiry = $expiry;
- }
- $this->_is_secure = $is_secure;
- }
-
- /**
- * Sets the host. The cookie rules determine
- * that the first two parts are taken for
- * certain TLDs and three for others. If the
- * new host does not match these rules then the
- * call will fail.
- * @param string $host New hostname.
- * @return boolean True if hostname is valid.
- * @access public
- */
- function setHost($host) {
- if ($host = $this->_truncateHost($host)) {
- $this->_host = $host;
- return true;
- }
- return false;
- }
-
- /**
- * Accessor for the truncated host to which this
- * cookie applies.
- * @return string Truncated hostname.
- * @access public
- */
- function getHost() {
- return $this->_host;
- }
-
- /**
- * Test for a cookie being valid for a host name.
- * @param string $host Host to test against.
- * @return boolean True if the cookie would be valid
- * here.
- */
- function isValidHost($host) {
- return ($this->_truncateHost($host) === $this->getHost());
- }
-
- /**
- * Extracts just the domain part that determines a
- * cookie's host validity.
- * @param string $host Host name to truncate.
- * @return string Domain or false on a bad host.
- * @access private
- */
- function _truncateHost($host) {
- $tlds = SimpleUrl::getAllTopLevelDomains();
- if (preg_match('/[a-z\-]+\.(' . $tlds . ')$/i', $host, $matches)) {
- return $matches[0];
- } elseif (preg_match('/[a-z\-]+\.[a-z\-]+\.[a-z\-]+$/i', $host, $matches)) {
- return $matches[0];
- }
- return false;
- }
-
- /**
- * Accessor for name.
- * @return string Cookie key.
- * @access public
- */
- function getName() {
- return $this->_name;
- }
-
- /**
- * Accessor for value. A deleted cookie will
- * have an empty string for this.
- * @return string Cookie value.
- * @access public
- */
- function getValue() {
- return $this->_value;
- }
-
- /**
- * Accessor for path.
- * @return string Valid cookie path.
- * @access public
- */
- function getPath() {
- return $this->_path;
- }
-
- /**
- * Tests a path to see if the cookie applies
- * there. The test path must be longer or
- * equal to the cookie path.
- * @param string $path Path to test against.
- * @return boolean True if cookie valid here.
- * @access public
- */
- function isValidPath($path) {
- return (strncmp(
- $this->_fixPath($path),
- $this->getPath(),
- strlen($this->getPath())) == 0);
- }
-
- /**
- * Accessor for expiry.
- * @return string Expiry string.
- * @access public
- */
- function getExpiry() {
- if (! $this->_expiry) {
- return false;
- }
- return gmdate("D, d M Y H:i:s", $this->_expiry) . " GMT";
- }
-
- /**
- * Test to see if cookie is expired against
- * the cookie format time or timestamp.
- * Will give true for a session cookie.
- * @param integer/string $now Time to test against. Result
- * will be false if this time
- * is later than the cookie expiry.
- * Can be either a timestamp integer
- * or a cookie format date.
- * @access public
- */
- function isExpired($now) {
- if (! $this->_expiry) {
- return true;
- }
- if (is_string($now)) {
- $now = strtotime($now);
- }
- return ($this->_expiry < $now);
- }
-
- /**
- * Ages the cookie by the specified number of
- * seconds.
- * @param integer $interval In seconds.
- * @public
- */
- function agePrematurely($interval) {
- if ($this->_expiry) {
- $this->_expiry -= $interval;
- }
- }
-
- /**
- * Accessor for the secure flag.
- * @return boolean True if cookie needs SSL.
- * @access public
- */
- function isSecure() {
- return $this->_is_secure;
- }
-
- /**
- * Adds a trailing and leading slash to the path
- * if missing.
- * @param string $path Path to fix.
- * @access private
- */
- function _fixPath($path) {
- if (substr($path, 0, 1) != '/') {
- $path = '/' . $path;
- }
- if (substr($path, -1, 1) != '/') {
- $path .= '/';
- }
- return $path;
- }
- }
-
- /**
* Creates HTTP headers for the end point of
* a HTTP request.
* @package SimpleTest
@@ -278,7 +72,7 @@
* @return SimpleSocket New socket.
* @access public
*/
- function createConnection($method, $timeout) {
+ function &createConnection($method, $timeout) {
$default_port = ('https' == $this->_url->getScheme()) ? 443 : 80;
$socket = $this->_createSocket(
$this->_url->getScheme() ? $this->_url->getScheme() : 'http',
@@ -302,11 +96,13 @@
* @return SimpleSocket/SimpleSecureSocket New socket.
* @access protected
*/
- function _createSocket($scheme, $host, $port, $timeout) {
+ function &_createSocket($scheme, $host, $port, $timeout) {
if (in_array($scheme, array('https'))) {
- return new SimpleSecureSocket($host, $port, $timeout);
+ $socket = new SimpleSecureSocket($host, $port, $timeout);
+ } else {
+ $socket = new SimpleSocket($host, $port, $timeout);
}
- return new SimpleSocket($host, $port, $timeout);
+ return $socket;
}
}
@@ -370,22 +166,23 @@
* @return SimpleSocket New socket.
* @access public
*/
- function createConnection($method, $timeout) {
+ function &createConnection($method, $timeout) {
$socket = $this->_createSocket(
$this->_proxy->getScheme() ? $this->_proxy->getScheme() : 'http',
$this->_proxy->getHost(),
$this->_proxy->getPort() ? $this->_proxy->getPort() : 8080,
$timeout);
- if (! $socket->isError()) {
- $socket->write($this->_getRequestLine($method) . "\r\n");
- $socket->write($this->_getHostLine() . "\r\n");
- if ($this->_username && $this->_password) {
- $socket->write('Proxy-Authorization: Basic ' .
- base64_encode($this->_username . ':' . $this->_password) .
- "\r\n");
- }
- $socket->write("Connection: close\r\n");
+ if ($socket->isError()) {
+ return $socket;
+ }
+ $socket->write($this->_getRequestLine($method) . "\r\n");
+ $socket->write($this->_getHostLine() . "\r\n");
+ if ($this->_username && $this->_password) {
+ $socket->write('Proxy-Authorization: Basic ' .
+ base64_encode($this->_username . ':' . $this->_password) .
+ "\r\n");
}
+ $socket->write("Connection: close\r\n");
return $socket;
}
}
@@ -398,42 +195,41 @@
*/
class SimpleHttpRequest {
protected $_route;
- protected $_method;
protected $_encoding;
protected $_headers;
protected $_cookies;
/**
- * Saves the URL ready for fetching.
- * @param SimpleRoute $route Request route.
- * @param string $method HTTP request method,
- * usually GET.
+ * Builds the socket request from the different pieces.
+ * These include proxy information, URL, cookies, headers,
+ * request method and choice of encoding.
+ * @param SimpleRoute $route Request route.
* @param SimpleFormEncoding $encoding Content to send with
- * request or false.
+ * request.
* @access public
*/
- function SimpleHttpRequest($route, $method, $encoding = false) {
+ function SimpleHttpRequest($route, $encoding) {
$this->_route = $route;
- $this->_method = $method;
$this->_encoding = $encoding;
$this->_headers = array();
$this->_cookies = array();
}
/**
- * Fetches the content and parses the headers.
+ * Dispatches the content to the route's socket.
* @param integer $timeout Connection timeout.
* @return SimpleHttpResponse A response which may only have
- * an error.
+ * an error, but hopefully has a
+ * complete web page.
* @access public
*/
- function fetch($timeout) {
- $socket = $this->_route->createConnection($this->_method, $timeout);
- if ($socket->isError()) {
- return $this->_createResponse($socket);
+ function &fetch($timeout) {
+ $socket = $this->_route->createConnection($this->_encoding->getMethod(), $timeout);
+ if (! $socket->isError()) {
+ $this->_dispatchRequest($socket, $this->_encoding);
}
- $this->_dispatchRequest($socket, $this->_method, $this->_encoding);
- return $this->_createResponse($socket);
+ $response = $this->_createResponse($socket);
+ return $response;
}
/**
@@ -444,38 +240,21 @@
* @param SimpleFormEncoding $encoding Content to send with request.
* @access private
*/
- function _dispatchRequest($socket, $method, $encoding) {
- if ($encoding || ($method == 'POST')) {
- $socket->write("Content-Length: " . $this->_getContentLength($encoding) . "\r\n");
- $socket->write("Content-Type: application/x-www-form-urlencoded\r\n");
- }
+ function _dispatchRequest($socket, $encoding) {
foreach ($this->_headers as $header_line) {
$socket->write($header_line . "\r\n");
}
if (count($this->_cookies) > 0) {
- $socket->write("Cookie: " . $this->_marshallCookies($this->_cookies) . "\r\n");
+ $socket->write("Cookie: " . implode(";", $this->_cookies) . "\r\n");
}
+ $encoding->writeHeadersTo($socket);
$socket->write("\r\n");
- if ($encoding) {
- $socket->write($encoding->asString());
- }
- }
-
- /**
- * Calculates the length of the encoded content.
- * @param SimpleFormEncoding $encoding Content to send with
- * request or false.
- */
- function _getContentLength($encoding) {
- if (! $encoding) {
- return 0;
- }
- return (integer)strlen($encoding->asString());
+ $encoding->writeTo($socket);
}
/**
* Adds a header line to the request.
- * @param string $header_line Text of header line.
+ * @param string $header_line Text of full header line.
* @access public
*/
function addHeaderLine($header_line) {
@@ -483,27 +262,14 @@
}
/**
- * Adds a cookie to the request.
- * @param SimpleCookie $cookie Additional cookie.
+ * Reads all the relevant cookies from the
+ * cookie jar.
+ * @param SimpleCookieJar $jar Jar to read
+ * @param SimpleUrl $url Url to use for scope.
* @access public
*/
- function setCookie($cookie) {
- $this->_cookies[] = $cookie;
- }
-
- /**
- * Serialises the cookie hash ready for
- * transmission.
- * @param hash $cookies Parsed cookies.
- * @return array Cookies in header form.
- * @access private
- */
- function _marshallCookies($cookies) {
- $cookie_pairs = array();
- foreach ($cookies as $cookie) {
- $cookie_pairs[] = $cookie->getName() . "=" . $cookie->getValue();
- }
- return implode(";", $cookie_pairs);
+ function readCookiesFromJar($jar, $url) {
+ $this->_cookies = $jar->selectAsPairs($url);
}
/**
@@ -512,12 +278,12 @@
* @return SimpleHttpResponse Parsed response object.
* @access protected
*/
- function _createResponse($socket) {
- return new SimpleHttpResponse(
+ function &_createResponse($socket) {
+ $response = new SimpleHttpResponse(
$socket,
- $this->_method,
$this->_route->getUrl(),
$this->_encoding);
+ return $response;
}
}
@@ -642,12 +408,20 @@
}
/**
- * Accessor for any new cookies.
- * @return array List of new cookies.
+ * Writes new cookies to the cookie jar.
+ * @param SimpleCookieJar $jar Jar to write to.
+ * @param SimpleUrl $url Host and path to write under.
* @access public
*/
- function getNewCookies() {
- return $this->_cookies;
+ function writeCookiesToJar($jar, $url) {
+ foreach ($this->_cookies as $cookie) {
+ $jar->setCookie(
+ $cookie->getName(),
+ $cookie->getValue(),
+ $url->getHost(),
+ $cookie->getPath(),
+ $cookie->getExpiry());
+ }
}
/**
@@ -657,7 +431,7 @@
* @access protected
*/
function _parseHeaderLine($header_line) {
- if (preg_match('/HTTP\/(\d+\.\d+)\s+(.*?)\s/i', $header_line, $matches)) {
+ if (preg_match('/HTTP\/(\d+\.\d+)\s+(\d+)/i', $header_line, $matches)) {
$this->_http_version = $matches[1];
$this->_response_code = $matches[2];
}
@@ -705,9 +479,8 @@
* @subpackage WebTester
*/
class SimpleHttpResponse extends SimpleStickyError {
- protected $_method;
protected $_url;
- protected $_request_data;
+ protected $_encoding;
protected $_sent;
protected $_content;
protected $_headers;
@@ -717,16 +490,14 @@
* content and headers.
* @param SimpleSocket $socket Network connection to fetch
* response text from.
- * @param string $method HTTP request method.
* @param SimpleUrl $url Resource name.
- * @param mixed $request_data Record of content sent.
+ * @param mixed $encoding Record of content sent.
* @access public
*/
- function SimpleHttpResponse($socket, $method, $url, $request_data = '') {
+ function SimpleHttpResponse($socket, $url, $encoding) {
$this->SimpleStickyError();
- $this->_method = $method;
$this->_url = $url;
- $this->_request_data = $request_data;
+ $this->_encoding = $encoding;
$this->_sent = $socket->getSent();
$this->_content = false;
$raw = $this->_readAll($socket);
@@ -747,7 +518,7 @@
$this->_setError('Nothing fetched');
$this->_headers = new SimpleHttpHeaders('');
} elseif (! strstr($raw, "\r\n\r\n")) {
- $this->_setError('Could not parse headers');
+ $this->_setError('Could not split headers from content');
$this->_headers = new SimpleHttpHeaders($raw);
} else {
list($headers, $this->_content) = split("\r\n\r\n", $raw, 2);
@@ -761,7 +532,7 @@
* @access public
*/
function getMethod() {
- return $this->_method;
+ return $this->_encoding->getMethod();
}
/**
@@ -779,7 +550,7 @@
* @access public
*/
function getRequestData() {
- return $this->_request_data;
+ return $this->_encoding;
}
/**
diff --git a/tests/test_tools/simpletest/invoker.php b/tests/test_tools/simpletest/invoker.php
new file mode 100644
index 00000000..5274bf5e
--- /dev/null
+++ b/tests/test_tools/simpletest/invoker.php
@@ -0,0 +1,139 @@
+<?php
+ /**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: invoker.php,v 1.3 2006/02/06 06:13:43 lastcraft Exp $
+ */
+
+ /**#@+
+ * Includes SimpleTest files and defined the root constant
+ * for dependent libraries.
+ */
+ require_once(dirname(__FILE__) . '/errors.php');
+ require_once(dirname(__FILE__) . '/compatibility.php');
+ require_once(dirname(__FILE__) . '/scorer.php');
+ require_once(dirname(__FILE__) . '/expectation.php');
+ require_once(dirname(__FILE__) . '/dumper.php');
+ if (! defined('SIMPLE_TEST')) {
+ define('SIMPLE_TEST', dirname(__FILE__) . '/');
+ }
+ /**#@-*/
+
+ /**
+ * This is called by the class runner to run a
+ * single test method. Will also run the setUp()
+ * and tearDown() methods.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleInvoker {
+ protected $_test_case;
+
+ /**
+ * Stashes the test case for later.
+ * @param SimpleTestCase $test_case Test case to run.
+ */
+ function SimpleInvoker($test_case) {
+ $this->_test_case = $test_case;
+ }
+
+ /**
+ * Accessor for test case being run.
+ * @return SimpleTestCase Test case.
+ * @access public
+ */
+ function &getTestCase() {
+ return $this->_test_case;
+ }
+
+ /**
+ * Runs test level set up. Used for changing
+ * the mechanics of base test cases.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function before($method) {
+ $this->_test_case->before($method);
+ }
+
+ /**
+ * Invokes a test method and buffered with setUp()
+ * and tearDown() calls.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function invoke($method) {
+ $this->_test_case->setUp();
+ $this->_test_case->$method();
+ $this->_test_case->tearDown();
+ }
+
+ /**
+ * Runs test level clean up. Used for changing
+ * the mechanics of base test cases.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function after($method) {
+ $this->_test_case->after($method);
+ }
+ }
+
+ /**
+ * Do nothing decorator. Just passes the invocation
+ * straight through.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleInvokerDecorator {
+ protected $_invoker;
+
+ /**
+ * Stores the invoker to wrap.
+ * @param SimpleInvoker $invoker Test method runner.
+ */
+ function SimpleInvokerDecorator($invoker) {
+ $this->_invoker = $invoker;
+ }
+
+ /**
+ * Accessor for test case being run.
+ * @return SimpleTestCase Test case.
+ * @access public
+ */
+ function &getTestCase() {
+ return $this->_invoker->getTestCase();
+ }
+
+ /**
+ * Runs test level set up. Used for changing
+ * the mechanics of base test cases.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function before($method) {
+ $this->_invoker->before($method);
+ }
+
+ /**
+ * Invokes a test method and buffered with setUp()
+ * and tearDown() calls.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function invoke($method) {
+ $this->_invoker->invoke($method);
+ }
+
+ /**
+ * Runs test level clean up. Used for changing
+ * the mechanics of base test cases.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function after($method) {
+ $this->_invoker->after($method);
+ }
+ }
+?>
diff --git a/tests/test_tools/simpletest/mock_objects.php b/tests/test_tools/simpletest/mock_objects.php
index d39eb84e..0b003491 100644
--- a/tests/test_tools/simpletest/mock_objects.php
+++ b/tests/test_tools/simpletest/mock_objects.php
@@ -3,37 +3,36 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage MockObjects
- * @version $Id: mock_objects.php,v 1.61 2005/02/13 01:09:25 lastcraft Exp $
+ * @version $Id: mock_objects.php,v 1.90 2006/02/05 19:35:31 lastcraft Exp $
*/
/**#@+
* include SimpleTest files
*/
require_once(dirname(__FILE__) . '/expectation.php');
- require_once(dirname(__FILE__) . '/options.php');
+ require_once(dirname(__FILE__) . '/simpletest.php');
require_once(dirname(__FILE__) . '/dumper.php');
+ if (version_compare(phpversion(), '5') >= 0) {
+ require_once(dirname(__FILE__) . '/reflection_php5.php');
+ } else {
+ require_once(dirname(__FILE__) . '/reflection_php4.php');
+ }
/**#@-*/
-
+
/**
* Default character simpletest will substitute for any value
*/
- define('MOCK_WILDCARD', '*');
-
+ if (! defined('MOCK_ANYTHING')) {
+ define('MOCK_ANYTHING', '*');
+ }
+
/**
* A wildcard expectation always matches.
* @package SimpleTest
* @subpackage MockObjects
*/
- class WildcardExpectation extends SimpleExpectation {
-
- /**
- * Chains constructor only.
- * @access public
- */
- function WildcardExpectation() {
- $this->SimpleExpectation();
- }
-
+ class AnythingExpectation extends SimpleExpectation {
+
/**
* Tests the expectation. Always true.
* @param mixed $compare Ignored.
@@ -43,7 +42,7 @@
function test($compare) {
return true;
}
-
+
/**
* Returns a human readable test message.
* @param mixed $compare Comparison value.
@@ -53,10 +52,10 @@
*/
function testMessage($compare) {
$dumper = $this->_getDumper();
- return 'Wildcard always matches [' . $dumper->describeValue($compare) . ']';
+ return 'Anything always matches [' . $dumper->describeValue($compare) . ']';
}
}
-
+
/**
* Parameter comparison assertion.
* @package SimpleTest
@@ -64,7 +63,7 @@
*/
class ParametersExpectation extends SimpleExpectation {
protected $_expected;
-
+
/**
* Sets the expected parameter list.
* @param array $parameters Array of parameters including
@@ -80,7 +79,7 @@
$this->SimpleExpectation($message);
$this->_expected = $expected;
}
-
+
/**
* Tests the assertion. True if correct.
* @param array $parameters Comparison values.
@@ -101,7 +100,7 @@
}
return true;
}
-
+
/**
* Tests an individual parameter.
* @param mixed $parameter Value to test.
@@ -114,7 +113,7 @@
$comparison = $this->_coerceToExpectation($expected);
return $comparison->test($parameter);
}
-
+
/**
* Returns a human readable test message.
* @param array $comparison Incoming parameter list.
@@ -131,7 +130,7 @@
return $this->_describeDifference($this->_expected, $parameters);
}
}
-
+
/**
* Message to display if expectation differs from
* the parameters actually received.
@@ -157,7 +156,7 @@
}
return "Parameter expectation differs at " . implode(" and ", $messages);
}
-
+
/**
* Creates an identical expectation if the
* object/value is not already some type
@@ -167,12 +166,12 @@
* @access private
*/
function _coerceToExpectation($expected) {
- if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) {
+ if (SimpleExpectation::isExpectation($expected)) {
return $expected;
}
return new IdenticalExpectation($expected);
}
-
+
/**
* Renders the argument list as a string for
* messages.
@@ -191,14 +190,14 @@
return implode(', ', $descriptions);
}
}
-
+
/**
* Confirms that the number of calls on a method is as expected.
*/
class CallCountExpectation extends SimpleExpectation {
protected $_method;
protected $_count;
-
+
/**
* Stashes the method and expected count for later
* reporting.
@@ -211,7 +210,7 @@
$this->_count = $count;
$this->SimpleExpectation($message);
}
-
+
/**
* Tests the assertion. True if correct.
* @param integer $compare Measured call count.
@@ -221,7 +220,7 @@
function test($compare) {
return ($this->_count == $compare);
}
-
+
/**
* Reports the comparison.
* @param integer $compare Measured call count.
@@ -234,14 +233,14 @@
'] got [' . $compare . ']';
}
}
-
+
/**
* Confirms that the number of calls on a method is as expected.
*/
class MinimumCallCountExpectation extends SimpleExpectation {
protected $_method;
protected $_count;
-
+
/**
* Stashes the method and expected count for later
* reporting.
@@ -254,7 +253,7 @@
$this->_count = $count;
$this->SimpleExpectation($message);
}
-
+
/**
* Tests the assertion. True if correct.
* @param integer $compare Measured call count.
@@ -264,7 +263,7 @@
function test($compare) {
return ($this->_count <= $compare);
}
-
+
/**
* Reports the comparison.
* @param integer $compare Measured call count.
@@ -277,14 +276,14 @@
'] got [' . $compare . ']';
}
}
-
+
/**
* Confirms that the number of calls on a method is as expected.
*/
class MaximumCallCountExpectation extends SimpleExpectation {
protected $_method;
protected $_count;
-
+
/**
* Stashes the method and expected count for later
* reporting.
@@ -297,7 +296,7 @@
$this->_count = $count;
$this->SimpleExpectation($message);
}
-
+
/**
* Tests the assertion. True if correct.
* @param integer $compare Measured call count.
@@ -307,7 +306,7 @@
function test($compare) {
return ($this->_count >= $compare);
}
-
+
/**
* Reports the comparison.
* @param integer $compare Measured call count.
@@ -329,7 +328,7 @@
*/
class CallMap {
protected $_map;
-
+
/**
* Creates an empty call map.
* @access public
@@ -337,7 +336,7 @@
function CallMap() {
$this->_map = array();
}
-
+
/**
* Stashes a value against a method call.
* @param array $parameters Arguments including wildcards.
@@ -347,7 +346,7 @@
function addValue($parameters, $value) {
$this->addReference($parameters, $value);
}
-
+
/**
* Stashes a reference against a method call.
* @param array $parameters Array of arguments (including wildcards).
@@ -360,7 +359,7 @@
$this->_map[$place]["params"] = new ParametersExpectation($parameters);
$this->_map[$place]["content"] = $reference;
}
-
+
/**
* Searches the call list for a matching parameter
* set. Returned by reference.
@@ -370,14 +369,15 @@
* slot, otherwise null.
* @access public
*/
- function findFirstMatch($parameters) {
+ function &findFirstMatch($parameters) {
$slot = $this->_findFirstSlot($parameters);
if (!isset($slot)) {
- return null;
+ $null = null;
+ return $null;
}
return $slot["content"];
}
-
+
/**
* Searches the call list for a matching parameter
* set. True if successful.
@@ -389,7 +389,7 @@
function isMatch($parameters) {
return ($this->_findFirstSlot($parameters) != null);
}
-
+
/**
* Searches the map for a matching item.
* @param array $parameters Parameters to search by
@@ -397,78 +397,100 @@
* @return array Reference to slot or null.
* @access private
*/
- function _findFirstSlot($parameters) {
+ function &_findFirstSlot($parameters) {
$count = count($this->_map);
for ($i = 0; $i < $count; $i++) {
if ($this->_map[$i]["params"]->test($parameters)) {
return $this->_map[$i];
}
}
- return null;
+ $null = null;
+ return $null;
}
}
-
+
/**
* An empty collection of methods that can have their
- * return values set. Used for prototyping.
+ * return values set and expectations made of the
+ * calls upon them. The mock will assert the
+ * expectations against it's attached test case in
+ * addition to the server stub behaviour.
* @package SimpleTest
* @subpackage MockObjects
*/
- class SimpleStub {
- protected $_wildcard;
- protected $_is_strict;
+ class SimpleMock {
+ protected $_wildcard = MOCK_ANYTHING;
+ protected $_is_strict = true;
protected $_returns;
protected $_return_sequence;
protected $_call_counts;
-
+ protected $_expected_counts;
+ protected $_max_counts;
+ protected $_expected_args;
+ protected $_expected_args_at;
+
/**
- * Sets up the wildcard and everything else empty.
- * @param mixed $wildcard Parameter matching wildcard.
- * @param boolean $is_strict Enables method name checks.
- * @access public
+ * Creates an empty return list and expectation list.
+ * All call counts are set to zero.
+ * @param SimpleTestCase $test Test case to test expectations in.
+ * @param mixed $wildcard Parameter matching wildcard.
+ * @param boolean $is_strict Enables method name checks on
+ * expectations.
*/
- function SimpleStub($wildcard, $is_strict = true) {
- $this->_wildcard = $wildcard;
- $this->_is_strict = $is_strict;
+ function SimpleMock() {
$this->_returns = array();
$this->_return_sequence = array();
$this->_call_counts = array();
+ $test = $this->_getCurrentTestCase();
+ $test->tell($this);
+ $this->_expected_counts = array();
+ $this->_max_counts = array();
+ $this->_expected_args = array();
+ $this->_expected_args_at = array();
}
-
+
/**
- * Replaces wildcard matches with wildcard
- * expectations in the argument list.
- * @param array $args Raw argument list.
- * @return array Argument list with
- * expectations.
- * @access private
+ * Disables a name check when setting expectations.
+ * This hack is needed for the partial mocks.
+ * @access public
*/
- function _replaceWildcards($args) {
- if ($args === false) {
- return false;
- }
- for ($i = 0; $i < count($args); $i++) {
- if ($args[$i] === $this->_wildcard) {
- $args[$i] = new WildcardExpectation();
- }
- }
- return $args;
+ function disableExpectationNameChecks() {
+ $this->_is_strict = false;
}
-
+
/**
- * Returns the expected value for the method name.
- * @param string $method Name of method to simulate.
- * @param array $args Arguments as an array.
- * @return mixed Stored return.
+ * Changes the default wildcard object.
+ * @param mixed $wildcard Parameter matching wildcard.
+ * @access public
+ */
+ function setWildcard($wildcard) {
+ $this->_wildcard = $wildcard;
+ }
+
+ /**
+ * Finds currently running test.
+ * @return SimpeTestCase Current test case.
+ * @access protected
+ */
+ function &_getCurrentTestCase() {
+ return SimpleTest::getCurrent();
+ }
+
+ /**
+ * Die if bad arguments array is passed
+ * @param mixed $args The arguments value to be checked.
+ * @param string $task Description of task attempt.
+ * @return boolean Valid arguments
* @access private
*/
- function _invoke($method, $args) {
- $method = strtolower($method);
- $step = $this->getCallCount($method);
- $this->_addCall($method, $args);
- return $this->_getReturn($method, $args, $step);
+ function _checkArgumentsIsArray($args, $task) {
+ if (! is_array($args)) {
+ trigger_error(
+ "Cannot $task as \$args parameter is not an array",
+ E_USER_ERROR);
+ }
}
-
+
/**
* Triggers a PHP error if the method is not part
* of this object.
@@ -477,13 +499,33 @@
* @access protected
*/
function _dieOnNoMethod($method, $task) {
- if ($this->_is_strict && !method_exists($this, $method)) {
+ if ($this->_is_strict && ! method_exists($this, $method)) {
trigger_error(
"Cannot $task as no ${method}() in class " . get_class($this),
E_USER_ERROR);
}
}
-
+
+ /**
+ * Replaces wildcard matches with wildcard
+ * expectations in the argument list.
+ * @param array $args Raw argument list.
+ * @return array Argument list with
+ * expectations.
+ * @access private
+ */
+ function _replaceWildcards($args) {
+ if ($args === false) {
+ return false;
+ }
+ for ($i = 0; $i < count($args); $i++) {
+ if ($args[$i] === $this->_wildcard) {
+ $args[$i] = new AnythingExpectation();
+ }
+ }
+ return $args;
+ }
+
/**
* Adds one to the call count of a method.
* @param string $method Method called.
@@ -496,7 +538,7 @@
}
$this->_call_counts[$method]++;
}
-
+
/**
* Fetches the call count of a method so far.
* @param string $method Method name called.
@@ -511,7 +553,7 @@
}
return $this->_call_counts[$method];
}
-
+
/**
* Sets a return for a parameter list that will
* be passed by value for all calls to this method.
@@ -530,7 +572,7 @@
}
$this->_returns[$method]->addValue($args, $value);
}
-
+
/**
* Sets a return for a parameter list that will
* be passed by value only when the required call count
@@ -557,7 +599,7 @@
}
$this->_return_sequence[$method][$timing]->addValue($args, $value);
}
-
+
/**
* Sets a return for a parameter list that will
* be passed by reference for all calls.
@@ -576,7 +618,7 @@
}
$this->_returns[$method]->addReference($args, $reference);
}
-
+
/**
* Sets a return for a parameter list that will
* be passed by value only when the required call count
@@ -603,94 +645,7 @@
}
$this->_return_sequence[$method][$timing]->addReference($args, $reference);
}
-
- /**
- * Finds the return value matching the incoming
- * arguments. If there is no matching value found
- * then an error is triggered.
- * @param string $method Method name.
- * @param array $args Calling arguments.
- * @param integer $step Current position in the
- * call history.
- * @return mixed Stored return.
- * @access protected
- */
- function _getReturn($method, $args, $step) {
- if (isset($this->_return_sequence[$method][$step])) {
- if ($this->_return_sequence[$method][$step]->isMatch($args)) {
- return $this->_return_sequence[$method][$step]->findFirstMatch($args);
- }
- }
- if (isset($this->_returns[$method])) {
- return $this->_returns[$method]->findFirstMatch($args);
- }
- return null;
- }
- }
-
- /**
- * An empty collection of methods that can have their
- * return values set and expectations made of the
- * calls upon them. The mock will assert the
- * expectations against it's attached test case in
- * addition to the server stub behaviour.
- * @package SimpleTest
- * @subpackage MockObjects
- */
- class SimpleMock extends SimpleStub {
- protected $_test;
- protected $_expected_counts;
- protected $_max_counts;
- protected $_expected_args;
- protected $_expected_args_at;
-
- /**
- * Creates an empty return list and expectation list.
- * All call counts are set to zero.
- * @param SimpleTestCase $test Test case to test expectations in.
- * @param mixed $wildcard Parameter matching wildcard.
- * @param boolean $is_strict Enables method name checks on
- * expectations.
- * @access public
- */
- function SimpleMock($test, $wildcard, $is_strict = true) {
- $this->SimpleStub($wildcard, $is_strict);
- if (! $test) {
- trigger_error('No unit tester for mock object', E_USER_ERROR);
- return;
- }
- $this->_test = SimpleMock::registerTest($test);
- $this->_expected_counts = array();
- $this->_max_counts = array();
- $this->_expected_args = array();
- $this->_expected_args_at = array();
- }
-
- /**
- * Accessor for attached unit test so that when
- * subclassed, new expectations can be added easily.
- * @return SimpleTestCase Unit test passed in constructor.
- * @access public
- */
- function getTest() {
- return $this->_test;
- }
-
- /**
- * Die if bad arguments array is passed
- * @param mixed $args The arguments value to be checked.
- * @param string $task Description of task attempt.
- * @return boolean Valid arguments
- * @access private
- */
- function _checkArgumentsIsArray($args, $task) {
- if (! is_array($args)) {
- trigger_error(
- "Cannot $task as \$args parameter is not an array",
- E_USER_ERROR);
- }
- }
-
+
/**
* Sets up an expected call with a set of
* expected parameters in that call. All
@@ -702,15 +657,22 @@
* @param string $message Overridden message.
* @access public
*/
- function expectArguments($method, $args, $message = '%s') {
+ function expect($method, $args, $message = '%s') {
$this->_dieOnNoMethod($method, 'set expected arguments');
$this->_checkArgumentsIsArray($args, 'set expected arguments');
$args = $this->_replaceWildcards($args);
- $message .= Mock::getExpectationLine(' at line [%d]');
+ $message .= Mock::getExpectationLine();
$this->_expected_args[strtolower($method)] =
new ParametersExpectation($args, $message);
}
-
+
+ /**
+ * @deprecated
+ */
+ function expectArguments($method, $args, $message = '%s') {
+ return $this->expect($method, $args, $message);
+ }
+
/**
* Sets up an expected call with a set of
* expected parameters in that call. The
@@ -724,7 +686,7 @@
* @param string $message Overridden message.
* @access public
*/
- function expectArgumentsAt($timing, $method, $args, $message = '%s') {
+ function expectAt($timing, $method, $args, $message = '%s') {
$this->_dieOnNoMethod($method, 'set expected arguments at time');
$this->_checkArgumentsIsArray($args, 'set expected arguments at time');
$args = $this->_replaceWildcards($args);
@@ -732,11 +694,18 @@
$this->_expected_args_at[$timing] = array();
}
$method = strtolower($method);
- $message .= Mock::getExpectationLine(' at line [%d]');
+ $message .= Mock::getExpectationLine();
$this->_expected_args_at[$timing][$method] =
new ParametersExpectation($args, $message);
}
-
+
+ /**
+ * @deprecated
+ */
+ function expectArgumentsAt($timing, $method, $args, $message = '%s') {
+ return $this->expectAt($timing, $method, $args, $message);
+ }
+
/**
* Sets an expectation for the number of times
* a method will be called. The tally method
@@ -749,11 +718,11 @@
*/
function expectCallCount($method, $count, $message = '%s') {
$this->_dieOnNoMethod($method, 'set expected call count');
- $message .= Mock::getExpectationLine(' at line [%d]');
+ $message .= Mock::getExpectationLine();
$this->_expected_counts[strtolower($method)] =
new CallCountExpectation($method, $count, $message);
}
-
+
/**
* Sets the number of times a method may be called
* before a test failure is triggered.
@@ -765,11 +734,11 @@
*/
function expectMaximumCallCount($method, $count, $message = '%s') {
$this->_dieOnNoMethod($method, 'set maximum call count');
- $message .= Mock::getExpectationLine(' at line [%d]');
- $this->_max_counts[strtolower($method)] =
+ $message .= Mock::getExpectationLine();
+ $this->_max_counts[strtolower($method)] =
new MaximumCallCountExpectation($method, $count, $message);
}
-
+
/**
* Sets the number of times to call a method to prevent
* a failure on the tally.
@@ -781,11 +750,11 @@
*/
function expectMinimumCallCount($method, $count, $message = '%s') {
$this->_dieOnNoMethod($method, 'set minimum call count');
- $message .= Mock::getExpectationLine(' at line [%d]');
+ $message .= Mock::getExpectationLine();
$this->_expected_counts[strtolower($method)] =
new MinimumCallCountExpectation($method, $count, $message);
}
-
+
/**
* Convenience method for barring a method
* call.
@@ -796,7 +765,7 @@
function expectNever($method, $message = '%s') {
$this->expectMaximumCallCount($method, 0, $message);
}
-
+
/**
* Convenience method for a single method
* call.
@@ -812,7 +781,7 @@
$this->expectArguments($method, $args, $message);
}
}
-
+
/**
* Convenience method for requiring a method
* call.
@@ -828,16 +797,22 @@
$this->expectArguments($method, $args, $message);
}
}
-
+
/**
- * Totals up the call counts and triggers a test
- * assertion if a test is present for expected
- * call counts.
- * This method must be called explicitly for the call
- * count assertions to be triggered.
- * @access public
+ * @deprecated
*/
function tally() {
+ }
+
+ /**
+ * Receives event from unit test that the current
+ * test method has finished. Totals up the call
+ * counts and triggers a test assertion if a test
+ * is present for expected call counts.
+ * @param string $method Current method name.
+ * @access public
+ */
+ function atTestEnd($method) {
foreach ($this->_expected_counts as $method => $expectation) {
$this->_assertTrue(
$expectation->test($this->getCallCount($method)),
@@ -862,14 +837,40 @@
* @return mixed Stored return.
* @access private
*/
- function _invoke($method, $args) {
+ function &_invoke($method, $args) {
$method = strtolower($method);
$step = $this->getCallCount($method);
$this->_addCall($method, $args);
$this->_checkExpectations($method, $args, $step);
- return $this->_getReturn($method, $args, $step);
+ $result = $this->_getReturn($method, $args, $step);
+ return $result;
+ }
+ /**
+ * Finds the return value matching the incoming
+ * arguments. If there is no matching value found
+ * then an error is triggered.
+ * @param string $method Method name.
+ * @param array $args Calling arguments.
+ * @param integer $step Current position in the
+ * call history.
+ * @return mixed Stored return.
+ * @access protected
+ */
+ function &_getReturn($method, $args, $step) {
+ if (isset($this->_return_sequence[$method][$step])) {
+ if ($this->_return_sequence[$method][$step]->isMatch($args)) {
+ $result = $this->_return_sequence[$method][$step]->findFirstMatch($args);
+ return $result;
+ }
+ }
+ if (isset($this->_returns[$method])) {
+ $result = $this->_returns[$method]->findFirstMatch($args);
+ return $result;
+ }
+ $null = null;
+ return $null;
}
-
+
/**
* Tests the arguments against expectations.
* @param string $method Method to check.
@@ -897,7 +898,7 @@
"Mock method [$method] -> " . $this->_expected_args[$method]->overlayMessage($args));
}
}
-
+
/**
* Triggers an assertion on the held test case.
* Should be overridden when using another test
@@ -909,253 +910,173 @@
* @access protected
*/
function _assertTrue($assertion, $message) {
- $test =SimpleMock::injectTest($this->_test);
+ $test = $this->_getCurrentTestCase();
$test->assertTrue($assertion, $message);
}
-
- /**
- * Stashes the test case for later recovery.
- * @param SimpleTestCase $test Test case.
- * @return string Key to find it again.
- * @access public
- * @static
- */
- function registerTest($test) {
- $registry =SimpleMock::_getRegistry();
- $registry[$class = get_class($test)] = $test;
- return $class;
- }
-
- /**
- * Resolves the dependency on the test case.
- * @param string $class Key to look up test case in.
- * @return SimpleTestCase Test case to send results to.
- * @access public
- * @static
- */
- function injectTest($key) {
- $registry =SimpleMock::_getRegistry();
- return $registry[$key];
- }
-
- /**
- * Registry for test cases. The reason for this is
- * to break the reference between the test cases and
- * the mocks. It was leading to a fatal error due to
- * recursive dependencies during comparisons. See
- * http://bugs.php.net/bug.php?id=31449 for the PHP
- * bug.
- * @return array List of references.
- * @access private
- * @static
- */
- function _getRegistry() {
- static $registry;
- if (! isset($registry)) {
- $registry = array();
- }
- return $registry;
- }
}
-
+
/**
* Static methods only service class for code generation of
- * server stubs.
+ * mock objects.
* @package SimpleTest
* @subpackage MockObjects
*/
- class Stub {
-
- /**
- * Factory for server stub classes.
- */
- function Stub() {
- trigger_error('Stub factory methods are class only.');
- }
-
- /**
- * Clones a class' interface and creates a stub version
- * that can have return values set.
- * @param string $class Class to clone.
- * @param string $stub_class New class name. Default is
- * the old name with "Stub"
- * prepended.
- * @param array $methods Additional methods to add beyond
- * those in the cloned class. Use this
- * to emulate the dynamic addition of
- * methods in the cloned class or when
- * the class hasn't been written yet.
- * @static
+ class Mock {
+
+ /**
+ * Factory for mock object classes.
* @access public
*/
- function generate($class, $stub_class = false, $methods = false) {
- if (! SimpleTestCompatibility::classExists($class)) {
- return false;
- }
- if (! $stub_class) {
- $stub_class = "Stub" . $class;
- }
- if (SimpleTestCompatibility::classExists($stub_class)) {
- return false;
- }
- return eval(Stub::_createClassCode(
- $class,
- $stub_class,
- $methods ? $methods : array()) . " return true;");
+ function Mock() {
+ trigger_error('Mock factory methods are class only.');
}
-
+
/**
- * The new server stub class code in string form.
- * @param string $class Class to clone.
- * @param string $mock_class New class name.
- * @param array $methods Additional methods.
+ * Clones a class' interface and creates a mock version
+ * that can have return values and expectations set.
+ * @param string $class Class to clone.
+ * @param string $mock_class New class name. Default is
+ * the old name with "Mock"
+ * prepended.
+ * @param array $methods Additional methods to add beyond
+ * those in th cloned class. Use this
+ * to emulate the dynamic addition of
+ * methods in the cloned class or when
+ * the class hasn't been written yet.
* @static
- * @access private
+ * @access public
*/
- function _createClassCode($class, $stub_class, $methods) {
- $stub_base = SimpleTestOptions::getStubBaseClass();
- $code = "class $stub_class extends $stub_base {\n";
- $code .= " function $stub_class(\$wildcard = MOCK_WILDCARD) {\n";
- $code .= " \$this->$stub_base(\$wildcard);\n";
- $code .= " }\n";
- $code .= Stub::_createHandlerCode($class, $stub_base, $methods);
- $code .= "}\n";
- return $code;
+ function generate($class, $mock_class = false, $methods = false) {
+ $generator = new MockGenerator($class, $mock_class);
+ return $generator->generate($methods);
}
-
+
/**
- * Creates code within a class to generate replaced
- * methods. All methods call the _invoke() handler
- * with the method name and the arguments in an
- * array.
- * @param string $class Class to clone.
- * @param string $base Base mock/stub class with methods that
- * cannot be cloned. Otherwise you
- * would be stubbing the accessors used
- * to set the stubs.
- * @param array $methods Additional methods.
+ * Generates a version of a class with selected
+ * methods mocked only. Inherits the old class
+ * and chains the mock methods of an aggregated
+ * mock object.
+ * @param string $class Class to clone.
+ * @param string $mock_class New class name.
+ * @param array $methods Methods to be overridden
+ * with mock versions.
* @static
- * @access private
+ * @access public
*/
- function _createHandlerCode($class, $base, $methods) {
- $code = "";
- $methods = array_merge($methods, get_class_methods($class));
- foreach ($methods as $method) {
- if (Stub::_isSpecialMethod($method)) {
- continue;
- }
- if (in_array($method, get_class_methods($base))) {
- continue;
- }
- $code .= " function $method() {\n";
- $code .= " \$args = func_get_args();\n";
- $code .= " return \$this->_invoke(\"$method\", \$args);\n";
- $code .= " }\n";
- }
- return $code;
+ function generatePartial($class, $mock_class, $methods) {
+ $generator = new MockGenerator($class, $mock_class);
+ return $generator->generatePartial($methods);
}
-
+
/**
- * Tests to see if a special PHP method is about to
- * be stubbed by mistake.
- * @param string $method Method name.
- * @return boolean True if special.
- * @access private
+ * Uses a stack trace to find the line of an assertion.
+ * @param array $stack Stack frames top most first. Only
+ * needed if not using the PHP
+ * backtrace function.
+ * @return string Location of first expect*
+ * method embedded in format string.
+ * @access public
* @static
*/
- function _isSpecialMethod($method) {
- return in_array(
- strtolower($method),
- array('__construct', '__clone', '__get', '__set', '__call'));
+ function getExpectationLine($stack = false) {
+ if ($stack === false) {
+ $stack = SimpleTestCompatibility::getStackTrace();
+ }
+ return SimpleDumper::getFormattedAssertionLine($stack);
}
}
-
+
/**
- * Static methods only service class for code generation of
- * mock objects.
+ * @deprecated
+ */
+ class Stub extends Mock {
+ }
+
+ /**
+ * Service class for code generation of mock objects.
* @package SimpleTest
* @subpackage MockObjects
*/
- class Mock {
-
- /**
- * Factory for mock object classes.
- * @access public
- */
- function Mock() {
- trigger_error("Mock factory methods are class only.");
+ class MockGenerator {
+ protected $_class;
+ protected $_mock_class;
+ protected $_mock_base;
+ protected $_reflection;
+
+ function MockGenerator($class, $mock_class) {
+ $this->_class = $class;
+ $this->_mock_class = $mock_class;
+ $this->_mock_base = SimpleTest::getMockBaseClass();
+ $this->_reflection = new SimpleReflection($this->_class);
}
-
+
/**
* Clones a class' interface and creates a mock version
* that can have return values and expectations set.
- * @param string $class Class to clone.
- * @param string $mock_class New class name. Default is
- * the old name with "Mock"
- * prepended.
* @param array $methods Additional methods to add beyond
* those in th cloned class. Use this
* to emulate the dynamic addition of
* methods in the cloned class or when
* the class hasn't been written yet.
- * @static
* @access public
*/
- function generate($class, $mock_class = false, $methods = false) {
- if (! SimpleTestCompatibility::classExists($class)) {
+ function generate($methods) {
+ if (! $this->_reflection->classOrInterfaceExists()) {
return false;
}
- if (! $mock_class) {
- $mock_class = "Mock" . $class;
+ if (! $this->_mock_class) {
+ $this->_mock_class = 'Mock' . $this->_class;
}
- if (SimpleTestCompatibility::classExists($mock_class)) {
+ $mock_reflection = new SimpleReflection($this->_mock_class);
+ if ($mock_reflection->classExistsSansAutoload()) {
return false;
}
- return eval(Mock::_createClassCode(
- $class,
- $mock_class,
- $methods ? $methods : array()) . " return true;");
+ return eval(
+ $this->_createClassCode($methods ? $methods : array()) .
+ " return true;");
}
-
+
/**
* Generates a version of a class with selected
* methods mocked only. Inherits the old class
* and chains the mock methods of an aggregated
* mock object.
- * @param string $class Class to clone.
- * @param string $mock_class New class name.
* @param array $methods Methods to be overridden
* with mock versions.
- * @static
* @access public
*/
- function generatePartial($class, $mock_class, $methods) {
- if (! SimpleTestCompatibility::classExists($class)) {
+ function generatePartial($methods) {
+ if (! $this->_reflection->classExists($this->_class)) {
return false;
}
- if (SimpleTestCompatibility::classExists($mock_class)) {
+ $mock_reflection = new SimpleReflection($this->_mock_class);
+ if ($mock_reflection->classExistsSansAutoload()) {
trigger_error("Partial mock class [$mock_class] already exists");
return false;
}
- return eval(Mock::_extendClassCode($class, $mock_class, $methods));
+ return eval($this->_extendClassCode($methods));
}
/**
* The new mock class code as a string.
- * @param string $class Class to clone.
- * @param string $mock_class New class name.
* @param array $methods Additional methods.
* @return string Code for new mock class.
- * @static
* @access private
*/
- function _createClassCode($class, $mock_class, $methods) {
- $mock_base = SimpleTestOptions::getMockBaseClass();
- $code = "class $mock_class extends $mock_base {\n";
- $code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n";
- $code .= " \$this->$mock_base(\$test, \$wildcard);\n";
+ function _createClassCode($methods) {
+ $implements = '';
+ $interfaces = $this->_reflection->getInterfaces();
+ if (function_exists('spl_classes')) {
+ $interfaces = array_diff($interfaces, array('Traversable'));
+ }
+ if (count($interfaces) > 0) {
+ $implements = 'implements ' . implode(', ', $interfaces);
+ }
+ $code = "class " . $this->_mock_class . " extends " . $this->_mock_base . " $implements {\n";
+ $code .= " function " . $this->_mock_class . "() {\n";
+ $code .= " \$this->" . $this->_mock_base . "();\n";
$code .= " }\n";
- $code .= Stub::_createHandlerCode($class, $mock_base, $methods);
+ $code .= $this->_createHandlerCode($methods);
$code .= "}\n";
return $code;
}
@@ -1164,30 +1085,67 @@
* The extension class code as a string. The class
* composites a mock object and chains mocked methods
* to it.
- * @param string $class Class to extend.
- * @param string $mock_class New class name.
* @param array $methods Mocked methods.
* @return string Code for a new class.
- * @static
* @access private
*/
- function _extendClassCode($class, $mock_class, $methods) {
- $mock_base = SimpleTestOptions::getMockBaseClass();
- $code = "class $mock_class extends $class {\n";
+ function _extendClassCode($methods) {
+ $code = "class " . $this->_mock_class . " extends " . $this->_class . " {\n";
$code .= " var \$_mock;\n";
- $code .= Mock::_addMethodList($methods);
+ $code .= $this->_addMethodList($methods);
$code .= "\n";
- $code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n";
- $code .= " \$this->_mock = new $mock_base(\$test, \$wildcard, false);\n";
+ $code .= " function " . $this->_mock_class . "() {\n";
+ $code .= " \$this->_mock = new " . $this->_mock_base . "();\n";
+ $code .= " \$this->_mock->disableExpectationNameChecks();\n";
$code .= " }\n";
- $code .= Mock::_chainMockReturns();
- $code .= Mock::_chainMockExpectations();
- $code .= Mock::_overrideMethods($methods);
- $code .= SimpleTestOptions::getPartialMockCode();
+ $code .= $this->_chainMockReturns();
+ $code .= $this->_chainMockExpectations();
+ $code .= $this->_overrideMethods($methods);
$code .= "}\n";
return $code;
}
-
+
+ /**
+ * Creates code within a class to generate replaced
+ * methods. All methods call the _invoke() handler
+ * with the method name and the arguments in an
+ * array.
+ * @param array $methods Additional methods.
+ * @access private
+ */
+ function _createHandlerCode($methods) {
+ $code = '';
+ $methods = array_merge($methods, $this->_reflection->getMethods());
+ foreach ($methods as $method) {
+ if ($this->_isConstructor($method)) {
+ continue;
+ }
+ $mock_reflection = new SimpleReflection($this->_mock_base);
+ if (in_array($method, $mock_reflection->getMethods())) {
+ continue;
+ }
+ $code .= " " . $this->_reflection->getSignature($method) . " {\n";
+ $code .= " \$args = func_get_args();\n";
+ $code .= " \$result = &\$this->_invoke(\"$method\", \$args);\n";
+ $code .= " return \$result;\n";
+ $code .= " }\n";
+ }
+ return $code;
+ }
+
+ /**
+ * Tests to see if a special PHP method is about to
+ * be stubbed by mistake.
+ * @param string $method Method name.
+ * @return boolean True if special.
+ * @access private
+ */
+ function _isConstructor($method) {
+ return in_array(
+ strtolower($method),
+ array('__construct', '__destruct', '__clone'));
+ }
+
/**
* Creates a list of mocked methods for error checking.
* @param array $methods Mocked methods.
@@ -1197,7 +1155,7 @@
function _addMethodList($methods) {
return " var \$_mocked_methods = array('" . implode("', '", $methods) . "');\n";
}
-
+
/**
* Creates code to abandon the expectation if not mocked.
* @param string $alias Parameter name of method name.
@@ -1207,11 +1165,12 @@
function _bailOutIfNotMocked($alias) {
$code = " if (! in_array($alias, \$this->_mocked_methods)) {\n";
$code .= " trigger_error(\"Method [$alias] is not mocked\");\n";
- $code .= " return;\n";
+ $code .= " \$null = null;\n";
+ $code .= " return \$null;\n";
$code .= " }\n";
return $code;
}
-
+
/**
* Creates source code for chaining to the composited
* mock object.
@@ -1220,24 +1179,24 @@
*/
function _chainMockReturns() {
$code = " function setReturnValue(\$method, \$value, \$args = false) {\n";
- $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= $this->_bailOutIfNotMocked("\$method");
$code .= " \$this->_mock->setReturnValue(\$method, \$value, \$args);\n";
$code .= " }\n";
$code .= " function setReturnValueAt(\$timing, \$method, \$value, \$args = false) {\n";
- $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= $this->_bailOutIfNotMocked("\$method");
$code .= " \$this->_mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n";
$code .= " }\n";
$code .= " function setReturnReference(\$method, &\$ref, \$args = false) {\n";
- $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= $this->_bailOutIfNotMocked("\$method");
$code .= " \$this->_mock->setReturnReference(\$method, \$ref, \$args);\n";
$code .= " }\n";
$code .= " function setReturnReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n";
- $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= $this->_bailOutIfNotMocked("\$method");
$code .= " \$this->_mock->setReturnReferenceAt(\$timing, \$method, \$ref, \$args);\n";
$code .= " }\n";
return $code;
}
-
+
/**
* Creates source code for chaining to an aggregated
* mock object.
@@ -1245,36 +1204,44 @@
* @access private
*/
function _chainMockExpectations() {
- $code = " function expectArguments(\$method, \$args = false) {\n";
- $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code = " function expect(\$method, \$args = false) {\n";
+ $code .= $this->_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expect(\$method, \$args);\n";
+ $code .= " }\n";
+ $code .= " function expectArguments(\$method, \$args = false) {\n";
+ $code .= $this->_bailOutIfNotMocked("\$method");
$code .= " \$this->_mock->expectArguments(\$method, \$args);\n";
$code .= " }\n";
+ $code .= " function expectAt(\$timing, \$method, \$args = false) {\n";
+ $code .= $this->_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args);\n";
+ $code .= " }\n";
$code .= " function expectArgumentsAt(\$timing, \$method, \$args = false) {\n";
- $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= $this->_bailOutIfNotMocked("\$method");
$code .= " \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args);\n";
$code .= " }\n";
$code .= " function expectCallCount(\$method, \$count) {\n";
- $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= $this->_bailOutIfNotMocked("\$method");
$code .= " \$this->_mock->expectCallCount(\$method, \$count);\n";
$code .= " }\n";
$code .= " function expectMaximumCallCount(\$method, \$count) {\n";
- $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= $this->_bailOutIfNotMocked("\$method");
$code .= " \$this->_mock->expectMaximumCallCount(\$method, \$count);\n";
$code .= " }\n";
$code .= " function expectMinimumCallCount(\$method, \$count) {\n";
- $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= $this->_bailOutIfNotMocked("\$method");
$code .= " \$this->_mock->expectMinimumCallCount(\$method, \$count);\n";
$code .= " }\n";
$code .= " function expectNever(\$method) {\n";
- $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= $this->_bailOutIfNotMocked("\$method");
$code .= " \$this->_mock->expectNever(\$method);\n";
$code .= " }\n";
$code .= " function expectOnce(\$method, \$args = false) {\n";
- $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= $this->_bailOutIfNotMocked("\$method");
$code .= " \$this->_mock->expectOnce(\$method, \$args);\n";
$code .= " }\n";
$code .= " function expectAtLeastOnce(\$method, \$args = false) {\n";
- $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= $this->_bailOutIfNotMocked("\$method");
$code .= " \$this->_mock->expectAtLeastOnce(\$method, \$args);\n";
$code .= " }\n";
$code .= " function tally() {\n";
@@ -1282,7 +1249,7 @@
$code .= " }\n";
return $code;
}
-
+
/**
* Creates source code to override a list of methods
* with mock versions.
@@ -1294,30 +1261,13 @@
function _overrideMethods($methods) {
$code = "";
foreach ($methods as $method) {
- $code .= " function $method() {\n";
+ $code .= " " . $this->_reflection->getSignature($method) . " {\n";
$code .= " \$args = func_get_args();\n";
- $code .= " return \$this->_mock->_invoke(\"$method\", \$args);\n";
+ $code .= " \$result = &\$this->_mock->_invoke(\"$method\", \$args);\n";
+ $code .= " return \$result;\n";
$code .= " }\n";
}
return $code;
}
-
- /**
- * Uses a stack trace to find the line of an assertion.
- * @param string $format String formatting.
- * @param array $stack Stack frames top most first. Only
- * needed if not using the PHP
- * backtrace function.
- * @return string Line number of first expect*
- * method embedded in format string.
- * @access public
- * @static
- */
- function getExpectationLine($format = '%d', $stack = false) {
- if ($stack === false) {
- $stack = SimpleTestCompatibility::getStackTrace();
- }
- return SimpleDumper::getFormattedAssertionLine($stack, $format, 'expect');
- }
}
?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/page.php b/tests/test_tools/simpletest/page.php
index 843dedf5..a7dc3a78 100644
--- a/tests/test_tools/simpletest/page.php
+++ b/tests/test_tools/simpletest/page.php
@@ -3,7 +3,7 @@
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
- * @version $Id: page.php,v 1.105 2005/02/04 05:32:16 lastcraft Exp $
+ * @version $Id: page.php,v 1.131 2006/02/05 01:07:49 lastcraft Exp $
*/
/**#@+
@@ -13,8 +13,103 @@
require_once(dirname(__FILE__) . '/parser.php');
require_once(dirname(__FILE__) . '/tag.php');
require_once(dirname(__FILE__) . '/form.php');
+ require_once(dirname(__FILE__) . '/selector.php');
/**#@-*/
-
+
+ /**
+ * Creates tags and widgets given HTML tag
+ * attributes.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleTagBuilder {
+
+ /**
+ * Factory for the tag objects. Creates the
+ * appropriate tag object for the incoming tag name
+ * and attributes.
+ * @param string $name HTML tag name.
+ * @param hash $attributes Element attributes.
+ * @return SimpleTag Tag object.
+ * @access public
+ */
+ function createTag($name, $attributes) {
+ static $map = array(
+ 'a' => 'SimpleAnchorTag',
+ 'title' => 'SimpleTitleTag',
+ 'button' => 'SimpleButtonTag',
+ 'textarea' => 'SimpleTextAreaTag',
+ 'option' => 'SimpleOptionTag',
+ 'label' => 'SimpleLabelTag',
+ 'form' => 'SimpleFormTag',
+ 'frame' => 'SimpleFrameTag');
+ $attributes = $this->_keysToLowerCase($attributes);
+ if (array_key_exists($name, $map)) {
+ $tag_class = $map[$name];
+ return new $tag_class($attributes);
+ } elseif ($name == 'select') {
+ return $this->_createSelectionTag($attributes);
+ } elseif ($name == 'input') {
+ return $this->_createInputTag($attributes);
+ }
+ return new SimpleTag($name, $attributes);
+ }
+
+ /**
+ * Factory for selection fields.
+ * @param hash $attributes Element attributes.
+ * @return SimpleTag Tag object.
+ * @access protected
+ */
+ function _createSelectionTag($attributes) {
+ if (isset($attributes['multiple'])) {
+ return new MultipleSelectionTag($attributes);
+ }
+ return new SimpleSelectionTag($attributes);
+ }
+
+ /**
+ * Factory for input tags.
+ * @param hash $attributes Element attributes.
+ * @return SimpleTag Tag object.
+ * @access protected
+ */
+ function _createInputTag($attributes) {
+ if (! isset($attributes['type'])) {
+ return new SimpleTextTag($attributes);
+ }
+ $type = strtolower(trim($attributes['type']));
+ $map = array(
+ 'submit' => 'SimpleSubmitTag',
+ 'image' => 'SimpleImageSubmitTag',
+ 'checkbox' => 'SimpleCheckboxTag',
+ 'radio' => 'SimpleRadioButtonTag',
+ 'text' => 'SimpleTextTag',
+ 'hidden' => 'SimpleTextTag',
+ 'password' => 'SimpleTextTag',
+ 'file' => 'SimpleUploadTag');
+ if (array_key_exists($type, $map)) {
+ $tag_class = $map[$type];
+ return new $tag_class($attributes);
+ }
+ return false;
+ }
+
+ /**
+ * Make the keys lower case for case insensitive look-ups.
+ * @param hash $map Hash to convert.
+ * @return hash Unchanged values, but keys lower case.
+ * @access private
+ */
+ function _keysToLowerCase($map) {
+ $lower = array();
+ foreach ($map as $key => $value) {
+ $lower[strtolower($key)] = $value;
+ }
+ return $lower;
+ }
+ }
+
/**
* SAX event handler. Maintains a list of
* open tags and dispatches them as they close.
@@ -24,7 +119,8 @@
class SimplePageBuilder extends SimpleSaxListener {
protected $_tags;
protected $_page;
-
+ protected $_private_content_tag;
+
/**
* Sets the builder up empty.
* @access public
@@ -34,13 +130,24 @@
}
/**
+ * Frees up any references so as to allow the PHP garbage
+ * collection from unset() to work.
+ * @access public
+ */
+ function free() {
+ unset($this->_tags);
+ unset($this->_page);
+ unset($this->_private_content_tags);
+ }
+
+ /**
* Reads the raw content and send events
* into the page to be built.
* @param $response SimpleHttpResponse Fetched response.
* @return SimplePage Newly parsed page.
* @access public
*/
- function parse($response) {
+ function &parse($response) {
$this->_tags = array();
$this->_page = $this->_createPage($response);
$parser = $this->_createParser($this);
@@ -48,16 +155,17 @@
$this->_page->acceptPageEnd();
return $this->_page;
}
-
+
/**
* Creates an empty page.
* @return SimplePage New unparsed page.
* @access protected
*/
- function _createPage($response) {
- return new SimplePage($response);
+ function &_createPage($response) {
+ $page = new SimplePage($response);
+ return $page;
}
-
+
/**
* Creates the parser used with the builder.
* @param $listener SimpleSaxListener Target of parser.
@@ -65,22 +173,9 @@
* events for the builder.
* @access protected
*/
- function _createParser($listener) {
- return new SimpleSaxParser($listener);
- }
-
- /**
- * Make the keys lower case for case insensitive look-ups.
- * @param hash $map Hash to convert.
- * @return hash Unchanged values, but keys lower case.
- * @access private
- */
- function _keysToLowerCase($map) {
- $lower = array();
- foreach ($map as $key => $value) {
- $lower[strtolower($key)] = $value;
- }
- return $lower;
+ function &_createParser($listener) {
+ $parser = new SimpleHtmlSaxParser($listener);
+ return $parser;
}
/**
@@ -92,19 +187,31 @@
* @access public
*/
function startElement($name, $attributes) {
- $tag = $this->_createTag($name, $this->_keysToLowerCase($attributes));
- if ($name == 'form') {
+ $factory = new SimpleTagBuilder();
+ $tag = $factory->createTag($name, $attributes);
+ if (! $tag) {
+ return true;
+ }
+ if ($tag->getTagName() == 'label') {
+ $this->_page->acceptLabelStart($tag);
+ $this->_openTag($tag);
+ return true;
+ }
+ if ($tag->getTagName() == 'form') {
$this->_page->acceptFormStart($tag);
return true;
- }
- if ($name == 'frameset') {
+ }
+ if ($tag->getTagName() == 'frameset') {
$this->_page->acceptFramesetStart($tag);
return true;
- }
- if ($name == 'frame') {
+ }
+ if ($tag->getTagName() == 'frame') {
$this->_page->acceptFrame($tag);
return true;
- }
+ }
+ if ($tag->isPrivateContent() && ! isset($this->_private_content_tag)) {
+ $this->_private_content_tag = $tag;
+ }
if ($tag->expectEndTag()) {
$this->_openTag($tag);
return true;
@@ -112,7 +219,7 @@
$this->_page->acceptTag($tag);
return true;
}
-
+
/**
* End of element event.
* @param string $name Element name.
@@ -120,23 +227,41 @@
* @access public
*/
function endElement($name) {
+ if ($name == 'label') {
+ $this->_page->acceptLabelEnd();
+ return true;
+ }
if ($name == 'form') {
$this->_page->acceptFormEnd();
return true;
- }
+ }
if ($name == 'frameset') {
$this->_page->acceptFramesetEnd();
return true;
- }
- if (isset($this->_tags[$name]) && (count($this->_tags[$name]) > 0)) {
+ }
+ if ($this->_hasNamedTagOnOpenTagStack($name)) {
$tag = array_pop($this->_tags[$name]);
+ if ($tag->isPrivateContent() && $this->_private_content_tag->getTagName() == $name) {
+ unset($this->_private_content_tag);
+ }
$this->_addContentTagToOpenTags($tag);
$this->_page->acceptTag($tag);
return true;
}
return true;
}
-
+
+ /**
+ * Test to see if there are any open tags awaiting
+ * closure that match the tag name.
+ * @param string $name Element name.
+ * @return boolean True if any are still open.
+ * @access private
+ */
+ function _hasNamedTagOnOpenTagStack($name) {
+ return isset($this->_tags[$name]) && (count($this->_tags[$name]) > 0);
+ }
+
/**
* Unparsed, but relevant data. The data is added
* to every open tag.
@@ -145,18 +270,33 @@
* @access public
*/
function addContent($text) {
+ if (isset($this->_private_content_tag)) {
+ $this->_private_content_tag->addContent($text);
+ } else {
+ $this->_addContentToAllOpenTags($text);
+ }
+ return true;
+ }
+
+ /**
+ * Any content fills all currently open tags unless it
+ * is part of an option tag.
+ * @param string $text May include unparsed tags.
+ * @access private
+ */
+ function _addContentToAllOpenTags($text) {
foreach (array_keys($this->_tags) as $name) {
for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) {
$this->_tags[$name][$i]->addContent($text);
}
}
- return true;
}
-
+
/**
- * Parsed relevant data. The parsed tag is added
- * to every open tag.
- * @param SimpleTag $tag May include unparsed tags.
+ * Parsed data in tag form. The parsed tag is added
+ * to every open tag. Used for adding options to select
+ * fields only.
+ * @param SimpleTag $tag Option tags only.
* @access private
*/
function _addContentTagToOpenTags($tag) {
@@ -169,7 +309,7 @@
}
}
}
-
+
/**
* Opens a tag for receiving content. Multiple tags
* will be receiving input at the same time.
@@ -181,78 +321,10 @@
if (! in_array($name, array_keys($this->_tags))) {
$this->_tags[$name] = array();
}
- array_push($this->_tags[$name], $tag);
- }
-
- /**
- * Factory for the tag objects. Creates the
- * appropriate tag object for the incoming tag name.
- * @param string $name HTML tag name.
- * @param hash $attributes Element attributes.
- * @return SimpleTag Tag object.
- * @access protected
- */
- function _createTag($name, $attributes) {
- if ($name == 'a') {
- return new SimpleAnchorTag($attributes);
- } elseif ($name == 'title') {
- return new SimpleTitleTag($attributes);
- } elseif ($name == 'input') {
- return $this->_createInputTag($attributes);
- } elseif ($name == 'button') {
- return new SimpleButtonTag($attributes);
- } elseif ($name == 'textarea') {
- return new SimpleTextAreaTag($attributes);
- } elseif ($name == 'select') {
- return $this->_createSelectionTag($attributes);
- } elseif ($name == 'option') {
- return new SimpleOptionTag($attributes);
- } elseif ($name == 'form') {
- return new SimpleFormTag($attributes);
- } elseif ($name == 'frame') {
- return new SimpleFrameTag($attributes);
- }
- return new SimpleTag($name, $attributes);
- }
-
- /**
- * Factory for selection fields.
- * @param hash $attributes Element attributes.
- * @return SimpleTag Tag object.
- * @access protected
- */
- function _createSelectionTag($attributes) {
- if (isset($attributes['multiple'])) {
- return new MultipleSelectionTag($attributes);
- }
- return new SimpleSelectionTag($attributes);
- }
-
- /**
- * Factory for input tags.
- * @param hash $attributes Element attributes.
- * @return SimpleTag Tag object.
- * @access protected
- */
- function _createInputTag($attributes) {
- if (! isset($attributes['type'])) {
- return new SimpleTextTag($attributes);
- }
- $type = strtolower($attributes['type']);
- if ($type == 'submit') {
- return new SimpleSubmitTag($attributes);
- } elseif ($type == 'image') {
- return new SimpleImageSubmitTag($attributes);
- } elseif ($type == 'checkbox') {
- return new SimpleCheckboxTag($attributes);
- } elseif ($type == 'radio') {
- return new SimpleRadioButtonTag($attributes);
- } else {
- return new SimpleTextTag($attributes);
- }
+ $this->_tags[$name][] = $tag;
}
}
-
+
/**
* A wrapper for a web page.
* @package SimpleTest
@@ -261,6 +333,9 @@
class SimplePage {
protected $_links;
protected $_title;
+ protected $_last_widget;
+ protected $_label;
+ protected $_left_over_labels;
protected $_open_forms;
protected $_complete_forms;
protected $_frameset;
@@ -274,7 +349,7 @@
protected $_method;
protected $_url;
protected $_request_data;
-
+
/**
* Parses a page ready to access it's contents.
* @param SimpleHttpResponse $response Result of HTTP fetch.
@@ -283,6 +358,7 @@
function SimplePage($response = false) {
$this->_links = array();
$this->_title = false;
+ $this->_left_over_labels = array();
$this->_open_forms = array();
$this->_complete_forms = array();
$this->_frameset = false;
@@ -295,7 +371,7 @@
$this->_noResponse();
}
}
-
+
/**
* Extracts all of the response information.
* @param SimpleHttpResponse $response Response being parsed.
@@ -310,7 +386,7 @@
$this->_url = $response->getUrl();
$this->_request_data = $response->getRequestData();
}
-
+
/**
* Sets up a missing response.
* @access private
@@ -324,7 +400,7 @@
$this->_url = false;
$this->_request_data = false;
}
-
+
/**
* Original request as bytes sent down the wire.
* @return mixed Sent content.
@@ -333,7 +409,7 @@
function getRequest() {
return $this->_sent;
}
-
+
/**
* Accessor for raw text of page.
* @return string Raw unparsed content.
@@ -342,7 +418,7 @@
function getRaw() {
return $this->_raw;
}
-
+
/**
* Accessor for plain text of page as a text browser
* would see it.
@@ -351,11 +427,11 @@
*/
function getText() {
if (! $this->_text) {
- $this->_text = SimpleSaxParser::normalise($this->_raw);
+ $this->_text = SimpleHtmlSaxParser::normalise($this->_raw);
}
return $this->_text;
}
-
+
/**
* Accessor for raw headers of page.
* @return string Header block as text.
@@ -367,7 +443,7 @@
}
return false;
}
-
+
/**
* Original request method.
* @return string GET, POST or HEAD.
@@ -376,7 +452,7 @@
function getMethod() {
return $this->_method;
}
-
+
/**
* Original resource name.
* @return SimpleUrl Current url.
@@ -385,7 +461,7 @@
function getUrl() {
return $this->_url;
}
-
+
/**
* Original request data.
* @return mixed Sent content.
@@ -394,7 +470,7 @@
function getRequestData() {
return $this->_request_data;
}
-
+
/**
* Accessor for last error.
* @return string Error from last response.
@@ -403,7 +479,7 @@
function getTransportError() {
return $this->_transport_error;
}
-
+
/**
* Accessor for current MIME type.
* @return string MIME type as string; e.g. 'text/html'
@@ -415,7 +491,7 @@
}
return false;
}
-
+
/**
* Accessor for HTTP response code.
* @return integer HTTP response code received.
@@ -427,7 +503,7 @@
}
return false;
}
-
+
/**
* Accessor for last Authentication type. Only valid
* straight after a challenge (401).
@@ -440,7 +516,7 @@
}
return false;
}
-
+
/**
* Accessor for last Authentication realm. Only valid
* straight after a challenge (401).
@@ -453,7 +529,7 @@
}
return false;
}
-
+
/**
* Accessor for current frame focus. Will be
* false as no frames.
@@ -463,7 +539,7 @@
function getFrameFocus() {
return array();
}
-
+
/**
* Sets the focus by index. The integer index starts from 1.
* @param integer $choice Chosen frame.
@@ -473,7 +549,7 @@
function setFrameFocusByIndex($choice) {
return false;
}
-
+
/**
* Sets the focus by name. Always fails for a leaf page.
* @param string $name Chosen frame.
@@ -483,14 +559,14 @@
function setFrameFocus($name) {
return false;
}
-
+
/**
* Clears the frame focus. Does nothing for a leaf page.
* @access public
*/
function clearFrameFocus() {
}
-
+
/**
* Adds a tag to the page.
* @param SimpleTag $tag Tag to accept.
@@ -505,9 +581,36 @@
for ($i = 0; $i < count($this->_open_forms); $i++) {
$this->_open_forms[$i]->addWidget($tag);
}
+ $this->_last_widget = $tag;
}
}
-
+
+ /**
+ * Opens a label for a described widget.
+ * @param SimpleFormTag $tag Tag to accept.
+ * @access public
+ */
+ function acceptLabelStart($tag) {
+ $this->_label = $tag;
+ unset($this->_last_widget);
+ }
+
+ /**
+ * Closes the most recently opened label.
+ * @access public
+ */
+ function acceptLabelEnd() {
+ if (isset($this->_label)) {
+ if (isset($this->_last_widget)) {
+ $this->_last_widget->setLabel($this->_label->getText());
+ unset($this->_last_widget);
+ } else {
+ $this->_left_over_labels[] = SimpleTestCompatibility::copy($this->_label);
+ }
+ unset($this->_label);
+ }
+ }
+
/**
* Tests to see if a tag is a possible form
* element.
@@ -518,7 +621,7 @@
function _isFormElement($name) {
return in_array($name, array('input', 'button', 'textarea', 'select'));
}
-
+
/**
* Opens a form. New widgets go here.
* @param SimpleFormTag $tag Tag to accept.
@@ -527,7 +630,7 @@
function acceptFormStart($tag) {
$this->_open_forms[] = new SimpleForm($tag, $this->getUrl());
}
-
+
/**
* Closes the most recently opened form.
* @access public
@@ -537,7 +640,7 @@
$this->_complete_forms[] = array_pop($this->_open_forms);
}
}
-
+
/**
* Opens a frameset. A frameset may contain nested
* frameset tags.
@@ -550,7 +653,7 @@
}
$this->_frameset_nesting_level++;
}
-
+
/**
* Closes the most recently opened frameset.
* @access public
@@ -560,7 +663,7 @@
$this->_frameset_nesting_level--;
}
}
-
+
/**
* Takes a single frame tag and stashes it in
* the current frame set.
@@ -574,7 +677,7 @@
}
}
}
-
+
/**
* Test to see if in the middle of reading
* a frameset.
@@ -587,7 +690,7 @@
}
return ($this->_frameset_nesting_level > 0);
}
-
+
/**
* Test to see if link is an absolute one.
* @param string $url Url to test.
@@ -598,7 +701,7 @@
$parsed = new SimpleUrl($url);
return (boolean)($parsed->getScheme() && $parsed->getHost());
}
-
+
/**
* Adds a link to the page.
* @param SimpleAnchorTag $tag Link to accept.
@@ -607,7 +710,7 @@
function _addLink($tag) {
$this->_links[] = $tag;
}
-
+
/**
* Marker for end of complete page. Any work in
* progress can now be closed.
@@ -617,8 +720,15 @@
while (count($this->_open_forms)) {
$this->_complete_forms[] = array_pop($this->_open_forms);
}
+ foreach ($this->_left_over_labels as $label) {
+ for ($i = 0, $count = count($this->_complete_forms); $i < $count; $i++) {
+ $this->_complete_forms[$i]->attachLabelBySelector(
+ new SimpleById($label->getFor()),
+ $label->getText());
+ }
+ }
}
-
+
/**
* Test for the presence of a frameset.
* @return boolean True if frameset.
@@ -627,7 +737,7 @@
function hasFrames() {
return (boolean)$this->_frameset;
}
-
+
/**
* Accessor for frame name and source URL for every frame that
* will need to be loaded. Immediate children only.
@@ -649,7 +759,7 @@
}
return $urls;
}
-
+
/**
* Fetches a list of loaded frames.
* @return array/string Just the URL for a single page.
@@ -659,7 +769,7 @@
$url = $this->getUrl();
return $url->asString();
}
-
+
/**
* Accessor for a list of all fixed links.
* @return array List of urls with scheme of
@@ -675,7 +785,7 @@
}
return $all;
}
-
+
/**
* Accessor for a list of all relative links.
* @return array List of urls without hostname.
@@ -690,7 +800,7 @@
}
return $all;
}
-
+
/**
* Accessor for URLs by the link label. Label will match
* regardess of whitespace issues and case.
@@ -707,7 +817,7 @@
}
return $matches;
}
-
+
/**
* Accessor for a URL by the id attribute.
* @param string $id Id attribute of link.
@@ -722,7 +832,7 @@
}
return false;
}
-
+
/**
* Converts a link into a target URL.
* @param SimpleAnchor $link Parsed link.
@@ -736,7 +846,7 @@
}
return $url;
}
-
+
/**
* Expands expandomatic URLs into fully qualified
* URLs.
@@ -750,7 +860,7 @@
}
return $url->makeAbsolute($this->getUrl());
}
-
+
/**
* Sets the title tag contents.
* @param SimpleTitleTag $tag Title of page.
@@ -759,7 +869,7 @@
function _setTitle($tag) {
$this->_title = $tag;
}
-
+
/**
* Accessor for parsed title.
* @return string Title or false if no title is present.
@@ -771,103 +881,43 @@
}
return false;
}
-
- /**
- * Finds a held form by button label. Will only
- * search correctly built forms.
- * @param string $label Button label, default 'Submit'.
- * @return SimpleForm Form object containing the button.
- * @access public
- */
- function getFormBySubmitLabel($label) {
- for ($i = 0; $i < count($this->_complete_forms); $i++) {
- if ($this->_complete_forms[$i]->hasSubmitLabel($label)) {
- return $this->_complete_forms[$i];
- }
- }
- return null;
- }
-
+
/**
* Finds a held form by button label. Will only
* search correctly built forms.
- * @param string $name Button name attribute.
- * @return SimpleForm Form object containing the button.
- * @access public
- */
- function getFormBySubmitName($name) {
- for ($i = 0; $i < count($this->_complete_forms); $i++) {
- if ($this->_complete_forms[$i]->hasSubmitName($name)) {
- return $this->_complete_forms[$i];
- }
- }
- return null;
- }
-
- /**
- * Finds a held form by button id. Will only
- * search correctly built forms.
- * @param string $id Button ID attribute.
- * @return SimpleForm Form object containing the button.
+ * @param SimpleSelector $selector Button finder.
+ * @return SimpleForm Form object containing
+ * the button.
* @access public
*/
- function getFormBySubmitId($id) {
+ function &getFormBySubmit($selector) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
- if ($this->_complete_forms[$i]->hasSubmitId($id)) {
+ if ($this->_complete_forms[$i]->hasSubmit($selector)) {
return $this->_complete_forms[$i];
}
}
- return null;
+ $null = null;
+ return $null;
}
-
- /**
- * Finds a held form by image label. Will only
- * search correctly built forms.
- * @param string $label Usually the alt attribute.
- * @return SimpleForm Form object containing the image.
- * @access public
- */
- function getFormByImageLabel($label) {
- for ($i = 0; $i < count($this->_complete_forms); $i++) {
- if ($this->_complete_forms[$i]->hasImageLabel($label)) {
- return $this->_complete_forms[$i];
- }
- }
- return null;
- }
-
- /**
- * Finds a held form by image button id. Will only
- * search correctly built forms.
- * @param string $name Image name.
- * @return SimpleForm Form object containing the image.
- * @access public
- */
- function getFormByImageName($name) {
- for ($i = 0; $i < count($this->_complete_forms); $i++) {
- if ($this->_complete_forms[$i]->hasImageName($name)) {
- return $this->_complete_forms[$i];
- }
- }
- return null;
- }
-
+
/**
- * Finds a held form by image button id. Will only
- * search correctly built forms.
- * @param string $id Image ID attribute.
- * @return SimpleForm Form object containing the image.
+ * Finds a held form by image using a selector.
+ * Will only search correctly built forms.
+ * @param SimpleSelector $selector Image finder.
+ * @return SimpleForm Form object containing
+ * the image.
* @access public
*/
- function getFormByImageId($id) {
+ function &getFormByImage($selector) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
- if ($this->_complete_forms[$i]->hasImageId($id)) {
+ if ($this->_complete_forms[$i]->hasImage($selector)) {
return $this->_complete_forms[$i];
}
}
- return null;
+ $null = null;
+ return $null;
}
-
+
/**
* Finds a held form by the form ID. A way of
* identifying a specific form when we have control
@@ -876,81 +926,45 @@
* @return SimpleForm Form object containing the matching ID.
* @access public
*/
- function getFormById($id) {
+ function &getFormById($id) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
if ($this->_complete_forms[$i]->getId() == $id) {
return $this->_complete_forms[$i];
}
}
- return null;
+ $null = null;
+ return $null;
}
-
+
/**
* Sets a field on each form in which the field is
* available.
- * @param string $name Field name.
- * @param string $value Value to set field to.
- * @return boolean True if value is valid.
+ * @param SimpleSelector $selector Field finder.
+ * @param string $value Value to set field to.
+ * @return boolean True if value is valid.
* @access public
*/
- function setField($name, $value) {
+ function setField($selector, $value) {
$is_set = false;
for ($i = 0; $i < count($this->_complete_forms); $i++) {
- if ($this->_complete_forms[$i]->setField($name, $value)) {
+ if ($this->_complete_forms[$i]->setField($selector, $value)) {
$is_set = true;
}
}
return $is_set;
}
-
- /**
- * Sets a field on the form in which the unique field is
- * available.
- * @param string/integer $id Field ID attribute.
- * @param string $value Value to set field to.
- * @return boolean True if value is valid.
- * @access public
- */
- function setFieldById($id, $value) {
- for ($i = 0; $i < count($this->_complete_forms); $i++) {
- if ($this->_complete_forms[$i]->setFieldById($id, $value)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Accessor for a form element value within a page.
- * Finds the first match.
- * @param string $name Field name.
- * @return string/boolean A string if the field is
- * present, false if unchecked
- * and null if missing.
- * @access public
- */
- function getField($name) {
- for ($i = 0; $i < count($this->_complete_forms); $i++) {
- $value = $this->_complete_forms[$i]->getValue($name);
- if (isset($value)) {
- return $value;
- }
- }
- return null;
- }
-
+
/**
* Accessor for a form element value within a page.
- * Finds the first match.
- * @param string/integer $id Field ID attribute.
- * @return string/boolean A string if the field is
- * present, false if unchecked
- * and null if missing.
+ * @param SimpleSelector $selector Field finder.
+ * @return string/boolean A string if the field is
+ * present, false if unchecked
+ * and null if missing.
* @access public
*/
- function getFieldById($id) {
+ function getField($selector) {
for ($i = 0; $i < count($this->_complete_forms); $i++) {
- $value = $this->_complete_forms[$i]->getValueById($id);
+ $value = $this->_complete_forms[$i]->getValue($selector);
if (isset($value)) {
return $value;
}
diff --git a/tests/test_tools/simpletest/parser.php b/tests/test_tools/simpletest/parser.php
index 7dc56a58..3f58e7e9 100644
--- a/tests/test_tools/simpletest/parser.php
+++ b/tests/test_tools/simpletest/parser.php
@@ -3,23 +3,33 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage MockObjects
- * @version $Id: parser.php,v 1.66 2005/02/06 04:03:27 lastcraft Exp $
+ * @version $Id: parser.php,v 1.72 2006/01/04 03:15:05 lastcraft Exp $
*/
/**#@+
* Lexer mode stack constants
*/
- define("LEXER_ENTER", 1);
- define("LEXER_MATCHED", 2);
- define("LEXER_UNMATCHED", 3);
- define("LEXER_EXIT", 4);
- define("LEXER_SPECIAL", 5);
+ if (! defined('LEXER_ENTER')) {
+ define('LEXER_ENTER', 1);
+ }
+ if (! defined('LEXER_MATCHED')) {
+ define('LEXER_MATCHED', 2);
+ }
+ if (! defined('LEXER_UNMATCHED')) {
+ define('LEXER_UNMATCHED', 3);
+ }
+ if (! defined('LEXER_EXIT')) {
+ define('LEXER_EXIT', 4);
+ }
+ if (! defined('LEXER_SPECIAL')) {
+ define('LEXER_SPECIAL', 5);
+ }
/**#@-*/
/**
* Compounded regular expression. Any of
* the contained patterns could match and
- * when one does it's label is returned.
+ * when one does, it's label is returned.
* @package SimpleTest
* @subpackage WebTester
*/
@@ -441,57 +451,27 @@
}
/**
- * Converts HTML tokens into selected SAX events.
+ * Breas HTML into SAX events.
* @package SimpleTest
* @subpackage WebTester
*/
- class SimpleSaxParser {
- protected $_lexer;
- protected $_listener;
- protected $_tag;
- protected $_attributes;
- protected $_current_attribute;
-
- /**
- * Sets the listener.
- * @param SimpleSaxListener $listener SAX event handler.
- * @access public
- */
- function SimpleSaxParser($listener) {
- $this->_listener = $listener;
- $this->_lexer = $this->createLexer($this);
- $this->_tag = '';
- $this->_attributes = array();
- $this->_current_attribute = '';
- }
-
- /**
- * Runs the content through the lexer which
- * should call back to the acceptors.
- * @param string $raw Page text to parse.
- * @return boolean False if parse error.
- * @access public
- */
- function parse($raw) {
- return $this->_lexer->parse($raw);
- }
+ class SimpleHtmlLexer extends SimpleLexer {
/**
- * Sets up the matching lexer. Starts in 'text' mode.
- * @param SimpleSaxParser $parser Event generator, usually $self.
- * @return SimpleLexer Lexer suitable for this parser.
+ * Sets up the lexer with case insensitive matching
+ * and adds the HTML handlers.
+ * @param SimpleSaxParser $parser Handling strategy by
+ * reference.
* @access public
- * @static
*/
- function createLexer($parser) {
- $lexer = new SimpleLexer($parser, 'text');
- $lexer->mapHandler('text', 'acceptTextToken');
- SimpleSaxParser::_addSkipping($lexer);
- foreach (SimpleSaxParser::_getParsedTags() as $tag) {
- SimpleSaxParser::_addTag($lexer, $tag);
+ function SimpleHtmlLexer($parser) {
+ $this->SimpleLexer($parser, 'text');
+ $this->mapHandler('text', 'acceptTextToken');
+ $this->_addSkipping();
+ foreach ($this->_getParsedTags() as $tag) {
+ $this->_addTag($tag);
}
- SimpleSaxParser::_addInTagTokens($lexer);
- return $lexer;
+ $this->_addInTagTokens();
}
/**
@@ -501,72 +481,114 @@
*/
function _getParsedTags() {
return array('a', 'title', 'form', 'input', 'button', 'textarea', 'select',
- 'option', 'frameset', 'frame');
+ 'option', 'frameset', 'frame', 'label');
}
/**
* The lexer has to skip certain sections such
* as server code, client code and styles.
- * @param SimpleLexer $lexer Lexer to add patterns to.
* @access private
- * @static
*/
- function _addSkipping($lexer) {
- $lexer->mapHandler('css', 'ignore');
- $lexer->addEntryPattern('<style', 'text', 'css');
- $lexer->addExitPattern('</style>', 'css');
- $lexer->mapHandler('js', 'ignore');
- $lexer->addEntryPattern('<script', 'text', 'js');
- $lexer->addExitPattern('</script>', 'js');
- $lexer->mapHandler('comment', 'ignore');
- $lexer->addEntryPattern('<!--', 'text', 'comment');
- $lexer->addExitPattern('-->', 'comment');
+ function _addSkipping() {
+ $this->mapHandler('css', 'ignore');
+ $this->addEntryPattern('<style', 'text', 'css');
+ $this->addExitPattern('</style>', 'css');
+ $this->mapHandler('js', 'ignore');
+ $this->addEntryPattern('<script', 'text', 'js');
+ $this->addExitPattern('</script>', 'js');
+ $this->mapHandler('comment', 'ignore');
+ $this->addEntryPattern('<!--', 'text', 'comment');
+ $this->addExitPattern('-->', 'comment');
}
/**
* Pattern matches to start and end a tag.
- * @param SimpleLexer $lexer Lexer to add patterns to.
* @param string $tag Name of tag to scan for.
* @access private
- * @static
*/
- function _addTag($lexer, $tag) {
- $lexer->addSpecialPattern("</$tag>", 'text', 'acceptEndToken');
- $lexer->addEntryPattern("<$tag", 'text', 'tag');
+ function _addTag($tag) {
+ $this->addSpecialPattern("</$tag>", 'text', 'acceptEndToken');
+ $this->addEntryPattern("<$tag", 'text', 'tag');
}
/**
* Pattern matches to parse the inside of a tag
* including the attributes and their quoting.
- * @param SimpleLexer $lexer Lexer to add patterns to.
* @access private
- * @static
*/
- function _addInTagTokens($lexer) {
- $lexer->mapHandler('tag', 'acceptStartToken');
- $lexer->addSpecialPattern('\s+', 'tag', 'ignore');
- SimpleSaxParser::_addAttributeTokens($lexer);
- $lexer->addExitPattern('>', 'tag');
+ function _addInTagTokens() {
+ $this->mapHandler('tag', 'acceptStartToken');
+ $this->addSpecialPattern('\s+', 'tag', 'ignore');
+ $this->_addAttributeTokens();
+ $this->addExitPattern('/>', 'tag');
+ $this->addExitPattern('>', 'tag');
}
/**
* Matches attributes that are either single quoted,
* double quoted or unquoted.
- * @param SimpleLexer $lexer Lexer to add patterns to.
* @access private
+ */
+ function _addAttributeTokens() {
+ $this->mapHandler('dq_attribute', 'acceptAttributeToken');
+ $this->addEntryPattern('=\s*"', 'tag', 'dq_attribute');
+ $this->addPattern("\\\\\"", 'dq_attribute');
+ $this->addExitPattern('"', 'dq_attribute');
+ $this->mapHandler('sq_attribute', 'acceptAttributeToken');
+ $this->addEntryPattern("=\s*'", 'tag', 'sq_attribute');
+ $this->addPattern("\\\\'", 'sq_attribute');
+ $this->addExitPattern("'", 'sq_attribute');
+ $this->mapHandler('uq_attribute', 'acceptAttributeToken');
+ $this->addSpecialPattern('=\s*[^>\s]*', 'tag', 'uq_attribute');
+ }
+ }
+
+ /**
+ * Converts HTML tokens into selected SAX events.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleHtmlSaxParser {
+ protected $_lexer;
+ protected $_listener;
+ protected $_tag;
+ protected $_attributes;
+ protected $_current_attribute;
+
+ /**
+ * Sets the listener.
+ * @param SimpleSaxListener $listener SAX event handler.
+ * @access public
+ */
+ function SimpleHtmlSaxParser($listener) {
+ $this->_listener = $listener;
+ $this->_lexer = $this->createLexer($this);
+ $this->_tag = '';
+ $this->_attributes = array();
+ $this->_current_attribute = '';
+ }
+
+ /**
+ * Runs the content through the lexer which
+ * should call back to the acceptors.
+ * @param string $raw Page text to parse.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function parse($raw) {
+ return $this->_lexer->parse($raw);
+ }
+
+ /**
+ * Sets up the matching lexer. Starts in 'text' mode.
+ * @param SimpleSaxParser $parser Event generator, usually $self.
+ * @return SimpleLexer Lexer suitable for this parser.
+ * @access public
* @static
*/
- function _addAttributeTokens($lexer) {
- $lexer->mapHandler('dq_attribute', 'acceptAttributeToken');
- $lexer->addEntryPattern('=\s*"', 'tag', 'dq_attribute');
- $lexer->addPattern("\\\\\"", 'dq_attribute');
- $lexer->addExitPattern('"', 'dq_attribute');
- $lexer->mapHandler('sq_attribute', 'acceptAttributeToken');
- $lexer->addEntryPattern("=\s*'", 'tag', 'sq_attribute');
- $lexer->addPattern("\\\\'", 'sq_attribute');
- $lexer->addExitPattern("'", 'sq_attribute');
- $lexer->mapHandler('uq_attribute', 'acceptAttributeToken');
- $lexer->addSpecialPattern('=\s*[^>\s]*', 'tag', 'uq_attribute');
+ function &createLexer($parser) {
+ $lexer = new SimpleHtmlLexer($parser);
+ return $lexer;
}
/**
@@ -589,13 +611,13 @@
$success = $this->_listener->startElement(
$this->_tag,
$this->_attributes);
- $this->_tag = "";
+ $this->_tag = '';
$this->_attributes = array();
return $success;
}
- if ($token != "=") {
- $this->_current_attribute = strtolower(SimpleSaxParser::decodeHtml($token));
- $this->_attributes[$this->_current_attribute] = "";
+ if ($token != '=') {
+ $this->_current_attribute = strtolower(SimpleHtmlSaxParser::decodeHtml($token));
+ $this->_attributes[$this->_current_attribute] = '';
}
return true;
}
@@ -625,11 +647,11 @@
function acceptAttributeToken($token, $event) {
if ($event == LEXER_UNMATCHED) {
$this->_attributes[$this->_current_attribute] .=
- SimpleSaxParser::decodeHtml($token);
+ SimpleHtmlSaxParser::decodeHtml($token);
}
if ($event == LEXER_SPECIAL) {
$this->_attributes[$this->_current_attribute] .=
- preg_replace('/^=\s*/' , '', SimpleSaxParser::decodeHtml($token));
+ preg_replace('/^=\s*/' , '', SimpleHtmlSaxParser::decodeHtml($token));
}
return true;
}
@@ -692,11 +714,12 @@
* @static
*/
function normalise($html) {
- $text = preg_replace('|<img.*?alt\s*=\s*"(.*?)".*?>|', ' \1 ', $html);
+ $text = preg_replace('|<!--.*?-->|', '', $html);
+ $text = preg_replace('|<img.*?alt\s*=\s*"(.*?)".*?>|', ' \1 ', $text);
$text = preg_replace('|<img.*?alt\s*=\s*\'(.*?)\'.*?>|', ' \1 ', $text);
$text = preg_replace('|<img.*?alt\s*=\s*([a-zA-Z_]+).*?>|', ' \1 ', $text);
$text = preg_replace('|<.*?>|', '', $text);
- $text = SimpleSaxParser::decodeHtml($text);
+ $text = SimpleHtmlSaxParser::decodeHtml($text);
$text = preg_replace('|\s+|', ' ', $text);
return trim($text);
}
diff --git a/tests/test_tools/simpletest/reflection_php4.php b/tests/test_tools/simpletest/reflection_php4.php
new file mode 100644
index 00000000..acd0d32d
--- /dev/null
+++ b/tests/test_tools/simpletest/reflection_php4.php
@@ -0,0 +1,115 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: reflection_php4.php,v 1.9 2005/11/22 02:07:32 lastcraft Exp $
+ */
+
+ /**
+ * Version specific reflection API.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleReflection {
+ protected $_interface;
+
+ /**
+ * Stashes the class/interface.
+ * @param string $interface Class or interface
+ * to inspect.
+ */
+ function SimpleReflection($interface) {
+ $this->_interface = $interface;
+ }
+
+ /**
+ * Checks that a class has been declared.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classExists() {
+ return class_exists($this->_interface);
+ }
+
+ /**
+ * Needed to kill the autoload feature in PHP5
+ * for classes created dynamically.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classExistsSansAutoload() {
+ return class_exists($this->_interface);
+ }
+
+ /**
+ * Checks that a class or interface has been
+ * declared.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classOrInterfaceExists() {
+ return class_exists($this->_interface);
+ }
+
+ /**
+ * Needed to kill the autoload feature in PHP5
+ * for classes created dynamically.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classOrInterfaceExistsSansAutoload() {
+ return class_exists($this->_interface);
+ }
+
+ /**
+ * Gets the list of methods on a class or
+ * interface.
+ * @returns array List of method names.
+ * @access public
+ */
+ function getMethods() {
+ return get_class_methods($this->_interface);
+ }
+
+ /**
+ * Gets the list of interfaces from a class. If the
+ * class name is actually an interface then just that
+ * interface is returned.
+ * @returns array List of interfaces.
+ * @access public
+ */
+ function getInterfaces() {
+ return array();
+ }
+
+ /**
+ * Finds the parent class name.
+ * @returns string Parent class name.
+ * @access public
+ */
+ function getParent() {
+ return strtolower(get_parent_class($this->_interface));
+ }
+
+ /**
+ * Determines if the class is abstract, which for PHP 4
+ * will never be the case.
+ * @returns boolean True if abstract.
+ * @access public
+ */
+ function isAbstract() {
+ return false;
+ }
+
+ /**
+ * Gets the source code matching the declaration
+ * of a method.
+ * @param string $method Method name.
+ * @access public
+ */
+ function getSignature($method) {
+ return "function $method()";
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/reflection_php5.php b/tests/test_tools/simpletest/reflection_php5.php
new file mode 100644
index 00000000..70419f7d
--- /dev/null
+++ b/tests/test_tools/simpletest/reflection_php5.php
@@ -0,0 +1,275 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: reflection_php5.php,v 1.20 2006/02/05 21:39:07 lastcraft Exp $
+ */
+
+ /**
+ * Version specific reflection API.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleReflection {
+ protected $_interface;
+
+ /**
+ * Stashes the class/interface.
+ * @param string $interface Class or interface
+ * to inspect.
+ */
+ function SimpleReflection($interface) {
+ $this->_interface = $interface;
+ }
+
+ /**
+ * Checks that a class has been declared. Versions
+ * before PHP5.0.2 need a check that it's not really
+ * an interface.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classExists() {
+ if (! class_exists($this->_interface)) {
+ return false;
+ }
+ $reflection = new ReflectionClass($this->_interface);
+ return ! $reflection->isInterface();
+ }
+
+ /**
+ * Needed to kill the autoload feature in PHP5
+ * for classes created dynamically.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classExistsSansAutoload() {
+ return class_exists($this->_interface, false);
+ }
+
+ /**
+ * Checks that a class or interface has been
+ * declared.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classOrInterfaceExists() {
+ return $this->_classOrInterfaceExistsWithAutoload($this->_interface, true);
+ }
+
+ /**
+ * Needed to kill the autoload feature in PHP5
+ * for classes created dynamically.
+ * @return boolean True if defined.
+ * @access public
+ */
+ function classOrInterfaceExistsSansAutoload() {
+ return $this->_classOrInterfaceExistsWithAutoload($this->_interface, false);
+ }
+
+ /**
+ * Needed to select the autoload feature in PHP5
+ * for classes created dynamically.
+ * @param string $interface Class or interface name.
+ * @param boolean $autoload True totriggerautoload.
+ * @return boolean True if interface defined.
+ * @access private
+ */
+ function _classOrInterfaceExistsWithAutoload($interface, $autoload) {
+ if (function_exists('interface_exists')) {
+ if (interface_exists($this->_interface, $autoload)) {
+ return true;
+ }
+ }
+ return class_exists($this->_interface, $autoload);
+ }
+
+ /**
+ * Gets the list of methods on a class or
+ * interface. Needs to recursively look at all of
+ * the interfaces included.
+ * @returns array List of method names.
+ * @access public
+ */
+ function getMethods() {
+ return array_unique(get_class_methods($this->_interface));
+ }
+
+ /**
+ * Gets the list of interfaces from a class. If the
+ * class name is actually an interface then just that
+ * interface is returned.
+ * @returns array List of interfaces.
+ * @access public
+ */
+ function getInterfaces() {
+ $reflection = new ReflectionClass($this->_interface);
+ if ($reflection->isInterface()) {
+ return array($this->_interface);
+ }
+ return $this->_onlyParents($reflection->getInterfaces());
+ }
+
+ /**
+ * Gets the list of methods for the implemented
+ * interfaces only.
+ * @returns array List of enforced method signatures.
+ * @access public
+ */
+ function getInterfaceMethods() {
+ $methods = array();
+ foreach ($this->getInterfaces() as $interface) {
+ $methods = array_merge($methods, get_class_methods($interface));
+ }
+ return array_unique($methods);
+ }
+
+ /**
+ * Checks to see if the method signature has to be tightly
+ * specified.
+ * @param string $method Method name.
+ * @returns boolean True if enforced.
+ * @access private
+ */
+ function _isInterfaceMethod($method) {
+ return in_array($method, $this->getInterfaceMethods());
+ }
+
+ /**
+ * Finds the parent class name.
+ * @returns string Parent class name.
+ * @access public
+ */
+ function getParent() {
+ $reflection = new ReflectionClass($this->_interface);
+ $parent = $reflection->getParentClass();
+ if ($parent) {
+ return $parent->getName();
+ }
+ return false;
+ }
+
+ /**
+ * Determines if the class is abstract.
+ * @returns boolean True if abstract.
+ * @access public
+ */
+ function isAbstract() {
+ $reflection = new ReflectionClass($this->_interface);
+ return $reflection->isAbstract();
+ }
+
+ /**
+ * Wittles a list of interfaces down to only the top
+ * level parents.
+ * @param array $interfaces Reflection API interfaces
+ * to reduce.
+ * @returns array List of parent interface names.
+ * @access private
+ */
+ function _onlyParents($interfaces) {
+ $parents = array();
+ foreach ($interfaces as $interface) {
+ foreach($interfaces as $possible_parent) {
+ if ($interface->getName() == $possible_parent->getName()) {
+ continue;
+ }
+ if ($interface->isSubClassOf($possible_parent)) {
+ break;
+ }
+ }
+ $parents[] = $interface->getName();
+ }
+ return $parents;
+ }
+
+ /**
+ * Gets the source code matching the declaration
+ * of a method.
+ * @param string $name Method name.
+ * @return string Method signature up to last
+ * bracket.
+ * @access public
+ */
+ function getSignature($name) {
+ if ($name == '__get') {
+ return 'function __get($key)';
+ }
+ if ($name == '__set') {
+ return 'function __set($key, $value)';
+ }
+ if (! is_callable(array($this->_interface, $name))) {
+ return "function $name()";
+ }
+ if ($this->_isInterfaceMethod($name)) {
+ return $this->_getFullSignature($name);
+ }
+ return "function $name()";
+ }
+
+ /**
+ * For a signature specified in an interface, full
+ * details must be replicated to be a valid implementation.
+ * @param string $name Method name.
+ * @return string Method signature up to last
+ * bracket.
+ * @access private
+ */
+ function _getFullSignature($name) {
+ $interface = new ReflectionClass($this->_interface);
+ $method = $interface->getMethod($name);
+ $reference = $method->returnsReference() ? '&' : '';
+ return "function $reference$name(" .
+ implode(', ', $this->_getParameterSignatures($method)) .
+ ")";
+ }
+
+ /**
+ * Gets the source code for each parameter.
+ * @param ReflectionMethod $method Method object from
+ * reflection API
+ * @return array List of strings, each
+ * a snippet of code.
+ * @access private
+ */
+ function _getParameterSignatures($method) {
+ $signatures = array();
+ foreach ($method->getParameters() as $parameter) {
+ $type = $parameter->getClass();
+ $signatures[] =
+ (! is_null($type) ? $type->getName() . ' ' : '') .
+ ($parameter->isPassedByReference() ? '&' : '') .
+ '$' . $this->_suppressSpurious($parameter->getName()) .
+ ($this->_isOptional($parameter) ? ' = null' : '');
+ }
+ return $signatures;
+ }
+
+ /**
+ * The SPL library has problems with the
+ * Reflection library. In particular, you can
+ * get extra characters in parameter names :(.
+ * @param string $name Parameter name.
+ * @return string Cleaner name.
+ * @access private
+ */
+ function _suppressSpurious($name) {
+ return str_replace(array('[', ']', ' '), '', $name);
+ }
+
+ /**
+ * Test of a reflection parameter being optional
+ * that works with early versions of PHP5.
+ * @param reflectionParameter $parameter Is this optional.
+ * @return boolean True if optional.
+ * @access private
+ */
+ function _isOptional($parameter) {
+ if (method_exists($parameter, 'isOptional')) {
+ return $parameter->isOptional();
+ }
+ return false;
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/remote.php b/tests/test_tools/simpletest/remote.php
index 5a5f2d32..adb020a9 100644
--- a/tests/test_tools/simpletest/remote.php
+++ b/tests/test_tools/simpletest/remote.php
@@ -3,7 +3,7 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
- * @version $Id: remote.php,v 1.11 2004/08/04 22:09:39 lastcraft Exp $
+ * @version $Id: remote.php,v 1.12 2005/08/03 17:26:55 lastcraft Exp $
*/
/**#@+
@@ -11,7 +11,7 @@
*/
require_once(dirname(__FILE__) . '/browser.php');
require_once(dirname(__FILE__) . '/xml.php');
- require_once(dirname(__FILE__) . '/simple_test.php');
+ require_once(dirname(__FILE__) . '/test_case.php');
/**#@-*/
/**
@@ -74,7 +74,7 @@
* @return SimpleBrowser New browser.
* @access protected
*/
- function _createBrowser() {
+ function &_createBrowser() {
return new SimpleBrowser();
}
@@ -84,7 +84,7 @@
* @return SimpleTestXmlListener XML reader.
* @access protected
*/
- function _createParser($reporter) {
+ function &_createParser($reporter) {
return new SimpleTestXmlParser($reporter);
}
diff --git a/tests/test_tools/simpletest/reporter.php b/tests/test_tools/simpletest/reporter.php
index 32125c9b..ea3895e3 100644
--- a/tests/test_tools/simpletest/reporter.php
+++ b/tests/test_tools/simpletest/reporter.php
@@ -3,7 +3,7 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
- * @version $Id: reporter.php,v 1.33 2004/11/29 04:35:49 lastcraft Exp $
+ * @version $Id: reporter.php,v 1.36 2006/02/06 06:05:18 lastcraft Exp $
*/
/**#@+
@@ -11,7 +11,7 @@
*/
require_once(dirname(__FILE__) . '/scorer.php');
/**#@-*/
-
+
/**
* Sample minimal test displayer. Generates only
* failure messages and a pass count.
@@ -20,7 +20,7 @@
*/
class HtmlReporter extends SimpleReporter {
protected $_character_set;
-
+
/**
* Does nothing yet. The first output will
* be sent on the first test start. For use
@@ -31,7 +31,7 @@
$this->SimpleReporter();
$this->_character_set = $character_set;
}
-
+
/**
* Paints the top of the web page setting the
* title to the name of the starting test.
@@ -50,7 +50,7 @@
print "<h1>$test_name</h1>\n";
flush();
}
-
+
/**
* Send the headers necessary to ensure the page is
* reloaded on every request. Otherwise you could be
@@ -67,7 +67,7 @@
header("Pragma: no-cache");
}
}
-
+
/**
* Paints the CSS. Add additional styles here.
* @return string CSS code as text.
@@ -76,7 +76,7 @@
function _getCss() {
return ".fail { color: red; } pre { background-color: lightgray; }";
}
-
+
/**
* Paints the end of the test with a summary of
* the passes and failures.
@@ -96,7 +96,7 @@
print "</div>\n";
print "</body>\n</html>\n";
}
-
+
/**
* Paints the test failure with a breadcrumbs
* trail of the nesting test suites below the
@@ -113,22 +113,22 @@
print implode(" -&gt; ", $breadcrumb);
print " -&gt; " . $this->_htmlEntities($message) . "<br />\n";
}
-
+
/**
* Paints a PHP error or exception.
* @param string $message Message is ignored.
* @access public
* @abstract
*/
- function paintException($message) {
- parent::paintException($message);
+ function paintError($message) {
+ parent::paintError($message);
print "<span class=\"fail\">Exception</span>: ";
$breadcrumb = $this->getTestList();
array_shift($breadcrumb);
print implode(" -&gt; ", $breadcrumb);
print " -&gt; <strong>" . $this->_htmlEntities($message) . "</strong><br />\n";
}
-
+
/**
* Paints formatted text such as dumped variables.
* @param string $message Text to show.
@@ -137,7 +137,7 @@
function paintFormattedMessage($message) {
print '<pre>' . $this->_htmlEntities($message) . '</pre>';
}
-
+
/**
* Character set adjusted entity conversion.
* @param string $message Plain text or Unicode message.
@@ -148,7 +148,7 @@
return htmlentities($message, ENT_COMPAT, $this->_character_set);
}
}
-
+
/**
* Sample minimal test displayer. Generates only
* failure messages and a pass count. For command
@@ -159,7 +159,7 @@
* @subpackage UnitTester
*/
class TextReporter extends SimpleReporter {
-
+
/**
* Does nothing yet. The first output will
* be sent on the first test start.
@@ -168,7 +168,7 @@
function TextReporter() {
$this->SimpleReporter();
}
-
+
/**
* Paints the title only.
* @param string $test_name Name class of test.
@@ -181,7 +181,7 @@
print "$test_name\n";
flush();
}
-
+
/**
* Paints the end of the test with a summary of
* the passes and failures.
@@ -199,13 +199,12 @@
", Passes: " . $this->getPassCount() .
", Failures: " . $this->getFailCount() .
", Exceptions: " . $this->getExceptionCount() . "\n";
-
}
-
+
/**
* Paints the test failure as a stack trace.
- * @param string $message Failure message displayed in
- * the context of the other tests.
+ * @param string $message Failure message displayed in
+ * the context of the other tests.
* @access public
*/
function paintFail($message) {
@@ -216,18 +215,18 @@
print "\tin " . implode("\n\tin ", array_reverse($breadcrumb));
print "\n";
}
-
+
/**
* Paints a PHP error or exception.
* @param string $message Message is ignored.
* @access public
* @abstract
*/
- function paintException($message) {
- parent::paintException($message);
+ function paintError($message) {
+ parent::paintError($message);
print "Exception " . $this->getExceptionCount() . "!\n$message\n";
}
-
+
/**
* Paints formatted text such as dumped variables.
* @param string $message Text to show.
@@ -238,4 +237,131 @@
flush();
}
}
-?>
+
+ /**
+ * Runs just a single test group, a single case or
+ * even a single test within that case.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SelectiveReporter extends SimpleReporterDecorator {
+ protected $_just_this_case =false;
+ protected $_just_this_test = false;
+ protected $_within_test_case = true;
+
+ /**
+ * Selects the test case or group to be run,
+ * and optionally a specific test.
+ * @param SimpleScorer $reporter Reporter to receive events.
+ * @param string $just_this_case Only this case or group will run.
+ * @param string $just_this_test Only this test method will run.
+ */
+ function SelectiveReporter($reporter, $just_this_case = false, $just_this_test = false) {
+ if (isset($just_this_case) && $just_this_case) {
+ $this->_just_this_case = strtolower($just_this_case);
+ $this->_within_test_case = false;
+ }
+ if (isset($just_this_test) && $just_this_test) {
+ $this->_just_this_test = strtolower($just_this_test);
+ }
+ $this->SimpleReporterDecorator($reporter);
+ }
+
+ /**
+ * Compares criteria to actual the case/group name.
+ * @param string $test_case The incoming test.
+ * @return boolean True if matched.
+ * @access protected
+ */
+ function _isCaseMatch($test_case) {
+ if ($this->_just_this_case) {
+ return $this->_just_this_case == strtolower($test_case);
+ }
+ return false;
+ }
+
+ /**
+ * Compares criteria to actual the test name.
+ * @param string $method The incoming test method.
+ * @return boolean True if matched.
+ * @access protected
+ */
+ function _isTestMatch($method) {
+ if ($this->_just_this_test) {
+ return $this->_just_this_test == strtolower($method);
+ }
+ return true;
+ }
+
+ /**
+ * Veto everything that doesn't match the method wanted.
+ * @param string $test_case Name of test case.
+ * @param string $method Name of test method.
+ * @return boolean True if test should be run.
+ * @access public
+ */
+ function shouldInvoke($test_case, $method) {
+ if ($this->_within_test_case && $this->_isTestMatch($method)) {
+ return $this->_reporter->shouldInvoke($test_case, $method);
+ }
+ return false;
+ }
+
+ /**
+ * Paints the start of a group test.
+ * @param string $test_case Name of test or other label.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($test_case, $size) {
+ if ($this->_isCaseMatch($test_case)) {
+ $this->_within_test_case = true;
+ }
+ if ($this->_within_test_case) {
+ $this->_reporter->paintGroupStart($test_case, $size);
+ }
+ }
+
+ /**
+ * Paints the end of a group test.
+ * @param string $test_case Name of test or other label.
+ * @access public
+ */
+ function paintGroupEnd($test_case) {
+ if ($this->_within_test_case) {
+ $this->_reporter->paintGroupEnd($test_case);
+ }
+ if ($this->_isCaseMatch($test_case)) {
+ $this->_within_test_case = false;
+ }
+ }
+
+ /**
+ * Paints the start of a test case.
+ * @param string $test_case Name of test or other label.
+ * @access public
+ */
+ function paintCaseStart($test_case) {
+ if ($this->_isCaseMatch($test_case)) {
+ $this->_within_test_case = true;
+ }
+ if ($this->_within_test_case) {
+ $this->_reporter->paintCaseStart($test_case);
+ }
+ }
+
+ /**
+ * Paints the end of a test case.
+ * @param string $test_case Name of test or other label.
+ * @access public
+ */
+ function paintCaseEnd($test_case) {
+ if ($this->_within_test_case) {
+ $this->_reporter->paintCaseEnd($test_case);
+ }
+ if ($this->_isCaseMatch($test_case)) {
+ $this->_within_test_case = false;
+ }
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/scorer.php b/tests/test_tools/simpletest/scorer.php
index 6c321f8c..e9cff6a6 100644
--- a/tests/test_tools/simpletest/scorer.php
+++ b/tests/test_tools/simpletest/scorer.php
@@ -3,9 +3,13 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
- * @version $Id: scorer.php,v 1.4 2005/01/11 04:03:46 lastcraft Exp $
+ * @version $Id: scorer.php,v 1.12 2006/02/06 06:05:18 lastcraft Exp $
*/
-
+
+ /**#@+*/
+ require_once(dirname(__FILE__) . '/invoker.php');
+ /**#@-*/
+
/**
* Can recieve test events and display them. Display
* is achieved by making display methods available
@@ -19,7 +23,7 @@
protected $_fails;
protected $_exceptions;
protected $_is_dry_run;
-
+
/**
* Starts the test run with no results.
* @access public
@@ -30,16 +34,18 @@
$this->_exceptions = 0;
$this->_is_dry_run = false;
}
-
+
/**
* Signals that the next evaluation will be a dry
* run. That is, the structure events will be
* recorded, but no tests will be run.
+ * @param boolean $is_dry Dry run if true.
+ * @access public
*/
function makeDry($is_dry = true) {
$this->_is_dry_run = $is_dry;
}
-
+
/**
* The reporter has a veto on what should be run.
* @param string $test_case_name name of test case.
@@ -51,6 +57,17 @@
}
/**
+ * Can wrap the invoker in preperation for running
+ * a test.
+ * @param SimpleInvoker $invoker Individual test runner.
+ * @return SimpleInvoker Wrapped test runner.
+ * @access public
+ */
+ function &createInvoker($invoker) {
+ return $invoker;
+ }
+
+ /**
* Accessor for current status. Will be false
* if there have been any failures or exceptions.
* Used for command line tools.
@@ -63,23 +80,24 @@
}
return true;
}
-
+
/**
- * Paints the start of a test method.
+ * Paints the start of a group test.
* @param string $test_name Name of test or other label.
+ * @param integer $size Number of test cases starting.
* @access public
*/
- function paintMethodStart($test_name) {
+ function paintGroupStart($test_name, $size) {
}
-
+
/**
- * Paints the end of a test method.
+ * Paints the end of a group test.
* @param string $test_name Name of test or other label.
* @access public
*/
- function paintMethodEnd($test_name) {
+ function paintGroupEnd($test_name) {
}
-
+
/**
* Paints the start of a test case.
* @param string $test_name Name of test or other label.
@@ -87,7 +105,7 @@
*/
function paintCaseStart($test_name) {
}
-
+
/**
* Paints the end of a test case.
* @param string $test_name Name of test or other label.
@@ -95,24 +113,23 @@
*/
function paintCaseEnd($test_name) {
}
-
+
/**
- * Paints the start of a group test.
+ * Paints the start of a test method.
* @param string $test_name Name of test or other label.
- * @param integer $size Number of test cases starting.
* @access public
*/
- function paintGroupStart($test_name, $size) {
+ function paintMethodStart($test_name) {
}
-
+
/**
- * Paints the end of a group test.
+ * Paints the end of a test method.
* @param string $test_name Name of test or other label.
* @access public
*/
- function paintGroupEnd($test_name) {
+ function paintMethodEnd($test_name) {
}
-
+
/**
* Increments the pass count.
* @param string $message Message is ignored.
@@ -121,7 +138,7 @@
function paintPass($message) {
$this->_passes++;
}
-
+
/**
* Increments the fail count.
* @param string $message Message is ignored.
@@ -130,27 +147,18 @@
function paintFail($message) {
$this->_fails++;
}
-
+
/**
- * Deals with PHP 4 throwing an error.
+ * Deals with PHP 4 throwing an error or PHP 5
+ * throwing an exception.
* @param string $message Text of error formatted by
* the test case.
* @access public
*/
function paintError($message) {
- $this->paintException($message);
- }
-
- /**
- * Deals with PHP 5 throwing an exception
- * This isn't really implemented yet.
- * @param Exception $exception Object thrown.
- * @access public
- */
- function paintException($exception) {
$this->_exceptions++;
}
-
+
/**
* Accessor for the number of passes so far.
* @return integer Number of passes.
@@ -159,7 +167,7 @@
function getPassCount() {
return $this->_passes;
}
-
+
/**
* Accessor for the number of fails so far.
* @return integer Number of fails.
@@ -168,7 +176,7 @@
function getFailCount() {
return $this->_fails;
}
-
+
/**
* Accessor for the number of untrapped errors
* so far.
@@ -178,7 +186,7 @@
function getExceptionCount() {
return $this->_exceptions;
}
-
+
/**
* Paints a simple supplementary message.
* @param string $message Text to display.
@@ -186,7 +194,7 @@
*/
function paintMessage($message) {
}
-
+
/**
* Paints a formatted ASCII message such as a
* variable dump.
@@ -195,7 +203,7 @@
*/
function paintFormattedMessage($message) {
}
-
+
/**
* By default just ignores user generated events.
* @param string $type Event type as text.
@@ -218,7 +226,7 @@
protected $_test_stack;
protected $_size;
protected $_progress;
-
+
/**
* Starts the display with no results in.
* @access public
@@ -229,7 +237,7 @@
$this->_size = null;
$this->_progress = 0;
}
-
+
/**
* Paints the start of a group test. Will also paint
* the page header and footer if this is the
@@ -248,7 +256,7 @@
}
$this->_test_stack[] = $test_name;
}
-
+
/**
* Paints the end of a group test. Will paint the page
* footer if the stack of tests has unwound.
@@ -262,7 +270,7 @@
$this->paintFooter($test_name);
}
}
-
+
/**
* Paints the start of a test case. Will also paint
* the page header and footer if this is the
@@ -280,7 +288,7 @@
}
$this->_test_stack[] = $test_name;
}
-
+
/**
* Paints the end of a test case. Will paint the page
* footer if the stack of tests has unwound.
@@ -294,7 +302,7 @@
$this->paintFooter($test_name);
}
}
-
+
/**
* Paints the start of a test method.
* @param string $test_name Name of test that is starting.
@@ -303,7 +311,7 @@
function paintMethodStart($test_name) {
$this->_test_stack[] = $test_name;
}
-
+
/**
* Paints the end of a test method. Will paint the page
* footer if the stack of tests has unwound.
@@ -313,7 +321,7 @@
function paintMethodEnd($test_name) {
array_pop($this->_test_stack);
}
-
+
/**
* Paints the test document header.
* @param string $test_name First test top level
@@ -323,7 +331,7 @@
*/
function paintHeader($test_name) {
}
-
+
/**
* Paints the test document footer.
* @param string $test_name The top level test.
@@ -332,7 +340,7 @@
*/
function paintFooter($test_name) {
}
-
+
/**
* Accessor for internal test stack. For
* subclasses that need to see the whole test
@@ -343,7 +351,7 @@
function getTestList() {
return $this->_test_stack;
}
-
+
/**
* Accessor for total test size in number
* of test cases. Null until the first
@@ -354,7 +362,7 @@
function getTestCaseCount() {
return $this->_size;
}
-
+
/**
* Accessor for the number of test cases
* completed so far.
@@ -364,15 +372,406 @@
function getTestCaseProgress() {
return $this->_progress;
}
-
+
/**
* Static check for running in the comand line.
* @return boolean True if CLI.
* @access public
* @static
*/
- static function inCli() {
+ function inCli() {
return php_sapi_name() == 'cli';
}
}
+
+ /**
+ * For modifying the behaviour of the visual reporters.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleReporterDecorator {
+ protected $_reporter;
+
+ /**
+ * Mediates between teh reporter and the test case.
+ * @param SimpleScorer $reporter Reporter to receive events.
+ */
+ function SimpleReporterDecorator($reporter) {
+ $this->_reporter = $reporter;
+ }
+
+ /**
+ * Signals that the next evaluation will be a dry
+ * run. That is, the structure events will be
+ * recorded, but no tests will be run.
+ * @param boolean $is_dry Dry run if true.
+ * @access public
+ */
+ function makeDry($is_dry = true) {
+ $this->_reporter->makeDry($is_dry);
+ }
+
+ /**
+ * Accessor for current status. Will be false
+ * if there have been any failures or exceptions.
+ * Used for command line tools.
+ * @return boolean True if no failures.
+ * @access public
+ */
+ function getStatus() {
+ return $this->_reporter->getStatus();
+ }
+
+ /**
+ * The reporter has a veto on what should be run.
+ * @param string $test_case_name name of test case.
+ * @param string $method Name of test method.
+ * @return boolean True if test should be run.
+ * @access public
+ */
+ function shouldInvoke($test_case_name, $method) {
+ return $this->_reporter->shouldInvoke($test_case_name, $method);
+ }
+
+ /**
+ * Can wrap the invoker in preperation for running
+ * a test.
+ * @param SimpleInvoker $invoker Individual test runner.
+ * @return SimpleInvoker Wrapped test runner.
+ * @access public
+ */
+ function &createInvoker($invoker) {
+ return $this->_reporter->createInvoker($invoker);
+ }
+
+ /**
+ * Paints the start of a group test.
+ * @param string $test_name Name of test or other label.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($test_name, $size) {
+ $this->_reporter->paintGroupStart($test_name, $size);
+ }
+
+ /**
+ * Paints the end of a group test.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintGroupEnd($test_name) {
+ $this->_reporter->paintGroupEnd($test_name);
+ }
+
+ /**
+ * Paints the start of a test case.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseStart($test_name) {
+ $this->_reporter->paintCaseStart($test_name);
+ }
+
+ /**
+ * Paints the end of a test case.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseEnd($test_name) {
+ $this->_reporter->paintCaseEnd($test_name);
+ }
+
+ /**
+ * Paints the start of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodStart($test_name) {
+ $this->_reporter->paintMethodStart($test_name);
+ }
+
+ /**
+ * Paints the end of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodEnd($test_name) {
+ $this->_reporter->paintMethodEnd($test_name);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintPass($message) {
+ $this->_reporter->paintPass($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintFail($message) {
+ $this->_reporter->paintFail($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text of error formatted by
+ * the test case.
+ * @access public
+ */
+ function paintError($message) {
+ $this->_reporter->paintError($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintMessage($message) {
+ $this->_reporter->paintMessage($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ $this->_reporter->paintFormattedMessage($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $type Event type as text.
+ * @param mixed $payload Message or object.
+ * @return boolean Should return false if this
+ * type of signal should fail the
+ * test suite.
+ * @access public
+ */
+ function paintSignal($type, $payload) {
+ $this->_reporter->paintSignal($type, $payload);
+ }
+ }
+
+ /**
+ * For sending messages to multiple reporters at
+ * the same time.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class MultipleReporter {
+ protected $_reporters = array();
+
+ /**
+ * Adds a reporter to the subscriber list.
+ * @param SimpleScorer $reporter Reporter to receive events.
+ * @access public
+ */
+ function attachReporter($reporter) {
+ $this->_reporters[] = $reporter;
+ }
+
+ /**
+ * Signals that the next evaluation will be a dry
+ * run. That is, the structure events will be
+ * recorded, but no tests will be run.
+ * @param boolean $is_dry Dry run if true.
+ * @access public
+ */
+ function makeDry($is_dry = true) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->makeDry($is_dry);
+ }
+ }
+
+ /**
+ * Accessor for current status. Will be false
+ * if there have been any failures or exceptions.
+ * If any reporter reports a failure, the whole
+ * suite fails.
+ * @return boolean True if no failures.
+ * @access public
+ */
+ function getStatus() {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ if (! $this->_reporters[$i]->getStatus()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * The reporter has a veto on what should be run.
+ * It requires all reporters to want to run the method.
+ * @param string $test_case_name name of test case.
+ * @param string $method Name of test method.
+ * @access public
+ */
+ function shouldInvoke($test_case_name, $method) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ if (! $this->_reporters[$i]->shouldInvoke($test_case_name, $method)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Every reporter gets a chance to wrap the invoker.
+ * @param SimpleInvoker $invoker Individual test runner.
+ * @return SimpleInvoker Wrapped test runner.
+ * @access public
+ */
+ function &createInvoker($invoker) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $invoker = $this->_reporters[$i]->createInvoker($invoker);
+ }
+ return $invoker;
+ }
+
+ /**
+ * Paints the start of a group test.
+ * @param string $test_name Name of test or other label.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($test_name, $size) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->paintGroupStart($test_name, $size);
+ }
+ }
+
+ /**
+ * Paints the end of a group test.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintGroupEnd($test_name) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->paintGroupEnd($test_name);
+ }
+ }
+
+ /**
+ * Paints the start of a test case.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseStart($test_name) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->paintCaseStart($test_name);
+ }
+ }
+
+ /**
+ * Paints the end of a test case.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseEnd($test_name) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->paintCaseEnd($test_name);
+ }
+ }
+
+ /**
+ * Paints the start of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodStart($test_name) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->paintMethodStart($test_name);
+ }
+ }
+
+ /**
+ * Paints the end of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodEnd($test_name) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->paintMethodEnd($test_name);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintPass($message) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->paintPass($message);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintFail($message) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->paintFail($message);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text of error formatted by
+ * the test case.
+ * @access public
+ */
+ function paintError($message) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->paintError($message);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintMessage($message) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->paintMessage($message);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->paintFormattedMessage($message);
+ }
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $type Event type as text.
+ * @param mixed $payload Message or object.
+ * @return boolean Should return false if this
+ * type of signal should fail the
+ * test suite.
+ * @access public
+ */
+ function paintSignal($type, $payload) {
+ for ($i = 0; $i < count($this->_reporters); $i++) {
+ $this->_reporters[$i]->paintSignal($type, $payload);
+ }
+ }
+ }
?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/selector.php b/tests/test_tools/simpletest/selector.php
new file mode 100644
index 00000000..78ee0fef
--- /dev/null
+++ b/tests/test_tools/simpletest/selector.php
@@ -0,0 +1,133 @@
+<?php
+ /**
+ * Base include file for SimpleTest.
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: selector.php,v 1.3 2005/08/25 03:34:24 lastcraft Exp $
+ */
+
+ /**#@+
+ * include SimpleTest files
+ */
+ require_once(dirname(__FILE__) . '/tag.php');
+ require_once(dirname(__FILE__) . '/encoding.php');
+ /**#@-*/
+
+ /**
+ * Used to extract form elements for testing against.
+ * Searches by name attribute.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleByName {
+ protected $_name;
+
+ /**
+ * Stashes the name for later comparison.
+ * @param string $name Name attribute to match.
+ */
+ function SimpleByName($name) {
+ $this->_name = $name;
+ }
+
+ /**
+ * Compares with name attribute of widget.
+ * @param SimpleWidget $widget Control to compare.
+ * @access public
+ */
+ function isMatch($widget) {
+ return ($widget->getName() == $this->_name);
+ }
+ }
+
+ /**
+ * Used to extract form elements for testing against.
+ * Searches by visible label or alt text.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleByLabel {
+ protected $_label;
+
+ /**
+ * Stashes the name for later comparison.
+ * @param string $label Visible text to match.
+ */
+ function SimpleByLabel($label) {
+ $this->_label = $label;
+ }
+
+ /**
+ * Comparison. Compares visible text of widget or
+ * related label.
+ * @param SimpleWidget $widget Control to compare.
+ * @access public
+ */
+ function isMatch($widget) {
+ if (! method_exists($widget, 'isLabel')) {
+ return false;
+ }
+ return $widget->isLabel($this->_label);
+ }
+ }
+
+ /**
+ * Used to extract form elements for testing against.
+ * Searches dy id attribute.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleById {
+ protected $_id;
+
+ /**
+ * Stashes the name for later comparison.
+ * @param string $id ID atribute to match.
+ */
+ function SimpleById($id) {
+ $this->_id = $id;
+ }
+
+ /**
+ * Comparison. Compares id attribute of widget.
+ * @param SimpleWidget $widget Control to compare.
+ * @access public
+ */
+ function isMatch($widget) {
+ return $widget->isId($this->_id);
+ }
+ }
+
+ /**
+ * Used to extract form elements for testing against.
+ * Searches by visible label, name or alt text.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleByLabelOrName {
+ protected $_label;
+
+ /**
+ * Stashes the name/label for later comparison.
+ * @param string $label Visible text to match.
+ */
+ function SimpleByLabelOrName($label) {
+ $this->_label = $label;
+ }
+
+ /**
+ * Comparison. Compares visible text of widget or
+ * related label or name.
+ * @param SimpleWidget $widget Control to compare.
+ * @access public
+ */
+ function isMatch($widget) {
+ if (method_exists($widget, 'isLabel')) {
+ if ($widget->isLabel($this->_label)) {
+ return true;
+ }
+ }
+ return ($widget->getName() == $this->_label);
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/shell_tester.php b/tests/test_tools/simpletest/shell_tester.php
index 7bab8ce0..572d4121 100644
--- a/tests/test_tools/simpletest/shell_tester.php
+++ b/tests/test_tools/simpletest/shell_tester.php
@@ -3,13 +3,13 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
- * @version $Id: shell_tester.php,v 1.14 2004/08/17 18:18:32 lastcraft Exp $
+ * @version $Id: shell_tester.php,v 1.19 2005/08/03 17:26:55 lastcraft Exp $
*/
/**#@+
* include other SimpleTest class files
*/
- require_once(dirname(__FILE__) . '/simple_test.php');
+ require_once(dirname(__FILE__) . '/test_case.php');
/**#@-*/
/**
@@ -127,6 +127,40 @@
$shell = $this->_getShell();
return $shell->getOutputAsList();
}
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * the same value only. Otherwise a fail. This
+ * is for testing hand extracted text, etc.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertEqual($first, $second, $message = "%s") {
+ return $this->assert(
+ new EqualExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * a different value. Otherwise a fail. This
+ * is for testing hand extracted text, etc.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNotEqual($first, $second, $message = "%s") {
+ return $this->assert(
+ new NotEqualExpectation($first),
+ $second,
+ $message);
+ }
/**
* Tests the last status code from the shell.
@@ -153,7 +187,7 @@
*/
function assertOutput($expected, $message = "%s") {
$shell = $this->_getShell();
- return $this->assertExpectation(
+ return $this->assert(
new EqualExpectation($expected),
$shell->getOutput(),
$message);
@@ -169,8 +203,8 @@
*/
function assertOutputPattern($pattern, $message = "%s") {
$shell = $this->_getShell();
- return $this->assertExpectation(
- new WantedPatternExpectation($pattern),
+ return $this->assert(
+ new PatternExpectation($pattern),
$shell->getOutput(),
$message);
}
@@ -185,8 +219,8 @@
*/
function assertNoOutputPattern($pattern, $message = "%s") {
$shell = $this->_getShell();
- return $this->assertExpectation(
- new UnwantedPatternExpectation($pattern),
+ return $this->assert(
+ new NoPatternExpectation($pattern),
$shell->getOutput(),
$message);
}
@@ -226,8 +260,8 @@
*/
function assertFilePattern($pattern, $path, $message = "%s") {
$shell = $this->_getShell();
- return $this->assertExpectation(
- new WantedPatternExpectation($pattern),
+ return $this->assert(
+ new PatternExpectation($pattern),
implode('', file($path)),
$message);
}
@@ -243,8 +277,8 @@
*/
function assertNoFilePattern($pattern, $path, $message = "%s") {
$shell = $this->_getShell();
- return $this->assertExpectation(
- new UnwantedPatternExpectation($pattern),
+ return $this->assert(
+ new NoPatternExpectation($pattern),
implode('', file($path)),
$message);
}
@@ -255,7 +289,7 @@
* @return Shell Current shell.
* @access protected
*/
- function _getShell() {
+ function &_getShell() {
return $this->_current_shell;
}
@@ -264,8 +298,9 @@
* @return Shell New shell object.
* @access protected
*/
- function _createShell() {
- return new SimpleShell();
+ function &_createShell() {
+ $shell = new SimpleShell();
+ return $shell;
}
}
?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/simpletest.php b/tests/test_tools/simpletest/simpletest.php
new file mode 100644
index 00000000..ca0d4e86
--- /dev/null
+++ b/tests/test_tools/simpletest/simpletest.php
@@ -0,0 +1,282 @@
+<?php
+ /**
+ * Global state for SimpleTest and kicker script in future versions.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: simpletest.php,v 1.6 2006/01/01 23:16:53 lastcraft Exp $
+ */
+
+ /**#@+
+ * include SimpleTest files
+ */
+ if (version_compare(phpversion(), '5') >= 0) {
+ require_once(dirname(__FILE__) . '/reflection_php5.php');
+ } else {
+ require_once(dirname(__FILE__) . '/reflection_php4.php');
+ }
+ /**#@-*/
+
+ /**
+ * Static global directives and options. I hate this
+ * class. It's a mixture of reference hacks, configuration
+ * and previous design screw-ups that I have to maintain
+ * to keep backward compatibility.
+ * @package SimpleTest
+ */
+ class SimpleTest {
+
+ /**
+ * Reads the SimpleTest version from the release file.
+ * @return string Version string.
+ * @static
+ * @access public
+ */
+ function getVersion() {
+ $content = file(dirname(__FILE__) . '/VERSION');
+ return trim($content[0]);
+ }
+
+ /**
+ * Sets the name of a test case to ignore, usually
+ * because the class is an abstract case that should
+ * not be run. Once PHP4 is dropped this will disappear
+ * as a public method and "abstract" will rule.
+ * @param string $class Add a class to ignore.
+ * @static
+ * @access public
+ */
+ function ignore($class) {
+ $registry = &SimpleTest::_getRegistry();
+ $registry['IgnoreList'][strtolower($class)] = true;
+ }
+
+ /**
+ * Scans the now complete ignore list, and adds
+ * all parent classes to the list. If a class
+ * is not a runnable test case, then it's parents
+ * wouldn't be either. This is syntactic sugar
+ * to cut down on ommissions of ignore()'s or
+ * missing abstract declarations. This cannot
+ * be done whilst loading classes wiithout forcing
+ * a particular order on the class declarations and
+ * the ignore() calls. It's nice to havethe ignore()
+ * calls at the top of teh file.
+ * @param array $classes Class names of interest.
+ * @static
+ * @access public
+ */
+ function ignoreParentsIfIgnored($classes) {
+ $registry = &SimpleTest::_getRegistry();
+ foreach ($classes as $class) {
+ if (SimpleTest::isIgnored($class)) {
+ $reflection = new SimpleReflection($class);
+ if ($parent = $reflection->getParent()) {
+ SimpleTest::ignore($parent);
+ }
+ }
+ }
+ }
+
+ /**
+ * Test to see if a test case is in the ignore
+ * list. Quite obviously the ignore list should
+ * be a separate object and will be one day.
+ * This method is internal to SimpleTest. Don't
+ * use it.
+ * @param string $class Class name to test.
+ * @return boolean True if should not be run.
+ * @access public
+ * @static
+ */
+ function isIgnored($class) {
+ $registry = &SimpleTest::_getRegistry();
+ return isset($registry['IgnoreList'][strtolower($class)]);
+ }
+
+ /**
+ * @deprecated
+ */
+ function setMockBaseClass($mock_base) {
+ $registry = &SimpleTest::_getRegistry();
+ $registry['MockBaseClass'] = $mock_base;
+ }
+
+ /**
+ * @deprecated
+ */
+ function getMockBaseClass() {
+ $registry = &SimpleTest::_getRegistry();
+ return $registry['MockBaseClass'];
+ }
+
+ /**
+ * Sets proxy to use on all requests for when
+ * testing from behind a firewall. Set host
+ * to false to disable. This will take effect
+ * if there are no other proxy settings.
+ * @param string $proxy Proxy host as URL.
+ * @param string $username Proxy username for authentication.
+ * @param string $password Proxy password for authentication.
+ * @access public
+ */
+ function useProxy($proxy, $username = false, $password = false) {
+ $registry = &SimpleTest::_getRegistry();
+ $registry['DefaultProxy'] = $proxy;
+ $registry['DefaultProxyUsername'] = $username;
+ $registry['DefaultProxyPassword'] = $password;
+ }
+
+ /**
+ * Accessor for default proxy host.
+ * @return string Proxy URL.
+ * @access public
+ */
+ function getDefaultProxy() {
+ $registry = &SimpleTest::_getRegistry();
+ return $registry['DefaultProxy'];
+ }
+
+ /**
+ * Accessor for default proxy username.
+ * @return string Proxy username for authentication.
+ * @access public
+ */
+ function getDefaultProxyUsername() {
+ $registry = &SimpleTest::_getRegistry();
+ return $registry['DefaultProxyUsername'];
+ }
+
+ /**
+ * Accessor for default proxy password.
+ * @return string Proxy password for authentication.
+ * @access public
+ */
+ function getDefaultProxyPassword() {
+ $registry = &SimpleTest::_getRegistry();
+ return $registry['DefaultProxyPassword'];
+ }
+
+ /**
+ * Sets the current test case instance. This
+ * global instance can be used by the mock objects
+ * to send message to the test cases.
+ * @param SimpleTestCase $test Test case to register.
+ * @access public
+ * @static
+ */
+ function setCurrent($test) {
+ $registry = &SimpleTest::_getRegistry();
+ $registry['CurrentTestCase'] = $test;
+ }
+
+ /**
+ * Accessor for current test instance.
+ * @return SimpleTEstCase Currently running test.
+ * @access public
+ * @static
+ */
+ function &getCurrent() {
+ $registry = &SimpleTest::_getRegistry();
+ return $registry['CurrentTestCase'];
+ }
+
+ /**
+ * Accessor for global registry of options.
+ * @return hash All stored values.
+ * @access private
+ * @static
+ */
+ function &_getRegistry() {
+ static $registry = false;
+ if (! $registry) {
+ $registry = SimpleTest::_getDefaults();
+ }
+ return $registry;
+ }
+
+ /**
+ * Constant default values.
+ * @return hash All registry defaults.
+ * @access private
+ * @static
+ */
+ function _getDefaults() {
+ return array(
+ 'StubBaseClass' => 'SimpleStub',
+ 'MockBaseClass' => 'SimpleMock',
+ 'IgnoreList' => array(),
+ 'DefaultProxy' => false,
+ 'DefaultProxyUsername' => false,
+ 'DefaultProxyPassword' => false);
+ }
+ }
+
+ /**
+ * @deprecated
+ */
+ class SimpleTestOptions extends SimpleTest {
+
+ /**
+ * @deprecated
+ */
+ function getVersion() {
+ return Simpletest::getVersion();
+ }
+
+ /**
+ * @deprecated
+ */
+ function ignore($class) {
+ return Simpletest::ignore($class);
+ }
+
+ /**
+ * @deprecated
+ */
+ function isIgnored($class) {
+ return Simpletest::isIgnored($class);
+ }
+
+ /**
+ * @deprecated
+ */
+ function setMockBaseClass($mock_base) {
+ return Simpletest::setMockBaseClass($mock_base);
+ }
+
+ /**
+ * @deprecated
+ */
+ function getMockBaseClass() {
+ return Simpletest::getMockBaseClass();
+ }
+
+ /**
+ * @deprecated
+ */
+ function useProxy($proxy, $username = false, $password = false) {
+ return Simpletest::useProxy($proxy, $username, $password);
+ }
+
+ /**
+ * @deprecated
+ */
+ function getDefaultProxy() {
+ return Simpletest::getDefaultProxy();
+ }
+
+ /**
+ * @deprecated
+ */
+ function getDefaultProxyUsername() {
+ return Simpletest::getDefaultProxyUsername();
+ }
+
+ /**
+ * @deprecated
+ */
+ function getDefaultProxyPassword() {
+ return Simpletest::getDefaultProxyPassword();
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/socket.php b/tests/test_tools/simpletest/socket.php
index 4c3c592d..b627a169 100644
--- a/tests/test_tools/simpletest/socket.php
+++ b/tests/test_tools/simpletest/socket.php
@@ -3,13 +3,13 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage MockObjects
- * @version $Id: socket.php,v 1.23 2004/09/30 16:46:31 lastcraft Exp $
+ * @version $Id: socket.php,v 1.26 2005/08/29 00:57:48 lastcraft Exp $
*/
/**#@+
* include SimpleTest files
*/
- require_once(dirname(__FILE__) . '/options.php');
+ require_once(dirname(__FILE__) . '/compatibility.php');
/**#@-*/
/**
@@ -73,25 +73,26 @@
*/
class SimpleSocket extends SimpleStickyError {
protected $_handle;
- protected $_is_open;
- protected $_sent;
+ protected $_is_open = false;
+ protected $_sent = '';
+ public $lock_size;
/**
* Opens a socket for reading and writing.
- * @param string $host Hostname to send request to.
- * @param integer $port Port on remote machine to open.
- * @param integer $timeout Connection timeout in seconds.
+ * @param string $host Hostname to send request to.
+ * @param integer $port Port on remote machine to open.
+ * @param integer $timeout Connection timeout in seconds.
+ * @param integer $block_size Size of chunk to read.
* @access public
*/
- function SimpleSocket($host, $port, $timeout) {
+ function SimpleSocket($host, $port, $timeout, $block_size = 255) {
$this->SimpleStickyError();
- $this->_is_open = false;
- $this->_sent = '';
if (! ($this->_handle = $this->_openSocket($host, $port, $error_number, $error, $timeout))) {
$this->_setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds");
return;
}
$this->_is_open = true;
+ $this->_block_size = $block_size;
SimpleTestCompatibility::setTimeout($this->_handle, $timeout);
}
@@ -122,16 +123,15 @@
* Reads data from the socket. The error suppresion
* is a workaround for PHP4 always throwing a warning
* with a secure socket.
- * @param integer $block_size Size of chunk to read.
- * @return integer Incoming bytes. False
+ * @return integer/boolean Incoming bytes. False
* on error.
* @access public
*/
- function read($block_size = 255) {
+ function read() {
if ($this->isError() || ! $this->isOpen()) {
return false;
}
- $raw = @fread($this->_handle, $block_size);
+ $raw = @fread($this->_handle, $this->_block_size);
if ($raw === false) {
$this->_setError('Cannot read from socket');
$this->close();
diff --git a/tests/test_tools/simpletest/tag.php b/tests/test_tools/simpletest/tag.php
index 9386712a..060265d2 100644
--- a/tests/test_tools/simpletest/tag.php
+++ b/tests/test_tools/simpletest/tag.php
@@ -3,13 +3,14 @@
* Base include file for SimpleTest.
* @package SimpleTest
* @subpackage WebTester
- * @version $Id: tag.php,v 1.73 2005/02/02 22:49:36 lastcraft Exp $
+ * @version $Id: tag.php,v 1.95 2006/02/05 00:34:29 lastcraft Exp $
*/
/**#@+
* include SimpleTest files
*/
require_once(dirname(__FILE__) . '/parser.php');
+ require_once(dirname(__FILE__) . '/encoding.php');
/**#@-*/
/**
@@ -31,7 +32,7 @@
* converted to lower case.
*/
function SimpleTag($name, $attributes) {
- $this->_name = $name;
+ $this->_name = strtolower(trim($name));
$this->_attributes = $attributes;
$this->_content = '';
}
@@ -47,6 +48,19 @@
}
/**
+ * The current tag should not swallow all content for
+ * itself as it's searchable page content. Private
+ * content tags are usually widgets that contain default
+ * values.
+ * @return boolean False as content is available
+ * to other tags by default.
+ * @access public
+ */
+ function isPrivateContent() {
+ return false;
+ }
+
+ /**
* Appends string content to the current content.
* @param string $content Additional text.
* @access public
@@ -73,7 +87,7 @@
}
/**
- * List oflegal child elements.
+ * List of legal child elements.
* @return array List of element names.
* @access public
*/
@@ -92,9 +106,6 @@
if (! isset($this->_attributes[$label])) {
return false;
}
- if ($this->_attributes[$label] === '') {
- return true;
- }
return (string)$this->_attributes[$label];
}
@@ -125,7 +136,7 @@
* @access public
*/
function getText() {
- return SimpleSaxParser::normalise($this->_content);
+ return SimpleHtmlSaxParser::normalise($this->_content);
}
/**
@@ -193,6 +204,7 @@
*/
class SimpleWidget extends SimpleTag {
protected $_value;
+ protected $_label;
protected $_is_set;
/**
@@ -204,6 +216,7 @@
function SimpleWidget($name, $attributes) {
$this->SimpleTag($name, $attributes);
$this->_value = false;
+ $this->_label = false;
$this->_is_set = false;
}
@@ -223,14 +236,7 @@
* @access public
*/
function getDefault() {
- $default = $this->getAttribute('value');
- if ($default === true) {
- $default = '';
- }
- if ($default === false) {
- $default = '';
- }
- return $default;
+ return $this->getAttribute('value');
}
/**
@@ -267,6 +273,37 @@
function resetValue() {
$this->_is_set = false;
}
+
+ /**
+ * Allows setting of a label externally, say by a
+ * label tag.
+ * @param string $label Label to attach.
+ * @access public
+ */
+ function setLabel($label) {
+ $this->_label = trim($label);
+ }
+
+ /**
+ * Reads external or internal label.
+ * @param string $label Label to test.
+ * @return boolean True is match.
+ * @access public
+ */
+ function isLabel($label) {
+ return $this->_label == trim($label);
+ }
+
+ /**
+ * Dispatches the value into the form encoded packet.
+ * @param SimpleEncoding $encoding Form packet.
+ * @access public
+ */
+ function write($encoding) {
+ if ($this->getName()) {
+ $encoding->add($this->getName(), $this->getValue());
+ }
+ }
}
/**
@@ -326,9 +363,6 @@
*/
function SimpleSubmitTag($attributes) {
$this->SimpleWidget('input', $attributes);
- if ($this->getAttribute('name') === false) {
- $this->_setAttribute('name', 'submit');
- }
if ($this->getAttribute('value') === false) {
$this->_setAttribute('value', 'Submit');
}
@@ -363,12 +397,13 @@
}
/**
- * Gets the values submitted as a form.
- * @return array Hash of name and values.
+ * Test for a label match when searching.
+ * @param string $label Label to test.
+ * @return boolean True on match.
* @access public
*/
- function getSubmitValues() {
- return array($this->getName() => $this->getValue());
+ function isLabel($label) {
+ return trim($label) == trim($this->getLabel());
}
}
@@ -420,14 +455,30 @@
}
/**
- * Gets the values submitted as a form.
- * @return array Hash of name and values.
+ * Test for a label match when searching.
+ * @param string $label Label to test.
+ * @return boolean True on match.
* @access public
*/
- function getSubmitValues($x, $y) {
- return array(
- $this->getName() . '.x' => $x,
- $this->getName() . '.y' => $y);
+ function isLabel($label) {
+ return trim($label) == trim($this->getLabel());
+ }
+
+ /**
+ * Dispatches the value into the form encoded packet.
+ * @param SimpleEncoding $encoding Form packet.
+ * @param integer $x X coordinate of click.
+ * @param integer $y Y coordinate of click.
+ * @access public
+ */
+ function write($encoding){//, $x, $y) {
+ if ($this->getName()) {
+ $encoding->add($this->getName() . '.x', $x);
+ $encoding->add($this->getName() . '.y', $y);
+ } else {
+ $encoding->add('x', $x);
+ $encoding->add('y', $y);
+ }
}
}
@@ -478,19 +529,13 @@
}
/**
- * Gets the values submitted as a form. Gone
- * for the Mozilla defaults values.
- * @return array Hash of name and values.
+ * Test for a label match when searching.
+ * @param string $label Label to test.
+ * @return boolean True on match.
* @access public
*/
- function getSubmitValues() {
- if ($this->getAttribute('name') === false) {
- return array();
- }
- if ($this->getAttribute('value') === false) {
- return array($this->getName() => '');
- }
- return array($this->getName() => $this->getValue());
+ function isLabel($label) {
+ return trim($label) == trim($this->getLabel());
}
}
@@ -516,13 +561,7 @@
* @access public
*/
function getDefault() {
- if ($this->_wrapIsEnabled()) {
- return wordwrap(
- $this->getContent(),
- (integer)$this->getAttribute('cols'),
- "\n");
- }
- return $this->getContent();
+ return $this->_wrap(SimpleHtmlSaxParser::decodeHtml($this->getContent()));
}
/**
@@ -532,13 +571,7 @@
* @access public
*/
function setValue($value) {
- if ($this->_wrapIsEnabled()) {
- $value = wordwrap(
- $value,
- (integer)$this->getAttribute('cols'),
- "\n");
- }
- return parent::setValue($value);
+ return parent::setValue($this->_wrap($value));
}
/**
@@ -555,25 +588,56 @@
}
return false;
}
+
+ /**
+ * Performs the formatting that is peculiar to
+ * this tag. There is strange behaviour in this
+ * one, including stripping a leading new line.
+ * Go figure. I am using Firefox as a guide.
+ * @param string $text Text to wrap.
+ * @return string Text wrapped with carriage
+ * returns and line feeds
+ * @access private
+ */
+ function _wrap($text) {
+ $text = str_replace("\r\r\n", "\r\n", str_replace("\n", "\r\n", $text));
+ $text = str_replace("\r\n\n", "\r\n", str_replace("\r", "\r\n", $text));
+ if (strncmp($text, "\r\n", strlen("\r\n")) == 0) {
+ $text = substr($text, strlen("\r\n"));
+ }
+ if ($this->_wrapIsEnabled()) {
+ return wordwrap(
+ $text,
+ (integer)$this->getAttribute('cols'),
+ "\r\n");
+ }
+ return $text;
+ }
+
+ /**
+ * The content of textarea is not part of the page.
+ * @return boolean True.
+ * @access public
+ */
+ function isPrivateContent() {
+ return true;
+ }
}
/**
- * Checkbox widget.
+ * File upload widget.
* @package SimpleTest
* @subpackage WebTester
*/
- class SimpleCheckboxTag extends SimpleWidget {
+ class SimpleUploadTag extends SimpleWidget {
/**
* Starts with attributes only.
* @param hash $attributes Attribute names and
* string values.
*/
- function SimpleCheckboxTag($attributes) {
+ function SimpleUploadTag($attributes) {
$this->SimpleWidget('input', $attributes);
- if ($this->getAttribute('value') === false) {
- $this->_setAttribute('value', 'on');
- }
}
/**
@@ -586,34 +650,18 @@
}
/**
- * The only allowed value in the one in the
- * "value" attribute. The default for this
- * attribute is "on".
- * @param string $value New value.
- * @return boolean True if allowed.
+ * Dispatches the value into the form encoded packet.
+ * @param SimpleEncoding $encoding Form packet.
* @access public
*/
- function setValue($value) {
- if ($value === false) {
- return parent::setValue($value);
- }
- if ($value != $this->getAttribute('value')) {
- return false;
- }
- return parent::setValue($value);
- }
-
- /**
- * Accessor for starting value. The default
- * value is "on".
- * @return string Parsed value.
- * @access public
- */
- function getDefault() {
- if ($this->getAttribute('checked')) {
- return $this->getAttribute('value');
+ function write($encoding) {
+ if (! file_exists($this->getValue())) {
+ return;
}
- return false;
+ $encoding->attach(
+ $this->getName(),
+ implode('', file($this->getValue())),
+ basename($this->getValue()));
}
}
@@ -664,7 +712,7 @@
*/
function getDefault() {
for ($i = 0, $count = count($this->_options); $i < $count; $i++) {
- if ($this->_options[$i]->getAttribute('selected')) {
+ if ($this->_options[$i]->getAttribute('selected') !== false) {
return $this->_options[$i]->getDefault();
}
}
@@ -682,7 +730,7 @@
*/
function setValue($value) {
for ($i = 0, $count = count($this->_options); $i < $count; $i++) {
- if (trim($this->_options[$i]->getContent()) == trim($value)) {
+ if ($this->_options[$i]->isValue($value)) {
$this->_choice = $i;
return true;
}
@@ -752,7 +800,7 @@
function getDefault() {
$default = array();
for ($i = 0, $count = count($this->_options); $i < $count; $i++) {
- if ($this->_options[$i]->getAttribute('selected')) {
+ if ($this->_options[$i]->getAttribute('selected') !== false) {
$default[] = $this->_options[$i]->getDefault();
}
}
@@ -760,25 +808,29 @@
}
/**
- * Can only set allowed values.
- * @param array $values New choices.
- * @return boolean True if allowed.
+ * Can only set allowed values. Any illegal value
+ * will result in a failure, but all correct values
+ * will be set.
+ * @param array $desired New choices.
+ * @return boolean True if all allowed.
* @access public
*/
- function setValue($values) {
- foreach ($values as $value) {
- $is_option = false;
+ function setValue($desired) {
+ $achieved = array();
+ foreach ($desired as $value) {
+ $success = false;
for ($i = 0, $count = count($this->_options); $i < $count; $i++) {
- if (trim($this->_options[$i]->getContent()) == trim($value)) {
- $is_option = true;
+ if ($this->_options[$i]->isValue($value)) {
+ $achieved[] = $this->_options[$i]->getValue();
+ $success = true;
break;
}
}
- if (! $is_option) {
+ if (! $success) {
return false;
}
}
- $this->_values = $values;
+ $this->_values = $achieved;
return true;
}
@@ -820,6 +872,20 @@
}
/**
+ * Test to see if a value matches the option.
+ * @param string $compare Value to compare with.
+ * @return boolean True if possible match.
+ * @access public
+ */
+ function isValue($compare) {
+ $compare = trim($compare);
+ if (trim($this->getValue()) == $compare) {
+ return true;
+ }
+ return trim($this->getContent()) == $compare;
+ }
+
+ /**
* Accessor for starting value. Will be set to
* the option label if no value exists.
* @return string Parsed value.
@@ -831,6 +897,15 @@
}
return $this->getAttribute('value');
}
+
+ /**
+ * The content of options is not part of the page.
+ * @return boolean True.
+ * @access public
+ */
+ function isPrivateContent() {
+ return true;
+ }
}
/**
@@ -861,7 +936,7 @@
}
/**
- * The only allowed value in the one in the
+ * The only allowed value sn the one in the
* "value" attribute.
* @param string $value New value.
* @return boolean True if allowed.
@@ -871,7 +946,7 @@
if ($value === false) {
return parent::setValue($value);
}
- if ($value != $this->getAttribute('value')) {
+ if ($value !== $this->getAttribute('value')) {
return false;
}
return parent::setValue($value);
@@ -883,27 +958,101 @@
* @access public
*/
function getDefault() {
- if ($this->getAttribute('checked')) {
+ if ($this->getAttribute('checked') !== false) {
return $this->getAttribute('value');
}
return false;
}
}
-
+
/**
- * A group of tags with the same name within a form.
+ * Checkbox widget.
* @package SimpleTest
* @subpackage WebTester
*/
- class SimpleCheckboxGroup {
- protected $_widgets;
+ class SimpleCheckboxTag extends SimpleWidget {
/**
- * Starts empty.
+ * Starts with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleCheckboxTag($attributes) {
+ $this->SimpleWidget('input', $attributes);
+ if ($this->getAttribute('value') === false) {
+ $this->_setAttribute('value', 'on');
+ }
+ }
+
+ /**
+ * Tag contains no content.
+ * @return boolean False.
* @access public
*/
- function SimpleCheckboxGroup() {
- $this->_widgets = array();
+ function expectEndTag() {
+ return false;
+ }
+
+ /**
+ * The only allowed value in the one in the
+ * "value" attribute. The default for this
+ * attribute is "on". If this widget is set to
+ * true, then the usual value will be taken.
+ * @param string $value New value.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ if ($value === false) {
+ return parent::setValue($value);
+ }
+ if ($value === true) {
+ return parent::setValue($this->getAttribute('value'));
+ }
+ if ($value != $this->getAttribute('value')) {
+ return false;
+ }
+ return parent::setValue($value);
+ }
+
+ /**
+ * Accessor for starting value. The default
+ * value is "on".
+ * @return string Parsed value.
+ * @access public
+ */
+ function getDefault() {
+ if ($this->getAttribute('checked') !== false) {
+ return $this->getAttribute('value');
+ }
+ return false;
+ }
+ }
+
+ /**
+ * A group of multiple widgets with some shared behaviour.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleTagGroup {
+ protected $_widgets = array();
+
+ /**
+ * Adds a tag to the group.
+ * @param SimpleWidget $widget
+ * @access public
+ */
+ function addWidget($widget) {
+ $this->_widgets[] = $widget;
+ }
+
+ /**
+ * Accessor to widget set.
+ * @return array All widgets.
+ * @access protected
+ */
+ function &_getWidgets() {
+ return $this->_widgets;
}
/**
@@ -917,7 +1066,19 @@
}
/**
- * Scans the checkboxes for one with the appropriate
+ * Fetches the name for the widget from the first
+ * member.
+ * @return string Name of widget.
+ * @access public
+ */
+ function getName() {
+ if (count($this->_widgets) > 0) {
+ return $this->_widgets[0]->getName();
+ }
+ }
+
+ /**
+ * Scans the widgets for one with the appropriate
* ID field.
* @param string $id ID value to try.
* @return boolean True if matched.
@@ -931,27 +1092,39 @@
}
return false;
}
-
+
/**
- * Adds a tag to the group.
- * @param SimpleWidget $widget
+ * Scans the widgets for one with the appropriate
+ * attached label.
+ * @param string $label Attached label to try.
+ * @return boolean True if matched.
* @access public
*/
- function addWidget($widget) {
- $this->_widgets[] = $widget;
+ function isLabel($label) {
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if ($this->_widgets[$i]->isLabel($label)) {
+ return true;
+ }
+ }
+ return false;
}
/**
- * Fetches the name for the widget from the first
- * member.
- * @return string Name of widget.
+ * Dispatches the value into the form encoded packet.
+ * @param SimpleEncoding $encoding Form packet.
* @access public
*/
- function getName() {
- if (count($this->_widgets) > 0) {
- return $this->_widgets[0]->getName();
- }
+ function write($encoding) {
+ $encoding->add($this->getName(), $this->getValue());
}
+ }
+
+ /**
+ * A group of tags with the same name within a form.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleCheckboxGroup extends SimpleTagGroup {
/**
* Accessor for current selected widget or false
@@ -961,9 +1134,10 @@
*/
function getValue() {
$values = array();
- for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
- if ($this->_widgets[$i]->getValue()) {
- $values[] = $this->_widgets[$i]->getValue();
+ $widgets = $this->_getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ if ($widgets[$i]->getValue() !== false) {
+ $values[] = $widgets[$i]->getValue();
}
}
return $this->_coerceValues($values);
@@ -976,9 +1150,10 @@
*/
function getDefault() {
$values = array();
- for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
- if ($this->_widgets[$i]->getDefault()) {
- $values[] = $this->_widgets[$i]->getDefault();
+ $widgets = $this->_getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ if ($widgets[$i]->getDefault() !== false) {
+ $values[] = $widgets[$i]->getDefault();
}
}
return $this->_coerceValues($values);
@@ -996,12 +1171,13 @@
if (! $this->_valuesArePossible($values)) {
return false;
}
- for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
- $possible = $this->_widgets[$i]->getAttribute('value');
- if (in_array($this->_widgets[$i]->getAttribute('value'), $values)) {
- $this->_widgets[$i]->setValue($possible);
+ $widgets = $this->_getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ $possible = $widgets[$i]->getAttribute('value');
+ if (in_array($widgets[$i]->getAttribute('value'), $values)) {
+ $widgets[$i]->setValue($possible);
} else {
- $this->_widgets[$i]->setValue(false);
+ $widgets[$i]->setValue(false);
}
}
return true;
@@ -1017,8 +1193,9 @@
*/
function _valuesArePossible($values) {
$matches = array();
- for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
- $possible = $this->_widgets[$i]->getAttribute('value');
+ $widgets = $this->_getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ $possible = $widgets[$i]->getAttribute('value');
if (in_array($possible, $values)) {
$matches[] = $possible;
}
@@ -1070,63 +1247,7 @@
* @package SimpleTest
* @subpackage WebTester
*/
- class SimpleRadioGroup {
- protected $_widgets;
-
- /**
- * Starts empty.
- * @access public
- */
- function SimpleRadioGroup() {
- $this->_widgets = array();
- }
-
- /**
- * Accessor for an attribute.
- * @param string $label Attribute name.
- * @return boolean Always false.
- * @access public
- */
- function getAttribute($label) {
- return false;
- }
-
- /**
- * Scans the checkboxes for one with the appropriate
- * ID field.
- * @param string $id ID value to try.
- * @return boolean True if matched.
- * @access public
- */
- function isId($id) {
- for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
- if ($this->_widgets[$i]->isId($id)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Adds a tag to the group.
- * @param SimpleWidget $widget
- * @access public
- */
- function addWidget($widget) {
- $this->_widgets[] = $widget;
- }
-
- /**
- * Fetches the name for the widget from the first
- * member.
- * @return string Name of widget.
- * @access public
- */
- function getName() {
- if (count($this->_widgets) > 0) {
- return $this->_widgets[0]->getName();
- }
- }
+ class SimpleRadioGroup extends SimpleTagGroup {
/**
* Each tag is tried in turn until one is
@@ -1141,9 +1262,10 @@
return false;
}
$index = false;
- for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
- if (! $this->_widgets[$i]->setValue($value)) {
- $this->_widgets[$i]->setValue(false);
+ $widgets = $this->_getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ if (! $widgets[$i]->setValue($value)) {
+ $widgets[$i]->setValue(false);
}
}
return true;
@@ -1156,8 +1278,9 @@
* @access private
*/
function _valueIsPossible($value) {
- for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
- if ($this->_widgets[$i]->getAttribute('value') == $value) {
+ $widgets = $this->_getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ if ($widgets[$i]->getAttribute('value') == $value) {
return true;
}
}
@@ -1172,9 +1295,10 @@
* @access public
*/
function getValue() {
- for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
- if ($this->_widgets[$i]->getValue()) {
- return $this->_widgets[$i]->getValue();
+ $widgets = $this->_getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ if ($widgets[$i]->getValue() !== false) {
+ return $widgets[$i]->getValue();
}
}
return false;
@@ -1187,9 +1311,10 @@
* @access public
*/
function getDefault() {
- for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
- if ($this->_widgets[$i]->getDefault()) {
- return $this->_widgets[$i]->getDefault();
+ $widgets = $this->_getWidgets();
+ for ($i = 0, $count = count($widgets); $i < $count; $i++) {
+ if ($widgets[$i]->getDefault() !== false) {
+ return $widgets[$i]->getDefault();
}
}
return false;
@@ -1197,6 +1322,32 @@
}
/**
+ * Tag to keep track of labels.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleLabelTag extends SimpleTag {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleLabelTag($attributes) {
+ $this->SimpleTag('label', $attributes);
+ }
+
+ /**
+ * Access for the ID to attach the label to.
+ * @return string For attribute.
+ * @access public
+ */
+ function getFor() {
+ return $this->getAttribute('for');
+ }
+ }
+
+ /**
* Tag to aid parsing the form.
* @package SimpleTest
* @subpackage WebTester
diff --git a/tests/test_tools/simpletest/test_case.php b/tests/test_tools/simpletest/test_case.php
new file mode 100644
index 00000000..1bf49789
--- /dev/null
+++ b/tests/test_tools/simpletest/test_case.php
@@ -0,0 +1,684 @@
+<?php
+ /**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: test_case.php,v 1.21 2006/02/06 06:13:43 lastcraft Exp $
+ */
+
+ /**#@+
+ * Includes SimpleTest files and defined the root constant
+ * for dependent libraries.
+ */
+ require_once(dirname(__FILE__) . '/invoker.php');
+ require_once(dirname(__FILE__) . '/errors.php');
+ require_once(dirname(__FILE__) . '/compatibility.php');
+ require_once(dirname(__FILE__) . '/scorer.php');
+ require_once(dirname(__FILE__) . '/expectation.php');
+ require_once(dirname(__FILE__) . '/dumper.php');
+ require_once(dirname(__FILE__) . '/simpletest.php');
+ if (version_compare(phpversion(), '5') >= 0) {
+ require_once(dirname(__FILE__) . '/exceptions.php');
+ require_once(dirname(__FILE__) . '/reflection_php5.php');
+ } else {
+ require_once(dirname(__FILE__) . '/reflection_php4.php');
+ }
+ if (! defined('SIMPLE_TEST')) {
+ /**
+ * @ignore
+ */
+ define('SIMPLE_TEST', dirname(__FILE__) . '/');
+ }
+ /**#@-*/
+
+ /**
+ * Basic test case. This is the smallest unit of a test
+ * suite. It searches for
+ * all methods that start with the the string "test" and
+ * runs them. Working test cases extend this class.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleTestCase {
+ protected $_label = false;
+ protected $_reporter;
+ protected $_observers;
+
+ /**
+ * Sets up the test with no display.
+ * @param string $label If no test name is given then
+ * the class name is used.
+ * @access public
+ */
+ function SimpleTestCase($label = false) {
+ if ($label) {
+ $this->_label = $label;
+ }
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->_label ? $this->_label : get_class($this);
+ }
+
+ /**
+ * Used to invoke the single tests.
+ * @return SimpleInvoker Individual test runner.
+ * @access public
+ */
+ function createInvoker() {
+ $invoker = new SimpleErrorTrappingInvoker(new SimpleInvoker($this));
+ if (version_compare(phpversion(), '5') >= 0) {
+ $invoker = new SimpleExceptionTrappingInvoker($invoker);
+ }
+ return $invoker;
+ }
+
+ /**
+ * Uses reflection to run every method within itself
+ * starting with the string "test" unless a method
+ * is specified.
+ * @param SimpleReporter $reporter Current test reporter.
+ * @access public
+ */
+ function run($reporter) {
+ SimpleTest::setCurrent($this);
+ $this->_reporter = $reporter;
+ $this->_reporter->paintCaseStart($this->getLabel());
+ foreach ($this->getTests() as $method) {
+ if ($this->_reporter->shouldInvoke($this->getLabel(), $method)) {
+ $invoker = $this->_reporter->createInvoker($this->createInvoker());
+ $invoker->before($method);
+ $invoker->invoke($method);
+ $invoker->after($method);
+ }
+ }
+ $this->_reporter->paintCaseEnd($this->getLabel());
+ unset($this->_reporter);
+ return $reporter->getStatus();
+ }
+
+ /**
+ * Gets a list of test names. Normally that will
+ * be all internal methods that start with the
+ * name "test". This method should be overridden
+ * if you want a different rule.
+ * @return array List of test names.
+ * @access public
+ */
+ function getTests() {
+ $methods = array();
+ foreach (get_class_methods(get_class($this)) as $method) {
+ if ($this->_isTest($method)) {
+ $methods[] = $method;
+ }
+ }
+ return $methods;
+ }
+
+ /**
+ * Tests to see if the method is a test that should
+ * be run. Currently any method that starts with 'test'
+ * is a candidate unless it is the constructor.
+ * @param string $method Method name to try.
+ * @return boolean True if test method.
+ * @access protected
+ */
+ function _isTest($method) {
+ if (strtolower(substr($method, 0, 4)) == 'test') {
+ return ! SimpleTestCompatibility::isA($this, strtolower($method));
+ }
+ return false;
+ }
+
+ /**
+ * Announces the start of the test.
+ * @param string $method Test method just started.
+ * @access public
+ */
+ function before($method) {
+ $this->_reporter->paintMethodStart($method);
+ $this->_observers = array();
+ }
+
+ /**
+ * Sets up unit test wide variables at the start
+ * of each test method. To be overridden in
+ * actual user test cases.
+ * @access public
+ */
+ function setUp() {
+ }
+
+ /**
+ * Clears the data set in the setUp() method call.
+ * To be overridden by the user in actual user test cases.
+ * @access public
+ */
+ function tearDown() {
+ }
+
+ /**
+ * Announces the end of the test. Includes private clean up.
+ * @param string $method Test method just finished.
+ * @access public
+ */
+ function after($method) {
+ for ($i = 0; $i < count($this->_observers); $i++) {
+ $this->_observers[$i]->atTestEnd($method);
+ }
+ $this->_reporter->paintMethodEnd($method);
+ }
+
+ /**
+ * Sets up an observer for the test end.
+ * @param object $observer Must have atTestEnd()
+ * method.
+ * @access public
+ */
+ function tell($observer) {
+ $this->_observers[] = $observer;
+ }
+
+ /**
+ * Sends a pass event with a message.
+ * @param string $message Message to send.
+ * @access public
+ */
+ function pass($message = "Pass") {
+ if (! isset($this->_reporter)) {
+ trigger_error('Can only make assertions within test methods');
+ }
+ $this->_reporter->paintPass(
+ $message . $this->getAssertionLine());
+ return true;
+ }
+
+ /**
+ * Sends a fail event with a message.
+ * @param string $message Message to send.
+ * @access public
+ */
+ function fail($message = "Fail") {
+ if (! isset($this->_reporter)) {
+ trigger_error('Can only make assertions within test methods');
+ }
+ $this->_reporter->paintFail(
+ $message . $this->getAssertionLine());
+ return false;
+ }
+
+ /**
+ * Formats a PHP error and dispatches it to the
+ * reporter.
+ * @param integer $severity PHP error code.
+ * @param string $message Text of error.
+ * @param string $file File error occoured in.
+ * @param integer $line Line number of error.
+ * @access public
+ */
+ function error($severity, $message, $file, $line) {
+ if (! isset($this->_reporter)) {
+ trigger_error('Can only make assertions within test methods');
+ }
+ $this->_reporter->paintError(
+ "Unexpected PHP error [$message] severity [$severity] in [$file] line [$line]");
+ }
+
+ /**
+ * Formats an exception and dispatches it to the
+ * reporter.
+ * @param Exception $exception Object thrown.
+ * @access public
+ */
+ function exception($exception) {
+ $this->_reporter->paintError(
+ 'Unexpected exception of type [' . get_class($exception) .
+ '] with message ['. $exception->getMessage() .
+ '] in ['. $exception->getFile() .
+ '] line [' . $exception->getLine() . ']');
+ }
+
+ /**
+ * Sends a user defined event to the test reporter.
+ * This is for small scale extension where
+ * both the test case and either the reporter or
+ * display are subclassed.
+ * @param string $type Type of event.
+ * @param mixed $payload Object or message to deliver.
+ * @access public
+ */
+ function signal($type, $payload) {
+ if (! isset($this->_reporter)) {
+ trigger_error('Can only make assertions within test methods');
+ }
+ $this->_reporter->paintSignal($type, $payload);
+ }
+
+ /**
+ * Cancels any outstanding errors.
+ * @access public
+ */
+ function swallowErrors() {
+ $queue = &SimpleErrorQueue::instance();
+ $queue->clear();
+ }
+
+ /**
+ * Runs an expectation directly, for extending the
+ * tests with new expectation classes.
+ * @param SimpleExpectation $expectation Expectation subclass.
+ * @param mixed $compare Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assert($expectation, $compare, $message = '%s') {
+ return $this->assertTrue(
+ $expectation->test($compare),
+ sprintf($message, $expectation->overlayMessage($compare)));
+ }
+
+ /**
+ * @deprecated
+ */
+ function assertExpectation($expectation, $compare, $message = '%s') {
+ return $this->assert($expectation, $compare, $message);
+ }
+
+ /**
+ * Called from within the test methods to register
+ * passes and failures.
+ * @param boolean $result Pass on true.
+ * @param string $message Message to display describing
+ * the test state.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertTrue($result, $message = false) {
+ if (! $message) {
+ $message = 'True assertion got ' . ($result ? 'True' : 'False');
+ }
+ if ($result) {
+ return $this->pass($message);
+ } else {
+ return $this->fail($message);
+ }
+ }
+
+ /**
+ * Will be true on false and vice versa. False
+ * is the PHP definition of false, so that null,
+ * empty strings, zero and an empty array all count
+ * as false.
+ * @param boolean $result Pass on false.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertFalse($result, $message = false) {
+ if (! $message) {
+ $message = 'False assertion got ' . ($result ? 'True' : 'False');
+ }
+ return $this->assertTrue(! $result, $message);
+ }
+
+ /**
+ * Uses a stack trace to find the line of an assertion.
+ * @param string $format String formatting.
+ * @param array $stack Stack frames top most first. Only
+ * needed if not using the PHP
+ * backtrace function.
+ * @return string Line number of first assert*
+ * method embedded in format string.
+ * @access public
+ */
+ function getAssertionLine($stack = false) {
+ if ($stack === false) {
+ $stack = SimpleTestCompatibility::getStackTrace();
+ }
+ return SimpleDumper::getFormattedAssertionLine($stack);
+ }
+
+ /**
+ * Sends a formatted dump of a variable to the
+ * test suite for those emergency debugging
+ * situations.
+ * @param mixed $variable Variable to display.
+ * @param string $message Message to display.
+ * @return mixed The original variable.
+ * @access public
+ */
+ function dump($variable, $message = false) {
+ $formatted = SimpleDumper::dump($variable);
+ if ($message) {
+ $formatted = $message . "\n" . $formatted;
+ }
+ $this->_reporter->paintFormattedMessage($formatted);
+ return $variable;
+ }
+
+ /**
+ * Dispatches a text message straight to the
+ * test suite. Useful for status bar displays.
+ * @param string $message Message to show.
+ * @access public
+ */
+ function sendMessage($message) {
+ $this->_reporter->PaintMessage($message);
+ }
+
+ /**
+ * Accessor for the number of subtests.
+ * @return integer Number of test cases.
+ * @access public
+ * @static
+ */
+ function getSize() {
+ return 1;
+ }
+ }
+
+ /**
+ * This is a composite test class for combining
+ * test cases and other RunnableTest classes into
+ * a group test.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class GroupTest {
+ protected $_label;
+ protected $_test_cases;
+ protected $_old_track_errors;
+ protected $_xdebug_is_enabled;
+
+ /**
+ * Sets the name of the test suite.
+ * @param string $label Name sent at the start and end
+ * of the test.
+ * @access public
+ */
+ function GroupTest($label = false) {
+ $this->_label = $label ? $label : get_class($this);
+ $this->_test_cases = array();
+ $this->_old_track_errors = ini_get('track_errors');
+ $this->_xdebug_is_enabled = function_exists('xdebug_is_enabled') ?
+ xdebug_is_enabled() : false;
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->_label;
+ }
+
+ /**
+ * Adds a test into the suite. Can be either a group
+ * test or some other unit test.
+ * @param SimpleTestCase $test_case Suite or individual test
+ * case implementing the
+ * runnable test interface.
+ * @access public
+ */
+ function addTestCase($test_case) {
+ $this->_test_cases[] = $test_case;
+ }
+
+ /**
+ * Adds a test into the suite by class name. The class will
+ * be instantiated as needed.
+ * @param SimpleTestCase $test_case Suite or individual test
+ * case implementing the
+ * runnable test interface.
+ * @access public
+ */
+ function addTestClass($class) {
+ if ($this->_getBaseTestCase($class) == 'grouptest') {
+ $this->_test_cases[] = new $class();
+ } else {
+ $this->_test_cases[] = $class;
+ }
+ }
+
+ /**
+ * Builds a group test from a library of test cases.
+ * The new group is composed into this one.
+ * @param string $test_file File name of library with
+ * test case classes.
+ * @access public
+ */
+ function addTestFile($test_file) {
+ $existing_classes = get_declared_classes();
+ if ($error = $this->_requireWithError($test_file)) {
+ $this->addTestCase(new BadGroupTest($test_file, $error));
+ return;
+ }
+ $classes = $this->_selectRunnableTests($existing_classes, get_declared_classes());
+ if (count($classes) == 0) {
+ $this->addTestCase(new BadGroupTest($test_file, "No runnable test cases in [$test_file]"));
+ return;
+ }
+ $group = $this->_createGroupFromClasses($test_file, $classes);
+ $this->addTestCase($group);
+ }
+
+ /**
+ * Requires a source file recording any syntax errors.
+ * @param string $file File name to require in.
+ * @return string/boolean An error message on failure or false
+ * if no errors.
+ * @access private
+ */
+ function _requireWithError($file) {
+ $this->_enableErrorReporting();
+ include_once($file);
+ $error = isset($php_errormsg) ? $php_errormsg : false;
+ $this->_disableErrorReporting();
+ $self_inflicted_errors = array(
+ 'Assigning the return value of new by reference is deprecated',
+ 'var: Deprecated. Please use the public/private/protected modifiers');
+ if (in_array($error, $self_inflicted_errors)) {
+ return false;
+ }
+ return $error;
+ }
+
+ /**
+ * Sets up detection of parse errors. Note that XDebug
+ * interferes with this and has to be disabled. This is
+ * to make sure the correct error code is returned
+ * from unattended scripts.
+ * @access private
+ */
+ function _enableErrorReporting() {
+ if ($this->_xdebug_is_enabled) {
+ xdebug_disable();
+ }
+ ini_set('track_errors', true);
+ }
+
+ /**
+ * Resets detection of parse errors to their old values.
+ * This is to make sure the correct error code is returned
+ * from unattended scripts.
+ * @access private
+ */
+ function _disableErrorReporting() {
+ ini_set('track_errors', $this->_old_track_errors);
+ if ($this->_xdebug_is_enabled) {
+ xdebug_enable();
+ }
+ }
+
+ /**
+ * Calculates the incoming test cases from a before
+ * and after list of loaded classes. Skips abstract
+ * classes.
+ * @param array $existing_classes Classes before require().
+ * @param array $new_classes Classes after require().
+ * @return array New classes which are test
+ * cases that shouldn't be ignored.
+ * @access private
+ */
+ function _selectRunnableTests($existing_classes, $new_classes) {
+ $classes = array();
+ foreach ($new_classes as $class) {
+ if (in_array($class, $existing_classes)) {
+ continue;
+ }
+ if ($this->_getBaseTestCase($class)) {
+ $reflection = new SimpleReflection($class);
+ if ($reflection->isAbstract()) {
+ SimpleTest::ignore($class);
+ }
+ $classes[] = $class;
+ }
+ }
+ return $classes;
+ }
+
+ /**
+ * Builds a group test from a class list.
+ * @param string $title Title of new group.
+ * @param array $classes Test classes.
+ * @return GroupTest Group loaded with the new
+ * test cases.
+ * @access private
+ */
+ function &_createGroupFromClasses($title, $classes) {
+ SimpleTest::ignoreParentsIfIgnored($classes);
+ $group = new GroupTest($title);
+ foreach ($classes as $class) {
+ if (! SimpleTest::isIgnored($class)) {
+ $group->addTestClass($class);
+ }
+ }
+ return $group;
+ }
+
+ /**
+ * Test to see if a class is derived from the
+ * SimpleTestCase class.
+ * @param string $class Class name.
+ * @access private
+ */
+ function _getBaseTestCase($class) {
+ while ($class = get_parent_class($class)) {
+ $class = strtolower($class);
+ if ($class == "simpletestcase" || $class == "grouptest") {
+ return $class;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Delegates to a visiting collector to add test
+ * files.
+ * @param string $path Path to scan from.
+ * @param SimpleCollector $collector Directory scanner.
+ * @access public
+ */
+ function collect($path, $collector) {
+ $collector->collect($this, $path);
+ }
+
+ /**
+ * Invokes run() on all of the held test cases, instantiating
+ * them if necessary.
+ * @param SimpleReporter $reporter Current test reporter.
+ * @access public
+ */
+ function run($reporter) {
+ $reporter->paintGroupStart($this->getLabel(), $this->getSize());
+ for ($i = 0, $count = count($this->_test_cases); $i < $count; $i++) {
+ if (is_string($this->_test_cases[$i])) {
+ $class = $this->_test_cases[$i];
+ $test = new $class();
+ $test->run($reporter);
+ } else {
+ $this->_test_cases[$i]->run($reporter);
+ }
+ }
+ $reporter->paintGroupEnd($this->getLabel());
+ return $reporter->getStatus();
+ }
+
+ /**
+ * Number of contained test cases.
+ * @return integer Total count of cases in the group.
+ * @access public
+ */
+ function getSize() {
+ $count = 0;
+ foreach ($this->_test_cases as $case) {
+ if (is_string($case)) {
+ $count++;
+ } else {
+ $count += $case->getSize();
+ }
+ }
+ return $count;
+ }
+ }
+
+ /**
+ * This is a failing group test for when a test suite hasn't
+ * loaded properly.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class BadGroupTest {
+ protected $_label;
+ protected $_error;
+
+ /**
+ * Sets the name of the test suite and error message.
+ * @param string $label Name sent at the start and end
+ * of the test.
+ * @access public
+ */
+ function BadGroupTest($label, $error) {
+ $this->_label = $label;
+ $this->_error = $error;
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->_label;
+ }
+
+ /**
+ * Sends a single error to the reporter.
+ * @param SimpleReporter $reporter Current test reporter.
+ * @access public
+ */
+ function run($reporter) {
+ $reporter->paintGroupStart($this->getLabel(), $this->getSize());
+ $reporter->paintFail('Bad GroupTest [' . $this->getLabel() .
+ '] with error [' . $this->_error . ']');
+ $reporter->paintGroupEnd($this->getLabel());
+ return $reporter->getStatus();
+ }
+
+ /**
+ * Number of contained test cases. Always zero.
+ * @return integer Total count of cases in the group.
+ * @access public
+ */
+ function getSize() {
+ return 0;
+ }
+ }
+?>
diff --git a/tests/test_tools/simpletest/unit_tester.php b/tests/test_tools/simpletest/unit_tester.php
index fa5e28b4..88e10b14 100644
--- a/tests/test_tools/simpletest/unit_tester.php
+++ b/tests/test_tools/simpletest/unit_tester.php
@@ -3,17 +3,16 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
- * @version $Id: unit_tester.php,v 1.24 2005/01/13 01:31:53 lastcraft Exp $
+ * @version $Id: unit_tester.php,v 1.31 2006/02/06 06:05:18 lastcraft Exp $
*/
/**#@+
* include other SimpleTest class files
*/
- require_once(dirname(__FILE__) . '/simple_test.php');
- require_once(dirname(__FILE__) . '/errors.php');
+ require_once(dirname(__FILE__) . '/test_case.php');
require_once(dirname(__FILE__) . '/dumper.php');
/**#@-*/
-
+
/**
* Standard unit test class for day to day testing
* of PHP code XP style. Adds some useful standard
@@ -22,7 +21,7 @@
* @subpackage UnitTester
*/
class UnitTestCase extends SimpleTestCase {
-
+
/**
* Creates an empty test case. Should be subclassed
* with test methods for a functional test case.
@@ -36,7 +35,7 @@
}
$this->SimpleTestCase($label);
}
-
+
/**
* Will be true if the value is null.
* @param null $value Supposedly null value.
@@ -51,7 +50,7 @@
"[" . $dumper->describeValue($value) . "] should be null");
return $this->assertTrue(! isset($value), $message);
}
-
+
/**
* Will be true if the value is set.
* @param mixed $value Supposedly set value.
@@ -66,7 +65,7 @@
"[" . $dumper->describeValue($value) . "] should not be null");
return $this->assertTrue(isset($value), $message);
}
-
+
/**
* Type and class test. Will pass if class
* matches the type name or is a subclass or
@@ -78,12 +77,12 @@
* @access public
*/
function assertIsA($object, $type, $message = "%s") {
- return $this->assertExpectation(
+ return $this->assert(
new IsAExpectation($type),
$object,
$message);
}
-
+
/**
* Type and class mismatch test. Will pass if class
* name or underling type does not match the one
@@ -95,12 +94,12 @@
* @access public
*/
function assertNotA($object, $type, $message = "%s") {
- return $this->assertExpectation(
+ return $this->assert(
new NotAExpectation($type),
$object,
$message);
}
-
+
/**
* Will trigger a pass if the two parameters have
* the same value only. Otherwise a fail.
@@ -111,12 +110,12 @@
* @access public
*/
function assertEqual($first, $second, $message = "%s") {
- return $this->assertExpectation(
+ return $this->assert(
new EqualExpectation($first),
$second,
$message);
}
-
+
/**
* Will trigger a pass if the two parameters have
* a different value. Otherwise a fail.
@@ -127,12 +126,46 @@
* @access public
*/
function assertNotEqual($first, $second, $message = "%s") {
- return $this->assertExpectation(
+ return $this->assert(
new NotEqualExpectation($first),
$second,
$message);
}
-
+
+ /**
+ * Will trigger a pass if the if the first parameter
+ * is near enough to the second by the margin.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param mixed $margin Fuzziness of match.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertWithinMargin($first, $second, $margin, $message = "%s") {
+ return $this->assert(
+ new WithinMarginExpectation($first, $margin),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters differ
+ * by more than the margin.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param mixed $margin Fuzziness of match.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertOutsideMargin($first, $second, $margin, $message = "%s") {
+ return $this->assert(
+ new OutsideMarginExpectation($first, $margin),
+ $second,
+ $message);
+ }
+
/**
* Will trigger a pass if the two parameters have
* the same value and same type. Otherwise a fail.
@@ -143,12 +176,12 @@
* @access public
*/
function assertIdentical($first, $second, $message = "%s") {
- return $this->assertExpectation(
+ return $this->assert(
new IdenticalExpectation($first),
$second,
$message);
}
-
+
/**
* Will trigger a pass if the two parameters have
* the different value or different type.
@@ -159,12 +192,12 @@
* @access public
*/
function assertNotIdentical($first, $second, $message = "%s") {
- return $this->assertExpectation(
+ return $this->assert(
new NotIdenticalExpectation($first),
$second,
$message);
}
-
+
/**
* Will trigger a pass if both parameters refer
* to the same object. Fail otherwise.
@@ -185,16 +218,34 @@
SimpleTestCompatibility::isReference($first, $second),
$message);
}
-
+
/**
* Will trigger a pass if both parameters refer
- * to different objects. Fail otherwise.
+ * to different objects. Fail otherwise. The objects
+ * have to be identical though.
* @param mixed $first Object reference to check.
* @param mixed $second Hopefully not the same object.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
+ function assertClone($first, $second, $message = "%s") {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ "[" . $dumper->describeValue($first) .
+ "] and [" . $dumper->describeValue($second) .
+ "] should not be the same object");
+ $identical = new IdenticalExpectation($first);
+ return $this->assertTrue(
+ $identical->test($second) &&
+ ! SimpleTestCompatibility::isReference($first, $second),
+ $message);
+ }
+
+ /**
+ * @deprecated
+ */
function assertCopy($first, $second, $message = "%s") {
$dumper = new SimpleDumper();
$message = sprintf(
@@ -206,7 +257,7 @@
SimpleTestCompatibility::isReference($first, $second),
$message);
}
-
+
/**
* Will trigger a pass if the Perl regex pattern
* is found in the subject. Fail otherwise.
@@ -217,13 +268,20 @@
* @return boolean True on pass
* @access public
*/
- function assertWantedPattern($pattern, $subject, $message = "%s") {
- return $this->assertExpectation(
- new WantedPatternExpectation($pattern),
+ function assertPattern($pattern, $subject, $message = "%s") {
+ return $this->assert(
+ new PatternExpectation($pattern),
$subject,
$message);
}
-
+
+ /**
+ * @deprecated
+ */
+ function assertWantedPattern($pattern, $subject, $message = "%s") {
+ return $this->assertPattern($pattern, $subject, $message);
+ }
+
/**
* Will trigger a pass if the perl regex pattern
* is not present in subject. Fail if found.
@@ -234,13 +292,20 @@
* @return boolean True on pass
* @access public
*/
- function assertNoUnwantedPattern($pattern, $subject, $message = "%s") {
- return $this->assertExpectation(
- new UnwantedPatternExpectation($pattern),
+ function assertNoPattern($pattern, $subject, $message = "%s") {
+ return $this->assert(
+ new NoPatternExpectation($pattern),
$subject,
$message);
}
-
+
+ /**
+ * @deprecated
+ */
+ function assertNoUnwantedPattern($pattern, $subject, $message = "%s") {
+ return $this->assertNoPattern($pattern, $subject, $message);
+ }
+
/**
* Confirms that no errors have occoured so
* far in the test method.
@@ -249,12 +314,12 @@
* @access public
*/
function assertNoErrors($message = "%s") {
- $queue =SimpleErrorQueue::instance();
+ $queue = &SimpleErrorQueue::instance();
return $this->assertTrue(
$queue->isEmpty(),
sprintf($message, "Should be no errors"));
}
-
+
/**
* Confirms that an error has occoured and
* optionally that the error text matches exactly.
@@ -265,39 +330,44 @@
* @access public
*/
function assertError($expected = false, $message = "%s") {
- $queue =SimpleErrorQueue::instance();
+ $queue = &SimpleErrorQueue::instance();
if ($queue->isEmpty()) {
$this->fail(sprintf($message, "Expected error not found"));
return;
}
list($severity, $content, $file, $line, $globals) = $queue->extract();
$severity = SimpleErrorQueue::getSeverityAsString($severity);
- return $this->assertTrue(
- ! $expected || ($expected == $content),
- "Expected [$expected] in PHP error [$content] severity [$severity] in [$file] line [$line]");
+ if (! $expected) {
+ return $this->pass(
+ "Captured a PHP error of [$content] severity [$severity] in [$file] line [$line] -> %s");
+ }
+ $expected = $this->_coerceToExpectation($expected);
+ return $this->assert(
+ $expected,
+ $content,
+ "Expected PHP error [$content] severity [$severity] in [$file] line [$line] -> %s");
}
-
+
/**
- * Confirms that an error has occoured and
- * that the error text matches a Perl regular
- * expression.
- * @param string $pattern Perl regular expresion to
- * match against.
- * @param string $message Message to display.
- * @return boolean True on pass
- * @access public
+ * Creates an equality expectation if the
+ * object/value is not already some type
+ * of expectation.
+ * @param mixed $expected Expected value.
+ * @return SimpleExpectation Expectation object.
+ * @access private
*/
- function assertErrorPattern($pattern, $message = "%s") {
- $queue =SimpleErrorQueue::instance();
- if ($queue->isEmpty()) {
- $this->fail(sprintf($message, "Expected error not found"));
- return;
+ function _coerceToExpectation($expected) {
+ if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) {
+ return $expected;
}
- list($severity, $content, $file, $line, $globals) = $queue->extract();
- $severity = SimpleErrorQueue::getSeverityAsString($severity);
- return $this->assertTrue(
- (boolean)preg_match($pattern, $content),
- "Expected pattern match [$pattern] in PHP error [$content] severity [$severity] in [$file] line [$line]");
+ return new EqualExpectation($expected);
+ }
+
+ /**
+ * @deprecated
+ */
+ function assertErrorPattern($pattern, $message = "%s") {
+ return $this->assertError(new PatternExpectation($pattern), $message);
}
}
?>
diff --git a/tests/test_tools/simpletest/url.php b/tests/test_tools/simpletest/url.php
index 03902ed0..5bfceb14 100644
--- a/tests/test_tools/simpletest/url.php
+++ b/tests/test_tools/simpletest/url.php
@@ -3,7 +3,7 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
- * @version $Id: url.php,v 1.22 2005/02/02 23:25:23 lastcraft Exp $
+ * @version $Id: url.php,v 1.29 2006/01/14 02:45:34 lastcraft Exp $
*/
/**#@+
@@ -17,7 +17,8 @@
* got broken in PHP 4.3.0. Adds some browser specific
* functionality such as expandomatics.
* Guesses a bit trying to separate the host from
- * the path.
+ * the path and tries to keep a raw, possibly unparsable,
+ * request string as long as possible.
* @package SimpleTest
* @subpackage WebTester
*/
@@ -30,7 +31,10 @@
protected $_path;
protected $_request;
protected $_fragment;
+ protected $_x;
+ protected $_y;
protected $_target;
+ protected $_raw = false;
/**
* Constructor. Parses URL into sections.
@@ -39,6 +43,7 @@
*/
function SimpleUrl($url) {
list($x, $y) = $this->_chompCoordinates($url);
+ $this->setCoordinates($x, $y);
$this->_scheme = $this->_chompScheme($url);
list($this->_username, $this->_password) = $this->_chompLogin($url);
$this->_host = $this->_chompHost($url);
@@ -49,7 +54,6 @@
}
$this->_path = $this->_chompPath($url);
$this->_request = $this->_parseRequest($this->_chompRequest($url));
- $this->_request->setCoordinates($x, $y);
$this->_fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false);
$this->_target = false;
}
@@ -96,7 +100,7 @@
*/
function _chompLogin($url) {
$prefix = '';
- if (preg_match('/(\/\/)(.*)/', $url, $matches)) {
+ if (preg_match('/^(\/\/)(.*)/', $url, $matches)) {
$prefix = $matches[1];
$url = $matches[2];
}
@@ -123,7 +127,7 @@
* @access private
*/
function _chompHost($url) {
- if (preg_match('/(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) {
+ if (preg_match('/^(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) {
$url = $matches[3];
return $matches[2];
}
@@ -178,7 +182,8 @@
* @access private
*/
function _parseRequest($raw) {
- $request = new SimpleFormEncoding();
+ $this->_raw = $raw;
+ $request = new SimpleGetEncoding();
foreach (split("&", $raw) as $pair) {
if (preg_match('/(.*?)=(.*)/', $pair, $matches)) {
$request->add($matches[1], urldecode($matches[2]));
@@ -293,12 +298,28 @@
}
/**
+ * Sets image coordinates. Set to false to clear
+ * them.
+ * @param integer $x Horizontal position.
+ * @param integer $y Vertical position.
+ * @access public
+ */
+ function setCoordinates($x = false, $y = false) {
+ if (($x === false) || ($y === false)) {
+ $this->_x = $this->_y = false;
+ return;
+ }
+ $this->_x = (integer)$x;
+ $this->_y = (integer)$y;
+ }
+
+ /**
* Accessor for horizontal image coordinate.
* @return integer X value.
* @access public
*/
function getX() {
- return $this->_request->getX();
+ return $this->_x;
}
/**
@@ -307,17 +328,23 @@
* @access public
*/
function getY() {
- return $this->_request->getY();
+ return $this->_y;
}
/**
* Accessor for current request parameters
- * in URL string form
+ * in URL string form. Will return teh original request
+ * if at all possible even if it doesn't make much
+ * sense.
* @return string Form is string "?a=1&b=2", etc.
* @access public
*/
function getEncodedRequest() {
- $encoded = $this->_request->asString();
+ if ($this->_raw) {
+ $encoded = $this->_raw;
+ } else {
+ $encoded = $this->_request->asUrlRequest();
+ }
if ($encoded) {
return '?' . preg_replace('/^\?/', '', $encoded);
}
@@ -331,6 +358,7 @@
* @access public
*/
function addRequestParameter($key, $value) {
+ $this->_raw = false;
$this->_request->add($key, $value);
}
@@ -341,6 +369,7 @@
* @access public
*/
function addRequestParameters($parameters) {
+ $this->_raw = false;
$this->_request->merge($parameters);
}
@@ -349,18 +378,8 @@
* @access public
*/
function clearRequest() {
- $this->_request = new SimpleFormEncoding();
- }
-
- /**
- * Sets image coordinates. Set to flase to clear
- * them.
- * @param integer $x Horizontal position.
- * @param integer $y Vertical position.
- * @access public
- */
- function setCoordinates($x = false, $y = false) {
- $this->_request->setCoordinates($x, $y);
+ $this->_raw = false;
+ $this->_request = new SimpleGetEncoding();
}
/**
@@ -380,6 +399,7 @@
* @access public
*/
function setTarget($frame) {
+ $this->_raw = false;
$this->_target = $frame;
}
@@ -402,7 +422,8 @@
}
$encoded = $this->getEncodedRequest();
$fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
- return "$scheme://$identity$host$path$encoded$fragment";
+ $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
+ return "$scheme://$identity$host$path$encoded$fragment$coords";
}
/**
@@ -417,27 +438,23 @@
$base = new SimpleUrl($base);
}
$scheme = $this->getScheme() ? $this->getScheme() : $base->getScheme();
- $host = $this->getHost() ? $this->getHost() : $base->getHost();
- $port = $this->_extractAbsolutePort($base);
+ if ($this->getHost()) {
+ $host = $this->getHost();
+ $port = $this->getPort() ? ':' . $this->getPort() : '';
+ $identity = $this->getIdentity() ? $this->getIdentity() . '@' : '';
+ if (! $identity) {
+ $identity = $base->getIdentity() ? $base->getIdentity() . '@' : '';
+ }
+ } else {
+ $host = $base->getHost();
+ $port = $base->getPort() ? ':' . $base->getPort() : '';
+ $identity = $base->getIdentity() ? $base->getIdentity() . '@' : '';
+ }
$path = $this->normalisePath($this->_extractAbsolutePath($base));
- $identity = $this->_getIdentity() ? $this->_getIdentity() . '@' : '';
$encoded = $this->getEncodedRequest();
$fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
- return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment");
- }
-
- /**
- * Extracts the port from the base URL if it's needed, but
- * not present, in the current URL.
- * @param string/SimpleUrl $base Base URL.
- * @param string Absolute port number.
- * @access private
- */
- function _extractAbsolutePort($base) {
- if ($this->getHost()) {
- return ($this->getPort() ? ':' . $this->getPort() : '');
- }
- return ($base->getPort() ? ':' . $base->getPort() : '');
+ $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
+ return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords");
}
/**
@@ -473,10 +490,10 @@
/**
* Extracts the username and password for use in rendering
* a URL.
- * @return string/boolean Form of username:password@ or false.
- * @access private
+ * @return string/boolean Form of username:password or false.
+ * @access public
*/
- function _getIdentity() {
+ function getIdentity() {
if ($this->_username && $this->_password) {
return $this->_username . ':' . $this->_password;
}
diff --git a/tests/test_tools/simpletest/user_agent.php b/tests/test_tools/simpletest/user_agent.php
index c65d5110..7216cbd1 100644
--- a/tests/test_tools/simpletest/user_agent.php
+++ b/tests/test_tools/simpletest/user_agent.php
@@ -3,153 +3,24 @@
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
- * @version $Id: user_agent.php,v 1.43 2005/01/02 22:46:08 lastcraft Exp $
+ * @version $Id: user_agent.php,v 1.55 2005/12/07 18:04:58 lastcraft Exp $
*/
/**#@+
* include other SimpleTest class files
*/
+ require_once(dirname(__FILE__) . '/cookies.php');
require_once(dirname(__FILE__) . '/http.php');
require_once(dirname(__FILE__) . '/encoding.php');
require_once(dirname(__FILE__) . '/authentication.php');
/**#@-*/
- define('DEFAULT_MAX_REDIRECTS', 3);
- define('DEFAULT_CONNECTION_TIMEOUT', 15);
+ if (! defined('DEFAULT_MAX_REDIRECTS')) {
+ define('DEFAULT_MAX_REDIRECTS', 3);
+ }
- /**
- * Repository for cookies. This stuff is a
- * tiny bit browser dependent.
- * @package SimpleTest
- * @subpackage WebTester
- */
- class SimpleCookieJar {
- protected $_cookies;
-
- /**
- * Constructor. Jar starts empty.
- * @access public
- */
- function SimpleCookieJar() {
- $this->_cookies = array();
- }
-
- /**
- * Removes expired and temporary cookies as if
- * the browser was closed and re-opened.
- * @param string/integer $now Time to test expiry against.
- * @access public
- */
- function restartSession($date = false) {
- $surviving_cookies = array();
- for ($i = 0; $i < count($this->_cookies); $i++) {
- if (! $this->_cookies[$i]->getValue()) {
- continue;
- }
- if (! $this->_cookies[$i]->getExpiry()) {
- continue;
- }
- if ($date && $this->_cookies[$i]->isExpired($date)) {
- continue;
- }
- $surviving_cookies[] = $this->_cookies[$i];
- }
- $this->_cookies = $surviving_cookies;
- }
-
- /**
- * Ages all cookies in the cookie jar.
- * @param integer $interval The old session is moved
- * into the past by this number
- * of seconds. Cookies now over
- * age will be removed.
- * @access public
- */
- function agePrematurely($interval) {
- for ($i = 0; $i < count($this->_cookies); $i++) {
- $this->_cookies[$i]->agePrematurely($interval);
- }
- }
-
- /**
- * Adds a cookie to the jar. This will overwrite
- * cookies with matching host, paths and keys.
- * @param SimpleCookie $cookie New cookie.
- * @access public
- */
- function setCookie($cookie) {
- for ($i = 0; $i < count($this->_cookies); $i++) {
- $is_match = $this->_isMatch(
- $cookie,
- $this->_cookies[$i]->getHost(),
- $this->_cookies[$i]->getPath(),
- $this->_cookies[$i]->getName());
- if ($is_match) {
- $this->_cookies[$i] = $cookie;
- return;
- }
- }
- $this->_cookies[] = $cookie;
- }
-
- /**
- * Fetches a hash of all valid cookies filtered
- * by host, path and keyed by name
- * Any cookies with missing categories will not
- * be filtered out by that category. Expired
- * cookies must be cleared by restarting the session.
- * @param string $host Host name requirement.
- * @param string $path Path encompassing cookies.
- * @return hash Valid cookie objects keyed
- * on the cookie name.
- * @access public
- */
- function getValidCookies($host = false, $path = "/") {
- $valid_cookies = array();
- foreach ($this->_cookies as $cookie) {
- if ($this->_isMatch($cookie, $host, $path, $cookie->getName())) {
- $valid_cookies[] = $cookie;
- }
- }
- return $valid_cookies;
- }
-
- /**
- * Tests cookie for matching against search
- * criteria.
- * @param SimpleTest $cookie Cookie to test.
- * @param string $host Host must match.
- * @param string $path Cookie path must be shorter than
- * this path.
- * @param string $name Name must match.
- * @return boolean True if matched.
- * @access private
- */
- function _isMatch($cookie, $host, $path, $name) {
- if ($cookie->getName() != $name) {
- return false;
- }
- if ($host && $cookie->getHost() && !$cookie->isValidHost($host)) {
- return false;
- }
- if (! $cookie->isValidPath($path)) {
- return false;
- }
- return true;
- }
-
- /**
- * Adds the current cookies to a request.
- * @param SimpleHttpRequest $request Request to modify.
- * @param SimpleUrl $url Cookie selector.
- * @access private
- */
- function addHeaders($request, $url) {
- $cookies = $this->getValidCookies($url->getHost(), $url->getPath());
- foreach ($cookies as $cookie) {
- $request->setCookie($cookie);
- }
- }
+ if (! defined('DEFAULT_CONNECTION_TIMEOUT')) {
+ define('DEFAULT_CONNECTION_TIMEOUT', 15);
}
/**
@@ -160,13 +31,14 @@
*/
class SimpleUserAgent {
protected $_cookie_jar;
+ protected $_cookies_enabled = true;
protected $_authenticator;
- protected $_max_redirects;
- protected $_proxy;
- protected $_proxy_username;
- protected $_proxy_password;
- protected $_connection_timeout;
- protected $_additional_headers;
+ protected $_max_redirects = DEFAULT_MAX_REDIRECTS;
+ protected $_proxy = false;
+ protected $_proxy_username = false;
+ protected $_proxy_password = false;
+ protected $_connection_timeout = DEFAULT_CONNECTION_TIMEOUT;
+ protected $_additional_headers = array();
/**
* Starts with no cookies, realms or proxies.
@@ -175,12 +47,6 @@
function SimpleUserAgent() {
$this->_cookie_jar = new SimpleCookieJar();
$this->_authenticator = new SimpleAuthenticator();
- $this->setMaximumRedirects(DEFAULT_MAX_REDIRECTS);
- $this->_proxy = false;
- $this->_proxy_username = false;
- $this->_proxy_password = false;
- $this->setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
- $this->_additional_headers = array();
}
/**
@@ -227,11 +93,7 @@
* @access public
*/
function setCookie($name, $value, $host = false, $path = '/', $expiry = false) {
- $cookie = new SimpleCookie($name, $value, $path, $expiry);
- if ($host) {
- $cookie->setHost($host);
- }
- $this->_cookie_jar->setCookie($cookie);
+ $this->_cookie_jar->setCookie($name, $value, $host, $path, $expiry);
}
/**
@@ -245,23 +107,14 @@
* @access public
*/
function getCookieValue($host, $path, $name) {
- $longest_path = '';
- foreach ($this->_cookie_jar->getValidCookies($host, $path) as $cookie) {
- if ($name == $cookie->getName()) {
- if (strlen($cookie->getPath()) > strlen($longest_path)) {
- $value = $cookie->getValue();
- $longest_path = $cookie->getPath();
- }
- }
- }
- return (isset($value) ? $value : false);
+ return $this->_cookie_jar->getCookieValue($host, $path, $name);
}
/**
* Reads the current cookies within the base URL.
* @param string $name Key of cookie to find.
* @param SimpleUrl $base Base URL to search from.
- * @return string Null if there is no base URL, false
+ * @return string/boolean Null if there is no base URL, false
* if the cookie is not set.
* @access public
*/
@@ -273,6 +126,22 @@
}
/**
+ * Switches off cookie sending and recieving.
+ * @access public
+ */
+ function ignoreCookies() {
+ $this->_cookies_enabled = false;
+ }
+
+ /**
+ * Switches back on the cookie sending and recieving.
+ * @access public
+ */
+ function useCookies() {
+ $this->_cookies_enabled = true;
+ }
+
+ /**
* Sets the socket timeout for opening a connection.
* @param integer $timeout Maximum time in seconds.
* @access public
@@ -305,7 +174,7 @@
$this->_proxy = false;
return;
}
- if (strncmp($proxy, 'http://', 7) != 0) {
+ if ((strncmp($proxy, 'http://', 7) != 0) && (strncmp($proxy, 'https://', 8) != 0)) {
$proxy = 'http://'. $proxy;
}
$this->_proxy = new SimpleUrl($proxy);
@@ -338,18 +207,17 @@
/**
* Fetches a URL as a response object. Will keep trying if redirected.
* It will also collect authentication realm information.
- * @param string $method GET, POST, etc.
- * @param string/SimpleUrl $url Target to fetch.
- * @param SimpleFormEncoding $parameters Additional parameters for request.
- * @return SimpleHttpResponse Hopefully the target page.
+ * @param string/SimpleUrl $url Target to fetch.
+ * @param SimpleEncoding $encoding Additional parameters for request.
+ * @return SimpleHttpResponse Hopefully the target page.
* @access public
*/
- function fetchResponse($method, $url, $parameters = false) {
- if ($method != 'POST') {
- $url->addRequestParameters($parameters);
- $parameters = false;
+ function &fetchResponse($url, $encoding) {
+ if ($encoding->getMethod() != 'POST') {
+ $url->addRequestParameters($encoding);
+ $encoding->clear();
}
- $response = $this->_fetchWhileRedirected($method, $url, $parameters);
+ $response = $this->_fetchWhileRedirected($url, $encoding);
if ($headers = $response->getHeaders()) {
if ($headers->isChallenge()) {
$this->_authenticator->addRealm(
@@ -364,84 +232,72 @@
/**
* Fetches the page until no longer redirected or
* until the redirect limit runs out.
- * @param string $method GET, POST, etc.
* @param SimpleUrl $url Target to fetch.
- * @param SimpelFormEncoding $parameters Additional parameters for request.
+ * @param SimpelFormEncoding $encoding Additional parameters for request.
* @return SimpleHttpResponse Hopefully the target page.
* @access private
*/
- function _fetchWhileRedirected($method, $url, $parameters) {
+ function &_fetchWhileRedirected($url, $encoding) {
$redirects = 0;
do {
- $response = $this->_fetch($method, $url, $parameters);
+ $response = $this->_fetch($url, $encoding);
if ($response->isError()) {
return $response;
}
$headers = $response->getHeaders();
$location = new SimpleUrl($headers->getLocation());
$url = $location->makeAbsolute($url);
- $this->_addCookiesToJar($url, $headers->getNewCookies());
+ if ($this->_cookies_enabled) {
+ $headers->writeCookiesToJar($this->_cookie_jar, $url);
+ }
if (! $headers->isRedirect()) {
break;
}
- $method = 'GET';
- $parameters = false;
+ $encoding = new SimpleGetEncoding();
} while (! $this->_isTooManyRedirects(++$redirects));
return $response;
}
/**
* Actually make the web request.
- * @param string $method GET, POST, etc.
* @param SimpleUrl $url Target to fetch.
- * @param SimpleFormEncoding $parameters Additional parameters for request.
+ * @param SimpleFormEncoding $encoding Additional parameters for request.
* @return SimpleHttpResponse Headers and hopefully content.
* @access protected
*/
- function _fetch($method, $url, $parameters) {
- if (! $parameters) {
- $parameters = new SimpleFormEncoding();
- }
- $request = $this->_createRequest($method, $url, $parameters);
- return $request->fetch($this->_connection_timeout);
+ function &_fetch($url, $encoding) {
+ $request = $this->_createRequest($url, $encoding);
+ $response = $request->fetch($this->_connection_timeout);
+ return $response;
}
/**
* Creates a full page request.
- * @param string $method Fetching method.
- * @param SimpleUrl $url Target to fetch as url object.
- * @param SimpleFormEncoding $parameters POST/GET parameters.
- * @return SimpleHttpRequest New request.
+ * @param SimpleUrl $url Target to fetch as url object.
+ * @param SimpleFormEncoding $encoding POST/GET parameters.
+ * @return SimpleHttpRequest New request.
* @access private
*/
- function _createRequest($method, $url, $parameters) {
- $request = $this->_createHttpRequest($method, $url, $parameters);
+ function &_createRequest($url, $encoding) {
+ $request = $this->_createHttpRequest($url, $encoding);
$this->_addAdditionalHeaders($request);
- $this->_cookie_jar->addHeaders($request, $url);
+ if ($this->_cookies_enabled) {
+ $request->readCookiesFromJar($this->_cookie_jar, $url);
+ }
$this->_authenticator->addHeaders($request, $url);
return $request;
}
/**
* Builds the appropriate HTTP request object.
- * @param string $method Fetching method.
* @param SimpleUrl $url Target to fetch as url object.
* @param SimpleFormEncoding $parameters POST/GET parameters.
* @return SimpleHttpRequest New request object.
* @access protected
*/
- function _createHttpRequest($method, $url, $parameters) {
- if ($method == 'POST') {
- $request = new SimpleHttpRequest(
- $this->_createRoute($url),
- 'POST',
- $parameters);
- return $request;
- }
- if ($parameters) {
- $url->addRequestParameters($parameters);
- }
- return new SimpleHttpRequest($this->_createRoute($url), $method);
+ function &_createHttpRequest($url, $encoding) {
+ $request = new SimpleHttpRequest($this->_createRoute($url), $encoding);
+ return $request;
}
/**
@@ -450,15 +306,17 @@
* @return SimpleRoute Route to take to fetch URL.
* @access protected
*/
- function _createRoute($url) {
+ function &_createRoute($url) {
if ($this->_proxy) {
- return new SimpleProxyRoute(
+ $route = new SimpleProxyRoute(
$url,
$this->_proxy,
$this->_proxy_username,
$this->_proxy_password);
+ } else {
+ $route = new SimpleRoute($url);
}
- return new SimpleRoute($url);
+ return $route;
}
/**
@@ -471,20 +329,5 @@
$request->addHeaderLine($header);
}
}
-
- /**
- * Extracts new cookies into the cookie jar.
- * @param SimpleUrl $url Target to fetch as url object.
- * @param array $cookies New cookies.
- * @access private
- */
- function _addCookiesToJar($url, $cookies) {
- foreach ($cookies as $cookie) {
- if ($url->getHost()) {
- $cookie->setHost($url->getHost());
- }
- $this->_cookie_jar->setCookie($cookie);
- }
- }
}
?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/web_tester.php b/tests/test_tools/simpletest/web_tester.php
index 4981d25a..203f729b 100644
--- a/tests/test_tools/simpletest/web_tester.php
+++ b/tests/test_tools/simpletest/web_tester.php
@@ -3,13 +3,13 @@
* Base include file for SimpleTest.
* @package SimpleTest
* @subpackage WebTester
- * @version $Id: web_tester.php,v 1.92 2005/02/22 02:39:22 lastcraft Exp $
+ * @version $Id: web_tester.php,v 1.114 2006/02/05 02:04:24 lastcraft Exp $
*/
/**#@+
* include other SimpleTest class files
*/
- require_once(dirname(__FILE__) . '/simple_test.php');
+ require_once(dirname(__FILE__) . '/test_case.php');
require_once(dirname(__FILE__) . '/browser.php');
require_once(dirname(__FILE__) . '/page.php');
require_once(dirname(__FILE__) . '/expectation.php');
@@ -25,11 +25,14 @@
/**
* Sets the field value to compare against.
- * @param mixed $value Test value to match.
+ * @param mixed $value Test value to match. Can be an
+ * expectation for say pattern matching.
+ * @param string $message Optiona message override. Can use %s as
+ * a placeholder for the original message.
* @access public
*/
- function FieldExpectation($value) {
- $this->SimpleExpectation();
+ function FieldExpectation($value, $message = '%s') {
+ $this->SimpleExpectation($message);
if (is_array($value)) {
sort($value);
}
@@ -135,16 +138,21 @@
/**
* Sets the field and value to compare against.
* @param string $header Case insenstive trimmed header name.
- * @param string $value Optional value to compare. If not
- * given then any value will match.
- */
- function HttpHeaderExpectation($header, $value = false) {
+ * @param mixed $value Optional value to compare. If not
+ * given then any value will match. If
+ * an expectation object then that will
+ * be used instead.
+ * @param string $message Optiona message override. Can use %s as
+ * a placeholder for the original message.
+ */
+ function HttpHeaderExpectation($header, $value = false, $message = '%s') {
+ $this->SimpleExpectation($message);
$this->_expected_header = $this->_normaliseHeader($header);
$this->_expected_value = $value;
}
/**
- * Accessor for subclases.
+ * Accessor for aggregated object.
* @return mixed Expectation set in constructor.
* @access protected
*/
@@ -198,7 +206,7 @@
* @access private
*/
function _testHeaderLine($line) {
- if (count($parsed = split(':', $line)) < 2) {
+ if (count($parsed = split(':', $line, 2)) < 2) {
return false;
}
list($header, $value) = $parsed;
@@ -219,6 +227,9 @@
if ($expected === false) {
return true;
}
+ if (SimpleExpectation::isExpectation($expected)) {
+ return $expected->test(trim($value));
+ }
return (trim($value) == trim($expected));
}
@@ -230,14 +241,16 @@
* @access public
*/
function testMessage($compare) {
- $expectation = $this->_expected_header;
- if ($this->_expected_value) {
- $expectation .= ': ' . $this->_expected_header;
+ if (SimpleExpectation::isExpectation($this->_expected_value)) {
+ $message = $this->_expected_value->testMessage($compare);
+ } else {
+ $message = $this->_expected_header .
+ ($this->_expected_value ? ': ' . $this->_expected_value : '');
}
if (is_string($line = $this->_findHeader($compare))) {
- return "Searching for header [$expectation] found [$line]";
+ return "Searching for header [$message] found [$line]";
} else {
- return "Failed to find header [$expectation]";
+ return "Failed to find header [$message]";
}
}
}
@@ -248,16 +261,18 @@
* @package SimpleTest
* @subpackage WebTester
*/
- class HttpUnwantedHeaderExpectation extends HttpHeaderExpectation {
+ class NoHttpHeaderExpectation extends HttpHeaderExpectation {
protected $_expected_header;
protected $_expected_value;
/**
* Sets the field and value to compare against.
* @param string $unwanted Case insenstive trimmed header name.
+ * @param string $message Optiona message override. Can use %s as
+ * a placeholder for the original message.
*/
- function HttpUnwantedHeaderExpectation($unwanted) {
- $this->HttpHeaderExpectation($unwanted);
+ function NoHttpHeaderExpectation($unwanted, $message = '%s') {
+ $this->HttpHeaderExpectation($unwanted, false, $message);
}
/**
@@ -286,42 +301,13 @@
}
}
}
-
- /**
- * Test for a specific HTTP header within a header block.
- * @package SimpleTest
- * @subpackage WebTester
- */
- class HttpHeaderPatternExpectation extends HttpHeaderExpectation {
-
- /**
- * Sets the field and value to compare against.
- * @param string $header Case insenstive header name.
- * @param string $pattern Pattern to compare value against.
- * @access public
- */
- function HttpHeaderPatternExpectation($header, $pattern) {
- $this->HttpHeaderExpectation($header, $pattern);
- }
-
- /**
- * Tests the value part of the header.
- * @param string $value Value to test.
- * @param mixed $pattern Pattern to test against.
- * @return boolean True if matched.
- * @access protected
- */
- function _testHeaderValue($value, $expected) {
- return (boolean)preg_match($expected, trim($value));
- }
- }
/**
* Test for a text substring.
* @package SimpleTest
* @subpackage UnitTester
*/
- class WantedTextExpectation extends SimpleExpectation {
+ class TextExpectation extends SimpleExpectation {
protected $_substring;
/**
@@ -330,7 +316,7 @@
* @param string $message Customised message on failure.
* @access public
*/
- function WantedTextExpectation($substring, $message = '%s') {
+ function TextExpectation($substring, $message = '%s') {
$this->SimpleExpectation($message);
$this->_substring = $substring;
}
@@ -395,7 +381,7 @@
* @package SimpleTest
* @subpackage UnitTester
*/
- class UnwantedTextExpectation extends WantedTextExpectation {
+ class NoTextExpectation extends TextExpectation {
/**
* Sets the reject pattern
@@ -403,8 +389,8 @@
* @param string $message Customised message on failure.
* @access public
*/
- function UnwantedTextExpectation($substring, $message = '%s') {
- $this->WantedTextExpectation($substring, $message);
+ function NoTextExpectation($substring, $message = '%s') {
+ $this->TextExpectation($substring, $message);
}
/**
@@ -438,36 +424,6 @@
}
/**
- * Extension that builds a web browser at the start of each
- * test.
- * @package SimpleTest
- * @subpackage WebTester
- */
- class WebTestCaseInvoker extends SimpleInvokerDecorator {
-
- /**
- * Takes in the test case and reporter to mediate between.
- * @param SimpleTestCase $test_case Test case to run.
- * @param SimpleScorer $scorer Reporter to receive events.
- */
- function WebTestCaseInvoker($invoker) {
- $this->SimpleInvokerDecorator($invoker);
- }
-
- /**
- * Builds the browser and runs the test.
- * @param string $method Test method to call.
- * @access public
- */
- function invoke($method) {
- $test = $this->getTestCase();
- $test->setBrowser($test->createBrowser());
- parent::invoke($method);
- $test->unsetBrowser();
- }
- }
-
- /**
* Test case for testing of web pages. Allows
* fetching of pages, parsing of HTML and
* submitting forms.
@@ -476,6 +432,7 @@
*/
class WebTestCase extends SimpleTestCase {
protected $_browser;
+ protected $_ignore_errors = false;
/**
* Creates an empty test case. Should be subclassed
@@ -489,13 +446,23 @@
}
/**
- * Sets the invoker to one that restarts the browser on
- * each request.
- * @return SimpleInvoker Invoker for each method.
+ * Announces the start of the test.
+ * @param string $method Test method just started.
* @access public
*/
- function createInvoker() {
- return new WebTestCaseInvoker(parent::createInvoker());
+ function before($method) {
+ parent::before($method);
+ $this->setBrowser($this->createBrowser());
+ }
+
+ /**
+ * Announces the end of the test. Includes private clean up.
+ * @param string $method Test method just finished.
+ * @access public
+ */
+ function after($method) {
+ $this->unsetBrowser();
+ parent::after($method);
}
/**
@@ -505,7 +472,7 @@
* @return SimpleBrowser Current test browser object.
* @access public
*/
- function getBrowser() {
+ function &getBrowser() {
return $this->_browser;
}
@@ -535,8 +502,9 @@
* @return TestBrowser New browser.
* @access public
*/
- function createBrowser() {
- return new SimpleBrowser();
+ function &createBrowser() {
+ $browser = new SimpleBrowser();
+ return $browser;
}
/**
@@ -581,6 +549,14 @@
function showSource() {
$this->dump($this->_browser->getContent());
}
+
+ /**
+ * Dumps the visible text only for debugging.
+ * @access public
+ */
+ function showText() {
+ $this->dump(wordwrap($this->_browser->getContentAsText(), 80));
+ }
/**
* Simulates the closing and reopening of the browser.
@@ -618,6 +594,42 @@
function ignoreFrames() {
$this->_browser->ignoreFrames();
}
+
+ /**
+ * Switches off cookie sending and recieving.
+ * @access public
+ */
+ function ignoreCookies() {
+ $this->_browser->ignoreCookies();
+ }
+
+ /**
+ * Skips errors for the next request only. You might
+ * want to confirm that a page is unreachable for
+ * example.
+ * @access public
+ */
+ function ignoreErrors() {
+ $this->_ignore_errors = true;
+ }
+
+ /**
+ * Issues a fail if there is a transport error anywhere
+ * in the current frameset. Only one such error is
+ * reported.
+ * @param string/boolean $result HTML or failure.
+ * @return string/boolean $result Passes through result.
+ * @access private
+ */
+ function _failOnError($result) {
+ if (! $this->_ignore_errors) {
+ if ($error = $this->_browser->getTransportError()) {
+ $this->fail($error);
+ }
+ }
+ $this->_ignore_errors = false;
+ return $result;
+ }
/**
* Adds a header to every fetch.
@@ -673,15 +685,11 @@
* the base URL reflects the new location.
* @param string $url URL to fetch.
* @param hash $parameters Optional additional GET data.
- * @return boolean True on success.
+ * @return boolean/string Raw page on success.
* @access public
*/
function get($url, $parameters = false) {
- $content = $this->_browser->get($url, $parameters);
- if ($content === false) {
- return false;
- }
- return true;
+ return $this->_failOnError($this->_browser->get($url, $parameters));
}
/**
@@ -691,15 +699,11 @@
* the base URL reflects the new location.
* @param string $url URL to fetch.
* @param hash $parameters Optional additional GET data.
- * @return boolean True on success.
+ * @return boolean/string Raw page on success.
* @access public
*/
function post($url, $parameters = false) {
- $content = $this->_browser->post($url, $parameters);
- if ($content === false) {
- return false;
- }
- return true;
+ return $this->_failOnError($this->_browser->post($url, $parameters));
}
/**
@@ -711,7 +715,7 @@
* @access public
*/
function head($url, $parameters = false) {
- return $this->_browser->head($url, $parameters);
+ return $this->_failOnError($this->_browser->head($url, $parameters));
}
/**
@@ -721,7 +725,7 @@
* @access public
*/
function retry() {
- return $this->_browser->retry();
+ return $this->_failOnError($this->_browser->retry());
}
/**
@@ -732,7 +736,7 @@
* @access public
*/
function back() {
- return $this->_browser->back();
+ return $this->_failOnError($this->_browser->back());
}
/**
@@ -743,7 +747,7 @@
* @access public
*/
function forward() {
- return $this->_browser->forward();
+ return $this->_failOnError($this->_browser->forward());
}
/**
@@ -751,13 +755,14 @@
* for the current realm.
* @param string $username Username for realm.
* @param string $password Password for realm.
- * @return boolean True if successful fetch. Note
+ * @return boolean/string HTML on successful fetch. Note
* that authentication may still have
* failed.
* @access public
*/
function authenticate($username, $password) {
- return $this->_browser->authenticate($username, $password);
+ return $this->_failOnError(
+ $this->_browser->authenticate($username, $password));
}
/**
@@ -825,16 +830,28 @@
}
/**
+ * Clicks a visible text item. Will first try buttons,
+ * then links and then images.
+ * @param string $label Visible text or alt text.
+ * @return string/boolean Raw page or false.
+ * @access public
+ */
+ function click($label) {
+ return $this->_failOnError($this->_browser->click($label));
+ }
+
+ /**
* Clicks the submit button by label. The owning
* form will be submitted by this.
* @param string $label Button label. An unlabeled
* button can be triggered by 'Submit'.
* @param hash $additional Additional form values.
- * @return boolean/string Page on success.
+ * @return boolean/string Page on success, else false.
* @access public
*/
function clickSubmit($label = 'Submit', $additional = false) {
- return $this->_browser->clickSubmit($label, $additional);
+ return $this->_failOnError(
+ $this->_browser->clickSubmit($label, $additional));
}
/**
@@ -846,7 +863,8 @@
* @access public
*/
function clickSubmitByName($name, $additional = false) {
- return $this->_browser->clickSubmitByName($name, $additional);
+ return $this->_failOnError(
+ $this->_browser->clickSubmitByName($name, $additional));
}
/**
@@ -858,7 +876,8 @@
* @access public
*/
function clickSubmitById($id, $additional = false) {
- return $this->_browser->clickSubmitById($id, $additional);
+ return $this->_failOnError(
+ $this->_browser->clickSubmitById($id, $additional));
}
/**
@@ -875,7 +894,8 @@
* @access public
*/
function clickImage($label, $x = 1, $y = 1, $additional = false) {
- return $this->_browser->clickImage($label, $x, $y, $additional);
+ return $this->_failOnError(
+ $this->_browser->clickImage($label, $x, $y, $additional));
}
/**
@@ -892,7 +912,8 @@
* @access public
*/
function clickImageByName($name, $x = 1, $y = 1, $additional = false) {
- return $this->_browser->clickImageByName($name, $x, $y, $additional);
+ return $this->_failOnError(
+ $this->_browser->clickImageByName($name, $x, $y, $additional));
}
/**
@@ -908,7 +929,8 @@
* @access public
*/
function clickImageById($id, $x = 1, $y = 1, $additional = false) {
- return $this->_browser->clickImageById($id, $x, $y, $additional);
+ return $this->_failOnError(
+ $this->_browser->clickImageById($id, $x, $y, $additional));
}
/**
@@ -919,7 +941,7 @@
* @access public
*/
function submitFormById($id) {
- return $this->_browser->submitFormById($id);
+ return $this->_failOnError($this->_browser->submitFormById($id));
}
/**
@@ -933,7 +955,7 @@
* @access public
*/
function clickLink($label, $index = 0) {
- return $this->_browser->clickLink($label, $index);
+ return $this->_failOnError($this->_browser->clickLink($label, $index));
}
/**
@@ -943,7 +965,41 @@
* @access public
*/
function clickLinkById($id) {
- return $this->_browser->clickLinkById($id);
+ return $this->_failOnError($this->_browser->clickLinkById($id));
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * the same value only. Otherwise a fail. This
+ * is for testing hand extracted text, etc.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertEqual($first, $second, $message = "%s") {
+ return $this->assert(
+ new EqualExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * a different value. Otherwise a fail. This
+ * is for testing hand extracted text, etc.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNotEqual($first, $second, $message = "%s") {
+ return $this->assert(
+ new NotEqualExpectation($first),
+ $second,
+ $message);
}
/**
@@ -1007,14 +1063,26 @@
}
/**
+ * Sets all form fields with that label, or name if there
+ * is no label attached.
+ * @param string $name Name of field in forms.
+ * @param string $value New value of field.
+ * @return boolean True if field exists, otherwise false.
+ * @access public
+ */
+ function setField($label, $value) {
+ return $this->_browser->setField($label, $value);
+ }
+
+ /**
* Sets all form fields with that name.
* @param string $name Name of field in forms.
* @param string $value New value of field.
* @return boolean True if field exists, otherwise false.
* @access public
*/
- function setField($name, $value) {
- return $this->_browser->setField($name, $value);
+ function setFieldByName($name, $value) {
+ return $this->_browser->setFieldByName($name, $value);
}
/**
@@ -1041,18 +1109,27 @@
* @return boolean True if pass.
* @access public
*/
- function assertField($name, $expected = true, $message = "%s") {
- $value = $this->_browser->getField($name);
- if ($expected === true) {
- return $this->assertTrue(
- isset($value),
- sprintf($message, "Field [$name] should exist"));
- } else {
- return $this->assertExpectation(
- new FieldExpectation($expected),
- $value,
- sprintf($message, "Field [$name] should match with [%s]"));
- }
+ function assertField($label, $expected = true, $message = '%s') {
+ $value = $this->_browser->getField($label);
+ return $this->_assertFieldValue($label, $value, $expected, $message);
+ }
+
+ /**
+ * Confirms that the form element is currently set
+ * to the expected value. A missing form element will always
+ * fail. If no value is given then only the existence
+ * of the field is checked.
+ * @param string $name Name of field in forms.
+ * @param mixed $expected Expected string/array value or
+ * false for unset fields.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertFieldByName($name, $expected = true, $message = '%s') {
+ $value = $this->_browser->getFieldByName($name);
+ return $this->_assertFieldValue($name, $value, $expected, $message);
}
/**
@@ -1068,18 +1145,33 @@
* @return boolean True if pass.
* @access public
*/
- function assertFieldById($id, $expected = true, $message = "%s") {
+ function assertFieldById($id, $expected = true, $message = '%s') {
$value = $this->_browser->getFieldById($id);
+ return $this->_assertFieldValue($id, $value, $expected, $message);
+ }
+
+ /**
+ * Tests the field value against the expectation.
+ * @param string $identifier Name, ID or label.
+ * @param mixed $value Current field value.
+ * @param mixed $expected Expected value to match.
+ * @param string $message Failure message.
+ * @return boolean True if pass
+ * @access protected
+ */
+ function _assertFieldValue($identifier, $value, $expected, $message) {
if ($expected === true) {
return $this->assertTrue(
isset($value),
- sprintf($message, "Field of ID [$id] should exist"));
- } else {
- return $this->assertExpectation(
- new FieldExpectation($expected),
- $value,
- sprintf($message, "Field of ID [$id] should match with [%s]"));
+ sprintf($message, "Field [$identifier] should exist"));
}
+ if (! SimpleExpectation::isExpectation($expected)) {
+ $identifier = str_replace('%', '%%', $identifier);
+ $expected = new FieldExpectation(
+ $expected,
+ "Field [$identifier] should match with [%s]");
+ }
+ return $this->assert($expected, $value, $message);
}
/**
@@ -1160,39 +1252,38 @@
* @access public
*/
function assertRealm($realm, $message = '%s') {
- $message = sprintf($message, "Expected realm [$realm] got [" .
- $this->_browser->getRealm() . "]");
- return $this->assertTrue(
- strtolower($this->_browser->getRealm()) == strtolower($realm),
- $message);
+ if (! SimpleExpectation::isExpectation($realm)) {
+ $realm = new EqualExpectation($realm);
+ }
+ return $this->assert(
+ $realm,
+ $this->_browser->getRealm(),
+ "Expected realm -> $message");
}
/**
* Checks each header line for the required value. If no
* value is given then only an existence check is made.
* @param string $header Case insensitive header name.
- * @param string $value Case sensitive trimmed string to
- * match against.
+ * @param mixed $value Case sensitive trimmed string to
+ * match against. An expectation object
+ * can be used for pattern matching.
* @return boolean True if pass.
* @access public
*/
function assertHeader($header, $value = false, $message = '%s') {
- return $this->assertExpectation(
+ return $this->assert(
new HttpHeaderExpectation($header, $value),
$this->_browser->getHeaders(),
$message);
}
/**
- * Checks each header line for the required pattern.
- * @param string $header Case insensitive header name.
- * @param string $pattern Pattern to match value against.
- * @return boolean True if pass.
- * @access public
+ * @deprecated
*/
function assertHeaderPattern($header, $pattern, $message = '%s') {
- return $this->assertExpectation(
- new HttpHeaderPatternExpectation($header, $pattern),
+ return $this->assert(
+ new HttpHeaderExpectation($header, new PatternExpectation($pattern)),
$this->_browser->getHeaders(),
$message);
}
@@ -1206,26 +1297,32 @@
* @return boolean True if pass.
* @access public
*/
- function assertNoUnwantedHeader($header, $message = '%s') {
- return $this->assertExpectation(
- new HttpUnwantedHeaderExpectation($header),
+ function assertNoHeader($header, $message = '%s') {
+ return $this->assert(
+ new NoHttpHeaderExpectation($header),
$this->_browser->getHeaders(),
$message);
}
+
+ /**
+ * @deprecated
+ */
+ function assertNoUnwantedHeader($header, $message = '%s') {
+ return $this->assertNoHeader($header, $message);
+ }
/**
* Tests the text between the title tags.
- * @param string $title Expected title or empty
- * if expecting no title.
- * @param string $message Message to display.
- * @return boolean True if pass.
+ * @param string $title Expected title.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
* @access public
*/
function assertTitle($title = false, $message = '%s') {
- return $this->assertTrue(
- $title === $this->_browser->getTitle(),
- sprintf($message, "Expecting title [$title] got [" .
- $this->_browser->getTitle() . "]"));
+ if (! SimpleExpectation::isExpectation($title)) {
+ $title = new EqualExpectation($title);
+ }
+ return $this->assert($title, $this->_browser->getTitle(), $message);
}
/**
@@ -1236,14 +1333,21 @@
* @return boolean True if pass.
* @access public
*/
- function assertWantedText($text, $message = '%s') {
- return $this->assertExpectation(
- new WantedTextExpectation($text),
+ function assertText($text, $message = '%s') {
+ return $this->assert(
+ new TextExpectation($text),
$this->_browser->getContentAsText(),
$message);
}
/**
+ * @deprecated
+ */
+ function assertWantedText($text, $message = '%s') {
+ return $this->assertText($text, $message);
+ }
+
+ /**
* Will trigger a pass if the text is not found in the plain
* text form of the page.
* @param string $text Text to look for.
@@ -1251,14 +1355,21 @@
* @return boolean True if pass.
* @access public
*/
- function assertNoUnwantedText($text, $message = '%s') {
- return $this->assertExpectation(
- new UnwantedTextExpectation($text),
+ function assertNoText($text, $message = '%s') {
+ return $this->assert(
+ new NoTextExpectation($text),
$this->_browser->getContentAsText(),
$message);
}
/**
+ * @deprecated
+ */
+ function assertNoUnwantedText($text, $message = '%s') {
+ return $this->assertNoText($text, $message);
+ }
+
+ /**
* Will trigger a pass if the Perl regex pattern
* is found in the raw content.
* @param string $pattern Perl regex to look for including
@@ -1267,14 +1378,21 @@
* @return boolean True if pass.
* @access public
*/
- function assertWantedPattern($pattern, $message = '%s') {
- return $this->assertExpectation(
- new WantedPatternExpectation($pattern),
+ function assertPattern($pattern, $message = '%s') {
+ return $this->assert(
+ new PatternExpectation($pattern),
$this->_browser->getContent(),
$message);
}
/**
+ * @deprecated
+ */
+ function assertWantedPattern($pattern, $message = '%s') {
+ return $this->assertPattern($pattern, $message);
+ }
+
+ /**
* Will trigger a pass if the perl regex pattern
* is not present in raw content.
* @param string $pattern Perl regex to look for including
@@ -1283,14 +1401,21 @@
* @return boolean True if pass.
* @access public
*/
- function assertNoUnwantedPattern($pattern, $message = '%s') {
- return $this->assertExpectation(
- new UnwantedPatternExpectation($pattern),
+ function assertNoPattern($pattern, $message = '%s') {
+ return $this->assert(
+ new NoPatternExpectation($pattern),
$this->_browser->getContent(),
$message);
}
/**
+ * @deprecated
+ */
+ function assertNoUnwantedPattern($pattern, $message = '%s') {
+ return $this->assertNoPattern($pattern, $message);
+ }
+
+ /**
* Checks that a cookie is set for the current page
* and optionally checks the value.
* @param string $name Name of cookie to test.
@@ -1302,15 +1427,15 @@
*/
function assertCookie($name, $expected = false, $message = '%s') {
$value = $this->getCookie($name);
- if ($expected) {
- return $this->assertTrue($value === $expected, sprintf(
- $message,
- "Expecting cookie [$name] value [$expected], got [$value]"));
- } else {
+ if (! $expected) {
return $this->assertTrue(
$value,
sprintf($message, "Expecting cookie [$name]"));
}
+ if (! SimpleExpectation::isExpectation($expected)) {
+ $expected = new EqualExpectation($expected);
+ }
+ return $this->assert($expected, $value, "Expecting cookie [$name] -> $message");
}
/**
diff --git a/tests/test_tools/simpletest/xml.php b/tests/test_tools/simpletest/xml.php
index dd007d41..0d578751 100644
--- a/tests/test_tools/simpletest/xml.php
+++ b/tests/test_tools/simpletest/xml.php
@@ -3,7 +3,7 @@
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
- * @version $Id: xml.php,v 1.20 2004/08/04 22:09:39 lastcraft Exp $
+ * @version $Id: xml.php,v 1.22 2006/02/06 06:05:18 lastcraft Exp $
*/
/**#@+
@@ -11,7 +11,7 @@
*/
require_once(dirname(__FILE__) . '/scorer.php');
/**#@-*/
-
+
/**
* Creates the XML needed for remote communication
* by SimpleTest.
@@ -21,7 +21,7 @@
class XmlReporter extends SimpleReporter {
protected $_indent;
protected $_namespace;
-
+
/**
* Does nothing yet.
* @access public
@@ -31,7 +31,7 @@
$this->_namespace = ($namespace ? $namespace . ':' : '');
$this->_indent = $indent;
}
-
+
/**
* Calculates the pretty printing indent level
* from the current level of nesting.
@@ -44,7 +44,7 @@
$this->_indent,
count($this->getTestList()) + $offset);
}
-
+
/**
* Converts character string to parsed XML
* entities string.
@@ -58,7 +58,7 @@
array('&amp;', '&lt;', '&gt;', '&quot;', '&apos;'),
$text);
}
-
+
/**
* Paints the start of a group test.
* @param string $test_name Name of test that is starting.
@@ -74,7 +74,7 @@
$this->toParsedXml($test_name) .
"</" . $this->_namespace . "name>\n";
}
-
+
/**
* Paints the end of a group test.
* @param string $test_name Name of test that is ending.
@@ -85,7 +85,7 @@
print "</" . $this->_namespace . "group>\n";
parent::paintGroupEnd($test_name);
}
-
+
/**
* Paints the start of a test case.
* @param string $test_name Name of test that is starting.
@@ -100,7 +100,7 @@
$this->toParsedXml($test_name) .
"</" . $this->_namespace . "name>\n";
}
-
+
/**
* Paints the end of a test case.
* @param string $test_name Name of test that is ending.
@@ -111,7 +111,7 @@
print "</" . $this->_namespace . "case>\n";
parent::paintCaseEnd($test_name);
}
-
+
/**
* Paints the start of a test method.
* @param string $test_name Name of test that is starting.
@@ -126,7 +126,7 @@
$this->toParsedXml($test_name) .
"</" . $this->_namespace . "name>\n";
}
-
+
/**
* Paints the end of a test method.
* @param string $test_name Name of test that is ending.
@@ -138,7 +138,7 @@
print "</" . $this->_namespace . "test>\n";
parent::paintMethodEnd($test_name);
}
-
+
/**
* Increments the pass count.
* @param string $message Message is ignored.
@@ -151,7 +151,7 @@
print $this->toParsedXml($message);
print "</" . $this->_namespace . "pass>\n";
}
-
+
/**
* Increments the fail count.
* @param string $message Message is ignored.
@@ -164,15 +164,15 @@
print $this->toParsedXml($message);
print "</" . $this->_namespace . "fail>\n";
}
-
+
/**
* Paints a PHP error or exception.
* @param string $message Message is ignored.
* @access public
* @abstract
*/
- function paintException($message) {
- parent::paintException($message);
+ function paintError($message) {
+ parent::paintError($message);
print $this->_getIndent(1);
print "<" . $this->_namespace . "exception>";
print $this->toParsedXml($message);
@@ -191,7 +191,7 @@
print $this->toParsedXml($message);
print "</" . $this->_namespace . "message>\n";
}
-
+
/**
* Paints a formatted ASCII message such as a
* variable dump.
@@ -239,7 +239,7 @@
print "?>\n";
print "<" . $this->_namespace . "run>\n";
}
-
+
/**
* Paints the test document footer.
* @param string $test_name The top level test.
@@ -250,7 +250,7 @@
print "</" . $this->_namespace . "run>\n";
}
}
-
+
/**
* Accumulator for incoming tag. Holds the
* incoming test structure information for
@@ -261,7 +261,7 @@
class NestingXmlTag {
protected $_name;
protected $_attributes;
-
+
/**
* Sets the basic test information except
* the name.
@@ -272,7 +272,7 @@
$this->_name = false;
$this->_attributes = $attributes;
}
-
+
/**
* Sets the test case/method name.
* @param string $name Name of test.
@@ -281,7 +281,7 @@
function setName($name) {
$this->_name = $name;
}
-
+
/**
* Accessor for name.
* @return string Name of test.
@@ -290,7 +290,7 @@
function getName() {
return $this->_name;
}
-
+
/**
* Accessor for attributes.
* @return hash All attributes.
@@ -300,7 +300,7 @@
return $this->_attributes;
}
}
-
+
/**
* Accumulator for incoming method tag. Holds the
* incoming test structure information for
@@ -309,7 +309,7 @@
* @subpackage UnitTester
*/
class NestingMethodTag extends NestingXmlTag {
-
+
/**
* Sets the basic test information except
* the name.
@@ -319,7 +319,7 @@
function NestingMethodTag($attributes) {
$this->NestingXmlTag($attributes);
}
-
+
/**
* Signals the appropriate start event on the
* listener.
@@ -328,8 +328,8 @@
*/
function paintStart($listener) {
$listener->paintMethodStart($this->getName());
- }
-
+ }
+
/**
* Signals the appropriate end event on the
* listener.
@@ -340,7 +340,7 @@
$listener->paintMethodEnd($this->getName());
}
}
-
+
/**
* Accumulator for incoming case tag. Holds the
* incoming test structure information for
@@ -349,7 +349,7 @@
* @subpackage UnitTester
*/
class NestingCaseTag extends NestingXmlTag {
-
+
/**
* Sets the basic test information except
* the name.
@@ -359,7 +359,7 @@
function NestingCaseTag($attributes) {
$this->NestingXmlTag($attributes);
}
-
+
/**
* Signals the appropriate start event on the
* listener.
@@ -368,8 +368,8 @@
*/
function paintStart($listener) {
$listener->paintCaseStart($this->getName());
- }
-
+ }
+
/**
* Signals the appropriate end event on the
* listener.
@@ -380,7 +380,7 @@
$listener->paintCaseEnd($this->getName());
}
}
-
+
/**
* Accumulator for incoming group tag. Holds the
* incoming test structure information for
@@ -389,7 +389,7 @@
* @subpackage UnitTester
*/
class NestingGroupTag extends NestingXmlTag {
-
+
/**
* Sets the basic test information except
* the name.
@@ -409,7 +409,7 @@
function paintStart($listener) {
$listener->paintGroupStart($this->getName(), $this->getSize());
}
-
+
/**
* Signals the appropriate end event on the
* listener.
@@ -419,7 +419,7 @@
function paintEnd($listener) {
$listener->paintGroupEnd($this->getName());
}
-
+
/**
* The size in the attributes.
* @return integer Value of size attribute or zero.
@@ -433,7 +433,7 @@
return 0;
}
}
-
+
/**
* Parser for importing the output of the XmlReporter.
* Dispatches that output to another reporter.
@@ -447,7 +447,7 @@
protected $_in_content_tag;
protected $_content;
protected $_attributes;
-
+
/**
* Loads a listener with the SimpleReporter
* interface.
@@ -462,7 +462,7 @@
$this->_content = '';
$this->_attributes = array();
}
-
+
/**
* Parses a block of XML sending the results to
* the listener.
@@ -478,13 +478,13 @@
}
return true;
}
-
+
/**
* Sets up expat as the XML parser.
* @return resource Expat handle.
* @access protected
*/
- function _createParser() {
+ function &_createParser() {
$expat = xml_parser_create();
xml_set_object($expat, $this);
xml_set_element_handler($expat, '_startElement', '_endElement');
@@ -492,7 +492,7 @@
xml_set_default_handler($expat, '_default');
return $expat;
}
-
+
/**
* Opens a new test nesting level.
* @return NestedXmlTag The group, case or method tag
@@ -502,17 +502,17 @@
function _pushNestingTag($nested) {
array_unshift($this->_tag_stack, $nested);
}
-
+
/**
* Accessor for current test structure tag.
* @return NestedXmlTag The group, case or method tag
* being parsed.
* @access private
*/
- function _getCurrentNestingTag() {
+ function &_getCurrentNestingTag() {
return $this->_tag_stack[0];
}
-
+
/**
* Ends a nesting tag.
* @return NestedXmlTag The group, case or method tag
@@ -522,7 +522,7 @@
function _popNestingTag() {
return array_shift($this->_tag_stack);
}
-
+
/**
* Test if tag is a leaf node with only text content.
* @param string $tag XML tag name.
@@ -530,9 +530,8 @@
* @private
*/
function _isLeaf($tag) {
- return in_array(
- $tag,
- array('NAME', 'PASS', 'FAIL', 'EXCEPTION', 'MESSAGE', 'FORMATTED', 'SIGNAL'));
+ return in_array($tag, array(
+ 'NAME', 'PASS', 'FAIL', 'EXCEPTION', 'MESSAGE', 'FORMATTED', 'SIGNAL'));
}
/**
@@ -557,7 +556,7 @@
$this->_content = '';
}
}
-
+
/**
* End of element event.
* @param resource $expat Parser handle.
@@ -578,7 +577,7 @@
} elseif ($tag == 'FAIL') {
$this->_listener->paintFail($this->_content);
} elseif ($tag == 'EXCEPTION') {
- $this->_listener->paintException($this->_content);
+ $this->_listener->paintError($this->_content);
} elseif ($tag == 'SIGNAL') {
$this->_listener->paintSignal(
$this->_attributes['TYPE'],
@@ -589,7 +588,7 @@
$this->_listener->paintFormattedMessage($this->_content);
}
}
-
+
/**
* Content between start and end elements.
* @param resource $expat Parser handle.
@@ -602,7 +601,7 @@
}
return true;
}
-
+
/**
* XML and Doctype handler. Discards all such content.
* @param resource $expat Parser handle.